cmdbabstract.class.inc.php 158 KB

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