cmdbabstract.class.inc.php 127 KB

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