cmdbabstract.class.inc.php 72 KB

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