cmdbabstract.class.inc.php 155 KB

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