cmdbabstract.class.inc.php 151 KB

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