cmdbabstract.class.inc.php 141 KB

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