cmdbabstract.class.inc.php 61 KB

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