cmdbabstract.class.inc.php 80 KB

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