cmdbabstract.class.inc.php 168 KB

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