cmdbabstract.class.inc.php 126 KB

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