cmdbabstract.class.inc.php 151 KB

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