cmdbabstract.class.inc.php 61 KB

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