cmdbabstract.class.inc.php 155 KB

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