cmdbabstract.class.inc.php 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  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 '../pages/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. $oReplicaSet = $this->GetMasterReplica();
  95. $bSynchronized = false;
  96. $bCreated = false;
  97. $bCanBeDeleted = false;
  98. $aMasterSources = array();
  99. if ($oReplicaSet->Count() > 0)
  100. {
  101. $bSynchronized = true;
  102. $sTip = "<p>".Dict::S('Core:Synchro:ThisObjectIsSynchronized')."</p>";
  103. while($aData = $oReplicaSet->FetchAssoc())
  104. {
  105. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  106. $sApplicationURL = $aData['datasource']->GetApplicationUrl($this, $aData['replica']);
  107. $sLink = $aData['datasource']->GetName();
  108. if (!empty($sApplicationURL))
  109. {
  110. $sLink = "<a href=\"$sApplicationURL\" target=\"_blank\">".$aData['datasource']->GetName()."</a>";
  111. }
  112. if ($aData['replica']->Get('status_dest_creator') == 1)
  113. {
  114. $sTip .= "<p>".Dict::Format('Core:Synchro:TheObjectWasCreatedBy_Source', $sLink)."</p>";
  115. $bCreated = true;
  116. }
  117. if ($bCreated)
  118. {
  119. $sDeletePolicy = $aData['datasource']->Get('delete_policy');
  120. if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete'))
  121. {
  122. $bCanBeDeleted = true;
  123. $sTip .= "<p>".Dict::Format('Core:Synchro:TheObjectCanBeDeletedBy_Source', $sLink)."</p>";
  124. }
  125. }
  126. $aMasterSources[$aData['datasource']->GetKey()]['datasource'] = $aData['datasource'];
  127. $aMasterSources[$aData['datasource']->GetKey()]['url'] = $sLink;
  128. $aMasterSources[$aData['datasource']->GetKey()]['last_synchro'] = $aData['replica']->Get('status_last_seen');
  129. }
  130. }
  131. $sSynchroIcon = '';
  132. if ($bSynchronized)
  133. {
  134. $sTip .= "<p><b>".Dict::S('Core:Synchro:ListOfDataSources')."</b></p>";
  135. foreach($aMasterSources as $aStruct)
  136. {
  137. $oDataSource = $aStruct['datasource'];
  138. $sLink = $aStruct['url'];
  139. $sTip .= "<p style=\"white-space:nowrap\">".$oDataSource->GetIcon(true, 'style="vertical-align:middle"')."&nbsp;$sLink<br/>";
  140. $sTip .= Dict::S('Core:Synchro:LastSynchro').'<br/>'.$aStruct['last_synchro']."</p>";
  141. }
  142. $sSynchroIcon = '&nbsp;<img style="vertical-align:middle;" id="synchro_icon" src="../images/locked.png"/>';
  143. $oPage->add_ready_script("$('#synchro_icon').qtip( { content: '$sTip', show: 'mouseover', hide: 'unfocus', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  144. }
  145. $oPage->add("<div class=\"page_header\"><h1>".$this->GetIcon()."&nbsp;\n");
  146. $oPage->add(MetaModel::GetName(get_class($this)).": <span class=\"hilite\">".$this->GetName()."</span>$sSynchroIcon</h1>\n");
  147. $oPage->add("</div>\n");
  148. }
  149. function DisplayBareHistory(WebPage $oPage, $bEditMode = false)
  150. {
  151. // history block (with as a tab)
  152. $oHistoryFilter = new DBObjectSearch('CMDBChangeOp');
  153. $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '=');
  154. $oHistoryFilter->AddCondition('objclass', get_class($this), '=');
  155. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  156. $oBlock->Display($oPage, -1);
  157. }
  158. function DisplayBareProperties(WebPage $oPage, $bEditMode = false)
  159. {
  160. $oPage->add($this->GetBareProperties($oPage, $bEditMode));
  161. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  162. {
  163. $oExtensionInstance->OnDisplayProperties($this, $oPage, $bEditMode);
  164. }
  165. }
  166. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  167. {
  168. // Related objects: display all the linkset attributes, each as a separate tab
  169. // In the order described by the 'display' ZList
  170. $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  171. if (count($aList) == 0)
  172. {
  173. // Empty ZList defined, display all the linkedset attributes defined
  174. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  175. }
  176. $sClass = get_class($this);
  177. foreach($aList as $sAttCode)
  178. {
  179. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  180. // Display mode
  181. if (!$oAttDef->IsLinkset()) continue; // Process only linkset attributes...
  182. $oPage->SetCurrentTab($oAttDef->GetLabel());
  183. if ($bEditMode)
  184. {
  185. $iFlags = $this->GetAttributeFlags($sAttCode);
  186. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  187. if (get_class($oAttDef) == 'AttributeLinkedSet')
  188. {
  189. // 1:n links
  190. $sTargetClass = $oAttDef->GetLinkedClass();
  191. if ($this->IsNew())
  192. {
  193. $oPage->p(Dict::Format('UI:BeforeAdding_Class_ObjectsSaveThisObject', MetaModel::GetName($sTargetClass)));
  194. }
  195. else
  196. {
  197. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  198. $oFilter = new DBObjectSearch($sTargetClass);
  199. $oFilter->AddCondition($oAttDef->GetExtKeyToMe(), $this->GetKey(),'=');
  200. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  201. $oAppContext = new ApplicationContext();
  202. foreach($oAppContext->GetNames() as $sKey)
  203. {
  204. // The linked object inherits the parent's value for the context
  205. if (MetaModel::IsValidAttCode($sClass, $sKey))
  206. {
  207. $aDefaults[$sKey] = $this->Get($sKey);
  208. }
  209. }
  210. $aParams = array(
  211. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  212. 'object_id' => $this->GetKey(),
  213. 'menu' => true,
  214. 'default' => $aDefaults,
  215. );
  216. $oBlock = new DisplayBlock($oFilter, 'list', false);
  217. $oBlock->Display($oPage, $sInputId, $aParams);
  218. }
  219. }
  220. else // get_class($oAttDef) == 'AttributeLinkedSetIndirect'
  221. {
  222. // n:n links
  223. $sLinkedClass = $oAttDef->GetLinkedClass();
  224. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  225. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  226. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription().'<span id="busy_'.$sInputId.'"></span>');
  227. $sValue = $this->Get($sAttCode);
  228. $sDisplayValue = $this->GetEditValue($sAttCode);
  229. $aArgs = array('this' => $this);
  230. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  231. $aFieldsMap[$sAttCode] = $sInputId;
  232. $oPage->add($sHTMLValue);
  233. }
  234. }
  235. else
  236. {
  237. // Display mode
  238. if (!$oAttDef->IsIndirect())
  239. {
  240. // 1:n links
  241. $sTargetClass = $oAttDef->GetLinkedClass();
  242. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  243. $oAppContext = new ApplicationContext();
  244. foreach($oAppContext->GetNames() as $sKey)
  245. {
  246. // The linked object inherits the parent's value for the context
  247. if (MetaModel::IsValidAttCode($sClass, $sKey))
  248. {
  249. $aDefaults[$sKey] = $this->Get($sKey);
  250. }
  251. }
  252. $aParams = array(
  253. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  254. 'object_id' => $this->GetKey(),
  255. 'menu' => false,
  256. 'default' => $aDefaults,
  257. );
  258. }
  259. else
  260. {
  261. // n:n links
  262. $sLinkedClass = $oAttDef->GetLinkedClass();
  263. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  264. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  265. $bMenu = ($this->Get($sAttCode)->Count() > 0); // The menu is enabled only if there are already some elements...
  266. $aParams = array(
  267. 'link_attr' => $oAttDef->GetExtKeyToMe(),
  268. 'object_id' => $this->GetKey(),
  269. 'target_attr' => $oAttDef->GetExtKeyToRemote(),
  270. 'view_link' => false,
  271. 'menu' => false,
  272. 'display_limit' => true, // By default limit the list to speed up the initial load & display
  273. );
  274. }
  275. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  276. $oBlock = new DisplayBlock($this->Get($sAttCode)->GetFilter(), 'list', false);
  277. $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams);
  278. }
  279. }
  280. $oPage->SetCurrentTab('');
  281. if (!$bEditMode)
  282. {
  283. // Get the actual class of the current object
  284. // And look for triggers referring to it
  285. // If any trigger has been found then display a tab with notifications
  286. //
  287. $sClass = get_class($this);
  288. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  289. $oTriggerSet = new CMDBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObject AS T WHERE T.target_class IN ('$sClassList')"));
  290. if ($oTriggerSet->Count() > 0)
  291. {
  292. $oPage->SetCurrentTab(Dict::S('UI:NotificationsTab'));
  293. // Display notifications regarding the object
  294. $iId = $this->GetKey();
  295. $oBlock = new DisplayBlock(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"), 'list', false);
  296. $oBlock->Display($oPage, 'notifications', array());
  297. }
  298. }
  299. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  300. {
  301. $oExtensionInstance->OnDisplayRelations($this, $oPage, $bEditMode);
  302. }
  303. }
  304. function GetBareProperties(WebPage $oPage, $bEditMode = false)
  305. {
  306. $sHtml = '';
  307. $oAppContext = new ApplicationContext();
  308. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  309. $aDetails = array();
  310. $sClass = get_class($this);
  311. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  312. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  313. // Compute the list of properties to display, first the attributes in the 'details' list, then
  314. // all the remaining attributes that are not external fields
  315. $sHtml = '';
  316. $aDetails = array();
  317. $iInputId = 0;
  318. foreach($aDetailsStruct as $sTab => $aCols )
  319. {
  320. $aDetails[$sTab] = array();
  321. ksort($aCols);
  322. $oPage->SetCurrentTab(Dict::S($sTab));
  323. $oPage->add('<table style="vertical-align:top"><tr>');
  324. foreach($aCols as $sColIndex => $aFieldsets)
  325. {
  326. $oPage->add('<td style="vertical-align:top">');
  327. //$aDetails[$sTab][$sColIndex] = array();
  328. $sLabel = '';
  329. $sPreviousLabel = '';
  330. $aDetails[$sTab][$sColIndex] = array();
  331. foreach($aFieldsets as $sFieldsetName => $aFields)
  332. {
  333. if (!empty($sFieldsetName) && ($sFieldsetName[0] != '_'))
  334. {
  335. $sLabel = $sFieldsetName;
  336. }
  337. else
  338. {
  339. $sLabel = '';
  340. }
  341. if ($sLabel != $sPreviousLabel)
  342. {
  343. if (!empty($sPreviousLabel))
  344. {
  345. $oPage->add('<fieldset>');
  346. $oPage->add('<legend>'.Dict::S($sPreviousLabel).'</legend>');
  347. }
  348. $oPage->Details($aDetails[$sTab][$sColIndex]);
  349. if (!empty($sPreviousLabel))
  350. {
  351. $oPage->add('</fieldset>');
  352. }
  353. $aDetails[$sTab][$sColIndex] = array();
  354. $sPreviousLabel = $sLabel;
  355. }
  356. foreach($aFields as $sAttCode)
  357. {
  358. $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode);
  359. if ($val != null)
  360. {
  361. /*
  362. * Removed for now...
  363. // Check if the attribute is not mastered by a synchro...
  364. $aReasons = array();
  365. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  366. $sSynchroIcon = '';
  367. if ($iSynchroFlags & OPT_ATT_SLAVE)
  368. {
  369. $sSynchroIcon = "&nbsp;<img id=\"synchro_$iInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  370. $sTip = '';
  371. foreach($aReasons as $aRow)
  372. {
  373. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  374. }
  375. $oPage->add_ready_script("$('#synchro_$iInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  376. }
  377. $val['comments'] = $sSynchroIcon;
  378. */
  379. // The field is visible, add it to the current column
  380. $aDetails[$sTab][$sColIndex][] = $val;
  381. $iInputId++;
  382. }
  383. }
  384. }
  385. if (!empty($sPreviousLabel))
  386. {
  387. $oPage->add('<fieldset>');
  388. $oPage->add('<legend>'.Dict::S($sFieldsetName).'</legend>');
  389. }
  390. $oPage->Details($aDetails[$sTab][$sColIndex]);
  391. if (!empty($sPreviousLabel))
  392. {
  393. $oPage->add('</fieldset>');
  394. }
  395. $oPage->add('</td>');
  396. }
  397. $oPage->add('</tr></table>');
  398. }
  399. return $sHtml;
  400. }
  401. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  402. {
  403. $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate(get_class($this)));
  404. if (!empty($sTemplate))
  405. {
  406. $oTemplate = new DisplayTemplate($sTemplate);
  407. // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved
  408. // but the preferred method is to use '$id$'
  409. $oTemplate->Render($oPage, array('class_name'=> MetaModel::GetName(get_class($this)),'class'=> get_class($this), 'pkey'=> $this->GetKey(), 'id'=> $this->GetKey(), 'name' => $this->Get('friendlyname')));
  410. }
  411. else
  412. {
  413. // Object's details
  414. // template not found display the object using the *old style*
  415. $this->DisplayBareHeader($oPage, $bEditMode);
  416. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  417. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  418. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  419. $this->DisplayBareProperties($oPage, $bEditMode);
  420. $this->DisplayBareRelations($oPage, $bEditMode);
  421. $oPage->SetCurrentTab(Dict::S('UI:HistoryTab'));
  422. $this->DisplayBareHistory($oPage, $bEditMode);
  423. }
  424. }
  425. function DisplayPreview(WebPage $oPage)
  426. {
  427. $aDetails = array();
  428. $sClass = get_class($this);
  429. $aList = MetaModel::GetZListItems($sClass, 'preview');
  430. foreach($aList as $sAttCode)
  431. {
  432. $aDetails[] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' =>$this->GetAsHTML($sAttCode));
  433. }
  434. $oPage->details($aDetails);
  435. }
  436. public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  437. {
  438. $oPage->add(self::GetDisplaySet($oPage, $oSet, $aExtraParams));
  439. }
  440. /**
  441. * Get the HTML fragment corresponding to the display of a table representing a set of objects
  442. * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output
  443. * @param CMDBObjectSet The set of objects to display
  444. * @param Hash $aExtraParams Some extra configuration parameters to tweak the behavior of the display
  445. * @return String The HTML fragment representing the table of objects
  446. */
  447. public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  448. {
  449. if (empty($aExtraParams['currentId']))
  450. {
  451. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  452. }
  453. else
  454. {
  455. $iListId = $aExtraParams['currentId'];
  456. }
  457. // Initialize and check the parameters
  458. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  459. $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
  460. $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0;
  461. $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : '';
  462. if (!empty($sLinkageAttribute))
  463. {
  464. if($iLinkedObjectId == 0)
  465. {
  466. // if 'links' mode is requested the id of the object to link to must be specified
  467. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  468. }
  469. if($sTargetAttr == '')
  470. {
  471. // if 'links' mode is requested the d of the object to link to must be specified
  472. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  473. }
  474. }
  475. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  476. $bTruncated = isset($aExtraParams['truncated']) ? $aExtraParams['truncated'] == true : true;
  477. $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
  478. $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
  479. $aExtraFields = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  480. $sHtml = '';
  481. $oAppContext = new ApplicationContext();
  482. $sClassName = $oSet->GetFilter()->GetClass();
  483. $aAttribs = array();
  484. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  485. $aList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  486. $aList = array_merge($aList, $aExtraFields);
  487. // Filter the list to removed linked set since we are not able to display them here
  488. foreach($aList as $index => $sAttCode)
  489. {
  490. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  491. if ($oAttDef instanceof AttributeLinkedSet)
  492. {
  493. // Removed from the display list
  494. unset($aList[$index]);
  495. }
  496. }
  497. if (!empty($sLinkageAttribute))
  498. {
  499. // The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
  500. // and other objects...
  501. // The display will then group all the attributes related to the link itself:
  502. // | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
  503. $aDisplayList = array();
  504. $aAttDefs = MetaModel::ListAttributeDefs($sClassName);
  505. assert(isset($aAttDefs[$sLinkageAttribute]));
  506. $oAttDef = $aAttDefs[$sLinkageAttribute];
  507. assert($oAttDef->IsExternalKey());
  508. // First display all the attributes specific to the link record
  509. foreach($aList as $sLinkAttCode)
  510. {
  511. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  512. if ( (!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField()) )
  513. {
  514. $aDisplayList[] = $sLinkAttCode;
  515. }
  516. }
  517. // Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
  518. foreach($aList as $sLinkAttCode)
  519. {
  520. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  521. if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
  522. || ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode()!=$sLinkageAttribute)) )
  523. {
  524. $aDisplayList[] = $sLinkAttCode;
  525. }
  526. }
  527. // First display all the attributes specific to the link
  528. // Then display all the attributes linked to the other end of the relationship
  529. $aList = $aDisplayList;
  530. }
  531. if ($bSelectMode)
  532. {
  533. if (!$bSingleSelectMode)
  534. {
  535. $aAttribs['form::select'] = array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList{$iListId}:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+'));
  536. }
  537. else
  538. {
  539. $aAttribs['form::select'] = array('label' => "", 'description' => '');
  540. }
  541. }
  542. if ($bViewLink)
  543. {
  544. $aAttribs['key'] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  545. }
  546. foreach($aList as $sAttCode)
  547. {
  548. $aAttribs[$sAttCode] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => MetaModel::GetDescription($sClassName, $sAttCode));
  549. }
  550. $aValues = array();
  551. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  552. $iMaxObjects = -1;
  553. if ($bDisplayLimit && $bTruncated)
  554. {
  555. if ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit())
  556. {
  557. $iMaxObjects = MetaModel::GetConfig()->GetMinDisplayLimit();
  558. $oSet->SetLimit($iMaxObjects);
  559. }
  560. }
  561. $oSet->Seek(0);
  562. while (($oObj = $oSet->Fetch()) && ($iMaxObjects != 0))
  563. {
  564. $aRow = array();
  565. $sHilightClass = $oObj->GetHilightClass();
  566. if ($sHilightClass != '')
  567. {
  568. $aRow['@class'] = $sHilightClass;
  569. }
  570. if ($bViewLink)
  571. {
  572. $aRow['key'] = $oObj->GetHyperLink();
  573. }
  574. if ($bSelectMode)
  575. {
  576. if (array_key_exists('selection_enabled', $aExtraParams) && isset($aExtraParams['selection_enabled'][$oObj->GetKey()]))
  577. {
  578. $sDisabled = ($aExtraParams['selection_enabled'][$oObj->GetKey()]) ? '' : ' disabled="disabled"';
  579. }
  580. else
  581. {
  582. $sDisabled = '';
  583. }
  584. if ($bSingleSelectMode)
  585. {
  586. $aRow['form::select'] = "<input type=\"radio\" $sDisabled class=\"selectList{$iListId}\" name=\"selectObject\" value=\"".$oObj->GetKey()."\"></input>";
  587. }
  588. else
  589. {
  590. $aRow['form::select'] = "<input type=\"checkBox\" $sDisabled class=\"selectList{$iListId}\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\"></input>";
  591. }
  592. }
  593. foreach($aList as $sAttCode)
  594. {
  595. $aRow[$sAttCode] = $oObj->GetAsHTML($sAttCode);
  596. }
  597. $aValues[] = $aRow;
  598. $iMaxObjects--;
  599. }
  600. $sHtml .= '<table class="listContainer">';
  601. $sColspan = '';
  602. // if (isset($aExtraParams['block_id']))
  603. // {
  604. // $divId = $aExtraParams['block_id'];
  605. // }
  606. // else
  607. // {
  608. // $divId = 'missingblockid';
  609. // }
  610. $sFilter = $oSet->GetFilter()->serialize();
  611. $iMinDisplayLimit = MetaModel::GetConfig()->GetMinDisplayLimit();
  612. $sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oSet->Count());
  613. $sLinkLabel = Dict::S('UI:DisplayAll');
  614. foreach($oSet->GetFilter()->GetInternalParams() as $sName => $sValue)
  615. {
  616. $aExtraParams['query_params'][$sName] = $sValue;
  617. }
  618. if ($bDisplayLimit && $bTruncated && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  619. {
  620. // list truncated
  621. $aExtraParams['display_limit'] = true;
  622. $sHtml .= '<tr class="containerHeader"><td><span id="lbl_'.$iListId.'">'.$sCollapsedLabel.'</span>&nbsp;&nbsp;<a class="truncated" id="trc_'.$iListId.'">'.$sLinkLabel.'</a></td><td>';
  623. $oPage->add_ready_script(
  624. <<<EOF
  625. $('#$iListId table.listResults').addClass('truncated');
  626. $('#$iListId table.listResults tr:last td').addClass('truncated');
  627. EOF
  628. );
  629. }
  630. else if ($bDisplayLimit && !$bTruncated && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  631. {
  632. // Collapsible list
  633. $aExtraParams['display_limit'] = true;
  634. $sHtml .= '<tr class="containerHeader"><td><span id="lbl_'.$iListId.'">'.Dict::Format('UI:CountOfResults', $oSet->Count()).'</span><a class="truncated" id="trc_'.$iListId.'">'.Dict::S('UI:CollapseList').'</a></td><td>';
  635. }
  636. $aExtraParams['truncated'] = false; // To expand the full list when clicked
  637. $sExtraParamsExpand = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  638. $oPage->add_ready_script(
  639. <<<EOF
  640. // Handle truncated lists
  641. $('#trc_$iListId').click(function()
  642. {
  643. var state = {};
  644. var currentState = $.bbq.getState( this.id, true ) || 'close';
  645. // Toggle the state!
  646. if (currentState == 'close')
  647. {
  648. state[ this.id ] = 'open';
  649. }
  650. else
  651. {
  652. state[ this.id ] = 'close';
  653. }
  654. $.bbq.pushState( state );
  655. $(this).trigger(state[this.id]);
  656. });
  657. $('#trc_$iListId').unbind('open');
  658. $('#trc_$iListId').bind('open', function()
  659. {
  660. ReloadTruncatedList('$iListId', '$sFilter', '$sExtraParamsExpand');
  661. });
  662. $('#trc_$iListId').unbind('close');
  663. $('#trc_$iListId').bind('close', function()
  664. {
  665. TruncateList('$iListId', $iMinDisplayLimit, '$sCollapsedLabel', '$sLinkLabel');
  666. });
  667. EOF
  668. );
  669. if ($bDisplayMenu)
  670. {
  671. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  672. $sColspan = 'colspan="2"';
  673. $aMenuExtraParams = $aExtraParams;
  674. if (!empty($sLinkageAttribute))
  675. {
  676. //$aMenuExtraParams['linkage'] = $sLinkageAttribute;
  677. $aMenuExtraParams = $aExtraParams;
  678. }
  679. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams, $iListId);
  680. $sHtml .= '</td></tr>';
  681. }
  682. $sHtml .= "<tr><td $sColspan>";
  683. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  684. $sHtml .= '</td></tr>';
  685. $sHtml .= '</table>';
  686. return $sHtml;
  687. }
  688. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  689. {
  690. static $iListId = 0;
  691. $iListId++;
  692. $aList = array();
  693. // Initialize and check the parameters
  694. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  695. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  696. // Check if there is a list of aliases to limit the display to...
  697. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  698. $sHtml = '';
  699. $oAppContext = new ApplicationContext();
  700. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  701. $aAuthorizedClasses = array();
  702. foreach($aClasses as $sAlias => $sClassName)
  703. {
  704. if ( (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) &&
  705. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  706. {
  707. $aAuthorizedClasses[$sAlias] = $sClassName;
  708. }
  709. }
  710. $aAttribs = array();
  711. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  712. {
  713. $aList[$sClassName] = MetaModel::GetZListItems($sClassName, 'list');
  714. if ($bViewLink)
  715. {
  716. $aAttribs['key_'.$sAlias] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  717. }
  718. foreach($aList[$sClassName] as $sAttCode)
  719. {
  720. $aAttribs[$sAttCode.'_'.$sAlias] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => MetaModel::GetDescription($sClassName, $sAttCode));
  721. }
  722. }
  723. $aValues = array();
  724. $oSet->Seek(0);
  725. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  726. $iMaxObjects = -1;
  727. if ($bDisplayLimit)
  728. {
  729. if ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit())
  730. {
  731. $iMaxObjects = MetaModel::GetConfig()->GetMinDisplayLimit();
  732. }
  733. }
  734. while (($aObjects = $oSet->FetchAssoc()) && ($iMaxObjects != 0))
  735. {
  736. $aRow = array();
  737. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  738. {
  739. if ($bViewLink)
  740. {
  741. if (is_null($aObjects[$sAlias]))
  742. {
  743. $aRow['key_'.$sAlias] = '';
  744. }
  745. else
  746. {
  747. $aRow['key_'.$sAlias] = $aObjects[$sAlias]->GetHyperLink();
  748. }
  749. }
  750. foreach($aList[$sClassName] as $sAttCode)
  751. {
  752. if (is_null($aObjects[$sAlias]))
  753. {
  754. $aRow[$sAttCode.'_'.$sAlias] = '';
  755. }
  756. else
  757. {
  758. $aRow[$sAttCode.'_'.$sAlias] = $aObjects[$sAlias]->GetAsHTML($sAttCode);
  759. }
  760. }
  761. }
  762. $aValues[] = $aRow;
  763. $iMaxObjects--;
  764. }
  765. $sHtml .= '<table class="listContainer">';
  766. $sColspan = '';
  767. if ($bDisplayMenu)
  768. {
  769. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  770. $sColspan = 'colspan="2"';
  771. $aMenuExtraParams = $aExtraParams;
  772. if (!empty($sLinkageAttribute))
  773. {
  774. $aMenuExtraParams = $aExtraParams;
  775. }
  776. if ($bDisplayLimit && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  777. {
  778. // list truncated
  779. $divId = $aExtraParams['block_id'];
  780. $sFilter = $oSet->GetFilter()->serialize();
  781. $aExtraParams['display_limit'] = false; // To expand the full list
  782. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  783. $sHtml .= '<tr class="containerHeader"><td>'.Dict::Format('UI:TruncatedResults', MetaModel::GetConfig()->GetMinDisplayLimit(), $oSet->Count()).'&nbsp;&nbsp;<a href="Javascript:ReloadTruncatedList(\''.$divId.'\', \''.$sFilter.'\', \''.$sExtraParams.'\');">'.Dict::S('UI:DisplayAll').'</a></td><td>';
  784. $oPage->add_ready_script("$('#{$divId} table.listResults').addClass('truncated');");
  785. $oPage->add_ready_script("$('#{$divId} table.listResults tr:last td').addClass('truncated');");
  786. }
  787. else
  788. {
  789. // Full list
  790. $sHtml .= '<tr class="containerHeader"><td>&nbsp;'.Dict::Format('UI:CountOfResults', $oSet->Count()).'</td><td>';
  791. }
  792. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams, $aMenuExtraParams['currentId']);
  793. $sHtml .= '</td></tr>';
  794. }
  795. $sHtml .= "<tr><td $sColspan>";
  796. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  797. $sHtml .= '</td></tr>';
  798. $sHtml .= '</table>';
  799. return $sHtml;
  800. }
  801. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  802. {
  803. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  804. }
  805. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  806. {
  807. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  808. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  809. $aFields = null;
  810. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  811. {
  812. $aFields = explode(',', $aParams['fields']);
  813. }
  814. $aList = array();
  815. $oAppContext = new ApplicationContext();
  816. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  817. $aAuthorizedClasses = array();
  818. foreach($aClasses as $sAlias => $sClassName)
  819. {
  820. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  821. {
  822. $aAuthorizedClasses[$sAlias] = $sClassName;
  823. }
  824. }
  825. $aAttribs = array();
  826. $aHeader = array();
  827. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  828. {
  829. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  830. {
  831. if (is_null($aFields) || (count($aFields) == 0))
  832. {
  833. // Standard list of attributes (no link sets)
  834. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  835. {
  836. $aList[$sClassName][$sAttCode] = $oAttDef;
  837. }
  838. }
  839. else
  840. {
  841. // User defined list of attributes
  842. if (in_array($sAttCode, $aFields))
  843. {
  844. $aList[$sClassName][$sAttCode] = $oAttDef;
  845. }
  846. }
  847. }
  848. $aHeader[] = 'id';
  849. foreach($aList[$sClassName] as $sAttCode => $oAttDef)
  850. {
  851. $sStar = '';
  852. if ($oAttDef->IsExternalField())
  853. {
  854. $sExtKeyLabel = MetaModel::GetLabel($sClassName, $oAttDef->GetKeyAttCode());
  855. $oExtKeyAttDef = MetaModel::GetAttributeDef($sClassName, $oAttDef->GetKeyAttCode());
  856. if (!$oExtKeyAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  857. {
  858. $sStar = '*';
  859. }
  860. $sRemoteAttLabel = MetaModel::GetLabel($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  861. $oTargetAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  862. $sSuffix = '';
  863. if ($oTargetAttDef->IsExternalKey())
  864. {
  865. $sSuffix = '->id';
  866. }
  867. $aHeader[] = $sExtKeyLabel.'->'.$sRemoteAttLabel.$sSuffix.$sStar;
  868. }
  869. else
  870. {
  871. if (!$oAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  872. {
  873. $sStar = '*';
  874. }
  875. $aHeader[] = MetaModel::GetLabel($sClassName, $sAttCode).$sStar;
  876. }
  877. }
  878. }
  879. $sHtml = implode($sSeparator, $aHeader)."\n";
  880. $oSet->Seek(0);
  881. while ($aObjects = $oSet->FetchAssoc())
  882. {
  883. $aRow = array();
  884. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  885. {
  886. $oObj = $aObjects[$sAlias];
  887. if (is_null($oObj))
  888. {
  889. $aRow[] = '';
  890. }
  891. else
  892. {
  893. $aRow[] = $oObj->GetKey();
  894. }
  895. foreach($aList[$sClassName] as $sAttCode => $oAttDef)
  896. {
  897. if (is_null($oObj))
  898. {
  899. $aRow[] = '';
  900. }
  901. else
  902. {
  903. $aRow[] = $oObj->GetAsCSV($sAttCode, $sSeparator, $sTextQualifier);
  904. }
  905. }
  906. }
  907. $sHtml .= implode($sSeparator, $aRow)."\n";
  908. }
  909. return $sHtml;
  910. }
  911. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  912. {
  913. $oAppContext = new ApplicationContext();
  914. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  915. $aAuthorizedClasses = array();
  916. foreach($aClasses as $sAlias => $sClassName)
  917. {
  918. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  919. {
  920. $aAuthorizedClasses[$sAlias] = $sClassName;
  921. }
  922. }
  923. $aAttribs = array();
  924. $aList = array();
  925. $aList[$sClassName] = MetaModel::GetZListItems($sClassName, 'details');
  926. $oPage->add("<Set>\n");
  927. $oSet->Seek(0);
  928. while ($aObjects = $oSet->FetchAssoc())
  929. {
  930. if (count($aAuthorizedClasses) > 1)
  931. {
  932. $oPage->add("<Row>\n");
  933. }
  934. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  935. {
  936. $oObj = $aObjects[$sAlias];
  937. if (is_null($oObj))
  938. {
  939. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n");
  940. }
  941. else
  942. {
  943. $sClassName = get_class($oObj);
  944. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  945. }
  946. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  947. {
  948. if (is_null($oObj))
  949. {
  950. $oPage->add("<$sAttCode>null</$sAttCode>\n");
  951. }
  952. else
  953. {
  954. if ($oAttDef->IsWritable())
  955. {
  956. $sValue = $oObj->GetAsXML($sAttCode);
  957. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  958. }
  959. }
  960. }
  961. $oPage->add("</$sClassName>\n");
  962. }
  963. if (count($aAuthorizedClasses) > 1)
  964. {
  965. $oPage->add("</Row>\n");
  966. }
  967. }
  968. $oPage->add("</Set>\n");
  969. }
  970. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  971. {
  972. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  973. }
  974. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  975. {
  976. static $iSearchFormId = 0;
  977. $oAppContext = new ApplicationContext();
  978. $sHtml = '';
  979. $numCols=4;
  980. $sClassName = $oSet->GetFilter()->GetClass();
  981. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  982. // (especially when used to add a link)
  983. /*
  984. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  985. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  986. <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>
  987. </ul></div>\n";
  988. */
  989. // Simple search form
  990. if (isset($aExtraParams['currentId']))
  991. {
  992. $sSearchFormId = $aExtraParams['currentId'];
  993. }
  994. else
  995. {
  996. $iSearchFormId = $oPage->GetUniqueId();
  997. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  998. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  999. }
  1000. // Check if the current class has some sub-classes
  1001. if (isset($aExtraParams['baseClass']))
  1002. {
  1003. $sRootClass = $aExtraParams['baseClass'];
  1004. }
  1005. else
  1006. {
  1007. $sRootClass = $sClassName;
  1008. }
  1009. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  1010. if (count($aSubClasses) > 0)
  1011. {
  1012. $aOptions = array();
  1013. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  1014. foreach($aSubClasses as $sSubclassName)
  1015. {
  1016. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  1017. }
  1018. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  1019. ksort($aOptions);
  1020. $sContext = $oAppContext->GetForLink();
  1021. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  1022. }
  1023. else
  1024. {
  1025. $sClassesCombo = MetaModel::GetName($sClassName);
  1026. }
  1027. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  1028. $sHtml .= "<form id=\"fs_{$sSearchFormId}\" action=\"../pages/UI.php\">\n"; // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  1029. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  1030. $index = 0;
  1031. $sHtml .= "<p>\n";
  1032. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  1033. $aMapCriteria = array();
  1034. foreach($aFilterCriteria as $aCriteria)
  1035. {
  1036. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  1037. }
  1038. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  1039. foreach($aList as $sFilterCode)
  1040. {
  1041. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  1042. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  1043. $sFilterValue = '';
  1044. $sFilterValue = utils::ReadParam($sFilterCode, '');
  1045. $sFilterOpCode = null; // Use the default 'loose' OpCode
  1046. if (empty($sFilterValue))
  1047. {
  1048. if (isset($aMapCriteria[$sFilterCode]))
  1049. {
  1050. if (count($aMapCriteria[$sFilterCode]) > 1)
  1051. {
  1052. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  1053. }
  1054. else
  1055. {
  1056. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  1057. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  1058. }
  1059. if ($sFilterCode != 'company')
  1060. {
  1061. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  1062. }
  1063. }
  1064. }
  1065. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  1066. if ($aAllowedValues != null)
  1067. {
  1068. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFilterCode);
  1069. if ($oAttDef->IsExternalKey())
  1070. {
  1071. $iFieldSize = $oAttDef->GetMaxSize();
  1072. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1073. $oWidget = new UIExtKeyWidget($sFilterCode, $sClassName, $oAttDef->GetLabel(), $aAllowedValues, $sFilterValue, 'search_'.$sFilterCode, false, '', '', '');
  1074. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;";
  1075. $sHtml .= $oWidget->Display($oPage, $aExtraParams, true /* bSearchMode */);
  1076. }
  1077. else
  1078. {
  1079. //Enum field or external key, display a combo
  1080. $sValue = "<select name=\"$sFilterCode\">\n";
  1081. $sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  1082. foreach($aAllowedValues as $key => $value)
  1083. {
  1084. if ($sFilterValue == $key)
  1085. {
  1086. $sSelected = ' selected';
  1087. }
  1088. else
  1089. {
  1090. $sSelected = '';
  1091. }
  1092. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  1093. }
  1094. $sValue .= "</select>\n";
  1095. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  1096. }
  1097. unset($aExtraParams[$sFilterCode]);
  1098. }
  1099. else
  1100. {
  1101. // Any value is possible, display an input box
  1102. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"$sFilterValue\"/>\n";
  1103. unset($aExtraParams[$sFilterCode]);
  1104. }
  1105. $index++;
  1106. $sHtml .= '</span> ';
  1107. }
  1108. $sHtml .= "</p>\n";
  1109. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  1110. foreach($aExtraParams as $sName => $sValue)
  1111. {
  1112. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1113. }
  1114. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  1115. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1116. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  1117. $sHtml .= $oAppContext->GetForForm();
  1118. $sHtml .= "</form>\n";
  1119. if (!isset($aExtraParams['currentId']))
  1120. {
  1121. $sHtml .= "</div><!-- Simple search form -->\n";
  1122. }
  1123. /*
  1124. // OQL query builder
  1125. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  1126. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  1127. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  1128. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  1129. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1130. $sSelectedClass = utils::ReadParam('oql_class', $sClassName);
  1131. $sOQLClause = utils::ReadParam('oql_clause', '');
  1132. asort($aClasses);
  1133. foreach($aClasses as $sChildClass)
  1134. {
  1135. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  1136. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  1137. }
  1138. $sHtml .= "</select>&nbsp;</td><td>\n";
  1139. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  1140. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  1141. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1142. foreach($aExtraParams as $sName => $sValue)
  1143. {
  1144. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1145. }
  1146. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  1147. $sHtml .= $oAppContext->GetForForm();
  1148. $sHtml .= "</table></form>\n";
  1149. $sHtml .= "</div><!-- OQL query form -->\n";
  1150. */
  1151. return $sHtml;
  1152. }
  1153. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  1154. {
  1155. static $iInputId = 0;
  1156. $sFieldPrefix = '';
  1157. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  1158. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  1159. if (isset($aArgs[$sAttCode]) && empty($value))
  1160. {
  1161. // default value passed by the context (either the app context of the operation)
  1162. $value = $aArgs[$sAttCode];
  1163. }
  1164. if (!empty($iId))
  1165. {
  1166. $iInputId = $iId;
  1167. }
  1168. else
  1169. {
  1170. $iInputId = $oPage->GetUniqueId();
  1171. }
  1172. if (!$oAttDef->IsExternalField())
  1173. {
  1174. $bMandatory = 'false';
  1175. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1176. {
  1177. $bMandatory = 'true';
  1178. }
  1179. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1180. $sHelpText = $oAttDef->GetHelpOnEdition();
  1181. $aEventsList = array();
  1182. switch($oAttDef->GetEditClass())
  1183. {
  1184. case 'Date':
  1185. case 'DateTime':
  1186. $aEventsList[] ='validate';
  1187. $aEventsList[] ='keyup';
  1188. $aEventsList[] ='change';
  1189. $sHTMLValue = "<input title=\"$sHelpText\" class=\"date-pick\" type=\"text\" size=\"20\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1190. break;
  1191. case 'Duration':
  1192. $aEventsList[] ='validate';
  1193. $aEventsList[] ='change';
  1194. $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1195. $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1196. $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1197. $oPage->add_ready_script("$('#{$iId}_s').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1198. $aVal = AttributeDuration::SplitDuration($value);
  1199. $sDays = "<input title=\"$sHelpText\" type=\"text\" size=\"3\" name=\"attr_{$sFieldPrefix}{$sAttCode}[d]{$sNameSuffix}\" value=\"{$aVal['days']}\" id=\"{$iId}_d\"/>";
  1200. $sHours = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[h]{$sNameSuffix}\" value=\"{$aVal['hours']}\" id=\"{$iId}_h\"/>";
  1201. $sMinutes = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[m]{$sNameSuffix}\" value=\"{$aVal['minutes']}\" id=\"{$iId}_m\"/>";
  1202. $sSeconds = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[s]{$sNameSuffix}\" value=\"{$aVal['seconds']}\" id=\"{$iId}_s\"/>";
  1203. $sHidden = "<input type=\"hidden\" id=\"{$iId}\" value=\"$value\"/>";
  1204. $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden."&nbsp;".$sValidationField;
  1205. $oPage->add_ready_script("$('#{$iId}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });");
  1206. break;
  1207. case 'Password':
  1208. $aEventsList[] ='validate';
  1209. $aEventsList[] ='keyup';
  1210. $aEventsList[] ='change';
  1211. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1212. break;
  1213. case 'Text':
  1214. $aEventsList[] ='validate';
  1215. $aEventsList[] ='keyup';
  1216. $aEventsList[] ='change';
  1217. $sEditValue = $oAttDef->GetEditValue($value);
  1218. $sHTMLValue = "<table><tr><td><textarea class=\"resizable\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\">$sEditValue</textarea></td><td>{$sValidationField}</td></tr></table>";
  1219. break;
  1220. case 'CaseLog':
  1221. $aEventsList[] ='validate';
  1222. $aEventsList[] ='keyup';
  1223. $aEventsList[] ='change';
  1224. $sEditValue = $oAttDef->GetEditValue($value);
  1225. $sPreviousLog = $oAttDef->GetAsHTML($value);
  1226. $sHTMLValue = "<div style=\"overflow:auto;border:1px #999 solid; background:#fff;\"><table style=\"width:100%\"><tr><td><textarea class=\"resizable\" style=\"border:0;width:100%\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\">$sEditValue</textarea>$sPreviousLog</td><td>{$sValidationField}</td></tr></table></div>";
  1227. break;
  1228. case 'HTML':
  1229. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationField, $value, $bMandatory);
  1230. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1231. break;
  1232. case 'LinkedSet':
  1233. $aEventsList[] ='validate';
  1234. $aEventsList[] ='change';
  1235. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed());
  1236. $sHTMLValue = $oWidget->Display($oPage, $value);
  1237. break;
  1238. case 'Document':
  1239. $aEventsList[] ='validate';
  1240. $aEventsList[] ='change';
  1241. $oDocument = $value; // Value is an ormDocument object
  1242. $sFileName = '';
  1243. if (is_object($oDocument))
  1244. {
  1245. $sFileName = $oDocument->GetFileName();
  1246. }
  1247. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1248. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1249. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" type=\"hidden\" id=\"$iId\" \" value=\"$sFileName\"/>\n";
  1250. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1251. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"file_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1252. break;
  1253. case 'List':
  1254. // Not editable for now...
  1255. $sHTMLValue = '';
  1256. break;
  1257. case 'One Way Password':
  1258. $aEventsList[] ='validate';
  1259. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1260. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1261. // Event list & validation is handled directly by the widget
  1262. break;
  1263. case 'ExtKey':
  1264. $aEventsList[] ='validate';
  1265. $aEventsList[] ='change';
  1266. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1267. $iFieldSize = $oAttDef->GetMaxSize();
  1268. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1269. $oWidget = new UIExtKeyWidget($sAttCode, $sClass, $oAttDef->GetLabel(), $aAllowedValues, $value, $iId, $bMandatory, $sNameSuffix, $sFieldPrefix, $sFormPrefix);
  1270. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1271. $sHTMLValue .= "<!-- iFlags: $iFlags bMandatory: $bMandatory -->\n";
  1272. break;
  1273. case 'String':
  1274. default:
  1275. $aEventsList[] ='validate';
  1276. // #@# todo - add context information (depending on dimensions)
  1277. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1278. $iFieldSize = $oAttDef->GetMaxSize();
  1279. if ($aAllowedValues !== null)
  1280. {
  1281. // Discrete list of values, use a SELECT
  1282. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1283. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1284. foreach($aAllowedValues as $key => $display_value)
  1285. {
  1286. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1287. {
  1288. // When there is only once choice, select it by default
  1289. $sSelected = ' selected';
  1290. }
  1291. else
  1292. {
  1293. $sSelected = ($value == $key) ? ' selected' : '';
  1294. }
  1295. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1296. }
  1297. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1298. $aEventsList[] ='change';
  1299. }
  1300. else
  1301. {
  1302. $sHTMLValue = "<input title=\"$sHelpText\" type=\"text\" size=\"30\" maxlength=\"$iFieldSize\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1303. $aEventsList[] ='keyup';
  1304. $aEventsList[] ='change';
  1305. }
  1306. break;
  1307. }
  1308. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1309. if (!empty($aEventsList))
  1310. {
  1311. $sNullValue = $oAttDef->GetNullValue();
  1312. if (!is_numeric($sNullValue))
  1313. {
  1314. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1315. }
  1316. $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
  1317. }
  1318. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1319. if (count($aDependencies) > 0)
  1320. {
  1321. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1322. }
  1323. }
  1324. return "<div>{$sHTMLValue}</div>";
  1325. }
  1326. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1327. {
  1328. self::$iGlobalFormId++;
  1329. $sPrefix = '';
  1330. if (isset($aExtraParams['formPrefix']))
  1331. {
  1332. $sPrefix = $aExtraParams['formPrefix'];
  1333. }
  1334. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  1335. $this->m_iFormId = $sPrefix.self::$iGlobalFormId;
  1336. $sClass = get_class($this);
  1337. $oAppContext = new ApplicationContext();
  1338. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1339. $iKey = $this->GetKey();
  1340. $aDetails = array();
  1341. $aFieldsMap = array();
  1342. if (!isset($aExtraParams['action']))
  1343. {
  1344. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1345. }
  1346. else
  1347. {
  1348. $sFormAction = $aExtraParams['action'];
  1349. }
  1350. $iTransactionId = utils::GetNewTransactionId();
  1351. $oPage->SetTransactionId($iTransactionId);
  1352. $oPage->add("<form action=\"$sFormAction\" id=\"form_{$this->m_iFormId}\" enctype=\"multipart/form-data\" method=\"post\" onSubmit=\"return CheckFields('form_{$this->m_iFormId}', true)\">\n");
  1353. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1354. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1355. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1356. // $aDetailsList = $this->FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1357. //$aFullList = MetaModel::ListAttributeDefs($sClass);
  1358. $aList = array();
  1359. // Compute the list of properties to display, first the attributes in the 'details' list, then
  1360. // all the remaining attributes that are not external fields
  1361. // foreach($aDetailsList as $sAttCode)
  1362. // {
  1363. // $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1364. // if (!$oAttDef->IsExternalField())
  1365. // {
  1366. // $aList[] = $sAttCode;
  1367. // }
  1368. // }
  1369. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  1370. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  1371. $sHtml = '';
  1372. $aDetails = array();
  1373. foreach($aDetailsStruct as $sTab => $aCols )
  1374. {
  1375. $aDetails[$sTab] = array();
  1376. ksort($aCols);
  1377. $oPage->SetCurrentTab(Dict::S($sTab));
  1378. $oPage->add('<table style="vertical-align:top"><tr>');
  1379. foreach($aCols as $sColIndex => $aFieldsets)
  1380. {
  1381. $sLabel = '';
  1382. $sPreviousLabel = '';
  1383. $aDetails[$sTab][$sColIndex] = array();
  1384. $oPage->add('<td style="vertical-align:top">');
  1385. //$aDetails[$sTab][$sColIndex] = array();
  1386. foreach($aFieldsets as $sFieldsetName => $aFields)
  1387. {
  1388. if (!empty($sFieldsetName) && ($sFieldsetName[0]!='_'))
  1389. {
  1390. $sLabel = $sFieldsetName;
  1391. }
  1392. else
  1393. {
  1394. $sLabel = '';
  1395. }
  1396. if ($sLabel != $sPreviousLabel)
  1397. {
  1398. if (!empty($sPreviousLabel))
  1399. {
  1400. $oPage->add('<fieldset>');
  1401. $oPage->add('<legend>'.Dict::S($sPreviousLabel).'</legend>');
  1402. }
  1403. $oPage->Details($aDetails[$sTab][$sColIndex]);
  1404. if (!empty($sPreviousLabel))
  1405. {
  1406. $oPage->add('</fieldset>');
  1407. }
  1408. $aDetails[$sTab][$sColIndex] = array();
  1409. $sPreviousLabel = $sLabel;
  1410. }
  1411. foreach($aFields as $sAttCode)
  1412. {
  1413. $aVal = null;
  1414. $sComments = isset($aFieldsComments[$sAttCode]) ? $aFieldsComments[$sAttCode] : '&nbsp;';
  1415. $sInfos = '&nbsp;';
  1416. $iFlags = $this->GetAttributeFlags($sAttCode);
  1417. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1418. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0))
  1419. {
  1420. if ($oAttDef->IsWritable())
  1421. {
  1422. if ($sStateAttCode == $sAttCode)
  1423. {
  1424. // State attribute is always read-only from the UI
  1425. $sHTMLValue = $this->GetStateLabel();
  1426. $aVal = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  1427. }
  1428. else
  1429. {
  1430. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  1431. if ($iFlags & OPT_ATT_HIDDEN)
  1432. {
  1433. // Attribute is hidden, add a hidden input
  1434. $oPage->add('<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>');
  1435. $aFieldsMap[$sAttCode] = $sInputId;
  1436. }
  1437. else
  1438. {
  1439. if ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE))
  1440. {
  1441. // Check if the attribute is not read-only becuase of a synchro...
  1442. $aReasons = array();
  1443. $sSynchroIcon = '';
  1444. if ($iFlags & OPT_ATT_SLAVE)
  1445. {
  1446. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  1447. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  1448. $sTip = '';
  1449. foreach($aReasons as $aRow)
  1450. {
  1451. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  1452. }
  1453. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  1454. }
  1455. // Attribute is read-only
  1456. $sHTMLValue = $this->GetAsHTML($sAttCode);;
  1457. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>';
  1458. $aFieldsMap[$sAttCode] = $sInputId;
  1459. $sComments = $sSynchroIcon;
  1460. }
  1461. else
  1462. {
  1463. $sValue = $this->Get($sAttCode);
  1464. $sDisplayValue = $this->GetEditValue($sAttCode);
  1465. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  1466. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  1467. $aFieldsMap[$sAttCode] = $sInputId;
  1468. }
  1469. $aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  1470. }
  1471. }
  1472. }
  1473. else
  1474. {
  1475. $aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $this->GetAsHTML($sAttCode), 'comments' => $sComments, 'infos' => $sInfos);
  1476. }
  1477. }
  1478. if ($aVal != null)
  1479. {
  1480. // The field is visible, add it to the current column
  1481. $aDetails[$sTab][$sColIndex][] = $aVal;
  1482. }
  1483. }
  1484. }
  1485. if (!empty($sPreviousLabel))
  1486. {
  1487. $oPage->add('<fieldset>');
  1488. $oPage->add('<legend>'.Dict::S($sPreviousLabel).'</legend>');
  1489. }
  1490. $oPage->Details($aDetails[$sTab][$sColIndex]);
  1491. if (!empty($sPreviousLabel))
  1492. {
  1493. $oPage->add('</fieldset>');
  1494. }
  1495. $oPage->add('</td>');
  1496. }
  1497. $oPage->add('</tr></table>');
  1498. }
  1499. // Now display the relations, one tab per relation
  1500. if (!isset($aExtraParams['noRelations']))
  1501. {
  1502. $this->DisplayBareRelations($oPage, true); // Edit mode
  1503. }
  1504. $oPage->SetCurrentTab('');
  1505. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1506. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"$iTransactionId\">\n");
  1507. foreach($aExtraParams as $sName => $value)
  1508. {
  1509. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1510. }
  1511. $oPage->add($oAppContext->GetForForm());
  1512. // Custom operation for the form ?
  1513. if (isset($aExtraParams['custom_operation']))
  1514. {
  1515. $sOperation = $aExtraParams['custom_operation'];
  1516. }
  1517. else if ($iKey > 0)
  1518. {
  1519. $sOperation = 'apply_modify';
  1520. }
  1521. else
  1522. {
  1523. $sOperation = 'apply_new';
  1524. }
  1525. // Custom label for the apply button ?
  1526. if (isset($aExtraParams['custom_button']))
  1527. {
  1528. $sApplyButton = $aExtraParams['custom_button'];
  1529. }
  1530. else if ($iKey > 0)
  1531. {
  1532. $sApplyButton = Dict::S('UI:Button:Apply');
  1533. }
  1534. else
  1535. {
  1536. $sApplyButton = Dict::S('UI:Button:Create');
  1537. }
  1538. if ($iKey > 0)
  1539. {
  1540. // The object already exists in the database, it's a modification
  1541. $oPage->add("<input type=\"hidden\" name=\"id\" value=\"$iKey\">\n");
  1542. $oPage->add("<input type=\"hidden\" name=\"operation\" value=\"{$sOperation}\">\n");
  1543. $oPage->add("<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1544. $oPage->add("<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n");
  1545. }
  1546. else
  1547. {
  1548. // The object does not exist in the database it's a creation
  1549. $oPage->add("<input type=\"hidden\" name=\"operation\" value=\"$sOperation\">\n");
  1550. $oPage->add("<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1551. $oPage->add("<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n");
  1552. }
  1553. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1554. $sDefaultUrl = '../pages/UI.php?operation=cancel';
  1555. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1556. $oPage->add("</form>\n");
  1557. $iFieldsCount = count($aFieldsMap);
  1558. $sJsonFieldsMap = json_encode($aFieldsMap);
  1559. $sState = $this->GetState();
  1560. $oPage->add_script(
  1561. <<<EOF
  1562. // Create the object once at the beginning of the page...
  1563. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix', '$sState');
  1564. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1565. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1566. EOF
  1567. );
  1568. $oPage->add_ready_script(
  1569. <<<EOF
  1570. // Starts the validation when the page is ready
  1571. CheckFields('form_{$this->m_iFormId}', false);
  1572. EOF
  1573. );
  1574. }
  1575. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1576. {
  1577. $oAppContext = new ApplicationContext();
  1578. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1579. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1580. $aStates = MetaModel::EnumStates($sClass);
  1581. if ($oObjectToClone == null)
  1582. {
  1583. $oObj = MetaModel::NewObject($sClass);
  1584. if (!empty($sStateAttCode))
  1585. {
  1586. $sTargetState = MetaModel::GetDefaultState($sClass);
  1587. $oObj->Set($sStateAttCode, $sTargetState);
  1588. }
  1589. }
  1590. else
  1591. {
  1592. $oObj = clone $oObjectToClone;
  1593. }
  1594. // Pre-fill the object with default values, when there is only on possible choice
  1595. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  1596. $aArgs['this'] = $oObj;
  1597. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1598. // Order the fields based on their dependencies
  1599. $aDeps = array();
  1600. foreach($aDetailsList as $sAttCode)
  1601. {
  1602. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1603. }
  1604. $aList = self::OrderDependentFields($aDeps);
  1605. // Now fill-in the fields with default/supplied values
  1606. foreach($aList as $sAttCode)
  1607. {
  1608. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1609. if (isset($aArgs['default'][$sAttCode]))
  1610. {
  1611. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  1612. }
  1613. elseif (count($aAllowedValues) == 1)
  1614. {
  1615. // If the field is mandatory, set it to the only possible value
  1616. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1617. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1618. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1619. {
  1620. $aValues = array_keys($aAllowedValues);
  1621. $oObj->Set($sAttCode, $aValues[0]);
  1622. }
  1623. }
  1624. }
  1625. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  1626. }
  1627. protected static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  1628. {
  1629. //echo "<pre>ZList: ";
  1630. //print_r($aList);
  1631. //echo "</pre>\n";
  1632. $index = 0;
  1633. foreach($aList as $sKey => $value)
  1634. {
  1635. if (is_array($value))
  1636. {
  1637. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  1638. {
  1639. $sCode = $aMatches[1];
  1640. $sName = $aMatches[2];
  1641. switch($sCode)
  1642. {
  1643. case 'tab':
  1644. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  1645. if(!isset($aDetails[$sName]))
  1646. {
  1647. $aDetails[$sName] = array('col1' => array());
  1648. }
  1649. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  1650. break;
  1651. case 'fieldset':
  1652. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  1653. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  1654. {
  1655. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  1656. }
  1657. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  1658. break;
  1659. default:
  1660. case 'col':
  1661. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  1662. if(!isset($aDetails[$sCurrentTab][$sName]))
  1663. {
  1664. $aDetails[$sCurrentTab][$sName] = array();
  1665. }
  1666. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  1667. break;
  1668. }
  1669. }
  1670. }
  1671. else
  1672. {
  1673. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  1674. if (empty($sCurrentSet))
  1675. {
  1676. $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value;
  1677. }
  1678. else
  1679. {
  1680. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  1681. }
  1682. }
  1683. $index++;
  1684. }
  1685. return $aDetails;
  1686. }
  1687. protected static function FlattenZList($aList)
  1688. {
  1689. $aResult = array();
  1690. foreach($aList as $value)
  1691. {
  1692. if (!is_array($value))
  1693. {
  1694. $aResult[] = $value;
  1695. }
  1696. else
  1697. {
  1698. $aResult = array_merge($aResult,self::FlattenZList($value));
  1699. }
  1700. }
  1701. return $aResult;
  1702. }
  1703. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  1704. {
  1705. $retVal = null;
  1706. $iFlags = $this->GetAttributeFlags($sAttCode);
  1707. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1708. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  1709. {
  1710. // The field is visible in the current state of the object
  1711. if ($sStateAttCode == $sAttCode)
  1712. {
  1713. // Special display for the 'state' attribute itself
  1714. $sDisplayValue = $this->GetStateLabel();
  1715. }
  1716. else if ($oAttDef->GetEditClass() == 'Document')
  1717. {
  1718. $oDocument = $this->Get($sAttCode);
  1719. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1720. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1721. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1722. }
  1723. else
  1724. {
  1725. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1726. }
  1727. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1728. }
  1729. return $retVal;
  1730. }
  1731. /**
  1732. * Displays a blob document *inline* (if possible, depending on the type of the document)
  1733. * @return string
  1734. */
  1735. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  1736. {
  1737. $oDoc = $this->Get($sAttCode);
  1738. $sClass = get_class($this);
  1739. $Id = $this->GetKey();
  1740. switch ($oDoc->GetMainMimeType())
  1741. {
  1742. case 'text':
  1743. case 'html':
  1744. $data = $oDoc->GetData();
  1745. switch($oDoc->GetMimeType())
  1746. {
  1747. case 'text/html':
  1748. case 'text/xml':
  1749. $oPage->add("<iframe id='preview_$sAttCode' src=\"../pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" width=\"100%\" height=\"400\">Loading...</iframe>\n");
  1750. break;
  1751. default:
  1752. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true), ENT_QUOTES, 'UTF-8')."</pre>\n");
  1753. }
  1754. break;
  1755. case 'application':
  1756. switch($oDoc->GetMimeType())
  1757. {
  1758. case 'application/pdf':
  1759. $oPage->add("<iframe id='preview_$sAttCode' src=\"../pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" width=\"100%\" height=\"400\">Loading...</iframe>\n");
  1760. break;
  1761. default:
  1762. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1763. }
  1764. break;
  1765. case 'image':
  1766. $oPage->add("<img src=\"../pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  1767. break;
  1768. default:
  1769. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1770. }
  1771. }
  1772. // $m_highlightComparison[previous][new] => next value
  1773. protected static $m_highlightComparison = array(
  1774. HILIGHT_CLASS_CRITICAL => array(
  1775. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  1776. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL,
  1777. HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL,
  1778. HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL,
  1779. ),
  1780. HILIGHT_CLASS_WARNING => array(
  1781. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  1782. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  1783. HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING,
  1784. HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING,
  1785. ),
  1786. HILIGHT_CLASS_OK => array(
  1787. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  1788. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  1789. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  1790. HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK,
  1791. ),
  1792. HILIGHT_CLASS_NONE => array(
  1793. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  1794. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  1795. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  1796. HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE,
  1797. ),
  1798. );
  1799. /**
  1800. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1801. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1802. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1803. * To Be overridden by derived classes
  1804. * @param void
  1805. * @return String The desired higlight class for the object/row
  1806. */
  1807. public function GetHilightClass()
  1808. {
  1809. // Possible return values are:
  1810. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1811. $current = HILIGHT_CLASS_NONE; // Not hilighted by default
  1812. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  1813. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  1814. {
  1815. $new = $oExtensionInstance->GetHilightClass($this);
  1816. @$current = self::$m_highlightComparison[$current][$new];
  1817. }
  1818. return $current;
  1819. }
  1820. /**
  1821. * Re-order the fields based on their inter-dependencies
  1822. * @params hash @aFields field_code => array_of_depencies
  1823. * @return array Ordered array of fields or throws an exception
  1824. */
  1825. public static function OrderDependentFields($aFields)
  1826. {
  1827. $bCircular = false;
  1828. $aResult = array();
  1829. $iCount = 0;
  1830. do
  1831. {
  1832. $bSet = false;
  1833. $iCount++;
  1834. foreach($aFields as $sFieldCode => $aDeps)
  1835. {
  1836. foreach($aDeps as $key => $sDependency)
  1837. {
  1838. if (in_array($sDependency, $aResult))
  1839. {
  1840. // Dependency is resolved, remove it
  1841. unset($aFields[$sFieldCode][$key]);
  1842. }
  1843. }
  1844. if (count($aFields[$sFieldCode]) == 0)
  1845. {
  1846. // No more pending depencies for this field, add it to the list
  1847. $aResult[] = $sFieldCode;
  1848. unset($aFields[$sFieldCode]);
  1849. $bSet = true;
  1850. }
  1851. }
  1852. }
  1853. while($bSet && (count($aFields) > 0));
  1854. if (count($aFields) > 0)
  1855. {
  1856. $sMessage = "Error: Circular dependencies between the fields (or field missing in ZList) ! <pre>".print_r($aFields, true)."</pre>";
  1857. throw(new Exception($sMessage));
  1858. }
  1859. return $aResult;
  1860. }
  1861. /**
  1862. * Maps the given context parameter name to the appropriate filter/search code for this class
  1863. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1864. * @return string Filter code, i.e. 'customer_id'
  1865. */
  1866. public static function MapContextParam($sContextParam)
  1867. {
  1868. if ($sContextParam == 'menu')
  1869. {
  1870. return null;
  1871. }
  1872. else
  1873. {
  1874. return $sContextParam;
  1875. }
  1876. }
  1877. /**
  1878. * Updates the object from the POSTed parameters
  1879. */
  1880. public function UpdateObject($sFormPrefix = '')
  1881. {
  1882. $aErrors = array();
  1883. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1884. {
  1885. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  1886. {
  1887. $aLinks = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null);
  1888. if (is_null($aLinks)) continue;
  1889. $sLinkedClass = $oAttDef->GetLinkedClass();
  1890. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  1891. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1892. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  1893. if (is_array($aLinks))
  1894. {
  1895. foreach($aLinks as $id => $aData)
  1896. {
  1897. if (is_numeric($id))
  1898. {
  1899. if ($id < 0)
  1900. {
  1901. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  1902. $oLink = MetaModel::NewObject($sLinkedClass);
  1903. $oLink->Set($sExtKeyToRemote, -$id);
  1904. $oLink->Set($sExtKeyToMe, $this->GetKey());
  1905. }
  1906. else
  1907. {
  1908. // Existing link, potentially to be updated...
  1909. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  1910. }
  1911. // Now populate the attributes
  1912. foreach($aData as $sName => $value)
  1913. {
  1914. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  1915. {
  1916. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  1917. if ($oLinkAttDef->IsWritable())
  1918. {
  1919. $oLink->Set($sName, $value);
  1920. }
  1921. }
  1922. }
  1923. $oLinkedSet->AddObject($oLink);
  1924. }
  1925. }
  1926. }
  1927. $this->Set($sAttCode, $oLinkedSet);
  1928. }
  1929. else if ($oAttDef->IsWritable())
  1930. {
  1931. $iFlags = $this->GetAttributeFlags($sAttCode);
  1932. if ( $iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  1933. {
  1934. // Non-visible, or read-only attribute, do nothing
  1935. }
  1936. elseif($iFlags & OPT_ATT_SLAVE)
  1937. {
  1938. $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null);
  1939. if (!is_null($value) && ($value != $this->Get($sAttCode)))
  1940. {
  1941. $aErrors[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  1942. }
  1943. }
  1944. elseif ($oAttDef->GetEditClass() == 'Document')
  1945. {
  1946. // There should be an uploaded file with the named attr_<attCode>
  1947. $oDocument = utils::ReadPostedDocument("file_{$sFormPrefix}{$sAttCode}");
  1948. if (!$oDocument->IsEmpty())
  1949. {
  1950. // A new file has been uploaded
  1951. $this->Set($sAttCode, $oDocument);
  1952. }
  1953. }
  1954. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  1955. {
  1956. // Check if the password was typed/changed
  1957. $bChanged = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_changed", false);
  1958. if ($bChanged)
  1959. {
  1960. // The password has been changed or set
  1961. $rawValue = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null);
  1962. $this->Set($sAttCode, $rawValue);
  1963. }
  1964. }
  1965. elseif ($oAttDef->GetEditClass() == 'Duration')
  1966. {
  1967. $rawValue = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null);
  1968. if (!is_array($rawValue)) continue;
  1969. $iValue = (((24*$rawValue['d'])+$rawValue['h'])*60 +$rawValue['m'])*60 + $rawValue['s'];
  1970. $this->Set($sAttCode, $iValue);
  1971. $previousValue = $this->Get($sAttCode);
  1972. if ($previousValue !== $iValue)
  1973. {
  1974. $this->Set($sAttCode, $iValue);
  1975. }
  1976. }
  1977. else
  1978. {
  1979. $rawValue = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null);
  1980. if (!is_null($rawValue))
  1981. {
  1982. $aAttributes[$sAttCode] = trim($rawValue);
  1983. $previousValue = $this->Get($sAttCode);
  1984. if ($previousValue !== $aAttributes[$sAttCode])
  1985. {
  1986. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  1987. }
  1988. }
  1989. }
  1990. }
  1991. }
  1992. // Invoke extensions after the update of the object from the form
  1993. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  1994. {
  1995. $oExtensionInstance->OnFormSubmit($this, $sFormPrefix);
  1996. }
  1997. return $aErrors;
  1998. }
  1999. protected function DBInsertTracked_Internal($bDoNotReload = false)
  2000. {
  2001. $res = parent::DBInsertTracked_Internal($bDoNotReload);
  2002. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2003. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2004. {
  2005. $oExtensionInstance->OnDBInsert($this, self::$m_oCurrChange);
  2006. }
  2007. return $res;
  2008. }
  2009. protected function DBCloneTracked_Internal($newKey = null)
  2010. {
  2011. $oNewObj = parent::DBCloneTracked_Internal($newKey);
  2012. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2013. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2014. {
  2015. $oExtensionInstance->OnDBInsert($oNewObj, self::$m_oCurrChange);
  2016. }
  2017. return $oNewObj;
  2018. }
  2019. protected function DBUpdateTracked_Internal()
  2020. {
  2021. $res = parent::DBUpdateTracked_Internal();
  2022. // Invoke extensions after the update (could be before)
  2023. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2024. {
  2025. $oExtensionInstance->OnDBUpdate($this, self::$m_oCurrChange);
  2026. }
  2027. return $res;
  2028. }
  2029. protected static function BulkUpdateTracked_Internal(DBObjectSearch $oFilter, array $aValues)
  2030. {
  2031. // Todo - invoke the extension
  2032. return parent::BulkUpdateTracked_Internal($oFilter, $aValues);
  2033. }
  2034. protected function DBDeleteTracked_Internal()
  2035. {
  2036. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2037. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2038. {
  2039. $oExtensionInstance->OnDBDelete($this, self::$m_oCurrChange);
  2040. }
  2041. return parent::DBDeleteTracked_Internal();
  2042. }
  2043. protected static function BulkDeleteTracked_Internal(DBObjectSearch $oFilter)
  2044. {
  2045. // Todo - invoke the extension
  2046. return parent::BulkDeleteTracked_Internal($oFilter);
  2047. }
  2048. public function DoCheckToWrite()
  2049. {
  2050. parent::DoCheckToWrite();
  2051. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2052. {
  2053. $aNewIssues = $oExtensionInstance->OnCheckToWrite($this);
  2054. if (count($aNewIssues) > 0)
  2055. {
  2056. $this->m_aCheckIssues = array_merge($this->m_aCheckIssues, $aNewIssues);
  2057. }
  2058. }
  2059. }
  2060. protected function DoCheckToDelete()
  2061. {
  2062. parent::DoCheckToDelete();
  2063. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2064. {
  2065. $aNewIssues = $oExtensionInstance->OnCheckToDelete($this);
  2066. if (count($aNewIssues) > 0)
  2067. {
  2068. $this->m_aDeleteIssues = array_merge($this->m_aDeleteIssues, $aNewIssues);
  2069. }
  2070. }
  2071. }
  2072. }
  2073. ?>