cmdbabstract.class.inc.php 129 KB

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