cmdbabstract.class.inc.php 155 KB

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