cmdbabstract.class.inc.php 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Abstract class that implements some common and useful methods for displaying
  20. * the objects
  21. *
  22. * @copyright Copyright (C) 2010-2012 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  24. */
  25. define('OBJECT_PROPERTIES_TAB', 'ObjectProperties');
  26. define('HILIGHT_CLASS_CRITICAL', 'red');
  27. define('HILIGHT_CLASS_WARNING', 'orange');
  28. define('HILIGHT_CLASS_OK', 'green');
  29. define('HILIGHT_CLASS_NONE', '');
  30. require_once(APPROOT.'/core/cmdbobject.class.inc.php');
  31. require_once(APPROOT.'/application/applicationextension.inc.php');
  32. require_once(APPROOT.'/application/utils.inc.php');
  33. require_once(APPROOT.'/application/applicationcontext.class.inc.php');
  34. require_once(APPROOT.'/application/ui.linkswidget.class.inc.php');
  35. require_once(APPROOT.'/application/ui.linksdirectwidget.class.inc.php');
  36. require_once(APPROOT.'/application/ui.passwordwidget.class.inc.php');
  37. require_once(APPROOT.'/application/ui.extkeywidget.class.inc.php');
  38. require_once(APPROOT.'/application/ui.htmleditorwidget.class.inc.php');
  39. require_once(APPROOT.'/application/datatable.class.inc.php');
  40. /**
  41. * All objects to be displayed in the application (either as a list or as details)
  42. * must implement this interface.
  43. */
  44. interface iDisplay
  45. {
  46. /**
  47. * Maps the given context parameter name to the appropriate filter/search code for this class
  48. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  49. * @return string Filter code, i.e. 'customer_id'
  50. */
  51. public static function MapContextParam($sContextParam);
  52. /**
  53. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  54. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  55. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  56. * To Be overridden by derived classes
  57. * @param void
  58. * @return String The desired higlight class for the object/row
  59. */
  60. public function GetHilightClass();
  61. /**
  62. * Returns the relative path to the page that handles the display of the object
  63. * @return string
  64. */
  65. public static function GetUIPage();
  66. /**
  67. * Displays the details of the object
  68. */
  69. public function DisplayDetails(WebPage $oPage, $bEditMode = false);
  70. }
  71. abstract class cmdbAbstractObject extends CMDBObject implements iDisplay
  72. {
  73. protected $m_iFormId; // The ID of the form used to edit the object (when in edition mode !)
  74. static $iGlobalFormId = 1;
  75. protected $aFieldsMap;
  76. /**
  77. * returns what will be the next ID for the forms
  78. */
  79. public static function GetNextFormId()
  80. {
  81. return 1 + self::$iGlobalFormId;
  82. }
  83. public static function GetUIPage()
  84. {
  85. return 'UI.php';
  86. }
  87. /**
  88. * Set a message diplayed to the end-user next time this object will be displayed
  89. * Messages are uniquely identified so that plugins can override standard messages (the final work is given to the last plugin to set the message for a given message id)
  90. * In practice, standard messages are recorded at the end but they will not overwrite existing messages
  91. *
  92. * @param string $sClass The class of the object (must be the final class)
  93. * @param int $iKey The identifier of the object
  94. * @param string $sMessageId Your id or one of the well-known ids: 'create', 'update' and 'apply_stimulus'
  95. * @param string $sMessage The HTML message (must be correctly escaped)
  96. * @param string $sSeverity Any of the following: ok, info, error.
  97. * @param float $fRank Ordering of the message: smallest displayed first (can be negative)
  98. * @param bool $bMustNotExist Do not alter any existing message (considering the id)
  99. *
  100. */
  101. public static function SetSessionMessage($sClass, $iKey, $sMessageId, $sMessage, $sSeverity, $fRank, $bMustNotExist = false)
  102. {
  103. $sMessageKey = $sClass.'::'.$iKey;
  104. if (!isset($_SESSION['obj_messages'][$sMessageKey]))
  105. {
  106. $_SESSION['obj_messages'][$sMessageKey] = array();
  107. }
  108. if (!$bMustNotExist || !array_key_exists($sMessageId, $_SESSION['obj_messages'][$sMessageKey]))
  109. {
  110. $_SESSION['obj_messages'][$sMessageKey][$sMessageId] = array(
  111. 'rank' => $fRank,
  112. 'severity' => $sSeverity,
  113. 'message' => $sMessage
  114. );
  115. }
  116. }
  117. function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
  118. {
  119. // Standard Header with name, actions menu and history block
  120. //
  121. // Is there a message for this object ??
  122. $sMessageKey = get_class($this).'::'.$this->GetKey();
  123. if (array_key_exists('obj_messages', $_SESSION) && array_key_exists($sMessageKey, $_SESSION['obj_messages']))
  124. {
  125. $aMessages = array();
  126. $aRanks = array();
  127. foreach ($_SESSION['obj_messages'][$sMessageKey] as $sMessageId => $aMessageData)
  128. {
  129. $sMsgClass = 'message_'.$aMessageData['severity'];
  130. $aMessages[] = "<div class=\"header_message $sMsgClass\">".$aMessageData['message']."</div>";
  131. $aRanks[] = $aMessageData['rank'];
  132. }
  133. array_multisort($aRanks, $aMessages);
  134. foreach ($aMessages as $sMessage)
  135. {
  136. $oPage->add($sMessage);
  137. }
  138. unset($_SESSION['obj_messages'][$sMessageKey]);
  139. }
  140. // action menu
  141. $oSingletonFilter = new DBObjectSearch(get_class($this));
  142. $oSingletonFilter->AddCondition('id', $this->GetKey(), '=');
  143. $oBlock = new MenuBlock($oSingletonFilter, 'details', false);
  144. $oBlock->Display($oPage, -1);
  145. // Master data sources
  146. $sSynchroIcon = '';
  147. $oReplicaSet = $this->GetMasterReplica();
  148. $bSynchronized = false;
  149. $oCreatorTask = null;
  150. $bCanBeDeletedByTask = false;
  151. $bCanBeDeletedByUser = true;
  152. $aMasterSources = array();
  153. if ($oReplicaSet->Count() > 0)
  154. {
  155. $bSynchronized = true;
  156. while($aData = $oReplicaSet->FetchAssoc())
  157. {
  158. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  159. $sApplicationURL = $aData['datasource']->GetApplicationUrl($this, $aData['replica']);
  160. $sLink = $aData['datasource']->GetName();
  161. if (!empty($sApplicationURL))
  162. {
  163. $sLink = "<a href=\"$sApplicationURL\" target=\"_blank\">".$aData['datasource']->GetName()."</a>";
  164. }
  165. if ($aData['replica']->Get('status_dest_creator') == 1)
  166. {
  167. $oCreatorTask = $aData['datasource'];
  168. $bCreatedByTask = true;
  169. }
  170. else
  171. {
  172. $bCreatedByTask = false;
  173. }
  174. if ($bCreatedByTask)
  175. {
  176. $sDeletePolicy = $aData['datasource']->Get('delete_policy');
  177. if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete'))
  178. {
  179. $bCanBeDeletedByTask = true;
  180. }
  181. $sUserDeletePolicy = $aData['datasource']->Get('user_delete_policy');
  182. if ($sUserDeletePolicy == 'nobody')
  183. {
  184. $bCanBeDeletedByUser = false;
  185. }
  186. elseif (($sUserDeletePolicy == 'administrators') && !UserRights::IsAdministrator())
  187. {
  188. $bCanBeDeletedByUser = false;
  189. }
  190. else // everybody...
  191. {
  192. }
  193. }
  194. $aMasterSources[$aData['datasource']->GetKey()]['datasource'] = $aData['datasource'];
  195. $aMasterSources[$aData['datasource']->GetKey()]['url'] = $sLink;
  196. $aMasterSources[$aData['datasource']->GetKey()]['last_synchro'] = $aData['replica']->Get('status_last_seen');
  197. }
  198. if (is_object($oCreatorTask))
  199. {
  200. $sTaskUrl = $aMasterSources[$oCreatorTask->GetKey()]['url'];
  201. if (!$bCanBeDeletedByUser)
  202. {
  203. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sTaskUrl)."</p>";
  204. }
  205. else
  206. {
  207. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectWasCreatedBy_Source', $sTaskUrl)."</p>";
  208. }
  209. if ($bCanBeDeletedByTask)
  210. {
  211. $sTip .= "<p>".Dict::Format('Core:Synchro:TheObjectCanBeDeletedBy_Source', $sTaskUrl)."</p>";
  212. }
  213. }
  214. else
  215. {
  216. $sTip = "<p>".Dict::S('Core:Synchro:ThisObjectIsSynchronized')."</p>";
  217. }
  218. $sTip .= "<p><b>".Dict::S('Core:Synchro:ListOfDataSources')."</b></p>";
  219. foreach($aMasterSources as $aStruct)
  220. {
  221. $oDataSource = $aStruct['datasource'];
  222. $sLink = $aStruct['url'];
  223. $sTip .= "<p style=\"white-space:nowrap\">".$oDataSource->GetIcon(true, 'style="vertical-align:middle"')."&nbsp;$sLink<br/>";
  224. $sTip .= Dict::S('Core:Synchro:LastSynchro').'<br/>'.$aStruct['last_synchro']."</p>";
  225. }
  226. $sSynchroIcon = '&nbsp;<img style="vertical-align:middle;" id="synchro_icon" src="../images/locked.png"/>';
  227. $sTip = addslashes($sTip);
  228. $oPage->add_ready_script("$('#synchro_icon').qtip( { content: '$sTip', show: 'mouseover', hide: { fixed: true }, style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  229. }
  230. $oPage->add("<div class=\"page_header\"><h1>".$this->GetIcon()."&nbsp;\n");
  231. $sRefreshIcon = '';
  232. if ($_SERVER['REQUEST_METHOD'] == 'GET')
  233. {
  234. $sRefreshIcon = '<img src="../images/reload.png" style="cursor:pointer;vertical-align:middle;margin-left:1em;" onclick="window.location.reload();" title="'.htmlentities(Dict::S('UI:Button:Refresh'), ENT_QUOTES, 'UTF-8').'"/>';
  235. }
  236. $oPage->add(MetaModel::GetName(get_class($this)).": <span class=\"hilite\">".$this->GetName()."</span>$sRefreshIcon $sSynchroIcon</h1>\n");
  237. $oPage->add("</div>\n");
  238. }
  239. function DisplayBareHistory(WebPage $oPage, $bEditMode = false, $iLimitCount = 0, $iLimitStart = 0)
  240. {
  241. // history block (with as a tab)
  242. $oHistoryFilter = new DBObjectSearch('CMDBChangeOp');
  243. $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '=');
  244. $oHistoryFilter->AddCondition('objclass', get_class($this), '=');
  245. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  246. $oBlock->SetLimit($iLimitCount, $iLimitStart);
  247. $oBlock->Display($oPage, 'history');
  248. }
  249. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  250. {
  251. $aFieldsMap = $this->GetBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams);
  252. if (!isset($aExtraParams['disable_plugins']) || !$aExtraParams['disable_plugins'])
  253. {
  254. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  255. {
  256. $oExtensionInstance->OnDisplayProperties($this, $oPage, $bEditMode);
  257. }
  258. }
  259. // Special case to display the case log, if any...
  260. // WARNING: if you modify the loop below, also check the corresponding code in UpdateObject and DisplayModifyForm
  261. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  262. {
  263. if ($oAttDef instanceof AttributeCaseLog)
  264. {
  265. $sComment = (isset($aExtraParams['fieldsComments'][$sAttCode])) ? $aExtraParams['fieldsComments'][$sAttCode] : '';
  266. $this->DisplayCaseLog($oPage, $sAttCode, $sComment, $sPrefix, $bEditMode);
  267. $aFieldsMap[$sAttCode] = $this->m_iFormId.'_'.$sAttCode;
  268. }
  269. }
  270. return $aFieldsMap;
  271. }
  272. /**
  273. * Add a field to the map: attcode => id used when building a form
  274. * @param string $sAttCode The attribute code of the field being edited
  275. * @param string $sInputId The unique ID of the control/widget in the page
  276. */
  277. protected function AddToFieldsMap($sAttCode, $sInputId)
  278. {
  279. $this->aFieldsMap[$sAttCode] = $sInputId;
  280. }
  281. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  282. {
  283. // Related objects: display all the linkset attributes, each as a separate tab
  284. // In the order described by the 'display' ZList
  285. $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  286. if (count($aList) == 0)
  287. {
  288. // Empty ZList defined, display all the linkedset attributes defined
  289. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  290. }
  291. $sClass = get_class($this);
  292. foreach($aList as $sAttCode)
  293. {
  294. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  295. // Display mode
  296. if (!$oAttDef->IsLinkset()) continue; // Process only linkset attributes...
  297. // $oSet = new DBObjectSet($this->Get($sAttCode)->GetFilter()); // Why do something so useless ?
  298. $oSet = $this->Get($sAttCode);
  299. $iCount = $oSet->Count();
  300. $sCount = '';
  301. if ($iCount != 0)
  302. {
  303. $sCount = " ($iCount)";
  304. }
  305. $oPage->SetCurrentTab($oAttDef->GetLabel().$sCount);
  306. if ($this->IsNew())
  307. {
  308. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  309. }
  310. else
  311. {
  312. $iFlags = $this->GetAttributeFlags($sAttCode);
  313. }
  314. $bReadOnly = ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE));
  315. if ($bEditMode && (!$bReadOnly))
  316. {
  317. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  318. $sLinkedClass = $oAttDef->GetLinkedClass();
  319. if ($oAttDef->IsIndirect())
  320. {
  321. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  322. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  323. }
  324. else
  325. {
  326. $sTargetClass = $sLinkedClass;
  327. }
  328. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription().'<span id="busy_'.$sInputId.'"></span>');
  329. $oValue = $this->Get($sAttCode);
  330. $sDisplayValue = ''; // not used
  331. $aArgs = array('this' => $this);
  332. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $oValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  333. $this->AddToFieldsMap($sAttCode, $sInputId);
  334. $oPage->add($sHTMLValue);
  335. }
  336. else
  337. {
  338. // Display mode
  339. if (!$oAttDef->IsIndirect())
  340. {
  341. // 1:n links
  342. $sTargetClass = $oAttDef->GetLinkedClass();
  343. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  344. $oAppContext = new ApplicationContext();
  345. foreach($oAppContext->GetNames() as $sKey)
  346. {
  347. // The linked object inherits the parent's value for the context
  348. if (MetaModel::IsValidAttCode($sClass, $sKey))
  349. {
  350. $aDefaults[$sKey] = $this->Get($sKey);
  351. }
  352. }
  353. $aParams = array(
  354. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  355. 'object_id' => $this->GetKey(),
  356. 'menu' => false,
  357. 'default' => $aDefaults,
  358. 'table_id' => $sClass.'_'.$sAttCode,
  359. );
  360. }
  361. else
  362. {
  363. // n:n links
  364. $sLinkedClass = $oAttDef->GetLinkedClass();
  365. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  366. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  367. $bMenu = ($this->Get($sAttCode)->Count() > 0); // The menu is enabled only if there are already some elements...
  368. $aParams = array(
  369. 'link_attr' => $oAttDef->GetExtKeyToMe(),
  370. 'object_id' => $this->GetKey(),
  371. 'target_attr' => $oAttDef->GetExtKeyToRemote(),
  372. 'view_link' => false,
  373. 'menu' => false,
  374. 'display_limit' => true, // By default limit the list to speed up the initial load & display
  375. 'table_id' => $sClass.'_'.$sAttCode,
  376. );
  377. }
  378. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  379. $oBlock = new DisplayBlock($this->Get($sAttCode)->GetFilter(), 'list', false);
  380. $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams);
  381. }
  382. }
  383. $oPage->SetCurrentTab('');
  384. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  385. {
  386. $oExtensionInstance->OnDisplayRelations($this, $oPage, $bEditMode);
  387. }
  388. // Display Notifications after the other tabs since this tab disappears in edition
  389. if (!$bEditMode)
  390. {
  391. // Look for any trigger that considers this object as "In Scope"
  392. // If any trigger has been found then display a tab with notifications
  393. //
  394. $oTriggerSet = new CMDBObjectSet(new DBObjectSearch('Trigger'));
  395. $aTriggers = array();
  396. while($oTrigger = $oTriggerSet->Fetch())
  397. {
  398. if($oTrigger->IsInScope($this))
  399. {
  400. $aTriggers[] = $oTrigger->GetKey();
  401. }
  402. }
  403. if (count($aTriggers) > 0)
  404. {
  405. $iId = $this->GetKey();
  406. $sTriggersList = implode(',', $aTriggers);
  407. $aNotifSearches = array();
  408. $iNotifsCount = 0;
  409. $aNotificationClasses = MetaModel::EnumChildClasses('EventNotification', ENUM_CHILD_CLASSES_EXCLUDETOP);
  410. foreach($aNotificationClasses as $sNotifClass)
  411. {
  412. $aNotifSearches[$sNotifClass] = DBObjectSearch::FromOQL("SELECT $sNotifClass AS Ev JOIN Trigger AS T ON Ev.trigger_id = T.id WHERE T.id IN ($sTriggersList) AND Ev.object_id = $iId");
  413. $oNotifSet = new DBObjectSet($aNotifSearches[$sNotifClass]);
  414. $iNotifsCount += $oNotifSet->Count();
  415. }
  416. // Display notifications regarding the object: on block per subclass to have the intersting columns
  417. $sCount = ($iNotifsCount > 0) ? ' ('.$iNotifsCount.')' : '';
  418. $oPage->SetCurrentTab(Dict::S('UI:NotificationsTab').$sCount);
  419. foreach($aNotificationClasses as $sNotifClass)
  420. {
  421. $oPage->p(MetaModel::GetClassIcon($sNotifClass, true).'&nbsp;'.MetaModel::GetName($sNotifClass));
  422. $oBlock = new DisplayBlock($aNotifSearches[$sNotifClass], 'list', false);
  423. $oBlock->Display($oPage, 'notifications_'.$sNotifClass, array('menu' => false));
  424. }
  425. }
  426. }
  427. }
  428. function GetBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix, $aExtraParams = array())
  429. {
  430. $sHtml = '';
  431. $oAppContext = new ApplicationContext();
  432. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  433. $aDetails = array();
  434. $sClass = get_class($this);
  435. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  436. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  437. // Compute the list of properties to display, first the attributes in the 'details' list, then
  438. // all the remaining attributes that are not external fields
  439. $sHtml = '';
  440. $aDetails = array();
  441. $iInputId = 0;
  442. $aFieldsMap = array();
  443. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  444. $aExtraFlags = (isset($aExtraParams['fieldsFlags'])) ? $aExtraParams['fieldsFlags'] : array();
  445. $bFieldComments = (count($aFieldsComments) > 0);
  446. foreach($aDetailsStruct as $sTab => $aCols )
  447. {
  448. $aDetails[$sTab] = array();
  449. ksort($aCols);
  450. $oPage->SetCurrentTab(Dict::S($sTab));
  451. $oPage->add('<table style="vertical-align:top"><tr>');
  452. foreach($aCols as $sColIndex => $aFieldsets)
  453. {
  454. $oPage->add('<td style="vertical-align:top">');
  455. //$aDetails[$sTab][$sColIndex] = array();
  456. $sLabel = '';
  457. $sPreviousLabel = '';
  458. $aDetails[$sTab][$sColIndex] = array();
  459. foreach($aFieldsets as $sFieldsetName => $aFields)
  460. {
  461. if (!empty($sFieldsetName) && ($sFieldsetName[0] != '_'))
  462. {
  463. $sLabel = $sFieldsetName;
  464. }
  465. else
  466. {
  467. $sLabel = '';
  468. }
  469. if ($sLabel != $sPreviousLabel)
  470. {
  471. if (!empty($sPreviousLabel))
  472. {
  473. $oPage->add('<fieldset>');
  474. $oPage->add('<legend>'.Dict::S($sPreviousLabel).'</legend>');
  475. }
  476. $oPage->Details($aDetails[$sTab][$sColIndex]);
  477. if (!empty($sPreviousLabel))
  478. {
  479. $oPage->add('</fieldset>');
  480. }
  481. $aDetails[$sTab][$sColIndex] = array();
  482. $sPreviousLabel = $sLabel;
  483. }
  484. foreach($aFields as $sAttCode)
  485. {
  486. if ($bEditMode)
  487. {
  488. $sComments = isset($aFieldsComments[$sAttCode]) ? $aFieldsComments[$sAttCode] : '&nbsp;';
  489. $sInfos = '&nbsp;';
  490. if ($this->IsNew())
  491. {
  492. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  493. }
  494. else
  495. {
  496. $iFlags = $this->GetAttributeFlags($sAttCode);
  497. }
  498. if (($iFlags & OPT_ATT_MANDATORY) && $this->IsNew())
  499. {
  500. $iFlags = $iFlags & ~OPT_ATT_READONLY; // Mandatory fields cannot be read-only when creating an object
  501. }
  502. if (array_key_exists($sAttCode, $aExtraFlags))
  503. {
  504. // the caller may override some flags if needed
  505. $iFlags = $iFlags | $aExtraFlags[$sAttCode];
  506. }
  507. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  508. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0))
  509. {
  510. if ($oAttDef->IsWritable())
  511. {
  512. if ($sStateAttCode == $sAttCode)
  513. {
  514. // State attribute is always read-only from the UI
  515. $sHTMLValue = $this->GetStateLabel();
  516. $val = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  517. }
  518. else
  519. {
  520. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  521. if ($iFlags & OPT_ATT_HIDDEN)
  522. {
  523. // Attribute is hidden, add a hidden input
  524. $oPage->add('<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>');
  525. $aFieldsMap[$sAttCode] = $sInputId;
  526. }
  527. else
  528. {
  529. if ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE))
  530. {
  531. // Check if the attribute is not read-only because of a synchro...
  532. $aReasons = array();
  533. $sSynchroIcon = '';
  534. if ($iFlags & OPT_ATT_SLAVE)
  535. {
  536. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  537. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  538. $sTip = '';
  539. foreach($aReasons as $aRow)
  540. {
  541. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  542. }
  543. $sTip = addslashes($sTip);
  544. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  545. }
  546. // Attribute is read-only
  547. $sHTMLValue = "<span id=\"field_{$sInputId}\">".$this->GetAsHTML($sAttCode);
  548. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/></span>';
  549. $aFieldsMap[$sAttCode] = $sInputId;
  550. $sComments = $sSynchroIcon;
  551. }
  552. else
  553. {
  554. $sValue = $this->Get($sAttCode);
  555. $sDisplayValue = $this->GetEditValue($sAttCode);
  556. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  557. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  558. $aFieldsMap[$sAttCode] = $sInputId;
  559. }
  560. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  561. }
  562. }
  563. }
  564. else
  565. {
  566. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $this->GetAsHTML($sAttCode), 'comments' => $sComments, 'infos' => $sInfos);
  567. }
  568. }
  569. else
  570. {
  571. $val = null; // Skip this field
  572. }
  573. }
  574. else
  575. {
  576. // !bEditMode
  577. $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode);
  578. }
  579. if ($val != null)
  580. {
  581. // The field is visible, add it to the current column
  582. $aDetails[$sTab][$sColIndex][] = $val;
  583. $iInputId++;
  584. }
  585. }
  586. }
  587. if (!empty($sPreviousLabel))
  588. {
  589. $oPage->add('<fieldset>');
  590. $oPage->add('<legend>'.Dict::S($sFieldsetName).'</legend>');
  591. }
  592. $oPage->Details($aDetails[$sTab][$sColIndex]);
  593. if (!empty($sPreviousLabel))
  594. {
  595. $oPage->add('</fieldset>');
  596. }
  597. $oPage->add('</td>');
  598. }
  599. $oPage->add('</tr></table>');
  600. }
  601. return $aFieldsMap;
  602. }
  603. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  604. {
  605. $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate(get_class($this)));
  606. if (!empty($sTemplate))
  607. {
  608. $oTemplate = new DisplayTemplate($sTemplate);
  609. // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved
  610. // but the preferred method is to use '$id$'
  611. $oTemplate->Render($oPage, array('class_name'=> MetaModel::GetName(get_class($this)),'class'=> get_class($this), 'pkey'=> $this->GetKey(), 'id'=> $this->GetKey(), 'name' => $this->GetName()));
  612. }
  613. else
  614. {
  615. // Object's details
  616. // template not found display the object using the *old style*
  617. $this->DisplayBareHeader($oPage, $bEditMode);
  618. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  619. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  620. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  621. $this->DisplayBareProperties($oPage, $bEditMode);
  622. $this->DisplayBareRelations($oPage, $bEditMode);
  623. //$oPage->SetCurrentTab(Dict::S('UI:HistoryTab'));
  624. //$this->DisplayBareHistory($oPage, $bEditMode);
  625. $oPage->AddAjaxTab(Dict::S('UI:HistoryTab'), utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php?operation=history&class='.get_class($this).'&id='.$this->GetKey());
  626. }
  627. }
  628. function DisplayPreview(WebPage $oPage)
  629. {
  630. $aDetails = array();
  631. $sClass = get_class($this);
  632. $aList = MetaModel::GetZListItems($sClass, 'preview');
  633. foreach($aList as $sAttCode)
  634. {
  635. $aDetails[] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' =>$this->GetAsHTML($sAttCode));
  636. }
  637. $oPage->details($aDetails);
  638. }
  639. public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  640. {
  641. $oPage->add(self::GetDisplaySet($oPage, $oSet, $aExtraParams));
  642. }
  643. /**
  644. * Get the HTML fragment corresponding to the display of a table representing a set of objects
  645. * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output
  646. * @param CMDBObjectSet The set of objects to display
  647. * @param Hash $aExtraParams Some extra configuration parameters to tweak the behavior of the display
  648. * @return String The HTML fragment representing the table of objects
  649. */
  650. public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  651. {
  652. if (empty($aExtraParams['currentId']))
  653. {
  654. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  655. }
  656. else
  657. {
  658. $iListId = $aExtraParams['currentId'];
  659. }
  660. // Initialize and check the parameters
  661. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  662. $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
  663. $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0;
  664. $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : '';
  665. if (!empty($sLinkageAttribute))
  666. {
  667. if($iLinkedObjectId == 0)
  668. {
  669. // if 'links' mode is requested the id of the object to link to must be specified
  670. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  671. }
  672. if($sTargetAttr == '')
  673. {
  674. // if 'links' mode is requested the d of the object to link to must be specified
  675. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  676. }
  677. }
  678. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  679. $bTruncated = isset($aExtraParams['truncated']) ? $aExtraParams['truncated'] == true : true;
  680. $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
  681. $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
  682. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  683. $aExtraFields = array();
  684. foreach ($aExtraFieldsRaw as $sFieldName)
  685. {
  686. // Ignore attributes not of the main queried class
  687. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  688. {
  689. $sClassAlias = $aMatches[1];
  690. $sAttCode = $aMatches[2];
  691. if ($sClassAlias == $oSet->GetFilter()->GetClassAlias())
  692. {
  693. $aExtraFields[] = $sAttCode;
  694. }
  695. }
  696. else
  697. {
  698. $aExtraFields[] = $sFieldName;
  699. }
  700. }
  701. $sHtml = '';
  702. $oAppContext = new ApplicationContext();
  703. $sClassName = $oSet->GetFilter()->GetClass();
  704. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  705. if ($sZListName !== false)
  706. {
  707. $aList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  708. $aList = array_merge($aList, $aExtraFields);
  709. }
  710. else
  711. {
  712. $aList = $aExtraFields;
  713. }
  714. // Filter the list to removed linked set since we are not able to display them here
  715. foreach($aList as $index => $sAttCode)
  716. {
  717. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  718. if ($oAttDef instanceof AttributeLinkedSet)
  719. {
  720. // Removed from the display list
  721. unset($aList[$index]);
  722. }
  723. }
  724. if (!empty($sLinkageAttribute))
  725. {
  726. // The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
  727. // and other objects...
  728. // The display will then group all the attributes related to the link itself:
  729. // | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
  730. $aDisplayList = array();
  731. $aAttDefs = MetaModel::ListAttributeDefs($sClassName);
  732. assert(isset($aAttDefs[$sLinkageAttribute]));
  733. $oAttDef = $aAttDefs[$sLinkageAttribute];
  734. assert($oAttDef->IsExternalKey());
  735. // First display all the attributes specific to the link record
  736. foreach($aList as $sLinkAttCode)
  737. {
  738. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  739. if ( (!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField()) )
  740. {
  741. $aDisplayList[] = $sLinkAttCode;
  742. }
  743. }
  744. // Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
  745. foreach($aList as $sLinkAttCode)
  746. {
  747. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  748. if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
  749. || ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode()!=$sLinkageAttribute)) )
  750. {
  751. $aDisplayList[] = $sLinkAttCode;
  752. }
  753. }
  754. // First display all the attributes specific to the link
  755. // Then display all the attributes linked to the other end of the relationship
  756. $aList = $aDisplayList;
  757. }
  758. $sSelectMode = 'none';
  759. if ($bSelectMode)
  760. {
  761. $sSelectMode = $bSingleSelectMode ? 'single' : 'multiple';
  762. }
  763. $sClassAlias = $oSet->GetClassAlias();
  764. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  765. $sTableId = isset($aExtraParams['table_id']) ? $aExtraParams['table_id'] : null;
  766. $aClassAliases = array( $sClassAlias => $sClassName);
  767. $oDataTable = new DataTable($iListId, $oSet, $aClassAliases, $sTableId);
  768. $oSettings = DataTableSettings::GetDataModelSettings($aClassAliases, $bViewLink, array($sClassAlias => $aList));
  769. if ($bDisplayLimit)
  770. {
  771. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  772. $oSettings->iDefaultPageSize = $iDefaultPageSize;
  773. }
  774. else
  775. {
  776. $oSettings->iDefaultPageSize = 0;
  777. }
  778. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  779. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  780. }
  781. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  782. {
  783. if (empty($aExtraParams['currentId']))
  784. {
  785. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  786. }
  787. else
  788. {
  789. $iListId = $aExtraParams['currentId'];
  790. }
  791. $aList = array();
  792. // Initialize and check the parameters
  793. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  794. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  795. // Check if there is a list of aliases to limit the display to...
  796. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  797. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  798. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  799. $aExtraFields = array();
  800. foreach ($aExtraFieldsRaw as $sFieldName)
  801. {
  802. // Ignore attributes not of the main queried class
  803. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  804. {
  805. $sClassAlias = $aMatches[1];
  806. $sAttCode = $aMatches[2];
  807. if (array_key_exists($sClassAlias, $oSet->GetSelectedClasses()))
  808. {
  809. $aExtraFields[$sClassAlias][] = $sAttCode;
  810. }
  811. }
  812. else
  813. {
  814. $aExtraFields['*'] = $sAttCode;
  815. }
  816. }
  817. $sHtml = '';
  818. $oAppContext = new ApplicationContext();
  819. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  820. $aAuthorizedClasses = array();
  821. foreach($aClasses as $sAlias => $sClassName)
  822. {
  823. if ( (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) &&
  824. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  825. {
  826. $aAuthorizedClasses[$sAlias] = $sClassName;
  827. }
  828. }
  829. $aAttribs = array();
  830. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  831. {
  832. if (array_key_exists($sAlias, $aExtraFields))
  833. {
  834. $aList[$sAlias] = $aExtraFields[$sAlias];
  835. }
  836. else
  837. {
  838. $aList[$sAlias] = array();
  839. }
  840. if ($sZListName !== false)
  841. {
  842. $aDefaultList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  843. $aList[$sAlias] = array_merge($aDefaultList, $aList[$sAlias]);
  844. }
  845. // Filter the list to removed linked set since we are not able to display them here
  846. foreach($aList[$sAlias] as $index => $sAttCode)
  847. {
  848. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  849. if ($oAttDef instanceof AttributeLinkedSet)
  850. {
  851. // Removed from the display list
  852. unset($aList[$sAlias][$index]);
  853. }
  854. }
  855. }
  856. $sSelectMode = 'none';
  857. $sClassAlias = $oSet->GetClassAlias();
  858. $oDataTable = new DataTable($iListId, $oSet, $aAuthorizedClasses);
  859. $oSettings = DataTableSettings::GetDataModelSettings($aAuthorizedClasses, $bViewLink, $aList);
  860. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  861. if ($bDisplayLimit)
  862. {
  863. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  864. $oSettings->iDefaultPageSize = $iDefaultPageSize;
  865. }
  866. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  867. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  868. }
  869. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  870. {
  871. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  872. }
  873. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  874. {
  875. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  876. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  877. $aFields = null;
  878. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  879. {
  880. $aFields = explode(',', $aParams['fields']);
  881. }
  882. $bFieldsAdvanced = false;
  883. if (isset($aParams['fields_advanced']))
  884. {
  885. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  886. }
  887. $bLocalize = true;
  888. if (isset($aParams['localize_values']))
  889. {
  890. $bLocalize = (bool) $aParams['localize_values'];
  891. }
  892. $aList = array();
  893. $oAppContext = new ApplicationContext();
  894. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  895. $aAuthorizedClasses = array();
  896. foreach($aClasses as $sAlias => $sClassName)
  897. {
  898. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  899. {
  900. $aAuthorizedClasses[$sAlias] = $sClassName;
  901. }
  902. }
  903. $aAttribs = array();
  904. $aHeader = array();
  905. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  906. {
  907. $aList[$sAlias] = array();
  908. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  909. {
  910. if (is_null($aFields) || (count($aFields) == 0))
  911. {
  912. // Standard list of attributes (no link sets)
  913. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  914. {
  915. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  916. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  917. {
  918. if ($bFieldsAdvanced)
  919. {
  920. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  921. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  922. {
  923. $sRemoteClass = $oAttDef->GetTargetClass();
  924. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  925. {
  926. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  927. }
  928. }
  929. }
  930. }
  931. else
  932. {
  933. // Any other attribute
  934. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  935. }
  936. }
  937. }
  938. else
  939. {
  940. // User defined list of attributes
  941. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  942. {
  943. $aList[$sAlias][$sAttCode] = $oAttDef;
  944. }
  945. }
  946. }
  947. if ($bFieldsAdvanced)
  948. {
  949. $aHeader[] = 'id';
  950. }
  951. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  952. {
  953. $aHeader[] = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx, isset($aParams['showMandatoryFields'])) : $sAttCodeEx;
  954. }
  955. }
  956. $sHtml = implode($sSeparator, $aHeader)."\n";
  957. $oSet->Seek(0);
  958. while ($aObjects = $oSet->FetchAssoc())
  959. {
  960. $aRow = array();
  961. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  962. {
  963. $oObj = $aObjects[$sAlias];
  964. if ($bFieldsAdvanced)
  965. {
  966. if (is_null($oObj))
  967. {
  968. $aRow[] = '';
  969. }
  970. else
  971. {
  972. $aRow[] = $oObj->GetKey();
  973. }
  974. }
  975. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  976. {
  977. if (is_null($oObj))
  978. {
  979. $aRow[] = '';
  980. }
  981. else
  982. {
  983. $value = $oObj->Get($sAttCodeEx);
  984. $aRow[] = $oAttDef->GetAsCSV($value, $sSeparator, $sTextQualifier, $oObj, $bLocalize);
  985. }
  986. }
  987. }
  988. $sHtml .= implode($sSeparator, $aRow)."\n";
  989. }
  990. return $sHtml;
  991. }
  992. static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  993. {
  994. $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams));
  995. }
  996. /**
  997. * Spreadsheet output: designed for end users doing some reporting
  998. * Then the ids are excluded and replaced by the corresponding friendlyname
  999. */
  1000. static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array())
  1001. {
  1002. $aFields = null;
  1003. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  1004. {
  1005. $aFields = explode(',', $aParams['fields']);
  1006. }
  1007. $bFieldsAdvanced = false;
  1008. if (isset($aParams['fields_advanced']))
  1009. {
  1010. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  1011. }
  1012. $bLocalize = true;
  1013. if (isset($aParams['localize_values']))
  1014. {
  1015. $bLocalize = (bool) $aParams['localize_values'];
  1016. }
  1017. $aList = array();
  1018. $oAppContext = new ApplicationContext();
  1019. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1020. $aAuthorizedClasses = array();
  1021. foreach($aClasses as $sAlias => $sClassName)
  1022. {
  1023. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1024. {
  1025. $aAuthorizedClasses[$sAlias] = $sClassName;
  1026. }
  1027. }
  1028. $aAttribs = array();
  1029. $aHeader = array();
  1030. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1031. {
  1032. $aList[$sAlias] = array();
  1033. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  1034. {
  1035. if (is_null($aFields) || (count($aFields) == 0))
  1036. {
  1037. // Standard list of attributes (no link sets)
  1038. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  1039. {
  1040. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  1041. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  1042. if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  1043. {
  1044. $sRemoteClass = $oAttDef->GetTargetClass();
  1045. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  1046. {
  1047. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  1048. }
  1049. }
  1050. }
  1051. }
  1052. else
  1053. {
  1054. // User defined list of attributes
  1055. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  1056. {
  1057. $aList[$sAlias][$sAttCode] = $oAttDef;
  1058. }
  1059. }
  1060. }
  1061. // Replace external key by the corresponding friendly name (if not already in the list)
  1062. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1063. {
  1064. if ($oAttDef->IsExternalKey())
  1065. {
  1066. unset($aList[$sAlias][$sAttCode]);
  1067. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1068. if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode))
  1069. {
  1070. $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode);
  1071. $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt;
  1072. }
  1073. }
  1074. }
  1075. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1076. {
  1077. $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx;
  1078. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1079. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1080. {
  1081. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  1082. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  1083. }
  1084. else
  1085. {
  1086. $aHeader[] = $sColLabel;
  1087. }
  1088. }
  1089. }
  1090. $sHtml = "<table border=\"1\">\n";
  1091. $sHtml .= "<tr>\n";
  1092. $sHtml .= "<td>".implode("</td><td>", $aHeader)."</td>\n";
  1093. $sHtml .= "</tr>\n";
  1094. $oSet->Seek(0);
  1095. while ($aObjects = $oSet->FetchAssoc())
  1096. {
  1097. $aRow = array();
  1098. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1099. {
  1100. $oObj = $aObjects[$sAlias];
  1101. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1102. {
  1103. if (is_null($oObj))
  1104. {
  1105. $aRow[] = '<td></td>';
  1106. }
  1107. else
  1108. {
  1109. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1110. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1111. {
  1112. $sDate = $oObj->Get($sAttCodeEx);
  1113. if ($sDate === null)
  1114. {
  1115. $aRow[] = '<td></td>';
  1116. $aRow[] = '<td></td>';
  1117. }
  1118. else
  1119. {
  1120. $iDate = AttributeDateTime::GetAsUnixSeconds($sDate);
  1121. $aRow[] = '<td>'.date('Y-m-d', $iDate).'</td>';
  1122. $aRow[] = '<td>'.date('H:i:s', $iDate).'</td>';
  1123. }
  1124. }
  1125. else if($oAttDef instanceof AttributeCaseLog)
  1126. {
  1127. $rawValue = $oObj->Get($sAttCodeEx);
  1128. $outputValue = str_replace("\n", "<br/>", htmlentities($rawValue->__toString(), ENT_QUOTES, 'UTF-8'));
  1129. // Trick for Excel: treat the content as text even if it begins with an equal sign
  1130. $aRow[] = '<td x:str>'.$outputValue.'</td>';
  1131. }
  1132. else
  1133. {
  1134. $rawValue = $oObj->Get($sAttCodeEx);
  1135. /*
  1136. if ($oAttDef instanceof AttributeFriendlyName)
  1137. {
  1138. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1139. if ($sKeyAttCode != 'id')
  1140. {
  1141. if ($oObj->Get($sKeyAttCode) == 0)
  1142. {
  1143. $rawValue = '';
  1144. }
  1145. }
  1146. }
  1147. */
  1148. if ($bLocalize)
  1149. {
  1150. $outputValue = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8');
  1151. }
  1152. else
  1153. {
  1154. $outputValue = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  1155. }
  1156. $aRow[] = '<td>'.$outputValue.'</td>';
  1157. }
  1158. }
  1159. }
  1160. }
  1161. $sHtml .= implode("\n", $aRow);
  1162. $sHtml .= "</tr>\n";
  1163. }
  1164. $sHtml .= "</table>\n";
  1165. return $sHtml;
  1166. }
  1167. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1168. {
  1169. $bLocalize = true;
  1170. if (isset($aParams['localize_values']))
  1171. {
  1172. $bLocalize = (bool) $aParams['localize_values'];
  1173. }
  1174. $oAppContext = new ApplicationContext();
  1175. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1176. $aAuthorizedClasses = array();
  1177. foreach($aClasses as $sAlias => $sClassName)
  1178. {
  1179. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1180. {
  1181. $aAuthorizedClasses[$sAlias] = $sClassName;
  1182. }
  1183. }
  1184. $aAttribs = array();
  1185. $aList = array();
  1186. $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details');
  1187. $oPage->add("<Set>\n");
  1188. $oSet->Seek(0);
  1189. while ($aObjects = $oSet->FetchAssoc())
  1190. {
  1191. if (count($aAuthorizedClasses) > 1)
  1192. {
  1193. $oPage->add("<Row>\n");
  1194. }
  1195. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1196. {
  1197. $oObj = $aObjects[$sAlias];
  1198. if (is_null($oObj))
  1199. {
  1200. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n");
  1201. }
  1202. else
  1203. {
  1204. $sClassName = get_class($oObj);
  1205. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  1206. }
  1207. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  1208. {
  1209. if (is_null($oObj))
  1210. {
  1211. $oPage->add("<$sAttCode>null</$sAttCode>\n");
  1212. }
  1213. else
  1214. {
  1215. if ($oAttDef->IsWritable())
  1216. {
  1217. if (!$oAttDef->IsLinkSet())
  1218. {
  1219. $sValue = $oObj->GetAsXML($sAttCode, $bLocalize);
  1220. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  1221. }
  1222. }
  1223. }
  1224. }
  1225. $oPage->add("</$sClassName>\n");
  1226. }
  1227. if (count($aAuthorizedClasses) > 1)
  1228. {
  1229. $oPage->add("</Row>\n");
  1230. }
  1231. }
  1232. $oPage->add("</Set>\n");
  1233. }
  1234. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1235. {
  1236. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  1237. }
  1238. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1239. {
  1240. static $iSearchFormId = 0;
  1241. $bMultiSelect = false;
  1242. $oAppContext = new ApplicationContext();
  1243. $sHtml = '';
  1244. $numCols=4;
  1245. $sClassName = $oSet->GetFilter()->GetClass();
  1246. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  1247. // (especially when used to add a link)
  1248. /*
  1249. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  1250. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  1251. <li><a class=\"selected\" href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:SimpleSearchTab')."</a></li>
  1252. </ul></div>\n";
  1253. */
  1254. // Simple search form
  1255. if (isset($aExtraParams['currentId']))
  1256. {
  1257. $sSearchFormId = $aExtraParams['currentId'];
  1258. }
  1259. else
  1260. {
  1261. $iSearchFormId = $oPage->GetUniqueId();
  1262. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  1263. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  1264. }
  1265. // Check if the current class has some sub-classes
  1266. if (isset($aExtraParams['baseClass']))
  1267. {
  1268. $sRootClass = $aExtraParams['baseClass'];
  1269. }
  1270. else
  1271. {
  1272. $sRootClass = $sClassName;
  1273. }
  1274. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  1275. if (count($aSubClasses) > 0)
  1276. {
  1277. $aOptions = array();
  1278. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  1279. foreach($aSubClasses as $sSubclassName)
  1280. {
  1281. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  1282. }
  1283. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  1284. ksort($aOptions);
  1285. $sContext = $oAppContext->GetForLink();
  1286. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  1287. }
  1288. else
  1289. {
  1290. $sClassesCombo = MetaModel::GetName($sClassName);
  1291. }
  1292. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  1293. $sAction = (isset($aExtraParams['action'])) ? $aExtraParams['action'] : utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1294. $sHtml .= "<form id=\"fs_{$sSearchFormId}\" action=\"{$sAction}\">\n"; // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  1295. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  1296. $index = 0;
  1297. $sHtml .= "<p>\n";
  1298. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  1299. $aMapCriteria = array();
  1300. foreach($aFilterCriteria as $aCriteria)
  1301. {
  1302. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  1303. }
  1304. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  1305. $aConsts = $oSet->ListConstantFields(); // Some fields are constants based on the query/context
  1306. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  1307. foreach($aList as $sFilterCode)
  1308. {
  1309. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  1310. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  1311. $sFilterValue = isset($aConsts[$sClassAlias][$sFilterCode]) ? $aConsts[$sClassAlias][$sFilterCode] : '';
  1312. $sFilterValue = utils::ReadParam($sFilterCode, $sFilterValue, false, 'raw_data');
  1313. $sFilterOpCode = null; // Use the default 'loose' OpCode
  1314. if (empty($sFilterValue))
  1315. {
  1316. if (isset($aMapCriteria[$sFilterCode]))
  1317. {
  1318. if (count($aMapCriteria[$sFilterCode]) > 1)
  1319. {
  1320. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  1321. }
  1322. else
  1323. {
  1324. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  1325. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  1326. }
  1327. if ($sFilterCode != 'company')
  1328. {
  1329. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  1330. }
  1331. }
  1332. }
  1333. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFilterCode);
  1334. if ($oAttDef->IsExternalKey())
  1335. {
  1336. $sTargetClass = $oAttDef->GetTargetClass();
  1337. $oSearch = new DBObjectSearch($sTargetClass);
  1338. $oSearch->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true);
  1339. $oAllowedValues = new DBObjectSet($oSearch);
  1340. $iFieldSize = $oAttDef->GetMaxSize();
  1341. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1342. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;";
  1343. $aExtKeyParams = $aExtraParams;
  1344. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1345. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1346. $sHtml .= UIExtKeyWidget::DisplayFromAttCode($oPage, $sFilterCode, $sClassName, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sSearchFormId.'search_'.$sFilterCode, false, $sFilterCode, '', $aExtKeyParams, true);
  1347. }
  1348. else
  1349. {
  1350. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  1351. if (is_null($aAllowedValues))
  1352. {
  1353. // Any value is possible, display an input box
  1354. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"".htmlentities($sFilterValue, ENT_QUOTES, 'utf-8')."\"/>\n";
  1355. }
  1356. else
  1357. {
  1358. //Enum field, display a multi-select combo
  1359. $sValue = "<select class=\"multiselect\" size=\"1\" name=\"{$sFilterCode}[]\" multiple>\n";
  1360. $bMultiSelect = true;
  1361. //$sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  1362. asort($aAllowedValues);
  1363. foreach($aAllowedValues as $key => $value)
  1364. {
  1365. if (is_array($sFilterValue) && in_array($key, $sFilterValue))
  1366. {
  1367. $sSelected = ' selected';
  1368. }
  1369. else if ($sFilterValue == $key)
  1370. {
  1371. $sSelected = ' selected';
  1372. }
  1373. else
  1374. {
  1375. $sSelected = '';
  1376. }
  1377. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  1378. }
  1379. $sValue .= "</select>\n";
  1380. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  1381. }
  1382. }
  1383. unset($aExtraParams[$sFilterCode]);
  1384. // Finally, add a tooltip if one is defined for this attribute definition
  1385. $sTip = $oAttDef->GetHelpOnSmartSearch();
  1386. if (strlen($sTip) > 0)
  1387. {
  1388. $sTip = addslashes($sTip);
  1389. $sTip = str_replace(array("\n", "\r"), " ", $sTip);
  1390. // :input does represent in form visible input (INPUT, SELECT, TEXTAREA)
  1391. $oPage->add_ready_script("$('form#fs_$sSearchFormId :input[name={$sFilterCode}]').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  1392. }
  1393. $index++;
  1394. $sHtml .= '</span> ';
  1395. }
  1396. $sHtml .= "</p>\n";
  1397. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  1398. if (isset($aExtraParams['table_id']))
  1399. {
  1400. // Rename to avoid collisions...
  1401. $aExtraParams['_table_id_'] = $aExtraParams['table_id'];
  1402. unset($aExtraParams['table_id']);
  1403. }
  1404. foreach($aExtraParams as $sName => $sValue)
  1405. {
  1406. if (is_scalar($sValue))
  1407. {
  1408. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1409. }
  1410. }
  1411. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  1412. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1413. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  1414. $sHtml .= $oAppContext->GetForForm();
  1415. $sHtml .= "</form>\n";
  1416. if (!isset($aExtraParams['currentId']))
  1417. {
  1418. $sHtml .= "</div><!-- Simple search form -->\n";
  1419. }
  1420. if ($bMultiSelect)
  1421. {
  1422. $aOptions = array(
  1423. 'header' => true,
  1424. 'checkAllText' => Dict::S('UI:SearchValue:CheckAll'),
  1425. 'uncheckAllText' => Dict::S('UI:SearchValue:UncheckAll'),
  1426. 'noneSelectedText' => Dict::S('UI:SearchValue:Any'),
  1427. 'selectedText' => Dict::S('UI:SearchValue:NbSelected'),
  1428. 'selectedList' => 1,
  1429. );
  1430. $sJSOptions = json_encode($aOptions);
  1431. $oPage->add_ready_script("$('.multiselect').multiselect($sJSOptions);");
  1432. }
  1433. /*
  1434. // OQL query builder
  1435. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  1436. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  1437. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  1438. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  1439. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1440. $sSelectedClass = utils::ReadParam('oql_class', $sClassName, false, 'class');
  1441. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  1442. asort($aClasses);
  1443. foreach($aClasses as $sChildClass)
  1444. {
  1445. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  1446. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  1447. }
  1448. $sHtml .= "</select>&nbsp;</td><td>\n";
  1449. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  1450. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  1451. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1452. foreach($aExtraParams as $sName => $sValue)
  1453. {
  1454. if (is_scalar($sValue))
  1455. {
  1456. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1457. }
  1458. }
  1459. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  1460. $sHtml .= $oAppContext->GetForForm();
  1461. $sHtml .= "</table></form>\n";
  1462. $sHtml .= "</div><!-- OQL query form -->\n";
  1463. */
  1464. return $sHtml;
  1465. }
  1466. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  1467. {
  1468. static $iInputId = 0;
  1469. $sFieldPrefix = '';
  1470. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  1471. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  1472. if ($sDisplayValue == '')
  1473. {
  1474. $sDisplayValue = $value;
  1475. }
  1476. if (isset($aArgs[$sAttCode]) && empty($value))
  1477. {
  1478. // default value passed by the context (either the app context of the operation)
  1479. $value = $aArgs[$sAttCode];
  1480. }
  1481. if (!empty($iId))
  1482. {
  1483. $iInputId = $iId;
  1484. }
  1485. else
  1486. {
  1487. $iInputId = $oPage->GetUniqueId();
  1488. }
  1489. if (!$oAttDef->IsExternalField())
  1490. {
  1491. $bMandatory = 'false';
  1492. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1493. {
  1494. $bMandatory = 'true';
  1495. }
  1496. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1497. $sHelpText = $oAttDef->GetHelpOnEdition();
  1498. $aEventsList = array();
  1499. switch($oAttDef->GetEditClass())
  1500. {
  1501. case 'Date':
  1502. $aEventsList[] ='validate';
  1503. $aEventsList[] ='keyup';
  1504. $aEventsList[] ='change';
  1505. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1506. {
  1507. $sDisplayValue = date($oAttDef->GetDateFormat());
  1508. }
  1509. $sHTMLValue = "<input title=\"$sHelpText\" class=\"date-pick\" type=\"text\" size=\"12\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($sDisplayValue, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1510. break;
  1511. case 'DateTime':
  1512. $aEventsList[] ='validate';
  1513. $aEventsList[] ='keyup';
  1514. $aEventsList[] ='change';
  1515. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1516. {
  1517. $sDisplayValue = date($oAttDef->GetDateFormat());
  1518. }
  1519. $sHTMLValue = "<input title=\"$sHelpText\" class=\"datetime-pick\" type=\"text\" size=\"20\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($sDisplayValue, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1520. break;
  1521. case 'Duration':
  1522. $aEventsList[] ='validate';
  1523. $aEventsList[] ='change';
  1524. $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1525. $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1526. $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1527. $oPage->add_ready_script("$('#{$iId}_s').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1528. $aVal = AttributeDuration::SplitDuration($value);
  1529. $sDays = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"3\" name=\"attr_{$sFieldPrefix}{$sAttCode}[d]{$sNameSuffix}\" value=\"{$aVal['days']}\" id=\"{$iId}_d\"/>";
  1530. $sHours = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[h]{$sNameSuffix}\" value=\"{$aVal['hours']}\" id=\"{$iId}_h\"/>";
  1531. $sMinutes = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[m]{$sNameSuffix}\" value=\"{$aVal['minutes']}\" id=\"{$iId}_m\"/>";
  1532. $sSeconds = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[s]{$sNameSuffix}\" value=\"{$aVal['seconds']}\" id=\"{$iId}_s\"/>";
  1533. $sHidden = "<input type=\"hidden\" id=\"{$iId}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\"/>";
  1534. $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden."&nbsp;".$sValidationField;
  1535. $oPage->add_ready_script("$('#{$iId}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });");
  1536. break;
  1537. case 'Password':
  1538. $aEventsList[] ='validate';
  1539. $aEventsList[] ='keyup';
  1540. $aEventsList[] ='change';
  1541. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1542. break;
  1543. case 'OQLExpression':
  1544. case 'Text':
  1545. $aEventsList[] ='validate';
  1546. $aEventsList[] ='keyup';
  1547. $aEventsList[] ='change';
  1548. $sEditValue = $oAttDef->GetEditValue($value);
  1549. $aStyles = array();
  1550. $sStyle = '';
  1551. $sWidth = $oAttDef->GetWidth('width', '');
  1552. if (!empty($sWidth))
  1553. {
  1554. $aStyles[] = 'width:'.$sWidth;
  1555. }
  1556. $sHeight = $oAttDef->GetHeight('height', '');
  1557. if (!empty($sHeight))
  1558. {
  1559. $aStyles[] = 'height:'.$sHeight;
  1560. }
  1561. if (count($aStyles) > 0)
  1562. {
  1563. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1564. }
  1565. if ($oAttDef->GetEditClass() == 'OQLExpression')
  1566. {
  1567. $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId();
  1568. $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression=';
  1569. $sInitialUrl = $sBaseUrl.urlencode($sEditValue);
  1570. $sAdditionalStuff = "<a id=\"$sTestResId\" target=\"_blank\" href=\"$sInitialUrl\">".Dict::S('UI:Edit:TestQuery')."</a>";
  1571. $oPage->add_ready_script("$('#$iId').bind('change keyup', function(evt, sFormId) { $('#$sTestResId').attr('href', '$sBaseUrl'+encodeURIComponent($(this).val())); } );");
  1572. }
  1573. else
  1574. {
  1575. $sAdditionalStuff = "";
  1576. }
  1577. // Ok, the text area is drawn here
  1578. $sHTMLValue = "<table><tr><td><textarea class=\"resizable\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\" $sStyle>".htmlentities($sEditValue, ENT_QUOTES, 'UTF-8')."</textarea>$sAdditionalStuff</td><td>{$sValidationField}</td></tr></table>";
  1579. break;
  1580. case 'CaseLog':
  1581. $aStyles = array();
  1582. $sStyle = '';
  1583. $sWidth = $oAttDef->GetWidth('width', '');
  1584. if (!empty($sWidth))
  1585. {
  1586. $aStyles[] = 'width:'.$sWidth;
  1587. }
  1588. $sHeight = $oAttDef->GetHeight('height', '');
  1589. if (!empty($sHeight))
  1590. {
  1591. $aStyles[] = 'height:'.$sHeight;
  1592. }
  1593. if (count($aStyles) > 0)
  1594. {
  1595. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1596. }
  1597. $sHeader = '<div class="caselog_input_header">&nbsp;'.Dict::S('UI:CaseLogTypeYourTextHere').'</div>';
  1598. $sEditValue = $oAttDef->GetEditValue($value);
  1599. $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, array('AttributeText', 'RenderWikiHtml')) : '';
  1600. $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0;
  1601. $sHidden = "<input type=\"hidden\" id=\"{$iId}_count\" value=\"$iEntriesCount\"/>"; // To know how many entries the case log already contains
  1602. $sHTMLValue = "<div class=\"caselog\" $sStyle><table style=\"width:100%;\"><tr><td>$sHeader<textarea style=\"border:0;width:100%\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\">".htmlentities($sEditValue, ENT_QUOTES, 'UTF-8')."</textarea>$sPreviousLog</td><td>{$sValidationField}</td></tr></table>$sHidden</div>";
  1603. $oPage->add_ready_script("$('#$iId').bind('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId) } );"); // Custom validation function
  1604. break;
  1605. case 'HTML':
  1606. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationField, $value, $bMandatory);
  1607. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1608. break;
  1609. case 'LinkedSet':
  1610. if ($oAttDef->IsIndirect())
  1611. {
  1612. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed(), $aArgs);
  1613. }
  1614. else
  1615. {
  1616. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix, $aArgs);
  1617. }
  1618. $aEventsList[] ='validate';
  1619. $aEventsList[] ='change';
  1620. $oObj = isset($aArgs['this']) ? $aArgs['this'] : null;
  1621. $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj);
  1622. break;
  1623. case 'Document':
  1624. $aEventsList[] ='validate';
  1625. $aEventsList[] ='change';
  1626. $oDocument = $value; // Value is an ormDocument object
  1627. $sFileName = '';
  1628. if (is_object($oDocument))
  1629. {
  1630. $sFileName = $oDocument->GetFileName();
  1631. }
  1632. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1633. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1634. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[filename]\" type=\"hidden\" id=\"$iId\" \" value=\"".htmlentities($sFileName, ENT_QUOTES, 'UTF-8')."\"/>\n";
  1635. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1636. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[fcontents]\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1637. break;
  1638. case 'StopWatch':
  1639. $sHTMLValue = "The edition of a stopwatch is not allowed!!!";
  1640. break;
  1641. case 'List':
  1642. // Not editable for now...
  1643. $sHTMLValue = '';
  1644. break;
  1645. case 'One Way Password':
  1646. $aEventsList[] ='validate';
  1647. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1648. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1649. // Event list & validation is handled directly by the widget
  1650. break;
  1651. case 'ExtKey':
  1652. $aEventsList[] ='validate';
  1653. $aEventsList[] ='change';
  1654. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1655. $sFieldName = $sFieldPrefix.$sAttCode.$sNameSuffix;
  1656. $aExtKeyParams = $aArgs;
  1657. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1658. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1659. $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams);
  1660. $sHTMLValue .= "<!-- iFlags: $iFlags bMandatory: $bMandatory -->\n";
  1661. break;
  1662. case 'String':
  1663. default:
  1664. $aEventsList[] ='validate';
  1665. // #@# todo - add context information (depending on dimensions)
  1666. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1667. $iFieldSize = $oAttDef->GetMaxSize();
  1668. if ($aAllowedValues !== null)
  1669. {
  1670. // Discrete list of values, use a SELECT or RADIO buttons depending on the config
  1671. $sDisplayStyle = $oAttDef->GetDisplayStyle();
  1672. switch($sDisplayStyle)
  1673. {
  1674. case 'radio':
  1675. case 'radio_horizontal':
  1676. case 'radio_vertical':
  1677. $sHTMLValue = '';
  1678. $bVertical = ($sDisplayStyle != 'radio_horizontal');
  1679. $sHTMLValue = $oPage->GetRadioButtons($aAllowedValues, $value, $iId, "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", $bMandatory, $bVertical, $sValidationField);
  1680. $aEventsList[] ='change';
  1681. break;
  1682. case 'select':
  1683. default:
  1684. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1685. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1686. foreach($aAllowedValues as $key => $display_value)
  1687. {
  1688. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1689. {
  1690. // When there is only once choice, select it by default
  1691. $sSelected = ' selected';
  1692. }
  1693. else
  1694. {
  1695. $sSelected = ($value == $key) ? ' selected' : '';
  1696. }
  1697. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1698. }
  1699. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1700. $aEventsList[] ='change';
  1701. }
  1702. }
  1703. else
  1704. {
  1705. $sHTMLValue = "<input title=\"$sHelpText\" type=\"text\" size=\"30\" maxlength=\"$iFieldSize\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($sDisplayValue, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1706. $aEventsList[] ='keyup';
  1707. $aEventsList[] ='change';
  1708. }
  1709. break;
  1710. }
  1711. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1712. if (!empty($aEventsList))
  1713. {
  1714. $sNullValue = $oAttDef->GetNullValue();
  1715. if (!is_numeric($sNullValue))
  1716. {
  1717. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1718. }
  1719. $oPage->add_ready_script("$('#$iId').bind('".implode(' ', $aEventsList)."', function(evt, sFormId) { return ValidateField('$iId', '$sPattern', $bMandatory, sFormId, $sNullValue) } );\n"); // Bind to a custom event: validate
  1720. }
  1721. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1722. if (count($aDependencies) > 0)
  1723. {
  1724. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1725. }
  1726. }
  1727. return "<div>{$sHTMLValue}</div>";
  1728. }
  1729. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1730. {
  1731. self::$iGlobalFormId++;
  1732. $this->aFieldsMap = array();
  1733. $sPrefix = '';
  1734. if (isset($aExtraParams['formPrefix']))
  1735. {
  1736. $sPrefix = $aExtraParams['formPrefix'];
  1737. }
  1738. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  1739. $this->m_iFormId = $sPrefix.self::$iGlobalFormId;
  1740. $sClass = get_class($this);
  1741. $oAppContext = new ApplicationContext();
  1742. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1743. $iKey = $this->GetKey();
  1744. $aDetails = array();
  1745. $aFieldsMap = array();
  1746. if (!isset($aExtraParams['action']))
  1747. {
  1748. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1749. }
  1750. else
  1751. {
  1752. $sFormAction = $aExtraParams['action'];
  1753. }
  1754. // Custom label for the apply button ?
  1755. if (isset($aExtraParams['custom_button']))
  1756. {
  1757. $sApplyButton = $aExtraParams['custom_button'];
  1758. }
  1759. else if ($iKey > 0)
  1760. {
  1761. $sApplyButton = Dict::S('UI:Button:Apply');
  1762. }
  1763. else
  1764. {
  1765. $sApplyButton = Dict::S('UI:Button:Create');
  1766. }
  1767. // Custom operation for the form ?
  1768. if (isset($aExtraParams['custom_operation']))
  1769. {
  1770. $sOperation = $aExtraParams['custom_operation'];
  1771. }
  1772. else if ($iKey > 0)
  1773. {
  1774. $sOperation = 'apply_modify';
  1775. }
  1776. else
  1777. {
  1778. $sOperation = 'apply_new';
  1779. }
  1780. if ($iKey > 0)
  1781. {
  1782. // The object already exists in the database, it's a modification
  1783. $sButtons = "<input id=\"{$sPrefix}_id\" type=\"hidden\" name=\"id\" value=\"$iKey\">\n";
  1784. $sButtons .= "<input type=\"hidden\" name=\"operation\" value=\"{$sOperation}\">\n";
  1785. $sButtons .= "<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1786. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1787. }
  1788. else
  1789. {
  1790. // The object does not exist in the database it's a creation
  1791. $sButtons = "<input type=\"hidden\" name=\"operation\" value=\"$sOperation\">\n";
  1792. $sButtons .= "<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1793. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1794. }
  1795. $aTransitions = $this->EnumTransitions();
  1796. if (!isset($aExtraParams['custom_operation']) && count($aTransitions))
  1797. {
  1798. // transitions are displayed only for the standard new/modify actions, not for modify_all or any other case...
  1799. $oSetToCheckRights = DBObjectSet::FromObject($this);
  1800. $aStimuli = Metamodel::EnumStimuli($sClass);
  1801. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1802. {
  1803. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSetToCheckRights) : UR_ALLOWED_NO;
  1804. switch($iActionAllowed)
  1805. {
  1806. case UR_ALLOWED_YES:
  1807. $sButtons .= "<button type=\"submit\" name=\"next_action\" value=\"{$sStimulusCode}\" class=\"action\"><span>".$aStimuli[$sStimulusCode]->GetLabel()."</span></button>\n";
  1808. break;
  1809. default:
  1810. // Do nothing
  1811. }
  1812. }
  1813. }
  1814. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1815. $iTransactionId = isset($aExtraParams['transaction_id']) ? $aExtraParams['transaction_id'] : utils::GetNewTransactionId();
  1816. $oPage->SetTransactionId($iTransactionId);
  1817. $oPage->add("<form action=\"$sFormAction\" id=\"form_{$this->m_iFormId}\" enctype=\"multipart/form-data\" method=\"post\" onSubmit=\"return OnSubmit('form_{$this->m_iFormId}');\">\n");
  1818. $sStatesSelection = '';
  1819. if (!isset($aExtraParams['custom_operation']) && $this->IsNew())
  1820. {
  1821. $aInitialStates = MetaModel::EnumInitialStates($sClass);
  1822. //$aInitialStates = array('new' => 'foo', 'closed' => 'bar');
  1823. if (count($aInitialStates) > 1)
  1824. {
  1825. $sStatesSelection = Dict::Format('UI:Create_Class_InState', MetaModel::GetName($sClass)).'<select name="obj_state" class="state_select_'.$this->m_iFormId.'">';
  1826. foreach($aInitialStates as $sStateCode => $sStateData)
  1827. {
  1828. $sSelected = '';
  1829. if ($sStateCode == $this->GetState())
  1830. {
  1831. $sSelected = ' selected';
  1832. }
  1833. $sStatesSelection .= '<option value="'.$sStateCode.'"'.$sSelected.'>'.MetaModel::GetStateLabel($sClass, $sStateCode).'</option>';
  1834. }
  1835. $sStatesSelection .= '</select>';
  1836. $oPage->add_ready_script("$('.state_select_{$this->m_iFormId}').change( function() { oWizardHelper$sPrefix.ReloadObjectCreationForm('form_{$this->m_iFormId}', $(this).val()); } );");
  1837. }
  1838. }
  1839. $sConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage'));
  1840. $oPage->add_ready_script(
  1841. <<<EOF
  1842. $(window).unload(function() { return OnUnload('$iTransactionId') } );
  1843. window.onbeforeunload = function() {
  1844. if (!window.bInSubmit && !window.bInCancel)
  1845. {
  1846. return '$sConfirmationMessage';
  1847. }
  1848. // return nothing ! safer for IE
  1849. };
  1850. EOF
  1851. );
  1852. if ($sButtonsPosition != 'bottom')
  1853. {
  1854. // top or both, display the buttons here
  1855. $oPage->p($sStatesSelection);
  1856. $oPage->add($sButtons);
  1857. }
  1858. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1859. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1860. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1861. $aFieldsMap = $this->DisplayBareProperties($oPage, true, $sPrefix, $aExtraParams);
  1862. if ($iKey > 0)
  1863. {
  1864. $aFieldsMap['id'] = $sPrefix.'_id';
  1865. }
  1866. // Now display the relations, one tab per relation
  1867. if (!isset($aExtraParams['noRelations']))
  1868. {
  1869. $this->DisplayBareRelations($oPage, true); // Edit mode, will fill $this->aFieldsMap
  1870. $aFieldsMap = array_merge($aFieldsMap, $this->aFieldsMap);
  1871. }
  1872. $oPage->SetCurrentTab('');
  1873. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1874. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"$iTransactionId\">\n");
  1875. foreach($aExtraParams as $sName => $value)
  1876. {
  1877. if (is_scalar($value))
  1878. {
  1879. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1880. }
  1881. }
  1882. $oPage->add($oAppContext->GetForForm());
  1883. if ($sButtonsPosition != 'top')
  1884. {
  1885. // bottom or both: display the buttons here
  1886. $oPage->p($sStatesSelection);
  1887. $oPage->add($sButtons);
  1888. }
  1889. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1890. $sDefaultUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=cancel&'.$oAppContext->GetForLink();
  1891. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1892. $oPage->add("</form>\n");
  1893. $iFieldsCount = count($aFieldsMap);
  1894. $sJsonFieldsMap = json_encode($aFieldsMap);
  1895. $sState = $this->GetState();
  1896. $oPage->add_script(
  1897. <<<EOF
  1898. // Create the object once at the beginning of the page...
  1899. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix', '$sState');
  1900. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1901. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1902. EOF
  1903. );
  1904. $oPage->add_ready_script(
  1905. <<<EOF
  1906. oWizardHelper$sPrefix.UpdateWizard();
  1907. // Starts the validation when the page is ready
  1908. CheckFields('form_{$this->m_iFormId}', false);
  1909. EOF
  1910. );
  1911. }
  1912. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1913. {
  1914. $oAppContext = new ApplicationContext();
  1915. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1916. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1917. $aStates = MetaModel::EnumStates($sClass);
  1918. $sStatesSelection = '';
  1919. if ($oObjectToClone == null)
  1920. {
  1921. $oObj = MetaModel::NewObject($sClass);
  1922. if (!empty($sStateAttCode))
  1923. {
  1924. $sTargetState = MetaModel::GetDefaultState($sClass);
  1925. $oObj->Set($sStateAttCode, $sTargetState);
  1926. }
  1927. }
  1928. else
  1929. {
  1930. $oObj = clone $oObjectToClone;
  1931. }
  1932. // Pre-fill the object with default values, when there is only on possible choice
  1933. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  1934. $aArgs['this'] = $oObj;
  1935. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1936. // Order the fields based on their dependencies
  1937. $aDeps = array();
  1938. foreach($aDetailsList as $sAttCode)
  1939. {
  1940. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1941. }
  1942. $aList = self::OrderDependentFields($aDeps);
  1943. // Now fill-in the fields with default/supplied values
  1944. foreach($aList as $sAttCode)
  1945. {
  1946. if (isset($aArgs['default'][$sAttCode]))
  1947. {
  1948. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  1949. }
  1950. else
  1951. {
  1952. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1953. // If the field is mandatory, set it to the only possible value
  1954. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  1955. if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1956. {
  1957. if ($oAttDef->IsExternalKey())
  1958. {
  1959. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1960. if ($oAllowedValues->Count() == 1)
  1961. {
  1962. $oRemoteObj = $oAllowedValues->Fetch();
  1963. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1964. }
  1965. }
  1966. else
  1967. {
  1968. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1969. if (count($aAllowedValues) == 1)
  1970. {
  1971. $aValues = array_keys($aAllowedValues);
  1972. $oObj->Set($sAttCode, $aValues[0]);
  1973. }
  1974. }
  1975. }
  1976. }
  1977. }
  1978. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  1979. }
  1980. public static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  1981. {
  1982. //echo "<pre>ZList: ";
  1983. //print_r($aList);
  1984. //echo "</pre>\n";
  1985. $index = 0;
  1986. foreach($aList as $sKey => $value)
  1987. {
  1988. if (is_array($value))
  1989. {
  1990. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  1991. {
  1992. $sCode = $aMatches[1];
  1993. $sName = $aMatches[2];
  1994. switch($sCode)
  1995. {
  1996. case 'tab':
  1997. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  1998. if(!isset($aDetails[$sName]))
  1999. {
  2000. $aDetails[$sName] = array('col1' => array());
  2001. }
  2002. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  2003. break;
  2004. case 'fieldset':
  2005. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  2006. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  2007. {
  2008. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  2009. }
  2010. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  2011. break;
  2012. default:
  2013. case 'col':
  2014. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  2015. if(!isset($aDetails[$sCurrentTab][$sName]))
  2016. {
  2017. $aDetails[$sCurrentTab][$sName] = array();
  2018. }
  2019. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  2020. break;
  2021. }
  2022. }
  2023. }
  2024. else
  2025. {
  2026. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  2027. if (empty($sCurrentSet))
  2028. {
  2029. $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value;
  2030. }
  2031. else
  2032. {
  2033. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  2034. }
  2035. }
  2036. $index++;
  2037. }
  2038. return $aDetails;
  2039. }
  2040. static function FlattenZList($aList)
  2041. {
  2042. $aResult = array();
  2043. foreach($aList as $value)
  2044. {
  2045. if (!is_array($value))
  2046. {
  2047. $aResult[] = $value;
  2048. }
  2049. else
  2050. {
  2051. $aResult = array_merge($aResult,self::FlattenZList($value));
  2052. }
  2053. }
  2054. return $aResult;
  2055. }
  2056. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  2057. {
  2058. $retVal = null;
  2059. if ($this->IsNew())
  2060. {
  2061. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2062. }
  2063. else
  2064. {
  2065. $iFlags = $this->GetAttributeFlags($sAttCode);
  2066. }
  2067. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  2068. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  2069. {
  2070. // The field is visible in the current state of the object
  2071. if ($sStateAttCode == $sAttCode)
  2072. {
  2073. // Special display for the 'state' attribute itself
  2074. $sDisplayValue = $this->GetStateLabel();
  2075. }
  2076. else if ($oAttDef->GetEditClass() == 'Document')
  2077. {
  2078. $oDocument = $this->Get($sAttCode);
  2079. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2080. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2081. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDownloadLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2082. }
  2083. else
  2084. {
  2085. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2086. }
  2087. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  2088. }
  2089. return $retVal;
  2090. }
  2091. /**
  2092. * Displays a blob document *inline* (if possible, depending on the type of the document)
  2093. * @return string
  2094. */
  2095. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  2096. {
  2097. $oDoc = $this->Get($sAttCode);
  2098. $sClass = get_class($this);
  2099. $Id = $this->GetKey();
  2100. switch ($oDoc->GetMainMimeType())
  2101. {
  2102. case 'text':
  2103. case 'html':
  2104. $data = $oDoc->GetData();
  2105. switch($oDoc->GetMimeType())
  2106. {
  2107. case 'text/html':
  2108. case 'text/xml':
  2109. $oPage->add("<iframe id='preview_$sAttCode' src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" width=\"100%\" height=\"400\">Loading...</iframe>\n");
  2110. break;
  2111. default:
  2112. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true), ENT_QUOTES, 'UTF-8')."</pre>\n");
  2113. }
  2114. break;
  2115. case 'application':
  2116. switch($oDoc->GetMimeType())
  2117. {
  2118. case 'application/pdf':
  2119. $oPage->add("<iframe id='preview_$sAttCode' src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" width=\"100%\" height=\"400\">Loading...</iframe>\n");
  2120. break;
  2121. default:
  2122. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2123. }
  2124. break;
  2125. case 'image':
  2126. $oPage->add("<img src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  2127. break;
  2128. default:
  2129. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2130. }
  2131. }
  2132. // $m_highlightComparison[previous][new] => next value
  2133. protected static $m_highlightComparison = array(
  2134. HILIGHT_CLASS_CRITICAL => array(
  2135. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2136. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL,
  2137. HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL,
  2138. HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL,
  2139. ),
  2140. HILIGHT_CLASS_WARNING => array(
  2141. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2142. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2143. HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING,
  2144. HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING,
  2145. ),
  2146. HILIGHT_CLASS_OK => array(
  2147. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2148. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2149. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2150. HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK,
  2151. ),
  2152. HILIGHT_CLASS_NONE => array(
  2153. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2154. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2155. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2156. HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE,
  2157. ),
  2158. );
  2159. /**
  2160. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  2161. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  2162. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2163. * To Be overridden by derived classes
  2164. * @param void
  2165. * @return String The desired higlight class for the object/row
  2166. */
  2167. public function GetHilightClass()
  2168. {
  2169. // Possible return values are:
  2170. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2171. $current = HILIGHT_CLASS_NONE; // Not hilighted by default
  2172. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2173. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2174. {
  2175. $new = $oExtensionInstance->GetHilightClass($this);
  2176. @$current = self::$m_highlightComparison[$current][$new];
  2177. }
  2178. return $current;
  2179. }
  2180. /**
  2181. * Re-order the fields based on their inter-dependencies
  2182. * @params hash @aFields field_code => array_of_depencies
  2183. * @return array Ordered array of fields or throws an exception
  2184. */
  2185. public static function OrderDependentFields($aFields)
  2186. {
  2187. $bCircular = false;
  2188. $aResult = array();
  2189. $iCount = 0;
  2190. do
  2191. {
  2192. $bSet = false;
  2193. $iCount++;
  2194. foreach($aFields as $sFieldCode => $aDeps)
  2195. {
  2196. foreach($aDeps as $key => $sDependency)
  2197. {
  2198. if (in_array($sDependency, $aResult))
  2199. {
  2200. // Dependency is resolved, remove it
  2201. unset($aFields[$sFieldCode][$key]);
  2202. }
  2203. }
  2204. if (count($aFields[$sFieldCode]) == 0)
  2205. {
  2206. // No more pending depencies for this field, add it to the list
  2207. $aResult[] = $sFieldCode;
  2208. unset($aFields[$sFieldCode]);
  2209. $bSet = true;
  2210. }
  2211. }
  2212. }
  2213. while($bSet && (count($aFields) > 0));
  2214. if (count($aFields) > 0)
  2215. {
  2216. $sMessage = "Error: Circular dependencies between the fields (or field missing in ZList) ! <pre>".print_r($aFields, true)."</pre>";
  2217. throw(new Exception($sMessage));
  2218. }
  2219. return $aResult;
  2220. }
  2221. /**
  2222. * Get the list of actions to be displayed as 'shortcuts' (i.e buttons) instead of inside the Actions popup menu
  2223. * @param $sFinalClass string The actual class of the objects for which to display the menu
  2224. * @return Array the list of menu codes (i.e dictionary entries) that can be displayed as shortcuts next to the actions menu
  2225. */
  2226. public static function GetShortcutActions($sFinalClass)
  2227. {
  2228. $sShortcutActions = MetaModel::GetConfig()->Get('shortcut_actions');
  2229. $aShortcutActions = explode(',', $sShortcutActions);
  2230. return $aShortcutActions;
  2231. }
  2232. /**
  2233. * Maps the given context parameter name to the appropriate filter/search code for this class
  2234. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  2235. * @return string Filter code, i.e. 'customer_id'
  2236. */
  2237. public static function MapContextParam($sContextParam)
  2238. {
  2239. if ($sContextParam == 'menu')
  2240. {
  2241. return null;
  2242. }
  2243. else
  2244. {
  2245. return $sContextParam;
  2246. }
  2247. }
  2248. /**
  2249. * Updates the object from a flat array of values
  2250. * @param $aAttList array $aAttList array of attcode
  2251. * @param $aErrors array Returns information about slave attributes
  2252. * @param $sTargetState string Target state for which to evaluate the writeable attributes (=current state is empty)
  2253. * @return array of attcodes that can be used for writing on the current object
  2254. */
  2255. public function GetWriteableAttList($aAttList, &$aErrors, $sTargetState = '')
  2256. {
  2257. if (!is_array($aAttList))
  2258. {
  2259. $aAttList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2260. // Special case to process the case log, if any...
  2261. // WARNING: if you change this also check the functions DisplayModifyForm and DisplayCaseLog
  2262. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2263. {
  2264. if ($this->IsNew())
  2265. {
  2266. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2267. }
  2268. else
  2269. {
  2270. $aVoid = array();
  2271. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2272. }
  2273. if ($oAttDef instanceof AttributeCaseLog)
  2274. {
  2275. if (!($iFlags & (OPT_ATT_HIDDEN|OPT_ATT_SLAVE|OPT_ATT_READONLY)))
  2276. {
  2277. // The case log is editable, append it to the list of fields to retrieve
  2278. $aAttList[] = $sAttCode;
  2279. }
  2280. }
  2281. }
  2282. }
  2283. $aWriteableAttList = array();
  2284. foreach($aAttList as $sAttCode)
  2285. {
  2286. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2287. if ($this->IsNew())
  2288. {
  2289. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2290. }
  2291. else
  2292. {
  2293. $aVoid = array();
  2294. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2295. }
  2296. if ($oAttDef->IsWritable())
  2297. {
  2298. if ( $iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  2299. {
  2300. // Non-visible, or read-only attribute, do nothing
  2301. }
  2302. elseif($iFlags & OPT_ATT_SLAVE)
  2303. {
  2304. $aErrors[$sAttCode] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  2305. }
  2306. else
  2307. {
  2308. $aWriteableAttList[$sAttCode] = $oAttDef;
  2309. }
  2310. }
  2311. }
  2312. return $aWriteableAttList;
  2313. }
  2314. /**
  2315. * Updates the object from a flat array of values
  2316. * @param string $aValues array of attcode => scalar or array (N-N links)
  2317. * @return void
  2318. */
  2319. public function UpdateObjectFromArray($aValues)
  2320. {
  2321. foreach($aValues as $sAttCode => $value)
  2322. {
  2323. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2324. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  2325. {
  2326. $aLinks = $value;
  2327. $sLinkedClass = $oAttDef->GetLinkedClass();
  2328. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  2329. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2330. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  2331. if (is_array($aLinks))
  2332. {
  2333. foreach($aLinks as $id => $aData)
  2334. {
  2335. if (is_numeric($id))
  2336. {
  2337. if ($id < 0)
  2338. {
  2339. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  2340. $oLink = MetaModel::NewObject($sLinkedClass);
  2341. $oLink->Set($sExtKeyToRemote, -$id);
  2342. $oLink->Set($sExtKeyToMe, $this->GetKey());
  2343. }
  2344. else
  2345. {
  2346. // Existing link, potentially to be updated...
  2347. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  2348. }
  2349. // Now populate the attributes
  2350. foreach($aData as $sName => $value)
  2351. {
  2352. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  2353. {
  2354. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  2355. if ($oLinkAttDef->IsWritable())
  2356. {
  2357. $oLink->Set($sName, $value);
  2358. }
  2359. }
  2360. }
  2361. $oLinkedSet->AddObject($oLink);
  2362. }
  2363. }
  2364. }
  2365. $this->Set($sAttCode, $oLinkedSet);
  2366. }
  2367. elseif ($oAttDef->GetEditClass() == 'Document')
  2368. {
  2369. // There should be an uploaded file with the named attr_<attCode>
  2370. $oDocument = $value['fcontents'];
  2371. if (!$oDocument->IsEmpty())
  2372. {
  2373. // A new file has been uploaded
  2374. $this->Set($sAttCode, $oDocument);
  2375. }
  2376. }
  2377. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  2378. {
  2379. // Check if the password was typed/changed
  2380. $aPwdData = $value;
  2381. if (!is_null($aPwdData) && $aPwdData['changed'])
  2382. {
  2383. // The password has been changed or set
  2384. $this->Set($sAttCode, $aPwdData['value']);
  2385. }
  2386. }
  2387. elseif ($oAttDef->GetEditClass() == 'Duration')
  2388. {
  2389. $aDurationData = $value;
  2390. if (!is_array($aDurationData)) continue;
  2391. $iValue = (((24*$aDurationData['d'])+$aDurationData['h'])*60 +$aDurationData['m'])*60 + $aDurationData['s'];
  2392. $this->Set($sAttCode, $iValue);
  2393. $previousValue = $this->Get($sAttCode);
  2394. if ($previousValue !== $iValue)
  2395. {
  2396. $this->Set($sAttCode, $iValue);
  2397. }
  2398. }
  2399. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() &&
  2400. (($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE) || ($oAttDef->GetEditMode() == LINKSET_EDITMODE_ADDREMOVE)))
  2401. {
  2402. $oLinkset = $this->Get($sAttCode);
  2403. $sLinkedClass = $oLinkset->GetClass();
  2404. $aObjSet = array();
  2405. $oLinkset->Rewind();
  2406. $bModified = false;
  2407. while($oLink = $oLinkset->Fetch())
  2408. {
  2409. if (in_array($oLink->GetKey(), $value['to_be_deleted']))
  2410. {
  2411. // The link is to be deleted, don't copy it in the array
  2412. $bModified = true;
  2413. }
  2414. else
  2415. {
  2416. if (!array_key_exists('to_be_removed', $value) || !in_array($oLink->GetKey(), $value['to_be_removed']))
  2417. {
  2418. $aObjSet[] = $oLink;
  2419. }
  2420. }
  2421. }
  2422. if (array_key_exists('to_be_created', $value) && (count($value['to_be_created']) > 0))
  2423. {
  2424. // Now handle the links to be created
  2425. foreach($value['to_be_created'] as $aData)
  2426. {
  2427. $sSubClass = $aData['class'];
  2428. if ( ($sLinkedClass == $sSubClass) || (is_subclass_of($sSubClass, $sLinkedClass)) )
  2429. {
  2430. $aObjData = $aData['data'];
  2431. $oLink = new $sSubClass;
  2432. $oLink->UpdateObjectFromArray($aObjData);
  2433. $aObjSet[] = $oLink;
  2434. $bModified = true;
  2435. }
  2436. }
  2437. }
  2438. if (array_key_exists('to_be_added', $value) && (count($value['to_be_added']) > 0))
  2439. {
  2440. // Now handle the links to be added by making the remote object point to self
  2441. foreach($value['to_be_added'] as $iObjKey)
  2442. {
  2443. $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false);
  2444. if ($oLink)
  2445. {
  2446. $aObjSet[] = $oLink;
  2447. $bModified = true;
  2448. }
  2449. }
  2450. }
  2451. if (array_key_exists('to_be_removed', $value) && (count($value['to_be_removed']) > 0))
  2452. {
  2453. // Now handle the links to be removed by making the remote object point to nothing
  2454. // Keep them in the set (modified), DBWriteLinks will handle them
  2455. foreach($value['to_be_removed'] as $iObjKey)
  2456. {
  2457. $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false);
  2458. if ($oLink)
  2459. {
  2460. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2461. $oLink->Set($sExtKeyToMe, null);
  2462. $aObjSet[] = $oLink;
  2463. $bModified = true;
  2464. }
  2465. }
  2466. }
  2467. if ($bModified)
  2468. {
  2469. $oNewSet = DBObjectSet::FromArray($oLinkset->GetClass(), $aObjSet);
  2470. $this->Set($sAttCode, $oNewSet);
  2471. }
  2472. }
  2473. else
  2474. {
  2475. if (!is_null($value))
  2476. {
  2477. $aAttributes[$sAttCode] = trim($value);
  2478. $previousValue = $this->Get($sAttCode);
  2479. if ($previousValue !== $aAttributes[$sAttCode])
  2480. {
  2481. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  2482. }
  2483. }
  2484. }
  2485. }
  2486. }
  2487. /**
  2488. * Updates the object from the POSTed parameters (form)
  2489. */
  2490. public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $sTargetState = '')
  2491. {
  2492. if (is_null($aAttList))
  2493. {
  2494. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2495. }
  2496. $aValues = array();
  2497. foreach($aAttList as $sAttCode)
  2498. {
  2499. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2500. if ($oAttDef->GetEditClass() == 'Document')
  2501. {
  2502. $value = array('fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'));
  2503. }
  2504. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() &&
  2505. (($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE) || ($oAttDef->GetEditMode() == LINKSET_EDITMODE_ADDREMOVE)) )
  2506. {
  2507. $aRawToBeCreated = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbc", '{}', 'raw_data'), true);
  2508. $aToBeCreated = array();
  2509. foreach($aRawToBeCreated as $aData)
  2510. {
  2511. $sSubFormPrefix = $aData['formPrefix'];
  2512. $sObjClass = $aData['class'];
  2513. $aObjData = array();
  2514. foreach($aData as $sKey => $value)
  2515. {
  2516. if (preg_match("/^attr_$sSubFormPrefix(.*)$/", $sKey, $aMatches))
  2517. {
  2518. $aObjData[$aMatches[1]] = $value;
  2519. }
  2520. }
  2521. $aToBeCreated[] = array('class' => $sObjClass, 'data' => $aObjData);
  2522. }
  2523. $value = array('to_be_created' => $aToBeCreated,
  2524. 'to_be_deleted' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbd", '[]', 'raw_data'), true),
  2525. 'to_be_added' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tba", '[]', 'raw_data'), true),
  2526. 'to_be_removed' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbr", '[]', 'raw_data'), true) );
  2527. }
  2528. else
  2529. {
  2530. $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data');
  2531. }
  2532. if (!is_null($value))
  2533. {
  2534. $aValues[$sAttCode] = $value;
  2535. }
  2536. }
  2537. $aErrors = array();
  2538. $aFinalValues = array();
  2539. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2540. {
  2541. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2542. }
  2543. $this->UpdateObjectFromArray($aFinalValues);
  2544. // Invoke extensions after the update of the object from the form
  2545. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2546. {
  2547. $oExtensionInstance->OnFormSubmit($this, $sFormPrefix);
  2548. }
  2549. return $aErrors;
  2550. }
  2551. /**
  2552. * Updates the object from a given page argument
  2553. */
  2554. public function UpdateObjectFromArg($sArgName, $aAttList = null, $sTargetState = '')
  2555. {
  2556. if (is_null($aAttList))
  2557. {
  2558. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2559. }
  2560. $aRawValues = utils::ReadParam($sArgName, array(), '', 'raw_data');
  2561. $aValues = array();
  2562. foreach($aAttList as $sAttCode)
  2563. {
  2564. if (isset($aRawValues[$sAttCode]))
  2565. {
  2566. $aValues[$sAttCode] = $aRawValues[$sAttCode];
  2567. }
  2568. }
  2569. $aErrors = array();
  2570. $aFinalValues = array();
  2571. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2572. {
  2573. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2574. }
  2575. $this->UpdateObjectFromArray($aFinalValues);
  2576. return $aErrors;
  2577. }
  2578. public function DBInsertNoReload()
  2579. {
  2580. $res = parent::DBInsertNoReload();
  2581. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2582. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2583. {
  2584. $oExtensionInstance->OnDBInsert($this, self::GetCurrentChange());
  2585. }
  2586. return $res;
  2587. }
  2588. protected function DBCloneTracked_Internal($newKey = null)
  2589. {
  2590. $oNewObj = parent::DBCloneTracked_Internal($newKey);
  2591. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2592. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2593. {
  2594. $oExtensionInstance->OnDBInsert($oNewObj, self::GetCurrentChange());
  2595. }
  2596. return $oNewObj;
  2597. }
  2598. public function DBUpdate()
  2599. {
  2600. $res = parent::DBUpdate();
  2601. // Invoke extensions after the update (could be before)
  2602. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2603. {
  2604. $oExtensionInstance->OnDBUpdate($this, self::GetCurrentChange());
  2605. }
  2606. return $res;
  2607. }
  2608. protected static function BulkUpdateTracked_Internal(DBObjectSearch $oFilter, array $aValues)
  2609. {
  2610. // Todo - invoke the extension
  2611. return parent::BulkUpdateTracked_Internal($oFilter, $aValues);
  2612. }
  2613. protected function DBDeleteTracked_Internal(&$oDeletionPlan = null)
  2614. {
  2615. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2616. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2617. {
  2618. $oExtensionInstance->OnDBDelete($this, self::GetCurrentChange());
  2619. }
  2620. return parent::DBDeleteTracked_Internal($oDeletionPlan);
  2621. }
  2622. public function IsModified()
  2623. {
  2624. if (parent::IsModified())
  2625. {
  2626. return true;
  2627. }
  2628. // Plugins
  2629. //
  2630. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2631. {
  2632. if ($oExtensionInstance->OnIsModified($this))
  2633. {
  2634. return true;
  2635. }
  2636. }
  2637. return false;
  2638. }
  2639. public function DoCheckToWrite()
  2640. {
  2641. parent::DoCheckToWrite();
  2642. // Plugins
  2643. //
  2644. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2645. {
  2646. $aNewIssues = $oExtensionInstance->OnCheckToWrite($this);
  2647. if (count($aNewIssues) > 0)
  2648. {
  2649. $this->m_aCheckIssues = array_merge($this->m_aCheckIssues, $aNewIssues);
  2650. }
  2651. }
  2652. // User rights
  2653. //
  2654. $aChanges = $this->ListChanges();
  2655. if (count($aChanges) > 0)
  2656. {
  2657. $aForbiddenFields = array();
  2658. foreach ($this->ListChanges() as $sAttCode => $value)
  2659. {
  2660. $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute(get_class($this), $sAttCode, UR_ACTION_MODIFY, DBObjectSet::FromObject($this));
  2661. if (!$bUpdateAllowed)
  2662. {
  2663. $oAttCode = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2664. $aForbiddenFields[] = $oAttCode->GetLabel();
  2665. }
  2666. }
  2667. if (count($aForbiddenFields) > 0)
  2668. {
  2669. // Security issue
  2670. $this->m_bSecurityIssue = true;
  2671. $this->m_aCheckIssues[] = Dict::Format('UI:Delete:NotAllowedToUpdate_Fields',implode(', ', $aForbiddenFields));
  2672. }
  2673. }
  2674. }
  2675. protected function DoCheckToDelete(&$oDeletionPlan)
  2676. {
  2677. parent::DoCheckToDelete($oDeletionPlan);
  2678. // Plugins
  2679. //
  2680. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2681. {
  2682. $aNewIssues = $oExtensionInstance->OnCheckToDelete($this);
  2683. if (count($aNewIssues) > 0)
  2684. {
  2685. $this->m_aDeleteIssues = array_merge($this->m_aDeleteIssues, $aNewIssues);
  2686. }
  2687. }
  2688. // User rights
  2689. //
  2690. $bDeleteAllowed = UserRights::IsActionAllowed(get_class($this), UR_ACTION_DELETE, DBObjectSet::FromObject($this));
  2691. if (!$bDeleteAllowed)
  2692. {
  2693. // Security issue
  2694. $this->m_bSecurityIssue = true;
  2695. $this->m_aDeleteIssues[] = Dict::S('UI:Delete:NotAllowedToDelete');
  2696. }
  2697. }
  2698. /**
  2699. * Special display where the case log uses the whole "screen" at the bottom of the "Properties" tab
  2700. */
  2701. public function DisplayCaseLog(WebPage $oPage, $sAttCode, $sComment = '', $sPrefix = '', $bEditMode = false)
  2702. {
  2703. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  2704. $sClass = get_class($this);
  2705. if ($this->IsNew())
  2706. {
  2707. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2708. }
  2709. else
  2710. {
  2711. $iFlags = $this->GetAttributeFlags($sAttCode);
  2712. }
  2713. if ( $iFlags & OPT_ATT_HIDDEN)
  2714. {
  2715. // The case log is hidden do nothing
  2716. }
  2717. else
  2718. {
  2719. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2720. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  2721. if ((!$bEditMode) || ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE)))
  2722. {
  2723. // Check if the attribute is not read-only because of a synchro...
  2724. $aReasons = array();
  2725. $sSynchroIcon = '';
  2726. if ($iFlags & OPT_ATT_SLAVE)
  2727. {
  2728. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  2729. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  2730. $sTip = '';
  2731. foreach($aReasons as $aRow)
  2732. {
  2733. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  2734. }
  2735. $sTip = addslashes($sTip);
  2736. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  2737. }
  2738. // Attribute is read-only
  2739. $sHTMLValue = $this->GetAsHTML($sAttCode);
  2740. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>';
  2741. $aFieldsMap[$sAttCode] = $sInputId;
  2742. $sComment .= $sSynchroIcon;
  2743. }
  2744. else
  2745. {
  2746. $sValue = $this->Get($sAttCode);
  2747. $sDisplayValue = $this->GetEditValue($sAttCode);
  2748. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  2749. $sHTMLValue = '';
  2750. if ($sComment != '')
  2751. {
  2752. $sHTMLValue = '<span>'.$sComment.'</span><br/>';
  2753. }
  2754. $sHTMLValue .= "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  2755. $aFieldsMap[$sAttCode] = $sInputId;
  2756. }
  2757. //$aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  2758. $oPage->add('<fieldset><legend>'.$oAttDef->GetLabel().'</legend>');
  2759. $oPage->add($sHTMLValue);
  2760. $oPage->add('</fieldset>');
  2761. }
  2762. }
  2763. public function GetExpectedAttributes($sCurrentState, $sStimulus, $bOnlyNewOnes)
  2764. {
  2765. $aTransitions = $this->EnumTransitions();
  2766. $aStimuli = MetaModel::EnumStimuli(get_class($this));
  2767. if (!isset($aTransitions[$sStimulus]))
  2768. {
  2769. // Invalid stimulus
  2770. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  2771. }
  2772. $aTransition = $aTransitions[$sStimulus];
  2773. $sTargetState = $aTransition['target_state'];
  2774. $aTargetStates = MetaModel::EnumStates(get_class($this));
  2775. $aTargetState = $aTargetStates[$sTargetState];
  2776. $aCurrentState = $aTargetStates[$this->GetState()];
  2777. $aExpectedAttributes = $aTargetState['attribute_list'];
  2778. $aCurrentAttributes = $aCurrentState['attribute_list'];
  2779. $aComputedAttributes = array();
  2780. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  2781. {
  2782. if (!array_key_exists($sAttCode, $aCurrentAttributes))
  2783. {
  2784. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2785. }
  2786. else
  2787. {
  2788. if ( !($aCurrentAttributes[$sAttCode] & (OPT_ATT_HIDDEN|OPT_ATT_READONLY)) )
  2789. {
  2790. $iExpectCode = $iExpectCode & ~(OPT_ATT_MUSTPROMPT|OPT_ATT_MUSTCHANGE); // Already prompted/changed, reset the flags
  2791. }
  2792. //TODO: better check if the attribute is not *null*
  2793. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($this->Get($sAttCode) != ''))
  2794. {
  2795. $iExpectCode = $iExpectCode & ~(OPT_ATT_MANDATORY); // If the attribute is present, then no need to request its presence
  2796. }
  2797. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2798. }
  2799. $aComputedAttributes[$sAttCode] = $aComputedAttributes[$sAttCode] & ~(OPT_ATT_READONLY|OPT_ATT_HIDDEN); // Don't care about this form now
  2800. if ($aComputedAttributes[$sAttCode] == 0)
  2801. {
  2802. unset($aComputedAttributes[$sAttCode]);
  2803. }
  2804. }
  2805. return $aComputedAttributes;
  2806. }
  2807. /**
  2808. * Display a form for modifying several objects at once
  2809. * The form will be submitted to the current page, with the specified additional values
  2810. */
  2811. public static function DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, $sCustomOperation, $sCancelUrl, $aExcludeAttributes = array(), $aContextData = array())
  2812. {
  2813. if (count($aSelectedObj) > 0)
  2814. {
  2815. $iAllowedCount = count($aSelectedObj);
  2816. $sSelectedObj = implode(',', $aSelectedObj);
  2817. $sOQL = "SELECT $sClass WHERE id IN (".$sSelectedObj.")";
  2818. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2819. // Compute the distribution of the values for each field to determine which of the "scalar" fields are homogenous
  2820. $aList = MetaModel::ListAttributeDefs($sClass);
  2821. $aValues = array();
  2822. foreach($aList as $sAttCode => $oAttDef)
  2823. {
  2824. if ($oAttDef->IsScalar())
  2825. {
  2826. $aValues[$sAttCode] = array();
  2827. }
  2828. }
  2829. while($oObj = $oSet->Fetch())
  2830. {
  2831. foreach($aList as $sAttCode => $oAttDef)
  2832. {
  2833. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  2834. {
  2835. $currValue = $oObj->Get($sAttCode);
  2836. if ($oAttDef instanceof AttributeCaseLog)
  2837. {
  2838. $currValue = ' '; // Don't put an empty string, in case the field would be considered as mandatory...
  2839. }
  2840. if (is_object($currValue)) continue; // Skip non scalar values...
  2841. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  2842. {
  2843. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  2844. }
  2845. else
  2846. {
  2847. $aValues[$sAttCode][$currValue]['count']++;
  2848. }
  2849. }
  2850. }
  2851. }
  2852. // Now create an object that has values for the homogenous values only
  2853. $oDummyObj = new $sClass(); // @@ What if the class is abstract ?
  2854. $aComments = array();
  2855. function MyComparison($a, $b) // Sort descending
  2856. {
  2857. if ($a['count'] == $b['count'])
  2858. {
  2859. return 0;
  2860. }
  2861. return ($a['count'] > $b['count']) ? -1 : 1;
  2862. }
  2863. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  2864. $sReadyScript = '';
  2865. $aDependsOn = array();
  2866. $sFormPrefix = '2_';
  2867. foreach($aList as $sAttCode => $oAttDef)
  2868. {
  2869. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  2870. if (count($aPrerequisites) > 0)
  2871. {
  2872. // When 'enabling' a field, all its prerequisites must be enabled too
  2873. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
  2874. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  2875. }
  2876. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  2877. if (count($aDependents) > 0)
  2878. {
  2879. // When 'disabling' a field, all its dependent fields must be disabled too
  2880. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
  2881. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  2882. }
  2883. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  2884. {
  2885. if ($oAttDef->GetEditClass() == 'One Way Password')
  2886. {
  2887. $sTip = "Unknown values";
  2888. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  2889. $oDummyObj->Set($sAttCode, null);
  2890. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2891. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'"> ? </div>';
  2892. $sReadyScript .= 'ToogleField(false, \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  2893. }
  2894. else
  2895. {
  2896. $iCount = count($aValues[$sAttCode]);
  2897. if ($iCount == 1)
  2898. {
  2899. // Homogenous value
  2900. reset($aValues[$sAttCode]);
  2901. $aKeys = array_keys($aValues[$sAttCode]);
  2902. $currValue = $aKeys[0]; // The only value is the first key
  2903. //echo "<p>current value for $sAttCode : $currValue</p>";
  2904. $oDummyObj->Set($sAttCode, $currValue);
  2905. $aComments[$sAttCode] = '<input type="checkbox" checked id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2906. $aComments[$sAttCode] .= '<div class="mono_value">1</div>';
  2907. }
  2908. else
  2909. {
  2910. // Non-homogenous value
  2911. $aMultiValues = $aValues[$sAttCode];
  2912. uasort($aMultiValues, 'MyComparison');
  2913. $iMaxCount = 5;
  2914. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."</b><ul>";
  2915. $index = 0;
  2916. foreach($aMultiValues as $sCurrValue => $aVal)
  2917. {
  2918. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  2919. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  2920. $index++;
  2921. if ($iMaxCount == $index)
  2922. {
  2923. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aMultiValues) - $iMaxCount)."</li>";
  2924. break;
  2925. }
  2926. }
  2927. $sTip .= "</ul></p>";
  2928. $sTip = addslashes($sTip);
  2929. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  2930. $oDummyObj->Set($sAttCode, null);
  2931. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2932. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.$iCount.'</div>';
  2933. }
  2934. $sReadyScript .= 'ToogleField('.(($iCount == 1) ? 'true': 'false').', \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  2935. }
  2936. }
  2937. }
  2938. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  2939. if (($sStateAttCode != '') && ($oDummyObj->GetState() == ''))
  2940. {
  2941. // Hmmm, it's not gonna work like this ! Set a default value for the "state"
  2942. // Maybe we should use the "state" that is the most common among the objects...
  2943. $aMultiValues = $aValues[$sStateAttCode];
  2944. uasort($aMultiValues, 'MyComparison');
  2945. foreach($aMultiValues as $sCurrValue => $aVal)
  2946. {
  2947. $oDummyObj->Set($sStateAttCode, $sCurrValue);
  2948. break;
  2949. }
  2950. //$oStateAtt = MetaModel::GetAttributeDef($sClass, $sStateAttCode);
  2951. //$oDummyObj->Set($sStateAttCode, $oStateAtt->GetDefaultValue());
  2952. }
  2953. $oP->add("<div class=\"page_header\">\n");
  2954. $oP->add("<h1>".$oDummyObj->GetIcon()."&nbsp;".Dict::Format('UI:Modify_M_ObjectsOf_Class_OutOf_N', $iAllowedCount, $sClass, $iAllowedCount)."</h1>\n");
  2955. $oP->add("</div>\n");
  2956. $oP->add("<div class=\"wizContainer\">\n");
  2957. $sDisableFields = json_encode($aExcludeAttributes);
  2958. $aParams = array
  2959. (
  2960. 'fieldsComments' => $aComments,
  2961. 'noRelations' => true,
  2962. 'custom_operation' => $sCustomOperation,
  2963. 'custom_button' => Dict::S('UI:Button:PreviewModifications'),
  2964. 'selectObj' => $sSelectedObj,
  2965. 'preview_mode' => true,
  2966. 'disabled_fields' => $sDisableFields,
  2967. 'disable_plugins' => true
  2968. );
  2969. $aParams = $aParams + $aContextData; // merge keeping associations
  2970. $oDummyObj->DisplayModifyForm($oP, $aParams);
  2971. $oP->add("</div>\n");
  2972. $oP->add_ready_script($sReadyScript);
  2973. $oP->add_ready_script(
  2974. <<<EOF
  2975. $('.wizContainer button.cancel').unbind('click');
  2976. $('.wizContainer button.cancel').click( function() { window.location.href = '$sCancelUrl'; } );
  2977. EOF
  2978. );
  2979. } // Else no object selected ???
  2980. else
  2981. {
  2982. $oP->p("No object selected !, nothing to do");
  2983. }
  2984. }
  2985. /**
  2986. * Process the reply made from a form built with DisplayBulkModifyForm
  2987. */
  2988. public static function DoBulkModify($oP, $sClass, $aSelectedObj, $sCustomOperation, $bPreview, $sCancelUrl, $aContextData = array())
  2989. {
  2990. $aHeaders = array(
  2991. 'form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')),
  2992. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  2993. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  2994. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  2995. );
  2996. $aRows = array();
  2997. $oP->add("<div class=\"page_header\">\n");
  2998. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), MetaModel::GetName($sClass))."</h1>\n");
  2999. $oP->add("</div>\n");
  3000. $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass));
  3001. if (!$bPreview)
  3002. {
  3003. // Not in preview mode, do the update for real
  3004. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  3005. if (!utils::IsTransactionValid($sTransactionId, false))
  3006. {
  3007. throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  3008. }
  3009. utils::RemoveTransaction($sTransactionId);
  3010. }
  3011. $iPreviousTimeLimit = ini_get('max_execution_time');
  3012. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  3013. foreach($aSelectedObj as $iId)
  3014. {
  3015. set_time_limit($iLoopTimeLimit);
  3016. $oObj = MetaModel::GetObject($sClass, $iId);
  3017. $aErrors = $oObj->UpdateObjectFromPostedForm('');
  3018. $bResult = (count($aErrors) == 0);
  3019. if ($bResult)
  3020. {
  3021. list($bResult, $aErrors) = $oObj->CheckToWrite(true /* Enforce Read-only fields */);
  3022. }
  3023. if ($bPreview)
  3024. {
  3025. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError');
  3026. }
  3027. else
  3028. {
  3029. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  3030. }
  3031. $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL;
  3032. $sChecked = $bResult ? 'checked' : '';
  3033. $sDisabled = $bResult ? '' : 'disabled';
  3034. $aRows[] = array(
  3035. 'form::select' => "<input type=\"checkbox\" class=\"selectList\" $sChecked $sDisabled\"></input>",
  3036. 'object' => $oObj->GetHyperlink(),
  3037. 'status' => $sStatus,
  3038. 'errors' => '<p>'.($bResult ? '': implode('</p><p>', $aErrors)).'</p>',
  3039. '@class' => $sCSSClass,
  3040. );
  3041. if ($bResult && (!$bPreview))
  3042. {
  3043. $oObj->DBUpdate();
  3044. }
  3045. }
  3046. set_time_limit($iPreviousTimeLimit);
  3047. $oP->Table($aHeaders, $aRows);
  3048. if ($bPreview)
  3049. {
  3050. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  3051. // Form to submit:
  3052. $oP->add("<form method=\"post\" action=\"$sFormAction\" enctype=\"multipart/form-data\">\n");
  3053. $aDefaults = utils::ReadParam('default', array());
  3054. $oAppContext = new ApplicationContext();
  3055. $oP->add($oAppContext->GetForForm());
  3056. foreach ($aContextData as $sKey => $value)
  3057. {
  3058. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  3059. }
  3060. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  3061. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  3062. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n");
  3063. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  3064. $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='$sCancelUrl'\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  3065. $oP->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:ModifyAll')."</span></button>\n");
  3066. foreach($_POST as $sKey => $value)
  3067. {
  3068. if (preg_match('/attr_(.+)/', $sKey, $aMatches))
  3069. {
  3070. // Beware: some values (like durations) are passed as arrays
  3071. if (is_array($value))
  3072. {
  3073. foreach($value as $vKey => $vValue)
  3074. {
  3075. $oP->add("<input type=\"hidden\" name=\"{$sKey}[$vKey]\" value=\"".htmlentities($vValue, ENT_QUOTES, 'UTF-8')."\">\n");
  3076. }
  3077. }
  3078. else
  3079. {
  3080. $oP->add("<input type=\"hidden\" name=\"$sKey\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\">\n");
  3081. }
  3082. }
  3083. }
  3084. $oP->add("</form>\n");
  3085. }
  3086. else
  3087. {
  3088. $oP->add("<button type=\"button\" onClick=\"window.location.href='$sCancelUrl'\" class=\"action\"><span>".Dict::S('UI:Button:Done')."</span></button>\n");
  3089. }
  3090. }
  3091. /**
  3092. * Perform all the needed checks to delete one (or more) objects
  3093. */
  3094. public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = array())
  3095. {
  3096. $oDeletionPlan = new DeletionPlan();
  3097. foreach($aObjects as $oObj)
  3098. {
  3099. if ($bPreview)
  3100. {
  3101. $oObj->CheckToDelete($oDeletionPlan);
  3102. }
  3103. else
  3104. {
  3105. $oObj->DBDeleteTracked(CMDBObject::GetCurrentChange(), null, $oDeletionPlan);
  3106. }
  3107. }
  3108. if ($bPreview)
  3109. {
  3110. if (count($aObjects) == 1)
  3111. {
  3112. $oObj = $aObjects[0];
  3113. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName())."</h1>\n");
  3114. }
  3115. else
  3116. {
  3117. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3118. }
  3119. // Explain what should be done
  3120. //
  3121. $aDisplayData = array();
  3122. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3123. {
  3124. foreach ($aDeletes as $iId => $aData)
  3125. {
  3126. $oToDelete = $aData['to_delete'];
  3127. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  3128. if (array_key_exists('issue', $aData))
  3129. {
  3130. if ($bAutoDel)
  3131. {
  3132. if (isset($aData['requested_explicitely']))
  3133. {
  3134. $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']);
  3135. }
  3136. else
  3137. {
  3138. $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']);
  3139. }
  3140. }
  3141. else
  3142. {
  3143. $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']);
  3144. }
  3145. }
  3146. else
  3147. {
  3148. if ($bAutoDel)
  3149. {
  3150. if (isset($aData['requested_explicitely']))
  3151. {
  3152. $sConsequence = ''; // not applicable
  3153. }
  3154. else
  3155. {
  3156. $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically');
  3157. }
  3158. }
  3159. else
  3160. {
  3161. $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually');
  3162. }
  3163. }
  3164. $aDisplayData[] = array(
  3165. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3166. 'object' => $oToDelete->GetHyperLink(),
  3167. 'consequence' => $sConsequence,
  3168. );
  3169. }
  3170. }
  3171. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  3172. {
  3173. foreach ($aToUpdate as $iId => $aData)
  3174. {
  3175. $oToUpdate = $aData['to_reset'];
  3176. if (array_key_exists('issue', $aData))
  3177. {
  3178. $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']);
  3179. }
  3180. else
  3181. {
  3182. $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']);
  3183. }
  3184. $aDisplayData[] = array(
  3185. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3186. 'object' => $oToUpdate->GetHyperLink(),
  3187. 'consequence' => $sConsequence,
  3188. );
  3189. }
  3190. }
  3191. $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects);
  3192. if ($iImpactedIndirectly > 0)
  3193. {
  3194. if (count($aObjects) == 1)
  3195. {
  3196. $oObj = $aObjects[0];
  3197. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName()));
  3198. }
  3199. else
  3200. {
  3201. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly));
  3202. }
  3203. $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'));
  3204. }
  3205. if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper())
  3206. {
  3207. $aDisplayConfig = array();
  3208. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3209. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3210. $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'));
  3211. $oP->table($aDisplayConfig, $aDisplayData);
  3212. }
  3213. if ($oDeletionPlan->FoundStopper())
  3214. {
  3215. if ($oDeletionPlan->FoundSecurityIssue())
  3216. {
  3217. $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed'));
  3218. }
  3219. elseif ($oDeletionPlan->FoundManualOperation())
  3220. {
  3221. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3222. }
  3223. else // $bFoundManualOp
  3224. {
  3225. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3226. }
  3227. $oAppContext = new ApplicationContext();
  3228. $oP->add("<form method=\"post\">\n");
  3229. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  3230. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3231. $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3232. $oP->add($oAppContext->GetForForm());
  3233. $oP->add("</form>\n");
  3234. }
  3235. else
  3236. {
  3237. if (count($aObjects) == 1)
  3238. {
  3239. $oObj = $aObjects[0];
  3240. $id = $oObj->GetKey();
  3241. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()).'</h1>');
  3242. }
  3243. else
  3244. {
  3245. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)).'</h1>');
  3246. }
  3247. foreach($aObjects as $oObj)
  3248. {
  3249. $aKeys[] = $oObj->GetKey();
  3250. }
  3251. $oFilter = new DBObjectSearch($sClass);
  3252. $oFilter->AddCondition('id', $aKeys, 'IN');
  3253. $oSet = new CMDBobjectSet($oFilter);
  3254. $oP->add('<div id="0">');
  3255. CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false));
  3256. $oP->add("</div>\n");
  3257. $oP->add("<form method=\"post\">\n");
  3258. foreach ($aContextData as $sKey => $value)
  3259. {
  3260. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  3261. }
  3262. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  3263. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  3264. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  3265. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  3266. foreach($aObjects as $oObj)
  3267. {
  3268. $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\">\n");
  3269. }
  3270. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3271. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3272. $oAppContext = new ApplicationContext();
  3273. $oP->add($oAppContext->GetForForm());
  3274. $oP->add("</form>\n");
  3275. }
  3276. }
  3277. else // if ($bPreview)...
  3278. {
  3279. // Execute the deletion
  3280. //
  3281. if (count($aObjects) == 1)
  3282. {
  3283. $oObj = $aObjects[0];
  3284. $oP->add("<h1>".Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName())."</h1>\n");
  3285. }
  3286. else
  3287. {
  3288. $oP->add("<h1>".Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3289. }
  3290. // Security - do not allow the user to force a forbidden delete by the mean of page arguments...
  3291. if ($oDeletionPlan->FoundSecurityIssue())
  3292. {
  3293. throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete'));
  3294. }
  3295. if ($oDeletionPlan->FoundManualOperation())
  3296. {
  3297. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded'));
  3298. }
  3299. if ($oDeletionPlan->FoundManualDelete())
  3300. {
  3301. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies'));
  3302. }
  3303. // Report deletions
  3304. //
  3305. $aDisplayData = array();
  3306. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3307. {
  3308. foreach ($aDeletes as $iId => $aData)
  3309. {
  3310. $oToDelete = $aData['to_delete'];
  3311. if (isset($aData['requested_explicitely']))
  3312. {
  3313. $sMessage = Dict::S('UI:Delete:Deleted');
  3314. }
  3315. else
  3316. {
  3317. $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted');
  3318. }
  3319. $aDisplayData[] = array(
  3320. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3321. 'object' => $oToDelete->GetName(),
  3322. 'consequence' => $sMessage,
  3323. );
  3324. }
  3325. }
  3326. // Report updates
  3327. //
  3328. foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate)
  3329. {
  3330. foreach ($aToUpdate as $iId => $aData)
  3331. {
  3332. $oToUpdate = $aData['to_reset'];
  3333. $aDisplayData[] = array(
  3334. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3335. 'object' => $oToUpdate->GetHyperLink(),
  3336. 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']),
  3337. );
  3338. }
  3339. }
  3340. // Report automatic jobs
  3341. //
  3342. if ($oDeletionPlan->GetTargetCount() > 0)
  3343. {
  3344. if (count($aObjects) == 1)
  3345. {
  3346. $oObj = $aObjects[0];
  3347. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()));
  3348. }
  3349. else
  3350. {
  3351. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)));
  3352. }
  3353. $aDisplayConfig = array();
  3354. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3355. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3356. $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+'));
  3357. $oP->table($aDisplayConfig, $aDisplayData);
  3358. }
  3359. }
  3360. }
  3361. }
  3362. ?>