cmdbabstract.class.inc.php 94 KB

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