cmdbabstract.class.inc.php 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499
  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. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  746. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  747. }
  748. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  749. {
  750. if (empty($aExtraParams['currentId']))
  751. {
  752. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  753. }
  754. else
  755. {
  756. $iListId = $aExtraParams['currentId'];
  757. }
  758. $aList = array();
  759. // Initialize and check the parameters
  760. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  761. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  762. // Check if there is a list of aliases to limit the display to...
  763. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  764. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  765. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  766. $aExtraFields = array();
  767. foreach ($aExtraFieldsRaw as $sFieldName)
  768. {
  769. // Ignore attributes not of the main queried class
  770. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  771. {
  772. $sClassAlias = $aMatches[1];
  773. $sAttCode = $aMatches[2];
  774. if (array_key_exists($sClassAlias, $oSet->GetSelectedClasses()))
  775. {
  776. $aExtraFields[$sClassAlias][] = $sAttCode;
  777. }
  778. }
  779. else
  780. {
  781. $aExtraFields['*'] = $sAttCode;
  782. }
  783. }
  784. $sHtml = '';
  785. $oAppContext = new ApplicationContext();
  786. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  787. $aAuthorizedClasses = array();
  788. foreach($aClasses as $sAlias => $sClassName)
  789. {
  790. if ( (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) &&
  791. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  792. {
  793. $aAuthorizedClasses[$sAlias] = $sClassName;
  794. }
  795. }
  796. $aAttribs = array();
  797. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  798. {
  799. if (array_key_exists($sAlias, $aExtraFields))
  800. {
  801. $aList[$sAlias] = $aExtraFields[$sAlias];
  802. }
  803. else
  804. {
  805. $aList[$sAlias] = array();
  806. }
  807. if ($sZListName !== false)
  808. {
  809. $aDefaultList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  810. $aList[$sAlias] = array_merge($aDefaultList, $aList[$sAlias]);
  811. }
  812. // Filter the list to removed linked set since we are not able to display them here
  813. foreach($aList[$sAlias] as $index => $sAttCode)
  814. {
  815. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  816. if ($oAttDef instanceof AttributeLinkedSet)
  817. {
  818. // Removed from the display list
  819. unset($aList[$sAlias][$index]);
  820. }
  821. }
  822. }
  823. // Load only the requested columns
  824. $aAttToLoad = array(); // attributes to load
  825. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  826. {
  827. foreach($aList[$sAlias] as $sAttCode)
  828. {
  829. $aAttToLoad[$sAlias][] = $sAttCode;
  830. }
  831. }
  832. $oSet->OptimizeColumnLoad($aAttToLoad);
  833. $sSelectMode = 'none';
  834. $sClassAlias = $oSet->GetClassAlias();
  835. $oDataTable = new DataTable($iListId, $oSet, $aAuthorizedClasses);
  836. $oSettings = DataTableSettings::GetDataModelSettings($aAuthorizedClasses, $bViewLink, $aList);
  837. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  838. if ($bDisplayLimit)
  839. {
  840. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  841. $oSettings->iDefaultPageSize = $iDefaultPageSize;
  842. }
  843. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  844. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  845. }
  846. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  847. {
  848. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  849. }
  850. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  851. {
  852. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  853. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  854. $aFields = null;
  855. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  856. {
  857. $aFields = explode(',', $aParams['fields']);
  858. }
  859. $bFieldsAdvanced = false;
  860. if (isset($aParams['fields_advanced']))
  861. {
  862. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  863. }
  864. $bLocalize = true;
  865. if (isset($aParams['localize_values']))
  866. {
  867. $bLocalize = (bool) $aParams['localize_values'];
  868. }
  869. $aList = array();
  870. $oAppContext = new ApplicationContext();
  871. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  872. $aAuthorizedClasses = array();
  873. foreach($aClasses as $sAlias => $sClassName)
  874. {
  875. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  876. {
  877. $aAuthorizedClasses[$sAlias] = $sClassName;
  878. }
  879. }
  880. $aAttribs = array();
  881. $aHeader = array();
  882. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  883. {
  884. $aList[$sAlias] = array();
  885. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  886. {
  887. if (is_null($aFields) || (count($aFields) == 0))
  888. {
  889. // Standard list of attributes (no link sets)
  890. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  891. {
  892. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  893. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  894. {
  895. if ($bFieldsAdvanced)
  896. {
  897. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  898. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  899. {
  900. $sRemoteClass = $oAttDef->GetTargetClass();
  901. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  902. {
  903. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  904. }
  905. }
  906. }
  907. }
  908. else
  909. {
  910. // Any other attribute
  911. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  912. }
  913. }
  914. }
  915. else
  916. {
  917. // User defined list of attributes
  918. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  919. {
  920. $aList[$sAlias][$sAttCode] = $oAttDef;
  921. }
  922. }
  923. }
  924. if ($bFieldsAdvanced)
  925. {
  926. $aHeader[] = 'id';
  927. }
  928. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  929. {
  930. $sStar = '';
  931. if (!$oAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  932. {
  933. $sStar = '*';
  934. }
  935. $aHeader[] = ($bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx).$sStar;
  936. }
  937. }
  938. $sHtml = implode($sSeparator, $aHeader)."\n";
  939. $oSet->Seek(0);
  940. while ($aObjects = $oSet->FetchAssoc())
  941. {
  942. $aRow = array();
  943. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  944. {
  945. $oObj = $aObjects[$sAlias];
  946. if ($bFieldsAdvanced)
  947. {
  948. if (is_null($oObj))
  949. {
  950. $aRow[] = '';
  951. }
  952. else
  953. {
  954. $aRow[] = $oObj->GetKey();
  955. }
  956. }
  957. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  958. {
  959. if (is_null($oObj))
  960. {
  961. $aRow[] = '';
  962. }
  963. else
  964. {
  965. $value = $oObj->Get($sAttCodeEx);
  966. $aRow[] = $oAttDef->GetAsCSV($value, $sSeparator, $sTextQualifier, $oObj, $bLocalize);
  967. }
  968. }
  969. }
  970. $sHtml .= implode($sSeparator, $aRow)."\n";
  971. }
  972. return $sHtml;
  973. }
  974. static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  975. {
  976. $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams));
  977. }
  978. /**
  979. * Spreadsheet output: designed for end users doing some reporting
  980. * Then the ids are excluded and replaced by the corresponding friendlyname
  981. */
  982. static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array())
  983. {
  984. $aFields = null;
  985. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  986. {
  987. $aFields = explode(',', $aParams['fields']);
  988. }
  989. $bFieldsAdvanced = false;
  990. if (isset($aParams['fields_advanced']))
  991. {
  992. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  993. }
  994. $bLocalize = true;
  995. if (isset($aParams['localize_values']))
  996. {
  997. $bLocalize = (bool) $aParams['localize_values'];
  998. }
  999. $aList = array();
  1000. $oAppContext = new ApplicationContext();
  1001. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1002. $aAuthorizedClasses = array();
  1003. foreach($aClasses as $sAlias => $sClassName)
  1004. {
  1005. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1006. {
  1007. $aAuthorizedClasses[$sAlias] = $sClassName;
  1008. }
  1009. }
  1010. $aAttribs = array();
  1011. $aHeader = array();
  1012. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1013. {
  1014. $aList[$sAlias] = array();
  1015. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  1016. {
  1017. if (is_null($aFields) || (count($aFields) == 0))
  1018. {
  1019. // Standard list of attributes (no link sets)
  1020. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  1021. {
  1022. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  1023. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  1024. if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  1025. {
  1026. $sRemoteClass = $oAttDef->GetTargetClass();
  1027. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  1028. {
  1029. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  1030. }
  1031. }
  1032. }
  1033. }
  1034. else
  1035. {
  1036. // User defined list of attributes
  1037. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  1038. {
  1039. $aList[$sAlias][$sAttCode] = $oAttDef;
  1040. }
  1041. }
  1042. }
  1043. // Replace external key by the corresponding friendly name (if not already in the list)
  1044. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1045. {
  1046. if ($oAttDef->IsExternalKey())
  1047. {
  1048. unset($aList[$sAlias][$sAttCode]);
  1049. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1050. if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode))
  1051. {
  1052. $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode);
  1053. $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt;
  1054. }
  1055. }
  1056. }
  1057. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1058. {
  1059. $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx;
  1060. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1061. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1062. {
  1063. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  1064. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  1065. }
  1066. else
  1067. {
  1068. $aHeader[] = $sColLabel;
  1069. }
  1070. }
  1071. }
  1072. $sHtml = "<table border=\"1\">\n";
  1073. $sHtml .= "<tr>\n";
  1074. $sHtml .= "<td>".implode("</td><td>", $aHeader)."</td>\n";
  1075. $sHtml .= "</tr>\n";
  1076. $oSet->Seek(0);
  1077. while ($aObjects = $oSet->FetchAssoc())
  1078. {
  1079. $aRow = array();
  1080. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1081. {
  1082. $oObj = $aObjects[$sAlias];
  1083. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1084. {
  1085. if (is_null($oObj))
  1086. {
  1087. $aRow[] = '<td></td>';
  1088. }
  1089. else
  1090. {
  1091. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1092. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1093. {
  1094. $sDate = $oObj->Get($sAttCodeEx);
  1095. if ($sDate === null)
  1096. {
  1097. $aRow[] = '<td></td>';
  1098. $aRow[] = '<td></td>';
  1099. }
  1100. else
  1101. {
  1102. $iDate = AttributeDateTime::GetAsUnixSeconds($sDate);
  1103. $aRow[] = '<td>'.date('Y-m-d', $iDate).'</td>';
  1104. $aRow[] = '<td>'.date('H:i:s', $iDate).'</td>';
  1105. }
  1106. }
  1107. else
  1108. {
  1109. $rawValue = $oObj->Get($sAttCodeEx);
  1110. if ($oAttDef instanceof AttributeFriendlyName)
  1111. {
  1112. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1113. if ($oObj->Get($sKeyAttCode) == 0)
  1114. {
  1115. $rawValue = '';
  1116. }
  1117. }
  1118. if ($bLocalize)
  1119. {
  1120. $outputValue = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8');
  1121. }
  1122. else
  1123. {
  1124. $outputValue = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  1125. }
  1126. $aRow[] = '<td>'.$outputValue.'</td>';
  1127. }
  1128. }
  1129. }
  1130. }
  1131. $sHtml .= implode("\n", $aRow);
  1132. $sHtml .= "</tr>\n";
  1133. }
  1134. $sHtml .= "</table>\n";
  1135. return $sHtml;
  1136. }
  1137. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1138. {
  1139. $bLocalize = true;
  1140. if (isset($aParams['localize_values']))
  1141. {
  1142. $bLocalize = (bool) $aParams['localize_values'];
  1143. }
  1144. $oAppContext = new ApplicationContext();
  1145. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1146. $aAuthorizedClasses = array();
  1147. foreach($aClasses as $sAlias => $sClassName)
  1148. {
  1149. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1150. {
  1151. $aAuthorizedClasses[$sAlias] = $sClassName;
  1152. }
  1153. }
  1154. $aAttribs = array();
  1155. $aList = array();
  1156. $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details');
  1157. $oPage->add("<Set>\n");
  1158. $oSet->Seek(0);
  1159. while ($aObjects = $oSet->FetchAssoc())
  1160. {
  1161. if (count($aAuthorizedClasses) > 1)
  1162. {
  1163. $oPage->add("<Row>\n");
  1164. }
  1165. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1166. {
  1167. $oObj = $aObjects[$sAlias];
  1168. if (is_null($oObj))
  1169. {
  1170. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n");
  1171. }
  1172. else
  1173. {
  1174. $sClassName = get_class($oObj);
  1175. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  1176. }
  1177. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  1178. {
  1179. if (is_null($oObj))
  1180. {
  1181. $oPage->add("<$sAttCode>null</$sAttCode>\n");
  1182. }
  1183. else
  1184. {
  1185. if ($oAttDef->IsWritable())
  1186. {
  1187. if (!$oAttDef->IsLinkSet())
  1188. {
  1189. $sValue = $oObj->GetAsXML($sAttCode, $bLocalize);
  1190. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  1191. }
  1192. }
  1193. }
  1194. }
  1195. $oPage->add("</$sClassName>\n");
  1196. }
  1197. if (count($aAuthorizedClasses) > 1)
  1198. {
  1199. $oPage->add("</Row>\n");
  1200. }
  1201. }
  1202. $oPage->add("</Set>\n");
  1203. }
  1204. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1205. {
  1206. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  1207. }
  1208. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1209. {
  1210. static $iSearchFormId = 0;
  1211. $bMultiSelect = false;
  1212. $oAppContext = new ApplicationContext();
  1213. $sHtml = '';
  1214. $numCols=4;
  1215. $sClassName = $oSet->GetFilter()->GetClass();
  1216. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  1217. // (especially when used to add a link)
  1218. /*
  1219. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  1220. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  1221. <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>
  1222. </ul></div>\n";
  1223. */
  1224. // Simple search form
  1225. if (isset($aExtraParams['currentId']))
  1226. {
  1227. $sSearchFormId = $aExtraParams['currentId'];
  1228. }
  1229. else
  1230. {
  1231. $iSearchFormId = $oPage->GetUniqueId();
  1232. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  1233. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  1234. }
  1235. // Check if the current class has some sub-classes
  1236. if (isset($aExtraParams['baseClass']))
  1237. {
  1238. $sRootClass = $aExtraParams['baseClass'];
  1239. }
  1240. else
  1241. {
  1242. $sRootClass = $sClassName;
  1243. }
  1244. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  1245. if (count($aSubClasses) > 0)
  1246. {
  1247. $aOptions = array();
  1248. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  1249. foreach($aSubClasses as $sSubclassName)
  1250. {
  1251. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  1252. }
  1253. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  1254. ksort($aOptions);
  1255. $sContext = $oAppContext->GetForLink();
  1256. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  1257. }
  1258. else
  1259. {
  1260. $sClassesCombo = MetaModel::GetName($sClassName);
  1261. }
  1262. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  1263. $sAction = (isset($aExtraParams['action'])) ? $aExtraParams['action'] : utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1264. $sHtml .= "<form id=\"fs_{$sSearchFormId}\" action=\"{$sAction}\">\n"; // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  1265. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  1266. $index = 0;
  1267. $sHtml .= "<p>\n";
  1268. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  1269. $aMapCriteria = array();
  1270. foreach($aFilterCriteria as $aCriteria)
  1271. {
  1272. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  1273. }
  1274. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  1275. $aConsts = $oSet->ListConstantFields(); // Some fields are constants based on the query/context
  1276. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  1277. foreach($aList as $sFilterCode)
  1278. {
  1279. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  1280. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  1281. $sFilterValue = isset($aConsts[$sClassAlias][$sFilterCode]) ? $aConsts[$sClassAlias][$sFilterCode] : '';
  1282. $sFilterValue = utils::ReadParam($sFilterCode, $sFilterValue, false, 'raw_data');
  1283. $sFilterOpCode = null; // Use the default 'loose' OpCode
  1284. if (empty($sFilterValue))
  1285. {
  1286. if (isset($aMapCriteria[$sFilterCode]))
  1287. {
  1288. if (count($aMapCriteria[$sFilterCode]) > 1)
  1289. {
  1290. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  1291. }
  1292. else
  1293. {
  1294. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  1295. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  1296. }
  1297. if ($sFilterCode != 'company')
  1298. {
  1299. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  1300. }
  1301. }
  1302. }
  1303. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFilterCode);
  1304. if ($oAttDef->IsExternalKey())
  1305. {
  1306. $sTargetClass = $oAttDef->GetTargetClass();
  1307. $oSearch = new DBObjectSearch($sTargetClass);
  1308. $oSearch->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true);
  1309. $oAllowedValues = new DBObjectSet($oSearch);
  1310. $iFieldSize = $oAttDef->GetMaxSize();
  1311. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1312. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;";
  1313. $aExtKeyParams = $aExtraParams;
  1314. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1315. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1316. $sHtml .= UIExtKeyWidget::DisplayFromAttCode($oPage, $sFilterCode, $sClassName, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sSearchFormId.'search_'.$sFilterCode, false, $sFilterCode, '', $aExtKeyParams, true);
  1317. }
  1318. else
  1319. {
  1320. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  1321. if (is_null($aAllowedValues))
  1322. {
  1323. // Any value is possible, display an input box
  1324. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"".htmlentities($sFilterValue, ENT_QUOTES, 'utf-8')."\"/>\n";
  1325. }
  1326. else
  1327. {
  1328. //Enum field, display a multi-select combo
  1329. $sValue = "<select class=\"multiselect\" size=\"1\" name=\"{$sFilterCode}[]\" multiple>\n";
  1330. $bMultiSelect = true;
  1331. //$sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  1332. foreach($aAllowedValues as $key => $value)
  1333. {
  1334. if (is_array($sFilterValue) && in_array($key, $sFilterValue))
  1335. {
  1336. $sSelected = ' selected';
  1337. }
  1338. else if ($sFilterValue == $key)
  1339. {
  1340. $sSelected = ' selected';
  1341. }
  1342. else
  1343. {
  1344. $sSelected = '';
  1345. }
  1346. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  1347. }
  1348. $sValue .= "</select>\n";
  1349. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  1350. }
  1351. }
  1352. unset($aExtraParams[$sFilterCode]);
  1353. // Finally, add a tooltip if one is defined for this attribute definition
  1354. $sTip = $oAttDef->GetHelpOnSmartSearch();
  1355. if (strlen($sTip) > 0)
  1356. {
  1357. $sTip = addslashes($sTip);
  1358. $sTip = str_replace(array("\n", "\r"), " ", $sTip);
  1359. // :input does represent in form visible input (INPUT, SELECT, TEXTAREA)
  1360. $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' }} } );");
  1361. }
  1362. $index++;
  1363. $sHtml .= '</span> ';
  1364. }
  1365. $sHtml .= "</p>\n";
  1366. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  1367. if (isset($aExtraParams['table_id']))
  1368. {
  1369. // Rename to avoid collisions...
  1370. $aExtraParams['_table_id_'] = $aExtraParams['table_id'];
  1371. unset($aExtraParams['table_id']);
  1372. }
  1373. foreach($aExtraParams as $sName => $sValue)
  1374. {
  1375. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1376. }
  1377. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  1378. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1379. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  1380. $sHtml .= $oAppContext->GetForForm();
  1381. $sHtml .= "</form>\n";
  1382. if (!isset($aExtraParams['currentId']))
  1383. {
  1384. $sHtml .= "</div><!-- Simple search form -->\n";
  1385. }
  1386. if ($bMultiSelect)
  1387. {
  1388. $oPage->add_ready_script("$('.multiselect').multiselect({header: false, noneSelectedText: '".addslashes(Dict::S('UI:SearchValue:Any'))."', selectedList: 1, selectedText:'".addslashes(Dict::S('UI:SearchValue:NbSelected'))."'});");
  1389. }
  1390. /*
  1391. // OQL query builder
  1392. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  1393. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  1394. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  1395. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  1396. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1397. $sSelectedClass = utils::ReadParam('oql_class', $sClassName, false, 'class');
  1398. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  1399. asort($aClasses);
  1400. foreach($aClasses as $sChildClass)
  1401. {
  1402. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  1403. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  1404. }
  1405. $sHtml .= "</select>&nbsp;</td><td>\n";
  1406. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  1407. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  1408. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1409. foreach($aExtraParams as $sName => $sValue)
  1410. {
  1411. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1412. }
  1413. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  1414. $sHtml .= $oAppContext->GetForForm();
  1415. $sHtml .= "</table></form>\n";
  1416. $sHtml .= "</div><!-- OQL query form -->\n";
  1417. */
  1418. return $sHtml;
  1419. }
  1420. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  1421. {
  1422. static $iInputId = 0;
  1423. $sFieldPrefix = '';
  1424. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  1425. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  1426. if ($sDisplayValue == '')
  1427. {
  1428. $sDisplayValue = $value;
  1429. }
  1430. if (isset($aArgs[$sAttCode]) && empty($value))
  1431. {
  1432. // default value passed by the context (either the app context of the operation)
  1433. $value = $aArgs[$sAttCode];
  1434. }
  1435. if (!empty($iId))
  1436. {
  1437. $iInputId = $iId;
  1438. }
  1439. else
  1440. {
  1441. $iInputId = $oPage->GetUniqueId();
  1442. }
  1443. if (!$oAttDef->IsExternalField())
  1444. {
  1445. $bMandatory = 'false';
  1446. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1447. {
  1448. $bMandatory = 'true';
  1449. }
  1450. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1451. $sHelpText = $oAttDef->GetHelpOnEdition();
  1452. $aEventsList = array();
  1453. switch($oAttDef->GetEditClass())
  1454. {
  1455. case 'Date':
  1456. $aEventsList[] ='validate';
  1457. $aEventsList[] ='keyup';
  1458. $aEventsList[] ='change';
  1459. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1460. {
  1461. $sDisplayValue = date($oAttDef->GetDateFormat());
  1462. }
  1463. $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}";
  1464. break;
  1465. case 'DateTime':
  1466. $aEventsList[] ='validate';
  1467. $aEventsList[] ='keyup';
  1468. $aEventsList[] ='change';
  1469. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1470. {
  1471. $sDisplayValue = date($oAttDef->GetDateFormat());
  1472. }
  1473. $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}";
  1474. break;
  1475. case 'Duration':
  1476. $aEventsList[] ='validate';
  1477. $aEventsList[] ='change';
  1478. $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1479. $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1480. $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1481. $oPage->add_ready_script("$('#{$iId}_s').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1482. $aVal = AttributeDuration::SplitDuration($value);
  1483. $sDays = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"3\" name=\"attr_{$sFieldPrefix}{$sAttCode}[d]{$sNameSuffix}\" value=\"{$aVal['days']}\" id=\"{$iId}_d\"/>";
  1484. $sHours = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[h]{$sNameSuffix}\" value=\"{$aVal['hours']}\" id=\"{$iId}_h\"/>";
  1485. $sMinutes = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[m]{$sNameSuffix}\" value=\"{$aVal['minutes']}\" id=\"{$iId}_m\"/>";
  1486. $sSeconds = "<input title=\"$sHelpText\" type=\"text\" style=\"text-align:right\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[s]{$sNameSuffix}\" value=\"{$aVal['seconds']}\" id=\"{$iId}_s\"/>";
  1487. $sHidden = "<input type=\"hidden\" id=\"{$iId}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\"/>";
  1488. $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden."&nbsp;".$sValidationField;
  1489. $oPage->add_ready_script("$('#{$iId}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });");
  1490. break;
  1491. case 'Password':
  1492. $aEventsList[] ='validate';
  1493. $aEventsList[] ='keyup';
  1494. $aEventsList[] ='change';
  1495. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1496. break;
  1497. case 'OQLExpression':
  1498. case 'Text':
  1499. $aEventsList[] ='validate';
  1500. $aEventsList[] ='keyup';
  1501. $aEventsList[] ='change';
  1502. $sEditValue = $oAttDef->GetEditValue($value);
  1503. $aStyles = array();
  1504. $sStyle = '';
  1505. $sWidth = $oAttDef->GetWidth('width', '');
  1506. if (!empty($sWidth))
  1507. {
  1508. $aStyles[] = 'width:'.$sWidth;
  1509. }
  1510. $sHeight = $oAttDef->GetHeight('height', '');
  1511. if (!empty($sHeight))
  1512. {
  1513. $aStyles[] = 'height:'.$sHeight;
  1514. }
  1515. if (count($aStyles) > 0)
  1516. {
  1517. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1518. }
  1519. if ($oAttDef->GetEditClass() == 'OQLExpression')
  1520. {
  1521. $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId();
  1522. $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression=';
  1523. $sInitialUrl = $sBaseUrl.urlencode($sEditValue);
  1524. $sAdditionalStuff = "<a id=\"$sTestResId\" target=\"_blank\" href=\"$sInitialUrl\">".Dict::S('UI:Edit:TestQuery')."</a>";
  1525. $oPage->add_ready_script("$('#$iId').bind('change keyup', function(evt, sFormId) { $('#$sTestResId').attr('href', '$sBaseUrl'+encodeURIComponent($(this).val())); } );");
  1526. }
  1527. else
  1528. {
  1529. $sAdditionalStuff = "";
  1530. }
  1531. // Ok, the text area is drawn here
  1532. $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>";
  1533. break;
  1534. case 'CaseLog':
  1535. $aStyles = array();
  1536. $sStyle = '';
  1537. $sWidth = $oAttDef->GetWidth('width', '');
  1538. if (!empty($sWidth))
  1539. {
  1540. $aStyles[] = 'width:'.$sWidth;
  1541. }
  1542. $sHeight = $oAttDef->GetHeight('height', '');
  1543. if (!empty($sHeight))
  1544. {
  1545. $aStyles[] = 'height:'.$sHeight;
  1546. }
  1547. if (count($aStyles) > 0)
  1548. {
  1549. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1550. }
  1551. $sHeader = '<div class="caselog_input_header">&nbsp;'.Dict::S('UI:CaseLogTypeYourTextHere').'</div>';
  1552. $sEditValue = $oAttDef->GetEditValue($value);
  1553. $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, array('AttributeText', 'RenderWikiHtml')) : '';
  1554. $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0;
  1555. $sHidden = "<input type=\"hidden\" id=\"{$iId}_count\" value=\"$iEntriesCount\"/>"; // To know how many entries the case log already contains
  1556. $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>";
  1557. $oPage->add_ready_script("$('#$iId').bind('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId) } );"); // Custom validation function
  1558. break;
  1559. case 'HTML':
  1560. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationField, $value, $bMandatory);
  1561. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1562. break;
  1563. case 'LinkedSet':
  1564. if ($oAttDef->IsIndirect())
  1565. {
  1566. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed(), $aArgs);
  1567. }
  1568. else
  1569. {
  1570. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix, $aArgs);
  1571. }
  1572. $aEventsList[] ='validate';
  1573. $aEventsList[] ='change';
  1574. $oObj = isset($aArgs['this']) ? $aArgs['this'] : null;
  1575. $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj);
  1576. break;
  1577. case 'Document':
  1578. $aEventsList[] ='validate';
  1579. $aEventsList[] ='change';
  1580. $oDocument = $value; // Value is an ormDocument object
  1581. $sFileName = '';
  1582. if (is_object($oDocument))
  1583. {
  1584. $sFileName = $oDocument->GetFileName();
  1585. }
  1586. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1587. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1588. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[filename]\" type=\"hidden\" id=\"$iId\" \" value=\"".htmlentities($sFileName, ENT_QUOTES, 'UTF-8')."\"/>\n";
  1589. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1590. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[fcontents]\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1591. break;
  1592. case 'StopWatch':
  1593. $sHTMLValue = "The edition of a stopwatch is not allowed!!!";
  1594. break;
  1595. case 'List':
  1596. // Not editable for now...
  1597. $sHTMLValue = '';
  1598. break;
  1599. case 'One Way Password':
  1600. $aEventsList[] ='validate';
  1601. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1602. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1603. // Event list & validation is handled directly by the widget
  1604. break;
  1605. case 'ExtKey':
  1606. $aEventsList[] ='validate';
  1607. $aEventsList[] ='change';
  1608. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1609. $sFieldName = $sFieldPrefix.$sAttCode.$sNameSuffix;
  1610. $aExtKeyParams = $aArgs;
  1611. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1612. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1613. $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams);
  1614. $sHTMLValue .= "<!-- iFlags: $iFlags bMandatory: $bMandatory -->\n";
  1615. break;
  1616. case 'String':
  1617. default:
  1618. $aEventsList[] ='validate';
  1619. // #@# todo - add context information (depending on dimensions)
  1620. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1621. $iFieldSize = $oAttDef->GetMaxSize();
  1622. if ($aAllowedValues !== null)
  1623. {
  1624. // Discrete list of values, use a SELECT or RADIO buttons depending on the config
  1625. $sDisplayStyle = $oAttDef->GetDisplayStyle();
  1626. switch($sDisplayStyle)
  1627. {
  1628. case 'radio':
  1629. case 'radio_horizontal':
  1630. case 'radio_vertical':
  1631. $sHTMLValue = '';
  1632. $bVertical = ($sDisplayStyle != 'radio_horizontal');
  1633. $sHTMLValue = $oPage->GetRadioButtons($aAllowedValues, $value, $iId, "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", $bMandatory, $bVertical, $sValidationField);
  1634. $aEventsList[] ='change';
  1635. break;
  1636. case 'select':
  1637. default:
  1638. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1639. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1640. foreach($aAllowedValues as $key => $display_value)
  1641. {
  1642. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1643. {
  1644. // When there is only once choice, select it by default
  1645. $sSelected = ' selected';
  1646. }
  1647. else
  1648. {
  1649. $sSelected = ($value == $key) ? ' selected' : '';
  1650. }
  1651. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1652. }
  1653. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1654. $aEventsList[] ='change';
  1655. }
  1656. }
  1657. else
  1658. {
  1659. $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}";
  1660. $aEventsList[] ='keyup';
  1661. $aEventsList[] ='change';
  1662. }
  1663. break;
  1664. }
  1665. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1666. if (!empty($aEventsList))
  1667. {
  1668. $sNullValue = $oAttDef->GetNullValue();
  1669. if (!is_numeric($sNullValue))
  1670. {
  1671. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1672. }
  1673. $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
  1674. }
  1675. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1676. if (count($aDependencies) > 0)
  1677. {
  1678. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1679. }
  1680. }
  1681. return "<div>{$sHTMLValue}</div>";
  1682. }
  1683. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1684. {
  1685. self::$iGlobalFormId++;
  1686. $sPrefix = '';
  1687. if (isset($aExtraParams['formPrefix']))
  1688. {
  1689. $sPrefix = $aExtraParams['formPrefix'];
  1690. }
  1691. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  1692. $this->m_iFormId = $sPrefix.self::$iGlobalFormId;
  1693. $sClass = get_class($this);
  1694. $oAppContext = new ApplicationContext();
  1695. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1696. $iKey = $this->GetKey();
  1697. $aDetails = array();
  1698. $aFieldsMap = array();
  1699. if (!isset($aExtraParams['action']))
  1700. {
  1701. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1702. }
  1703. else
  1704. {
  1705. $sFormAction = $aExtraParams['action'];
  1706. }
  1707. // Custom label for the apply button ?
  1708. if (isset($aExtraParams['custom_button']))
  1709. {
  1710. $sApplyButton = $aExtraParams['custom_button'];
  1711. }
  1712. else if ($iKey > 0)
  1713. {
  1714. $sApplyButton = Dict::S('UI:Button:Apply');
  1715. }
  1716. else
  1717. {
  1718. $sApplyButton = Dict::S('UI:Button:Create');
  1719. }
  1720. // Custom operation for the form ?
  1721. if (isset($aExtraParams['custom_operation']))
  1722. {
  1723. $sOperation = $aExtraParams['custom_operation'];
  1724. }
  1725. else if ($iKey > 0)
  1726. {
  1727. $sOperation = 'apply_modify';
  1728. }
  1729. else
  1730. {
  1731. $sOperation = 'apply_new';
  1732. }
  1733. if ($iKey > 0)
  1734. {
  1735. // The object already exists in the database, it's a modification
  1736. $sButtons = "<input id=\"{$sPrefix}_id\" type=\"hidden\" name=\"id\" value=\"$iKey\">\n";
  1737. $sButtons .= "<input type=\"hidden\" name=\"operation\" value=\"{$sOperation}\">\n";
  1738. $sButtons .= "<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1739. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1740. }
  1741. else
  1742. {
  1743. // The object does not exist in the database it's a creation
  1744. $sButtons = "<input type=\"hidden\" name=\"operation\" value=\"$sOperation\">\n";
  1745. $sButtons .= "<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1746. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1747. }
  1748. $aTransitions = $this->EnumTransitions();
  1749. if (!isset($aExtraParams['custom_operation']) && count($aTransitions))
  1750. {
  1751. // transitions are displayed only for the standard new/modify actions, not for modify_all or any other case...
  1752. $oSetToCheckRights = DBObjectSet::FromObject($this);
  1753. $aStimuli = Metamodel::EnumStimuli($sClass);
  1754. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1755. {
  1756. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSetToCheckRights) : UR_ALLOWED_NO;
  1757. switch($iActionAllowed)
  1758. {
  1759. case UR_ALLOWED_YES:
  1760. $sButtons .= "<button type=\"submit\" name=\"next_action\" value=\"{$sStimulusCode}\" class=\"action\"><span>".$aStimuli[$sStimulusCode]->GetLabel()."</span></button>\n";
  1761. break;
  1762. default:
  1763. // Do nothing
  1764. }
  1765. }
  1766. }
  1767. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1768. $iTransactionId = isset($aExtraParams['transaction_id']) ? $aExtraParams['transaction_id'] : utils::GetNewTransactionId();
  1769. $oPage->SetTransactionId($iTransactionId);
  1770. $oPage->add("<form action=\"$sFormAction\" id=\"form_{$this->m_iFormId}\" enctype=\"multipart/form-data\" method=\"post\" onSubmit=\"return OnSubmit('form_{$this->m_iFormId}');\">\n");
  1771. $sStatesSelection = '';
  1772. if (!isset($aExtraParams['custom_operation']) && $this->IsNew())
  1773. {
  1774. $aInitialStates = MetaModel::EnumInitialStates($sClass);
  1775. //$aInitialStates = array('new' => 'foo', 'closed' => 'bar');
  1776. if (count($aInitialStates) > 1)
  1777. {
  1778. $sStatesSelection = Dict::Format('UI:Create_Class_InState', MetaModel::GetName($sClass)).'<select name="obj_state" class="state_select_'.$this->m_iFormId.'">';
  1779. foreach($aInitialStates as $sStateCode => $sStateData)
  1780. {
  1781. $sSelected = '';
  1782. if ($sStateCode == $this->GetState())
  1783. {
  1784. $sSelected = ' selected';
  1785. }
  1786. $sStatesSelection .= '<option value="'.$sStateCode.'"'.$sSelected.'>'.MetaModel::GetStateLabel($sClass, $sStateCode).'</option>';
  1787. }
  1788. $sStatesSelection .= '</select>';
  1789. $oPage->add_ready_script("$('.state_select_{$this->m_iFormId}').change( function() { oWizardHelper$sPrefix.ReloadObjectCreationForm('form_{$this->m_iFormId}', $(this).val()); } );");
  1790. }
  1791. }
  1792. $sConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage'));
  1793. $oPage->add_ready_script(
  1794. <<<EOF
  1795. $(window).unload(function() { return OnUnload('$iTransactionId') } );
  1796. window.onbeforeunload = function() {
  1797. if (!window.bInSubmit && !window.bInCancel)
  1798. {
  1799. return '$sConfirmationMessage';
  1800. }
  1801. // return nothing ! safer for IE
  1802. };
  1803. EOF
  1804. );
  1805. if ($sButtonsPosition != 'bottom')
  1806. {
  1807. // top or both, display the buttons here
  1808. $oPage->p($sStatesSelection);
  1809. $oPage->add($sButtons);
  1810. }
  1811. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1812. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1813. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1814. $aFieldsMap = $this->DisplayBareProperties($oPage, true, $sPrefix, $aExtraParams);
  1815. if ($iKey > 0)
  1816. {
  1817. $aFieldsMap['id'] = $sPrefix.'_id';
  1818. }
  1819. // Now display the relations, one tab per relation
  1820. if (!isset($aExtraParams['noRelations']))
  1821. {
  1822. $this->DisplayBareRelations($oPage, true); // Edit mode
  1823. }
  1824. $oPage->SetCurrentTab('');
  1825. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1826. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"$iTransactionId\">\n");
  1827. foreach($aExtraParams as $sName => $value)
  1828. {
  1829. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1830. }
  1831. $oPage->add($oAppContext->GetForForm());
  1832. if ($sButtonsPosition != 'top')
  1833. {
  1834. // bottom or both: display the buttons here
  1835. $oPage->p($sStatesSelection);
  1836. $oPage->add($sButtons);
  1837. }
  1838. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1839. $sDefaultUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=cancel&'.$oAppContext->GetForLink();
  1840. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1841. $oPage->add("</form>\n");
  1842. $iFieldsCount = count($aFieldsMap);
  1843. $sJsonFieldsMap = json_encode($aFieldsMap);
  1844. $sState = $this->GetState();
  1845. $oPage->add_script(
  1846. <<<EOF
  1847. // Create the object once at the beginning of the page...
  1848. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix', '$sState');
  1849. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1850. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1851. EOF
  1852. );
  1853. $oPage->add_ready_script(
  1854. <<<EOF
  1855. oWizardHelper$sPrefix.UpdateWizard();
  1856. // Starts the validation when the page is ready
  1857. CheckFields('form_{$this->m_iFormId}', false);
  1858. EOF
  1859. );
  1860. }
  1861. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1862. {
  1863. $oAppContext = new ApplicationContext();
  1864. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1865. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1866. $aStates = MetaModel::EnumStates($sClass);
  1867. $sStatesSelection = '';
  1868. if ($oObjectToClone == null)
  1869. {
  1870. $oObj = MetaModel::NewObject($sClass);
  1871. if (!empty($sStateAttCode))
  1872. {
  1873. $sTargetState = MetaModel::GetDefaultState($sClass);
  1874. $oObj->Set($sStateAttCode, $sTargetState);
  1875. }
  1876. }
  1877. else
  1878. {
  1879. $oObj = clone $oObjectToClone;
  1880. }
  1881. // Pre-fill the object with default values, when there is only on possible choice
  1882. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  1883. $aArgs['this'] = $oObj;
  1884. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1885. // Order the fields based on their dependencies
  1886. $aDeps = array();
  1887. foreach($aDetailsList as $sAttCode)
  1888. {
  1889. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1890. }
  1891. $aList = self::OrderDependentFields($aDeps);
  1892. // Now fill-in the fields with default/supplied values
  1893. foreach($aList as $sAttCode)
  1894. {
  1895. if (isset($aArgs['default'][$sAttCode]))
  1896. {
  1897. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  1898. }
  1899. else
  1900. {
  1901. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1902. // If the field is mandatory, set it to the only possible value
  1903. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  1904. if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1905. {
  1906. if ($oAttDef->IsExternalKey())
  1907. {
  1908. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1909. if ($oAllowedValues->Count() == 1)
  1910. {
  1911. $oRemoteObj = $oAllowedValues->Fetch();
  1912. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1913. }
  1914. }
  1915. else
  1916. {
  1917. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1918. if (count($aAllowedValues) == 1)
  1919. {
  1920. $aValues = array_keys($aAllowedValues);
  1921. $oObj->Set($sAttCode, $aValues[0]);
  1922. }
  1923. }
  1924. }
  1925. }
  1926. }
  1927. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  1928. }
  1929. public static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  1930. {
  1931. //echo "<pre>ZList: ";
  1932. //print_r($aList);
  1933. //echo "</pre>\n";
  1934. $index = 0;
  1935. foreach($aList as $sKey => $value)
  1936. {
  1937. if (is_array($value))
  1938. {
  1939. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  1940. {
  1941. $sCode = $aMatches[1];
  1942. $sName = $aMatches[2];
  1943. switch($sCode)
  1944. {
  1945. case 'tab':
  1946. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  1947. if(!isset($aDetails[$sName]))
  1948. {
  1949. $aDetails[$sName] = array('col1' => array());
  1950. }
  1951. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  1952. break;
  1953. case 'fieldset':
  1954. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  1955. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  1956. {
  1957. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  1958. }
  1959. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  1960. break;
  1961. default:
  1962. case 'col':
  1963. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  1964. if(!isset($aDetails[$sCurrentTab][$sName]))
  1965. {
  1966. $aDetails[$sCurrentTab][$sName] = array();
  1967. }
  1968. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  1969. break;
  1970. }
  1971. }
  1972. }
  1973. else
  1974. {
  1975. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  1976. if (empty($sCurrentSet))
  1977. {
  1978. $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value;
  1979. }
  1980. else
  1981. {
  1982. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  1983. }
  1984. }
  1985. $index++;
  1986. }
  1987. return $aDetails;
  1988. }
  1989. static function FlattenZList($aList)
  1990. {
  1991. $aResult = array();
  1992. foreach($aList as $value)
  1993. {
  1994. if (!is_array($value))
  1995. {
  1996. $aResult[] = $value;
  1997. }
  1998. else
  1999. {
  2000. $aResult = array_merge($aResult,self::FlattenZList($value));
  2001. }
  2002. }
  2003. return $aResult;
  2004. }
  2005. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  2006. {
  2007. $retVal = null;
  2008. if ($this->IsNew())
  2009. {
  2010. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2011. }
  2012. else
  2013. {
  2014. $iFlags = $this->GetAttributeFlags($sAttCode);
  2015. }
  2016. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  2017. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  2018. {
  2019. // The field is visible in the current state of the object
  2020. if ($sStateAttCode == $sAttCode)
  2021. {
  2022. // Special display for the 'state' attribute itself
  2023. $sDisplayValue = $this->GetStateLabel();
  2024. }
  2025. else if ($oAttDef->GetEditClass() == 'Document')
  2026. {
  2027. $oDocument = $this->Get($sAttCode);
  2028. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2029. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2030. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDownloadLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2031. }
  2032. else
  2033. {
  2034. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2035. }
  2036. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  2037. }
  2038. return $retVal;
  2039. }
  2040. /**
  2041. * Displays a blob document *inline* (if possible, depending on the type of the document)
  2042. * @return string
  2043. */
  2044. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  2045. {
  2046. $oDoc = $this->Get($sAttCode);
  2047. $sClass = get_class($this);
  2048. $Id = $this->GetKey();
  2049. switch ($oDoc->GetMainMimeType())
  2050. {
  2051. case 'text':
  2052. case 'html':
  2053. $data = $oDoc->GetData();
  2054. switch($oDoc->GetMimeType())
  2055. {
  2056. case 'text/html':
  2057. case 'text/xml':
  2058. $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");
  2059. break;
  2060. default:
  2061. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true), ENT_QUOTES, 'UTF-8')."</pre>\n");
  2062. }
  2063. break;
  2064. case 'application':
  2065. switch($oDoc->GetMimeType())
  2066. {
  2067. case 'application/pdf':
  2068. $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");
  2069. break;
  2070. default:
  2071. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2072. }
  2073. break;
  2074. case 'image':
  2075. $oPage->add("<img src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  2076. break;
  2077. default:
  2078. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2079. }
  2080. }
  2081. // $m_highlightComparison[previous][new] => next value
  2082. protected static $m_highlightComparison = array(
  2083. HILIGHT_CLASS_CRITICAL => array(
  2084. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2085. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL,
  2086. HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL,
  2087. HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL,
  2088. ),
  2089. HILIGHT_CLASS_WARNING => array(
  2090. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2091. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2092. HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING,
  2093. HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING,
  2094. ),
  2095. HILIGHT_CLASS_OK => array(
  2096. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2097. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2098. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2099. HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK,
  2100. ),
  2101. HILIGHT_CLASS_NONE => array(
  2102. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2103. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2104. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2105. HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE,
  2106. ),
  2107. );
  2108. /**
  2109. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  2110. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  2111. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2112. * To Be overridden by derived classes
  2113. * @param void
  2114. * @return String The desired higlight class for the object/row
  2115. */
  2116. public function GetHilightClass()
  2117. {
  2118. // Possible return values are:
  2119. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2120. $current = HILIGHT_CLASS_NONE; // Not hilighted by default
  2121. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2122. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2123. {
  2124. $new = $oExtensionInstance->GetHilightClass($this);
  2125. @$current = self::$m_highlightComparison[$current][$new];
  2126. }
  2127. return $current;
  2128. }
  2129. /**
  2130. * Re-order the fields based on their inter-dependencies
  2131. * @params hash @aFields field_code => array_of_depencies
  2132. * @return array Ordered array of fields or throws an exception
  2133. */
  2134. public static function OrderDependentFields($aFields)
  2135. {
  2136. $bCircular = false;
  2137. $aResult = array();
  2138. $iCount = 0;
  2139. do
  2140. {
  2141. $bSet = false;
  2142. $iCount++;
  2143. foreach($aFields as $sFieldCode => $aDeps)
  2144. {
  2145. foreach($aDeps as $key => $sDependency)
  2146. {
  2147. if (in_array($sDependency, $aResult))
  2148. {
  2149. // Dependency is resolved, remove it
  2150. unset($aFields[$sFieldCode][$key]);
  2151. }
  2152. }
  2153. if (count($aFields[$sFieldCode]) == 0)
  2154. {
  2155. // No more pending depencies for this field, add it to the list
  2156. $aResult[] = $sFieldCode;
  2157. unset($aFields[$sFieldCode]);
  2158. $bSet = true;
  2159. }
  2160. }
  2161. }
  2162. while($bSet && (count($aFields) > 0));
  2163. if (count($aFields) > 0)
  2164. {
  2165. $sMessage = "Error: Circular dependencies between the fields (or field missing in ZList) ! <pre>".print_r($aFields, true)."</pre>";
  2166. throw(new Exception($sMessage));
  2167. }
  2168. return $aResult;
  2169. }
  2170. /**
  2171. * Get the list of actions to be displayed as 'shortcuts' (i.e buttons) instead of inside the Actions popup menu
  2172. * @param $sFinalClass string The actual class of the objects for which to display the menu
  2173. * @return Array the list of menu codes (i.e dictionary entries) that can be displayed as shortcuts next to the actions menu
  2174. */
  2175. public static function GetShortcutActions($sFinalClass)
  2176. {
  2177. $sShortcutActions = MetaModel::GetConfig()->Get('shortcut_actions');
  2178. $aShortcutActions = explode(',', $sShortcutActions);
  2179. return $aShortcutActions;
  2180. }
  2181. /**
  2182. * Maps the given context parameter name to the appropriate filter/search code for this class
  2183. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  2184. * @return string Filter code, i.e. 'customer_id'
  2185. */
  2186. public static function MapContextParam($sContextParam)
  2187. {
  2188. if ($sContextParam == 'menu')
  2189. {
  2190. return null;
  2191. }
  2192. else
  2193. {
  2194. return $sContextParam;
  2195. }
  2196. }
  2197. /**
  2198. * Updates the object from a flat array of values
  2199. * @param $aAttList array $aAttList array of attcode
  2200. * @param $aErrors array Returns information about slave attributes
  2201. * @param $sTargetState string Target state for which to evaluate the writeable attributes (=current state is empty)
  2202. * @return array of attcodes that can be used for writing on the current object
  2203. */
  2204. public function GetWriteableAttList($aAttList, &$aErrors, $sTargetState = '')
  2205. {
  2206. if (!is_array($aAttList))
  2207. {
  2208. $aAttList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2209. // Special case to process the case log, if any...
  2210. // WARNING: if you change this also check the functions DisplayModifyForm and DisplayCaseLog
  2211. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2212. {
  2213. if ($this->IsNew())
  2214. {
  2215. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2216. }
  2217. else
  2218. {
  2219. $aVoid = array();
  2220. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2221. }
  2222. if ($oAttDef instanceof AttributeCaseLog)
  2223. {
  2224. if (!($iFlags & (OPT_ATT_HIDDEN|OPT_ATT_SLAVE|OPT_ATT_READONLY)))
  2225. {
  2226. // The case log is editable, append it to the list of fields to retrieve
  2227. $aAttList[] = $sAttCode;
  2228. }
  2229. }
  2230. }
  2231. }
  2232. $aWriteableAttList = array();
  2233. foreach($aAttList as $sAttCode)
  2234. {
  2235. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2236. if ($this->IsNew())
  2237. {
  2238. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2239. }
  2240. else
  2241. {
  2242. $aVoid = array();
  2243. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2244. }
  2245. if ($oAttDef->IsWritable())
  2246. {
  2247. if ( $iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  2248. {
  2249. // Non-visible, or read-only attribute, do nothing
  2250. }
  2251. elseif($iFlags & OPT_ATT_SLAVE)
  2252. {
  2253. $aErrors[$sAttCode] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  2254. }
  2255. else
  2256. {
  2257. $aWriteableAttList[$sAttCode] = $oAttDef;
  2258. }
  2259. }
  2260. }
  2261. return $aWriteableAttList;
  2262. }
  2263. /**
  2264. * Updates the object from a flat array of values
  2265. * @param string $aValues array of attcode => scalar or array (N-N links)
  2266. * @return void
  2267. */
  2268. public function UpdateObjectFromArray($aValues)
  2269. {
  2270. foreach($aValues as $sAttCode => $value)
  2271. {
  2272. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2273. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  2274. {
  2275. $aLinks = $value;
  2276. $sLinkedClass = $oAttDef->GetLinkedClass();
  2277. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  2278. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2279. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  2280. if (is_array($aLinks))
  2281. {
  2282. foreach($aLinks as $id => $aData)
  2283. {
  2284. if (is_numeric($id))
  2285. {
  2286. if ($id < 0)
  2287. {
  2288. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  2289. $oLink = MetaModel::NewObject($sLinkedClass);
  2290. $oLink->Set($sExtKeyToRemote, -$id);
  2291. $oLink->Set($sExtKeyToMe, $this->GetKey());
  2292. }
  2293. else
  2294. {
  2295. // Existing link, potentially to be updated...
  2296. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  2297. }
  2298. // Now populate the attributes
  2299. foreach($aData as $sName => $value)
  2300. {
  2301. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  2302. {
  2303. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  2304. if ($oLinkAttDef->IsWritable())
  2305. {
  2306. $oLink->Set($sName, $value);
  2307. }
  2308. }
  2309. }
  2310. $oLinkedSet->AddObject($oLink);
  2311. }
  2312. }
  2313. }
  2314. $this->Set($sAttCode, $oLinkedSet);
  2315. }
  2316. elseif ($oAttDef->GetEditClass() == 'Document')
  2317. {
  2318. // There should be an uploaded file with the named attr_<attCode>
  2319. $oDocument = $value['fcontents'];
  2320. if (!$oDocument->IsEmpty())
  2321. {
  2322. // A new file has been uploaded
  2323. $this->Set($sAttCode, $oDocument);
  2324. }
  2325. }
  2326. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  2327. {
  2328. // Check if the password was typed/changed
  2329. $aPwdData = $value;
  2330. if (!is_null($aPwdData) && $aPwdData['changed'])
  2331. {
  2332. // The password has been changed or set
  2333. $this->Set($sAttCode, $aPwdData['value']);
  2334. }
  2335. }
  2336. elseif ($oAttDef->GetEditClass() == 'Duration')
  2337. {
  2338. $aDurationData = $value;
  2339. if (!is_array($aDurationData)) continue;
  2340. $iValue = (((24*$aDurationData['d'])+$aDurationData['h'])*60 +$aDurationData['m'])*60 + $aDurationData['s'];
  2341. $this->Set($sAttCode, $iValue);
  2342. $previousValue = $this->Get($sAttCode);
  2343. if ($previousValue !== $iValue)
  2344. {
  2345. $this->Set($sAttCode, $iValue);
  2346. }
  2347. }
  2348. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() && ($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE))
  2349. {
  2350. $oLinkset = $this->Get($sAttCode);
  2351. $sLinkedClass = $oLinkset->GetClass();
  2352. $aObjSet = array();
  2353. $oLinkset->Rewind();
  2354. $bModified = false;
  2355. while($oLink = $oLinkset->Fetch())
  2356. {
  2357. if (in_array($oLink->GetKey(), $value['to_be_deleted']))
  2358. {
  2359. // The link is to be deleted, don't copy it in the array
  2360. $bModified = true;
  2361. }
  2362. else
  2363. {
  2364. $aObjSet[] = $oLink;
  2365. }
  2366. }
  2367. if (array_key_exists('to_be_created', $value) && (count($value['to_be_created']) > 0))
  2368. {
  2369. // Now handle the lniks to be created
  2370. foreach($value['to_be_created'] as $aData)
  2371. {
  2372. $sSubClass = $aData['class'];
  2373. if ( ($sLinkedClass == $sSubClass) || (is_subclass_of($sSubClass, $sLinkedClass)) )
  2374. {
  2375. $aObjData = $aData['data'];
  2376. $oLink = new $sSubClass;
  2377. $oLink->UpdateObjectFromArray($aObjData);
  2378. $aObjSet[] = $oLink;
  2379. $bModified = true;
  2380. }
  2381. }
  2382. }
  2383. if ($bModified)
  2384. {
  2385. $oNewSet = DBObjectSet::FromArray($oLinkset->GetClass(), $aObjSet);
  2386. $this->Set($sAttCode, $oNewSet);
  2387. }
  2388. }
  2389. else
  2390. {
  2391. if (!is_null($value))
  2392. {
  2393. $aAttributes[$sAttCode] = trim($value);
  2394. $previousValue = $this->Get($sAttCode);
  2395. if ($previousValue !== $aAttributes[$sAttCode])
  2396. {
  2397. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  2398. }
  2399. }
  2400. }
  2401. }
  2402. }
  2403. /**
  2404. * Updates the object from the POSTed parameters (form)
  2405. */
  2406. public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $sTargetState = '')
  2407. {
  2408. if (is_null($aAttList))
  2409. {
  2410. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2411. }
  2412. $aValues = array();
  2413. foreach($aAttList as $sAttCode)
  2414. {
  2415. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2416. if ($oAttDef->GetEditClass() == 'Document')
  2417. {
  2418. $value = array('fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'));
  2419. }
  2420. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() && ($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE))
  2421. {
  2422. $aRawToBeCreated = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbc", '{}', 'raw_data'), true);
  2423. $aToBeCreated = array();
  2424. foreach($aRawToBeCreated as $aData)
  2425. {
  2426. $sSubFormPrefix = $aData['formPrefix'];
  2427. $sObjClass = $aData['class'];
  2428. $aObjData = array();
  2429. foreach($aData as $sKey => $value)
  2430. {
  2431. if (preg_match("/^attr_$sSubFormPrefix(.*)$/", $sKey, $aMatches))
  2432. {
  2433. $aObjData[$aMatches[1]] = $value;
  2434. }
  2435. }
  2436. $aToBeCreated[] = array('class' => $sObjClass, 'data' => $aObjData);
  2437. }
  2438. $value = array('to_be_created' => $aToBeCreated,
  2439. 'to_be_deleted' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbd", '[]', 'raw_data'), true) );
  2440. }
  2441. else
  2442. {
  2443. $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data');
  2444. }
  2445. if (!is_null($value))
  2446. {
  2447. $aValues[$sAttCode] = $value;
  2448. }
  2449. }
  2450. $aErrors = array();
  2451. $aFinalValues = array();
  2452. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2453. {
  2454. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2455. }
  2456. $this->UpdateObjectFromArray($aFinalValues);
  2457. // Invoke extensions after the update of the object from the form
  2458. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2459. {
  2460. $oExtensionInstance->OnFormSubmit($this, $sFormPrefix);
  2461. }
  2462. return $aErrors;
  2463. }
  2464. /**
  2465. * Updates the object from a given page argument
  2466. */
  2467. public function UpdateObjectFromArg($sArgName, $aAttList = null, $sTargetState = '')
  2468. {
  2469. if (is_null($aAttList))
  2470. {
  2471. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2472. }
  2473. $aRawValues = utils::ReadParam($sArgName, array(), '', 'raw_data');
  2474. $aValues = array();
  2475. foreach($aAttList as $sAttCode)
  2476. {
  2477. if (isset($aRawValues[$sAttCode]))
  2478. {
  2479. $aValues[$sAttCode] = $aRawValues[$sAttCode];
  2480. }
  2481. }
  2482. $aErrors = array();
  2483. $aFinalValues = array();
  2484. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2485. {
  2486. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2487. }
  2488. $this->UpdateObjectFromArray($aFinalValues);
  2489. return $aErrors;
  2490. }
  2491. public function DBInsertNoReload()
  2492. {
  2493. $res = parent::DBInsertNoReload();
  2494. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2495. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2496. {
  2497. $oExtensionInstance->OnDBInsert($this, self::GetCurrentChange());
  2498. }
  2499. return $res;
  2500. }
  2501. protected function DBCloneTracked_Internal($newKey = null)
  2502. {
  2503. $oNewObj = parent::DBCloneTracked_Internal($newKey);
  2504. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2505. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2506. {
  2507. $oExtensionInstance->OnDBInsert($oNewObj, self::GetCurrentChange());
  2508. }
  2509. return $oNewObj;
  2510. }
  2511. public function DBUpdate()
  2512. {
  2513. $res = parent::DBUpdate();
  2514. // Invoke extensions after the update (could be before)
  2515. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2516. {
  2517. $oExtensionInstance->OnDBUpdate($this, self::GetCurrentChange());
  2518. }
  2519. return $res;
  2520. }
  2521. protected static function BulkUpdateTracked_Internal(DBObjectSearch $oFilter, array $aValues)
  2522. {
  2523. // Todo - invoke the extension
  2524. return parent::BulkUpdateTracked_Internal($oFilter, $aValues);
  2525. }
  2526. protected function DBDeleteTracked_Internal(&$oDeletionPlan = null)
  2527. {
  2528. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2529. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2530. {
  2531. $oExtensionInstance->OnDBDelete($this, self::GetCurrentChange());
  2532. }
  2533. return parent::DBDeleteTracked_Internal($oDeletionPlan);
  2534. }
  2535. public function IsModified()
  2536. {
  2537. if (parent::IsModified())
  2538. {
  2539. return true;
  2540. }
  2541. // Plugins
  2542. //
  2543. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2544. {
  2545. if ($oExtensionInstance->OnIsModified($this))
  2546. {
  2547. return true;
  2548. }
  2549. }
  2550. return false;
  2551. }
  2552. public function DoCheckToWrite()
  2553. {
  2554. parent::DoCheckToWrite();
  2555. // Plugins
  2556. //
  2557. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2558. {
  2559. $aNewIssues = $oExtensionInstance->OnCheckToWrite($this);
  2560. if (count($aNewIssues) > 0)
  2561. {
  2562. $this->m_aCheckIssues = array_merge($this->m_aCheckIssues, $aNewIssues);
  2563. }
  2564. }
  2565. // User rights
  2566. //
  2567. $aChanges = $this->ListChanges();
  2568. if (count($aChanges) > 0)
  2569. {
  2570. $aForbiddenFields = array();
  2571. foreach ($this->ListChanges() as $sAttCode => $value)
  2572. {
  2573. $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute(get_class($this), $sAttCode, UR_ACTION_MODIFY, DBObjectSet::FromObject($this));
  2574. if (!$bUpdateAllowed)
  2575. {
  2576. $oAttCode = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2577. $aForbiddenFields[] = $oAttCode->GetLabel();
  2578. }
  2579. }
  2580. if (count($aForbiddenFields) > 0)
  2581. {
  2582. // Security issue
  2583. $this->m_bSecurityIssue = true;
  2584. $this->m_aCheckIssues[] = Dict::Format('UI:Delete:NotAllowedToUpdate_Fields',implode(', ', $aForbiddenFields));
  2585. }
  2586. }
  2587. }
  2588. protected function DoCheckToDelete(&$oDeletionPlan)
  2589. {
  2590. parent::DoCheckToDelete($oDeletionPlan);
  2591. // Plugins
  2592. //
  2593. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2594. {
  2595. $aNewIssues = $oExtensionInstance->OnCheckToDelete($this);
  2596. if (count($aNewIssues) > 0)
  2597. {
  2598. $this->m_aDeleteIssues = array_merge($this->m_aDeleteIssues, $aNewIssues);
  2599. }
  2600. }
  2601. // User rights
  2602. //
  2603. $bDeleteAllowed = UserRights::IsActionAllowed(get_class($this), UR_ACTION_DELETE, DBObjectSet::FromObject($this));
  2604. if (!$bDeleteAllowed)
  2605. {
  2606. // Security issue
  2607. $this->m_bSecurityIssue = true;
  2608. $this->m_aDeleteIssues[] = Dict::S('UI:Delete:NotAllowedToDelete');
  2609. }
  2610. }
  2611. /**
  2612. * Special display where the case log uses the whole "screen" at the bottom of the "Properties" tab
  2613. */
  2614. public function DisplayCaseLog(WebPage $oPage, $sAttCode, $sComment = '', $sPrefix = '', $bEditMode = false)
  2615. {
  2616. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  2617. $sClass = get_class($this);
  2618. if ($this->IsNew())
  2619. {
  2620. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2621. }
  2622. else
  2623. {
  2624. $iFlags = $this->GetAttributeFlags($sAttCode);
  2625. }
  2626. if ( $iFlags & OPT_ATT_HIDDEN)
  2627. {
  2628. // The case log is hidden do nothing
  2629. }
  2630. else
  2631. {
  2632. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2633. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  2634. if ((!$bEditMode) || ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE)))
  2635. {
  2636. // Check if the attribute is not read-only because of a synchro...
  2637. $aReasons = array();
  2638. $sSynchroIcon = '';
  2639. if ($iFlags & OPT_ATT_SLAVE)
  2640. {
  2641. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  2642. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  2643. $sTip = '';
  2644. foreach($aReasons as $aRow)
  2645. {
  2646. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  2647. }
  2648. $sTip = addslashes($sTip);
  2649. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  2650. }
  2651. // Attribute is read-only
  2652. $sHTMLValue = $this->GetAsHTML($sAttCode);
  2653. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>';
  2654. $aFieldsMap[$sAttCode] = $sInputId;
  2655. $sComment .= $sSynchroIcon;
  2656. }
  2657. else
  2658. {
  2659. $sValue = $this->Get($sAttCode);
  2660. $sDisplayValue = $this->GetEditValue($sAttCode);
  2661. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  2662. $sHTMLValue = '';
  2663. if ($sComment != '')
  2664. {
  2665. $sHTMLValue = '<span>'.$sComment.'</span><br/>';
  2666. }
  2667. $sHTMLValue .= "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  2668. $aFieldsMap[$sAttCode] = $sInputId;
  2669. }
  2670. //$aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  2671. $oPage->add('<fieldset><legend>'.$oAttDef->GetLabel().'</legend>');
  2672. $oPage->add($sHTMLValue);
  2673. $oPage->add('</fieldset>');
  2674. }
  2675. }
  2676. public function GetExpectedAttributes($sCurrentState, $sStimulus, $bOnlyNewOnes)
  2677. {
  2678. $aTransitions = $this->EnumTransitions();
  2679. $aStimuli = MetaModel::EnumStimuli(get_class($this));
  2680. if (!isset($aTransitions[$sStimulus]))
  2681. {
  2682. // Invalid stimulus
  2683. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  2684. }
  2685. $aTransition = $aTransitions[$sStimulus];
  2686. $sTargetState = $aTransition['target_state'];
  2687. $aTargetStates = MetaModel::EnumStates(get_class($this));
  2688. $aTargetState = $aTargetStates[$sTargetState];
  2689. $aCurrentState = $aTargetStates[$this->GetState()];
  2690. $aExpectedAttributes = $aTargetState['attribute_list'];
  2691. $aCurrentAttributes = $aCurrentState['attribute_list'];
  2692. $aComputedAttributes = array();
  2693. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  2694. {
  2695. if (!array_key_exists($sAttCode, $aCurrentAttributes))
  2696. {
  2697. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2698. }
  2699. else
  2700. {
  2701. if ( !($aCurrentAttributes[$sAttCode] & (OPT_ATT_HIDDEN|OPT_ATT_READONLY)) )
  2702. {
  2703. $iExpectCode = $iExpectCode & ~(OPT_ATT_MUSTPROMPT|OPT_ATT_MUSTCHANGE); // Already prompted/changed, reset the flags
  2704. }
  2705. //TODO: better check if the attribute is not *null*
  2706. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($this->Get($sAttCode) != ''))
  2707. {
  2708. $iExpectCode = $iExpectCode & ~(OPT_ATT_MANDATORY); // If the attribute is present, then no need to request its presence
  2709. }
  2710. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2711. }
  2712. $aComputedAttributes[$sAttCode] = $aComputedAttributes[$sAttCode] & ~(OPT_ATT_READONLY|OPT_ATT_HIDDEN); // Don't care about this form now
  2713. if ($aComputedAttributes[$sAttCode] == 0)
  2714. {
  2715. unset($aComputedAttributes[$sAttCode]);
  2716. }
  2717. }
  2718. return $aComputedAttributes;
  2719. }
  2720. /**
  2721. * Display a form for modifying several objects at once
  2722. * The form will be submitted to the current page, with the specified additional values
  2723. */
  2724. public static function DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, $sCustomOperation, $sCancelUrl, $aExcludeAttributes = array(), $aContextData = array())
  2725. {
  2726. if (count($aSelectedObj) > 0)
  2727. {
  2728. $iAllowedCount = count($aSelectedObj);
  2729. $sSelectedObj = implode(',', $aSelectedObj);
  2730. $sOQL = "SELECT $sClass WHERE id IN (".$sSelectedObj.")";
  2731. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2732. // Compute the distribution of the values for each field to determine which of the "scalar" fields are homogenous
  2733. $aList = MetaModel::ListAttributeDefs($sClass);
  2734. $aValues = array();
  2735. foreach($aList as $sAttCode => $oAttDef)
  2736. {
  2737. if ($oAttDef->IsScalar())
  2738. {
  2739. $aValues[$sAttCode] = array();
  2740. }
  2741. }
  2742. while($oObj = $oSet->Fetch())
  2743. {
  2744. foreach($aList as $sAttCode => $oAttDef)
  2745. {
  2746. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  2747. {
  2748. $currValue = $oObj->Get($sAttCode);
  2749. if ($oAttDef instanceof AttributeCaseLog)
  2750. {
  2751. $currValue = ' '; // Don't put an empty string, in case the field would be considered as mandatory...
  2752. }
  2753. if (is_object($currValue)) continue; // Skip non scalar values...
  2754. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  2755. {
  2756. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  2757. }
  2758. else
  2759. {
  2760. $aValues[$sAttCode][$currValue]['count']++;
  2761. }
  2762. }
  2763. }
  2764. }
  2765. // Now create an object that has values for the homogenous values only
  2766. $oDummyObj = new $sClass(); // @@ What if the class is abstract ?
  2767. $aComments = array();
  2768. function MyComparison($a, $b) // Sort descending
  2769. {
  2770. if ($a['count'] == $b['count'])
  2771. {
  2772. return 0;
  2773. }
  2774. return ($a['count'] > $b['count']) ? -1 : 1;
  2775. }
  2776. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  2777. $sReadyScript = '';
  2778. $aDependsOn = array();
  2779. $sFormPrefix = '2_';
  2780. foreach($aList as $sAttCode => $oAttDef)
  2781. {
  2782. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  2783. if (count($aPrerequisites) > 0)
  2784. {
  2785. // When 'enabling' a field, all its prerequisites must be enabled too
  2786. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
  2787. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  2788. }
  2789. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  2790. if (count($aDependents) > 0)
  2791. {
  2792. // When 'disabling' a field, all its dependent fields must be disabled too
  2793. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
  2794. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  2795. }
  2796. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  2797. {
  2798. if ($oAttDef->GetEditClass() == 'One Way Password')
  2799. {
  2800. $sTip = "Unknown values";
  2801. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  2802. $oDummyObj->Set($sAttCode, null);
  2803. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2804. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'"> ? </div>';
  2805. $sReadyScript .= 'ToogleField(false, \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  2806. }
  2807. else
  2808. {
  2809. $iCount = count($aValues[$sAttCode]);
  2810. if ($iCount == 1)
  2811. {
  2812. // Homogenous value
  2813. reset($aValues[$sAttCode]);
  2814. $aKeys = array_keys($aValues[$sAttCode]);
  2815. $currValue = $aKeys[0]; // The only value is the first key
  2816. //echo "<p>current value for $sAttCode : $currValue</p>";
  2817. $oDummyObj->Set($sAttCode, $currValue);
  2818. $aComments[$sAttCode] = '<input type="checkbox" checked id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2819. $aComments[$sAttCode] .= '<div class="mono_value">1</div>';
  2820. }
  2821. else
  2822. {
  2823. // Non-homogenous value
  2824. $aMultiValues = $aValues[$sAttCode];
  2825. uasort($aMultiValues, 'MyComparison');
  2826. $iMaxCount = 5;
  2827. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."</b><ul>";
  2828. $index = 0;
  2829. foreach($aMultiValues as $sCurrValue => $aVal)
  2830. {
  2831. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  2832. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  2833. $index++;
  2834. if ($iMaxCount == $index)
  2835. {
  2836. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aMultiValues) - $iMaxCount)."</li>";
  2837. break;
  2838. }
  2839. }
  2840. $sTip .= "</ul></p>";
  2841. $sTip = addslashes($sTip);
  2842. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  2843. $oDummyObj->Set($sAttCode, null);
  2844. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2845. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.$iCount.'</div>';
  2846. }
  2847. $sReadyScript .= 'ToogleField('.(($iCount == 1) ? 'true': 'false').', \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  2848. }
  2849. }
  2850. }
  2851. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  2852. if (($sStateAttCode != '') && ($oDummyObj->GetState() == ''))
  2853. {
  2854. // Hmmm, it's not gonna work like this ! Set a default value for the "state"
  2855. // Maybe we should use the "state" that is the most common among the objects...
  2856. $aMultiValues = $aValues[$sStateAttCode];
  2857. uasort($aMultiValues, 'MyComparison');
  2858. foreach($aMultiValues as $sCurrValue => $aVal)
  2859. {
  2860. $oDummyObj->Set($sStateAttCode, $sCurrValue);
  2861. break;
  2862. }
  2863. //$oStateAtt = MetaModel::GetAttributeDef($sClass, $sStateAttCode);
  2864. //$oDummyObj->Set($sStateAttCode, $oStateAtt->GetDefaultValue());
  2865. }
  2866. $oP->add("<div class=\"page_header\">\n");
  2867. $oP->add("<h1>".$oDummyObj->GetIcon()."&nbsp;".Dict::Format('UI:Modify_M_ObjectsOf_Class_OutOf_N', $iAllowedCount, $sClass, $iAllowedCount)."</h1>\n");
  2868. $oP->add("</div>\n");
  2869. $oP->add("<div class=\"wizContainer\">\n");
  2870. $sDisableFields = json_encode($aExcludeAttributes);
  2871. $aParams = array
  2872. (
  2873. 'fieldsComments' => $aComments,
  2874. 'noRelations' => true,
  2875. 'custom_operation' => $sCustomOperation,
  2876. 'custom_button' => Dict::S('UI:Button:PreviewModifications'),
  2877. 'selectObj' => $sSelectedObj,
  2878. 'preview_mode' => true,
  2879. 'disabled_fields' => $sDisableFields,
  2880. 'disable_plugins' => true
  2881. );
  2882. $aParams = $aParams + $aContextData; // merge keeping associations
  2883. $oDummyObj->DisplayModifyForm($oP, $aParams);
  2884. $oP->add("</div>\n");
  2885. $oP->add_ready_script($sReadyScript);
  2886. $oP->add_ready_script(
  2887. <<<EOF
  2888. $('.wizContainer button.cancel').unbind('click');
  2889. $('.wizContainer button.cancel').click( function() { window.location.href = '$sCancelUrl'; } );
  2890. EOF
  2891. );
  2892. } // Else no object selected ???
  2893. else
  2894. {
  2895. $oP->p("No object selected !, nothing to do");
  2896. }
  2897. }
  2898. /**
  2899. * Process the reply made from a form built with DisplayBulkModifyForm
  2900. */
  2901. public static function DoBulkModify($oP, $sClass, $aSelectedObj, $sCustomOperation, $bPreview, $sCancelUrl, $aContextData = array())
  2902. {
  2903. $aHeaders = array(
  2904. 'form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')),
  2905. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  2906. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  2907. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  2908. );
  2909. $aRows = array();
  2910. $oP->add("<div class=\"page_header\">\n");
  2911. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass)."</h1>\n");
  2912. $oP->add("</div>\n");
  2913. $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass));
  2914. if (!$bPreview)
  2915. {
  2916. // Not in preview mode, do the update for real
  2917. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  2918. if (!utils::IsTransactionValid($sTransactionId, false))
  2919. {
  2920. throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  2921. }
  2922. utils::RemoveTransaction($sTransactionId);
  2923. }
  2924. foreach($aSelectedObj as $iId)
  2925. {
  2926. $oObj = MetaModel::GetObject($sClass, $iId);
  2927. $aErrors = $oObj->UpdateObjectFromPostedForm('');
  2928. $bResult = (count($aErrors) == 0);
  2929. if ($bResult)
  2930. {
  2931. list($bResult, $aErrors) = $oObj->CheckToWrite(true /* Enforce Read-only fields */);
  2932. }
  2933. if ($bPreview)
  2934. {
  2935. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError');
  2936. }
  2937. else
  2938. {
  2939. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  2940. }
  2941. $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL;
  2942. $sChecked = $bResult ? 'checked' : '';
  2943. $sDisabled = $bResult ? '' : 'disabled';
  2944. $aRows[] = array(
  2945. 'form::select' => "<input type=\"checkbox\" class=\"selectList\" $sChecked $sDisabled\"></input>",
  2946. 'object' => $oObj->GetHyperlink(),
  2947. 'status' => $sStatus,
  2948. 'errors' => '<p>'.($bResult ? '': implode('</p><p>', $aErrors)).'</p>',
  2949. '@class' => $sCSSClass,
  2950. );
  2951. if ($bResult && (!$bPreview))
  2952. {
  2953. $oObj->DBUpdate();
  2954. }
  2955. }
  2956. $oP->Table($aHeaders, $aRows);
  2957. if ($bPreview)
  2958. {
  2959. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  2960. // Form to submit:
  2961. $oP->add("<form method=\"post\" action=\"$sFormAction\" enctype=\"multipart/form-data\">\n");
  2962. $aDefaults = utils::ReadParam('default', array());
  2963. $oAppContext = new ApplicationContext();
  2964. $oP->add($oAppContext->GetForForm());
  2965. foreach ($aContextData as $sKey => $value)
  2966. {
  2967. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  2968. }
  2969. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  2970. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  2971. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n");
  2972. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  2973. $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='$sCancelUrl'\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  2974. $oP->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:ModifyAll')."</span></button>\n");
  2975. foreach($_POST as $sKey => $value)
  2976. {
  2977. if (preg_match('/attr_(.+)/', $sKey, $aMatches))
  2978. {
  2979. // Beware: some values (like durations) are passed as arrays
  2980. if (is_array($value))
  2981. {
  2982. foreach($value as $vKey => $vValue)
  2983. {
  2984. $oP->add("<input type=\"hidden\" name=\"{$sKey}[$vKey]\" value=\"$vValue\">\n");
  2985. }
  2986. }
  2987. else
  2988. {
  2989. $oP->add("<input type=\"hidden\" name=\"$sKey\" value=\"$value\">\n");
  2990. }
  2991. }
  2992. }
  2993. $oP->add("</form>\n");
  2994. }
  2995. else
  2996. {
  2997. $oP->add("<button type=\"button\" onClick=\"window.location.href='$sCancelUrl'\" class=\"action\"><span>".Dict::S('UI:Button:Done')."</span></button>\n");
  2998. }
  2999. }
  3000. /**
  3001. * Perform all the needed checks to delete one (or more) objects
  3002. */
  3003. public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = array())
  3004. {
  3005. $oDeletionPlan = new DeletionPlan();
  3006. foreach($aObjects as $oObj)
  3007. {
  3008. if ($bPreview)
  3009. {
  3010. $oObj->CheckToDelete($oDeletionPlan);
  3011. }
  3012. else
  3013. {
  3014. $oObj->DBDeleteTracked(CMDBObject::GetCurrentChange(), null, $oDeletionPlan);
  3015. }
  3016. }
  3017. if ($bPreview)
  3018. {
  3019. if (count($aObjects) == 1)
  3020. {
  3021. $oObj = $aObjects[0];
  3022. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName())."</h1>\n");
  3023. }
  3024. else
  3025. {
  3026. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3027. }
  3028. // Explain what should be done
  3029. //
  3030. $aDisplayData = array();
  3031. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3032. {
  3033. foreach ($aDeletes as $iId => $aData)
  3034. {
  3035. $oToDelete = $aData['to_delete'];
  3036. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  3037. if (array_key_exists('issue', $aData))
  3038. {
  3039. if ($bAutoDel)
  3040. {
  3041. if (isset($aData['requested_explicitely']))
  3042. {
  3043. $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']);
  3044. }
  3045. else
  3046. {
  3047. $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']);
  3048. }
  3049. }
  3050. else
  3051. {
  3052. $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']);
  3053. }
  3054. }
  3055. else
  3056. {
  3057. if ($bAutoDel)
  3058. {
  3059. if (isset($aData['requested_explicitely']))
  3060. {
  3061. $sConsequence = ''; // not applicable
  3062. }
  3063. else
  3064. {
  3065. $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically');
  3066. }
  3067. }
  3068. else
  3069. {
  3070. $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually');
  3071. }
  3072. }
  3073. $aDisplayData[] = array(
  3074. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3075. 'object' => $oToDelete->GetHyperLink(),
  3076. 'consequence' => $sConsequence,
  3077. );
  3078. }
  3079. }
  3080. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  3081. {
  3082. foreach ($aToUpdate as $iId => $aData)
  3083. {
  3084. $oToUpdate = $aData['to_reset'];
  3085. if (array_key_exists('issue', $aData))
  3086. {
  3087. $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']);
  3088. }
  3089. else
  3090. {
  3091. $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']);
  3092. }
  3093. $aDisplayData[] = array(
  3094. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3095. 'object' => $oToUpdate->GetHyperLink(),
  3096. 'consequence' => $sConsequence,
  3097. );
  3098. }
  3099. }
  3100. $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects);
  3101. if ($iImpactedIndirectly > 0)
  3102. {
  3103. if (count($aObjects) == 1)
  3104. {
  3105. $oObj = $aObjects[0];
  3106. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName()));
  3107. }
  3108. else
  3109. {
  3110. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly));
  3111. }
  3112. $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'));
  3113. }
  3114. if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper())
  3115. {
  3116. $aDisplayConfig = array();
  3117. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3118. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3119. $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'));
  3120. $oP->table($aDisplayConfig, $aDisplayData);
  3121. }
  3122. if ($oDeletionPlan->FoundStopper())
  3123. {
  3124. if ($oDeletionPlan->FoundSecurityIssue())
  3125. {
  3126. $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed'));
  3127. }
  3128. elseif ($oDeletionPlan->FoundManualOperation())
  3129. {
  3130. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3131. }
  3132. else // $bFoundManualOp
  3133. {
  3134. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3135. }
  3136. $oAppContext = new ApplicationContext();
  3137. $oP->add("<form method=\"post\">\n");
  3138. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  3139. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3140. $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3141. $oP->add($oAppContext->GetForForm());
  3142. $oP->add("</form>\n");
  3143. }
  3144. else
  3145. {
  3146. if (count($aObjects) == 1)
  3147. {
  3148. $oObj = $aObjects[0];
  3149. $id = $oObj->GetKey();
  3150. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()).'</h1>');
  3151. }
  3152. else
  3153. {
  3154. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)).'</h1>');
  3155. }
  3156. foreach($aObjects as $oObj)
  3157. {
  3158. $aKeys[] = $oObj->GetKey();
  3159. }
  3160. $oFilter = new DBObjectSearch($sClass);
  3161. $oFilter->AddCondition('id', $aKeys, 'IN');
  3162. $oSet = new CMDBobjectSet($oFilter);
  3163. $oP->add('<div id="0">');
  3164. CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false));
  3165. $oP->add("</div>\n");
  3166. $oP->add("<form method=\"post\">\n");
  3167. foreach ($aContextData as $sKey => $value)
  3168. {
  3169. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  3170. }
  3171. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  3172. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  3173. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  3174. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  3175. foreach($aObjects as $oObj)
  3176. {
  3177. $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\">\n");
  3178. }
  3179. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3180. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3181. $oAppContext = new ApplicationContext();
  3182. $oP->add($oAppContext->GetForForm());
  3183. $oP->add("</form>\n");
  3184. }
  3185. }
  3186. else // if ($bPreview)...
  3187. {
  3188. // Execute the deletion
  3189. //
  3190. if (count($aObjects) == 1)
  3191. {
  3192. $oObj = $aObjects[0];
  3193. $oP->add("<h1>".Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName())."</h1>\n");
  3194. }
  3195. else
  3196. {
  3197. $oP->add("<h1>".Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3198. }
  3199. // Security - do not allow the user to force a forbidden delete by the mean of page arguments...
  3200. if ($oDeletionPlan->FoundSecurityIssue())
  3201. {
  3202. throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete'));
  3203. }
  3204. if ($oDeletionPlan->FoundManualOperation())
  3205. {
  3206. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded'));
  3207. }
  3208. if ($oDeletionPlan->FoundManualDelete())
  3209. {
  3210. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies'));
  3211. }
  3212. // Report deletions
  3213. //
  3214. $aDisplayData = array();
  3215. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3216. {
  3217. foreach ($aDeletes as $iId => $aData)
  3218. {
  3219. $oToDelete = $aData['to_delete'];
  3220. if (isset($aData['requested_explicitely']))
  3221. {
  3222. $sMessage = Dict::S('UI:Delete:Deleted');
  3223. }
  3224. else
  3225. {
  3226. $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted');
  3227. }
  3228. $aDisplayData[] = array(
  3229. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3230. 'object' => $oToDelete->GetName(),
  3231. 'consequence' => $sMessage,
  3232. );
  3233. }
  3234. }
  3235. // Report updates
  3236. //
  3237. foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate)
  3238. {
  3239. foreach ($aToUpdate as $iId => $aData)
  3240. {
  3241. $oToUpdate = $aData['to_reset'];
  3242. $aDisplayData[] = array(
  3243. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3244. 'object' => $oToUpdate->GetHyperLink(),
  3245. 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']),
  3246. );
  3247. }
  3248. }
  3249. // Report automatic jobs
  3250. //
  3251. if ($oDeletionPlan->GetTargetCount() > 0)
  3252. {
  3253. if (count($aObjects) == 1)
  3254. {
  3255. $oObj = $aObjects[0];
  3256. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()));
  3257. }
  3258. else
  3259. {
  3260. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)));
  3261. }
  3262. $aDisplayConfig = array();
  3263. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3264. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3265. $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+'));
  3266. $oP->table($aDisplayConfig, $aDisplayData);
  3267. }
  3268. }
  3269. }
  3270. }
  3271. ?>