cmdbabstract.class.inc.php 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Abstract class that implements some common and useful methods for displaying
  18. * the objects
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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.passwordwidget.class.inc.php');
  36. require_once(APPROOT.'/application/ui.extkeywidget.class.inc.php');
  37. require_once(APPROOT.'/application/ui.htmleditorwidget.class.inc.php');
  38. /**
  39. * All objects to be displayed in the application (either as a list or as details)
  40. * must implement this interface.
  41. */
  42. interface iDisplay
  43. {
  44. /**
  45. * Maps the given context parameter name to the appropriate filter/search code for this class
  46. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  47. * @return string Filter code, i.e. 'customer_id'
  48. */
  49. public static function MapContextParam($sContextParam);
  50. /**
  51. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  52. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  53. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  54. * To Be overridden by derived classes
  55. * @param void
  56. * @return String The desired higlight class for the object/row
  57. */
  58. public function GetHilightClass();
  59. /**
  60. * Returns the relative path to the page that handles the display of the object
  61. * @return string
  62. */
  63. public static function GetUIPage();
  64. /**
  65. * Displays the details of the object
  66. */
  67. public function DisplayDetails(WebPage $oPage, $bEditMode = false);
  68. }
  69. abstract class cmdbAbstractObject extends CMDBObject implements iDisplay
  70. {
  71. protected $m_iFormId; // The ID of the form used to edit the object (when in edition mode !)
  72. static $iGlobalFormId = 1;
  73. /**
  74. * returns what will be the next ID for the forms
  75. */
  76. public static function GetNextFormId()
  77. {
  78. return 1 + self::$iGlobalFormId;
  79. }
  80. public static function GetUIPage()
  81. {
  82. return 'UI.php';
  83. }
  84. function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
  85. {
  86. // Standard Header with name, actions menu and history block
  87. //
  88. // action menu
  89. $oSingletonFilter = new DBObjectSearch(get_class($this));
  90. $oSingletonFilter->AddCondition('id', $this->GetKey(), '=');
  91. $oBlock = new MenuBlock($oSingletonFilter, 'popup', false);
  92. $oBlock->Display($oPage, -1);
  93. // Master data sources
  94. $sSynchroIcon = '';
  95. $oReplicaSet = $this->GetMasterReplica();
  96. $bSynchronized = false;
  97. $oCreatorTask = null;
  98. $bCanBeDeletedByTask = false;
  99. $bCanBeDeletedByUser = true;
  100. $aMasterSources = array();
  101. if ($oReplicaSet->Count() > 0)
  102. {
  103. $bSynchronized = true;
  104. while($aData = $oReplicaSet->FetchAssoc())
  105. {
  106. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  107. $sApplicationURL = $aData['datasource']->GetApplicationUrl($this, $aData['replica']);
  108. $sLink = $aData['datasource']->GetName();
  109. if (!empty($sApplicationURL))
  110. {
  111. $sLink = "<a href=\"$sApplicationURL\" target=\"_blank\">".$aData['datasource']->GetName()."</a>";
  112. }
  113. if ($aData['replica']->Get('status_dest_creator') == 1)
  114. {
  115. $oCreatorTask = $aData['datasource'];
  116. $bCreatedByTask = true;
  117. }
  118. else
  119. {
  120. $bCreatedByTask = false;
  121. }
  122. if ($bCreatedByTask)
  123. {
  124. $sDeletePolicy = $aData['datasource']->Get('delete_policy');
  125. if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete'))
  126. {
  127. $bCanBeDeletedByTask = true;
  128. }
  129. $sUserDeletePolicy = $aData['datasource']->Get('user_delete_policy');
  130. if ($sUserDeletePolicy == 'nobody')
  131. {
  132. $bCanBeDeletedByUser = false;
  133. }
  134. elseif (($sUserDeletePolicy == 'administrators') && !UserRights::IsAdministrator())
  135. {
  136. $bCanBeDeletedByUser = false;
  137. }
  138. else // everybody...
  139. {
  140. }
  141. }
  142. $aMasterSources[$aData['datasource']->GetKey()]['datasource'] = $aData['datasource'];
  143. $aMasterSources[$aData['datasource']->GetKey()]['url'] = $sLink;
  144. $aMasterSources[$aData['datasource']->GetKey()]['last_synchro'] = $aData['replica']->Get('status_last_seen');
  145. }
  146. if (is_object($oCreatorTask))
  147. {
  148. $sTaskUrl = $aMasterSources[$oCreatorTask->GetKey()]['url'];
  149. if (!$bCanBeDeletedByUser)
  150. {
  151. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sTaskUrl)."</p>";
  152. }
  153. else
  154. {
  155. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectWasCreatedBy_Source', $sTaskUrl)."</p>";
  156. }
  157. if ($bCanBeDeletedByTask)
  158. {
  159. $sTip .= "<p>".Dict::Format('Core:Synchro:TheObjectCanBeDeletedBy_Source', $sTaskUrl)."</p>";
  160. }
  161. }
  162. else
  163. {
  164. $sTip = "<p>".Dict::S('Core:Synchro:ThisObjectIsSynchronized')."</p>";
  165. }
  166. $sTip .= "<p><b>".Dict::S('Core:Synchro:ListOfDataSources')."</b></p>";
  167. foreach($aMasterSources as $aStruct)
  168. {
  169. $oDataSource = $aStruct['datasource'];
  170. $sLink = $aStruct['url'];
  171. $sTip .= "<p style=\"white-space:nowrap\">".$oDataSource->GetIcon(true, 'style="vertical-align:middle"')."&nbsp;$sLink<br/>";
  172. $sTip .= Dict::S('Core:Synchro:LastSynchro').'<br/>'.$aStruct['last_synchro']."</p>";
  173. }
  174. $sSynchroIcon = '&nbsp;<img style="vertical-align:middle;" id="synchro_icon" src="../images/locked.png"/>';
  175. $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' }} } );");
  176. }
  177. $oPage->add("<div class=\"page_header\"><h1>".$this->GetIcon()."&nbsp;\n");
  178. $oPage->add(MetaModel::GetName(get_class($this)).": <span class=\"hilite\">".$this->GetName()."</span>$sSynchroIcon</h1>\n");
  179. $oPage->add("</div>\n");
  180. }
  181. function DisplayBareHistory(WebPage $oPage, $bEditMode = false)
  182. {
  183. // history block (with as a tab)
  184. $oHistoryFilter = new DBObjectSearch('CMDBChangeOp');
  185. $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '=');
  186. $oHistoryFilter->AddCondition('objclass', get_class($this), '=');
  187. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  188. $oBlock->Display($oPage, -1);
  189. }
  190. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  191. {
  192. $aFieldsMap = $this->GetBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams);
  193. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  194. {
  195. $oExtensionInstance->OnDisplayProperties($this, $oPage, $bEditMode);
  196. }
  197. // Special case to display the case log, if any...
  198. // WARNING: if you modify the loop below, also check the corresponding code in UpdateObject and DisplayModifyForm
  199. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  200. {
  201. if ($oAttDef instanceof AttributeCaseLog)
  202. {
  203. $sComment = (isset($aExtraParams['fieldsComments'][$sAttCode])) ? $aExtraParams['fieldsComments'][$sAttCode] : '';
  204. $this->DisplayCaseLog($oPage, $sAttCode, $sComment, $sPrefix, $bEditMode);
  205. }
  206. }
  207. return $aFieldsMap;
  208. }
  209. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  210. {
  211. // Related objects: display all the linkset attributes, each as a separate tab
  212. // In the order described by the 'display' ZList
  213. $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  214. if (count($aList) == 0)
  215. {
  216. // Empty ZList defined, display all the linkedset attributes defined
  217. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  218. }
  219. $sClass = get_class($this);
  220. foreach($aList as $sAttCode)
  221. {
  222. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  223. // Display mode
  224. if (!$oAttDef->IsLinkset()) continue; // Process only linkset attributes...
  225. $oSet = new DBObjectSet($this->Get($sAttCode)->GetFilter());
  226. $iCount = $oSet->Count();
  227. $sCount = '';
  228. if ($iCount != 0)
  229. {
  230. $sCount = " ($iCount)";
  231. }
  232. $oPage->SetCurrentTab($oAttDef->GetLabel().$sCount);
  233. if ($this->IsNew())
  234. {
  235. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  236. }
  237. else
  238. {
  239. $iFlags = $this->GetAttributeFlags($sAttCode);
  240. }
  241. $bReadOnly = ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE));
  242. if ($bEditMode && (!$bReadOnly))
  243. {
  244. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  245. if (get_class($oAttDef) == 'AttributeLinkedSet')
  246. {
  247. // 1:n links
  248. $sTargetClass = $oAttDef->GetLinkedClass();
  249. if ($this->IsNew())
  250. {
  251. $oPage->p(Dict::Format('UI:BeforeAdding_Class_ObjectsSaveThisObject', MetaModel::GetName($sTargetClass)));
  252. }
  253. else
  254. {
  255. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  256. $oFilter = new DBObjectSearch($sTargetClass);
  257. $oFilter->AddCondition($oAttDef->GetExtKeyToMe(), $this->GetKey(),'=');
  258. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  259. $oAppContext = new ApplicationContext();
  260. foreach($oAppContext->GetNames() as $sKey)
  261. {
  262. // The linked object inherits the parent's value for the context
  263. if (MetaModel::IsValidAttCode($sClass, $sKey))
  264. {
  265. $aDefaults[$sKey] = $this->Get($sKey);
  266. }
  267. }
  268. $aParams = array(
  269. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  270. 'object_id' => $this->GetKey(),
  271. 'menu' => true,
  272. 'default' => $aDefaults,
  273. );
  274. $oBlock = new DisplayBlock($oFilter, 'list', false);
  275. $oBlock->Display($oPage, $sInputId, $aParams);
  276. }
  277. }
  278. else // get_class($oAttDef) == 'AttributeLinkedSetIndirect'
  279. {
  280. // n:n links
  281. $sLinkedClass = $oAttDef->GetLinkedClass();
  282. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  283. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  284. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription().'<span id="busy_'.$sInputId.'"></span>');
  285. $sValue = $this->Get($sAttCode);
  286. $sDisplayValue = $this->GetEditValue($sAttCode);
  287. $aArgs = array('this' => $this);
  288. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  289. $aFieldsMap[$sAttCode] = $sInputId;
  290. $oPage->add($sHTMLValue);
  291. }
  292. }
  293. else
  294. {
  295. // Display mode
  296. if (!$oAttDef->IsIndirect())
  297. {
  298. // 1:n links
  299. $sTargetClass = $oAttDef->GetLinkedClass();
  300. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  301. $oAppContext = new ApplicationContext();
  302. foreach($oAppContext->GetNames() as $sKey)
  303. {
  304. // The linked object inherits the parent's value for the context
  305. if (MetaModel::IsValidAttCode($sClass, $sKey))
  306. {
  307. $aDefaults[$sKey] = $this->Get($sKey);
  308. }
  309. }
  310. $aParams = array(
  311. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  312. 'object_id' => $this->GetKey(),
  313. 'menu' => false,
  314. 'default' => $aDefaults,
  315. );
  316. }
  317. else
  318. {
  319. // n:n links
  320. $sLinkedClass = $oAttDef->GetLinkedClass();
  321. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  322. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  323. $bMenu = ($this->Get($sAttCode)->Count() > 0); // The menu is enabled only if there are already some elements...
  324. $aParams = array(
  325. 'link_attr' => $oAttDef->GetExtKeyToMe(),
  326. 'object_id' => $this->GetKey(),
  327. 'target_attr' => $oAttDef->GetExtKeyToRemote(),
  328. 'view_link' => false,
  329. 'menu' => false,
  330. 'display_limit' => true, // By default limit the list to speed up the initial load & display
  331. );
  332. }
  333. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  334. $oBlock = new DisplayBlock($this->Get($sAttCode)->GetFilter(), 'list', false);
  335. $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams);
  336. }
  337. }
  338. $oPage->SetCurrentTab('');
  339. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  340. {
  341. $oExtensionInstance->OnDisplayRelations($this, $oPage, $bEditMode);
  342. }
  343. // Display Notifications after the other tabs since this tab disappears in edition
  344. if (!$bEditMode)
  345. {
  346. // Get the actual class of the current object
  347. // And look for triggers referring to it
  348. // If any trigger has been found then display a tab with notifications
  349. //
  350. $sClass = get_class($this);
  351. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  352. $oTriggerSet = new CMDBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObject AS T WHERE T.target_class IN ('$sClassList')"));
  353. if ($oTriggerSet->Count() > 0)
  354. {
  355. // Display notifications regarding the object
  356. $iId = $this->GetKey();
  357. $oNotifSearch = DBObjectSearch::FromOQL("SELECT EventNotificationEmail AS Ev JOIN TriggerOnObject AS T ON Ev.trigger_id = T.id WHERE T.target_class IN ('$sClassList') AND Ev.object_id = $iId");
  358. $oNotifSet = new DBObjectSet($oNotifSearch);
  359. $sCount = ($oNotifSet->Count() > 0) ? ' ('.$oNotifSet->Count().')' : '';
  360. $oPage->SetCurrentTab(Dict::S('UI:NotificationsTab').$sCount);
  361. $oBlock = new DisplayBlock($oNotifSearch, 'list', false);
  362. $oBlock->Display($oPage, 'notifications', array('menu' => false));
  363. }
  364. }
  365. }
  366. function GetBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix, $aExtraParams = array())
  367. {
  368. $sHtml = '';
  369. $oAppContext = new ApplicationContext();
  370. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  371. $aDetails = array();
  372. $sClass = get_class($this);
  373. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  374. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  375. // Compute the list of properties to display, first the attributes in the 'details' list, then
  376. // all the remaining attributes that are not external fields
  377. $sHtml = '';
  378. $aDetails = array();
  379. $iInputId = 0;
  380. $aFieldsMap = array();
  381. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  382. $bFieldComments = (count($aFieldsComments) > 0);
  383. foreach($aDetailsStruct as $sTab => $aCols )
  384. {
  385. $aDetails[$sTab] = array();
  386. ksort($aCols);
  387. $oPage->SetCurrentTab(Dict::S($sTab));
  388. $oPage->add('<table style="vertical-align:top"><tr>');
  389. foreach($aCols as $sColIndex => $aFieldsets)
  390. {
  391. $oPage->add('<td style="vertical-align:top">');
  392. //$aDetails[$sTab][$sColIndex] = array();
  393. $sLabel = '';
  394. $sPreviousLabel = '';
  395. $aDetails[$sTab][$sColIndex] = array();
  396. foreach($aFieldsets as $sFieldsetName => $aFields)
  397. {
  398. if (!empty($sFieldsetName) && ($sFieldsetName[0] != '_'))
  399. {
  400. $sLabel = $sFieldsetName;
  401. }
  402. else
  403. {
  404. $sLabel = '';
  405. }
  406. if ($sLabel != $sPreviousLabel)
  407. {
  408. if (!empty($sPreviousLabel))
  409. {
  410. $oPage->add('<fieldset>');
  411. $oPage->add('<legend>'.Dict::S($sPreviousLabel).'</legend>');
  412. }
  413. $oPage->Details($aDetails[$sTab][$sColIndex]);
  414. if (!empty($sPreviousLabel))
  415. {
  416. $oPage->add('</fieldset>');
  417. }
  418. $aDetails[$sTab][$sColIndex] = array();
  419. $sPreviousLabel = $sLabel;
  420. }
  421. foreach($aFields as $sAttCode)
  422. {
  423. if ($bEditMode)
  424. {
  425. $sComments = isset($aFieldsComments[$sAttCode]) ? $aFieldsComments[$sAttCode] : '&nbsp;';
  426. $sInfos = '&nbsp;';
  427. if ($this->IsNew())
  428. {
  429. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  430. }
  431. else
  432. {
  433. $iFlags = $this->GetAttributeFlags($sAttCode);
  434. }
  435. if (($iFlags & OPT_ATT_MANDATORY) && $this->IsNew())
  436. {
  437. $iFlags = $iFlags & ~OPT_ATT_READONLY; // Mandatory fields cannot be read-only when creating an object
  438. }
  439. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  440. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0))
  441. {
  442. if ($oAttDef->IsWritable())
  443. {
  444. if ($sStateAttCode == $sAttCode)
  445. {
  446. // State attribute is always read-only from the UI
  447. $sHTMLValue = $this->GetStateLabel();
  448. $val = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  449. }
  450. else
  451. {
  452. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  453. if ($iFlags & OPT_ATT_HIDDEN)
  454. {
  455. // Attribute is hidden, add a hidden input
  456. $oPage->add('<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>');
  457. $aFieldsMap[$sAttCode] = $sInputId;
  458. }
  459. else
  460. {
  461. if ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE))
  462. {
  463. // Check if the attribute is not read-only because of a synchro...
  464. $aReasons = array();
  465. $sSynchroIcon = '';
  466. if ($iFlags & OPT_ATT_SLAVE)
  467. {
  468. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  469. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  470. $sTip = '';
  471. foreach($aReasons as $aRow)
  472. {
  473. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  474. }
  475. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  476. }
  477. // Attribute is read-only
  478. $sHTMLValue = "<span id=\"field_{$sInputId}\">".$this->GetAsHTML($sAttCode);
  479. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/></span>';
  480. $aFieldsMap[$sAttCode] = $sInputId;
  481. $sComments = $sSynchroIcon;
  482. }
  483. else
  484. {
  485. $sValue = $this->Get($sAttCode);
  486. $sDisplayValue = $this->GetEditValue($sAttCode);
  487. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  488. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  489. $aFieldsMap[$sAttCode] = $sInputId;
  490. }
  491. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  492. }
  493. }
  494. }
  495. else
  496. {
  497. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $this->GetAsHTML($sAttCode), 'comments' => $sComments, 'infos' => $sInfos);
  498. }
  499. }
  500. else
  501. {
  502. $val = null; // Skip this field
  503. }
  504. }
  505. else
  506. {
  507. // !bEditMode
  508. $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode);
  509. }
  510. if ($val != null)
  511. {
  512. // The field is visible, add it to the current column
  513. $aDetails[$sTab][$sColIndex][] = $val;
  514. $iInputId++;
  515. }
  516. }
  517. }
  518. if (!empty($sPreviousLabel))
  519. {
  520. $oPage->add('<fieldset>');
  521. $oPage->add('<legend>'.Dict::S($sFieldsetName).'</legend>');
  522. }
  523. $oPage->Details($aDetails[$sTab][$sColIndex]);
  524. if (!empty($sPreviousLabel))
  525. {
  526. $oPage->add('</fieldset>');
  527. }
  528. $oPage->add('</td>');
  529. }
  530. $oPage->add('</tr></table>');
  531. }
  532. return $aFieldsMap;
  533. }
  534. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  535. {
  536. $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate(get_class($this)));
  537. if (!empty($sTemplate))
  538. {
  539. $oTemplate = new DisplayTemplate($sTemplate);
  540. // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved
  541. // but the preferred method is to use '$id$'
  542. $oTemplate->Render($oPage, array('class_name'=> MetaModel::GetName(get_class($this)),'class'=> get_class($this), 'pkey'=> $this->GetKey(), 'id'=> $this->GetKey(), 'name' => $this->GetName()));
  543. }
  544. else
  545. {
  546. // Object's details
  547. // template not found display the object using the *old style*
  548. $this->DisplayBareHeader($oPage, $bEditMode);
  549. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  550. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  551. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  552. $this->DisplayBareProperties($oPage, $bEditMode);
  553. $this->DisplayBareRelations($oPage, $bEditMode);
  554. $oPage->SetCurrentTab(Dict::S('UI:HistoryTab'));
  555. $this->DisplayBareHistory($oPage, $bEditMode);
  556. }
  557. }
  558. function DisplayPreview(WebPage $oPage)
  559. {
  560. $aDetails = array();
  561. $sClass = get_class($this);
  562. $aList = MetaModel::GetZListItems($sClass, 'preview');
  563. foreach($aList as $sAttCode)
  564. {
  565. $aDetails[] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' =>$this->GetAsHTML($sAttCode));
  566. }
  567. $oPage->details($aDetails);
  568. }
  569. public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  570. {
  571. $oPage->add(self::GetDisplaySet($oPage, $oSet, $aExtraParams));
  572. }
  573. /**
  574. * Get the HTML fragment corresponding to the display of a table representing a set of objects
  575. * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output
  576. * @param CMDBObjectSet The set of objects to display
  577. * @param Hash $aExtraParams Some extra configuration parameters to tweak the behavior of the display
  578. * @return String The HTML fragment representing the table of objects
  579. */
  580. public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  581. {
  582. if (empty($aExtraParams['currentId']))
  583. {
  584. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  585. }
  586. else
  587. {
  588. $iListId = $aExtraParams['currentId'];
  589. }
  590. // Initialize and check the parameters
  591. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  592. $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
  593. $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0;
  594. $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : '';
  595. if (!empty($sLinkageAttribute))
  596. {
  597. if($iLinkedObjectId == 0)
  598. {
  599. // if 'links' mode is requested the id of the object to link to must be specified
  600. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  601. }
  602. if($sTargetAttr == '')
  603. {
  604. // if 'links' mode is requested the d of the object to link to must be specified
  605. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  606. }
  607. }
  608. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  609. $bTruncated = isset($aExtraParams['truncated']) ? $aExtraParams['truncated'] == true : true;
  610. $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
  611. $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
  612. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  613. $aExtraFields = array();
  614. foreach ($aExtraFieldsRaw as $sFieldName)
  615. {
  616. // Ignore attributes not of the main queried class
  617. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  618. {
  619. $sClassAlias = $aMatches[1];
  620. $sAttCode = $aMatches[2];
  621. if ($sClassAlias == $oSet->GetFilter()->GetClassAlias())
  622. {
  623. $aExtraFields[] = $sAttCode;
  624. }
  625. }
  626. else
  627. {
  628. $aExtraFields[] = $sFieldName;
  629. }
  630. }
  631. $sHtml = '';
  632. $oAppContext = new ApplicationContext();
  633. $sClassName = $oSet->GetFilter()->GetClass();
  634. $aAttribs = array();
  635. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  636. if ($sZListName !== false)
  637. {
  638. $aList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  639. $aList = array_merge($aList, $aExtraFields);
  640. }
  641. else
  642. {
  643. $aList = $aExtraFields;
  644. }
  645. // Filter the list to removed linked set since we are not able to display them here
  646. foreach($aList as $index => $sAttCode)
  647. {
  648. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  649. if ($oAttDef instanceof AttributeLinkedSet)
  650. {
  651. // Removed from the display list
  652. unset($aList[$index]);
  653. }
  654. }
  655. // Load only the requested columns
  656. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  657. $oSet->OptimizeColumnLoad(array($sClassAlias => $aList));
  658. if (!empty($sLinkageAttribute))
  659. {
  660. // The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
  661. // and other objects...
  662. // The display will then group all the attributes related to the link itself:
  663. // | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
  664. $aDisplayList = array();
  665. $aAttDefs = MetaModel::ListAttributeDefs($sClassName);
  666. assert(isset($aAttDefs[$sLinkageAttribute]));
  667. $oAttDef = $aAttDefs[$sLinkageAttribute];
  668. assert($oAttDef->IsExternalKey());
  669. // First display all the attributes specific to the link record
  670. foreach($aList as $sLinkAttCode)
  671. {
  672. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  673. if ( (!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField()) )
  674. {
  675. $aDisplayList[] = $sLinkAttCode;
  676. }
  677. }
  678. // Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
  679. foreach($aList as $sLinkAttCode)
  680. {
  681. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  682. if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
  683. || ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode()!=$sLinkageAttribute)) )
  684. {
  685. $aDisplayList[] = $sLinkAttCode;
  686. }
  687. }
  688. // First display all the attributes specific to the link
  689. // Then display all the attributes linked to the other end of the relationship
  690. $aList = $aDisplayList;
  691. }
  692. if ($bSelectMode)
  693. {
  694. if (!$bSingleSelectMode)
  695. {
  696. $aAttribs['form::select'] = array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList{$iListId}:not(:disabled)', this.checked);\" class=\"checkAll\"></input>", 'description' => Dict::S('UI:SelectAllToggle+'));
  697. }
  698. else
  699. {
  700. $aAttribs['form::select'] = array('label' => "", 'description' => '');
  701. }
  702. }
  703. if ($bViewLink)
  704. {
  705. $aAttribs['key'] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  706. }
  707. foreach($aList as $sAttCode)
  708. {
  709. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  710. $aAttribs[$sAttCode] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => $oAttDef->GetOrderByHint());
  711. }
  712. $aValues = array();
  713. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  714. $iMaxObjects = -1;
  715. if ($bDisplayLimit && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  716. {
  717. $iMaxObjects = MetaModel::GetConfig()->GetMinDisplayLimit();
  718. $oSet->SetLimit($iMaxObjects);
  719. }
  720. $oSet->Seek(0);
  721. while (($oObj = $oSet->Fetch()) && ($iMaxObjects != 0))
  722. {
  723. $aRow = array();
  724. $sHilightClass = $oObj->GetHilightClass();
  725. if ($sHilightClass != '')
  726. {
  727. $aRow['@class'] = $sHilightClass;
  728. }
  729. if ($bViewLink)
  730. {
  731. $aRow['key'] = $oObj->GetHyperLink();
  732. }
  733. if ($bSelectMode)
  734. {
  735. if (array_key_exists('selection_enabled', $aExtraParams) && isset($aExtraParams['selection_enabled'][$oObj->GetKey()]))
  736. {
  737. $sDisabled = ($aExtraParams['selection_enabled'][$oObj->GetKey()]) ? '' : ' disabled="disabled"';
  738. }
  739. else
  740. {
  741. $sDisabled = '';
  742. }
  743. if ($bSingleSelectMode)
  744. {
  745. $aRow['form::select'] = "<input type=\"radio\" $sDisabled class=\"selectList{$iListId}\" name=\"selectObject\" value=\"".$oObj->GetKey()."\"></input>";
  746. }
  747. else
  748. {
  749. $aRow['form::select'] = "<input type=\"checkBox\" $sDisabled class=\"selectList{$iListId}\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\"></input>";
  750. }
  751. }
  752. foreach($aList as $sAttCode)
  753. {
  754. $aRow[$sAttCode] = $oObj->GetAsHTML($sAttCode);
  755. }
  756. $aValues[] = $aRow;
  757. $iMaxObjects--;
  758. }
  759. $sHtml .= '<table class="listContainer">';
  760. $sColspan = '';
  761. $sFilter = $oSet->GetFilter()->serialize();
  762. $iMinDisplayLimit = MetaModel::GetConfig()->GetMinDisplayLimit();
  763. $sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oSet->Count());
  764. $sLinkLabel = Dict::S('UI:DisplayAll');
  765. foreach($oSet->GetFilter()->GetInternalParams() as $sName => $sValue)
  766. {
  767. $aExtraParams['query_params'][$sName] = $sValue;
  768. }
  769. if ($bDisplayMenu)
  770. {
  771. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  772. $sColspan = 'colspan="2"';
  773. $aMenuExtraParams = $aExtraParams;
  774. if (!empty($sLinkageAttribute))
  775. {
  776. //$aMenuExtraParams['linkage'] = $sLinkageAttribute;
  777. $aMenuExtraParams = $aExtraParams;
  778. }
  779. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams, $iListId);
  780. $sHtml .= '</td></tr>';
  781. }
  782. $sHtml .= "<tr><td $sColspan>";
  783. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  784. $sHtml .= '</td></tr>';
  785. $sHtml .= '</table>';
  786. $iCount = $oSet->Count();
  787. if ($bSelectMode)
  788. {
  789. $sHeader = Dict::Format('UI:Pagination:HeaderSelection', '<span id="total">'.$iCount.'</span>', '<span class="selectedCount">0</span>');
  790. }
  791. else
  792. {
  793. $sHeader = Dict::Format('UI:Pagination:HeaderNoSelection', '<span id="total">'.$iCount.'</span>');
  794. }
  795. // All lists are now paginated in order to benefit from the SQL sort order
  796. if (!$bDisplayLimit)
  797. {
  798. $sPagerStyle = 'style="display:none"'; // no limit: display the full table, so hide the "pager" UI
  799. $iPageSize = -1; // Display all
  800. }
  801. else
  802. {
  803. $sPagerStyle = '';
  804. $iPageSize = MetaModel::GetConfig()->GetMinDisplayLimit();
  805. }
  806. $iDefaultPageSize = MetaModel::GetConfig()->GetMinDisplayLimit();
  807. $sCombo = '<select class="pagesize">';
  808. for($iPage = 1; $iPage < 5; $iPage++)
  809. {
  810. $sSelected = ($iPage == $iPageSize) ? 'selected="selected"' : '';
  811. $iNbItems = $iPage * $iDefaultPageSize;
  812. $sCombo .= "<option $sSelected value=\"$iNbItems\">$iNbItems</option>";
  813. }
  814. $sSelected = (-1 == $iPageSize) ? 'selected="selected"' : '';
  815. $sCombo .= "<option $sSelected value=\"-1\">".Dict::S('UI:Pagination:All')."</option>";
  816. $sCombo .= '</select>';
  817. $sPages = Dict::S('UI:Pagination:PagesLabel');
  818. $sPageSizeCombo = Dict::Format('UI:Pagination:PageSize', $sCombo);
  819. $iNbPages = ($iPageSize == -1) ? 1 : ceil($iCount / $iPageSize);
  820. $aPagesToDisplay = array();
  821. for($idx = 0; $idx <= min(4, $iNbPages-1); $idx++)
  822. {
  823. if ($idx == 0)
  824. {
  825. $aPagesToDisplay[$idx] = '<span page="0" class="curr_page">1</span>';
  826. }
  827. else
  828. {
  829. $aPagesToDisplay[$idx] = "<span id=\"gotopage_$idx\" class=\"gotopage\" page=\"$idx\">".(1+$idx)."</span>";
  830. }
  831. }
  832. $iLastPageIdx = $iNbPages - 1;
  833. if (!isset($aPagesToDisplay[$iLastPageIdx]))
  834. {
  835. unset($aPagesToDisplay[$idx - 1]); // remove the last page added to make room for the very last page
  836. $aPagesToDisplay[$iLastPageIdx] = "<span id=\"gotopage_$iLastPageIdx\" class=\"gotopage\" page=\"$iLastPageIdx\">... $iNbPages</span>";
  837. }
  838. $sPagesLinks = implode('', $aPagesToDisplay);
  839. $sPagesList = '['.implode(',', array_keys($aPagesToDisplay)).']';
  840. $sHtml =
  841. <<<EOF
  842. <div id="pager{$iListId}" class="pager" $sPagerStyle>
  843. <p>$sHeader</p>
  844. <p><table class="pagination"><tr><td>$sPages</td><td><img src="../images/first.png" class="first"/></td>
  845. <td><img src="../images/prev.png" class="prev"/></td>
  846. <td><span id="index">$sPagesLinks</span></td>
  847. <td><img src="../images/next.png" class="next"/></td>
  848. <td><img src="../images/last.png" class="last"/></td>
  849. <td>$sPageSizeCombo</td>
  850. <td><span id="loading">&nbsp;</span></td>
  851. </tr>
  852. </table>
  853. <input type="hidden" name="selectionMode" value="positive"></input>
  854. </div>
  855. EOF
  856. .$sHtml;
  857. $aArgs = $oSet->GetArgs();
  858. $sExtraParams = addslashes(str_replace('"', "'", json_encode(array_merge($aExtraParams, $aArgs)))); // JSON encode, change the style of the quotes and escape them
  859. $sSelectMode = '';
  860. $sHeaders = '';
  861. if ($bSelectMode)
  862. {
  863. $sSelectMode = $bSingleSelectMode ? 'single' : 'multiple';
  864. $sHeaders = 'headers: { 0: {sorter: false}},';
  865. }
  866. $sDisplayKey = ($bViewLink) ? 'true' : 'false';
  867. // Protect against duplicate elements in the Zlist
  868. $aUniqueOrderedList = array();
  869. foreach($aList as $sAttCode)
  870. {
  871. $aUniqueOrderedList[$sAttCode] = true;
  872. }
  873. $aUniqueOrderedList = array_keys($aUniqueOrderedList);
  874. $sDisplayList = json_encode($aUniqueOrderedList);
  875. $sCssCount = isset($aExtraParams['cssCount']) ? ", cssCount: '{$aExtraParams['cssCount']}'" : '';
  876. $oSet->ApplyParameters();
  877. // Display the actual sort order of the table
  878. $aRealSortOrder = $oSet->GetRealSortOrder();
  879. $aDefaultSort = array();
  880. $iColOffset = 0;
  881. if ($bSelectMode)
  882. {
  883. $iColOffset += 1;
  884. }
  885. if ($bViewLink)
  886. {
  887. $iColOffset += 1;
  888. }
  889. foreach($aRealSortOrder as $sColCode => $bAscending)
  890. {
  891. $iPos = array_search($sColCode, $aUniqueOrderedList);
  892. if ($iPos !== false)
  893. {
  894. $aDefaultSort[] = "[".($iColOffset+$iPos).",".($bAscending ? '0' : '1')."]";
  895. }
  896. else if($sColCode == 'friendlyname' && $bViewLink)
  897. {
  898. $aDefaultSort[] = "[".($iColOffset-1).",".($bAscending ? '0' : '1')."]";
  899. }
  900. }
  901. $sSortList = '';
  902. if (count($aDefaultSort) > 0)
  903. {
  904. $sSortList = ', sortList: ['.implode(',', $aDefaultSort).']';
  905. }
  906. $sOQL = addslashes($oSet->GetFilter()->serialize());
  907. $oPage->add_ready_script(
  908. <<<EOF
  909. var oTable = $('#{$iListId} table.listResults');
  910. oTable.tablesorter( { $sHeaders widgets: ['myZebra', 'truncatedList'] $sSortList} ).tablesorterPager({container: $('#pager{$iListId}'), totalRows:$iCount, size: $iPageSize, filter: '$sOQL', extra_params: '$sExtraParams', select_mode: '$sSelectMode', displayKey: $sDisplayKey, displayList: $sDisplayList $sCssCount});
  911. EOF
  912. );
  913. return $sHtml;
  914. }
  915. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  916. {
  917. static $iListId = 0;
  918. $iListId++;
  919. $aList = array();
  920. // Initialize and check the parameters
  921. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  922. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  923. // Check if there is a list of aliases to limit the display to...
  924. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  925. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  926. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  927. $aExtraFields = array();
  928. foreach ($aExtraFieldsRaw as $sFieldName)
  929. {
  930. // Ignore attributes not of the main queried class
  931. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  932. {
  933. $sClassAlias = $aMatches[1];
  934. $sAttCode = $aMatches[2];
  935. if (array_key_exists($sClassAlias, $oSet->GetSelectedClasses()))
  936. {
  937. $aExtraFields[$sClassAlias][] = $sAttCode;
  938. }
  939. }
  940. else
  941. {
  942. $aExtraFields['*'] = $sAttCode;
  943. }
  944. }
  945. $sHtml = '';
  946. $oAppContext = new ApplicationContext();
  947. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  948. $aAuthorizedClasses = array();
  949. foreach($aClasses as $sAlias => $sClassName)
  950. {
  951. if ( (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) &&
  952. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  953. {
  954. $aAuthorizedClasses[$sAlias] = $sClassName;
  955. }
  956. }
  957. $aAttribs = array();
  958. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  959. {
  960. if (array_key_exists($sAlias, $aExtraFields))
  961. {
  962. $aList[$sAlias] = $aExtraFields[$sAlias];
  963. }
  964. else
  965. {
  966. $aList[$sAlias] = array();
  967. }
  968. if ($sZListName !== false)
  969. {
  970. $aDefaultList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  971. $aList[$sAlias] = array_merge($aDefaultList, $aList[$sAlias]);
  972. }
  973. // Filter the list to removed linked set since we are not able to display them here
  974. foreach($aList[$sAlias] as $index => $sAttCode)
  975. {
  976. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  977. if ($oAttDef instanceof AttributeLinkedSet)
  978. {
  979. // Removed from the display list
  980. unset($aList[$sAlias][$index]);
  981. }
  982. }
  983. if ($bViewLink)
  984. {
  985. $aAttribs['key_'.$sAlias] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  986. }
  987. foreach($aList[$sAlias] as $sAttCode)
  988. {
  989. $aAttribs[$sAttCode.'_'.$sAlias] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => MetaModel::GetDescription($sClassName, $sAttCode));
  990. }
  991. }
  992. // Load only the requested columns
  993. $aAttToLoad = array(); // attributes to load
  994. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  995. {
  996. foreach($aList[$sAlias] as $sAttCode)
  997. {
  998. $aAttToLoad[$sAlias][] = $sAttCode;
  999. }
  1000. }
  1001. $oSet->OptimizeColumnLoad($aAttToLoad);
  1002. $aValues = array();
  1003. $oSet->Seek(0);
  1004. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  1005. $iMaxObjects = -1;
  1006. if ($bDisplayLimit)
  1007. {
  1008. if ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit())
  1009. {
  1010. $iMaxObjects = MetaModel::GetConfig()->GetMinDisplayLimit();
  1011. }
  1012. }
  1013. while (($aObjects = $oSet->FetchAssoc()) && ($iMaxObjects != 0))
  1014. {
  1015. $aRow = array();
  1016. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  1017. {
  1018. if ($bViewLink)
  1019. {
  1020. if (is_null($aObjects[$sAlias]))
  1021. {
  1022. $aRow['key_'.$sAlias] = '';
  1023. }
  1024. else
  1025. {
  1026. $aRow['key_'.$sAlias] = $aObjects[$sAlias]->GetHyperLink();
  1027. }
  1028. }
  1029. foreach($aList[$sAlias] as $sAttCode)
  1030. {
  1031. if (is_null($aObjects[$sAlias]))
  1032. {
  1033. $aRow[$sAttCode.'_'.$sAlias] = '';
  1034. }
  1035. else
  1036. {
  1037. $aRow[$sAttCode.'_'.$sAlias] = $aObjects[$sAlias]->GetAsHTML($sAttCode);
  1038. }
  1039. }
  1040. }
  1041. $aValues[] = $aRow;
  1042. $iMaxObjects--;
  1043. }
  1044. $sHtml .= '<table class="listContainer">';
  1045. $sColspan = '';
  1046. if ($bDisplayMenu)
  1047. {
  1048. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  1049. $sColspan = 'colspan="2"';
  1050. $aMenuExtraParams = $aExtraParams;
  1051. if (!empty($sLinkageAttribute))
  1052. {
  1053. $aMenuExtraParams = $aExtraParams;
  1054. }
  1055. if ($bDisplayLimit && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  1056. {
  1057. // list truncated
  1058. $divId = $aExtraParams['block_id'];
  1059. $sFilter = $oSet->GetFilter()->serialize();
  1060. $aExtraParams['display_limit'] = false; // To expand the full list
  1061. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  1062. $sHtml .= '<tr class="containerHeader"><td>'.Dict::Format('UI:TruncatedResults', MetaModel::GetConfig()->GetMinDisplayLimit(), $oSet->Count()).'&nbsp;&nbsp;<span style=\"cursor:pointer;\" onClick="Javascript:ReloadTruncatedList(\''.$divId.'\', \''.$sFilter.'\', \''.$sExtraParams.'\');">'.Dict::S('UI:DisplayAll').'</span></td><td>';
  1063. $oPage->add_ready_script("$('#{$divId} table.listResults').addClass('truncated');");
  1064. $oPage->add_ready_script("$('#{$divId} table.listResults tr:last td').addClass('truncated');");
  1065. }
  1066. else
  1067. {
  1068. // Full list
  1069. $sHtml .= '<tr class="containerHeader"><td>&nbsp;'.Dict::Format('UI:CountOfResults', $oSet->Count()).'</td><td>';
  1070. }
  1071. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams, $aMenuExtraParams['currentId']);
  1072. $sHtml .= '</td></tr>';
  1073. }
  1074. $sHtml .= "<tr><td $sColspan>";
  1075. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  1076. $sHtml .= '</td></tr>';
  1077. $sHtml .= '</table>';
  1078. return $sHtml;
  1079. }
  1080. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1081. {
  1082. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  1083. }
  1084. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  1085. {
  1086. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  1087. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  1088. $aFields = null;
  1089. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  1090. {
  1091. $aFields = explode(',', $aParams['fields']);
  1092. }
  1093. $aList = array();
  1094. $oAppContext = new ApplicationContext();
  1095. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1096. $aAuthorizedClasses = array();
  1097. foreach($aClasses as $sAlias => $sClassName)
  1098. {
  1099. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1100. {
  1101. $aAuthorizedClasses[$sAlias] = $sClassName;
  1102. }
  1103. }
  1104. $aAttribs = array();
  1105. $aHeader = array();
  1106. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1107. {
  1108. $aList[$sAlias] = array();
  1109. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  1110. {
  1111. if (is_null($aFields) || (count($aFields) == 0))
  1112. {
  1113. // Standard list of attributes (no link sets)
  1114. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  1115. {
  1116. $aList[$sAlias][$sAttCode] = $oAttDef;
  1117. }
  1118. }
  1119. else
  1120. {
  1121. // User defined list of attributes
  1122. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  1123. {
  1124. $aList[$sAlias][$sAttCode] = $oAttDef;
  1125. }
  1126. }
  1127. }
  1128. $aHeader[] = 'id';
  1129. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1130. {
  1131. $sStar = '';
  1132. if ($oAttDef->IsExternalField())
  1133. {
  1134. $sExtKeyLabel = MetaModel::GetLabel($sClassName, $oAttDef->GetKeyAttCode());
  1135. $oExtKeyAttDef = MetaModel::GetAttributeDef($sClassName, $oAttDef->GetKeyAttCode());
  1136. if (!$oExtKeyAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  1137. {
  1138. $sStar = '*';
  1139. }
  1140. $sRemoteAttLabel = MetaModel::GetLabel($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  1141. $oTargetAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  1142. $sSuffix = '';
  1143. if ($oTargetAttDef->IsExternalKey())
  1144. {
  1145. $sSuffix = '->id';
  1146. }
  1147. $aHeader[] = $sExtKeyLabel.'->'.$sRemoteAttLabel.$sSuffix.$sStar;
  1148. }
  1149. else
  1150. {
  1151. if (!$oAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  1152. {
  1153. $sStar = '*';
  1154. }
  1155. $aHeader[] = MetaModel::GetLabel($sClassName, $sAttCode).$sStar;
  1156. }
  1157. }
  1158. }
  1159. $sHtml = implode($sSeparator, $aHeader)."\n";
  1160. $oSet->Seek(0);
  1161. while ($aObjects = $oSet->FetchAssoc())
  1162. {
  1163. $aRow = array();
  1164. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1165. {
  1166. $oObj = $aObjects[$sAlias];
  1167. if (is_null($oObj))
  1168. {
  1169. $aRow[] = '';
  1170. }
  1171. else
  1172. {
  1173. $aRow[] = $oObj->GetKey();
  1174. }
  1175. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1176. {
  1177. if (is_null($oObj))
  1178. {
  1179. $aRow[] = '';
  1180. }
  1181. else
  1182. {
  1183. $aRow[] = $oObj->GetAsCSV($sAttCode, $sSeparator, $sTextQualifier);
  1184. }
  1185. }
  1186. }
  1187. $sHtml .= implode($sSeparator, $aRow)."\n";
  1188. }
  1189. return $sHtml;
  1190. }
  1191. static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1192. {
  1193. $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams));
  1194. }
  1195. /**
  1196. * Spreadsheet output: designed for end users doing some reporting
  1197. * Then the ids are excluded and replaced by the corresponding friendlyname
  1198. */
  1199. static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array())
  1200. {
  1201. $aFields = null;
  1202. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  1203. {
  1204. $aFields = explode(',', $aParams['fields']);
  1205. }
  1206. $aList = array();
  1207. $oAppContext = new ApplicationContext();
  1208. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1209. $aAuthorizedClasses = array();
  1210. foreach($aClasses as $sAlias => $sClassName)
  1211. {
  1212. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1213. {
  1214. $aAuthorizedClasses[$sAlias] = $sClassName;
  1215. }
  1216. }
  1217. $aAttribs = array();
  1218. $aHeader = array();
  1219. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1220. {
  1221. $aList[$sAlias] = array();
  1222. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  1223. {
  1224. if (is_null($aFields) || (count($aFields) == 0))
  1225. {
  1226. // Standard list of attributes (no link sets)
  1227. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  1228. {
  1229. $aList[$sAlias][$sAttCode] = $oAttDef;
  1230. }
  1231. }
  1232. else
  1233. {
  1234. // User defined list of attributes
  1235. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  1236. {
  1237. $aList[$sAlias][$sAttCode] = $oAttDef;
  1238. }
  1239. }
  1240. }
  1241. // Replace external key by the corresponding friendly name (if not already in the list)
  1242. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1243. {
  1244. if ($oAttDef->IsExternalKey())
  1245. {
  1246. unset($aList[$sAlias][$sAttCode]);
  1247. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1248. if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode))
  1249. {
  1250. $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode);
  1251. $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt;
  1252. }
  1253. }
  1254. }
  1255. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1256. {
  1257. if ($oAttDef->IsExternalField())
  1258. {
  1259. $sExtKeyLabel = MetaModel::GetLabel($sClassName, $oAttDef->GetKeyAttCode());
  1260. $oExtKeyAttDef = MetaModel::GetAttributeDef($sClassName, $oAttDef->GetKeyAttCode());
  1261. $sRemoteAttLabel = MetaModel::GetLabel($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  1262. $oTargetAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  1263. $sSuffix = '';
  1264. if ($oTargetAttDef->IsExternalKey())
  1265. {
  1266. $sSuffix = '->id';
  1267. }
  1268. $sColLabel = $sExtKeyLabel.'->'.$sRemoteAttLabel.$sSuffix;
  1269. }
  1270. else
  1271. {
  1272. $sColLabel = MetaModel::GetLabel($sClassName, $sAttCode);
  1273. }
  1274. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1275. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1276. {
  1277. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  1278. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  1279. }
  1280. else
  1281. {
  1282. $aHeader[] = $sColLabel;
  1283. }
  1284. }
  1285. }
  1286. $sHtml = "<table border=\"1\">\n";
  1287. $sHtml .= "<tr>\n";
  1288. $sHtml .= "<td>".implode("</td><td>", $aHeader)."</td>\n";
  1289. $sHtml .= "</tr>\n";
  1290. $oSet->Seek(0);
  1291. while ($aObjects = $oSet->FetchAssoc())
  1292. {
  1293. $aRow = array();
  1294. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1295. {
  1296. $oObj = $aObjects[$sAlias];
  1297. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1298. {
  1299. if (is_null($oObj))
  1300. {
  1301. $aRow[] = '<td></td>';
  1302. }
  1303. else
  1304. {
  1305. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1306. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1307. {
  1308. $iDate = AttributeDateTime::GetAsUnixSeconds($oObj->Get($sAttCode));
  1309. $aRow[] = '<td>'.date('Y-m-d', $iDate).'</td>';
  1310. $aRow[] = '<td>'.date('H:i:s', $iDate).'</td>';
  1311. }
  1312. else
  1313. {
  1314. $aRow[] = '<td>'.(string) $oObj->Get($sAttCode).'</td>';
  1315. }
  1316. }
  1317. }
  1318. }
  1319. $sHtml .= implode("\n", $aRow);
  1320. $sHtml .= "</tr>\n";
  1321. }
  1322. $sHtml .= "</table>\n";
  1323. return $sHtml;
  1324. }
  1325. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1326. {
  1327. $oAppContext = new ApplicationContext();
  1328. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1329. $aAuthorizedClasses = array();
  1330. foreach($aClasses as $sAlias => $sClassName)
  1331. {
  1332. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1333. {
  1334. $aAuthorizedClasses[$sAlias] = $sClassName;
  1335. }
  1336. }
  1337. $aAttribs = array();
  1338. $aList = array();
  1339. $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details');
  1340. $oPage->add("<Set>\n");
  1341. $oSet->Seek(0);
  1342. while ($aObjects = $oSet->FetchAssoc())
  1343. {
  1344. if (count($aAuthorizedClasses) > 1)
  1345. {
  1346. $oPage->add("<Row>\n");
  1347. }
  1348. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1349. {
  1350. $oObj = $aObjects[$sAlias];
  1351. if (is_null($oObj))
  1352. {
  1353. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n");
  1354. }
  1355. else
  1356. {
  1357. $sClassName = get_class($oObj);
  1358. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  1359. }
  1360. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  1361. {
  1362. if (is_null($oObj))
  1363. {
  1364. $oPage->add("<$sAttCode>null</$sAttCode>\n");
  1365. }
  1366. else
  1367. {
  1368. if ($oAttDef->IsWritable())
  1369. {
  1370. $sValue = $oObj->GetAsXML($sAttCode);
  1371. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  1372. }
  1373. }
  1374. }
  1375. $oPage->add("</$sClassName>\n");
  1376. }
  1377. if (count($aAuthorizedClasses) > 1)
  1378. {
  1379. $oPage->add("</Row>\n");
  1380. }
  1381. }
  1382. $oPage->add("</Set>\n");
  1383. }
  1384. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1385. {
  1386. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  1387. }
  1388. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1389. {
  1390. static $iSearchFormId = 0;
  1391. $oAppContext = new ApplicationContext();
  1392. $sHtml = '';
  1393. $numCols=4;
  1394. $sClassName = $oSet->GetFilter()->GetClass();
  1395. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  1396. // (especially when used to add a link)
  1397. /*
  1398. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  1399. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  1400. <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>
  1401. </ul></div>\n";
  1402. */
  1403. // Simple search form
  1404. if (isset($aExtraParams['currentId']))
  1405. {
  1406. $sSearchFormId = $aExtraParams['currentId'];
  1407. }
  1408. else
  1409. {
  1410. $iSearchFormId = $oPage->GetUniqueId();
  1411. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  1412. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  1413. }
  1414. // Check if the current class has some sub-classes
  1415. if (isset($aExtraParams['baseClass']))
  1416. {
  1417. $sRootClass = $aExtraParams['baseClass'];
  1418. }
  1419. else
  1420. {
  1421. $sRootClass = $sClassName;
  1422. }
  1423. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  1424. if (count($aSubClasses) > 0)
  1425. {
  1426. $aOptions = array();
  1427. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  1428. foreach($aSubClasses as $sSubclassName)
  1429. {
  1430. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  1431. }
  1432. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  1433. ksort($aOptions);
  1434. $sContext = $oAppContext->GetForLink();
  1435. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  1436. }
  1437. else
  1438. {
  1439. $sClassesCombo = MetaModel::GetName($sClassName);
  1440. }
  1441. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  1442. $sAction = (isset($aExtraParams['action'])) ? $aExtraParams['action'] : utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1443. $sHtml .= "<form id=\"fs_{$sSearchFormId}\" action=\"{$sAction}\">\n"; // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  1444. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  1445. $index = 0;
  1446. $sHtml .= "<p>\n";
  1447. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  1448. $aMapCriteria = array();
  1449. foreach($aFilterCriteria as $aCriteria)
  1450. {
  1451. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  1452. }
  1453. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  1454. $aConsts = $oSet->ListConstantFields(); // Some fields are constants based on the query/context
  1455. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  1456. foreach($aList as $sFilterCode)
  1457. {
  1458. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  1459. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  1460. $sFilterValue = isset($aConsts[$sClassAlias][$sFilterCode]) ? $aConsts[$sClassAlias][$sFilterCode] : '';
  1461. $sFilterValue = utils::ReadParam($sFilterCode, $sFilterValue, false, 'raw_data');
  1462. $sFilterOpCode = null; // Use the default 'loose' OpCode
  1463. if (empty($sFilterValue))
  1464. {
  1465. if (isset($aMapCriteria[$sFilterCode]))
  1466. {
  1467. if (count($aMapCriteria[$sFilterCode]) > 1)
  1468. {
  1469. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  1470. }
  1471. else
  1472. {
  1473. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  1474. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  1475. }
  1476. if ($sFilterCode != 'company')
  1477. {
  1478. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  1479. }
  1480. }
  1481. }
  1482. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFilterCode);
  1483. if ($oAttDef->IsExternalKey())
  1484. {
  1485. $sTargetClass = $oAttDef->GetTargetClass();
  1486. $oSearch = new DBObjectSearch($sTargetClass);
  1487. $oSearch->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true);
  1488. $oAllowedValues = new DBObjectSet($oSearch);
  1489. $iFieldSize = $oAttDef->GetMaxSize();
  1490. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1491. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;";
  1492. $aExtKeyParams = $aExtraParams;
  1493. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1494. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1495. $sHtml .= UIExtKeyWidget::DisplayFromAttCode($oPage, $sFilterCode, $sClassName, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sSearchFormId.'search_'.$sFilterCode, false, $sFilterCode, '', $aExtKeyParams, true);
  1496. }
  1497. else
  1498. {
  1499. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  1500. if (is_null($aAllowedValues))
  1501. {
  1502. // Any value is possible, display an input box
  1503. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"$sFilterValue\"/>\n";
  1504. }
  1505. else
  1506. {
  1507. //Enum field, display a combo
  1508. $sValue = "<select name=\"$sFilterCode\">\n";
  1509. $sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  1510. foreach($aAllowedValues as $key => $value)
  1511. {
  1512. if ($sFilterValue == $key)
  1513. {
  1514. $sSelected = ' selected';
  1515. }
  1516. else
  1517. {
  1518. $sSelected = '';
  1519. }
  1520. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  1521. }
  1522. $sValue .= "</select>\n";
  1523. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  1524. }
  1525. }
  1526. unset($aExtraParams[$sFilterCode]);
  1527. // Finally, add a tooltip if one is defined for this attribute definition
  1528. $sTip = $oAttDef->GetHelpOnSmartSearch();
  1529. if (strlen($sTip) > 0)
  1530. {
  1531. $sTip = addslashes($sTip);
  1532. $sTip = str_replace(array("\n", "\r"), " ", $sTip);
  1533. // :input does represent in form visible input (INPUT, SELECT, TEXTAREA)
  1534. $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' }} } );");
  1535. }
  1536. $index++;
  1537. $sHtml .= '</span> ';
  1538. }
  1539. $sHtml .= "</p>\n";
  1540. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  1541. foreach($aExtraParams as $sName => $sValue)
  1542. {
  1543. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1544. }
  1545. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  1546. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1547. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  1548. $sHtml .= $oAppContext->GetForForm();
  1549. $sHtml .= "</form>\n";
  1550. if (!isset($aExtraParams['currentId']))
  1551. {
  1552. $sHtml .= "</div><!-- Simple search form -->\n";
  1553. }
  1554. /*
  1555. // OQL query builder
  1556. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  1557. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  1558. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  1559. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  1560. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1561. $sSelectedClass = utils::ReadParam('oql_class', $sClassName, false, 'class');
  1562. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  1563. asort($aClasses);
  1564. foreach($aClasses as $sChildClass)
  1565. {
  1566. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  1567. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  1568. }
  1569. $sHtml .= "</select>&nbsp;</td><td>\n";
  1570. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  1571. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  1572. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1573. foreach($aExtraParams as $sName => $sValue)
  1574. {
  1575. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1576. }
  1577. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  1578. $sHtml .= $oAppContext->GetForForm();
  1579. $sHtml .= "</table></form>\n";
  1580. $sHtml .= "</div><!-- OQL query form -->\n";
  1581. */
  1582. return $sHtml;
  1583. }
  1584. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  1585. {
  1586. static $iInputId = 0;
  1587. $sFieldPrefix = '';
  1588. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  1589. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  1590. if ($sDisplayValue == '')
  1591. {
  1592. $sDisplayValue = $value;
  1593. }
  1594. if (isset($aArgs[$sAttCode]) && empty($value))
  1595. {
  1596. // default value passed by the context (either the app context of the operation)
  1597. $value = $aArgs[$sAttCode];
  1598. }
  1599. if (!empty($iId))
  1600. {
  1601. $iInputId = $iId;
  1602. }
  1603. else
  1604. {
  1605. $iInputId = $oPage->GetUniqueId();
  1606. }
  1607. if (!$oAttDef->IsExternalField())
  1608. {
  1609. $bMandatory = 'false';
  1610. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1611. {
  1612. $bMandatory = 'true';
  1613. }
  1614. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1615. $sHelpText = $oAttDef->GetHelpOnEdition();
  1616. $aEventsList = array();
  1617. switch($oAttDef->GetEditClass())
  1618. {
  1619. case 'Date':
  1620. $aEventsList[] ='validate';
  1621. $aEventsList[] ='keyup';
  1622. $aEventsList[] ='change';
  1623. $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}";
  1624. break;
  1625. case 'DateTime':
  1626. $aEventsList[] ='validate';
  1627. $aEventsList[] ='keyup';
  1628. $aEventsList[] ='change';
  1629. $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}";
  1630. break;
  1631. case 'Duration':
  1632. $aEventsList[] ='validate';
  1633. $aEventsList[] ='change';
  1634. $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1635. $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1636. $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1637. $oPage->add_ready_script("$('#{$iId}_s').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1638. $aVal = AttributeDuration::SplitDuration($value);
  1639. $sDays = "<input title=\"$sHelpText\" type=\"text\" size=\"3\" name=\"attr_{$sFieldPrefix}{$sAttCode}[d]{$sNameSuffix}\" value=\"{$aVal['days']}\" id=\"{$iId}_d\"/>";
  1640. $sHours = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[h]{$sNameSuffix}\" value=\"{$aVal['hours']}\" id=\"{$iId}_h\"/>";
  1641. $sMinutes = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[m]{$sNameSuffix}\" value=\"{$aVal['minutes']}\" id=\"{$iId}_m\"/>";
  1642. $sSeconds = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[s]{$sNameSuffix}\" value=\"{$aVal['seconds']}\" id=\"{$iId}_s\"/>";
  1643. $sHidden = "<input type=\"hidden\" id=\"{$iId}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\"/>";
  1644. $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden."&nbsp;".$sValidationField;
  1645. $oPage->add_ready_script("$('#{$iId}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });");
  1646. break;
  1647. case 'Password':
  1648. $aEventsList[] ='validate';
  1649. $aEventsList[] ='keyup';
  1650. $aEventsList[] ='change';
  1651. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1652. break;
  1653. case 'OQLExpression':
  1654. case 'Text':
  1655. $aEventsList[] ='validate';
  1656. $aEventsList[] ='keyup';
  1657. $aEventsList[] ='change';
  1658. $sEditValue = $oAttDef->GetEditValue($value);
  1659. $aStyles = array();
  1660. $sStyle = '';
  1661. $sWidth = $oAttDef->GetWidth('width', '');
  1662. if (!empty($sWidth))
  1663. {
  1664. $aStyles[] = 'width:'.$sWidth;
  1665. }
  1666. $sHeight = $oAttDef->GetHeight('height', '');
  1667. if (!empty($sHeight))
  1668. {
  1669. $aStyles[] = 'height:'.$sHeight;
  1670. }
  1671. if (count($aStyles) > 0)
  1672. {
  1673. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1674. }
  1675. if ($oAttDef->GetEditClass() == 'OQLExpression')
  1676. {
  1677. $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId();
  1678. $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression=';
  1679. $sInitialUrl = $sBaseUrl.urlencode($sEditValue);
  1680. $sAdditionalStuff = "<a id=\"$sTestResId\" target=\"_blank\" href=\"$sInitialUrl\">".Dict::S('UI:Edit:TestQuery')."</a>";
  1681. $oPage->add_ready_script("$('#$iId').bind('change keyup', function(evt, sFormId) { $('#$sTestResId').attr('href', '$sBaseUrl'+encodeURIComponent($(this).val())); } );");
  1682. }
  1683. else
  1684. {
  1685. $sAdditionalStuff = "";
  1686. }
  1687. // Ok, the text area is drawn here
  1688. $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>";
  1689. break;
  1690. case 'CaseLog':
  1691. $aStyles = array();
  1692. $sStyle = '';
  1693. $sWidth = $oAttDef->GetWidth('width', '');
  1694. if (!empty($sWidth))
  1695. {
  1696. $aStyles[] = 'width:'.$sWidth;
  1697. }
  1698. $sHeight = $oAttDef->GetHeight('height', '');
  1699. if (!empty($sHeight))
  1700. {
  1701. $aStyles[] = 'height:'.$sHeight;
  1702. }
  1703. if (count($aStyles) > 0)
  1704. {
  1705. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1706. }
  1707. $sHeader = '<div class="caselog_input_header">&nbsp;'.Dict::S('UI:CaseLogTypeYourTextHere').'</div>';
  1708. $sEditValue = $oAttDef->GetEditValue($value);
  1709. $sPreviousLog = is_object($value) ? $value->GetAsHTML() : '';
  1710. $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0;
  1711. $sHidden = "<input type=\"hidden\" id=\"{$iId}_count\" value=\"$iEntriesCount\"/>"; // To know how many entries the case log already contains
  1712. $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>";
  1713. $oPage->add_ready_script("$('#$iId').bind('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId) } );"); // Custom validation function
  1714. break;
  1715. case 'HTML':
  1716. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationField, $value, $bMandatory);
  1717. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1718. break;
  1719. case 'LinkedSet':
  1720. $aEventsList[] ='validate';
  1721. $aEventsList[] ='change';
  1722. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed(), $aArgs);
  1723. $oObj = isset($aArgs['this']) ? $aArgs['this'] : null;
  1724. $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj);
  1725. break;
  1726. case 'Document':
  1727. $aEventsList[] ='validate';
  1728. $aEventsList[] ='change';
  1729. $oDocument = $value; // Value is an ormDocument object
  1730. $sFileName = '';
  1731. if (is_object($oDocument))
  1732. {
  1733. $sFileName = $oDocument->GetFileName();
  1734. }
  1735. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1736. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1737. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[filename]\" type=\"hidden\" id=\"$iId\" \" value=\"".htmlentities($sFileName, ENT_QUOTES, 'UTF-8')."\"/>\n";
  1738. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1739. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[fcontents]\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1740. break;
  1741. case 'List':
  1742. // Not editable for now...
  1743. $sHTMLValue = '';
  1744. break;
  1745. case 'One Way Password':
  1746. $aEventsList[] ='validate';
  1747. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1748. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1749. // Event list & validation is handled directly by the widget
  1750. break;
  1751. case 'ExtKey':
  1752. $aEventsList[] ='validate';
  1753. $aEventsList[] ='change';
  1754. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1755. $sFieldName = $sFieldPrefix.$sAttCode.$sNameSuffix;
  1756. $aExtKeyParams = $aArgs;
  1757. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1758. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1759. $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams);
  1760. $sHTMLValue .= "<!-- iFlags: $iFlags bMandatory: $bMandatory -->\n";
  1761. break;
  1762. case 'String':
  1763. default:
  1764. $aEventsList[] ='validate';
  1765. // #@# todo - add context information (depending on dimensions)
  1766. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1767. $iFieldSize = $oAttDef->GetMaxSize();
  1768. if ($aAllowedValues !== null)
  1769. {
  1770. // Discrete list of values, use a SELECT or RADIO buttons depending on the config
  1771. $sDisplayStyle = $oAttDef->GetDisplayStyle();
  1772. switch($sDisplayStyle)
  1773. {
  1774. case 'radio':
  1775. case 'radio_horizontal':
  1776. case 'radio_vertical':
  1777. $sHTMLValue = '';
  1778. $bVertical = ($sDisplayStyle != 'radio_horizontal');
  1779. $sHTMLValue = $oPage->GetRadioButtons($aAllowedValues, $value, $iId, "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", $bMandatory, $bVertical, $sValidationField);
  1780. $aEventsList[] ='change';
  1781. break;
  1782. case 'select':
  1783. default:
  1784. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1785. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1786. foreach($aAllowedValues as $key => $display_value)
  1787. {
  1788. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1789. {
  1790. // When there is only once choice, select it by default
  1791. $sSelected = ' selected';
  1792. }
  1793. else
  1794. {
  1795. $sSelected = ($value == $key) ? ' selected' : '';
  1796. }
  1797. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1798. }
  1799. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1800. $aEventsList[] ='change';
  1801. }
  1802. }
  1803. else
  1804. {
  1805. $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}";
  1806. $aEventsList[] ='keyup';
  1807. $aEventsList[] ='change';
  1808. }
  1809. break;
  1810. }
  1811. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1812. if (!empty($aEventsList))
  1813. {
  1814. $sNullValue = $oAttDef->GetNullValue();
  1815. if (!is_numeric($sNullValue))
  1816. {
  1817. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1818. }
  1819. $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
  1820. }
  1821. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1822. if (count($aDependencies) > 0)
  1823. {
  1824. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1825. }
  1826. }
  1827. return "<div>{$sHTMLValue}</div>";
  1828. }
  1829. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1830. {
  1831. self::$iGlobalFormId++;
  1832. $sPrefix = '';
  1833. if (isset($aExtraParams['formPrefix']))
  1834. {
  1835. $sPrefix = $aExtraParams['formPrefix'];
  1836. }
  1837. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  1838. $this->m_iFormId = $sPrefix.self::$iGlobalFormId;
  1839. $sClass = get_class($this);
  1840. $oAppContext = new ApplicationContext();
  1841. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1842. $iKey = $this->GetKey();
  1843. $aDetails = array();
  1844. $aFieldsMap = array();
  1845. if (!isset($aExtraParams['action']))
  1846. {
  1847. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1848. }
  1849. else
  1850. {
  1851. $sFormAction = $aExtraParams['action'];
  1852. }
  1853. // Custom label for the apply button ?
  1854. if (isset($aExtraParams['custom_button']))
  1855. {
  1856. $sApplyButton = $aExtraParams['custom_button'];
  1857. }
  1858. else if ($iKey > 0)
  1859. {
  1860. $sApplyButton = Dict::S('UI:Button:Apply');
  1861. }
  1862. else
  1863. {
  1864. $sApplyButton = Dict::S('UI:Button:Create');
  1865. }
  1866. // Custom operation for the form ?
  1867. if (isset($aExtraParams['custom_operation']))
  1868. {
  1869. $sOperation = $aExtraParams['custom_operation'];
  1870. }
  1871. else if ($iKey > 0)
  1872. {
  1873. $sOperation = 'apply_modify';
  1874. }
  1875. else
  1876. {
  1877. $sOperation = 'apply_new';
  1878. }
  1879. if ($iKey > 0)
  1880. {
  1881. // The object already exists in the database, it's a modification
  1882. $sButtons = "<input id=\"{$sPrefix}_id\" type=\"hidden\" name=\"id\" value=\"$iKey\">\n";
  1883. $sButtons .= "<input type=\"hidden\" name=\"operation\" value=\"{$sOperation}\">\n";
  1884. $sButtons .= "<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1885. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1886. }
  1887. else
  1888. {
  1889. // The object does not exist in the database it's a creation
  1890. $sButtons = "<input type=\"hidden\" name=\"operation\" value=\"$sOperation\">\n";
  1891. $sButtons .= "<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1892. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1893. }
  1894. $aTransitions = $this->EnumTransitions();
  1895. if (!isset($aExtraParams['custom_operation']) && count($aTransitions))
  1896. {
  1897. // transitions are displayed only for the standard new/modify actions, not for modify_all or any other case...
  1898. $oSetToCheckRights = DBObjectSet::FromObject($this);
  1899. $aStimuli = Metamodel::EnumStimuli($sClass);
  1900. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1901. {
  1902. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSetToCheckRights) : UR_ALLOWED_NO;
  1903. switch($iActionAllowed)
  1904. {
  1905. case UR_ALLOWED_YES:
  1906. $sButtons .= "<button type=\"submit\" name=\"next_action\" value=\"{$sStimulusCode}\" class=\"action\"><span>".$aStimuli[$sStimulusCode]->GetLabel()."</span></button>\n";
  1907. break;
  1908. default:
  1909. // Do nothing
  1910. }
  1911. }
  1912. }
  1913. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1914. $iTransactionId = isset($aExtraParams['transaction_id']) ? $aExtraParams['transaction_id'] : utils::GetNewTransactionId();
  1915. $oPage->SetTransactionId($iTransactionId);
  1916. $oPage->add("<form action=\"$sFormAction\" id=\"form_{$this->m_iFormId}\" enctype=\"multipart/form-data\" method=\"post\" onSubmit=\"return OnSubmit('form_{$this->m_iFormId}');\">\n");
  1917. $sStatesSelection = '';
  1918. if (!isset($aExtraParams['custom_operation']) && $this->IsNew())
  1919. {
  1920. $aInitialStates = MetaModel::EnumInitialStates($sClass);
  1921. //$aInitialStates = array('new' => 'foo', 'closed' => 'bar');
  1922. if (count($aInitialStates) > 1)
  1923. {
  1924. $sStatesSelection = Dict::Format('UI:Create_Class_InState', MetaModel::GetName($sClass)).'<select name="obj_state" class="state_select_'.$this->m_iFormId.'">';
  1925. foreach($aInitialStates as $sStateCode => $sStateData)
  1926. {
  1927. $sSelected = '';
  1928. if ($sStateCode == $this->GetState())
  1929. {
  1930. $sSelected = ' selected';
  1931. }
  1932. $sStatesSelection .= '<option value="'.$sStateCode.'"'.$sSelected.'>'.MetaModel::GetStateLabel($sClass, $sStateCode).'</option>';
  1933. }
  1934. $sStatesSelection .= '</select>';
  1935. $oPage->add_ready_script("$('.state_select_{$this->m_iFormId}').change( function() { oWizardHelper$sPrefix.ReloadObjectCreationForm('form_{$this->m_iFormId}', $(this).val()); } );");
  1936. }
  1937. }
  1938. $sConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage'));
  1939. $oPage->add_ready_script(
  1940. <<<EOF
  1941. $(window).unload(function() { return OnUnload('$iTransactionId') } );
  1942. window.onbeforeunload = function() {
  1943. if (!window.bInSubmit && !window.bInCancel)
  1944. {
  1945. return '$sConfirmationMessage';
  1946. }
  1947. // return nothing ! safer for IE
  1948. };
  1949. EOF
  1950. );
  1951. if ($sButtonsPosition != 'bottom')
  1952. {
  1953. // top or both, display the buttons here
  1954. $oPage->p($sStatesSelection);
  1955. $oPage->add($sButtons);
  1956. }
  1957. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1958. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1959. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1960. $aFieldsMap = $this->DisplayBareProperties($oPage, true, $sPrefix, $aExtraParams);
  1961. if ($iKey > 0)
  1962. {
  1963. $aFieldsMap['id'] = $sPrefix.'_id';
  1964. }
  1965. // Now display the relations, one tab per relation
  1966. if (!isset($aExtraParams['noRelations']))
  1967. {
  1968. $this->DisplayBareRelations($oPage, true); // Edit mode
  1969. }
  1970. $oPage->SetCurrentTab('');
  1971. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1972. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"$iTransactionId\">\n");
  1973. foreach($aExtraParams as $sName => $value)
  1974. {
  1975. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1976. }
  1977. $oPage->add($oAppContext->GetForForm());
  1978. if ($sButtonsPosition != 'top')
  1979. {
  1980. // bottom or both: display the buttons here
  1981. $oPage->p($sStatesSelection);
  1982. $oPage->add($sButtons);
  1983. }
  1984. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1985. $sDefaultUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=cancel&'.$oAppContext->GetForLink();
  1986. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1987. $oPage->add("</form>\n");
  1988. $iFieldsCount = count($aFieldsMap);
  1989. $sJsonFieldsMap = json_encode($aFieldsMap);
  1990. $sState = $this->GetState();
  1991. $oPage->add_script(
  1992. <<<EOF
  1993. // Create the object once at the beginning of the page...
  1994. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix', '$sState');
  1995. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1996. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1997. EOF
  1998. );
  1999. $oPage->add_ready_script(
  2000. <<<EOF
  2001. oWizardHelper$sPrefix.UpdateWizard();
  2002. // Starts the validation when the page is ready
  2003. CheckFields('form_{$this->m_iFormId}', false);
  2004. EOF
  2005. );
  2006. }
  2007. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  2008. {
  2009. $oAppContext = new ApplicationContext();
  2010. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  2011. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  2012. $aStates = MetaModel::EnumStates($sClass);
  2013. $sStatesSelection = '';
  2014. if ($oObjectToClone == null)
  2015. {
  2016. $oObj = MetaModel::NewObject($sClass);
  2017. if (!empty($sStateAttCode))
  2018. {
  2019. $sTargetState = MetaModel::GetDefaultState($sClass);
  2020. $oObj->Set($sStateAttCode, $sTargetState);
  2021. }
  2022. }
  2023. else
  2024. {
  2025. $oObj = clone $oObjectToClone;
  2026. }
  2027. // Pre-fill the object with default values, when there is only on possible choice
  2028. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  2029. $aArgs['this'] = $oObj;
  2030. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  2031. // Order the fields based on their dependencies
  2032. $aDeps = array();
  2033. foreach($aDetailsList as $sAttCode)
  2034. {
  2035. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  2036. }
  2037. $aList = self::OrderDependentFields($aDeps);
  2038. // Now fill-in the fields with default/supplied values
  2039. foreach($aList as $sAttCode)
  2040. {
  2041. if (isset($aArgs['default'][$sAttCode]))
  2042. {
  2043. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  2044. }
  2045. else
  2046. {
  2047. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  2048. // If the field is mandatory, set it to the only possible value
  2049. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  2050. if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  2051. {
  2052. if ($oAttDef->IsExternalKey())
  2053. {
  2054. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  2055. if ($oAllowedValues->Count() == 1)
  2056. {
  2057. $oRemoteObj = $oAllowedValues->Fetch();
  2058. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  2059. }
  2060. }
  2061. else
  2062. {
  2063. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  2064. if (count($aAllowedValues) == 1)
  2065. {
  2066. $aValues = array_keys($aAllowedValues);
  2067. $oObj->Set($sAttCode, $aValues[0]);
  2068. }
  2069. }
  2070. }
  2071. }
  2072. }
  2073. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  2074. }
  2075. public static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  2076. {
  2077. //echo "<pre>ZList: ";
  2078. //print_r($aList);
  2079. //echo "</pre>\n";
  2080. $index = 0;
  2081. foreach($aList as $sKey => $value)
  2082. {
  2083. if (is_array($value))
  2084. {
  2085. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  2086. {
  2087. $sCode = $aMatches[1];
  2088. $sName = $aMatches[2];
  2089. switch($sCode)
  2090. {
  2091. case 'tab':
  2092. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  2093. if(!isset($aDetails[$sName]))
  2094. {
  2095. $aDetails[$sName] = array('col1' => array());
  2096. }
  2097. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  2098. break;
  2099. case 'fieldset':
  2100. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  2101. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  2102. {
  2103. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  2104. }
  2105. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  2106. break;
  2107. default:
  2108. case 'col':
  2109. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  2110. if(!isset($aDetails[$sCurrentTab][$sName]))
  2111. {
  2112. $aDetails[$sCurrentTab][$sName] = array();
  2113. }
  2114. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  2115. break;
  2116. }
  2117. }
  2118. }
  2119. else
  2120. {
  2121. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  2122. if (empty($sCurrentSet))
  2123. {
  2124. $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value;
  2125. }
  2126. else
  2127. {
  2128. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  2129. }
  2130. }
  2131. $index++;
  2132. }
  2133. return $aDetails;
  2134. }
  2135. static function FlattenZList($aList)
  2136. {
  2137. $aResult = array();
  2138. foreach($aList as $value)
  2139. {
  2140. if (!is_array($value))
  2141. {
  2142. $aResult[] = $value;
  2143. }
  2144. else
  2145. {
  2146. $aResult = array_merge($aResult,self::FlattenZList($value));
  2147. }
  2148. }
  2149. return $aResult;
  2150. }
  2151. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  2152. {
  2153. $retVal = null;
  2154. if ($this->IsNew())
  2155. {
  2156. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2157. }
  2158. else
  2159. {
  2160. $iFlags = $this->GetAttributeFlags($sAttCode);
  2161. }
  2162. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  2163. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  2164. {
  2165. // The field is visible in the current state of the object
  2166. if ($sStateAttCode == $sAttCode)
  2167. {
  2168. // Special display for the 'state' attribute itself
  2169. $sDisplayValue = $this->GetStateLabel();
  2170. }
  2171. else if ($oAttDef->GetEditClass() == 'Document')
  2172. {
  2173. $oDocument = $this->Get($sAttCode);
  2174. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2175. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2176. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDownloadLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2177. }
  2178. else
  2179. {
  2180. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2181. }
  2182. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  2183. }
  2184. return $retVal;
  2185. }
  2186. /**
  2187. * Displays a blob document *inline* (if possible, depending on the type of the document)
  2188. * @return string
  2189. */
  2190. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  2191. {
  2192. $oDoc = $this->Get($sAttCode);
  2193. $sClass = get_class($this);
  2194. $Id = $this->GetKey();
  2195. switch ($oDoc->GetMainMimeType())
  2196. {
  2197. case 'text':
  2198. case 'html':
  2199. $data = $oDoc->GetData();
  2200. switch($oDoc->GetMimeType())
  2201. {
  2202. case 'text/html':
  2203. case 'text/xml':
  2204. $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");
  2205. break;
  2206. default:
  2207. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true), ENT_QUOTES, 'UTF-8')."</pre>\n");
  2208. }
  2209. break;
  2210. case 'application':
  2211. switch($oDoc->GetMimeType())
  2212. {
  2213. case 'application/pdf':
  2214. $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");
  2215. break;
  2216. default:
  2217. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2218. }
  2219. break;
  2220. case 'image':
  2221. $oPage->add("<img src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  2222. break;
  2223. default:
  2224. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2225. }
  2226. }
  2227. // $m_highlightComparison[previous][new] => next value
  2228. protected static $m_highlightComparison = array(
  2229. HILIGHT_CLASS_CRITICAL => array(
  2230. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2231. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL,
  2232. HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL,
  2233. HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL,
  2234. ),
  2235. HILIGHT_CLASS_WARNING => array(
  2236. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2237. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2238. HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING,
  2239. HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING,
  2240. ),
  2241. HILIGHT_CLASS_OK => array(
  2242. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2243. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2244. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2245. HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK,
  2246. ),
  2247. HILIGHT_CLASS_NONE => array(
  2248. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2249. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2250. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2251. HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE,
  2252. ),
  2253. );
  2254. /**
  2255. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  2256. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  2257. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2258. * To Be overridden by derived classes
  2259. * @param void
  2260. * @return String The desired higlight class for the object/row
  2261. */
  2262. public function GetHilightClass()
  2263. {
  2264. // Possible return values are:
  2265. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2266. $current = HILIGHT_CLASS_NONE; // Not hilighted by default
  2267. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2268. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2269. {
  2270. $new = $oExtensionInstance->GetHilightClass($this);
  2271. @$current = self::$m_highlightComparison[$current][$new];
  2272. }
  2273. return $current;
  2274. }
  2275. /**
  2276. * Re-order the fields based on their inter-dependencies
  2277. * @params hash @aFields field_code => array_of_depencies
  2278. * @return array Ordered array of fields or throws an exception
  2279. */
  2280. public static function OrderDependentFields($aFields)
  2281. {
  2282. $bCircular = false;
  2283. $aResult = array();
  2284. $iCount = 0;
  2285. do
  2286. {
  2287. $bSet = false;
  2288. $iCount++;
  2289. foreach($aFields as $sFieldCode => $aDeps)
  2290. {
  2291. foreach($aDeps as $key => $sDependency)
  2292. {
  2293. if (in_array($sDependency, $aResult))
  2294. {
  2295. // Dependency is resolved, remove it
  2296. unset($aFields[$sFieldCode][$key]);
  2297. }
  2298. }
  2299. if (count($aFields[$sFieldCode]) == 0)
  2300. {
  2301. // No more pending depencies for this field, add it to the list
  2302. $aResult[] = $sFieldCode;
  2303. unset($aFields[$sFieldCode]);
  2304. $bSet = true;
  2305. }
  2306. }
  2307. }
  2308. while($bSet && (count($aFields) > 0));
  2309. if (count($aFields) > 0)
  2310. {
  2311. $sMessage = "Error: Circular dependencies between the fields (or field missing in ZList) ! <pre>".print_r($aFields, true)."</pre>";
  2312. throw(new Exception($sMessage));
  2313. }
  2314. return $aResult;
  2315. }
  2316. /**
  2317. * Get the list of actions to be displayed as 'shortcuts' (i.e buttons) instead of inside the Actions popup menu
  2318. * @param $sFinalClass string The actual class of the objects for which to display the menu
  2319. * @return Array the list of menu codes (i.e dictionary entries) that can be displayed as shortcuts next to the actions menu
  2320. */
  2321. public static function GetShortcutActions($sFinalClass)
  2322. {
  2323. $sShortcutActions = MetaModel::GetConfig()->Get('shortcut_actions');
  2324. $aShortcutActions = explode(',', $sShortcutActions);
  2325. return $aShortcutActions;
  2326. }
  2327. /**
  2328. * Maps the given context parameter name to the appropriate filter/search code for this class
  2329. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  2330. * @return string Filter code, i.e. 'customer_id'
  2331. */
  2332. public static function MapContextParam($sContextParam)
  2333. {
  2334. if ($sContextParam == 'menu')
  2335. {
  2336. return null;
  2337. }
  2338. else
  2339. {
  2340. return $sContextParam;
  2341. }
  2342. }
  2343. /**
  2344. * Updates the object from a flat array of values
  2345. * @param $aAttList array $aAttList array of attcode
  2346. * @param $aErrors array Returns information about slave attributes
  2347. * @param $sTargetState string Target state for which to evaluate the writeable attributes (=current state is empty)
  2348. * @return array of attcodes that can be used for writing on the current object
  2349. */
  2350. public function GetWriteableAttList($aAttList, &$aErrors, $sTargetState = '')
  2351. {
  2352. if (!is_array($aAttList))
  2353. {
  2354. $aAttList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2355. // Special case to process the case log, if any...
  2356. // WARNING: if you change this also check the functions DisplayModifyForm and DisplayCaseLog
  2357. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2358. {
  2359. if ($this->IsNew())
  2360. {
  2361. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2362. }
  2363. else
  2364. {
  2365. $aVoid = array();
  2366. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2367. }
  2368. if ($oAttDef instanceof AttributeCaseLog)
  2369. {
  2370. if (!($iFlags & (OPT_ATT_HIDDEN|OPT_ATT_SLAVE|OPT_ATT_READONLY)))
  2371. {
  2372. // The case log is editable, append it to the list of fields to retrieve
  2373. $aAttList[] = $sAttCode;
  2374. }
  2375. }
  2376. }
  2377. }
  2378. $aWriteableAttList = array();
  2379. foreach($aAttList as $sAttCode)
  2380. {
  2381. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2382. if ($this->IsNew())
  2383. {
  2384. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2385. }
  2386. else
  2387. {
  2388. $aVoid = array();
  2389. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2390. }
  2391. if ($oAttDef->IsWritable())
  2392. {
  2393. if ( $iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  2394. {
  2395. // Non-visible, or read-only attribute, do nothing
  2396. }
  2397. elseif($iFlags & OPT_ATT_SLAVE)
  2398. {
  2399. $aErrors[$sAttCode] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  2400. }
  2401. else
  2402. {
  2403. $aWriteableAttList[$sAttCode] = $oAttDef;
  2404. }
  2405. }
  2406. }
  2407. return $aWriteableAttList;
  2408. }
  2409. /**
  2410. * Updates the object from a flat array of values
  2411. * @param string $aValues array of attcode => scalar or array (N-N links)
  2412. * @return void
  2413. */
  2414. public function UpdateObjectFromArray($aValues)
  2415. {
  2416. foreach($aValues as $sAttCode => $value)
  2417. {
  2418. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2419. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  2420. {
  2421. $aLinks = $value;
  2422. $sLinkedClass = $oAttDef->GetLinkedClass();
  2423. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  2424. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2425. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  2426. if (is_array($aLinks))
  2427. {
  2428. foreach($aLinks as $id => $aData)
  2429. {
  2430. if (is_numeric($id))
  2431. {
  2432. if ($id < 0)
  2433. {
  2434. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  2435. $oLink = MetaModel::NewObject($sLinkedClass);
  2436. $oLink->Set($sExtKeyToRemote, -$id);
  2437. $oLink->Set($sExtKeyToMe, $this->GetKey());
  2438. }
  2439. else
  2440. {
  2441. // Existing link, potentially to be updated...
  2442. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  2443. }
  2444. // Now populate the attributes
  2445. foreach($aData as $sName => $value)
  2446. {
  2447. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  2448. {
  2449. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  2450. if ($oLinkAttDef->IsWritable())
  2451. {
  2452. $oLink->Set($sName, $value);
  2453. }
  2454. }
  2455. }
  2456. $oLinkedSet->AddObject($oLink);
  2457. }
  2458. }
  2459. }
  2460. $this->Set($sAttCode, $oLinkedSet);
  2461. }
  2462. elseif ($oAttDef->GetEditClass() == 'Document')
  2463. {
  2464. // There should be an uploaded file with the named attr_<attCode>
  2465. $oDocument = $value['fcontents'];
  2466. if (!$oDocument->IsEmpty())
  2467. {
  2468. // A new file has been uploaded
  2469. $this->Set($sAttCode, $oDocument);
  2470. }
  2471. }
  2472. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  2473. {
  2474. // Check if the password was typed/changed
  2475. $aPwdData = $value;
  2476. if (!is_null($aPwdData) && $aPwdData['changed'])
  2477. {
  2478. // The password has been changed or set
  2479. $this->Set($sAttCode, $aPwdData['value']);
  2480. }
  2481. }
  2482. elseif ($oAttDef->GetEditClass() == 'Duration')
  2483. {
  2484. $aDurationData = $value;
  2485. if (!is_array($aDurationData)) continue;
  2486. $iValue = (((24*$aDurationData['d'])+$aDurationData['h'])*60 +$aDurationData['m'])*60 + $aDurationData['s'];
  2487. $this->Set($sAttCode, $iValue);
  2488. $previousValue = $this->Get($sAttCode);
  2489. if ($previousValue !== $iValue)
  2490. {
  2491. $this->Set($sAttCode, $iValue);
  2492. }
  2493. }
  2494. else
  2495. {
  2496. if (!is_null($value))
  2497. {
  2498. $aAttributes[$sAttCode] = trim($value);
  2499. $previousValue = $this->Get($sAttCode);
  2500. if ($previousValue !== $aAttributes[$sAttCode])
  2501. {
  2502. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  2503. }
  2504. }
  2505. }
  2506. }
  2507. }
  2508. /**
  2509. * Updates the object from the POSTed parameters (form)
  2510. */
  2511. public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $sTargetState = '')
  2512. {
  2513. if (is_null($aAttList))
  2514. {
  2515. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2516. }
  2517. $aValues = array();
  2518. foreach($aAttList as $sAttCode)
  2519. {
  2520. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2521. if ($oAttDef->GetEditClass() == 'Document')
  2522. {
  2523. $value = array('fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'));
  2524. }
  2525. else
  2526. {
  2527. $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data');
  2528. }
  2529. if (!is_null($value))
  2530. {
  2531. $aValues[$sAttCode] = $value;
  2532. }
  2533. }
  2534. $aErrors = array();
  2535. $aFinalValues = array();
  2536. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2537. {
  2538. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2539. }
  2540. $this->UpdateObjectFromArray($aFinalValues);
  2541. // Invoke extensions after the update of the object from the form
  2542. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2543. {
  2544. $oExtensionInstance->OnFormSubmit($this, $sFormPrefix);
  2545. }
  2546. return $aErrors;
  2547. }
  2548. /**
  2549. * Updates the object from a given page argument
  2550. */
  2551. public function UpdateObjectFromArg($sArgName, $aAttList = null, $sTargetState = '')
  2552. {
  2553. if (is_null($aAttList))
  2554. {
  2555. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2556. }
  2557. $aRawValues = utils::ReadParam($sArgName, array(), '', 'raw_data');
  2558. $aValues = array();
  2559. foreach($aAttList as $sAttCode)
  2560. {
  2561. if (isset($aRawValues[$sAttCode]))
  2562. {
  2563. $aValues[$sAttCode] = $aRawValues[$sAttCode];
  2564. }
  2565. }
  2566. $aErrors = array();
  2567. $aFinalValues = array();
  2568. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2569. {
  2570. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2571. }
  2572. $this->UpdateObjectFromArray($aFinalValues);
  2573. return $aErrors;
  2574. }
  2575. protected function DBInsertTracked_Internal($bDoNotReload = false)
  2576. {
  2577. $res = parent::DBInsertTracked_Internal($bDoNotReload);
  2578. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2579. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2580. {
  2581. $oExtensionInstance->OnDBInsert($this, self::$m_oCurrChange);
  2582. }
  2583. return $res;
  2584. }
  2585. protected function DBCloneTracked_Internal($newKey = null)
  2586. {
  2587. $oNewObj = parent::DBCloneTracked_Internal($newKey);
  2588. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2589. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2590. {
  2591. $oExtensionInstance->OnDBInsert($oNewObj, self::$m_oCurrChange);
  2592. }
  2593. return $oNewObj;
  2594. }
  2595. protected function DBUpdateTracked_Internal()
  2596. {
  2597. $res = parent::DBUpdateTracked_Internal();
  2598. // Invoke extensions after the update (could be before)
  2599. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2600. {
  2601. $oExtensionInstance->OnDBUpdate($this, self::$m_oCurrChange);
  2602. }
  2603. return $res;
  2604. }
  2605. protected static function BulkUpdateTracked_Internal(DBObjectSearch $oFilter, array $aValues)
  2606. {
  2607. // Todo - invoke the extension
  2608. return parent::BulkUpdateTracked_Internal($oFilter, $aValues);
  2609. }
  2610. protected function DBDeleteTracked_Internal(&$oDeletionPlan = null)
  2611. {
  2612. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2613. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2614. {
  2615. $oExtensionInstance->OnDBDelete($this, self::$m_oCurrChange);
  2616. }
  2617. return parent::DBDeleteTracked_Internal($oDeletionPlan);
  2618. }
  2619. protected static function BulkDeleteTracked_Internal(DBObjectSearch $oFilter)
  2620. {
  2621. // Todo - invoke the extension
  2622. return parent::BulkDeleteTracked_Internal($oFilter);
  2623. }
  2624. public function IsModified()
  2625. {
  2626. if (parent::IsModified())
  2627. {
  2628. return true;
  2629. }
  2630. // Plugins
  2631. //
  2632. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2633. {
  2634. if ($oExtensionInstance->OnIsModified($this))
  2635. {
  2636. return true;
  2637. }
  2638. }
  2639. }
  2640. public function DoCheckToWrite()
  2641. {
  2642. parent::DoCheckToWrite();
  2643. // Plugins
  2644. //
  2645. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2646. {
  2647. $aNewIssues = $oExtensionInstance->OnCheckToWrite($this);
  2648. if (count($aNewIssues) > 0)
  2649. {
  2650. $this->m_aCheckIssues = array_merge($this->m_aCheckIssues, $aNewIssues);
  2651. }
  2652. }
  2653. // User rights
  2654. //
  2655. $aChanges = $this->ListChanges();
  2656. if (count($aChanges) > 0)
  2657. {
  2658. $aForbiddenFields = array();
  2659. foreach ($this->ListChanges() as $sAttCode => $value)
  2660. {
  2661. $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute(get_class($this), $sAttCode, UR_ACTION_MODIFY, DBObjectSet::FromObject($this));
  2662. if (!$bUpdateAllowed)
  2663. {
  2664. $oAttCode = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2665. $aForbiddenFields[] = $oAttCode->GetLabel();
  2666. }
  2667. }
  2668. if (count($aForbiddenFields) > 0)
  2669. {
  2670. // Security issue
  2671. $this->m_bSecurityIssue = true;
  2672. $this->m_aCheckIssues[] = Dict::Format('UI:Delete:NotAllowedToUpdate_Fields',implode(', ', $aForbiddenFields));
  2673. }
  2674. }
  2675. }
  2676. protected function DoCheckToDelete(&$oDeletionPlan)
  2677. {
  2678. parent::DoCheckToDelete($oDeletionPlan);
  2679. // Plugins
  2680. //
  2681. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2682. {
  2683. $aNewIssues = $oExtensionInstance->OnCheckToDelete($this);
  2684. if (count($aNewIssues) > 0)
  2685. {
  2686. $this->m_aDeleteIssues = array_merge($this->m_aDeleteIssues, $aNewIssues);
  2687. }
  2688. }
  2689. // User rights
  2690. //
  2691. $bDeleteAllowed = UserRights::IsActionAllowed(get_class($this), UR_ACTION_DELETE, DBObjectSet::FromObject($this));
  2692. if (!$bDeleteAllowed)
  2693. {
  2694. // Security issue
  2695. $this->m_bSecurityIssue = true;
  2696. $this->m_aDeleteIssues[] = Dict::S('UI:Delete:NotAllowedToDelete');
  2697. }
  2698. }
  2699. /**
  2700. * Special display where the case log uses the whole "screen" at the bottom of the "Properties" tab
  2701. */
  2702. public function DisplayCaseLog(WebPage $oPage, $sAttCode, $sComment = '', $sPrefix = '', $bEditMode = false)
  2703. {
  2704. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  2705. $sClass = get_class($this);
  2706. if ($this->IsNew())
  2707. {
  2708. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2709. }
  2710. else
  2711. {
  2712. $iFlags = $this->GetAttributeFlags($sAttCode);
  2713. }
  2714. if ( $iFlags & OPT_ATT_HIDDEN)
  2715. {
  2716. // The case log is hidden do nothing
  2717. }
  2718. else
  2719. {
  2720. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2721. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  2722. if ((!$bEditMode) || ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE)))
  2723. {
  2724. // Check if the attribute is not read-only because of a synchro...
  2725. $aReasons = array();
  2726. $sSynchroIcon = '';
  2727. if ($iFlags & OPT_ATT_SLAVE)
  2728. {
  2729. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  2730. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  2731. $sTip = '';
  2732. foreach($aReasons as $aRow)
  2733. {
  2734. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  2735. }
  2736. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  2737. }
  2738. // Attribute is read-only
  2739. $sHTMLValue = $this->GetAsHTML($sAttCode);
  2740. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>';
  2741. $aFieldsMap[$sAttCode] = $sInputId;
  2742. $sComment .= $sSynchroIcon;
  2743. }
  2744. else
  2745. {
  2746. $sValue = $this->Get($sAttCode);
  2747. $sDisplayValue = $this->GetEditValue($sAttCode);
  2748. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  2749. $sHTMLValue = '';
  2750. if ($sComment != '')
  2751. {
  2752. $sHTMLValue = '<span>'.$sComment.'</span><br/>';
  2753. }
  2754. $sHTMLValue .= "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  2755. $aFieldsMap[$sAttCode] = $sInputId;
  2756. }
  2757. //$aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  2758. $oPage->add('<fieldset><legend>'.$oAttDef->GetLabel().'</legend>');
  2759. $oPage->add($sHTMLValue);
  2760. $oPage->add('</fieldset>');
  2761. }
  2762. }
  2763. public function GetExpectedAttributes($sCurrentState, $sStimulus, $bOnlyNewOnes)
  2764. {
  2765. $aTransitions = $this->EnumTransitions();
  2766. $aStimuli = MetaModel::EnumStimuli(get_class($this));
  2767. if (!isset($aTransitions[$sStimulus]))
  2768. {
  2769. // Invalid stimulus
  2770. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  2771. }
  2772. $aTransition = $aTransitions[$sStimulus];
  2773. $sTargetState = $aTransition['target_state'];
  2774. $aTargetStates = MetaModel::EnumStates(get_class($this));
  2775. $aTargetState = $aTargetStates[$sTargetState];
  2776. $aCurrentState = $aTargetStates[$this->GetState()];
  2777. $aExpectedAttributes = $aTargetState['attribute_list'];
  2778. $aCurrentAttributes = $aCurrentState['attribute_list'];
  2779. $aComputedAttributes = array();
  2780. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  2781. {
  2782. if (!array_key_exists($sAttCode, $aCurrentAttributes))
  2783. {
  2784. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2785. }
  2786. else
  2787. {
  2788. if ( !($aCurrentAttributes[$sAttCode] & (OPT_ATT_HIDDEN|OPT_ATT_READONLY)) )
  2789. {
  2790. $iExpectCode = $iExpectCode & ~(OPT_ATT_MUSTPROMPT|OPT_ATT_MUSTCHANGE); // Already prompted/changed, reset the flags
  2791. }
  2792. //TODO: better check if the attribute is not *null*
  2793. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($this->Get($sAttCode) != ''))
  2794. {
  2795. $iExpectCode = $iExpectCode & ~(OPT_ATT_MANDATORY); // If the attribute is present, then no need to request its presence
  2796. }
  2797. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2798. }
  2799. $aComputedAttributes[$sAttCode] = $aComputedAttributes[$sAttCode] & ~(OPT_ATT_READONLY|OPT_ATT_HIDDEN); // Don't care about this form now
  2800. if ($aComputedAttributes[$sAttCode] == 0)
  2801. {
  2802. unset($aComputedAttributes[$sAttCode]);
  2803. }
  2804. }
  2805. return $aComputedAttributes;
  2806. }
  2807. }
  2808. ?>