cmdbabstract.class.inc.php 159 KB

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