cmdbabstract.class.inc.php 127 KB

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