cmdbabstract.class.inc.php 167 KB

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