cmdbabstract.class.inc.php 79 KB

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