cmdbabstract.class.inc.php 60 KB

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