cmdbabstract.class.inc.php 163 KB

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