cmdbabstract.class.inc.php 129 KB

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