cmdbabstract.class.inc.php 150 KB

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