cmdbabstract.class.inc.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750
  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/utils.inc.php');
  32. require_once(APPROOT.'/application/applicationcontext.class.inc.php');
  33. require_once(APPROOT.'/application/ui.linkswidget.class.inc.php');
  34. require_once(APPROOT.'/application/ui.passwordwidget.class.inc.php');
  35. require_once(APPROOT.'/application/ui.extkeywidget.class.inc.php');
  36. require_once(APPROOT.'/application/ui.htmleditorwidget.class.inc.php');
  37. abstract class cmdbAbstractObject extends CMDBObject
  38. {
  39. protected $m_iFormId; // The ID of the form used to edit the object (when in edition mode !)
  40. public static function GetUIPage()
  41. {
  42. return '../pages/UI.php';
  43. }
  44. public static function ComputeUIPage($sClass)
  45. {
  46. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  47. if (!isset($aUIPagesCache[$sClass]))
  48. {
  49. $UIPage = false;
  50. if (is_callable("$sClass::GetUIPage"))
  51. {
  52. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  53. }
  54. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  55. }
  56. $sPage = $aUIPagesCache[$sClass];
  57. return $sPage;
  58. }
  59. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  60. {
  61. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  62. $oAppContext = new ApplicationContext();
  63. $sExtClassNameAtt = MetaModel::GetNameAttributeCode($sObjClass);
  64. $sPage = self::ComputeUIPage($sObjClass);
  65. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  66. // Use the "name" of the target class as the label of the hyperlink
  67. // unless it's not available in the external attributes...
  68. if (isset($aAvailableFields[$sExtClassNameAtt]))
  69. {
  70. $sLabel = $aAvailableFields[$sExtClassNameAtt];
  71. }
  72. else
  73. {
  74. $sLabel = implode(' / ', $aAvailableFields);
  75. }
  76. // Safety belt
  77. //
  78. if (empty($sLabel))
  79. {
  80. // Developer's note:
  81. // This is doing the job for you, but that is just there in case
  82. // the external fields associated to the external key are blanks
  83. // The ultimate solution will be to query the name automatically
  84. // and independantly from the data model (automatic external field)
  85. // AND make the name be a mandatory field
  86. //
  87. $sObject = MetaModel::GetObject($sObjClass, $sObjKey);
  88. $sLabel = $sObject->GetName();
  89. }
  90. // Safety net
  91. //
  92. if (empty($sLabel))
  93. {
  94. $sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  95. }
  96. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  97. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  98. }
  99. function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
  100. {
  101. // Standard Header with name, actions menu and history block
  102. //
  103. // action menu
  104. $oSingletonFilter = new DBObjectSearch(get_class($this));
  105. $oSingletonFilter->AddCondition('id', $this->GetKey(), '=');
  106. $oBlock = new MenuBlock($oSingletonFilter, 'popup', false);
  107. $oBlock->Display($oPage, -1);
  108. $oPage->add("<div class=\"page_header\"><h1>".$this->GetIcon()."&nbsp;\n");
  109. $oPage->add(MetaModel::GetName(get_class($this)).": <span class=\"hilite\">".$this->GetName()."</span></h1>\n");
  110. $oPage->add("</div>\n");
  111. }
  112. function DisplayBareHistory(WebPage $oPage, $bEditMode = false)
  113. {
  114. // history block (with as a tab)
  115. $oHistoryFilter = new DBObjectSearch('CMDBChangeOp');
  116. $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '=');
  117. $oHistoryFilter->AddCondition('objclass', get_class($this), '=');
  118. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  119. $oBlock->Display($oPage, -1);
  120. }
  121. function DisplayBareProperties(WebPage $oPage, $bEditMode = false)
  122. {
  123. $oPage->add($this->GetBareProperties($oPage, $bEditMode));
  124. }
  125. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  126. {
  127. // Related objects: display all the linkset attributes, each as a separate tab
  128. // In the order described by the 'display' ZList
  129. $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  130. if (count($aList) == 0)
  131. {
  132. // Empty ZList defined, display all the linkedset attributes defined
  133. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  134. }
  135. $sClass = get_class($this);
  136. foreach($aList as $sAttCode)
  137. {
  138. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  139. // Display mode
  140. if (!$oAttDef->IsLinkset()) continue; // Process only linkset attributes...
  141. $oPage->SetCurrentTab($oAttDef->GetLabel());
  142. if ($bEditMode)
  143. {
  144. $iFlags = $this->GetAttributeFlags($sAttCode);
  145. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  146. if (get_class($oAttDef) == 'AttributeLinkedSet')
  147. {
  148. // 1:n links
  149. $sTargetClass = $oAttDef->GetLinkedClass();
  150. if ($this->IsNew())
  151. {
  152. $oPage->p(Dict::Format('UI:BeforeAdding_Class_ObjectsSaveThisObject', MetaModel::GetName($sTargetClass)));
  153. }
  154. else
  155. {
  156. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  157. $oFilter = new DBObjectSearch($sTargetClass);
  158. $oFilter->AddCondition($oAttDef->GetExtKeyToMe(), $this->GetKey(),'=');
  159. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  160. $oAppContext = new ApplicationContext();
  161. foreach($oAppContext->GetNames() as $sKey)
  162. {
  163. // The linked object inherits the parent's value for the context
  164. if (MetaModel::IsValidAttCode($sClass, $sKey))
  165. {
  166. $aDefaults[$sKey] = $this->Get($sKey);
  167. }
  168. }
  169. $aParams = array(
  170. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  171. 'object_id' => $this->GetKey(),
  172. 'menu' => true,
  173. 'default' => $aDefaults,
  174. );
  175. $oBlock = new DisplayBlock($oFilter, 'list', false);
  176. $oBlock->Display($oPage, $sInputId, $aParams);
  177. }
  178. }
  179. else // get_class($oAttDef) == 'AttributeLinkedSetIndirect'
  180. {
  181. // n:n links
  182. $sLinkedClass = $oAttDef->GetLinkedClass();
  183. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  184. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  185. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription().'<span id="busy_'.$sInputId.'"></span>');
  186. $sValue = $this->Get($sAttCode);
  187. $sDisplayValue = $this->GetEditValue($sAttCode);
  188. $aArgs = array('this' => $this);
  189. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  190. $aFieldsMap[$sAttCode] = $sInputId;
  191. $oPage->add($sHTMLValue);
  192. }
  193. }
  194. else
  195. {
  196. // Display mode
  197. if (!$oAttDef->IsIndirect())
  198. {
  199. // 1:n links
  200. $sTargetClass = $oAttDef->GetLinkedClass();
  201. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  202. $oAppContext = new ApplicationContext();
  203. foreach($oAppContext->GetNames() as $sKey)
  204. {
  205. // The linked object inherits the parent's value for the context
  206. if (MetaModel::IsValidAttCode($sClass, $sKey))
  207. {
  208. $aDefaults[$sKey] = $this->Get($sKey);
  209. }
  210. }
  211. $aParams = array(
  212. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  213. 'object_id' => $this->GetKey(),
  214. 'menu' => false,
  215. 'default' => $aDefaults,
  216. );
  217. }
  218. else
  219. {
  220. // n:n links
  221. $sLinkedClass = $oAttDef->GetLinkedClass();
  222. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  223. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  224. $bMenu = ($this->Get($sAttCode)->Count() > 0); // The menu is enabled only if there are already some elements...
  225. $aParams = array(
  226. 'link_attr' => $oAttDef->GetExtKeyToMe(),
  227. 'object_id' => $this->GetKey(),
  228. 'target_attr' => $oAttDef->GetExtKeyToRemote(),
  229. 'view_link' => false,
  230. 'menu' => false,
  231. 'display_limit' => true, // By default limit the list to speed up the initial load & display
  232. );
  233. }
  234. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  235. $oBlock = new DisplayBlock($this->Get($sAttCode)->GetFilter(), 'list', false);
  236. $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams);
  237. }
  238. }
  239. $oPage->SetCurrentTab('');
  240. if (!$bEditMode)
  241. {
  242. // Get the actual class of the current object
  243. // And look for triggers referring to it
  244. // If any trigger has been found then display a tab with notifications
  245. //
  246. $sClass = get_class($this);
  247. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  248. $oTriggerSet = new CMDBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObject AS T WHERE T.target_class IN ('$sClassList')"));
  249. if ($oTriggerSet->Count() > 0)
  250. {
  251. $oPage->SetCurrentTab(Dict::S('UI:NotificationsTab'));
  252. // Display notifications regarding the object
  253. $iId = $this->GetKey();
  254. $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);
  255. $oBlock->Display($oPage, 'notifications', array());
  256. }
  257. }
  258. }
  259. function GetBareProperties(WebPage $oPage, $bEditMode = false)
  260. {
  261. $sHtml = '';
  262. $oAppContext = new ApplicationContext();
  263. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  264. $aDetails = array();
  265. $sClass = get_class($this);
  266. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  267. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  268. // Compute the list of properties to display, first the attributes in the 'details' list, then
  269. // all the remaining attributes that are not external fields
  270. $sHtml = '';
  271. $aDetails = array();
  272. foreach($aDetailsStruct as $sTab => $aCols )
  273. {
  274. $aDetails[$sTab] = array();
  275. ksort($aCols);
  276. $oPage->SetCurrentTab(Dict::S($sTab));
  277. $oPage->add('<table style="vertical-align:top"><tr>');
  278. foreach($aCols as $sColIndex => $aFieldsets)
  279. {
  280. $oPage->add('<td style="vertical-align:top">');
  281. //$aDetails[$sTab][$sColIndex] = array();
  282. foreach($aFieldsets as $sFieldsetName => $aFields)
  283. {
  284. $aDetails[$sTab][$sColIndex] = array();
  285. if (!empty($sFieldsetName))
  286. {
  287. $oPage->add('<fieldset>');
  288. $oPage->add('<legend>'.Dict::S($sFieldsetName).'</legend>');
  289. }
  290. foreach($aFields as $sAttCode)
  291. {
  292. $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode);
  293. if ($val != null)
  294. {
  295. // The field is visible, add it to the current column
  296. $aDetails[$sTab][$sColIndex][] = $val;
  297. }
  298. }
  299. $oPage->Details($aDetails[$sTab][$sColIndex]);
  300. if (!empty($sFieldsetName))
  301. {
  302. $oPage->add('</fieldset>');
  303. }
  304. }
  305. $oPage->add('</td>');
  306. }
  307. $oPage->add('</tr></table>');
  308. }
  309. return $sHtml;
  310. }
  311. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  312. {
  313. $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate(get_class($this)));
  314. if (!empty($sTemplate))
  315. {
  316. $oTemplate = new DisplayTemplate($sTemplate);
  317. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  318. // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved
  319. // but the preferred method is to use '$id$'
  320. $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)));
  321. }
  322. else
  323. {
  324. // Object's details
  325. // template not found display the object using the *old style*
  326. $this->DisplayBareHeader($oPage, $bEditMode);
  327. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  328. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  329. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  330. $this->DisplayBareProperties($oPage, $bEditMode);
  331. $this->DisplayBareRelations($oPage, $bEditMode);
  332. $oPage->SetCurrentTab(Dict::S('UI:HistoryTab'));
  333. $this->DisplayBareHistory($oPage, $bEditMode);
  334. }
  335. }
  336. function DisplayPreview(WebPage $oPage)
  337. {
  338. $aDetails = array();
  339. $sClass = get_class($this);
  340. $aList = MetaModel::GetZListItems($sClass, 'preview');
  341. foreach($aList as $sAttCode)
  342. {
  343. $aDetails[] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' =>$this->GetAsHTML($sAttCode));
  344. }
  345. $oPage->details($aDetails);
  346. }
  347. public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  348. {
  349. $oPage->add(self::GetDisplaySet($oPage, $oSet, $aExtraParams));
  350. }
  351. /**
  352. * Get the HTML fragment corresponding to the display of a table representing a set of objects
  353. * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output
  354. * @param CMDBObjectSet The set of objects to display
  355. * @param Hash $aExtraParams Some extra configuration parameters to tweak the behavior of the display
  356. * @return String The HTML fragment representing the table of objects
  357. */
  358. public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  359. {
  360. if (empty($aExtraParams['currentId']))
  361. {
  362. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  363. }
  364. else
  365. {
  366. $iListId = $aExtraParams['currentId'];
  367. }
  368. // Initialize and check the parameters
  369. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  370. $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
  371. $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0;
  372. $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : '';
  373. if (!empty($sLinkageAttribute))
  374. {
  375. if($iLinkedObjectId == 0)
  376. {
  377. // if 'links' mode is requested the id of the object to link to must be specified
  378. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  379. }
  380. if($sTargetAttr == '')
  381. {
  382. // if 'links' mode is requested the d of the object to link to must be specified
  383. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  384. }
  385. }
  386. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  387. $bTruncated = isset($aExtraParams['truncated']) ? $aExtraParams['truncated'] == true : true;
  388. $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
  389. $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
  390. $aExtraFields = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  391. $sHtml = '';
  392. $oAppContext = new ApplicationContext();
  393. $sClassName = $oSet->GetFilter()->GetClass();
  394. $aAttribs = array();
  395. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  396. $aList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  397. $aList = array_merge($aList, $aExtraFields);
  398. // Filter the list to removed linked set since we are not able to display them here
  399. foreach($aList as $index => $sAttCode)
  400. {
  401. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  402. if ($oAttDef instanceof AttributeLinkedSet)
  403. {
  404. // Removed from the display list
  405. unset($aList[$index]);
  406. }
  407. }
  408. if (!empty($sLinkageAttribute))
  409. {
  410. // The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
  411. // and other objects...
  412. // The display will then group all the attributes related to the link itself:
  413. // | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
  414. $aDisplayList = array();
  415. $aAttDefs = MetaModel::ListAttributeDefs($sClassName);
  416. assert(isset($aAttDefs[$sLinkageAttribute]));
  417. $oAttDef = $aAttDefs[$sLinkageAttribute];
  418. assert($oAttDef->IsExternalKey());
  419. // First display all the attributes specific to the link record
  420. foreach($aList as $sLinkAttCode)
  421. {
  422. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  423. if ( (!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField()) )
  424. {
  425. $aDisplayList[] = $sLinkAttCode;
  426. }
  427. }
  428. // Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
  429. foreach($aList as $sLinkAttCode)
  430. {
  431. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  432. if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
  433. || ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode()!=$sLinkageAttribute)) )
  434. {
  435. $aDisplayList[] = $sLinkAttCode;
  436. }
  437. }
  438. // First display all the attributes specific to the link
  439. // Then display all the attributes linked to the other end of the relationship
  440. $aList = $aDisplayList;
  441. }
  442. if ($bSelectMode)
  443. {
  444. if (!$bSingleSelectMode)
  445. {
  446. $aAttribs['form::select'] = array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList{$iListId}', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+'));
  447. }
  448. else
  449. {
  450. $aAttribs['form::select'] = array('label' => "", 'description' => '');
  451. }
  452. }
  453. if ($bViewLink)
  454. {
  455. $aAttribs['key'] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  456. }
  457. foreach($aList as $sAttCode)
  458. {
  459. $aAttribs[$sAttCode] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => MetaModel::GetDescription($sClassName, $sAttCode));
  460. }
  461. $aValues = array();
  462. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  463. $iMaxObjects = -1;
  464. if ($bDisplayLimit && $bTruncated)
  465. {
  466. if ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit())
  467. {
  468. $iMaxObjects = MetaModel::GetConfig()->GetMinDisplayLimit();
  469. $oSet->SetLimit($iMaxObjects);
  470. }
  471. }
  472. $oSet->Seek(0);
  473. while (($oObj = $oSet->Fetch()) && ($iMaxObjects != 0))
  474. {
  475. $aRow = array();
  476. $sHilightClass = $oObj->GetHilightClass();
  477. if ($sHilightClass != '')
  478. {
  479. $aRow['@class'] = $sHilightClass;
  480. }
  481. if ($bViewLink)
  482. {
  483. $aRow['key'] = $oObj->GetHyperLink();
  484. }
  485. if ($bSelectMode)
  486. {
  487. if ($bSingleSelectMode)
  488. {
  489. $aRow['form::select'] = "<input type=\"radio\" class=\"selectList{$iListId}\" name=\"selectObject\" value=\"".$oObj->GetKey()."\"></input>";
  490. }
  491. else
  492. {
  493. $aRow['form::select'] = "<input type=\"checkBox\" class=\"selectList{$iListId}\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\"></input>";
  494. }
  495. }
  496. foreach($aList as $sAttCode)
  497. {
  498. $aRow[$sAttCode] = $oObj->GetAsHTML($sAttCode);
  499. }
  500. $aValues[] = $aRow;
  501. $iMaxObjects--;
  502. }
  503. $sHtml .= '<table class="listContainer">';
  504. $sColspan = '';
  505. // if (isset($aExtraParams['block_id']))
  506. // {
  507. // $divId = $aExtraParams['block_id'];
  508. // }
  509. // else
  510. // {
  511. // $divId = 'missingblockid';
  512. // }
  513. $sFilter = $oSet->GetFilter()->serialize();
  514. $iMinDisplayLimit = MetaModel::GetConfig()->GetMinDisplayLimit();
  515. $sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oSet->Count());
  516. $sLinkLabel = Dict::S('UI:DisplayAll');
  517. foreach($oSet->GetFilter()->GetInternalParams() as $sName => $sValue)
  518. {
  519. $aExtraParams['query_params'][$sName] = $sValue;
  520. }
  521. if ($bDisplayLimit && $bTruncated && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  522. {
  523. // list truncated
  524. $aExtraParams['display_limit'] = true;
  525. $sHtml .= '<tr class="containerHeader"><td><span id="lbl_'.$iListId.'">'.$sCollapsedLabel.'</span>&nbsp;&nbsp;<a class="truncated" id="trc_'.$iListId.'">'.$sLinkLabel.'</a></td><td>';
  526. $oPage->add_ready_script(
  527. <<<EOF
  528. $('#$iListId table.listResults').addClass('truncated');
  529. $('#$iListId table.listResults tr:last td').addClass('truncated');
  530. EOF
  531. );
  532. }
  533. else if ($bDisplayLimit && !$bTruncated && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  534. {
  535. // Collapsible list
  536. $aExtraParams['display_limit'] = true;
  537. $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>';
  538. }
  539. $aExtraParams['truncated'] = false; // To expand the full list when clicked
  540. $sExtraParamsExpand = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  541. $oPage->add_ready_script(
  542. <<<EOF
  543. // Handle truncated lists
  544. $('#trc_$iListId').click(function()
  545. {
  546. var state = {};
  547. var currentState = $.bbq.getState( this.id, true ) || 'close';
  548. // Toggle the state!
  549. if (currentState == 'close')
  550. {
  551. state[ this.id ] = 'open';
  552. }
  553. else
  554. {
  555. state[ this.id ] = 'close';
  556. }
  557. $.bbq.pushState( state );
  558. $(this).trigger(state[this.id]);
  559. });
  560. $('#trc_$iListId').unbind('open');
  561. $('#trc_$iListId').bind('open', function()
  562. {
  563. ReloadTruncatedList('$iListId', '$sFilter', '$sExtraParamsExpand');
  564. });
  565. $('#trc_$iListId').unbind('close');
  566. $('#trc_$iListId').bind('close', function()
  567. {
  568. TruncateList('$iListId', $iMinDisplayLimit, '$sCollapsedLabel', '$sLinkLabel');
  569. });
  570. EOF
  571. );
  572. if ($bDisplayMenu)
  573. {
  574. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  575. $sColspan = 'colspan="2"';
  576. $aMenuExtraParams = $aExtraParams;
  577. if (!empty($sLinkageAttribute))
  578. {
  579. //$aMenuExtraParams['linkage'] = $sLinkageAttribute;
  580. $aMenuExtraParams = $aExtraParams;
  581. }
  582. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams, $iListId);
  583. $sHtml .= '</td></tr>';
  584. }
  585. $sHtml .= "<tr><td $sColspan>";
  586. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  587. $sHtml .= '</td></tr>';
  588. $sHtml .= '</table>';
  589. return $sHtml;
  590. }
  591. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  592. {
  593. static $iListId = 0;
  594. $iListId++;
  595. $aList = array();
  596. // Initialize and check the parameters
  597. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  598. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  599. // Check if there is a list of aliases to limit the display to...
  600. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  601. $sHtml = '';
  602. $oAppContext = new ApplicationContext();
  603. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  604. $aAuthorizedClasses = array();
  605. foreach($aClasses as $sAlias => $sClassName)
  606. {
  607. if ( (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) &&
  608. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  609. {
  610. $aAuthorizedClasses[$sAlias] = $sClassName;
  611. }
  612. }
  613. $aAttribs = array();
  614. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  615. {
  616. $aList[$sClassName] = MetaModel::GetZListItems($sClassName, 'list');
  617. if ($bViewLink)
  618. {
  619. $aAttribs['key_'.$sAlias] = array('label' => MetaModel::GetName($sClassName), 'description' => '');
  620. }
  621. foreach($aList[$sClassName] as $sAttCode)
  622. {
  623. $aAttribs[$sAttCode.'_'.$sAlias] = array('label' => MetaModel::GetLabel($sClassName, $sAttCode), 'description' => MetaModel::GetDescription($sClassName, $sAttCode));
  624. }
  625. }
  626. $aValues = array();
  627. $oSet->Seek(0);
  628. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  629. $iMaxObjects = -1;
  630. if ($bDisplayLimit)
  631. {
  632. if ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit())
  633. {
  634. $iMaxObjects = MetaModel::GetConfig()->GetMinDisplayLimit();
  635. }
  636. }
  637. while (($aObjects = $oSet->FetchAssoc()) && ($iMaxObjects != 0))
  638. {
  639. $aRow = array();
  640. foreach($aAuthorizedClasses as $sAlias => $sClassName) // TO DO: check if the user has enough rights to view the classes of the list...
  641. {
  642. if ($bViewLink)
  643. {
  644. $aRow['key_'.$sAlias] = $aObjects[$sAlias]->GetHyperLink();
  645. }
  646. foreach($aList[$sClassName] as $sAttCode)
  647. {
  648. $aRow[$sAttCode.'_'.$sAlias] = $aObjects[$sAlias]->GetAsHTML($sAttCode);
  649. }
  650. }
  651. $aValues[] = $aRow;
  652. $iMaxObjects--;
  653. }
  654. $sHtml .= '<table class="listContainer">';
  655. $sColspan = '';
  656. if ($bDisplayMenu)
  657. {
  658. $oMenuBlock = new MenuBlock($oSet->GetFilter());
  659. $sColspan = 'colspan="2"';
  660. $aMenuExtraParams = $aExtraParams;
  661. if (!empty($sLinkageAttribute))
  662. {
  663. $aMenuExtraParams = $aExtraParams;
  664. }
  665. if ($bDisplayLimit && ($oSet->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit()))
  666. {
  667. // list truncated
  668. $divId = $aExtraParams['block_id'];
  669. $sFilter = $oSet->GetFilter()->serialize();
  670. $aExtraParams['display_limit'] = false; // To expand the full list
  671. $sExtraParams = addslashes(str_replace('"', "'", json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
  672. $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>';
  673. $oPage->add_ready_script("$('#{$divId} table.listResults').addClass('truncated');");
  674. $oPage->add_ready_script("$('#{$divId} table.listResults tr:last td').addClass('truncated');");
  675. }
  676. else
  677. {
  678. // Full list
  679. $sHtml .= '<tr class="containerHeader"><td>&nbsp;'.Dict::Format('UI:CountOfResults', $oSet->Count()).'</td><td>';
  680. }
  681. $sHtml .= $oMenuBlock->GetRenderContent($oPage, $aMenuExtraParams);
  682. $sHtml .= '</td></tr>';
  683. }
  684. $sHtml .= "<tr><td $sColspan>";
  685. $sHtml .= $oPage->GetTable($aAttribs, $aValues);
  686. $sHtml .= '</td></tr>';
  687. $sHtml .= '</table>';
  688. return $sHtml;
  689. }
  690. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  691. {
  692. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  693. }
  694. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  695. {
  696. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  697. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  698. $aList = array();
  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. {
  706. $aAuthorizedClasses[$sAlias] = $sClassName;
  707. }
  708. }
  709. $aAttribs = array();
  710. $aHeader = array();
  711. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  712. {
  713. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  714. {
  715. if ((($oAttDef->IsExternalField()) || ($oAttDef->IsWritable())) && $oAttDef->IsScalar())
  716. {
  717. $aList[$sClassName][$sAttCode] = $oAttDef;
  718. }
  719. }
  720. $aHeader[] = 'id';
  721. foreach($aList[$sClassName] as $sAttCode => $oAttDef)
  722. {
  723. $sStar = '';
  724. if ($oAttDef->IsExternalField())
  725. {
  726. $sExtKeyLabel = MetaModel::GetLabel($sClassName, $oAttDef->GetKeyAttCode());
  727. $oExtKeyAttDef = MetaModel::GetAttributeDef($sClassName, $oAttDef->GetKeyAttCode());
  728. if (!$oExtKeyAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  729. {
  730. $sStar = '*';
  731. }
  732. $sRemoteAttLabel = MetaModel::GetLabel($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  733. $oTargetAttDef = MetaModel::GetAttributeDef($oAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  734. $sSuffix = '';
  735. if ($oTargetAttDef->IsExternalKey())
  736. {
  737. $sSuffix = '->id';
  738. }
  739. $aHeader[] = $sExtKeyLabel.'->'.$sRemoteAttLabel.$sSuffix.$sStar;
  740. }
  741. else
  742. {
  743. if (!$oAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  744. {
  745. $sStar = '*';
  746. }
  747. $aHeader[] = MetaModel::GetLabel($sClassName, $sAttCode).$sStar;
  748. }
  749. }
  750. }
  751. $sHtml = implode($sSeparator, $aHeader)."\n";
  752. $oSet->Seek(0);
  753. while ($aObjects = $oSet->FetchAssoc())
  754. {
  755. $aRow = array();
  756. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  757. {
  758. $oObj = $aObjects[$sAlias];
  759. $aRow[] = $oObj->GetKey();
  760. foreach($aList[$sClassName] as $sAttCode => $oAttDef)
  761. {
  762. $aRow[] = $oObj->GetAsCSV($sAttCode, $sSeparator, '\\');
  763. }
  764. }
  765. $sHtml .= implode($sSeparator, $aRow)."\n";
  766. }
  767. return $sHtml;
  768. }
  769. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  770. {
  771. $oAppContext = new ApplicationContext();
  772. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  773. $aAuthorizedClasses = array();
  774. foreach($aClasses as $sAlias => $sClassName)
  775. {
  776. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  777. {
  778. $aAuthorizedClasses[$sAlias] = $sClassName;
  779. }
  780. }
  781. $aAttribs = array();
  782. $aList = array();
  783. $aList[$sClassName] = MetaModel::GetZListItems($sClassName, 'details');
  784. $oPage->add("<Set>\n");
  785. $oSet->Seek(0);
  786. while ($aObjects = $oSet->FetchAssoc())
  787. {
  788. if (count($aAuthorizedClasses) > 1)
  789. {
  790. $oPage->add("<Row>\n");
  791. }
  792. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  793. {
  794. $oObj = $aObjects[$sAlias];
  795. $sClassName = get_class($oObj);
  796. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  797. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  798. {
  799. if (($oAttDef->IsWritable()) && ($oAttDef->IsScalar()))
  800. {
  801. $sValue = $oObj->GetAsXML($sAttCode);
  802. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  803. }
  804. }
  805. $oPage->add("</$sClassName>\n");
  806. }
  807. if (count($aAuthorizedClasses) > 1)
  808. {
  809. $oPage->add("</Row>\n");
  810. }
  811. }
  812. $oPage->add("</Set>\n");
  813. }
  814. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  815. {
  816. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  817. }
  818. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  819. {
  820. static $iSearchFormId = 0;
  821. $oAppContext = new ApplicationContext();
  822. $sHtml = '';
  823. $numCols=4;
  824. $sClassName = $oSet->GetFilter()->GetClass();
  825. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  826. // (especially when used to add a link)
  827. /*
  828. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  829. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  830. <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>
  831. </ul></div>\n";
  832. */
  833. // Simple search form
  834. if (isset($aExtraParams['currentId']))
  835. {
  836. $sSearchFormId = $aExtraParams['currentId'];
  837. }
  838. else
  839. {
  840. $iSearchFormId = $oPage->GetUniqueId();
  841. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  842. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  843. }
  844. // Check if the current class has some sub-classes
  845. if (isset($aExtraParams['baseClass']))
  846. {
  847. $sRootClass = $aExtraParams['baseClass'];
  848. }
  849. else
  850. {
  851. $sRootClass = $sClassName;
  852. }
  853. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  854. if (count($aSubClasses) > 0)
  855. {
  856. $aOptions = array();
  857. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  858. foreach($aSubClasses as $sSubclassName)
  859. {
  860. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  861. }
  862. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  863. ksort($aOptions);
  864. $sContext = $oAppContext->GetForLink();
  865. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  866. }
  867. else
  868. {
  869. $sClassesCombo = MetaModel::GetName($sClassName);
  870. }
  871. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  872. $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)
  873. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  874. $index = 0;
  875. $sHtml .= "<p>\n";
  876. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  877. $aMapCriteria = array();
  878. foreach($aFilterCriteria as $aCriteria)
  879. {
  880. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  881. }
  882. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  883. foreach($aList as $sFilterCode)
  884. {
  885. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  886. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  887. $sFilterValue = '';
  888. $sFilterValue = utils::ReadParam($sFilterCode, '');
  889. $sFilterOpCode = null; // Use the default 'loose' OpCode
  890. if (empty($sFilterValue))
  891. {
  892. if (isset($aMapCriteria[$sFilterCode]))
  893. {
  894. if (count($aMapCriteria[$sFilterCode]) > 1)
  895. {
  896. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  897. }
  898. else
  899. {
  900. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  901. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  902. }
  903. if ($sFilterCode != 'company')
  904. {
  905. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  906. }
  907. }
  908. }
  909. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  910. if ($aAllowedValues != null)
  911. {
  912. //Enum field or external key, display a combo
  913. $sValue = "<select name=\"$sFilterCode\">\n";
  914. $sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  915. foreach($aAllowedValues as $key => $value)
  916. {
  917. if ($sFilterValue == $key)
  918. {
  919. $sSelected = ' selected';
  920. }
  921. else
  922. {
  923. $sSelected = '';
  924. }
  925. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  926. }
  927. $sValue .= "</select>\n";
  928. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  929. unset($aExtraParams[$sFilterCode]);
  930. }
  931. else
  932. {
  933. // Any value is possible, display an input box
  934. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"$sFilterValue\"/>\n";
  935. unset($aExtraParams[$sFilterCode]);
  936. }
  937. $index++;
  938. $sHtml .= '</span> ';
  939. }
  940. $sHtml .= "</p>\n";
  941. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  942. foreach($aExtraParams as $sName => $sValue)
  943. {
  944. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  945. }
  946. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  947. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  948. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  949. $sHtml .= $oAppContext->GetForForm();
  950. $sHtml .= "</form>\n";
  951. if (!isset($aExtraParams['currentId']))
  952. {
  953. $sHtml .= "</div><!-- Simple search form -->\n";
  954. }
  955. /*
  956. // OQL query builder
  957. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  958. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  959. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  960. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  961. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  962. $sSelectedClass = utils::ReadParam('oql_class', $sClassName);
  963. $sOQLClause = utils::ReadParam('oql_clause', '');
  964. asort($aClasses);
  965. foreach($aClasses as $sChildClass)
  966. {
  967. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  968. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  969. }
  970. $sHtml .= "</select>&nbsp;</td><td>\n";
  971. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  972. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  973. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  974. foreach($aExtraParams as $sName => $sValue)
  975. {
  976. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  977. }
  978. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  979. $sHtml .= $oAppContext->GetForForm();
  980. $sHtml .= "</table></form>\n";
  981. $sHtml .= "</div><!-- OQL query form -->\n";
  982. */
  983. return $sHtml;
  984. }
  985. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  986. {
  987. static $iInputId = 0;
  988. $sFieldPrefix = '';
  989. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  990. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  991. if (isset($aArgs[$sAttCode]) && empty($value))
  992. {
  993. // default value passed by the context (either the app context of the operation)
  994. $value = $aArgs[$sAttCode];
  995. }
  996. if (!empty($iId))
  997. {
  998. $iInputId = $iId;
  999. }
  1000. else
  1001. {
  1002. $iInputId = $oPage->GetUniqueId();
  1003. }
  1004. if (!$oAttDef->IsExternalField())
  1005. {
  1006. $bMandatory = 'false';
  1007. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1008. {
  1009. $bMandatory = 'true';
  1010. }
  1011. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1012. $sHelpText = $oAttDef->GetHelpOnEdition();
  1013. $aEventsList = array();
  1014. switch($oAttDef->GetEditClass())
  1015. {
  1016. case 'Date':
  1017. case 'DateTime':
  1018. $aEventsList[] ='validate';
  1019. $aEventsList[] ='keyup';
  1020. $aEventsList[] ='change';
  1021. $sHTMLValue = "<input title=\"$sHelpText\" class=\"date-pick\" type=\"text\" size=\"20\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1022. break;
  1023. case 'Password':
  1024. $aEventsList[] ='validate';
  1025. $aEventsList[] ='keyup';
  1026. $aEventsList[] ='change';
  1027. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1028. break;
  1029. case 'Text':
  1030. $aEventsList[] ='validate';
  1031. $aEventsList[] ='keyup';
  1032. $aEventsList[] ='change';
  1033. $sHTMLValue = "<table><tr><td><textarea class=\"resizable\" title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" rows=\"8\" cols=\"40\" id=\"$iId\">$value</textarea></td><td>{$sValidationField}</td></tr></table>";
  1034. break;
  1035. case 'HTML':
  1036. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sHelpText, $sValidationField, $value, $bMandatory);
  1037. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1038. break;
  1039. case 'LinkedSet':
  1040. $aEventsList[] ='validate';
  1041. $aEventsList[] ='change';
  1042. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed());
  1043. $sHTMLValue = $oWidget->Display($oPage, $value);
  1044. break;
  1045. case 'Document':
  1046. $aEventsList[] ='validate';
  1047. $aEventsList[] ='change';
  1048. $oDocument = $value; // Value is an ormDocument object
  1049. $sFileName = '';
  1050. if (is_object($oDocument))
  1051. {
  1052. $sFileName = $oDocument->GetFileName();
  1053. }
  1054. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1055. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1056. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" type=\"hidden\" id=\"$iId\" \" value=\"$sFileName\"/>\n";
  1057. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1058. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"file_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1059. break;
  1060. case 'List':
  1061. // Not editable for now...
  1062. $sHTMLValue = '';
  1063. break;
  1064. case 'One Way Password':
  1065. $aEventsList[] ='validate';
  1066. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1067. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1068. // Event list & validation is handled directly by the widget
  1069. break;
  1070. case 'ExtKey':
  1071. $aEventsList[] ='validate';
  1072. $aEventsList[] ='change';
  1073. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1074. $iFieldSize = $oAttDef->GetMaxSize();
  1075. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1076. $oWidget = new UIExtKeyWidget($sAttCode, $sClass, $oAttDef->GetLabel(), $aAllowedValues, $value, $iId, $bMandatory, $sNameSuffix, $sFieldPrefix, $sFormPrefix);
  1077. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1078. break;
  1079. case 'String':
  1080. default:
  1081. $aEventsList[] ='validate';
  1082. // #@# todo - add context information (depending on dimensions)
  1083. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1084. $iFieldSize = $oAttDef->GetMaxSize();
  1085. if ($aAllowedValues !== null)
  1086. {
  1087. // Discrete list of values, use a SELECT
  1088. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1089. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1090. foreach($aAllowedValues as $key => $display_value)
  1091. {
  1092. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1093. {
  1094. // When there is only once choice, select it by default
  1095. $sSelected = ' selected';
  1096. }
  1097. else
  1098. {
  1099. $sSelected = ($value == $key) ? ' selected' : '';
  1100. }
  1101. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1102. }
  1103. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1104. $aEventsList[] ='change';
  1105. }
  1106. else
  1107. {
  1108. $sHTMLValue = "<input title=\"$sHelpText\" type=\"text\" size=\"30\" maxlength=\"$iFieldSize\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"$value\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1109. $aEventsList[] ='keyup';
  1110. $aEventsList[] ='change';
  1111. }
  1112. break;
  1113. }
  1114. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1115. if (!empty($aEventsList))
  1116. {
  1117. $sNullValue = $oAttDef->GetNullValue();
  1118. if (!is_numeric($sNullValue))
  1119. {
  1120. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1121. }
  1122. $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
  1123. }
  1124. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1125. if (count($aDependencies) > 0)
  1126. {
  1127. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1128. }
  1129. }
  1130. return "<div>{$sHTMLValue}</div>";
  1131. }
  1132. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1133. {
  1134. static $iGlobalFormId = 1;
  1135. $iGlobalFormId++;
  1136. $sPrefix = '';
  1137. if (isset($aExtraParams['formPrefix']))
  1138. {
  1139. $sPrefix = $aExtraParams['formPrefix'];
  1140. }
  1141. $this->m_iFormId = $sPrefix.$iGlobalFormId;
  1142. $sClass = get_class($this);
  1143. $oAppContext = new ApplicationContext();
  1144. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1145. $iKey = $this->GetKey();
  1146. $aDetails = array();
  1147. $aFieldsMap = array();
  1148. if (!isset($aExtraParams['action']))
  1149. {
  1150. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1151. }
  1152. else
  1153. {
  1154. $sFormAction = $aExtraParams['action'];
  1155. }
  1156. $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");
  1157. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1158. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1159. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1160. // $aDetailsList = $this->FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1161. //$aFullList = MetaModel::ListAttributeDefs($sClass);
  1162. $aList = array();
  1163. // Compute the list of properties to display, first the attributes in the 'details' list, then
  1164. // all the remaining attributes that are not external fields
  1165. // foreach($aDetailsList as $sAttCode)
  1166. // {
  1167. // $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1168. // if (!$oAttDef->IsExternalField())
  1169. // {
  1170. // $aList[] = $sAttCode;
  1171. // }
  1172. // }
  1173. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  1174. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  1175. $sHtml = '';
  1176. $aDetails = array();
  1177. foreach($aDetailsStruct as $sTab => $aCols )
  1178. {
  1179. $aDetails[$sTab] = array();
  1180. ksort($aCols);
  1181. $oPage->SetCurrentTab(Dict::S($sTab));
  1182. $oPage->add('<table style="vertical-align:top"><tr>');
  1183. foreach($aCols as $sColIndex => $aFieldsets)
  1184. {
  1185. $oPage->add('<td style="vertical-align:top">');
  1186. //$aDetails[$sTab][$sColIndex] = array();
  1187. foreach($aFieldsets as $sFieldsetName => $aFields)
  1188. {
  1189. $aDetails[$sTab][$sColIndex] = array();
  1190. if (!empty($sFieldsetName))
  1191. {
  1192. $oPage->add('<fieldset>');
  1193. $oPage->add('<legend>'.Dict::S($sFieldsetName).'</legend>');
  1194. }
  1195. foreach($aFields as $sAttCode)
  1196. {
  1197. $aVal = null;
  1198. $iFlags = $this->GetAttributeFlags($sAttCode);
  1199. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1200. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0))
  1201. {
  1202. if ($oAttDef->IsWritable())
  1203. {
  1204. if ($sStateAttCode == $sAttCode)
  1205. {
  1206. // State attribute is always read-only from the UI
  1207. $sHTMLValue = $this->GetStateLabel();
  1208. $aVal = array('label' => $oAttDef->GetLabel(), 'value' => $sHTMLValue);
  1209. }
  1210. else
  1211. {
  1212. $iFlags = $this->GetAttributeFlags($sAttCode);
  1213. if ($iFlags & OPT_ATT_HIDDEN)
  1214. {
  1215. // Attribute is hidden, do nothing
  1216. }
  1217. else
  1218. {
  1219. if ($iFlags & OPT_ATT_READONLY)
  1220. {
  1221. // Attribute is read-only
  1222. $sHTMLValue = $this->GetAsHTML($sAttCode);
  1223. }
  1224. else
  1225. {
  1226. $sValue = $this->Get($sAttCode);
  1227. $sDisplayValue = $this->GetEditValue($sAttCode);
  1228. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  1229. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  1230. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  1231. $aFieldsMap[$sAttCode] = $sInputId;
  1232. }
  1233. $aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue);
  1234. }
  1235. }
  1236. }
  1237. else
  1238. {
  1239. $aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $this->GetAsHTML($sAttCode));
  1240. }
  1241. }
  1242. if ($aVal != null)
  1243. {
  1244. // The field is visible, add it to the current column
  1245. $aDetails[$sTab][$sColIndex][] = $aVal;
  1246. }
  1247. }
  1248. $oPage->Details($aDetails[$sTab][$sColIndex]);
  1249. if (!empty($sFieldsetName))
  1250. {
  1251. $oPage->add('</fieldset>');
  1252. }
  1253. }
  1254. $oPage->add('</td>');
  1255. }
  1256. $oPage->add('</tr></table>');
  1257. }
  1258. // Now display the relations, one tab per relation
  1259. if (!isset($aExtraParams['noRelations']))
  1260. {
  1261. $this->DisplayBareRelations($oPage, true); // Edit mode
  1262. }
  1263. $oPage->SetCurrentTab('');
  1264. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1265. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  1266. foreach($aExtraParams as $sName => $value)
  1267. {
  1268. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1269. }
  1270. $oPage->add($oAppContext->GetForForm());
  1271. if ($iKey > 0)
  1272. {
  1273. // The object already exists in the database, it's modification
  1274. $oPage->add("<input type=\"hidden\" name=\"id\" value=\"$iKey\">\n");
  1275. $oPage->add("<input type=\"hidden\" name=\"operation\" value=\"apply_modify\">\n");
  1276. // $oPage->add("<button type=\"button\" id=\"btn_cancel_{$sPrefix}\" class=\"action\" onClick=\"BackToDetails('$sClass', $iKey)\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1277. $oPage->add("<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1278. $oPage->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:Apply')."</span></button>\n");
  1279. }
  1280. else
  1281. {
  1282. // The object does not exist in the database it's a creation
  1283. $oPage->add("<input type=\"hidden\" name=\"operation\" value=\"apply_new\">\n");
  1284. // $oPage->add("<button type=\"button\" id=\"btn_cancel_{$sPrefix}\" class=\"action\" onClick=\"BackToDetails('$sClass', $iKey)\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1285. $oPage->add("<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  1286. $oPage->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:Create')."</span></button>\n");
  1287. }
  1288. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1289. $sDefaultUrl = '../pages/UI.php?operation=cancel';
  1290. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1291. $oPage->add("</form>\n");
  1292. $iFieldsCount = count($aFieldsMap);
  1293. $sJsonFieldsMap = json_encode($aFieldsMap);
  1294. $oPage->add_script(
  1295. <<<EOF
  1296. // Create the object once at the beginning of the page...
  1297. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix');
  1298. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1299. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1300. EOF
  1301. );
  1302. $oPage->add_ready_script(
  1303. <<<EOF
  1304. // Starts the validation when the page is ready
  1305. CheckFields('form_{$this->m_iFormId}', false);
  1306. EOF
  1307. );
  1308. }
  1309. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1310. {
  1311. $oAppContext = new ApplicationContext();
  1312. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1313. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1314. $aStates = MetaModel::EnumStates($sClass);
  1315. if ($oObjectToClone == null)
  1316. {
  1317. $oObj = MetaModel::NewObject($sClass);
  1318. if (!empty($sStateAttCode))
  1319. {
  1320. $sTargetState = MetaModel::GetDefaultState($sClass);
  1321. $oObj->Set($sStateAttCode, $sTargetState);
  1322. }
  1323. }
  1324. else
  1325. {
  1326. $oObj = clone $oObjectToClone;
  1327. }
  1328. // Pre-fill the object with default values, when there is only on possible choice
  1329. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  1330. $aArgs['this'] = $oObj;
  1331. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1332. // Order the fields based on their dependencies
  1333. $aDeps = array();
  1334. foreach($aDetailsList as $sAttCode)
  1335. {
  1336. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1337. }
  1338. $aList = self::OrderDependentFields($aDeps);
  1339. // Now fill-in the fields with default/supplied values
  1340. foreach($aList as $sAttCode)
  1341. {
  1342. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1343. if (isset($aArgs['default'][$sAttCode]))
  1344. {
  1345. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  1346. }
  1347. elseif (count($aAllowedValues) == 1)
  1348. {
  1349. // If the field is mandatory, set it to the only possible value
  1350. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1351. $iFlags = $oObj->GetAttributeFlags($sAttCode);
  1352. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1353. {
  1354. $aValues = array_keys($aAllowedValues);
  1355. $oObj->Set($sAttCode, $aValues[0]);
  1356. }
  1357. }
  1358. }
  1359. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  1360. }
  1361. protected static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  1362. {
  1363. //echo "<pre>ZList: ";
  1364. //print_r($aList);
  1365. //echo "</pre>\n";
  1366. foreach($aList as $sKey => $value)
  1367. {
  1368. if (is_array($value))
  1369. {
  1370. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  1371. {
  1372. $sCode = $aMatches[1];
  1373. $sName = $aMatches[2];
  1374. switch($sCode)
  1375. {
  1376. case 'tab':
  1377. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  1378. if(!isset($aDetails[$sName]))
  1379. {
  1380. $aDetails[$sName] = array('col1' => array('' => array()));
  1381. }
  1382. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  1383. break;
  1384. case 'fieldset':
  1385. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  1386. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  1387. {
  1388. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  1389. }
  1390. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  1391. break;
  1392. default:
  1393. case 'col':
  1394. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  1395. if(!isset($aDetails[$sCurrentTab][$sName]))
  1396. {
  1397. $aDetails[$sCurrentTab][$sName] = array('' => array());
  1398. }
  1399. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  1400. break;
  1401. }
  1402. }
  1403. }
  1404. else
  1405. {
  1406. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  1407. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  1408. }
  1409. }
  1410. return $aDetails;
  1411. }
  1412. protected static function FlattenZList($aList)
  1413. {
  1414. $aResult = array();
  1415. foreach($aList as $value)
  1416. {
  1417. if (!is_array($value))
  1418. {
  1419. $aResult[] = $value;
  1420. }
  1421. else
  1422. {
  1423. $aResult = array_merge($aResult,self::FlattenZList($value));
  1424. }
  1425. }
  1426. return $aResult;
  1427. }
  1428. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  1429. {
  1430. $retVal = null;
  1431. $iFlags = $this->GetAttributeFlags($sAttCode);
  1432. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1433. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  1434. {
  1435. // The field is visible in the current state of the object
  1436. if ($sStateAttCode == $sAttCode)
  1437. {
  1438. // Special display for the 'state' attribute itself
  1439. $sDisplayValue = $this->GetStateLabel();
  1440. }
  1441. else if ($oAttDef->GetEditClass() == 'Document')
  1442. {
  1443. $oDocument = $this->Get($sAttCode);
  1444. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1445. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1446. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  1447. }
  1448. else
  1449. {
  1450. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1451. }
  1452. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1453. }
  1454. return $retVal;
  1455. }
  1456. /**
  1457. * Displays a blob document *inline* (if possible, depending on the type of the document)
  1458. * @return string
  1459. */
  1460. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  1461. {
  1462. $oDoc = $this->Get($sAttCode);
  1463. $sClass = get_class($this);
  1464. $Id = $this->GetKey();
  1465. switch ($oDoc->GetMainMimeType())
  1466. {
  1467. case 'text':
  1468. case 'html':
  1469. $data = $oDoc->GetData();
  1470. switch($oDoc->GetMimeType())
  1471. {
  1472. case 'text/html':
  1473. case 'text/xml':
  1474. $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");
  1475. break;
  1476. default:
  1477. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true))."</pre>\n");
  1478. }
  1479. break;
  1480. case 'application':
  1481. switch($oDoc->GetMimeType())
  1482. {
  1483. case 'application/pdf':
  1484. $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");
  1485. break;
  1486. default:
  1487. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1488. }
  1489. break;
  1490. case 'image':
  1491. $oPage->add("<img src=\"../pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  1492. break;
  1493. default:
  1494. $oPage->add(Dict::S('UI:Document:NoPreview'));
  1495. }
  1496. }
  1497. /**
  1498. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1499. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1500. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1501. * To Be overridden by derived classes
  1502. * @param void
  1503. * @return String The desired higlight class for the object/row
  1504. */
  1505. public function GetHilightClass()
  1506. {
  1507. // Possible return values are:
  1508. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1509. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1510. }
  1511. /**
  1512. * Re-order the fields based on their inter-dependencies
  1513. * @params hash @aFields field_code => array_of_depencies
  1514. * @return array Ordered array of fields or throws an exception
  1515. */
  1516. public static function OrderDependentFields($aFields)
  1517. {
  1518. $bCircular = false;
  1519. $aResult = array();
  1520. $iCount = 0;
  1521. do
  1522. {
  1523. $bSet = false;
  1524. $iCount++;
  1525. foreach($aFields as $sFieldCode => $aDeps)
  1526. {
  1527. foreach($aDeps as $key => $sDependency)
  1528. {
  1529. if (in_array($sDependency, $aResult))
  1530. {
  1531. // Dependency is resolved, remove it
  1532. unset($aFields[$sFieldCode][$key]);
  1533. }
  1534. }
  1535. if (count($aFields[$sFieldCode]) == 0)
  1536. {
  1537. // No more pending depencies for this field, add it to the list
  1538. $aResult[] = $sFieldCode;
  1539. unset($aFields[$sFieldCode]);
  1540. $bSet = true;
  1541. }
  1542. }
  1543. }
  1544. while($bSet && (count($aFields) > 0));
  1545. if (count($aFields) > 0)
  1546. {
  1547. $sMessage = "Error: Circular dependencies between the fields ! <pre>".print_r($aFields, true)."</pre>";
  1548. throw(new Exception($sMessage));
  1549. }
  1550. return $aResult;
  1551. }
  1552. /**
  1553. * Maps the given context parameter name to the appropriate filter/search code for this class
  1554. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1555. * @return string Filter code, i.e. 'customer_id'
  1556. */
  1557. public static function MapContextParam($sContextParam)
  1558. {
  1559. if ($sContextParam == 'menu')
  1560. {
  1561. return null;
  1562. }
  1563. else
  1564. {
  1565. return $sContextParam;
  1566. }
  1567. }
  1568. /**
  1569. * Updates the object from the POSTed parameters
  1570. */
  1571. function UpdateObject($sFormPrefix = '')
  1572. {
  1573. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1574. {
  1575. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  1576. {
  1577. $aLinks = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", '');
  1578. $sLinkedClass = $oAttDef->GetLinkedClass();
  1579. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  1580. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1581. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  1582. if (is_array($aLinks))
  1583. {
  1584. foreach($aLinks as $id => $aData)
  1585. {
  1586. if (is_numeric($id))
  1587. {
  1588. if ($id < 0)
  1589. {
  1590. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  1591. $oLink = MetaModel::NewObject($sLinkedClass);
  1592. $oLink->Set($sExtKeyToRemote, -$id);
  1593. $oLink->Set($sExtKeyToMe, $this->GetKey());
  1594. }
  1595. else
  1596. {
  1597. // Existing link, potentially to be updated...
  1598. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  1599. }
  1600. // Now populate the attributes
  1601. foreach($aData as $sName => $value)
  1602. {
  1603. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  1604. {
  1605. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  1606. if ($oLinkAttDef->IsWritable())
  1607. {
  1608. $oLink->Set($sName, $value);
  1609. }
  1610. }
  1611. }
  1612. $oLinkedSet->AddObject($oLink);
  1613. }
  1614. }
  1615. }
  1616. $this->Set($sAttCode, $oLinkedSet);
  1617. }
  1618. else if ($oAttDef->IsWritable())
  1619. {
  1620. $iFlags = $this->GetAttributeFlags($sAttCode);
  1621. if ($iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  1622. {
  1623. // Non-visible, or read-only attribute, do nothing
  1624. }
  1625. elseif ($oAttDef->GetEditClass() == 'Document')
  1626. {
  1627. // There should be an uploaded file with the named attr_<attCode>
  1628. $oDocument = utils::ReadPostedDocument("file_{$sFormPrefix}{$sAttCode}");
  1629. if (!$oDocument->IsEmpty())
  1630. {
  1631. // A new file has been uploaded
  1632. $this->Set($sAttCode, $oDocument);
  1633. }
  1634. }
  1635. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  1636. {
  1637. // Check if the password was typed/changed
  1638. $bChanged = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_changed", false);
  1639. if ($bChanged)
  1640. {
  1641. // The password has been changed or set
  1642. $rawValue = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null);
  1643. $this->Set($sAttCode, $rawValue);
  1644. }
  1645. }
  1646. else
  1647. {
  1648. $rawValue = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null);
  1649. if (!is_null($rawValue))
  1650. {
  1651. $aAttributes[$sAttCode] = trim($rawValue);
  1652. $previousValue = $this->Get($sAttCode);
  1653. if ($previousValue !== $aAttributes[$sAttCode])
  1654. {
  1655. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  1656. }
  1657. }
  1658. }
  1659. }
  1660. }
  1661. }
  1662. }
  1663. ?>