cmdbabstract.class.inc.php 136 KB

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