cmdbabstract.class.inc.php 102 KB

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