cmdbabstract.class.inc.php 77 KB

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