cmdbabstract.class.inc.php 66 KB

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