cmdbabstract.class.inc.php 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735
  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(), $sCharset = 'UTF-8')
  872. {
  873. $oPage->add(self::GetSetAsCSV($oSet, $aParams, $sCharset));
  874. }
  875. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array(), $sCharset = 'UTF-8')
  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. $sCSVValue = $oAttDef->GetAsCSV($value, $sSeparator, $sTextQualifier, $oObj, $bLocalize);
  987. $aRow[] = iconv('UTF-8', $sCharset.'//IGNORE//TRANSLIT', $sCSVValue);
  988. }
  989. }
  990. }
  991. $sHtml .= implode($sSeparator, $aRow)."\n";
  992. }
  993. return $sHtml;
  994. }
  995. static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  996. {
  997. $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams));
  998. }
  999. /**
  1000. * Spreadsheet output: designed for end users doing some reporting
  1001. * Then the ids are excluded and replaced by the corresponding friendlyname
  1002. */
  1003. static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array())
  1004. {
  1005. $aFields = null;
  1006. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  1007. {
  1008. $aFields = explode(',', $aParams['fields']);
  1009. }
  1010. $bFieldsAdvanced = false;
  1011. if (isset($aParams['fields_advanced']))
  1012. {
  1013. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  1014. }
  1015. $bLocalize = true;
  1016. if (isset($aParams['localize_values']))
  1017. {
  1018. $bLocalize = (bool) $aParams['localize_values'];
  1019. }
  1020. $aList = array();
  1021. $oAppContext = new ApplicationContext();
  1022. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1023. $aAuthorizedClasses = array();
  1024. foreach($aClasses as $sAlias => $sClassName)
  1025. {
  1026. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1027. {
  1028. $aAuthorizedClasses[$sAlias] = $sClassName;
  1029. }
  1030. }
  1031. $aAttribs = array();
  1032. $aHeader = array();
  1033. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1034. {
  1035. $aList[$sAlias] = array();
  1036. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  1037. {
  1038. if (is_null($aFields) || (count($aFields) == 0))
  1039. {
  1040. // Standard list of attributes (no link sets)
  1041. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  1042. {
  1043. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  1044. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  1045. if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  1046. {
  1047. $sRemoteClass = $oAttDef->GetTargetClass();
  1048. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  1049. {
  1050. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  1051. }
  1052. }
  1053. }
  1054. }
  1055. else
  1056. {
  1057. // User defined list of attributes
  1058. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  1059. {
  1060. $aList[$sAlias][$sAttCode] = $oAttDef;
  1061. }
  1062. }
  1063. }
  1064. // Replace external key by the corresponding friendly name (if not already in the list)
  1065. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1066. {
  1067. if ($oAttDef->IsExternalKey())
  1068. {
  1069. unset($aList[$sAlias][$sAttCode]);
  1070. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1071. if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode))
  1072. {
  1073. $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode);
  1074. $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt;
  1075. }
  1076. }
  1077. }
  1078. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1079. {
  1080. $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx;
  1081. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1082. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1083. {
  1084. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  1085. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  1086. }
  1087. else
  1088. {
  1089. $aHeader[] = $sColLabel;
  1090. }
  1091. }
  1092. }
  1093. $sHtml = "<table border=\"1\">\n";
  1094. $sHtml .= "<tr>\n";
  1095. $sHtml .= "<td>".implode("</td><td>", $aHeader)."</td>\n";
  1096. $sHtml .= "</tr>\n";
  1097. $oSet->Seek(0);
  1098. while ($aObjects = $oSet->FetchAssoc())
  1099. {
  1100. $aRow = array();
  1101. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1102. {
  1103. $oObj = $aObjects[$sAlias];
  1104. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1105. {
  1106. if (is_null($oObj))
  1107. {
  1108. $aRow[] = '<td></td>';
  1109. }
  1110. else
  1111. {
  1112. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1113. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1114. {
  1115. $sDate = $oObj->Get($sAttCodeEx);
  1116. if ($sDate === null)
  1117. {
  1118. $aRow[] = '<td></td>';
  1119. $aRow[] = '<td></td>';
  1120. }
  1121. else
  1122. {
  1123. $iDate = AttributeDateTime::GetAsUnixSeconds($sDate);
  1124. $aRow[] = '<td>'.date('Y-m-d', $iDate).'</td>';
  1125. $aRow[] = '<td>'.date('H:i:s', $iDate).'</td>';
  1126. }
  1127. }
  1128. else if($oAttDef instanceof AttributeCaseLog)
  1129. {
  1130. $rawValue = $oObj->Get($sAttCodeEx);
  1131. $outputValue = str_replace("\n", "<br/>", htmlentities($rawValue->__toString(), ENT_QUOTES, 'UTF-8'));
  1132. // Trick for Excel: treat the content as text even if it begins with an equal sign
  1133. $aRow[] = '<td x:str>'.$outputValue.'</td>';
  1134. }
  1135. else
  1136. {
  1137. $rawValue = $oObj->Get($sAttCodeEx);
  1138. // Due to custom formatting rules, empty friendlynames may be rendered as non-empty strings
  1139. // let's fix this and make sure we render an empty string if the key == 0
  1140. if ($oAttDef instanceof AttributeFriendlyName)
  1141. {
  1142. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1143. if ($sKeyAttCode != 'id')
  1144. {
  1145. if ($oObj->Get($sKeyAttCode) == 0)
  1146. {
  1147. $rawValue = '';
  1148. }
  1149. }
  1150. }
  1151. if ($bLocalize)
  1152. {
  1153. $outputValue = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8');
  1154. }
  1155. else
  1156. {
  1157. $outputValue = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  1158. }
  1159. $aRow[] = '<td>'.$outputValue.'</td>';
  1160. }
  1161. }
  1162. }
  1163. }
  1164. $sHtml .= implode("\n", $aRow);
  1165. $sHtml .= "</tr>\n";
  1166. }
  1167. $sHtml .= "</table>\n";
  1168. return $sHtml;
  1169. }
  1170. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1171. {
  1172. $bLocalize = true;
  1173. if (isset($aParams['localize_values']))
  1174. {
  1175. $bLocalize = (bool) $aParams['localize_values'];
  1176. }
  1177. $oAppContext = new ApplicationContext();
  1178. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1179. $aAuthorizedClasses = array();
  1180. foreach($aClasses as $sAlias => $sClassName)
  1181. {
  1182. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1183. {
  1184. $aAuthorizedClasses[$sAlias] = $sClassName;
  1185. }
  1186. }
  1187. $aAttribs = array();
  1188. $aList = array();
  1189. $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details');
  1190. $oPage->add("<Set>\n");
  1191. $oSet->Seek(0);
  1192. while ($aObjects = $oSet->FetchAssoc())
  1193. {
  1194. if (count($aAuthorizedClasses) > 1)
  1195. {
  1196. $oPage->add("<Row>\n");
  1197. }
  1198. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1199. {
  1200. $oObj = $aObjects[$sAlias];
  1201. if (is_null($oObj))
  1202. {
  1203. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n");
  1204. }
  1205. else
  1206. {
  1207. $sClassName = get_class($oObj);
  1208. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  1209. }
  1210. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  1211. {
  1212. if (is_null($oObj))
  1213. {
  1214. $oPage->add("<$sAttCode>null</$sAttCode>\n");
  1215. }
  1216. else
  1217. {
  1218. if ($oAttDef->IsWritable())
  1219. {
  1220. if (!$oAttDef->IsLinkSet())
  1221. {
  1222. $sValue = $oObj->GetAsXML($sAttCode, $bLocalize);
  1223. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  1224. }
  1225. }
  1226. }
  1227. }
  1228. $oPage->add("</$sClassName>\n");
  1229. }
  1230. if (count($aAuthorizedClasses) > 1)
  1231. {
  1232. $oPage->add("</Row>\n");
  1233. }
  1234. }
  1235. $oPage->add("</Set>\n");
  1236. }
  1237. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1238. {
  1239. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  1240. }
  1241. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1242. {
  1243. static $iSearchFormId = 0;
  1244. $bMultiSelect = false;
  1245. $oAppContext = new ApplicationContext();
  1246. $sHtml = '';
  1247. $numCols=4;
  1248. $sClassName = $oSet->GetFilter()->GetClass();
  1249. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  1250. // (especially when used to add a link)
  1251. /*
  1252. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  1253. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  1254. <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>
  1255. </ul></div>\n";
  1256. */
  1257. // Simple search form
  1258. if (isset($aExtraParams['currentId']))
  1259. {
  1260. $sSearchFormId = $aExtraParams['currentId'];
  1261. }
  1262. else
  1263. {
  1264. $iSearchFormId = $oPage->GetUniqueId();
  1265. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  1266. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  1267. }
  1268. // Check if the current class has some sub-classes
  1269. if (isset($aExtraParams['baseClass']))
  1270. {
  1271. $sRootClass = $aExtraParams['baseClass'];
  1272. }
  1273. else
  1274. {
  1275. $sRootClass = $sClassName;
  1276. }
  1277. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  1278. if (count($aSubClasses) > 0)
  1279. {
  1280. $aOptions = array();
  1281. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  1282. foreach($aSubClasses as $sSubclassName)
  1283. {
  1284. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  1285. }
  1286. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  1287. ksort($aOptions);
  1288. $sContext = $oAppContext->GetForLink();
  1289. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  1290. }
  1291. else
  1292. {
  1293. $sClassesCombo = MetaModel::GetName($sClassName);
  1294. }
  1295. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  1296. $sAction = (isset($aExtraParams['action'])) ? $aExtraParams['action'] : utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1297. $sHtml .= "<form id=\"fs_{$sSearchFormId}\" action=\"{$sAction}\">\n"; // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  1298. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  1299. $index = 0;
  1300. $sHtml .= "<p>\n";
  1301. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  1302. $aMapCriteria = array();
  1303. foreach($aFilterCriteria as $aCriteria)
  1304. {
  1305. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  1306. }
  1307. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  1308. $aConsts = $oSet->ListConstantFields(); // Some fields are constants based on the query/context
  1309. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  1310. foreach($aList as $sFilterCode)
  1311. {
  1312. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  1313. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  1314. $sFilterValue = isset($aConsts[$sClassAlias][$sFilterCode]) ? $aConsts[$sClassAlias][$sFilterCode] : '';
  1315. $sFilterValue = utils::ReadParam($sFilterCode, $sFilterValue, false, 'raw_data');
  1316. $sFilterOpCode = null; // Use the default 'loose' OpCode
  1317. if (empty($sFilterValue))
  1318. {
  1319. if (isset($aMapCriteria[$sFilterCode]))
  1320. {
  1321. if (count($aMapCriteria[$sFilterCode]) > 1)
  1322. {
  1323. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  1324. }
  1325. else
  1326. {
  1327. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  1328. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  1329. }
  1330. if ($sFilterCode != 'company')
  1331. {
  1332. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  1333. }
  1334. }
  1335. }
  1336. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFilterCode);
  1337. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1338. {
  1339. $oKeyAttDef = $oAttDef->GetFinalAttDef();
  1340. $sKeyAttClass = $oKeyAttDef->GetHostClass();
  1341. $sKeyAttCode = $oKeyAttDef->GetCode();
  1342. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1343. $oSearch = new DBObjectSearch($sTargetClass);
  1344. $oSearch->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true);
  1345. $oAllowedValues = new DBObjectSet($oSearch);
  1346. $iFieldSize = $oKeyAttDef->GetMaxSize();
  1347. $iMaxComboLength = $oKeyAttDef->GetMaximumComboLength();
  1348. $sHtml .= "<label>".MetaModel::GetFilterLabel($sKeyAttClass, $sKeyAttCode).":</label>&nbsp;";
  1349. $aExtKeyParams = $aExtraParams;
  1350. $aExtKeyParams['iFieldSize'] = $oKeyAttDef->GetMaxSize();
  1351. $aExtKeyParams['iMinChars'] = $oKeyAttDef->GetMinAutoCompleteChars();
  1352. $sHtml .= UIExtKeyWidget::DisplayFromAttCode($oPage, $sKeyAttCode, $sKeyAttClass, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sSearchFormId.'search_'.$sFilterCode, false, $sFilterCode, '', $aExtKeyParams, true);
  1353. }
  1354. else
  1355. {
  1356. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  1357. if (is_null($aAllowedValues))
  1358. {
  1359. // Any value is possible, display an input box
  1360. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"".htmlentities($sFilterValue, ENT_QUOTES, 'utf-8')."\"/>\n";
  1361. }
  1362. else
  1363. {
  1364. //Enum field, display a multi-select combo
  1365. $sValue = "<select class=\"multiselect\" size=\"1\" name=\"{$sFilterCode}[]\" multiple>\n";
  1366. $bMultiSelect = true;
  1367. //$sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  1368. asort($aAllowedValues);
  1369. foreach($aAllowedValues as $key => $value)
  1370. {
  1371. if (is_array($sFilterValue) && in_array($key, $sFilterValue))
  1372. {
  1373. $sSelected = ' selected';
  1374. }
  1375. else if ($sFilterValue == $key)
  1376. {
  1377. $sSelected = ' selected';
  1378. }
  1379. else
  1380. {
  1381. $sSelected = '';
  1382. }
  1383. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  1384. }
  1385. $sValue .= "</select>\n";
  1386. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  1387. }
  1388. }
  1389. unset($aExtraParams[$sFilterCode]);
  1390. // Finally, add a tooltip if one is defined for this attribute definition
  1391. $sTip = $oAttDef->GetHelpOnSmartSearch();
  1392. if (strlen($sTip) > 0)
  1393. {
  1394. $sTip = addslashes($sTip);
  1395. $sTip = str_replace(array("\n", "\r"), " ", $sTip);
  1396. // :input does represent in form visible input (INPUT, SELECT, TEXTAREA)
  1397. $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' }} } );");
  1398. }
  1399. $index++;
  1400. $sHtml .= '</span> ';
  1401. }
  1402. $sHtml .= "</p>\n";
  1403. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  1404. if (isset($aExtraParams['table_id']))
  1405. {
  1406. // Rename to avoid collisions...
  1407. $aExtraParams['_table_id_'] = $aExtraParams['table_id'];
  1408. unset($aExtraParams['table_id']);
  1409. }
  1410. foreach($aExtraParams as $sName => $sValue)
  1411. {
  1412. if (is_scalar($sValue))
  1413. {
  1414. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1415. }
  1416. }
  1417. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  1418. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1419. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  1420. $sHtml .= $oAppContext->GetForForm();
  1421. $sHtml .= "</form>\n";
  1422. if (!isset($aExtraParams['currentId']))
  1423. {
  1424. $sHtml .= "</div><!-- Simple search form -->\n";
  1425. }
  1426. if ($bMultiSelect)
  1427. {
  1428. $aOptions = array(
  1429. 'header' => true,
  1430. 'checkAllText' => Dict::S('UI:SearchValue:CheckAll'),
  1431. 'uncheckAllText' => Dict::S('UI:SearchValue:UncheckAll'),
  1432. 'noneSelectedText' => Dict::S('UI:SearchValue:Any'),
  1433. 'selectedText' => Dict::S('UI:SearchValue:NbSelected'),
  1434. 'selectedList' => 1,
  1435. );
  1436. $sJSOptions = json_encode($aOptions);
  1437. $oPage->add_ready_script("$('.multiselect').multiselect($sJSOptions);");
  1438. }
  1439. /*
  1440. // OQL query builder
  1441. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  1442. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  1443. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  1444. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  1445. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1446. $sSelectedClass = utils::ReadParam('oql_class', $sClassName, false, 'class');
  1447. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  1448. asort($aClasses);
  1449. foreach($aClasses as $sChildClass)
  1450. {
  1451. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  1452. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  1453. }
  1454. $sHtml .= "</select>&nbsp;</td><td>\n";
  1455. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  1456. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  1457. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1458. foreach($aExtraParams as $sName => $sValue)
  1459. {
  1460. if (is_scalar($sValue))
  1461. {
  1462. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1463. }
  1464. }
  1465. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  1466. $sHtml .= $oAppContext->GetForForm();
  1467. $sHtml .= "</table></form>\n";
  1468. $sHtml .= "</div><!-- OQL query form -->\n";
  1469. */
  1470. return $sHtml;
  1471. }
  1472. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  1473. {
  1474. static $iInputId = 0;
  1475. $sFieldPrefix = '';
  1476. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  1477. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  1478. if ($sDisplayValue == '')
  1479. {
  1480. $sDisplayValue = $value;
  1481. }
  1482. if (isset($aArgs[$sAttCode]) && empty($value))
  1483. {
  1484. // default value passed by the context (either the app context of the operation)
  1485. $value = $aArgs[$sAttCode];
  1486. }
  1487. if (!empty($iId))
  1488. {
  1489. $iInputId = $iId;
  1490. }
  1491. else
  1492. {
  1493. $iInputId = $oPage->GetUniqueId();
  1494. }
  1495. if (!$oAttDef->IsExternalField())
  1496. {
  1497. $bMandatory = 'false';
  1498. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1499. {
  1500. $bMandatory = 'true';
  1501. }
  1502. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1503. $sHelpText = htmlentities($oAttDef->GetHelpOnEdition(), ENT_QUOTES, 'UTF-8');
  1504. $aEventsList = array();
  1505. switch($oAttDef->GetEditClass())
  1506. {
  1507. case 'Date':
  1508. $aEventsList[] ='validate';
  1509. $aEventsList[] ='keyup';
  1510. $aEventsList[] ='change';
  1511. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1512. {
  1513. $sDisplayValue = date($oAttDef->GetDateFormat());
  1514. }
  1515. $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}";
  1516. break;
  1517. case 'DateTime':
  1518. $aEventsList[] ='validate';
  1519. $aEventsList[] ='keyup';
  1520. $aEventsList[] ='change';
  1521. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1522. {
  1523. $sDisplayValue = date($oAttDef->GetDateFormat());
  1524. }
  1525. $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}";
  1526. break;
  1527. case 'Duration':
  1528. $aEventsList[] ='validate';
  1529. $aEventsList[] ='change';
  1530. $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1531. $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1532. $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1533. $oPage->add_ready_script("$('#{$iId}_s').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1534. $aVal = AttributeDuration::SplitDuration($value);
  1535. $sDays = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"3\" name=\"attr_{$sFieldPrefix}{$sAttCode}[d]{$sNameSuffix}\" value=\"{$aVal['days']}\" id=\"{$iId}_d\"/>";
  1536. $sHours = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[h]{$sNameSuffix}\" value=\"{$aVal['hours']}\" id=\"{$iId}_h\"/>";
  1537. $sMinutes = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[m]{$sNameSuffix}\" value=\"{$aVal['minutes']}\" id=\"{$iId}_m\"/>";
  1538. $sSeconds = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[s]{$sNameSuffix}\" value=\"{$aVal['seconds']}\" id=\"{$iId}_s\"/>";
  1539. $sHidden = "<input type=\"hidden\" id=\"{$iId}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\"/>";
  1540. $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden."&nbsp;".$sValidationField;
  1541. $oPage->add_ready_script("$('#{$iId}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });");
  1542. break;
  1543. case 'Password':
  1544. $aEventsList[] ='validate';
  1545. $aEventsList[] ='keyup';
  1546. $aEventsList[] ='change';
  1547. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1548. break;
  1549. case 'OQLExpression':
  1550. case 'Text':
  1551. $aEventsList[] ='validate';
  1552. $aEventsList[] ='keyup';
  1553. $aEventsList[] ='change';
  1554. $sEditValue = $oAttDef->GetEditValue($value);
  1555. $aStyles = array();
  1556. $sStyle = '';
  1557. $sWidth = $oAttDef->GetWidth('width', '');
  1558. if (!empty($sWidth))
  1559. {
  1560. $aStyles[] = 'width:'.$sWidth;
  1561. }
  1562. $sHeight = $oAttDef->GetHeight('height', '');
  1563. if (!empty($sHeight))
  1564. {
  1565. $aStyles[] = 'height:'.$sHeight;
  1566. }
  1567. if (count($aStyles) > 0)
  1568. {
  1569. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1570. }
  1571. if ($oAttDef->GetEditClass() == 'OQLExpression')
  1572. {
  1573. $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId();
  1574. $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression=';
  1575. $sInitialUrl = $sBaseUrl.urlencode($sEditValue);
  1576. $sAdditionalStuff = "<a id=\"$sTestResId\" target=\"_blank\" href=\"$sInitialUrl\">".Dict::S('UI:Edit:TestQuery')."</a>";
  1577. $oPage->add_ready_script("$('#$iId').bind('change keyup', function(evt, sFormId) { $('#$sTestResId').attr('href', '$sBaseUrl'+encodeURIComponent($(this).val())); } );");
  1578. }
  1579. else
  1580. {
  1581. $sAdditionalStuff = "";
  1582. }
  1583. // Ok, the text area is drawn here
  1584. $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>";
  1585. break;
  1586. case 'CaseLog':
  1587. $aStyles = array();
  1588. $sStyle = '';
  1589. $sWidth = $oAttDef->GetWidth('width', '');
  1590. if (!empty($sWidth))
  1591. {
  1592. $aStyles[] = 'width:'.$sWidth;
  1593. }
  1594. $sHeight = $oAttDef->GetHeight('height', '');
  1595. if (!empty($sHeight))
  1596. {
  1597. $aStyles[] = 'height:'.$sHeight;
  1598. }
  1599. if (count($aStyles) > 0)
  1600. {
  1601. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1602. }
  1603. $sHeader = '<div class="caselog_input_header">&nbsp;'.Dict::S('UI:CaseLogTypeYourTextHere').'</div>';
  1604. $sEditValue = $oAttDef->GetEditValue($value);
  1605. $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, array('AttributeText', 'RenderWikiHtml')) : '';
  1606. $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0;
  1607. $sHidden = "<input type=\"hidden\" id=\"{$iId}_count\" value=\"$iEntriesCount\"/>"; // To know how many entries the case log already contains
  1608. $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>";
  1609. $oPage->add_ready_script("$('#$iId').bind('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId) } );"); // Custom validation function
  1610. break;
  1611. case 'HTML':
  1612. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationField, $value, $bMandatory);
  1613. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1614. break;
  1615. case 'LinkedSet':
  1616. if ($oAttDef->IsIndirect())
  1617. {
  1618. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed(), $aArgs);
  1619. }
  1620. else
  1621. {
  1622. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix, $aArgs);
  1623. }
  1624. $aEventsList[] ='validate';
  1625. $aEventsList[] ='change';
  1626. $oObj = isset($aArgs['this']) ? $aArgs['this'] : null;
  1627. $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj);
  1628. break;
  1629. case 'Document':
  1630. $aEventsList[] ='validate';
  1631. $aEventsList[] ='change';
  1632. $oDocument = $value; // Value is an ormDocument object
  1633. $sFileName = '';
  1634. if (is_object($oDocument))
  1635. {
  1636. $sFileName = $oDocument->GetFileName();
  1637. }
  1638. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1639. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1640. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[filename]\" type=\"hidden\" id=\"$iId\" \" value=\"".htmlentities($sFileName, ENT_QUOTES, 'UTF-8')."\"/>\n";
  1641. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1642. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[fcontents]\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1643. break;
  1644. case 'StopWatch':
  1645. $sHTMLValue = "The edition of a stopwatch is not allowed!!!";
  1646. break;
  1647. case 'List':
  1648. // Not editable for now...
  1649. $sHTMLValue = '';
  1650. break;
  1651. case 'One Way Password':
  1652. $aEventsList[] ='validate';
  1653. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1654. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1655. // Event list & validation is handled directly by the widget
  1656. break;
  1657. case 'ExtKey':
  1658. $aEventsList[] ='validate';
  1659. $aEventsList[] ='change';
  1660. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1661. $sFieldName = $sFieldPrefix.$sAttCode.$sNameSuffix;
  1662. $aExtKeyParams = $aArgs;
  1663. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1664. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1665. $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams);
  1666. $sHTMLValue .= "<!-- iFlags: $iFlags bMandatory: $bMandatory -->\n";
  1667. break;
  1668. case 'String':
  1669. default:
  1670. $aEventsList[] ='validate';
  1671. // #@# todo - add context information (depending on dimensions)
  1672. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1673. $iFieldSize = $oAttDef->GetMaxSize();
  1674. if ($aAllowedValues !== null)
  1675. {
  1676. // Discrete list of values, use a SELECT or RADIO buttons depending on the config
  1677. $sDisplayStyle = $oAttDef->GetDisplayStyle();
  1678. switch($sDisplayStyle)
  1679. {
  1680. case 'radio':
  1681. case 'radio_horizontal':
  1682. case 'radio_vertical':
  1683. $sHTMLValue = '';
  1684. $bVertical = ($sDisplayStyle != 'radio_horizontal');
  1685. $sHTMLValue = $oPage->GetRadioButtons($aAllowedValues, $value, $iId, "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", $bMandatory, $bVertical, $sValidationField);
  1686. $aEventsList[] ='change';
  1687. break;
  1688. case 'select':
  1689. default:
  1690. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1691. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1692. foreach($aAllowedValues as $key => $display_value)
  1693. {
  1694. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1695. {
  1696. // When there is only once choice, select it by default
  1697. $sSelected = ' selected';
  1698. }
  1699. else
  1700. {
  1701. $sSelected = ($value == $key) ? ' selected' : '';
  1702. }
  1703. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1704. }
  1705. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1706. $aEventsList[] ='change';
  1707. }
  1708. }
  1709. else
  1710. {
  1711. $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}";
  1712. $aEventsList[] ='keyup';
  1713. $aEventsList[] ='change';
  1714. }
  1715. break;
  1716. }
  1717. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1718. if (!empty($aEventsList))
  1719. {
  1720. $sNullValue = $oAttDef->GetNullValue();
  1721. if (!is_numeric($sNullValue))
  1722. {
  1723. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1724. }
  1725. $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
  1726. }
  1727. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1728. if (count($aDependencies) > 0)
  1729. {
  1730. // Unbind first to avoid duplicate event handlers in case of reload of the whole (or part of the) form
  1731. $oPage->add_ready_script("$('#$iId').unbind('change.dependencies').bind('change.dependencies', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1732. }
  1733. }
  1734. return "<div>{$sHTMLValue}</div>";
  1735. }
  1736. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1737. {
  1738. self::$iGlobalFormId++;
  1739. $this->aFieldsMap = array();
  1740. $sPrefix = '';
  1741. if (isset($aExtraParams['formPrefix']))
  1742. {
  1743. $sPrefix = $aExtraParams['formPrefix'];
  1744. }
  1745. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  1746. $this->m_iFormId = $sPrefix.self::$iGlobalFormId;
  1747. $sClass = get_class($this);
  1748. $oAppContext = new ApplicationContext();
  1749. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1750. $iKey = $this->GetKey();
  1751. $aDetails = array();
  1752. $aFieldsMap = array();
  1753. if (!isset($aExtraParams['action']))
  1754. {
  1755. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1756. }
  1757. else
  1758. {
  1759. $sFormAction = $aExtraParams['action'];
  1760. }
  1761. // Custom label for the apply button ?
  1762. if (isset($aExtraParams['custom_button']))
  1763. {
  1764. $sApplyButton = $aExtraParams['custom_button'];
  1765. }
  1766. else if ($iKey > 0)
  1767. {
  1768. $sApplyButton = Dict::S('UI:Button:Apply');
  1769. }
  1770. else
  1771. {
  1772. $sApplyButton = Dict::S('UI:Button:Create');
  1773. }
  1774. // Custom operation for the form ?
  1775. if (isset($aExtraParams['custom_operation']))
  1776. {
  1777. $sOperation = $aExtraParams['custom_operation'];
  1778. }
  1779. else if ($iKey > 0)
  1780. {
  1781. $sOperation = 'apply_modify';
  1782. }
  1783. else
  1784. {
  1785. $sOperation = 'apply_new';
  1786. }
  1787. if ($iKey > 0)
  1788. {
  1789. // The object already exists in the database, it's a modification
  1790. $sButtons = "<input id=\"{$sPrefix}_id\" type=\"hidden\" name=\"id\" value=\"$iKey\">\n";
  1791. $sButtons .= "<input type=\"hidden\" name=\"operation\" value=\"{$sOperation}\">\n";
  1792. $sButtons .= "<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1793. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1794. }
  1795. else
  1796. {
  1797. // The object does not exist in the database it's a creation
  1798. $sButtons = "<input type=\"hidden\" name=\"operation\" value=\"$sOperation\">\n";
  1799. $sButtons .= "<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1800. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1801. }
  1802. $aTransitions = $this->EnumTransitions();
  1803. if (!isset($aExtraParams['custom_operation']) && count($aTransitions))
  1804. {
  1805. // transitions are displayed only for the standard new/modify actions, not for modify_all or any other case...
  1806. $oSetToCheckRights = DBObjectSet::FromObject($this);
  1807. $aStimuli = Metamodel::EnumStimuli($sClass);
  1808. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1809. {
  1810. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSetToCheckRights) : UR_ALLOWED_NO;
  1811. switch($iActionAllowed)
  1812. {
  1813. case UR_ALLOWED_YES:
  1814. $sButtons .= "<button type=\"submit\" name=\"next_action\" value=\"{$sStimulusCode}\" class=\"action\"><span>".$aStimuli[$sStimulusCode]->GetLabel()."</span></button>\n";
  1815. break;
  1816. default:
  1817. // Do nothing
  1818. }
  1819. }
  1820. }
  1821. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1822. $iTransactionId = isset($aExtraParams['transaction_id']) ? $aExtraParams['transaction_id'] : utils::GetNewTransactionId();
  1823. $oPage->SetTransactionId($iTransactionId);
  1824. $oPage->add("<form action=\"$sFormAction\" id=\"form_{$this->m_iFormId}\" enctype=\"multipart/form-data\" method=\"post\" onSubmit=\"return OnSubmit('form_{$this->m_iFormId}');\">\n");
  1825. $sStatesSelection = '';
  1826. if (!isset($aExtraParams['custom_operation']) && $this->IsNew())
  1827. {
  1828. $aInitialStates = MetaModel::EnumInitialStates($sClass);
  1829. //$aInitialStates = array('new' => 'foo', 'closed' => 'bar');
  1830. if (count($aInitialStates) > 1)
  1831. {
  1832. $sStatesSelection = Dict::Format('UI:Create_Class_InState', MetaModel::GetName($sClass)).'<select name="obj_state" class="state_select_'.$this->m_iFormId.'">';
  1833. foreach($aInitialStates as $sStateCode => $sStateData)
  1834. {
  1835. $sSelected = '';
  1836. if ($sStateCode == $this->GetState())
  1837. {
  1838. $sSelected = ' selected';
  1839. }
  1840. $sStatesSelection .= '<option value="'.$sStateCode.'"'.$sSelected.'>'.MetaModel::GetStateLabel($sClass, $sStateCode).'</option>';
  1841. }
  1842. $sStatesSelection .= '</select>';
  1843. $oPage->add_ready_script("$('.state_select_{$this->m_iFormId}').change( function() { oWizardHelper$sPrefix.ReloadObjectCreationForm('form_{$this->m_iFormId}', $(this).val()); } );");
  1844. }
  1845. }
  1846. $sConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage'));
  1847. $oPage->add_ready_script(
  1848. <<<EOF
  1849. $(window).unload(function() { return OnUnload('$iTransactionId') } );
  1850. window.onbeforeunload = function() {
  1851. if (!window.bInSubmit && !window.bInCancel)
  1852. {
  1853. return '$sConfirmationMessage';
  1854. }
  1855. // return nothing ! safer for IE
  1856. };
  1857. EOF
  1858. );
  1859. if ($sButtonsPosition != 'bottom')
  1860. {
  1861. // top or both, display the buttons here
  1862. $oPage->p($sStatesSelection);
  1863. $oPage->add($sButtons);
  1864. }
  1865. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1866. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1867. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1868. $aFieldsMap = $this->DisplayBareProperties($oPage, true, $sPrefix, $aExtraParams);
  1869. if ($iKey > 0)
  1870. {
  1871. $aFieldsMap['id'] = $sPrefix.'_id';
  1872. }
  1873. // Now display the relations, one tab per relation
  1874. if (!isset($aExtraParams['noRelations']))
  1875. {
  1876. $this->DisplayBareRelations($oPage, true); // Edit mode, will fill $this->aFieldsMap
  1877. $aFieldsMap = array_merge($aFieldsMap, $this->aFieldsMap);
  1878. }
  1879. $oPage->SetCurrentTab('');
  1880. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1881. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"$iTransactionId\">\n");
  1882. foreach($aExtraParams as $sName => $value)
  1883. {
  1884. if (is_scalar($value))
  1885. {
  1886. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1887. }
  1888. }
  1889. $oPage->add($oAppContext->GetForForm());
  1890. if ($sButtonsPosition != 'top')
  1891. {
  1892. // bottom or both: display the buttons here
  1893. $oPage->p($sStatesSelection);
  1894. $oPage->add($sButtons);
  1895. }
  1896. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1897. $sDefaultUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=cancel&'.$oAppContext->GetForLink();
  1898. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1899. $oPage->add("</form>\n");
  1900. $iFieldsCount = count($aFieldsMap);
  1901. $sJsonFieldsMap = json_encode($aFieldsMap);
  1902. $sState = $this->GetState();
  1903. $oPage->add_script(
  1904. <<<EOF
  1905. // Create the object once at the beginning of the page...
  1906. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix', '$sState');
  1907. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1908. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1909. EOF
  1910. );
  1911. $oPage->add_ready_script(
  1912. <<<EOF
  1913. oWizardHelper$sPrefix.UpdateWizard();
  1914. // Starts the validation when the page is ready
  1915. CheckFields('form_{$this->m_iFormId}', false);
  1916. EOF
  1917. );
  1918. }
  1919. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1920. {
  1921. $oAppContext = new ApplicationContext();
  1922. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1923. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1924. $aStates = MetaModel::EnumStates($sClass);
  1925. $sStatesSelection = '';
  1926. if ($oObjectToClone == null)
  1927. {
  1928. $oObj = MetaModel::NewObject($sClass);
  1929. if (!empty($sStateAttCode))
  1930. {
  1931. $sTargetState = MetaModel::GetDefaultState($sClass);
  1932. $oObj->Set($sStateAttCode, $sTargetState);
  1933. }
  1934. }
  1935. else
  1936. {
  1937. $oObj = clone $oObjectToClone;
  1938. }
  1939. // Pre-fill the object with default values, when there is only on possible choice
  1940. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  1941. $aArgs['this'] = $oObj;
  1942. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1943. // Order the fields based on their dependencies
  1944. $aDeps = array();
  1945. foreach($aDetailsList as $sAttCode)
  1946. {
  1947. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1948. }
  1949. $aList = self::OrderDependentFields($aDeps);
  1950. // Now fill-in the fields with default/supplied values
  1951. foreach($aList as $sAttCode)
  1952. {
  1953. if (isset($aArgs['default'][$sAttCode]))
  1954. {
  1955. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  1956. }
  1957. else
  1958. {
  1959. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1960. // If the field is mandatory, set it to the only possible value
  1961. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  1962. if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1963. {
  1964. if ($oAttDef->IsExternalKey())
  1965. {
  1966. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1967. if ($oAllowedValues->Count() == 1)
  1968. {
  1969. $oRemoteObj = $oAllowedValues->Fetch();
  1970. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1971. }
  1972. }
  1973. else
  1974. {
  1975. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1976. if (count($aAllowedValues) == 1)
  1977. {
  1978. $aValues = array_keys($aAllowedValues);
  1979. $oObj->Set($sAttCode, $aValues[0]);
  1980. }
  1981. }
  1982. }
  1983. }
  1984. }
  1985. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  1986. }
  1987. public function DisplayStimulusForm(WebPage $oPage, $sStimulus)
  1988. {
  1989. $sClass = get_class($this);
  1990. $aTransitions = $this->EnumTransitions();
  1991. $aStimuli = MetaModel::EnumStimuli($sClass);
  1992. if (!isset($aTransitions[$sStimulus]))
  1993. {
  1994. // Invalid stimulus
  1995. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $this->GetName(), $this->GetStateLabel()));
  1996. }
  1997. $sActionLabel = $aStimuli[$sStimulus]->GetLabel();
  1998. $sActionDetails = $aStimuli[$sStimulus]->GetDescription();
  1999. $aTransition = $aTransitions[$sStimulus];
  2000. $sTargetState = $aTransition['target_state'];
  2001. $aTargetStates = MetaModel::EnumStates($sClass);
  2002. $oPage->add("<div class=\"page_header\">\n");
  2003. $oPage->add("<h1>$sActionLabel - <span class=\"hilite\">{$this->GetName()}</span></h1>\n");
  2004. $oPage->set_title($sActionLabel);
  2005. $oPage->add("</div>\n");
  2006. $aTargetState = $aTargetStates[$sTargetState];
  2007. $aExpectedAttributes = $aTargetState['attribute_list'];
  2008. $oPage->add("<h1>$sActionDetails</h1>\n");
  2009. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  2010. if ($sButtonsPosition == 'bottom')
  2011. {
  2012. // bottom: Displays the ticket details BEFORE the actions
  2013. $oPage->add('<div class="ui-widget-content">');
  2014. $this->DisplayBareProperties($oPage);
  2015. $oPage->add('</div>');
  2016. }
  2017. $oPage->add("<div class=\"wizContainer\">\n");
  2018. $oPage->add("<form id=\"apply_stimulus\" method=\"post\" onSubmit=\"return OnSubmit('apply_stimulus');\">\n");
  2019. $aDetails = array();
  2020. $iFieldIndex = 0;
  2021. $aFieldsMap = array();
  2022. $aDetailsList =$this->FlattenZList(MetaModel::GetZListItems($sClass, 'details'));
  2023. // Order the fields based on their dependencies, set the fields for which there is only one possible value
  2024. // and perform this in the order of dependencies to avoid dead-ends
  2025. $aDeps = array();
  2026. foreach($aDetailsList as $sAttCode)
  2027. {
  2028. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  2029. }
  2030. $aList =$this->OrderDependentFields($aDeps);
  2031. foreach($aList as $sAttCode)
  2032. {
  2033. // Consider only the "expected" fields for the target state
  2034. if (array_key_exists($sAttCode, $aExpectedAttributes))
  2035. {
  2036. $iExpectCode = $aExpectedAttributes[$sAttCode];
  2037. // Prompt for an attribute if
  2038. // - the attribute must be changed or must be displayed to the user for confirmation
  2039. // - or the field is mandatory and currently empty
  2040. if ( ($iExpectCode & (OPT_ATT_MUSTCHANGE | OPT_ATT_MUSTPROMPT)) ||
  2041. (($iExpectCode & OPT_ATT_MANDATORY) && ($this->Get($sAttCode) == '')) )
  2042. {
  2043. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  2044. $aArgs = array('this' => $this);
  2045. // If the field is mandatory, set it to the only possible value
  2046. if ((!$oAttDef->IsNullAllowed()) || ($iExpectCode & OPT_ATT_MANDATORY))
  2047. {
  2048. if ($oAttDef->IsExternalKey())
  2049. {
  2050. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  2051. if ($oAllowedValues->Count() == 1)
  2052. {
  2053. $oRemoteObj = $oAllowedValues->Fetch();
  2054. $this->Set($sAttCode, $oRemoteObj->GetKey());
  2055. }
  2056. }
  2057. else
  2058. {
  2059. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  2060. if (count($aAllowedValues) == 1)
  2061. {
  2062. $aValues = array_keys($aAllowedValues);
  2063. $this->Set($sAttCode, $aValues[0]);
  2064. }
  2065. }
  2066. }
  2067. $sHTMLValue = cmdbAbstractObject::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef,$this->Get($sAttCode),$this->GetEditValue($sAttCode), 'att_'.$iFieldIndex, '', $iExpectCode, $aArgs);
  2068. $aDetails[] = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => "<span id=\"field_att_$iFieldIndex\">$sHTMLValue</span>");
  2069. $aFieldsMap[$sAttCode] = 'att_'.$iFieldIndex;
  2070. $iFieldIndex++;
  2071. }
  2072. }
  2073. }
  2074. $oPage->add('<table><tr><td>');
  2075. $oPage->details($aDetails);
  2076. $oPage->add('</td></tr></table>');
  2077. $oPage->add("<input type=\"hidden\" name=\"id\" value=\"".$this->GetKey()."\" id=\"id\">\n");
  2078. $aFieldsMap['id'] = 'id';
  2079. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  2080. $oPage->add("<input type=\"hidden\" name=\"operation\" value=\"apply_stimulus\">\n");
  2081. $oPage->add("<input type=\"hidden\" name=\"stimulus\" value=\"$sStimulus\">\n");
  2082. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  2083. $oAppContext = new ApplicationContext();
  2084. $oPage->add($oAppContext->GetForForm());
  2085. $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");
  2086. $oPage->add("<button type=\"submit\" class=\"action\"><span>$sActionLabel</span></button>\n");
  2087. $oPage->add("</form>\n");
  2088. $oPage->add("</div>\n");
  2089. if ($sButtonsPosition != 'top')
  2090. {
  2091. // bottom or both: Displays the ticket details AFTER the actions
  2092. $oPage->add('<div class="ui-widget-content">');
  2093. $this->DisplayBareProperties($oPage);
  2094. $oPage->add('</div>');
  2095. }
  2096. $iFieldsCount = count($aFieldsMap);
  2097. $sJsonFieldsMap = json_encode($aFieldsMap);
  2098. $oPage->add_script(
  2099. <<<EOF
  2100. // Initializes the object once at the beginning of the page...
  2101. var oWizardHelper = new WizardHelper('$sClass', '', '$sTargetState');
  2102. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  2103. oWizardHelper.SetFieldsCount($iFieldsCount);
  2104. EOF
  2105. );
  2106. $oPage->add_ready_script(
  2107. <<<EOF
  2108. // Starts the validation when the page is ready
  2109. CheckFields('apply_stimulus', false);
  2110. EOF
  2111. );
  2112. }
  2113. public static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  2114. {
  2115. //echo "<pre>ZList: ";
  2116. //print_r($aList);
  2117. //echo "</pre>\n";
  2118. $index = 0;
  2119. foreach($aList as $sKey => $value)
  2120. {
  2121. if (is_array($value))
  2122. {
  2123. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  2124. {
  2125. $sCode = $aMatches[1];
  2126. $sName = $aMatches[2];
  2127. switch($sCode)
  2128. {
  2129. case 'tab':
  2130. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  2131. if(!isset($aDetails[$sName]))
  2132. {
  2133. $aDetails[$sName] = array('col1' => array());
  2134. }
  2135. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  2136. break;
  2137. case 'fieldset':
  2138. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  2139. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  2140. {
  2141. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  2142. }
  2143. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  2144. break;
  2145. default:
  2146. case 'col':
  2147. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  2148. if(!isset($aDetails[$sCurrentTab][$sName]))
  2149. {
  2150. $aDetails[$sCurrentTab][$sName] = array();
  2151. }
  2152. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  2153. break;
  2154. }
  2155. }
  2156. }
  2157. else
  2158. {
  2159. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  2160. if (empty($sCurrentSet))
  2161. {
  2162. $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value;
  2163. }
  2164. else
  2165. {
  2166. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  2167. }
  2168. }
  2169. $index++;
  2170. }
  2171. return $aDetails;
  2172. }
  2173. static function FlattenZList($aList)
  2174. {
  2175. $aResult = array();
  2176. foreach($aList as $value)
  2177. {
  2178. if (!is_array($value))
  2179. {
  2180. $aResult[] = $value;
  2181. }
  2182. else
  2183. {
  2184. $aResult = array_merge($aResult,self::FlattenZList($value));
  2185. }
  2186. }
  2187. return $aResult;
  2188. }
  2189. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  2190. {
  2191. $retVal = null;
  2192. if ($this->IsNew())
  2193. {
  2194. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2195. }
  2196. else
  2197. {
  2198. $iFlags = $this->GetAttributeFlags($sAttCode);
  2199. }
  2200. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  2201. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  2202. {
  2203. // The field is visible in the current state of the object
  2204. if ($sStateAttCode == $sAttCode)
  2205. {
  2206. // Special display for the 'state' attribute itself
  2207. $sDisplayValue = $this->GetStateLabel();
  2208. }
  2209. else if ($oAttDef->GetEditClass() == 'Document')
  2210. {
  2211. $oDocument = $this->Get($sAttCode);
  2212. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2213. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2214. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDownloadLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2215. }
  2216. else
  2217. {
  2218. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2219. }
  2220. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  2221. }
  2222. return $retVal;
  2223. }
  2224. /**
  2225. * Displays a blob document *inline* (if possible, depending on the type of the document)
  2226. * @return string
  2227. */
  2228. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  2229. {
  2230. $oDoc = $this->Get($sAttCode);
  2231. $sClass = get_class($this);
  2232. $Id = $this->GetKey();
  2233. switch ($oDoc->GetMainMimeType())
  2234. {
  2235. case 'text':
  2236. case 'html':
  2237. $data = $oDoc->GetData();
  2238. switch($oDoc->GetMimeType())
  2239. {
  2240. case 'text/html':
  2241. case 'text/xml':
  2242. $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");
  2243. break;
  2244. default:
  2245. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true), ENT_QUOTES, 'UTF-8')."</pre>\n");
  2246. }
  2247. break;
  2248. case 'application':
  2249. switch($oDoc->GetMimeType())
  2250. {
  2251. case 'application/pdf':
  2252. $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");
  2253. break;
  2254. default:
  2255. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2256. }
  2257. break;
  2258. case 'image':
  2259. $oPage->add("<img src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  2260. break;
  2261. default:
  2262. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2263. }
  2264. }
  2265. // $m_highlightComparison[previous][new] => next value
  2266. protected static $m_highlightComparison = array(
  2267. HILIGHT_CLASS_CRITICAL => array(
  2268. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2269. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL,
  2270. HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL,
  2271. HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL,
  2272. ),
  2273. HILIGHT_CLASS_WARNING => array(
  2274. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2275. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2276. HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING,
  2277. HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING,
  2278. ),
  2279. HILIGHT_CLASS_OK => array(
  2280. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2281. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2282. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2283. HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK,
  2284. ),
  2285. HILIGHT_CLASS_NONE => array(
  2286. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2287. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2288. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2289. HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE,
  2290. ),
  2291. );
  2292. /**
  2293. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  2294. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  2295. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2296. * To Be overridden by derived classes
  2297. * @param void
  2298. * @return String The desired higlight class for the object/row
  2299. */
  2300. public function GetHilightClass()
  2301. {
  2302. // Possible return values are:
  2303. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2304. $current = parent::GetHilightClass(); // Default computation
  2305. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2306. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2307. {
  2308. $new = $oExtensionInstance->GetHilightClass($this);
  2309. @$current = self::$m_highlightComparison[$current][$new];
  2310. }
  2311. return $current;
  2312. }
  2313. /**
  2314. * Re-order the fields based on their inter-dependencies
  2315. * @params hash @aFields field_code => array_of_depencies
  2316. * @return array Ordered array of fields or throws an exception
  2317. */
  2318. public static function OrderDependentFields($aFields)
  2319. {
  2320. $bCircular = false;
  2321. $aResult = array();
  2322. $iCount = 0;
  2323. do
  2324. {
  2325. $bSet = false;
  2326. $iCount++;
  2327. foreach($aFields as $sFieldCode => $aDeps)
  2328. {
  2329. foreach($aDeps as $key => $sDependency)
  2330. {
  2331. if (in_array($sDependency, $aResult))
  2332. {
  2333. // Dependency is resolved, remove it
  2334. unset($aFields[$sFieldCode][$key]);
  2335. }
  2336. else if (!array_key_exists($sDependency, $aFields))
  2337. {
  2338. // The current fields depends on a field not present in the form
  2339. // let's ignore it (since it cannot change)
  2340. unset($aFields[$sFieldCode][$key]);
  2341. }
  2342. }
  2343. if (count($aFields[$sFieldCode]) == 0)
  2344. {
  2345. // No more pending depencies for this field, add it to the list
  2346. $aResult[] = $sFieldCode;
  2347. unset($aFields[$sFieldCode]);
  2348. $bSet = true;
  2349. }
  2350. }
  2351. }
  2352. while($bSet && (count($aFields) > 0));
  2353. if (count($aFields) > 0)
  2354. {
  2355. $sMessage = "Error: Circular dependencies between the fields! <pre>".print_r($aFields, true)."</pre>";
  2356. throw(new Exception($sMessage));
  2357. }
  2358. return $aResult;
  2359. }
  2360. /**
  2361. * Get the list of actions to be displayed as 'shortcuts' (i.e buttons) instead of inside the Actions popup menu
  2362. * @param $sFinalClass string The actual class of the objects for which to display the menu
  2363. * @return Array the list of menu codes (i.e dictionary entries) that can be displayed as shortcuts next to the actions menu
  2364. */
  2365. public static function GetShortcutActions($sFinalClass)
  2366. {
  2367. $sShortcutActions = MetaModel::GetConfig()->Get('shortcut_actions');
  2368. $aShortcutActions = explode(',', $sShortcutActions);
  2369. return $aShortcutActions;
  2370. }
  2371. /**
  2372. * Maps the given context parameter name to the appropriate filter/search code for this class
  2373. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  2374. * @return string Filter code, i.e. 'customer_id'
  2375. */
  2376. public static function MapContextParam($sContextParam)
  2377. {
  2378. if ($sContextParam == 'menu')
  2379. {
  2380. return null;
  2381. }
  2382. else
  2383. {
  2384. return $sContextParam;
  2385. }
  2386. }
  2387. /**
  2388. * Updates the object from a flat array of values
  2389. * @param $aAttList array $aAttList array of attcode
  2390. * @param $aErrors array Returns information about slave attributes
  2391. * @param $sTargetState string Target state for which to evaluate the writeable attributes (=current state is empty)
  2392. * @return array of attcodes that can be used for writing on the current object
  2393. */
  2394. public function GetWriteableAttList($aAttList, &$aErrors, $sTargetState = '')
  2395. {
  2396. if (!is_array($aAttList))
  2397. {
  2398. $aAttList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2399. // Special case to process the case log, if any...
  2400. // WARNING: if you change this also check the functions DisplayModifyForm and DisplayCaseLog
  2401. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2402. {
  2403. if ($this->IsNew())
  2404. {
  2405. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2406. }
  2407. else
  2408. {
  2409. $aVoid = array();
  2410. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2411. }
  2412. if ($oAttDef instanceof AttributeCaseLog)
  2413. {
  2414. if (!($iFlags & (OPT_ATT_HIDDEN|OPT_ATT_SLAVE|OPT_ATT_READONLY)))
  2415. {
  2416. // The case log is editable, append it to the list of fields to retrieve
  2417. $aAttList[] = $sAttCode;
  2418. }
  2419. }
  2420. }
  2421. }
  2422. $aWriteableAttList = array();
  2423. foreach($aAttList as $sAttCode)
  2424. {
  2425. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2426. if ($this->IsNew())
  2427. {
  2428. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2429. }
  2430. else
  2431. {
  2432. $aVoid = array();
  2433. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2434. }
  2435. if ($oAttDef->IsWritable())
  2436. {
  2437. if ( $iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  2438. {
  2439. // Non-visible, or read-only attribute, do nothing
  2440. }
  2441. elseif($iFlags & OPT_ATT_SLAVE)
  2442. {
  2443. $aErrors[$sAttCode] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  2444. }
  2445. else
  2446. {
  2447. $aWriteableAttList[$sAttCode] = $oAttDef;
  2448. }
  2449. }
  2450. }
  2451. return $aWriteableAttList;
  2452. }
  2453. /**
  2454. * Updates the object from a flat array of values
  2455. * @param string $aValues array of attcode => scalar or array (N-N links)
  2456. * @return void
  2457. */
  2458. public function UpdateObjectFromArray($aValues)
  2459. {
  2460. foreach($aValues as $sAttCode => $value)
  2461. {
  2462. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2463. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  2464. {
  2465. $aLinks = $value;
  2466. $sLinkedClass = $oAttDef->GetLinkedClass();
  2467. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  2468. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2469. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  2470. if (is_array($aLinks))
  2471. {
  2472. foreach($aLinks as $id => $aData)
  2473. {
  2474. if (is_numeric($id))
  2475. {
  2476. if ($id < 0)
  2477. {
  2478. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  2479. $oLink = MetaModel::NewObject($sLinkedClass);
  2480. $oLink->Set($sExtKeyToRemote, -$id);
  2481. $oLink->Set($sExtKeyToMe, $this->GetKey());
  2482. }
  2483. else
  2484. {
  2485. // Existing link, potentially to be updated...
  2486. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  2487. }
  2488. // Now populate the attributes
  2489. foreach($aData as $sName => $value)
  2490. {
  2491. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  2492. {
  2493. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  2494. if ($oLinkAttDef->IsWritable())
  2495. {
  2496. $oLink->Set($sName, $value);
  2497. }
  2498. }
  2499. }
  2500. $oLinkedSet->AddObject($oLink);
  2501. }
  2502. }
  2503. }
  2504. $this->Set($sAttCode, $oLinkedSet);
  2505. }
  2506. elseif ($oAttDef->GetEditClass() == 'Document')
  2507. {
  2508. // There should be an uploaded file with the named attr_<attCode>
  2509. $oDocument = $value['fcontents'];
  2510. if (!$oDocument->IsEmpty())
  2511. {
  2512. // A new file has been uploaded
  2513. $this->Set($sAttCode, $oDocument);
  2514. }
  2515. }
  2516. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  2517. {
  2518. // Check if the password was typed/changed
  2519. $aPwdData = $value;
  2520. if (!is_null($aPwdData) && $aPwdData['changed'])
  2521. {
  2522. // The password has been changed or set
  2523. $this->Set($sAttCode, $aPwdData['value']);
  2524. }
  2525. }
  2526. elseif ($oAttDef->GetEditClass() == 'Duration')
  2527. {
  2528. $aDurationData = $value;
  2529. if (!is_array($aDurationData)) continue;
  2530. $iValue = (((24*$aDurationData['d'])+$aDurationData['h'])*60 +$aDurationData['m'])*60 + $aDurationData['s'];
  2531. $this->Set($sAttCode, $iValue);
  2532. $previousValue = $this->Get($sAttCode);
  2533. if ($previousValue !== $iValue)
  2534. {
  2535. $this->Set($sAttCode, $iValue);
  2536. }
  2537. }
  2538. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() &&
  2539. (($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE) || ($oAttDef->GetEditMode() == LINKSET_EDITMODE_ADDREMOVE)))
  2540. {
  2541. $oLinkset = $this->Get($sAttCode);
  2542. $sLinkedClass = $oLinkset->GetClass();
  2543. $aObjSet = array();
  2544. $oLinkset->Rewind();
  2545. $bModified = false;
  2546. while($oLink = $oLinkset->Fetch())
  2547. {
  2548. if (in_array($oLink->GetKey(), $value['to_be_deleted']))
  2549. {
  2550. // The link is to be deleted, don't copy it in the array
  2551. $bModified = true;
  2552. }
  2553. else
  2554. {
  2555. if (!array_key_exists('to_be_removed', $value) || !in_array($oLink->GetKey(), $value['to_be_removed']))
  2556. {
  2557. $aObjSet[] = $oLink;
  2558. }
  2559. }
  2560. }
  2561. if (array_key_exists('to_be_created', $value) && (count($value['to_be_created']) > 0))
  2562. {
  2563. // Now handle the links to be created
  2564. foreach($value['to_be_created'] as $aData)
  2565. {
  2566. $sSubClass = $aData['class'];
  2567. if ( ($sLinkedClass == $sSubClass) || (is_subclass_of($sSubClass, $sLinkedClass)) )
  2568. {
  2569. $aObjData = $aData['data'];
  2570. $oLink = new $sSubClass;
  2571. $oLink->UpdateObjectFromArray($aObjData);
  2572. $aObjSet[] = $oLink;
  2573. $bModified = true;
  2574. }
  2575. }
  2576. }
  2577. if (array_key_exists('to_be_added', $value) && (count($value['to_be_added']) > 0))
  2578. {
  2579. // Now handle the links to be added by making the remote object point to self
  2580. foreach($value['to_be_added'] as $iObjKey)
  2581. {
  2582. $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false);
  2583. if ($oLink)
  2584. {
  2585. $aObjSet[] = $oLink;
  2586. $bModified = true;
  2587. }
  2588. }
  2589. }
  2590. if (array_key_exists('to_be_removed', $value) && (count($value['to_be_removed']) > 0))
  2591. {
  2592. // Now handle the links to be removed by making the remote object point to nothing
  2593. // Keep them in the set (modified), DBWriteLinks will handle them
  2594. foreach($value['to_be_removed'] as $iObjKey)
  2595. {
  2596. $oLink = MetaModel::GetObject($sLinkedClass, $iObjKey, false);
  2597. if ($oLink)
  2598. {
  2599. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2600. $oLink->Set($sExtKeyToMe, null);
  2601. $aObjSet[] = $oLink;
  2602. $bModified = true;
  2603. }
  2604. }
  2605. }
  2606. if ($bModified)
  2607. {
  2608. $oNewSet = DBObjectSet::FromArray($oLinkset->GetClass(), $aObjSet);
  2609. $this->Set($sAttCode, $oNewSet);
  2610. }
  2611. }
  2612. else
  2613. {
  2614. if (!is_null($value))
  2615. {
  2616. $aAttributes[$sAttCode] = trim($value);
  2617. $previousValue = $this->Get($sAttCode);
  2618. if ($previousValue !== $aAttributes[$sAttCode])
  2619. {
  2620. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  2621. }
  2622. }
  2623. }
  2624. }
  2625. }
  2626. /**
  2627. * Updates the object from the POSTed parameters (form)
  2628. */
  2629. public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $sTargetState = '')
  2630. {
  2631. if (is_null($aAttList))
  2632. {
  2633. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2634. }
  2635. $aValues = array();
  2636. foreach($aAttList as $sAttCode)
  2637. {
  2638. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2639. if ($oAttDef->GetEditClass() == 'Document')
  2640. {
  2641. $value = array('fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'));
  2642. }
  2643. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() &&
  2644. (($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE) || ($oAttDef->GetEditMode() == LINKSET_EDITMODE_ADDREMOVE)) )
  2645. {
  2646. $aRawToBeCreated = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbc", '{}', 'raw_data'), true);
  2647. $aToBeCreated = array();
  2648. foreach($aRawToBeCreated as $aData)
  2649. {
  2650. $sSubFormPrefix = $aData['formPrefix'];
  2651. $sObjClass = $aData['class'];
  2652. $aObjData = array();
  2653. foreach($aData as $sKey => $value)
  2654. {
  2655. if (preg_match("/^attr_$sSubFormPrefix(.*)$/", $sKey, $aMatches))
  2656. {
  2657. $aObjData[$aMatches[1]] = $value;
  2658. }
  2659. }
  2660. $aToBeCreated[] = array('class' => $sObjClass, 'data' => $aObjData);
  2661. }
  2662. $value = array('to_be_created' => $aToBeCreated,
  2663. 'to_be_deleted' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbd", '[]', 'raw_data'), true),
  2664. 'to_be_added' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tba", '[]', 'raw_data'), true),
  2665. 'to_be_removed' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbr", '[]', 'raw_data'), true) );
  2666. }
  2667. else
  2668. {
  2669. $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data');
  2670. }
  2671. if (!is_null($value))
  2672. {
  2673. $aValues[$sAttCode] = $value;
  2674. }
  2675. }
  2676. $aErrors = array();
  2677. $aFinalValues = array();
  2678. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2679. {
  2680. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2681. }
  2682. $this->UpdateObjectFromArray($aFinalValues);
  2683. // Invoke extensions after the update of the object from the form
  2684. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2685. {
  2686. $oExtensionInstance->OnFormSubmit($this, $sFormPrefix);
  2687. }
  2688. return $aErrors;
  2689. }
  2690. /**
  2691. * Updates the object from a given page argument
  2692. */
  2693. public function UpdateObjectFromArg($sArgName, $aAttList = null, $sTargetState = '')
  2694. {
  2695. if (is_null($aAttList))
  2696. {
  2697. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2698. }
  2699. $aRawValues = utils::ReadParam($sArgName, array(), '', 'raw_data');
  2700. $aValues = array();
  2701. foreach($aAttList as $sAttCode)
  2702. {
  2703. if (isset($aRawValues[$sAttCode]))
  2704. {
  2705. $aValues[$sAttCode] = $aRawValues[$sAttCode];
  2706. }
  2707. }
  2708. $aErrors = array();
  2709. $aFinalValues = array();
  2710. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2711. {
  2712. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2713. }
  2714. $this->UpdateObjectFromArray($aFinalValues);
  2715. return $aErrors;
  2716. }
  2717. public function DBInsertNoReload()
  2718. {
  2719. $res = parent::DBInsertNoReload();
  2720. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2721. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2722. {
  2723. $oExtensionInstance->OnDBInsert($this, self::GetCurrentChange());
  2724. }
  2725. return $res;
  2726. }
  2727. protected function DBCloneTracked_Internal($newKey = null)
  2728. {
  2729. $oNewObj = parent::DBCloneTracked_Internal($newKey);
  2730. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2731. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2732. {
  2733. $oExtensionInstance->OnDBInsert($oNewObj, self::GetCurrentChange());
  2734. }
  2735. return $oNewObj;
  2736. }
  2737. public function DBUpdate()
  2738. {
  2739. $res = parent::DBUpdate();
  2740. // Invoke extensions after the update (could be before)
  2741. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2742. {
  2743. $oExtensionInstance->OnDBUpdate($this, self::GetCurrentChange());
  2744. }
  2745. return $res;
  2746. }
  2747. protected static function BulkUpdateTracked_Internal(DBObjectSearch $oFilter, array $aValues)
  2748. {
  2749. // Todo - invoke the extension
  2750. return parent::BulkUpdateTracked_Internal($oFilter, $aValues);
  2751. }
  2752. protected function DBDeleteTracked_Internal(&$oDeletionPlan = null)
  2753. {
  2754. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2755. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2756. {
  2757. $oExtensionInstance->OnDBDelete($this, self::GetCurrentChange());
  2758. }
  2759. return parent::DBDeleteTracked_Internal($oDeletionPlan);
  2760. }
  2761. public function IsModified()
  2762. {
  2763. if (parent::IsModified())
  2764. {
  2765. return true;
  2766. }
  2767. // Plugins
  2768. //
  2769. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2770. {
  2771. if ($oExtensionInstance->OnIsModified($this))
  2772. {
  2773. return true;
  2774. }
  2775. }
  2776. return false;
  2777. }
  2778. public function DoCheckToWrite()
  2779. {
  2780. parent::DoCheckToWrite();
  2781. // Plugins
  2782. //
  2783. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2784. {
  2785. $aNewIssues = $oExtensionInstance->OnCheckToWrite($this);
  2786. if (count($aNewIssues) > 0)
  2787. {
  2788. $this->m_aCheckIssues = array_merge($this->m_aCheckIssues, $aNewIssues);
  2789. }
  2790. }
  2791. // User rights
  2792. //
  2793. $aChanges = $this->ListChanges();
  2794. if (count($aChanges) > 0)
  2795. {
  2796. $aForbiddenFields = array();
  2797. foreach ($this->ListChanges() as $sAttCode => $value)
  2798. {
  2799. $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute(get_class($this), $sAttCode, UR_ACTION_MODIFY, DBObjectSet::FromObject($this));
  2800. if (!$bUpdateAllowed)
  2801. {
  2802. $oAttCode = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2803. $aForbiddenFields[] = $oAttCode->GetLabel();
  2804. }
  2805. }
  2806. if (count($aForbiddenFields) > 0)
  2807. {
  2808. // Security issue
  2809. $this->m_bSecurityIssue = true;
  2810. $this->m_aCheckIssues[] = Dict::Format('UI:Delete:NotAllowedToUpdate_Fields',implode(', ', $aForbiddenFields));
  2811. }
  2812. }
  2813. }
  2814. protected function DoCheckToDelete(&$oDeletionPlan)
  2815. {
  2816. parent::DoCheckToDelete($oDeletionPlan);
  2817. // Plugins
  2818. //
  2819. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2820. {
  2821. $aNewIssues = $oExtensionInstance->OnCheckToDelete($this);
  2822. if (count($aNewIssues) > 0)
  2823. {
  2824. $this->m_aDeleteIssues = array_merge($this->m_aDeleteIssues, $aNewIssues);
  2825. }
  2826. }
  2827. // User rights
  2828. //
  2829. $bDeleteAllowed = UserRights::IsActionAllowed(get_class($this), UR_ACTION_DELETE, DBObjectSet::FromObject($this));
  2830. if (!$bDeleteAllowed)
  2831. {
  2832. // Security issue
  2833. $this->m_bSecurityIssue = true;
  2834. $this->m_aDeleteIssues[] = Dict::S('UI:Delete:NotAllowedToDelete');
  2835. }
  2836. }
  2837. /**
  2838. * Special display where the case log uses the whole "screen" at the bottom of the "Properties" tab
  2839. */
  2840. public function DisplayCaseLog(WebPage $oPage, $sAttCode, $sComment = '', $sPrefix = '', $bEditMode = false)
  2841. {
  2842. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  2843. $sClass = get_class($this);
  2844. if ($this->IsNew())
  2845. {
  2846. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2847. }
  2848. else
  2849. {
  2850. $iFlags = $this->GetAttributeFlags($sAttCode);
  2851. }
  2852. if ( $iFlags & OPT_ATT_HIDDEN)
  2853. {
  2854. // The case log is hidden do nothing
  2855. }
  2856. else
  2857. {
  2858. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2859. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  2860. if ((!$bEditMode) || ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE)))
  2861. {
  2862. // Check if the attribute is not read-only because of a synchro...
  2863. $aReasons = array();
  2864. $sSynchroIcon = '';
  2865. if ($iFlags & OPT_ATT_SLAVE)
  2866. {
  2867. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  2868. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  2869. $sTip = '';
  2870. foreach($aReasons as $aRow)
  2871. {
  2872. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  2873. }
  2874. $sTip = addslashes($sTip);
  2875. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  2876. }
  2877. // Attribute is read-only
  2878. $sHTMLValue = $this->GetAsHTML($sAttCode);
  2879. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>';
  2880. $aFieldsMap[$sAttCode] = $sInputId;
  2881. $sComment .= $sSynchroIcon;
  2882. }
  2883. else
  2884. {
  2885. $sValue = $this->Get($sAttCode);
  2886. $sDisplayValue = $this->GetEditValue($sAttCode);
  2887. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  2888. $sHTMLValue = '';
  2889. if ($sComment != '')
  2890. {
  2891. $sHTMLValue = '<span>'.$sComment.'</span><br/>';
  2892. }
  2893. $sHTMLValue .= "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  2894. $aFieldsMap[$sAttCode] = $sInputId;
  2895. }
  2896. //$aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  2897. $oPage->add('<fieldset><legend>'.$oAttDef->GetLabel().'</legend>');
  2898. $oPage->add($sHTMLValue);
  2899. $oPage->add('</fieldset>');
  2900. }
  2901. }
  2902. public function GetExpectedAttributes($sCurrentState, $sStimulus, $bOnlyNewOnes)
  2903. {
  2904. $aTransitions = $this->EnumTransitions();
  2905. $aStimuli = MetaModel::EnumStimuli(get_class($this));
  2906. if (!isset($aTransitions[$sStimulus]))
  2907. {
  2908. // Invalid stimulus
  2909. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus,$this->GetName(),$this->GetStateLabel()));
  2910. }
  2911. $aTransition = $aTransitions[$sStimulus];
  2912. $sTargetState = $aTransition['target_state'];
  2913. $aTargetStates = MetaModel::EnumStates(get_class($this));
  2914. $aTargetState = $aTargetStates[$sTargetState];
  2915. $aCurrentState = $aTargetStates[$this->GetState()];
  2916. $aExpectedAttributes = $aTargetState['attribute_list'];
  2917. $aCurrentAttributes = $aCurrentState['attribute_list'];
  2918. $aComputedAttributes = array();
  2919. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  2920. {
  2921. if (!array_key_exists($sAttCode, $aCurrentAttributes))
  2922. {
  2923. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2924. }
  2925. else
  2926. {
  2927. if ( !($aCurrentAttributes[$sAttCode] & (OPT_ATT_HIDDEN|OPT_ATT_READONLY)) )
  2928. {
  2929. $iExpectCode = $iExpectCode & ~(OPT_ATT_MUSTPROMPT|OPT_ATT_MUSTCHANGE); // Already prompted/changed, reset the flags
  2930. }
  2931. //TODO: better check if the attribute is not *null*
  2932. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($this->Get($sAttCode) != ''))
  2933. {
  2934. $iExpectCode = $iExpectCode & ~(OPT_ATT_MANDATORY); // If the attribute is present, then no need to request its presence
  2935. }
  2936. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2937. }
  2938. $aComputedAttributes[$sAttCode] = $aComputedAttributes[$sAttCode] & ~(OPT_ATT_READONLY|OPT_ATT_HIDDEN); // Don't care about this form now
  2939. if ($aComputedAttributes[$sAttCode] == 0)
  2940. {
  2941. unset($aComputedAttributes[$sAttCode]);
  2942. }
  2943. }
  2944. return $aComputedAttributes;
  2945. }
  2946. /**
  2947. * Display a form for modifying several objects at once
  2948. * The form will be submitted to the current page, with the specified additional values
  2949. */
  2950. public static function DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, $sCustomOperation, $sCancelUrl, $aExcludeAttributes = array(), $aContextData = array())
  2951. {
  2952. if (count($aSelectedObj) > 0)
  2953. {
  2954. $iAllowedCount = count($aSelectedObj);
  2955. $sSelectedObj = implode(',', $aSelectedObj);
  2956. $sOQL = "SELECT $sClass WHERE id IN (".$sSelectedObj.")";
  2957. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2958. // Compute the distribution of the values for each field to determine which of the "scalar" fields are homogenous
  2959. $aList = MetaModel::ListAttributeDefs($sClass);
  2960. $aValues = array();
  2961. foreach($aList as $sAttCode => $oAttDef)
  2962. {
  2963. if ($oAttDef->IsScalar())
  2964. {
  2965. $aValues[$sAttCode] = array();
  2966. }
  2967. }
  2968. while($oObj = $oSet->Fetch())
  2969. {
  2970. foreach($aList as $sAttCode => $oAttDef)
  2971. {
  2972. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  2973. {
  2974. $currValue = $oObj->Get($sAttCode);
  2975. if ($oAttDef instanceof AttributeCaseLog)
  2976. {
  2977. $currValue = ' '; // Don't put an empty string, in case the field would be considered as mandatory...
  2978. }
  2979. if (is_object($currValue)) continue; // Skip non scalar values...
  2980. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  2981. {
  2982. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  2983. }
  2984. else
  2985. {
  2986. $aValues[$sAttCode][$currValue]['count']++;
  2987. }
  2988. }
  2989. }
  2990. }
  2991. // Now create an object that has values for the homogenous values only
  2992. $oDummyObj = new $sClass(); // @@ What if the class is abstract ?
  2993. $aComments = array();
  2994. function MyComparison($a, $b) // Sort descending
  2995. {
  2996. if ($a['count'] == $b['count'])
  2997. {
  2998. return 0;
  2999. }
  3000. return ($a['count'] > $b['count']) ? -1 : 1;
  3001. }
  3002. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  3003. $sReadyScript = '';
  3004. $aDependsOn = array();
  3005. $sFormPrefix = '2_';
  3006. foreach($aList as $sAttCode => $oAttDef)
  3007. {
  3008. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  3009. if (count($aPrerequisites) > 0)
  3010. {
  3011. // When 'enabling' a field, all its prerequisites must be enabled too
  3012. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
  3013. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  3014. }
  3015. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  3016. if (count($aDependents) > 0)
  3017. {
  3018. // When 'disabling' a field, all its dependent fields must be disabled too
  3019. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
  3020. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  3021. }
  3022. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  3023. {
  3024. if ($oAttDef->GetEditClass() == 'One Way Password')
  3025. {
  3026. $sTip = "Unknown values";
  3027. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  3028. $oDummyObj->Set($sAttCode, null);
  3029. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  3030. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'"> ? </div>';
  3031. $sReadyScript .= 'ToogleField(false, \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  3032. }
  3033. else
  3034. {
  3035. $iCount = count($aValues[$sAttCode]);
  3036. if ($iCount == 1)
  3037. {
  3038. // Homogenous value
  3039. reset($aValues[$sAttCode]);
  3040. $aKeys = array_keys($aValues[$sAttCode]);
  3041. $currValue = $aKeys[0]; // The only value is the first key
  3042. //echo "<p>current value for $sAttCode : $currValue</p>";
  3043. $oDummyObj->Set($sAttCode, $currValue);
  3044. $aComments[$sAttCode] = '<input type="checkbox" checked id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  3045. $aComments[$sAttCode] .= '<div class="mono_value">1</div>';
  3046. }
  3047. else
  3048. {
  3049. // Non-homogenous value
  3050. $aMultiValues = $aValues[$sAttCode];
  3051. uasort($aMultiValues, 'MyComparison');
  3052. $iMaxCount = 5;
  3053. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."</b><ul>";
  3054. $index = 0;
  3055. foreach($aMultiValues as $sCurrValue => $aVal)
  3056. {
  3057. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  3058. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  3059. $index++;
  3060. if ($iMaxCount == $index)
  3061. {
  3062. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aMultiValues) - $iMaxCount)."</li>";
  3063. break;
  3064. }
  3065. }
  3066. $sTip .= "</ul></p>";
  3067. $sTip = addslashes($sTip);
  3068. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  3069. $oDummyObj->Set($sAttCode, null);
  3070. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  3071. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.$iCount.'</div>';
  3072. }
  3073. $sReadyScript .= 'ToogleField('.(($iCount == 1) ? 'true': 'false').', \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  3074. }
  3075. }
  3076. }
  3077. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  3078. if (($sStateAttCode != '') && ($oDummyObj->GetState() == ''))
  3079. {
  3080. // Hmmm, it's not gonna work like this ! Set a default value for the "state"
  3081. // Maybe we should use the "state" that is the most common among the objects...
  3082. $aMultiValues = $aValues[$sStateAttCode];
  3083. uasort($aMultiValues, 'MyComparison');
  3084. foreach($aMultiValues as $sCurrValue => $aVal)
  3085. {
  3086. $oDummyObj->Set($sStateAttCode, $sCurrValue);
  3087. break;
  3088. }
  3089. //$oStateAtt = MetaModel::GetAttributeDef($sClass, $sStateAttCode);
  3090. //$oDummyObj->Set($sStateAttCode, $oStateAtt->GetDefaultValue());
  3091. }
  3092. $oP->add("<div class=\"page_header\">\n");
  3093. $oP->add("<h1>".$oDummyObj->GetIcon()."&nbsp;".Dict::Format('UI:Modify_M_ObjectsOf_Class_OutOf_N', $iAllowedCount, $sClass, $iAllowedCount)."</h1>\n");
  3094. $oP->add("</div>\n");
  3095. $oP->add("<div class=\"wizContainer\">\n");
  3096. $sDisableFields = json_encode($aExcludeAttributes);
  3097. $aParams = array
  3098. (
  3099. 'fieldsComments' => $aComments,
  3100. 'noRelations' => true,
  3101. 'custom_operation' => $sCustomOperation,
  3102. 'custom_button' => Dict::S('UI:Button:PreviewModifications'),
  3103. 'selectObj' => $sSelectedObj,
  3104. 'preview_mode' => true,
  3105. 'disabled_fields' => $sDisableFields,
  3106. 'disable_plugins' => true
  3107. );
  3108. $aParams = $aParams + $aContextData; // merge keeping associations
  3109. $oDummyObj->DisplayModifyForm($oP, $aParams);
  3110. $oP->add("</div>\n");
  3111. $oP->add_ready_script($sReadyScript);
  3112. $oP->add_ready_script(
  3113. <<<EOF
  3114. $('.wizContainer button.cancel').unbind('click');
  3115. $('.wizContainer button.cancel').click( function() { window.location.href = '$sCancelUrl'; } );
  3116. EOF
  3117. );
  3118. } // Else no object selected ???
  3119. else
  3120. {
  3121. $oP->p("No object selected !, nothing to do");
  3122. }
  3123. }
  3124. /**
  3125. * Process the reply made from a form built with DisplayBulkModifyForm
  3126. */
  3127. public static function DoBulkModify($oP, $sClass, $aSelectedObj, $sCustomOperation, $bPreview, $sCancelUrl, $aContextData = array())
  3128. {
  3129. $aHeaders = array(
  3130. 'form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')),
  3131. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  3132. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  3133. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  3134. );
  3135. $aRows = array();
  3136. $oP->add("<div class=\"page_header\">\n");
  3137. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), MetaModel::GetName($sClass))."</h1>\n");
  3138. $oP->add("</div>\n");
  3139. $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass));
  3140. if (!$bPreview)
  3141. {
  3142. // Not in preview mode, do the update for real
  3143. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  3144. if (!utils::IsTransactionValid($sTransactionId, false))
  3145. {
  3146. throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  3147. }
  3148. utils::RemoveTransaction($sTransactionId);
  3149. }
  3150. $iPreviousTimeLimit = ini_get('max_execution_time');
  3151. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  3152. foreach($aSelectedObj as $iId)
  3153. {
  3154. set_time_limit($iLoopTimeLimit);
  3155. $oObj = MetaModel::GetObject($sClass, $iId);
  3156. $aErrors = $oObj->UpdateObjectFromPostedForm('');
  3157. $bResult = (count($aErrors) == 0);
  3158. if ($bResult)
  3159. {
  3160. list($bResult, $aErrors) = $oObj->CheckToWrite(true /* Enforce Read-only fields */);
  3161. }
  3162. if ($bPreview)
  3163. {
  3164. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError');
  3165. }
  3166. else
  3167. {
  3168. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  3169. }
  3170. $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL;
  3171. $sChecked = $bResult ? 'checked' : '';
  3172. $sDisabled = $bResult ? '' : 'disabled';
  3173. $aRows[] = array(
  3174. 'form::select' => "<input type=\"checkbox\" class=\"selectList\" $sChecked $sDisabled\"></input>",
  3175. 'object' => $oObj->GetHyperlink(),
  3176. 'status' => $sStatus,
  3177. 'errors' => '<p>'.($bResult ? '': implode('</p><p>', $aErrors)).'</p>',
  3178. '@class' => $sCSSClass,
  3179. );
  3180. if ($bResult && (!$bPreview))
  3181. {
  3182. $oObj->DBUpdate();
  3183. }
  3184. }
  3185. set_time_limit($iPreviousTimeLimit);
  3186. $oP->Table($aHeaders, $aRows);
  3187. if ($bPreview)
  3188. {
  3189. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  3190. // Form to submit:
  3191. $oP->add("<form method=\"post\" action=\"$sFormAction\" enctype=\"multipart/form-data\">\n");
  3192. $aDefaults = utils::ReadParam('default', array());
  3193. $oAppContext = new ApplicationContext();
  3194. $oP->add($oAppContext->GetForForm());
  3195. foreach ($aContextData as $sKey => $value)
  3196. {
  3197. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  3198. }
  3199. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  3200. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  3201. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n");
  3202. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  3203. $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='$sCancelUrl'\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  3204. $oP->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:ModifyAll')."</span></button>\n");
  3205. foreach($_POST as $sKey => $value)
  3206. {
  3207. if (preg_match('/attr_(.+)/', $sKey, $aMatches))
  3208. {
  3209. // Beware: some values (like durations) are passed as arrays
  3210. if (is_array($value))
  3211. {
  3212. foreach($value as $vKey => $vValue)
  3213. {
  3214. $oP->add("<input type=\"hidden\" name=\"{$sKey}[$vKey]\" value=\"".htmlentities($vValue, ENT_QUOTES, 'UTF-8')."\">\n");
  3215. }
  3216. }
  3217. else
  3218. {
  3219. $oP->add("<input type=\"hidden\" name=\"$sKey\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\">\n");
  3220. }
  3221. }
  3222. }
  3223. $oP->add("</form>\n");
  3224. }
  3225. else
  3226. {
  3227. $oP->add("<button type=\"button\" onClick=\"window.location.href='$sCancelUrl'\" class=\"action\"><span>".Dict::S('UI:Button:Done')."</span></button>\n");
  3228. }
  3229. }
  3230. /**
  3231. * Perform all the needed checks to delete one (or more) objects
  3232. */
  3233. public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = array())
  3234. {
  3235. $oDeletionPlan = new DeletionPlan();
  3236. foreach($aObjects as $oObj)
  3237. {
  3238. if ($bPreview)
  3239. {
  3240. $oObj->CheckToDelete($oDeletionPlan);
  3241. }
  3242. else
  3243. {
  3244. $oObj->DBDeleteTracked(CMDBObject::GetCurrentChange(), null, $oDeletionPlan);
  3245. }
  3246. }
  3247. if ($bPreview)
  3248. {
  3249. if (count($aObjects) == 1)
  3250. {
  3251. $oObj = $aObjects[0];
  3252. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName())."</h1>\n");
  3253. }
  3254. else
  3255. {
  3256. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3257. }
  3258. // Explain what should be done
  3259. //
  3260. $aDisplayData = array();
  3261. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3262. {
  3263. foreach ($aDeletes as $iId => $aData)
  3264. {
  3265. $oToDelete = $aData['to_delete'];
  3266. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  3267. if (array_key_exists('issue', $aData))
  3268. {
  3269. if ($bAutoDel)
  3270. {
  3271. if (isset($aData['requested_explicitely']))
  3272. {
  3273. $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']);
  3274. }
  3275. else
  3276. {
  3277. $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']);
  3278. }
  3279. }
  3280. else
  3281. {
  3282. $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']);
  3283. }
  3284. }
  3285. else
  3286. {
  3287. if ($bAutoDel)
  3288. {
  3289. if (isset($aData['requested_explicitely']))
  3290. {
  3291. $sConsequence = ''; // not applicable
  3292. }
  3293. else
  3294. {
  3295. $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically');
  3296. }
  3297. }
  3298. else
  3299. {
  3300. $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually');
  3301. }
  3302. }
  3303. $aDisplayData[] = array(
  3304. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3305. 'object' => $oToDelete->GetHyperLink(),
  3306. 'consequence' => $sConsequence,
  3307. );
  3308. }
  3309. }
  3310. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  3311. {
  3312. foreach ($aToUpdate as $iId => $aData)
  3313. {
  3314. $oToUpdate = $aData['to_reset'];
  3315. if (array_key_exists('issue', $aData))
  3316. {
  3317. $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']);
  3318. }
  3319. else
  3320. {
  3321. $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']);
  3322. }
  3323. $aDisplayData[] = array(
  3324. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3325. 'object' => $oToUpdate->GetHyperLink(),
  3326. 'consequence' => $sConsequence,
  3327. );
  3328. }
  3329. }
  3330. $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects);
  3331. if ($iImpactedIndirectly > 0)
  3332. {
  3333. if (count($aObjects) == 1)
  3334. {
  3335. $oObj = $aObjects[0];
  3336. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName()));
  3337. }
  3338. else
  3339. {
  3340. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly));
  3341. }
  3342. $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'));
  3343. }
  3344. if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper())
  3345. {
  3346. $aDisplayConfig = array();
  3347. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3348. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3349. $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'));
  3350. $oP->table($aDisplayConfig, $aDisplayData);
  3351. }
  3352. if ($oDeletionPlan->FoundStopper())
  3353. {
  3354. if ($oDeletionPlan->FoundSecurityIssue())
  3355. {
  3356. $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed'));
  3357. }
  3358. elseif ($oDeletionPlan->FoundManualOperation())
  3359. {
  3360. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3361. }
  3362. else // $bFoundManualOp
  3363. {
  3364. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3365. }
  3366. $oAppContext = new ApplicationContext();
  3367. $oP->add("<form method=\"post\">\n");
  3368. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  3369. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3370. $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3371. $oP->add($oAppContext->GetForForm());
  3372. $oP->add("</form>\n");
  3373. }
  3374. else
  3375. {
  3376. if (count($aObjects) == 1)
  3377. {
  3378. $oObj = $aObjects[0];
  3379. $id = $oObj->GetKey();
  3380. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()).'</h1>');
  3381. }
  3382. else
  3383. {
  3384. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)).'</h1>');
  3385. }
  3386. foreach($aObjects as $oObj)
  3387. {
  3388. $aKeys[] = $oObj->GetKey();
  3389. }
  3390. $oFilter = new DBObjectSearch($sClass);
  3391. $oFilter->AddCondition('id', $aKeys, 'IN');
  3392. $oSet = new CMDBobjectSet($oFilter);
  3393. $oP->add('<div id="0">');
  3394. CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false));
  3395. $oP->add("</div>\n");
  3396. $oP->add("<form method=\"post\">\n");
  3397. foreach ($aContextData as $sKey => $value)
  3398. {
  3399. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  3400. }
  3401. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  3402. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  3403. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  3404. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  3405. foreach($aObjects as $oObj)
  3406. {
  3407. $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\">\n");
  3408. }
  3409. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3410. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3411. $oAppContext = new ApplicationContext();
  3412. $oP->add($oAppContext->GetForForm());
  3413. $oP->add("</form>\n");
  3414. }
  3415. }
  3416. else // if ($bPreview)...
  3417. {
  3418. // Execute the deletion
  3419. //
  3420. if (count($aObjects) == 1)
  3421. {
  3422. $oObj = $aObjects[0];
  3423. $oP->add("<h1>".Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName())."</h1>\n");
  3424. }
  3425. else
  3426. {
  3427. $oP->add("<h1>".Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3428. }
  3429. // Security - do not allow the user to force a forbidden delete by the mean of page arguments...
  3430. if ($oDeletionPlan->FoundSecurityIssue())
  3431. {
  3432. throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete'));
  3433. }
  3434. if ($oDeletionPlan->FoundManualOperation())
  3435. {
  3436. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded'));
  3437. }
  3438. if ($oDeletionPlan->FoundManualDelete())
  3439. {
  3440. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies'));
  3441. }
  3442. // Report deletions
  3443. //
  3444. $aDisplayData = array();
  3445. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3446. {
  3447. foreach ($aDeletes as $iId => $aData)
  3448. {
  3449. $oToDelete = $aData['to_delete'];
  3450. if (isset($aData['requested_explicitely']))
  3451. {
  3452. $sMessage = Dict::S('UI:Delete:Deleted');
  3453. }
  3454. else
  3455. {
  3456. $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted');
  3457. }
  3458. $aDisplayData[] = array(
  3459. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3460. 'object' => $oToDelete->GetName(),
  3461. 'consequence' => $sMessage,
  3462. );
  3463. }
  3464. }
  3465. // Report updates
  3466. //
  3467. foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate)
  3468. {
  3469. foreach ($aToUpdate as $iId => $aData)
  3470. {
  3471. $oToUpdate = $aData['to_reset'];
  3472. $aDisplayData[] = array(
  3473. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3474. 'object' => $oToUpdate->GetHyperLink(),
  3475. 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']),
  3476. );
  3477. }
  3478. }
  3479. // Report automatic jobs
  3480. //
  3481. if ($oDeletionPlan->GetTargetCount() > 0)
  3482. {
  3483. if (count($aObjects) == 1)
  3484. {
  3485. $oObj = $aObjects[0];
  3486. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()));
  3487. }
  3488. else
  3489. {
  3490. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)));
  3491. }
  3492. $aDisplayConfig = array();
  3493. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3494. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3495. $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+'));
  3496. $oP->table($aDisplayConfig, $aDisplayData);
  3497. }
  3498. }
  3499. }
  3500. }
  3501. ?>