cmdbabstract.class.inc.php 65 KB

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