cmdbabstract.class.inc.php 98 KB

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