cmdbabstract.class.inc.php 169 KB

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