cmdbabstract.class.inc.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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('../core/cmdbobject.class.inc.php');
  31. require_once('../application/utils.inc.php');
  32. require_once('../application/applicationcontext.class.inc.php');
  33. require_once('../application/ui.linkswidget.class.inc.php');
  34. abstract class cmdbAbstractObject extends CMDBObject
  35. {
  36. protected $m_iFormId; // The ID of the form used to edit the object (when in edition mode !)
  37. public static function GetUIPage()
  38. {
  39. return '../pages/UI.php';
  40. }
  41. public static function ComputeUIPage($sClass)
  42. {
  43. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  44. if (!isset($aUIPagesCache[$sClass]))
  45. {
  46. $UIPage = false;
  47. if (is_callable("$sClass::GetUIPage"))
  48. {
  49. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  50. }
  51. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  52. }
  53. $sPage = $aUIPagesCache[$sClass];
  54. return $sPage;
  55. }
  56. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  57. {
  58. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  59. $oAppContext = new ApplicationContext();
  60. $sExtClassNameAtt = MetaModel::GetNameAttributeCode($sObjClass);
  61. $sPage = self::ComputeUIPage($sObjClass);
  62. $sAbsoluteUrl = utils::GetAbsoluteUrl(false); // False => Don't get the query string
  63. $sAbsoluteUrl = substr($sAbsoluteUrl, 0, 1+strrpos($sAbsoluteUrl, '/')); // remove the current page, keep just the path, up to the last /
  64. // Use the "name" of the target class as the label of the hyperlink
  65. // unless it's not available in the external attributes...
  66. if (isset($aAvailableFields[$sExtClassNameAtt]))
  67. {
  68. $sLabel = $aAvailableFields[$sExtClassNameAtt];
  69. }
  70. else
  71. {
  72. $sLabel = implode(' / ', $aAvailableFields);
  73. }
  74. // Safety belt
  75. //
  76. if (empty($sLabel))
  77. {
  78. // Developer's note:
  79. // This is doing the job for you, but that is just there in case
  80. // the external fields associated to the external key are blanks
  81. // The ultimate solution will be to query the name automatically
  82. // and independantly from the data model (automatic external field)
  83. // AND make the name be a mandatory field
  84. //
  85. $sObject = MetaModel::GetObject($sObjClass, $sObjKey);
  86. $sLabel = $sObject->GetName();
  87. }
  88. // Safety net
  89. //
  90. if (empty($sLabel))
  91. {
  92. $sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  93. }
  94. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  95. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  96. }
  97. function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
  98. {
  99. // Standard Header with name, actions menu and history block
  100. //
  101. // action menu
  102. $oSingletonFilter = new DBObjectSearch(get_class($this));
  103. $oSingletonFilter->AddCondition('id', $this->GetKey(), '=');
  104. $oBlock = new MenuBlock($oSingletonFilter, 'popup', false);
  105. $oBlock->Display($oPage, -1);
  106. $oPage->add("<div class=\"page_header\"><h1>".$this->GetIcon()."&nbsp;\n");
  107. $oPage->add(MetaModel::GetName(get_class($this)).": <span class=\"hilite\">".$this->GetName()."</span></h1>\n");
  108. $oPage->add("</div>\n");
  109. }
  110. function DisplayBareHistory(WebPage $oPage, $bEditMode = false)
  111. {
  112. // history block (with as a tab)
  113. $oHistoryFilter = new DBObjectSearch('CMDBChangeOp');
  114. $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '=');
  115. $oHistoryFilter->AddCondition('objclass', get_class($this), '=');
  116. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  117. $oBlock->Display($oPage, -1);
  118. }
  119. function DisplayBareProperties(WebPage $oPage, $bEditMode = false)
  120. {
  121. $oPage->add($this->GetBareProperties($oPage, $bEditMode));
  122. }
  123. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  124. {
  125. // Related objects: display all the linkset attributes, each as a separate tab
  126. // In the order described by the 'display' ZList
  127. $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  128. if (count($aList) == 0)
  129. {
  130. // Empty ZList defined, display all the linkedset attributes defined
  131. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  132. }
  133. foreach($aList as $sAttCode)
  134. {
  135. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  136. // Display mode
  137. if (!$oAttDef->IsLinkset()) continue; // Process only linkset attributes...
  138. $oPage->SetCurrentTab($oAttDef->GetLabel());
  139. if ($bEditMode)
  140. {
  141. $iFlags = $this->GetAttributeFlags($sAttCode);
  142. $sClass = get_class($this);
  143. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  144. if (get_class($oAttDef) == 'AttributeLinkedSet')
  145. {
  146. // 1:n links
  147. $sTargetClass = $oAttDef->GetLinkedClass();
  148. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  149. $oFilter = new DBObjectSearch($sTargetClass);
  150. $oFilter->AddCondition($oAttDef->GetExtKeyToMe(), $this->GetKey(),'=');
  151. $aParams = array(
  152. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  153. 'object_id' => $this->GetKey(),
  154. 'menu' => true,
  155. 'default' => array($oAttDef->GetExtKeyToMe() => $this->GetKey()),
  156. );
  157. $oBlock = new DisplayBlock($oFilter, 'list', false);
  158. $oBlock->Display($oPage, $sInputId, $aParams);
  159. }
  160. else // get_class($oAttDef) == 'AttributeLinkedSetIndirect'
  161. {
  162. // n:n links
  163. $sLinkedClass = $oAttDef->GetLinkedClass();
  164. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  165. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  166. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  167. $sValue = $this->Get($sAttCode);
  168. $sDisplayValue = $this->GetEditValue($sAttCode);
  169. $aArgs = array('this' => $this);
  170. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  171. $aFieldsMap[$sAttCode] = $sInputId;
  172. $oPage->add($sHTMLValue);
  173. }
  174. }
  175. else
  176. {
  177. // Display mode
  178. if (!$oAttDef->IsIndirect())
  179. {
  180. // 1:n links
  181. $sTargetClass = $oAttDef->GetLinkedClass();
  182. $aParams = array(
  183. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  184. 'object_id' => $this->GetKey(),
  185. 'menu' => true,
  186. 'default' => array($oAttDef->GetExtKeyToMe() => $this->GetKey()),
  187. );
  188. }
  189. else
  190. {
  191. // n:n links
  192. $sLinkedClass = $oAttDef->GetLinkedClass();
  193. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  194. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  195. $bMenu = ($this->Get($sAttCode)->Count() > 0); // The menu is enabled only if there are already some elements...
  196. $aParams = array(
  197. 'link_attr' => $oAttDef->GetExtKeyToMe(),
  198. 'object_id' => $this->GetKey(),
  199. 'target_attr' => $oAttDef->GetExtKeyToRemote(),
  200. 'view_link' => false,
  201. 'menu' => false,
  202. );
  203. }
  204. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  205. $oBlock = new DisplayBlock($this->Get($sAttCode)->GetFilter(), 'list', false);
  206. $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams);
  207. }
  208. }
  209. $oPage->SetCurrentTab('');
  210. if (!$bEditMode)
  211. {
  212. // Get the actual class of the current object
  213. // And look for triggers referring to it
  214. // If any trigger has been found then display a tab with notifications
  215. //
  216. $sClass = get_class($this);
  217. $oTriggerSet = new CMDBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObject AS T WHERE T.target_class = '$sClass'"));
  218. if ($oTriggerSet->Count() > 0)
  219. {
  220. $oPage->SetCurrentTab(Dict::S('UI:NotificationsTab'));
  221. // Display notifications regarding the object
  222. $iId = $this->GetKey();
  223. $oNotifSet = new CMDBObjectSet(DBObjectSearch::FromOQL("SELECT EventNotificationEmail AS Ev JOIN TriggerOnObject AS T ON Ev.trigger_id = T.id WHERE T.target_class = '$sClass' AND Ev.object_id = $iId"));
  224. self::DisplaySet($oPage, $oNotifSet);
  225. }
  226. }
  227. }
  228. function GetBareProperties(WebPage $oPage, $bEditMode = false)
  229. {
  230. $sHtml = '';
  231. $oAppContext = new ApplicationContext();
  232. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  233. $aDetails = array();
  234. $sClass = get_class($this);
  235. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  236. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  237. // Compute the list of properties to display, first the attributes in the 'details' list, then
  238. // all the remaining attributes that are not external fields
  239. $sHtml = '';
  240. $aDetails = array();
  241. foreach($aDetailsStruct as $sTab => $aCols )
  242. {
  243. $aDetails[$sTab] = array();
  244. ksort($aCols);
  245. $oPage->SetCurrentTab(Dict::S($sTab));
  246. $oPage->add('<table style="vertical-align:top"><tr>');
  247. foreach($aCols as $sColIndex => $aFieldsets)
  248. {
  249. $aDetails[$sTab][$sColIndex] = array();
  250. foreach($aFieldsets as $sFieldsetName => $aFields)
  251. {
  252. //if ($sFieldsetName == '')
  253. //{
  254. foreach($aFields as $sAttCode)
  255. {
  256. $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode);
  257. if ($val != null)
  258. {
  259. // The field is visible, add it to the current column
  260. $aDetails[$sTab][$sColIndex][] = $val;
  261. }
  262. }
  263. //}
  264. }
  265. $oPage->add('<td style="vertical-align:top">');
  266. $oPage->Details($aDetails[$sTab][$sColIndex]);
  267. $oPage->add('</td>');
  268. }
  269. $oPage->add('</tr></table>');
  270. }
  271. return $sHtml;
  272. }
  273. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  274. {
  275. $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate(get_class($this)));
  276. if (!empty($sTemplate))
  277. {
  278. $oTemplate = new DisplayTemplate($sTemplate);
  279. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  280. // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved
  281. // but the preferred method is to use '$id$'
  282. $oTemplate->Render($oPage, array('class_name'=> MetaModel::GetName(get_class($this)),'class'=> get_class($this), 'pkey'=> $this->GetKey(), 'id'=> $this->GetKey(), 'name' => $this->Get($sNameAttCode)));
  283. }
  284. else
  285. {
  286. // Object's details
  287. // template not found display the object using the *old style*
  288. $this->DisplayBareHeader($oPage, $bEditMode);
  289. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  290. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  291. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  292. $this->DisplayBareProperties($oPage, $bEditMode);
  293. $this->DisplayBareRelations($oPage, $bEditMode);
  294. $oPage->SetCurrentTab(Dict::S('UI:HistoryTab'));
  295. $this->DisplayBareHistory($oPage, $bEditMode);
  296. }
  297. }
  298. function DisplayPreview(WebPage $oPage)
  299. {
  300. $aDetails = array();
  301. $sClass = get_class($this);
  302. $aList = MetaModel::GetZListItems($sClass, 'preview');
  303. foreach($aList as $sAttCode)
  304. {
  305. $aDetails[] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' =>$this->GetAsHTML($sAttCode));
  306. }
  307. $oPage->details($aDetails);
  308. }
  309. public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  310. {
  311. $oPage->add(self::GetDisplaySet($oPage, $oSet, $aExtraParams));
  312. }
  313. /**
  314. * Get the HTML fragment corresponding to the display of a table representing a set of objects
  315. * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output
  316. * @param CMDBObjectSet The set of objects to display
  317. * @param Hash $aExtraParams Some extra configuration parameters to tweak the behavior of the display
  318. * @return String The HTML fragment representing the table of objects
  319. */
  320. public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  321. {
  322. static $iListId = 0;
  323. $iListId++;
  324. // Initialize and check the parameters
  325. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  326. $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
  327. $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0;
  328. $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : '';
  329. if (!empty($sLinkageAttribute))
  330. {
  331. if($iLinkedObjectId == 0)
  332. {
  333. // if 'links' mode is requested the id of the object to link to must be specified
  334. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  335. }
  336. if($sTargetAttr == '')
  337. {
  338. // if 'links' mode is requested the d of the object to link to must be specified
  339. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  340. }
  341. }
  342. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  343. $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
  344. $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
  345. $aExtraFields = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  346. $sHtml = '';
  347. $oAppContext = new ApplicationContext();
  348. $sClassName = $oSet->GetFilter()->GetClass();
  349. $aAttribs = array();
  350. $aList = MetaModel::GetZListItems($sClassName, 'list');
  351. $aList = array_merge($aList, $aExtraFields);
  352. if (!empty($sLinkageAttribute))
  353. {
  354. // The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
  355. // and other objects...
  356. // The display will then group all the attributes related to the link itself:
  357. // | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
  358. $aAttDefs = MetaModel::ListAttributeDefs($sClassName);
  359. assert(isset($aAttDefs[$sLinkageAttribute]));
  360. $oAttDef = $aAttDefs[$sLinkageAttribute];
  361. assert($oAttDef->IsExternalKey());
  362. // First display all the attributes specific to the link record
  363. foreach($aList as $sLinkAttCode)
  364. {
  365. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  366. if ( (!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField()) )
  367. {
  368. $aDisplayList[] = $sLinkAttCode;
  369. }
  370. }
  371. // Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
  372. foreach($aList as $sLinkAttCode)
  373. {
  374. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  375. if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
  376. || ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode()!=$sLinkageAttribute)) )
  377. {
  378. $aDisplayList[] = $sLinkAttCode;
  379. }
  380. }
  381. // First display all the attributes specific to the link
  382. // Then display all the attributes linked to the other end of the relationship
  383. $aList = $aDisplayList;
  384. }
  385. if ($bSelectMode)
  386. {
  387. if (!$bSingleSelectMode)
  388. {
  389. $aAttribs['form::select'] = array('label' => "<input type=\"checkbox\" onChange=\"var value = this.checked; $('.selectList{$iListId}').each( function() { this.checked = value; } );\"></input>", 'description' => Dict::S('UI:SelectAllToggle+'));
  390. }
  391. else
  392. {
  393. $aAttribs['form::select'] = array('label' => "", 'description' => '');
  394. }
  395. }
  396. if ($bViewLink)
  397. {
  398. $aAttribs['key'] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  399. }
  400. foreach($aList as $sAttCode)
  401. {
  402. $aAttribs[$sAttCode] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => MetaModel::GetDescription($sClassName, $sAttCode));
  403. }
  404. $aValues = array();
  405. $oSet->Seek(0);
  406. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  407. $iMaxObjects = -1;
  408. if ($bDisplayLimit)
  409. {
  410. if ($oSet->Count() > utils::GetConfig()->GetMaxDisplayLimit())
  411. {
  412. $iMaxObjects = utils::GetConfig()->GetMinDisplayLimit();
  413. }
  414. }
  415. while (($oObj = $oSet->Fetch()) && ($iMaxObjects != 0))
  416. {
  417. $aRow = array();
  418. $sHilightClass = $oObj->GetHilightClass();
  419. if ($sHilightClass != '')
  420. {
  421. $aRow['@class'] = $sHilightClass;
  422. }
  423. if ($bViewLink)
  424. {
  425. $aRow['key'] = $oObj->GetHyperLink();
  426. }
  427. if ($bSelectMode)
  428. {
  429. if ($bSingleSelectMode)
  430. {
  431. $aRow['form::select'] = "<input type=\"radio\" class=\"selectList{$iListId}\" name=\"selectObject\" value=\"".$oObj->GetKey()."\"></input>";
  432. }
  433. else
  434. {
  435. $aRow['form::select'] = "<input type=\"checkBox\" class=\"selectList{$iListId}\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\"></input>";
  436. }
  437. }
  438. foreach($aList as $sAttCode)
  439. {
  440. $aRow[$sAttCode] = $oObj->GetAsHTML($sAttCode);
  441. }
  442. $aValues[] = $aRow;
  443. $iMaxObjects--;
  444. }
  445. $sHtml .= '<table class="listContainer">';
  446. $sColspan = '';
  447. if ($bDisplayMenu)
  448. {
  449. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  450. $sColspan = 'colspan="2"';
  451. $aMenuExtraParams = $aExtraParams;
  452. if (!empty($sLinkageAttribute))
  453. {
  454. //$aMenuExtraParams['linkage'] = $sLinkageAttribute;
  455. $aMenuExtraParams = $aExtraParams;
  456. }
  457. if ($bDisplayLimit && ($oSet->Count() > utils::GetConfig()->GetMaxDisplayLimit()))
  458. {
  459. // list truncated
  460. $divId = $aExtraParams['block_id'];
  461. $sFilter = $oSet->GetFilter()->serialize();
  462. $aExtraParams['display_limit'] = false; // To expand the full list
  463. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  464. $sHtml .= '<tr class="containerHeader"><td>'.Dict::Format('UI:TruncatedResults', utils::GetConfig()->GetMinDisplayLimit(), $oSet->Count()).'&nbsp;&nbsp;<a href="#open_'.$divId.'" onClick="Javascript:ReloadTruncatedList(\''.$divId.'\', \''.$sFilter.'\', \''.$sExtraParams.'\');">'.Dict::S('UI:DisplayAll').'</a></td><td>';
  465. $oPage->add_ready_script("$('#{$divId} table.listResults').addClass('truncated');");
  466. $oPage->add_ready_script("$('#{$divId} table.listResults tr:last td').addClass('truncated');");
  467. }
  468. else
  469. {
  470. // Full list
  471. $sHtml .= '<tr class="containerHeader"><td>&nbsp;'.Dict::Format('UI:CountOfResults', $oSet->Count()).'</td><td>';
  472. }
  473. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams);
  474. $sHtml .= '</td></tr>';
  475. }
  476. $sHtml .= "<tr><td $sColspan>";
  477. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  478. $sHtml .= '</td></tr>';
  479. $sHtml .= '</table>';
  480. return $sHtml;
  481. }
  482. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  483. {
  484. static $iListId = 0;
  485. $iListId++;
  486. $aList = array();
  487. // Initialize and check the parameters
  488. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  489. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  490. // Check if there is a list of aliases to limit the display to...
  491. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  492. $sHtml = '';
  493. $oAppContext = new ApplicationContext();
  494. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  495. $aAuthorizedClasses = array();
  496. foreach($aClasses as $sAlias => $sClassName)
  497. {
  498. if ((UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) == UR_ALLOWED_YES) &&
  499. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  500. {
  501. $aAuthorizedClasses[$sAlias] = $sClassName;
  502. }
  503. }
  504. $aAttribs = array();
  505. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  506. {
  507. $aList[$sClassName] = MetaModel::GetZListItems($sClassName, 'list');
  508. if ($bViewLink)
  509. {
  510. $aAttribs['key_'.$sAlias] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  511. }
  512. foreach($aList[$sClassName] as $sAttCode)
  513. {
  514. $aAttribs[$sAttCode.'_'.$sAlias] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => MetaModel::GetDescription($sClassName, $sAttCode));
  515. }
  516. }
  517. $aValues = array();
  518. $oSet->Seek(0);
  519. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  520. $iMaxObjects = -1;
  521. if ($bDisplayLimit)
  522. {
  523. if ($oSet->Count() > utils::GetConfig()->GetMaxDisplayLimit())
  524. {
  525. $iMaxObjects = utils::GetConfig()->GetMinDisplayLimit();
  526. }
  527. }
  528. while (($aObjects = $oSet->FetchAssoc()) && ($iMaxObjects != 0))
  529. {
  530. $aRow = array();
  531. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  532. {
  533. if ($bViewLink)
  534. {
  535. $aRow['key_'.$sAlias] = $aObjects[$sAlias]->GetHyperLink();
  536. }
  537. foreach($aList[$sClassName] as $sAttCode)
  538. {
  539. $aRow[$sAttCode.'_'.$sAlias] = $aObjects[$sAlias]->GetAsHTML($sAttCode);
  540. }
  541. }
  542. $aValues[] = $aRow;
  543. $iMaxObjects--;
  544. }
  545. $sHtml .= '<table class="listContainer">';
  546. $sColspan = '';
  547. if ($bDisplayMenu)
  548. {
  549. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  550. $sColspan = 'colspan="2"';
  551. $aMenuExtraParams = $aExtraParams;
  552. if (!empty($sLinkageAttribute))
  553. {
  554. $aMenuExtraParams = $aExtraParams;
  555. }
  556. if ($bDisplayLimit && ($oSet->Count() > utils::GetConfig()->GetMaxDisplayLimit()))
  557. {
  558. // list truncated
  559. $divId = $aExtraParams['block_id'];
  560. $sFilter = $oSet->GetFilter()->serialize();
  561. $aExtraParams['display_limit'] = false; // To expand the full list
  562. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  563. $sHtml .= '<tr class="containerHeader"><td>'.Dict::Format('UI:TruncatedResults', utils::GetConfig()->GetMinDisplayLimit(), $oSet->Count()).'&nbsp;&nbsp;<a href="Javascript:ReloadTruncatedList(\''.$divId.'\', \''.$sFilter.'\', \''.$sExtraParams.'\');">'.Dict::S('UI:DisplayAll').'</a></td><td>';
  564. $oPage->add_ready_script("$('#{$divId} table.listResults').addClass('truncated');");
  565. $oPage->add_ready_script("$('#{$divId} table.listResults tr:last td').addClass('truncated');");
  566. }
  567. else
  568. {
  569. // Full list
  570. $sHtml .= '<tr class="containerHeader"><td>&nbsp;'.Dict::Format('UI:CountOfResults', $oSet->Count()).'</td><td>';
  571. }
  572. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams);
  573. $sHtml .= '</td></tr>';
  574. }
  575. $sHtml .= "<tr><td $sColspan>";
  576. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  577. $sHtml .= '</td></tr>';
  578. $sHtml .= '</table>';
  579. return $sHtml;
  580. }
  581. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  582. {
  583. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  584. }
  585. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  586. {
  587. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  588. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  589. $aList = array();
  590. $oAppContext = new ApplicationContext();
  591. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  592. $aAuthorizedClasses = array();
  593. foreach($aClasses as $sAlias => $sClassName)
  594. {
  595. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) == UR_ALLOWED_YES)
  596. {
  597. $aAuthorizedClasses[$sAlias] = $sClassName;
  598. }
  599. }
  600. $aAttribs = array();
  601. $aHeader = array();
  602. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  603. {
  604. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  605. {
  606. if ((($oAttDef->IsExternalField()) || ($oAttDef->IsWritable())) && $oAttDef->IsScalar())
  607. {
  608. $aList[$sClassName][$sAttCode] = $oAttDef;
  609. }
  610. }
  611. $aHeader[] = 'id';
  612. foreach($aList[$sClassName] as $sAttCode => $oAttDef)
  613. {
  614. if ($oAttDef->IsExternalField())
  615. {
  616. $sExtKeyLabel = MetaModel::GetLabel($sClassName, $oAttDef->GetKeyAttCode());
  617. $sRemoteAttLabel = MetaModel::GetLabel($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  618. $aHeader[] = $sExtKeyLabel.'->'.$sRemoteAttLabel;
  619. }
  620. else
  621. {
  622. $aHeader[] = MetaModel::GetLabel($sClassName, $sAttCode);
  623. }
  624. }
  625. }
  626. $sHtml = implode($sSeparator, $aHeader)."\n";
  627. $oSet->Seek(0);
  628. while ($aObjects = $oSet->FetchAssoc())
  629. {
  630. $aRow = array();
  631. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  632. {
  633. $oObj = $aObjects[$sAlias];
  634. $aRow[] = $oObj->GetKey();
  635. foreach($aList[$sClassName] as $sAttCode => $oAttDef)
  636. {
  637. $aRow[] = $oObj->GetAsCSV($sAttCode, $sSeparator, '\\');
  638. }
  639. }
  640. $sHtml .= implode($sSeparator, $aRow)."\n";
  641. }
  642. return $sHtml;
  643. }
  644. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  645. {
  646. $oAppContext = new ApplicationContext();
  647. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  648. $aAuthorizedClasses = array();
  649. foreach($aClasses as $sAlias => $sClassName)
  650. {
  651. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) == UR_ALLOWED_YES)
  652. {
  653. $aAuthorizedClasses[$sAlias] = $sClassName;
  654. }
  655. }
  656. $aAttribs = array();
  657. $aList = array();
  658. $aList[$sClassName] = MetaModel::GetZListItems($sClassName, 'details');
  659. $oPage->add("<Set>\n");
  660. $oSet->Seek(0);
  661. while ($aObjects = $oSet->FetchAssoc())
  662. {
  663. if (count($aAuthorizedClasses) > 1)
  664. {
  665. $oPage->add("<Row>\n");
  666. }
  667. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  668. {
  669. $oObj = $aObjects[$sAlias];
  670. $sClassName = get_class($oObj);
  671. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  672. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  673. {
  674. if (($oAttDef->IsWritable()) && ($oAttDef->IsScalar()))
  675. {
  676. $sValue = $oObj->GetAsXML($sAttCode);
  677. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  678. }
  679. }
  680. $oPage->add("</$sClassName>\n");
  681. }
  682. if (count($aAuthorizedClasses) > 1)
  683. {
  684. $oPage->add("</Row>\n");
  685. }
  686. }
  687. $oPage->add("</Set>\n");
  688. }
  689. // By rom
  690. function DisplayChangesLog(WebPage $oPage)
  691. {
  692. $oFltChangeOps = new CMDBSearchFilter('CMDBChangeOpSetAttribute');
  693. $oFltChangeOps->AddCondition('objkey', $this->GetKey(), '=');
  694. $oFltChangeOps->AddCondition('objclass', get_class($this), '=');
  695. $oSet = new CMDBObjectSet($oFltChangeOps, array('date' => false)); // order by date descending (i.e. false)
  696. $count = $oSet->Count();
  697. if ($count > 0)
  698. {
  699. $oPage->p(Dict::Format('UI:ChangesLogTitle', $count));
  700. self::DisplaySet($oPage, $oSet);
  701. }
  702. else
  703. {
  704. $oPage->p(Dict::S('UI:EmptyChangesLogTitle'));
  705. }
  706. }
  707. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  708. {
  709. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  710. }
  711. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  712. {
  713. static $iSearchFormId = 0;
  714. $oAppContext = new ApplicationContext();
  715. $sHtml = '';
  716. $numCols=4;
  717. $sClassName = $oSet->GetFilter()->GetClass();
  718. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  719. // (especially when used to add a link)
  720. /*
  721. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  722. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  723. <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>
  724. </ul></div>\n";
  725. */
  726. // Simple search form
  727. if (isset($aExtraParams['currentId']))
  728. {
  729. $sSearchFormId = $aExtraParams['currentId'];
  730. $iSearchFormId++;
  731. }
  732. else
  733. {
  734. $iSearchFormId++;
  735. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  736. $sHtml .= "<div id=\"$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  737. }
  738. // Check if the current class has some sub-classes
  739. if (isset($aExtraParams['baseClass']))
  740. {
  741. $sRootClass = $aExtraParams['baseClass'];
  742. }
  743. else
  744. {
  745. $sRootClass = $sClassName;
  746. }
  747. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  748. if (count($aSubClasses) > 0)
  749. {
  750. $aOptions = array();
  751. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  752. foreach($aSubClasses as $sSubclassName)
  753. {
  754. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  755. }
  756. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  757. ksort($aOptions);
  758. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass')\">\n".implode('', $aOptions)."</select>\n";
  759. }
  760. else
  761. {
  762. $sClassesCombo = MetaModel::GetName($sClassName);
  763. }
  764. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  765. $sHtml .= "<form id=\"form{$iSearchFormId}\">\n";
  766. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  767. $index = 0;
  768. $sHtml .= "<p>\n";
  769. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  770. $aMapCriteria = array();
  771. foreach($aFilterCriteria as $aCriteria)
  772. {
  773. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  774. }
  775. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  776. foreach($aList as $sFilterCode)
  777. {
  778. $oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  779. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  780. $sFilterValue = '';
  781. $sFilterValue = utils::ReadParam($sFilterCode, '');
  782. $sFilterOpCode = null; // Use the default 'loose' OpCode
  783. if (empty($sFilterValue))
  784. {
  785. if (isset($aMapCriteria[$sFilterCode]))
  786. {
  787. if (count($aMapCriteria[$sFilterCode]) > 1)
  788. {
  789. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  790. }
  791. else
  792. {
  793. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  794. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  795. }
  796. if ($sFilterCode != 'company')
  797. {
  798. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  799. }
  800. }
  801. }
  802. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  803. if ($aAllowedValues != null)
  804. {
  805. //Enum field or external key, display a combo
  806. $sValue = "<select name=\"$sFilterCode\">\n";
  807. $sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  808. foreach($aAllowedValues as $key => $value)
  809. {
  810. if ($sFilterValue == $key)
  811. {
  812. $sSelected = ' selected';
  813. }
  814. else
  815. {
  816. $sSelected = '';
  817. }
  818. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  819. }
  820. $sValue .= "</select>\n";
  821. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  822. }
  823. else
  824. {
  825. // Any value is possible, display an input box
  826. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"$sFilterValue\"/>\n";
  827. }
  828. $index++;
  829. $sHtml .= '</span> ';
  830. }
  831. $sHtml .= "</p>\n";
  832. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  833. foreach($aExtraParams as $sName => $sValue)
  834. {
  835. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  836. }
  837. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  838. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  839. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  840. $sHtml .= $oAppContext->GetForForm();
  841. $sHtml .= "</form>\n";
  842. if (!isset($aExtraParams['currentId']))
  843. {
  844. $sHtml .= "</div><!-- Simple search form -->\n";
  845. }
  846. // OQL query builder
  847. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  848. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  849. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  850. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  851. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  852. $sSelectedClass = utils::ReadParam('oql_class', $sClassName);
  853. $sOQLClause = utils::ReadParam('oql_clause', '');
  854. asort($aClasses);
  855. foreach($aClasses as $sChildClass)
  856. {
  857. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  858. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  859. }
  860. $sHtml .= "</select>&nbsp;</td><td>\n";
  861. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  862. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  863. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  864. foreach($aExtraParams as $sName => $sValue)
  865. {
  866. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  867. }
  868. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  869. $sHtml .= $oAppContext->GetForForm();
  870. $sHtml .= "</table></form>\n";
  871. $sHtml .= "</div><!-- OQL query form -->\n";
  872. return $sHtml;
  873. }
  874. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  875. {
  876. static $iInputId = 0;
  877. $sFieldPrefix = '';
  878. if (isset($aArgs['prefix']))
  879. {
  880. $sFieldPrefix = $aArgs['prefix'];
  881. }
  882. if (isset($aArgs[$sAttCode]) && empty($value))
  883. {
  884. // default value passed by the context (either the app context of the operation)
  885. $value = $aArgs[$sAttCode];
  886. }
  887. if (!empty($iId))
  888. {
  889. $iInputId = $iId;
  890. }
  891. else
  892. {
  893. $iInputId++;
  894. $iId = $iInputId;
  895. }
  896. if (!$oAttDef->IsExternalField())
  897. {
  898. $aCSSClasses = array();
  899. $bMandatory = 0;
  900. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  901. {
  902. $aCSSClasses[] = 'mandatory';
  903. $bMandatory = 1;
  904. }
  905. $sCSSClasses = self::GetCSSClasses($aCSSClasses);
  906. $sValidationField = "<span id=\"v_{$iId}\"></span>";
  907. $sHelpText = $oAttDef->GetHelpOnEdition();
  908. $aEventsList = array('validate');
  909. switch($oAttDef->GetEditClass())
  910. {
  911. case 'Date':
  912. case 'DateTime':
  913. $aEventsList[] ='keyup';
  914. $aEventsList[] ='change';
  915. $sHTMLValue = "<input title=\"$sHelpText\" class=\"date-pick\" type=\"text\" size=\"20\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  916. break;
  917. case 'Password':
  918. $aEventsList[] ='keyup';
  919. $aEventsList[] ='change';
  920. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  921. break;
  922. case 'Text':
  923. $aEventsList[] ='keyup';
  924. $aEventsList[] ='change';
  925. $sHTMLValue = "<textarea class=\"resizable\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\">$value</textarea>&nbsp;{$sValidationField}";
  926. break;
  927. case 'LinkedSet':
  928. $aEventsList[] ='change';
  929. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix);
  930. $sHTMLValue = $oWidget->Display($oPage, $value);
  931. break;
  932. case 'Document':
  933. $aEventsList[] ='change';
  934. $oDocument = $value; // Value is an ormDocument object
  935. $sFileName = '';
  936. if (is_object($oDocument))
  937. {
  938. $sFileName = $oDocument->GetFileName();
  939. }
  940. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  941. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  942. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" type=\"hidden\" id=\"$iId\" \" value=\"$sFileName\"/>\n";
  943. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  944. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"file_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  945. break;
  946. case 'List':
  947. // Not editable for now...
  948. $sHTMLValue = '';
  949. break;
  950. case 'String':
  951. default:
  952. // #@# todo - add context information (depending on dimensions)
  953. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  954. if ($aAllowedValues !== null)
  955. {
  956. //Enum field or external key, display a combo
  957. //if (count($aAllowedValues) == 0)
  958. //{
  959. // $sHTMLValue = "<input count=\"0\" type=\"text\" size=\"30\" value=\"\" name=\"attr_{$sAttCode}{$sNameSuffix}\" id=\"$iInputId\"{$sCSSClasses}/>";
  960. //}
  961. //else if (count($aAllowedValues) > 50)
  962. if (count($aAllowedValues) > 50)
  963. {
  964. // too many choices, use an autocomplete
  965. // The input for the auto complete
  966. $sHTMLValue = "<input count=\"".count($aAllowedValues)."\" type=\"text\" id=\"label_$iId\" size=\"30\" value=\"$sDisplayValue\"{$sCSSClasses}/>&nbsp;{$sValidationField}";
  967. // another hidden input to store & pass the object's Id
  968. $sHTMLValue .= "<input type=\"hidden\" id=\"$iId\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" />\n";
  969. $oPage->add_ready_script("\$('#label_$iId').autocomplete('./ajax.render.php', { scroll:true, minChars:3, onItemSelect:selectItem, onFindValue:findValue, formatItem:formatItem, autoFill:true, keyHolder:'#$iId', extraParams:{operation:'autocomplete', sclass:'$sClass',attCode:'".$sAttCode."'}});");
  970. $oPage->add_ready_script("\$('#label_$iId').result( function(event, data, formatted) { if (data) { $('#{$iId}').val(data[1]); } } );");
  971. $aEventsList[] ='change';
  972. }
  973. else
  974. {
  975. // Few choices, use a normal 'select'
  976. // In case there are no valid values, the select will be empty, thus blocking the user from validating the form
  977. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  978. $sHTMLValue .= "<option value=\"0\">".Dict::S('UI:SelectOne')."</option>\n";
  979. foreach($aAllowedValues as $key => $display_value)
  980. {
  981. if ((count($aAllowedValues) == 1) && $bMandatory )
  982. {
  983. // When there is only once choice, select it by default
  984. $sSelected = ' selected';
  985. }
  986. else
  987. {
  988. $sSelected = ($value == $key) ? ' selected' : '';
  989. }
  990. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  991. }
  992. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  993. $aEventsList[] ='change';
  994. }
  995. }
  996. else
  997. {
  998. $sHTMLValue = "<input title=\"$sHelpText\" type=\"text\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  999. $aEventsList[] ='keyup';
  1000. $aEventsList[] ='change';
  1001. }
  1002. break;
  1003. }
  1004. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1005. $oPage->add_ready_script("$('#$iId').bind('".implode(' ', $aEventsList)."', function(evt, sFormId) { return ValidateField('$iId', '$sPattern', $bMandatory, sFormId) } );"); // Bind to a custom event: validate
  1006. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1007. if (count($aDependencies) > 0)
  1008. {
  1009. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return UpdateDependentFields(['".implode("','", $aDependencies)."']) } );"); // Bind to a custom event: validate
  1010. }
  1011. }
  1012. return "<div>{$sHTMLValue}</div>";
  1013. }
  1014. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1015. {
  1016. static $iGlobalFormId = 0;
  1017. $iGlobalFormId++;
  1018. $this->m_iFormId = $iGlobalFormId;
  1019. $sClass = get_class($this);
  1020. $oAppContext = new ApplicationContext();
  1021. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1022. $iKey = $this->GetKey();
  1023. $aDetails = array();
  1024. $aFieldsMap = array();
  1025. if (!isset($aExtraParams['action']))
  1026. {
  1027. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1028. }
  1029. else
  1030. {
  1031. $sFormAction = $aExtraParams['action'];
  1032. }
  1033. $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");
  1034. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  1035. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1036. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1037. $aDetailsList = $this->FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1038. //$aFullList = MetaModel::ListAttributeDefs($sClass);
  1039. $aList = array();
  1040. // Compute the list of properties to display, first the attributes in the 'details' list, then
  1041. // all the remaining attributes that are not external fields
  1042. foreach($aDetailsList as $sAttCode)
  1043. {
  1044. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1045. if (!$oAttDef->IsExternalField())
  1046. {
  1047. $aList[] = $sAttCode;
  1048. }
  1049. }
  1050. foreach($aList as $sAttCode)
  1051. {
  1052. $iFlags = $this->GetAttributeFlags($sAttCode);
  1053. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1054. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0))
  1055. {
  1056. if ($oAttDef->IsWritable())
  1057. {
  1058. if ($sStateAttCode == $sAttCode)
  1059. {
  1060. // State attribute is always read-only from the UI
  1061. $sHTMLValue = $this->GetStateLabel();
  1062. $aDetails[] = array('label' => $oAttDef->GetLabel(), 'value' => $sHTMLValue);
  1063. }
  1064. else
  1065. {
  1066. $iFlags = $this->GetAttributeFlags($sAttCode);
  1067. if ($iFlags & OPT_ATT_HIDDEN)
  1068. {
  1069. // Attribute is hidden, do nothing
  1070. }
  1071. else
  1072. {
  1073. if ($iFlags & OPT_ATT_READONLY)
  1074. {
  1075. // Attribute is read-only
  1076. $sHTMLValue = $this->GetAsHTML($sAttCode);
  1077. }
  1078. else
  1079. {
  1080. $sValue = $this->Get($sAttCode);
  1081. $sDisplayValue = $this->GetEditValue($sAttCode);
  1082. $aArgs = array('this' => $this);
  1083. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  1084. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  1085. $aFieldsMap[$sAttCode] = $sInputId;
  1086. }
  1087. $aDetails[] = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue);
  1088. }
  1089. }
  1090. }
  1091. else
  1092. {
  1093. $aDetails[] = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $this->GetAsHTML($sAttCode));
  1094. }
  1095. }
  1096. }
  1097. $oPage->details($aDetails);
  1098. // Now display the relations, one tab per relation
  1099. $this->DisplayBareRelations($oPage, true); // Edit mode
  1100. $oPage->SetCurrentTab('');
  1101. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1102. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1103. foreach($aExtraParams as $sName => $value)
  1104. {
  1105. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1106. }
  1107. $oPage->add($oAppContext->GetForForm());
  1108. if ($iKey > 0)
  1109. {
  1110. // The object already exists in the database, it's modification
  1111. $oPage->add("<input type=\"hidden\" name=\"id\" value=\"$iKey\">\n");
  1112. $oPage->add("<input type=\"hidden\" name=\"operation\" value=\"apply_modify\">\n");
  1113. $oPage->add("<button type=\"button\" class=\"action\" onClick=\"BackToDetails('$sClass', $iKey)\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1114. $oPage->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:Apply')."</span></button>\n");
  1115. }
  1116. else
  1117. {
  1118. // The object does not exist in the database it's a creation
  1119. $oPage->add("<input type=\"hidden\" name=\"operation\" value=\"apply_new\">\n");
  1120. $oPage->add("<button type=\"button\" class=\"action\" onClick=\"goBack()\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1121. $oPage->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:Create')."</span></button>\n");
  1122. }
  1123. $oPage->add("</form>\n");
  1124. $iFieldsCount = count($aFieldsMap);
  1125. $sJsonFieldsMap = json_encode($aFieldsMap);
  1126. $oPage->add_script(
  1127. <<<EOF
  1128. // Create the object once at the beginning of the page...
  1129. var oWizardHelper = new WizardHelper('$sClass');
  1130. oWizardHelper.SetFieldsMap($sJsonFieldsMap);
  1131. oWizardHelper.SetFieldsCount($iFieldsCount);
  1132. EOF
  1133. );
  1134. $oPage->add_ready_script(
  1135. <<<EOF
  1136. // Starts the validation when the page is ready
  1137. CheckFields('form_{$this->m_iFormId}', false);
  1138. EOF
  1139. );
  1140. }
  1141. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1142. {
  1143. $oAppContext = new ApplicationContext();
  1144. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1145. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1146. $aStates = MetaModel::EnumStates($sClass);
  1147. if ($oObjectToClone == null)
  1148. {
  1149. $sTargetState = MetaModel::GetDefaultState($sClass);
  1150. $oObj = MetaModel::NewObject($sClass);
  1151. $oObj->Set($sStateAttCode, $sTargetState);
  1152. }
  1153. else
  1154. {
  1155. $oObj = clone $oObjectToClone;
  1156. }
  1157. return $oObj->DisplayModifyForm( $oPage, $aExtraParams = array());
  1158. }
  1159. protected static function GetCSSClasses($aCSSClasses)
  1160. {
  1161. $sCSSClasses = '';
  1162. if (!empty($aCSSClasses))
  1163. {
  1164. $sCSSClasses = ' class="'.implode(' ', $aCSSClasses).'" ';
  1165. }
  1166. return $sCSSClasses;
  1167. }
  1168. protected static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  1169. {
  1170. //echo "<pre>ZList: ";
  1171. //print_r($aList);
  1172. //echo "</pre>\n";
  1173. foreach($aList as $sKey => $value)
  1174. {
  1175. if (is_array($value))
  1176. {
  1177. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  1178. {
  1179. $sCode = $aMatches[1];
  1180. $sName = $aMatches[2];
  1181. switch($sCode)
  1182. {
  1183. case 'tab':
  1184. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  1185. if(!isset($aDetails[$sName]))
  1186. {
  1187. $aDetails[$sName] = array('col1' => array('' => array()));
  1188. }
  1189. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  1190. break;
  1191. case 'fieldset':
  1192. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  1193. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  1194. {
  1195. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  1196. }
  1197. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  1198. break;
  1199. default:
  1200. case 'col':
  1201. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  1202. if(!isset($aDetails[$sCurrentTab][$sName]))
  1203. {
  1204. $aDetails[$sCurrentTab][$sName] = array('' => array());
  1205. }
  1206. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  1207. break;
  1208. }
  1209. }
  1210. }
  1211. else
  1212. {
  1213. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  1214. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  1215. }
  1216. }
  1217. return $aDetails;
  1218. }
  1219. protected static function FlattenZList($aList)
  1220. {
  1221. $aResult = array();
  1222. foreach($aList as $value)
  1223. {
  1224. if (!is_array($value))
  1225. {
  1226. $aResult[] = $value;
  1227. }
  1228. else
  1229. {
  1230. $aResult = array_merge($aResult, $this->FlattenZList($value));
  1231. }
  1232. }
  1233. return $aResult;
  1234. }
  1235. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  1236. {
  1237. $retVal = null;
  1238. $iFlags = $this->GetAttributeFlags($sAttCode);
  1239. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1240. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  1241. {
  1242. // The field is visible in the current state of the object
  1243. if ($sStateAttCode == $sAttCode)
  1244. {
  1245. // Special display for the 'state' attribute itself
  1246. $sDisplayValue = $this->GetStateLabel();
  1247. }
  1248. else if ($oAttDef->GetEditClass() == 'Document')
  1249. {
  1250. $oDocument = $this->Get($sAttCode);
  1251. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1252. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1253. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1254. }
  1255. else
  1256. {
  1257. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1258. }
  1259. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1260. }
  1261. return $retVal;
  1262. }
  1263. /**
  1264. * Displays a blob document *inline* (if possible, depending on the type of the document)
  1265. * @return string
  1266. */
  1267. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  1268. {
  1269. $oDoc = $this->Get($sAttCode);
  1270. $sClass = get_class($this);
  1271. $Id = $this->GetKey();
  1272. switch ($oDoc->GetMainMimeType())
  1273. {
  1274. case 'text':
  1275. case 'html':
  1276. $data = $oDoc->GetData();
  1277. switch($oDoc->GetMimeType())
  1278. {
  1279. case 'text/html':
  1280. case 'text/xml':
  1281. $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");
  1282. break;
  1283. default:
  1284. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true))."</pre>\n");
  1285. }
  1286. break;
  1287. case 'application':
  1288. switch($oDoc->GetMimeType())
  1289. {
  1290. case 'application/pdf':
  1291. $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");
  1292. break;
  1293. default:
  1294. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1295. }
  1296. break;
  1297. case 'image':
  1298. $oPage->add("<img src=\"../pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  1299. break;
  1300. default:
  1301. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1302. }
  1303. }
  1304. /**
  1305. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1306. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1307. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1308. * To Be overridden by derived classes
  1309. * @param void
  1310. * @return String The desired higlight class for the object/row
  1311. */
  1312. public function GetHilightClass()
  1313. {
  1314. // Possible return values are:
  1315. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1316. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1317. }
  1318. }
  1319. ?>