cmdbabstract.class.inc.php 126 KB

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