cmdbabstract.class.inc.php 127 KB

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