cmdbabstract.class.inc.php 160 KB

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