cmdbabstract.class.inc.php 108 KB

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