cmdbabstract.class.inc.php 127 KB

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