cmdbabstract.class.inc.php 136 KB

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