dbobject.class.php 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * All objects to be displayed in the application (either as a list or as details)
  20. * must implement this interface.
  21. */
  22. interface iDisplay
  23. {
  24. /**
  25. * Maps the given context parameter name to the appropriate filter/search code for this class
  26. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  27. * @return string Filter code, i.e. 'customer_id'
  28. */
  29. public static function MapContextParam($sContextParam);
  30. /**
  31. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  32. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  33. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  34. * To Be overridden by derived classes
  35. * @param void
  36. * @return String The desired higlight class for the object/row
  37. */
  38. public function GetHilightClass();
  39. /**
  40. * Returns the relative path to the page that handles the display of the object
  41. * @return string
  42. */
  43. public static function GetUIPage();
  44. /**
  45. * Displays the details of the object
  46. */
  47. public function DisplayDetails(WebPage $oPage, $bEditMode = false);
  48. }
  49. /**
  50. * Class dbObject: the root of persistent classes
  51. *
  52. * @copyright Copyright (C) 2010-2015 Combodo SARL
  53. * @license http://opensource.org/licenses/AGPL-3.0
  54. */
  55. require_once('metamodel.class.php');
  56. require_once('deletionplan.class.inc.php');
  57. require_once('mutex.class.inc.php');
  58. /**
  59. * A persistent object, as defined by the metamodel
  60. *
  61. * @package iTopORM
  62. */
  63. abstract class DBObject implements iDisplay
  64. {
  65. private static $m_aMemoryObjectsByClass = array();
  66. private static $m_aBulkInsertItems = array(); // class => array of ('table' => array of (array of <sql_value>))
  67. private static $m_aBulkInsertCols = array(); // class => array of ('table' => array of <sql_column>)
  68. private static $m_bBulkInsert = false;
  69. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  70. private $m_iKey = null;
  71. private $m_aCurrValues = array();
  72. protected $m_aOrigValues = array();
  73. protected $m_aExtendedData = null;
  74. private $m_bDirty = false; // Means: "a modification is ongoing"
  75. // The object may have incorrect external keys, then any attempt of reload must be avoided
  76. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  77. // if null, then the check has to be performed again to know the status
  78. protected $m_bSecurityIssue = null;
  79. protected $m_aCheckIssues = null;
  80. protected $m_aDeleteIssues = null;
  81. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  82. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  83. protected $m_aModifiedAtt = array(); // list of (potentially) modified sAttCodes
  84. protected $m_aSynchroData = null; // Set of Synch data related to this object
  85. protected $m_sHighlightCode = null;
  86. protected $m_aCallbacks = array();
  87. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  88. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  89. {
  90. if (!empty($aRow))
  91. {
  92. $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  93. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  94. $this->m_aModifiedAtt = array();
  95. return;
  96. }
  97. // Creation of a brand new object
  98. //
  99. $this->m_iKey = self::GetNextTempId(get_class($this));
  100. // set default values
  101. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  102. {
  103. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  104. $this->m_aOrigValues[$sAttCode] = null;
  105. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  106. {
  107. // This field has to be read from the DB
  108. // Leave the flag unset (optimization)
  109. }
  110. else
  111. {
  112. // No need to trigger a reload for that attribute
  113. // Let's consider it as being already fully loaded
  114. $this->m_aLoadedAtt[$sAttCode] = true;
  115. }
  116. }
  117. }
  118. // Read-only <=> Written once (archive)
  119. public function RegisterAsDirty()
  120. {
  121. // While the object may be written to the DB, it is NOT possible to reload it
  122. // or at least not possible to reload it the same way
  123. $this->m_bDirty = true;
  124. }
  125. public function IsNew()
  126. {
  127. return (!$this->m_bIsInDB);
  128. }
  129. // Returns an Id for memory objects
  130. static protected function GetNextTempId($sClass)
  131. {
  132. $sRootClass = MetaModel::GetRootClass($sClass);
  133. if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
  134. {
  135. self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
  136. }
  137. self::$m_aMemoryObjectsByClass[$sRootClass]++;
  138. return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
  139. }
  140. public function __toString()
  141. {
  142. $sRet = '';
  143. $sClass = get_class($this);
  144. $sRootClass = MetaModel::GetRootClass($sClass);
  145. $iPKey = $this->GetKey();
  146. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  147. $sRet .= "<ul class=\"treeview\">\n";
  148. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  149. {
  150. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  151. }
  152. $sRet .= "</ul>";
  153. return $sRet;
  154. }
  155. // Restore initial values... mmmm, to be discussed
  156. public function DBRevert()
  157. {
  158. $this->Reload();
  159. }
  160. protected function IsFullyLoaded()
  161. {
  162. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  163. {
  164. if (!$oAttDef->LoadInObject()) continue;
  165. if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
  166. {
  167. return false;
  168. }
  169. }
  170. return true;
  171. }
  172. public function Reload()
  173. {
  174. assert($this->m_bIsInDB);
  175. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false/*, $this->m_bAllowAllData*/);
  176. if (empty($aRow))
  177. {
  178. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  179. }
  180. $this->FromRow($aRow);
  181. // Process linked set attributes
  182. //
  183. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  184. {
  185. if (!$oAttDef->IsLinkSet()) continue;
  186. // Load the link information
  187. $sLinkClass = $oAttDef->GetLinkedClass();
  188. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  189. // The class to target is not the current class, because if this is a derived class,
  190. // it may differ from the target class, then things start to become confusing
  191. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  192. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  193. $oMyselfSearch = new DBObjectSearch($sMyClass);
  194. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  195. $oLinkSearch = new DBObjectSearch($sLinkClass);
  196. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  197. $oLinks = new DBObjectSet($oLinkSearch);
  198. $this->m_aCurrValues[$sAttCode] = $oLinks;
  199. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  200. $this->m_aLoadedAtt[$sAttCode] = true;
  201. }
  202. $this->m_bFullyLoaded = true;
  203. $this->m_aModifiedAtt = array();
  204. }
  205. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  206. {
  207. if (strlen($sClassAlias) == 0)
  208. {
  209. // Default to the current class
  210. $sClassAlias = get_class($this);
  211. }
  212. $this->m_iKey = null;
  213. $this->m_bIsInDB = true;
  214. $this->m_aCurrValues = array();
  215. $this->m_aOrigValues = array();
  216. $this->m_aLoadedAtt = array();
  217. $this->m_bCheckStatus = true;
  218. // Get the key
  219. //
  220. $sKeyField = $sClassAlias."id";
  221. if (!array_key_exists($sKeyField, $aRow))
  222. {
  223. // #@# Bug ?
  224. throw new CoreException("Missing key for class '".get_class($this)."'");
  225. }
  226. $iPKey = $aRow[$sKeyField];
  227. if (!self::IsValidPKey($iPKey))
  228. {
  229. if (is_null($iPKey))
  230. {
  231. throw new CoreException("Missing object id in query result (found null)");
  232. }
  233. else
  234. {
  235. throw new CoreException("An object id must be an integer value ($iPKey)");
  236. }
  237. }
  238. $this->m_iKey = $iPKey;
  239. // Build the object from an array of "attCode"=>"value")
  240. //
  241. $bFullyLoaded = true; // ... set to false if any attribute is not found
  242. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  243. {
  244. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  245. }
  246. else
  247. {
  248. $aAttList = $aAttToLoad[$sClassAlias];
  249. }
  250. foreach($aAttList as $sAttCode=>$oAttDef)
  251. {
  252. // Skip links (could not be loaded by the mean of this query)
  253. if ($oAttDef->IsLinkSet()) continue;
  254. if (!$oAttDef->LoadInObject()) continue;
  255. // Note: we assume that, for a given attribute, if it can be loaded,
  256. // then one column will be found with an empty suffix, the others have a suffix
  257. // Take care: the function isset will return false in case the value is null,
  258. // which is something that could happen on open joins
  259. $sAttRef = $sClassAlias.$sAttCode;
  260. if (array_key_exists($sAttRef, $aRow))
  261. {
  262. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  263. $this->m_aCurrValues[$sAttCode] = $value;
  264. if (is_object($value))
  265. {
  266. $this->m_aOrigValues[$sAttCode] = clone $value;
  267. }
  268. else
  269. {
  270. $this->m_aOrigValues[$sAttCode] = $value;
  271. }
  272. $this->m_aLoadedAtt[$sAttCode] = true;
  273. }
  274. else
  275. {
  276. // This attribute was expected and not found in the query columns
  277. $bFullyLoaded = false;
  278. }
  279. }
  280. // Load extended data
  281. if ($aExtendedDataSpec != null)
  282. {
  283. $aExtendedDataSpec['table'];
  284. foreach($aExtendedDataSpec['fields'] as $sColumn)
  285. {
  286. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  287. if (array_key_exists($sColRef, $aRow))
  288. {
  289. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  290. }
  291. }
  292. }
  293. return $bFullyLoaded;
  294. }
  295. public function Set($sAttCode, $value)
  296. {
  297. if ($sAttCode == 'finalclass')
  298. {
  299. // Ignore it - this attribute is set upon object creation and that's it
  300. return false;
  301. }
  302. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  303. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  304. {
  305. // First time Set is called... ensure that the object gets fully loaded
  306. // Otherwise we would lose the values on a further Reload
  307. // + consistency does not make sense !
  308. $this->Reload();
  309. }
  310. if ($oAttDef->IsExternalKey())
  311. {
  312. if (is_object($value))
  313. {
  314. // Setting an external key with a whole object (instead of just an ID)
  315. // let's initialize also the external fields that depend on it
  316. // (useful when building objects in memory and not from a query)
  317. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  318. {
  319. throw new CoreUnexpectedValue("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
  320. }
  321. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  322. {
  323. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  324. {
  325. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  326. }
  327. }
  328. }
  329. else if ($this->m_aCurrValues[$sAttCode] != $value)
  330. {
  331. // Setting an external key, but no any other information is available...
  332. // Invalidate the corresponding fields so that they get reloaded in case they are needed (See Get())
  333. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  334. {
  335. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  336. {
  337. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  338. unset($this->m_aLoadedAtt[$sCode]);
  339. }
  340. }
  341. }
  342. }
  343. if(!$oAttDef->IsScalar() && !is_object($value))
  344. {
  345. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  346. }
  347. if($oAttDef->IsLinkSet())
  348. {
  349. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  350. {
  351. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  352. }
  353. $oObjectSet = $value;
  354. $sSetClass = $oObjectSet->GetClass();
  355. $sLinkClass = $oAttDef->GetLinkedClass();
  356. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  357. if ($sSetClass != $sLinkClass)
  358. {
  359. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  360. }
  361. }
  362. $realvalue = $oAttDef->MakeRealValue($value, $this);
  363. $this->m_aCurrValues[$sAttCode] = $realvalue;
  364. $this->m_aModifiedAtt[$sAttCode] = true;
  365. // The object has changed, reset caches
  366. $this->m_bCheckStatus = null;
  367. // Make sure we do not reload it anymore... before saving it
  368. $this->RegisterAsDirty();
  369. // This function is eligible as a lifecycle action: returning true upon success is a must
  370. return true;
  371. }
  372. public function GetLabel($sAttCode)
  373. {
  374. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  375. return $oAttDef->GetLabel();
  376. }
  377. public function Get($sAttCode)
  378. {
  379. if (($iPos = strpos($sAttCode, '->')) === false)
  380. {
  381. return $this->GetStrict($sAttCode);
  382. }
  383. else
  384. {
  385. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  386. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  387. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  388. {
  389. throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
  390. }
  391. $oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode);
  392. if (!is_null($oExtFieldAtt))
  393. {
  394. return $this->GetStrict($oExtFieldAtt->GetCode());
  395. }
  396. else
  397. {
  398. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  399. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  400. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  401. if (is_null($oRemoteObj))
  402. {
  403. return '';
  404. }
  405. else
  406. {
  407. return $oRemoteObj->Get($sRemoteAttCode);
  408. }
  409. }
  410. }
  411. }
  412. public function GetStrict($sAttCode)
  413. {
  414. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  415. if (!$oAttDef->LoadInObject())
  416. {
  417. $sParentAttCode = $oAttDef->GetParentAttCode();
  418. $parentValue = $this->GetStrict($sParentAttCode);
  419. $value = $oAttDef->GetValue($parentValue, $this);
  420. }
  421. else
  422. {
  423. if (isset($this->m_aLoadedAtt[$sAttCode]))
  424. {
  425. // Standard case... we have the information directly
  426. }
  427. elseif ($this->m_bIsInDB && !$this->m_bDirty)
  428. {
  429. // Lazy load (polymorphism): complete by reloading the entire object
  430. // #@# non-scalar attributes.... handle that differently?
  431. $oKPI = new ExecutionKPI();
  432. $this->Reload();
  433. $oKPI->ComputeStats('Reload', get_class($this).'/'.$sAttCode);
  434. }
  435. elseif ($sAttCode == 'friendlyname')
  436. {
  437. // The friendly name is not computed and the object is dirty
  438. // Todo: implement the computation of the friendly name based on sprintf()
  439. //
  440. $this->m_aCurrValues[$sAttCode] = '';
  441. }
  442. else
  443. {
  444. // Not loaded... is it related to an external key?
  445. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  446. {
  447. // Let's get the object and compute all of the corresponding attributes
  448. // (i.e not only the requested attribute)
  449. //
  450. $sExtKeyAttCode = $oAttDef->GetKeyAttCode();
  451. if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
  452. {
  453. $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  454. // Note: "allow all data" must be enabled because the external fields are always visible
  455. // to the current user even if this is not the case for the remote object
  456. // This is consistent with the behavior of the lists
  457. $oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
  458. }
  459. else
  460. {
  461. $oRemote = null;
  462. }
  463. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  464. {
  465. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sExtKeyAttCode))
  466. {
  467. if ($oRemote)
  468. {
  469. $this->m_aCurrValues[$sCode] = $oRemote->Get($oDef->GetExtAttCode());
  470. }
  471. else
  472. {
  473. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  474. }
  475. $this->m_aLoadedAtt[$sCode] = true;
  476. }
  477. }
  478. }
  479. }
  480. $value = $this->m_aCurrValues[$sAttCode];
  481. }
  482. if ($value instanceof DBObjectSet)
  483. {
  484. $value->Rewind();
  485. }
  486. return $value;
  487. }
  488. public function GetOriginal($sAttCode)
  489. {
  490. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  491. {
  492. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  493. }
  494. return $this->m_aOrigValues[$sAttCode];
  495. }
  496. /**
  497. * Returns data loaded by the mean of a dynamic and explicit JOIN
  498. */
  499. public function GetExtendedData()
  500. {
  501. return $this->m_aExtendedData;
  502. }
  503. /**
  504. * Set the HighlightCode if the given code has a greater rank than the current HilightCode
  505. * @param string $sCode
  506. * @return void
  507. */
  508. protected function SetHighlightCode($sCode)
  509. {
  510. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  511. $fCurrentRank = 0.0;
  512. if (($this->m_sHighlightCode !== null) && array_key_exists($this->m_sHighlightCode, $aHighlightScale))
  513. {
  514. $fCurrentRank = $aHighlightScale[$this->m_sHighlightCode]['rank'];
  515. }
  516. if (array_key_exists($sCode, $aHighlightScale))
  517. {
  518. $fRank = $aHighlightScale[$sCode]['rank'];
  519. if ($fRank > $fCurrentRank)
  520. {
  521. $this->m_sHighlightCode = $sCode;
  522. }
  523. }
  524. }
  525. /**
  526. * Get the current HighlightCode
  527. * @return string The Hightlight code (null if none set, meaning rank = 0)
  528. */
  529. protected function GetHighlightCode()
  530. {
  531. return $this->m_sHighlightCode;
  532. }
  533. protected function ComputeHighlightCode()
  534. {
  535. // First if the state defines a HiglightCode, apply it
  536. $sState = $this->GetState();
  537. if ($sState != '')
  538. {
  539. $sCode = MetaModel::GetHighlightCode(get_class($this), $sState);
  540. $this->SetHighlightCode($sCode);
  541. }
  542. // The check for each StopWatch if a HighlightCode is effective
  543. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  544. {
  545. if ($oAttDef instanceof AttributeStopWatch)
  546. {
  547. $oStopWatch = $this->Get($sAttCode);
  548. $sCode = $oStopWatch->GetHighlightCode();
  549. if ($sCode !== '')
  550. {
  551. $this->SetHighlightCode($sCode);
  552. }
  553. }
  554. }
  555. return $this->GetHighlightCode();
  556. }
  557. /**
  558. * Updates the value of an external field by (re)loading the object
  559. * corresponding to the external key and getting the value from it
  560. *
  561. * UNUSED ?
  562. *
  563. * @param string $sAttCode Attribute code of the external field to update
  564. * @return void
  565. */
  566. protected function UpdateExternalField($sAttCode)
  567. {
  568. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  569. if ($oAttDef->IsExternalField())
  570. {
  571. $sTargetClass = $oAttDef->GetTargetClass();
  572. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  573. // Note: "allow all data" must be enabled because the external fields are always visible
  574. // to the current user even if this is not the case for the remote object
  575. // This is consistent with the behavior of the lists
  576. $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
  577. if (is_object($oObj))
  578. {
  579. $value = $oObj->Get($oAttDef->GetExtAttCode());
  580. $this->Set($sAttCode, $value);
  581. }
  582. }
  583. }
  584. public function ComputeValues()
  585. {
  586. }
  587. // Compute scalar attributes that depend on any other type of attribute
  588. final public function DoComputeValues()
  589. {
  590. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  591. // First check that we are not currently computing the fields
  592. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  593. foreach (debug_backtrace() as $aCallInfo)
  594. {
  595. if (!array_key_exists("class", $aCallInfo)) continue;
  596. if ($aCallInfo["class"] != get_class($this)) continue;
  597. if ($aCallInfo["function"] != "ComputeValues") continue;
  598. return; //skip!
  599. }
  600. $this->ComputeValues();
  601. }
  602. public function GetAsHTML($sAttCode, $bLocalize = true)
  603. {
  604. $sClass = get_class($this);
  605. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  606. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  607. {
  608. //return $this->Get($sAttCode.'_friendlyname');
  609. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  610. $iTargetKey = $this->Get($sAttCode);
  611. if ($iTargetKey < 0)
  612. {
  613. // the key points to an object that exists only in memory... no hyperlink points to it yet
  614. return '';
  615. }
  616. else
  617. {
  618. $sLabel = $this->Get($sAttCode.'_friendlyname');
  619. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  620. }
  621. }
  622. // That's a standard attribute (might be an ext field or a direct field, etc.)
  623. return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
  624. }
  625. public function GetEditValue($sAttCode)
  626. {
  627. $sClass = get_class($this);
  628. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  629. if ($oAtt->IsExternalKey())
  630. {
  631. $sTargetClass = $oAtt->GetTargetClass();
  632. if ($this->IsNew())
  633. {
  634. // The current object exists only in memory, don't try to query it in the DB !
  635. // instead let's query for the object pointed by the external key, and get its name
  636. $targetObjId = $this->Get($sAttCode);
  637. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  638. if (is_object($oTargetObj))
  639. {
  640. $sEditValue = $oTargetObj->GetName();
  641. }
  642. else
  643. {
  644. $sEditValue = 0;
  645. }
  646. }
  647. else
  648. {
  649. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  650. }
  651. }
  652. else
  653. {
  654. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
  655. }
  656. return $sEditValue;
  657. }
  658. public function GetAsXML($sAttCode, $bLocalize = true)
  659. {
  660. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  661. return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
  662. }
  663. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  664. {
  665. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  666. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  667. }
  668. public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
  669. {
  670. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  671. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
  672. }
  673. public function GetOriginalAsXML($sAttCode, $bLocalize = true)
  674. {
  675. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  676. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
  677. }
  678. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  679. {
  680. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  681. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  682. }
  683. public static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true)
  684. {
  685. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  686. // Safety net
  687. //
  688. if (empty($sLabel))
  689. {
  690. // If the object if not issued from a query but constructed programmatically
  691. // the label may be empty. In this case run a query to get the object's friendly name
  692. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
  693. if (is_object($oTmpObj))
  694. {
  695. $sLabel = $oTmpObj->GetName();
  696. }
  697. else
  698. {
  699. // May happen in case the target object is not in the list of allowed values for this attribute
  700. $sLabel = "<em>$sObjClass::$sObjKey</em>";
  701. }
  702. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  703. }
  704. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  705. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  706. if (strlen($sUrl) > 0)
  707. {
  708. return "<a href=\"$sUrl\" title=\"$sHint\">$sLabel</a>";
  709. }
  710. else
  711. {
  712. return $sLabel;
  713. }
  714. }
  715. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  716. {
  717. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext);
  718. }
  719. public static function ComputeStandardUIPage($sClass)
  720. {
  721. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  722. if (!isset($aUIPagesCache[$sClass]))
  723. {
  724. $UIPage = false;
  725. if (is_callable("$sClass::GetUIPage"))
  726. {
  727. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  728. }
  729. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  730. }
  731. $sPage = $aUIPagesCache[$sClass];
  732. return $sPage;
  733. }
  734. public static function GetUIPage()
  735. {
  736. return 'UI.php';
  737. }
  738. // could be in the metamodel ?
  739. public static function IsValidPKey($value)
  740. {
  741. return ((string)$value === (string)(int)$value);
  742. }
  743. public function GetKey()
  744. {
  745. return $this->m_iKey;
  746. }
  747. public function SetKey($iNewKey)
  748. {
  749. if (!self::IsValidPKey($iNewKey))
  750. {
  751. throw new CoreException("An object id must be an integer value ($iNewKey)");
  752. }
  753. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  754. {
  755. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  756. }
  757. $this->m_iKey = $iNewKey;
  758. }
  759. /**
  760. * Get the icon representing this object
  761. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  762. * @return string Either the full IMG tag ($bImgTag == true) or just the URL to the icon file
  763. */
  764. public function GetIcon($bImgTag = true)
  765. {
  766. $sCode = $this->ComputeHighlightCode();
  767. if($sCode != '')
  768. {
  769. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  770. if (array_key_exists($sCode, $aHighlightScale))
  771. {
  772. $sIconUrl = $aHighlightScale[$sCode]['icon'];
  773. if($bImgTag)
  774. {
  775. return "<img src=\"$sIconUrl\" style=\"vertical-align:middle\"/>";
  776. }
  777. else
  778. {
  779. return $sIconUrl;
  780. }
  781. }
  782. }
  783. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  784. }
  785. /**
  786. * Gets the name of an object in a safe manner for displaying inside a web page
  787. * @return string
  788. */
  789. public function GetName()
  790. {
  791. return htmlentities($this->GetRawName(), ENT_QUOTES, 'UTF-8');
  792. }
  793. /**
  794. * Gets the raw name of an object, this is not safe for displaying inside a web page
  795. * since the " < > characters are not escaped and the name may contain some XSS script
  796. * instructions.
  797. * Use this function only for internal computations or for an output to a non-HTML destination
  798. * @return string
  799. */
  800. public function GetRawName()
  801. {
  802. return $this->Get('friendlyname');
  803. }
  804. public function GetState()
  805. {
  806. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  807. if (empty($sStateAttCode))
  808. {
  809. return '';
  810. }
  811. else
  812. {
  813. return $this->Get($sStateAttCode);
  814. }
  815. }
  816. public function GetStateLabel()
  817. {
  818. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  819. if (empty($sStateAttCode))
  820. {
  821. return '';
  822. }
  823. else
  824. {
  825. $sStateValue = $this->Get($sStateAttCode);
  826. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  827. }
  828. }
  829. public function GetStateDescription()
  830. {
  831. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  832. if (empty($sStateAttCode))
  833. {
  834. return '';
  835. }
  836. else
  837. {
  838. $sStateValue = $this->Get($sStateAttCode);
  839. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  840. }
  841. }
  842. /**
  843. * Overridable - Define attributes read-only from the end-user perspective
  844. *
  845. * @return array List of attcodes
  846. */
  847. public static function GetReadOnlyAttributes()
  848. {
  849. return null;
  850. }
  851. /**
  852. * Overridable - Get predefined objects (could be hardcoded)
  853. * The predefined objects will be synchronized with the DB at each install/upgrade
  854. * As soon as a class has predefined objects, then nobody can create nor delete objects
  855. * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
  856. */
  857. public static function GetPredefinedObjects()
  858. {
  859. return null;
  860. }
  861. /**
  862. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  863. * for the given attribute in the current state of the object
  864. * @param $sAttCode string $sAttCode The code of the attribute
  865. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  866. * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
  867. * @return integer Flags: the binary combination of the flags applicable to this attribute
  868. */
  869. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  870. {
  871. $iFlags = 0; // By default (if no life cycle) no flag at all
  872. $aReadOnlyAtts = $this->GetReadOnlyAttributes();
  873. if ($aReadOnlyAtts != null)
  874. {
  875. if (in_array($sAttCode, $aReadOnlyAtts))
  876. {
  877. return OPT_ATT_READONLY;
  878. }
  879. }
  880. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  881. if (!empty($sStateAttCode))
  882. {
  883. if ($sTargetState != '')
  884. {
  885. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  886. }
  887. else
  888. {
  889. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  890. }
  891. }
  892. $aReasons = array();
  893. $iSynchroFlags = 0;
  894. if ($this->InSyncScope())
  895. {
  896. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  897. }
  898. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  899. }
  900. /**
  901. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  902. * for the given attribute for the current state of the object considered as an INITIAL state
  903. * @param string $sAttCode The code of the attribute
  904. * @return integer Flags: the binary combination of the flags applicable to this attribute
  905. */
  906. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  907. {
  908. $iFlags = 0;
  909. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  910. if (!empty($sStateAttCode))
  911. {
  912. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  913. }
  914. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  915. }
  916. // check if the given (or current) value is suitable for the attribute
  917. // return true if successfull
  918. // return the error desciption otherwise
  919. public function CheckValue($sAttCode, $value = null)
  920. {
  921. if (!is_null($value))
  922. {
  923. $toCheck = $value;
  924. }
  925. else
  926. {
  927. $toCheck = $this->Get($sAttCode);
  928. }
  929. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  930. if (!$oAtt->IsWritable())
  931. {
  932. return true;
  933. }
  934. elseif ($oAtt->IsNull($toCheck))
  935. {
  936. if ($oAtt->IsNullAllowed())
  937. {
  938. return true;
  939. }
  940. else
  941. {
  942. return "Null not allowed";
  943. }
  944. }
  945. elseif ($oAtt->IsExternalKey())
  946. {
  947. if (!MetaModel::SkipCheckExtKeys())
  948. {
  949. $sTargetClass = $oAtt->GetTargetClass();
  950. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  951. if (is_null($oTargetObj))
  952. {
  953. return "Target object not found ($sTargetClass::$toCheck)";
  954. }
  955. }
  956. if ($oAtt->IsHierarchicalKey())
  957. {
  958. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  959. if ($toCheck == $this->GetKey())
  960. {
  961. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  962. }
  963. }
  964. }
  965. elseif ($oAtt->IsScalar())
  966. {
  967. $aValues = $oAtt->GetAllowedValues($this->ToArgsForQuery());
  968. if (count($aValues) > 0)
  969. {
  970. if (!array_key_exists($toCheck, $aValues))
  971. {
  972. return "Value not allowed [$toCheck]";
  973. }
  974. }
  975. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  976. {
  977. $iLen = strlen($toCheck);
  978. if ($iLen > $iMaxSize)
  979. {
  980. return "String too long (found $iLen, limited to $iMaxSize)";
  981. }
  982. }
  983. if (!$oAtt->CheckFormat($toCheck))
  984. {
  985. return "Wrong format [$toCheck]";
  986. }
  987. }
  988. return true;
  989. }
  990. // check attributes together
  991. public function CheckConsistency()
  992. {
  993. return true;
  994. }
  995. // check integrity rules (before inserting or updating the object)
  996. // a displayable error is returned
  997. public function DoCheckToWrite()
  998. {
  999. $this->DoComputeValues();
  1000. $aChanges = $this->ListChanges();
  1001. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1002. {
  1003. $res = $this->CheckValue($sAttCode);
  1004. if ($res !== true)
  1005. {
  1006. // $res contains the error description
  1007. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  1008. }
  1009. }
  1010. if (count($this->m_aCheckIssues) > 0)
  1011. {
  1012. // No need to check consistency between attributes if any of them has
  1013. // an unexpected value
  1014. return;
  1015. }
  1016. $res = $this->CheckConsistency();
  1017. if ($res !== true)
  1018. {
  1019. // $res contains the error description
  1020. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  1021. }
  1022. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  1023. //
  1024. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  1025. {
  1026. foreach($aChanges as $sAttCode => $value)
  1027. {
  1028. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  1029. if ($iFlags & OPT_ATT_SLAVE)
  1030. {
  1031. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  1032. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1033. $sAttLabel = $oAttDef->GetLabel();
  1034. foreach($aReasons as $aReasonInfo)
  1035. {
  1036. // Todo: associate the attribute code with the error
  1037. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  1038. }
  1039. }
  1040. }
  1041. }
  1042. }
  1043. final public function CheckToWrite()
  1044. {
  1045. if (MetaModel::SkipCheckToWrite())
  1046. {
  1047. return array(true, array());
  1048. }
  1049. if (is_null($this->m_bCheckStatus))
  1050. {
  1051. $this->m_aCheckIssues = array();
  1052. $oKPI = new ExecutionKPI();
  1053. $this->DoCheckToWrite();
  1054. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  1055. if (count($this->m_aCheckIssues) == 0)
  1056. {
  1057. $this->m_bCheckStatus = true;
  1058. }
  1059. else
  1060. {
  1061. $this->m_bCheckStatus = false;
  1062. }
  1063. }
  1064. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  1065. }
  1066. // check if it is allowed to delete the existing object from the database
  1067. // a displayable error is returned
  1068. protected function DoCheckToDelete(&$oDeletionPlan)
  1069. {
  1070. $this->m_aDeleteIssues = array(); // Ok
  1071. if ($this->InSyncScope())
  1072. {
  1073. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  1074. {
  1075. foreach ($aSourceData['replica'] as $oReplica)
  1076. {
  1077. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  1078. }
  1079. $oDataSource = $aSourceData['source'];
  1080. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  1081. {
  1082. // The current task has the right to delete the object
  1083. continue;
  1084. }
  1085. $oReplica = reset($aSourceData['replica']); // Take the first one
  1086. if ($oReplica->Get('status_dest_creator') != 1)
  1087. {
  1088. // The object is not owned by the task
  1089. continue;
  1090. }
  1091. $sLink = $oDataSource->GetName();
  1092. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  1093. switch($sUserDeletePolicy)
  1094. {
  1095. case 'nobody':
  1096. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1097. break;
  1098. case 'administrators':
  1099. if (!UserRights::IsAdministrator())
  1100. {
  1101. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  1102. }
  1103. break;
  1104. case 'everybody':
  1105. default:
  1106. // Ok
  1107. break;
  1108. }
  1109. }
  1110. }
  1111. }
  1112. public function CheckToDelete(&$oDeletionPlan)
  1113. {
  1114. $this->MakeDeletionPlan($oDeletionPlan);
  1115. $oDeletionPlan->ComputeResults();
  1116. return (!$oDeletionPlan->FoundStopper());
  1117. }
  1118. protected function ListChangedValues(array $aProposal)
  1119. {
  1120. $aDelta = array();
  1121. foreach ($aProposal as $sAtt => $proposedValue)
  1122. {
  1123. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1124. {
  1125. // The value was not set
  1126. $aDelta[$sAtt] = $proposedValue;
  1127. }
  1128. elseif(!array_key_exists($sAtt, $this->m_aModifiedAtt))
  1129. {
  1130. // This attCode was never set, canno tbe modified
  1131. continue;
  1132. }
  1133. elseif(is_object($proposedValue))
  1134. {
  1135. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1136. // The value is an object, the comparison is not strict
  1137. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  1138. {
  1139. $aDelta[$sAtt] = $proposedValue;
  1140. }
  1141. }
  1142. else
  1143. {
  1144. // The value is a scalar, the comparison must be 100% strict
  1145. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1146. {
  1147. //echo "$sAtt:<pre>\n";
  1148. //var_dump($this->m_aOrigValues[$sAtt]);
  1149. //var_dump($proposedValue);
  1150. //echo "</pre>\n";
  1151. $aDelta[$sAtt] = $proposedValue;
  1152. }
  1153. }
  1154. }
  1155. return $aDelta;
  1156. }
  1157. // List the attributes that have been changed
  1158. // Returns an array of attname => currentvalue
  1159. public function ListChanges()
  1160. {
  1161. if ($this->m_bIsInDB)
  1162. {
  1163. return $this->ListChangedValues($this->m_aCurrValues);
  1164. }
  1165. else
  1166. {
  1167. return $this->m_aCurrValues;
  1168. }
  1169. }
  1170. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1171. public function IsModified()
  1172. {
  1173. $aChanges = $this->ListChanges();
  1174. return (count($aChanges) != 0);
  1175. }
  1176. public function Equals($oSibling)
  1177. {
  1178. if (get_class($oSibling) != get_class($this))
  1179. {
  1180. return false;
  1181. }
  1182. if ($this->GetKey() != $oSibling->GetKey())
  1183. {
  1184. return false;
  1185. }
  1186. if ($this->m_bIsInDB)
  1187. {
  1188. // If one has changed, then consider them as being different
  1189. if ($this->IsModified() || $oSibling->IsModified())
  1190. {
  1191. return false;
  1192. }
  1193. }
  1194. else
  1195. {
  1196. // Todo - implement this case (loop on every attribute)
  1197. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1198. //{
  1199. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1200. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1201. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1202. //{
  1203. //return false;
  1204. //}
  1205. //}
  1206. return false;
  1207. }
  1208. return true;
  1209. }
  1210. // used both by insert/update
  1211. private function DBWriteLinks()
  1212. {
  1213. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1214. {
  1215. if (!$oAttDef->IsLinkSet()) continue;
  1216. if (!array_key_exists($sAttCode, $this->m_aModifiedAtt)) continue;
  1217. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  1218. if ($oOriginalSet != null)
  1219. {
  1220. $aOriginalList = $oOriginalSet->ToArray();
  1221. }
  1222. else
  1223. {
  1224. $aOriginalList = array();
  1225. }
  1226. $oLinks = $this->Get($sAttCode);
  1227. $oLinks->Rewind();
  1228. while ($oLinkedObject = $oLinks->Fetch())
  1229. {
  1230. if (!array_key_exists($oLinkedObject->GetKey(), $aOriginalList))
  1231. {
  1232. // New object added to the set, make it point properly
  1233. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1234. }
  1235. if ($oLinkedObject->IsModified())
  1236. {
  1237. // Objects can be modified because:
  1238. // 1) They've just been added into the set, so their ExtKey is modified
  1239. // 2) They are about to be removed from the set BUT NOT deleted, their ExtKey has been reset
  1240. $oLinkedObject->DBWrite();
  1241. }
  1242. }
  1243. // Delete the objects that were initialy present and disappeared from the list
  1244. // (if any)
  1245. if (count($aOriginalList) > 0)
  1246. {
  1247. $aNewSet = $oLinks->ToArray();
  1248. foreach($aOriginalList as $iId => $oObject)
  1249. {
  1250. if (!array_key_exists($iId, $aNewSet))
  1251. {
  1252. // It disappeared from the list
  1253. $oObject->DBDelete();
  1254. }
  1255. }
  1256. }
  1257. }
  1258. }
  1259. // Note: this is experimental - it was designed to speed up the setup of iTop
  1260. // Known limitations:
  1261. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1262. // - the id of the object is not updated
  1263. static public final function BulkInsertStart()
  1264. {
  1265. self::$m_bBulkInsert = true;
  1266. }
  1267. static public final function BulkInsertFlush()
  1268. {
  1269. if (!self::$m_bBulkInsert) return;
  1270. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1271. {
  1272. foreach ($aTables as $sTable => $sColumns)
  1273. {
  1274. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1275. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1276. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1277. }
  1278. }
  1279. // Reset
  1280. self::$m_aBulkInsertItems = array();
  1281. self::$m_aBulkInsertCols = array();
  1282. self::$m_bBulkInsert = false;
  1283. }
  1284. private function DBInsertSingleTable($sTableClass)
  1285. {
  1286. $sTable = MetaModel::DBGetTable($sTableClass);
  1287. // Abstract classes or classes having no specific attribute do not have an associated table
  1288. if ($sTable == '') return;
  1289. $sClass = get_class($this);
  1290. // fields in first array, values in the second
  1291. $aFieldsToWrite = array();
  1292. $aValuesToWrite = array();
  1293. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1294. {
  1295. // Add it to the list of fields to write
  1296. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1297. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1298. }
  1299. $aHierarchicalKeys = array();
  1300. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1301. {
  1302. // Skip this attribute if not defined in this table
  1303. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1304. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1305. foreach($aAttColumns as $sColumn => $sValue)
  1306. {
  1307. $aFieldsToWrite[] = "`$sColumn`";
  1308. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1309. }
  1310. if ($oAttDef->IsHierarchicalKey())
  1311. {
  1312. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1313. }
  1314. }
  1315. if (count($aValuesToWrite) == 0) return false;
  1316. if (MetaModel::DBIsReadOnly())
  1317. {
  1318. $iNewKey = -1;
  1319. }
  1320. else
  1321. {
  1322. if (self::$m_bBulkInsert)
  1323. {
  1324. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1325. {
  1326. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1327. }
  1328. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1329. $iNewKey = 999999; // TODO - compute next id....
  1330. }
  1331. else
  1332. {
  1333. if (count($aHierarchicalKeys) > 0)
  1334. {
  1335. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1336. {
  1337. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1338. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1339. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1340. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1341. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1342. }
  1343. }
  1344. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1345. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1346. }
  1347. }
  1348. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1349. if (empty($this->m_iKey))
  1350. {
  1351. // Take the autonumber
  1352. $this->m_iKey = $iNewKey;
  1353. }
  1354. return $this->m_iKey;
  1355. }
  1356. // Insert of record for the new object into the database
  1357. // Returns the key of the newly created object
  1358. public function DBInsertNoReload()
  1359. {
  1360. if ($this->m_bIsInDB)
  1361. {
  1362. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1363. }
  1364. $sClass = get_class($this);
  1365. $sRootClass = MetaModel::GetRootClass($sClass);
  1366. // Ensure the update of the values (we are accessing the data directly)
  1367. $this->DoComputeValues();
  1368. $this->OnInsert();
  1369. if ($this->m_iKey < 0)
  1370. {
  1371. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1372. $this->m_iKey = null;
  1373. }
  1374. // If not automatically computed, then check that the key is given by the caller
  1375. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1376. {
  1377. if (empty($this->m_iKey))
  1378. {
  1379. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber", array('class' => $sRootClass));
  1380. }
  1381. }
  1382. // Ultimate check - ensure DB integrity
  1383. list($bRes, $aIssues) = $this->CheckToWrite();
  1384. if (!$bRes)
  1385. {
  1386. $sIssues = implode(', ', $aIssues);
  1387. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1388. }
  1389. // Stop watches
  1390. $sState = $this->GetState();
  1391. if ($sState != '')
  1392. {
  1393. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1394. {
  1395. if ($oAttDef instanceof AttributeStopWatch)
  1396. {
  1397. if (in_array($sState, $oAttDef->GetStates()))
  1398. {
  1399. // Start the stop watch and compute the deadlines
  1400. $oSW = $this->Get($sAttCode);
  1401. $oSW->Start($this, $oAttDef);
  1402. $oSW->ComputeDeadlines($this, $oAttDef);
  1403. $this->Set($sAttCode, $oSW);
  1404. }
  1405. }
  1406. }
  1407. }
  1408. // First query built upon on the root class, because the ID must be created first
  1409. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1410. // Then do the leaf class, if different from the root class
  1411. if ($sClass != $sRootClass)
  1412. {
  1413. $this->DBInsertSingleTable($sClass);
  1414. }
  1415. // Then do the other classes
  1416. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1417. {
  1418. if ($sParentClass == $sRootClass) continue;
  1419. $this->DBInsertSingleTable($sParentClass);
  1420. }
  1421. $this->DBWriteLinks();
  1422. $this->m_bIsInDB = true;
  1423. $this->m_bDirty = false;
  1424. $this->AfterInsert();
  1425. // Activate any existing trigger
  1426. $sClass = get_class($this);
  1427. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1428. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1429. while ($oTrigger = $oSet->Fetch())
  1430. {
  1431. $oTrigger->DoActivate($this->ToArgs('this'));
  1432. }
  1433. // Callbacks registered with RegisterCallback
  1434. if (isset($this->m_aCallbacks[self::CALLBACK_AFTERINSERT]))
  1435. {
  1436. foreach ($this->m_aCallbacks[self::CALLBACK_AFTERINSERT] as $aCallBackData)
  1437. {
  1438. call_user_func_array($aCallBackData['callback'], $aCallBackData['params']);
  1439. }
  1440. }
  1441. $this->RecordObjCreation();
  1442. return $this->m_iKey;
  1443. }
  1444. protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
  1445. {
  1446. $sTable = MetaModel::DBGetTable($sTableClass);
  1447. // Abstract classes or classes having no specific attribute do not have an associated table
  1448. if ($sTable == '') return;
  1449. $sClass = get_class($this);
  1450. // fields in first array, values in the second
  1451. $aFieldsToWrite = array();
  1452. $aValuesToWrite = array();
  1453. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1454. {
  1455. // Add it to the list of fields to write
  1456. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1457. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1458. }
  1459. $aHierarchicalKeys = array();
  1460. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1461. {
  1462. // Skip this attribute if not defined in this table
  1463. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1464. // Skip link set that can still be undefined though the object is 100% loaded
  1465. if ($oAttDef->IsLinkSet()) continue;
  1466. $value = $this->m_aCurrValues[$sAttCode];
  1467. if ($oAttDef->IsExternalKey())
  1468. {
  1469. $sTargetClass = $oAttDef->GetTargetClass();
  1470. if (is_array($aAuthorizedExtKeys))
  1471. {
  1472. if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
  1473. {
  1474. $value = 0;
  1475. }
  1476. }
  1477. }
  1478. $aAttColumns = $oAttDef->GetSQLValues($value);
  1479. foreach($aAttColumns as $sColumn => $sValue)
  1480. {
  1481. $aFieldsToWrite[] = "`$sColumn`";
  1482. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1483. }
  1484. if ($oAttDef->IsHierarchicalKey())
  1485. {
  1486. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1487. }
  1488. }
  1489. if (count($aValuesToWrite) == 0) return false;
  1490. if (count($aHierarchicalKeys) > 0)
  1491. {
  1492. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1493. {
  1494. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1495. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1496. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1497. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1498. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1499. }
  1500. }
  1501. $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
  1502. }
  1503. public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
  1504. {
  1505. $sClass = get_class($this);
  1506. $sRootClass = MetaModel::GetRootClass($sClass);
  1507. // First query built upon on the root class, because the ID must be created first
  1508. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
  1509. // Then do the leaf class, if different from the root class
  1510. if ($sClass != $sRootClass)
  1511. {
  1512. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
  1513. }
  1514. // Then do the other classes
  1515. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1516. {
  1517. if ($sParentClass == $sRootClass) continue;
  1518. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
  1519. }
  1520. }
  1521. public function DBInsert()
  1522. {
  1523. $this->DBInsertNoReload();
  1524. $this->Reload();
  1525. return $this->m_iKey;
  1526. }
  1527. public function DBInsertTracked(CMDBChange $oChange)
  1528. {
  1529. CMDBObject::SetCurrentChange($oChange);
  1530. return $this->DBInsert();
  1531. }
  1532. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1533. {
  1534. CMDBObject::SetCurrentChange($oChange);
  1535. return $this->DBInsertNoReload();
  1536. }
  1537. // Creates a copy of the current object into the database
  1538. // Returns the id of the newly created object
  1539. public function DBClone($iNewKey = null)
  1540. {
  1541. $this->m_bIsInDB = false;
  1542. $this->m_iKey = $iNewKey;
  1543. $ret = $this->DBInsert();
  1544. $this->RecordObjCreation();
  1545. return $ret;
  1546. }
  1547. /**
  1548. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1549. * The purpose of this method is to reset the appropriate attributes of the object in
  1550. * order to make sure that the newly cloned object is really distinct from its clone
  1551. */
  1552. public function __clone()
  1553. {
  1554. $this->m_bIsInDB = false;
  1555. $this->m_bDirty = true;
  1556. $this->m_iKey = self::GetNextTempId(get_class($this));
  1557. }
  1558. // Update a record
  1559. public function DBUpdate()
  1560. {
  1561. if (!$this->m_bIsInDB)
  1562. {
  1563. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1564. }
  1565. // Protect against reentrance (e.g. cascading the update of ticket logs)
  1566. static $aUpdateReentrance = array();
  1567. $sKey = get_class($this).'::'.$this->GetKey();
  1568. if (array_key_exists($sKey, $aUpdateReentrance))
  1569. {
  1570. return;
  1571. }
  1572. $aUpdateReentrance[$sKey] = true;
  1573. try
  1574. {
  1575. // Stop watches
  1576. $sState = $this->GetState();
  1577. if ($sState != '')
  1578. {
  1579. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1580. {
  1581. if ($oAttDef instanceof AttributeStopWatch)
  1582. {
  1583. if (in_array($sState, $oAttDef->GetStates()))
  1584. {
  1585. // Compute or recompute the deadlines
  1586. $oSW = $this->Get($sAttCode);
  1587. $oSW->ComputeDeadlines($this, $oAttDef);
  1588. $this->Set($sAttCode, $oSW);
  1589. }
  1590. }
  1591. }
  1592. }
  1593. $this->DoComputeValues();
  1594. $this->OnUpdate();
  1595. $aChanges = $this->ListChanges();
  1596. if (count($aChanges) == 0)
  1597. {
  1598. // Attempting to update an unchanged object
  1599. unset($aUpdateReentrance[$sKey]);
  1600. return $this->m_iKey;
  1601. }
  1602. // Ultimate check - ensure DB integrity
  1603. list($bRes, $aIssues) = $this->CheckToWrite();
  1604. if (!$bRes)
  1605. {
  1606. $sIssues = implode(', ', $aIssues);
  1607. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1608. }
  1609. // Save the original values (will be reset to the new values when the object get written to the DB)
  1610. $aOriginalValues = $this->m_aOrigValues;
  1611. $bHasANewExternalKeyValue = false;
  1612. $aHierarchicalKeys = array();
  1613. foreach($aChanges as $sAttCode => $valuecurr)
  1614. {
  1615. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1616. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1617. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1618. if ($oAttDef->IsHierarchicalKey())
  1619. {
  1620. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1621. }
  1622. }
  1623. if (!MetaModel::DBIsReadOnly())
  1624. {
  1625. // Update the left & right indexes for each hierarchical key
  1626. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1627. {
  1628. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1629. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1630. $aRes = CMDBSource::QueryToArray($sSQL);
  1631. $iMyLeft = $aRes[0]['left'];
  1632. $iMyRight = $aRes[0]['right'];
  1633. $iDelta =$iMyRight - $iMyLeft + 1;
  1634. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1635. if ($aChanges[$sAttCode] == 0)
  1636. {
  1637. // No new parent, insert completely at the right of the tree
  1638. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1639. $aRes = CMDBSource::QueryToArray($sSQL);
  1640. if (count($aRes) == 0)
  1641. {
  1642. $iNewLeft = 1;
  1643. }
  1644. else
  1645. {
  1646. $iNewLeft = $aRes[0]['max']+1;
  1647. }
  1648. }
  1649. else
  1650. {
  1651. // Insert at the right of the specified parent
  1652. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aChanges[$sAttCode]);
  1653. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1654. }
  1655. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1656. $aHKChanges = array();
  1657. $aHKChanges[$sAttCode] = $aChanges[$sAttCode];
  1658. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1659. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1660. $aChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1661. }
  1662. // Update scalar attributes
  1663. if (count($aChanges) != 0)
  1664. {
  1665. $oFilter = new DBObjectSearch(get_class($this));
  1666. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1667. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1668. CMDBSource::Query($sSQL);
  1669. }
  1670. }
  1671. $this->DBWriteLinks();
  1672. $this->m_bDirty = false;
  1673. $this->AfterUpdate();
  1674. // Reload to get the external attributes
  1675. if ($bHasANewExternalKeyValue)
  1676. {
  1677. $this->Reload();
  1678. }
  1679. else
  1680. {
  1681. // Reset original values although the object has not been reloaded
  1682. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1683. {
  1684. if ($bLoaded)
  1685. {
  1686. $value = $this->m_aCurrValues[$sAttCode];
  1687. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1688. }
  1689. }
  1690. }
  1691. if (count($aChanges) != 0)
  1692. {
  1693. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1694. }
  1695. }
  1696. catch (Exception $e)
  1697. {
  1698. unset($aUpdateReentrance[$sKey]);
  1699. throw $e;
  1700. }
  1701. unset($aUpdateReentrance[$sKey]);
  1702. return $this->m_iKey;
  1703. }
  1704. public function DBUpdateTracked(CMDBChange $oChange)
  1705. {
  1706. CMDBObject::SetCurrentChange($oChange);
  1707. return $this->DBUpdate();
  1708. }
  1709. // Make the current changes persistent - clever wrapper for Insert or Update
  1710. public function DBWrite()
  1711. {
  1712. if ($this->m_bIsInDB)
  1713. {
  1714. return $this->DBUpdate();
  1715. }
  1716. else
  1717. {
  1718. return $this->DBInsert();
  1719. }
  1720. }
  1721. private function DBDeleteSingleTable($sTableClass)
  1722. {
  1723. $sTable = MetaModel::DBGetTable($sTableClass);
  1724. // Abstract classes or classes having no specific attribute do not have an associated table
  1725. if ($sTable == '') return;
  1726. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1727. $sKey = CMDBSource::Quote($this->m_iKey);
  1728. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1729. CMDBSource::DeleteFrom($sDeleteSQL);
  1730. }
  1731. protected function DBDeleteSingleObject()
  1732. {
  1733. if (!MetaModel::DBIsReadOnly())
  1734. {
  1735. $this->OnDelete();
  1736. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1737. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1738. {
  1739. if ($oAttDef->IsHierarchicalKey())
  1740. {
  1741. // Update the left & right indexes for each hierarchical key
  1742. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1743. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1744. $aRes = CMDBSource::QueryToArray($sSQL);
  1745. $iMyLeft = $aRes[0]['left'];
  1746. $iMyRight = $aRes[0]['right'];
  1747. $iDelta =$iMyRight - $iMyLeft + 1;
  1748. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1749. // No new parent for now, insert completely at the right of the tree
  1750. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1751. $aRes = CMDBSource::QueryToArray($sSQL);
  1752. if (count($aRes) == 0)
  1753. {
  1754. $iNewLeft = 1;
  1755. }
  1756. else
  1757. {
  1758. $iNewLeft = $aRes[0]['max']+1;
  1759. }
  1760. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1761. }
  1762. }
  1763. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1764. {
  1765. $this->DBDeleteSingleTable($sParentClass);
  1766. }
  1767. $this->AfterDelete();
  1768. $this->m_bIsInDB = false;
  1769. // Fix for #926: do NOT reset m_iKey as it can be used to have it for reporting purposes (see the REST service to delete objects, reported as bug #926)
  1770. // Thought the key is not reset, using DBInsert or DBWrite will create an object having the same characteristics and a new ID. DBUpdate is protected
  1771. }
  1772. }
  1773. // Delete an object... and guarantee data integrity
  1774. //
  1775. public function DBDelete(&$oDeletionPlan = null)
  1776. {
  1777. static $iLoopTimeLimit = null;
  1778. if ($iLoopTimeLimit == null)
  1779. {
  1780. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  1781. }
  1782. if (is_null($oDeletionPlan))
  1783. {
  1784. $oDeletionPlan = new DeletionPlan();
  1785. }
  1786. $this->MakeDeletionPlan($oDeletionPlan);
  1787. $oDeletionPlan->ComputeResults();
  1788. if ($oDeletionPlan->FoundStopper())
  1789. {
  1790. $aIssues = $oDeletionPlan->GetIssues();
  1791. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1792. }
  1793. else
  1794. {
  1795. // Getting and setting time limit are not symetric:
  1796. // www.php.net/manual/fr/function.set-time-limit.php#72305
  1797. $iPreviousTimeLimit = ini_get('max_execution_time');
  1798. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1799. {
  1800. foreach ($aToDelete as $iId => $aData)
  1801. {
  1802. $oToDelete = $aData['to_delete'];
  1803. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1804. // because for each object we would try to update all the preceding ones... that are already deleted
  1805. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1806. // As a temporary fix: delete only the objects that are still to be deleted...
  1807. if ($oToDelete->m_bIsInDB)
  1808. {
  1809. set_time_limit($iLoopTimeLimit);
  1810. $oToDelete->DBDeleteSingleObject();
  1811. }
  1812. }
  1813. }
  1814. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1815. {
  1816. foreach ($aToUpdate as $iId => $aData)
  1817. {
  1818. $oToUpdate = $aData['to_reset'];
  1819. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1820. {
  1821. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1822. set_time_limit($iLoopTimeLimit);
  1823. $oToUpdate->DBUpdate();
  1824. }
  1825. }
  1826. }
  1827. set_time_limit($iPreviousTimeLimit);
  1828. }
  1829. return $oDeletionPlan;
  1830. }
  1831. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1832. {
  1833. CMDBObject::SetCurrentChange($oChange);
  1834. $this->DBDelete($oDeletionPlan);
  1835. }
  1836. public function EnumTransitions()
  1837. {
  1838. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1839. if (empty($sStateAttCode)) return array();
  1840. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1841. return MetaModel::EnumTransitions(get_class($this), $sState);
  1842. }
  1843. /**
  1844. * Designed as an action to be called when a stop watch threshold times out
  1845. * or from within the framework
  1846. */
  1847. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  1848. {
  1849. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1850. if (empty($sStateAttCode)) return false;
  1851. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1852. $aStateTransitions = $this->EnumTransitions();
  1853. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  1854. {
  1855. // This simulus has no effect in the current state... do nothing
  1856. return;
  1857. }
  1858. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1859. // Change the state before proceeding to the actions, this is necessary because an action might
  1860. // trigger another stimuli (alternative: push the stimuli into a queue)
  1861. $sPreviousState = $this->Get($sStateAttCode);
  1862. $sNewState = $aTransitionDef['target_state'];
  1863. $this->Set($sStateAttCode, $sNewState);
  1864. // $aTransitionDef is an
  1865. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1866. $bSuccess = true;
  1867. foreach ($aTransitionDef['actions'] as $actionHandler)
  1868. {
  1869. if (is_string($actionHandler))
  1870. {
  1871. // Old (pre-2.1.0 modules) action definition without any parameter
  1872. $aActionCallSpec = array($this, $actionHandler);
  1873. if (!is_callable($aActionCallSpec))
  1874. {
  1875. throw new CoreException("Unable to call action: ".get_class($this)."::$actionHandler");
  1876. return;
  1877. }
  1878. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1879. }
  1880. else // if (is_array($actionHandler))
  1881. {
  1882. // New syntax: 'verb' and typed parameters
  1883. $sAction = $actionHandler['verb'];
  1884. $aParams = array();
  1885. foreach($actionHandler['params'] as $aDefinition)
  1886. {
  1887. $sParamType = array_key_exists('type', $aDefinition) ? $aDefinition['type'] : 'string';
  1888. switch($sParamType)
  1889. {
  1890. case 'int':
  1891. $value = (int)$aDefinition['value'];
  1892. break;
  1893. case 'float':
  1894. $value = (float)$aDefinition['value'];
  1895. break;
  1896. case 'bool':
  1897. $value = (bool)$aDefinition['value'];
  1898. break;
  1899. case 'reference':
  1900. $value = ${$aDefinition['value']};
  1901. break;
  1902. case 'string':
  1903. default:
  1904. $value = (string)$aDefinition['value'];
  1905. }
  1906. $aParams[] = $value;
  1907. }
  1908. $aCallSpec = array($this, $sAction);
  1909. $bRet = call_user_func_array($aCallSpec, $aParams);
  1910. }
  1911. // if one call fails, the whole is considered as failed
  1912. if (!$bRet) $bSuccess = false;
  1913. }
  1914. if ($bSuccess)
  1915. {
  1916. $sClass = get_class($this);
  1917. // Stop watches
  1918. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1919. {
  1920. if ($oAttDef instanceof AttributeStopWatch)
  1921. {
  1922. $oSW = $this->Get($sAttCode);
  1923. if (in_array($sNewState, $oAttDef->GetStates()))
  1924. {
  1925. $oSW->Start($this, $oAttDef);
  1926. }
  1927. else
  1928. {
  1929. $oSW->Stop($this, $oAttDef);
  1930. }
  1931. $this->Set($sAttCode, $oSW);
  1932. }
  1933. }
  1934. if (!$bDoNotWrite)
  1935. {
  1936. $this->DBWrite();
  1937. }
  1938. // Change state triggers...
  1939. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1940. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1941. while ($oTrigger = $oSet->Fetch())
  1942. {
  1943. $oTrigger->DoActivate($this->ToArgs('this'));
  1944. }
  1945. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1946. while ($oTrigger = $oSet->Fetch())
  1947. {
  1948. $oTrigger->DoActivate($this->ToArgs('this'));
  1949. }
  1950. }
  1951. return $bSuccess;
  1952. }
  1953. /**
  1954. * Designed as an action to be called when a stop watch threshold times out
  1955. */
  1956. public function ResetStopWatch($sAttCode)
  1957. {
  1958. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1959. if (!$oAttDef instanceof AttributeStopWatch)
  1960. {
  1961. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  1962. }
  1963. $oSW = $this->Get($sAttCode);
  1964. $oSW->Reset($this, $oAttDef);
  1965. $this->Set($sAttCode, $oSW);
  1966. }
  1967. /**
  1968. * Lifecycle action: Recover the default value (aka when an object is being created)
  1969. */
  1970. public function Reset($sAttCode)
  1971. {
  1972. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1973. $this->Set($sAttCode, $oAttDef->GetDefaultValue());
  1974. return true;
  1975. }
  1976. /**
  1977. * Lifecycle action: Copy an attribute to another
  1978. */
  1979. public function Copy($sDestAttCode, $sSourceAttCode)
  1980. {
  1981. $this->Set($sDestAttCode, $this->Get($sSourceAttCode));
  1982. return true;
  1983. }
  1984. /**
  1985. * Lifecycle action: Set the current date/time for the given attribute
  1986. */
  1987. public function SetCurrentDate($sAttCode)
  1988. {
  1989. $this->Set($sAttCode, time());
  1990. return true;
  1991. }
  1992. /**
  1993. * Lifecycle action: Set the current logged in user for the given attribute
  1994. */
  1995. public function SetCurrentUser($sAttCode)
  1996. {
  1997. $this->Set($sAttCode, UserRights::GetUserId());
  1998. return true;
  1999. }
  2000. /**
  2001. * Lifecycle action: Set the time elapsed since a reference point
  2002. */
  2003. public function SetElapsedTime($sAttCode, $sRefAttCode, $sWorkingTimeComputer = null)
  2004. {
  2005. if (is_null($sWorkingTimeComputer))
  2006. {
  2007. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  2008. }
  2009. $oComputer = new $sWorkingTimeComputer();
  2010. $aCallSpec = array($oComputer, 'GetOpenDuration');
  2011. if (!is_callable($aCallSpec))
  2012. {
  2013. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  2014. }
  2015. $iStartTime = AttributeDateTime::GetAsUnixSeconds($this->Get($sRefAttCode));
  2016. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  2017. $oEndDate = new DateTime(); // now
  2018. if (class_exists('WorkingTimeRecorder'))
  2019. {
  2020. $sClass = get_class($this);
  2021. WorkingTimeRecorder::Start($this, time(), "DBObject-SetElapsedTime-$sAttCode-$sRefAttCode", 'Core:ExplainWTC:ElapsedTime', array("Class:$sClass/Attribute:$sAttCode"));
  2022. }
  2023. $iElapsed = call_user_func($aCallSpec, $this, $oStartDate, $oEndDate);
  2024. if (class_exists('WorkingTimeRecorder'))
  2025. {
  2026. WorkingTimeRecorder::End();
  2027. }
  2028. $this->Set($sAttCode, $iElapsed);
  2029. return true;
  2030. }
  2031. /**
  2032. * Create query parameters (SELECT ... WHERE service = :this->service_id)
  2033. * to be used with the APIs DBObjectSearch/DBObjectSet
  2034. *
  2035. * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
  2036. * in VariableExpression::Render()
  2037. */
  2038. public function ToArgsForQuery($sArgName = 'this')
  2039. {
  2040. return array($sArgName.'->object()' => $this);
  2041. }
  2042. /**
  2043. * Create template placeholders: now equivalent to ToArgsForQuery since the actual
  2044. * template placeholders are computed on demand.
  2045. */
  2046. public function ToArgs($sArgName = 'this')
  2047. {
  2048. return $this->ToArgsForQuery($sArgName);
  2049. }
  2050. public function GetForTemplate($sPlaceholderAttCode)
  2051. {
  2052. $ret = null;
  2053. if (($iPos = strpos($sPlaceholderAttCode, '->')) !== false)
  2054. {
  2055. $sExtKeyAttCode = substr($sPlaceholderAttCode, 0, $iPos);
  2056. $sRemoteAttCode = substr($sPlaceholderAttCode, $iPos + 2);
  2057. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  2058. {
  2059. throw new CoreException("Unknown attribute '$sExtKeyAttCode' for the class ".get_class($this));
  2060. }
  2061. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  2062. if (!$oKeyAttDef instanceof AttributeExternalKey)
  2063. {
  2064. throw new CoreException("'$sExtKeyAttCode' is not an external key of the class ".get_class($this));
  2065. }
  2066. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  2067. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  2068. if (is_null($oRemoteObj))
  2069. {
  2070. $ret = Dict::S('UI:UndefinedObject');
  2071. }
  2072. else
  2073. {
  2074. // Recurse
  2075. $ret = $oRemoteObj->GetForTemplate($sRemoteAttCode);
  2076. }
  2077. }
  2078. else
  2079. {
  2080. switch($sPlaceholderAttCode)
  2081. {
  2082. case 'id':
  2083. $ret = $this->GetKey();
  2084. break;
  2085. case 'hyperlink()':
  2086. $ret = $this->GetHyperlink('iTopStandardURLMaker', false);
  2087. break;
  2088. case 'hyperlink(portal)':
  2089. $ret = $this->GetHyperlink('PortalURLMaker', false);
  2090. break;
  2091. case 'name()':
  2092. $ret = $this->GetName();
  2093. break;
  2094. default:
  2095. if (preg_match('/^([^(]+)\\((.+)\\)$/', $sPlaceholderAttCode, $aMatches))
  2096. {
  2097. $sVerb = $aMatches[1];
  2098. $sAttCode = $aMatches[2];
  2099. }
  2100. else
  2101. {
  2102. $sVerb = '';
  2103. $sAttCode = $sPlaceholderAttCode;
  2104. }
  2105. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2106. $ret = $oAttDef->GetForTemplate($this->Get($sAttCode), $sVerb, $this);
  2107. }
  2108. }
  2109. return $ret;
  2110. }
  2111. // To be optionaly overloaded
  2112. protected function OnInsert()
  2113. {
  2114. }
  2115. // To be optionaly overloaded
  2116. protected function AfterInsert()
  2117. {
  2118. }
  2119. // To be optionaly overloaded
  2120. protected function OnUpdate()
  2121. {
  2122. }
  2123. // To be optionaly overloaded
  2124. protected function AfterUpdate()
  2125. {
  2126. }
  2127. // To be optionaly overloaded
  2128. protected function OnDelete()
  2129. {
  2130. }
  2131. // To be optionaly overloaded
  2132. protected function AfterDelete()
  2133. {
  2134. }
  2135. /**
  2136. * Common to the recording of link set changes (add/remove/modify)
  2137. */
  2138. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  2139. {
  2140. if ($iLinkSetOwnerId <= 0)
  2141. {
  2142. return null;
  2143. }
  2144. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  2145. {
  2146. // The link set owner class does not keep track of its history
  2147. return null;
  2148. }
  2149. // Determine the linked item class and id
  2150. //
  2151. if ($oLinkSet->IsIndirect())
  2152. {
  2153. // The "item" is on the other end (N-N links)
  2154. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  2155. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  2156. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  2157. if ($aOriginalValues)
  2158. {
  2159. // Get the value from the original values
  2160. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  2161. }
  2162. else
  2163. {
  2164. $iItemId = $this->Get($sExtKeyToRemote);
  2165. }
  2166. }
  2167. else
  2168. {
  2169. // I am the "item" (1-N links)
  2170. $sItemClass = get_class($this);
  2171. $iItemId = $this->GetKey();
  2172. }
  2173. // Get the remote object, to determine its exact class
  2174. // Possible optimization: implement a tool in MetaModel, to get the final class of an object (not always querying + query reduced to a select on the root table!
  2175. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  2176. if ($oOwner)
  2177. {
  2178. $sLinkSetOwnerClass = get_class($oOwner);
  2179. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  2180. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  2181. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  2182. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  2183. $oMyChangeOp->Set("item_class", $sItemClass);
  2184. $oMyChangeOp->Set("item_id", $iItemId);
  2185. return $oMyChangeOp;
  2186. }
  2187. else
  2188. {
  2189. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  2190. return null;
  2191. }
  2192. }
  2193. /**
  2194. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  2195. */
  2196. private function RecordLinkSetListChange($bAdd = true)
  2197. {
  2198. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2199. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2200. {
  2201. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2202. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2203. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2204. if ($oMyChangeOp)
  2205. {
  2206. if ($bAdd)
  2207. {
  2208. $oMyChangeOp->Set("type", "added");
  2209. }
  2210. else
  2211. {
  2212. $oMyChangeOp->Set("type", "removed");
  2213. }
  2214. $iId = $oMyChangeOp->DBInsertNoReload();
  2215. }
  2216. }
  2217. }
  2218. protected function RecordObjCreation()
  2219. {
  2220. $this->RecordLinkSetListChange(true);
  2221. }
  2222. protected function RecordObjDeletion($objkey)
  2223. {
  2224. $this->RecordLinkSetListChange(false);
  2225. }
  2226. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  2227. {
  2228. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  2229. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  2230. {
  2231. if (array_key_exists($sExtKeyAttCode, $aValues))
  2232. {
  2233. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  2234. // Keep track of link added/removed
  2235. //
  2236. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  2237. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2238. if ($oMyChangeOp)
  2239. {
  2240. $oMyChangeOp->Set("type", "added");
  2241. $oMyChangeOp->DBInsertNoReload();
  2242. }
  2243. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  2244. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  2245. if ($oMyChangeOp)
  2246. {
  2247. $oMyChangeOp->Set("type", "removed");
  2248. $oMyChangeOp->DBInsertNoReload();
  2249. }
  2250. }
  2251. else
  2252. {
  2253. // Keep track of link changes
  2254. //
  2255. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  2256. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2257. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  2258. if ($oMyChangeOp)
  2259. {
  2260. $oMyChangeOp->Set("link_id", $this->GetKey());
  2261. $iId = $oMyChangeOp->DBInsertNoReload();
  2262. }
  2263. }
  2264. }
  2265. }
  2266. // Return an empty set for the parent of all
  2267. // May be overloaded.
  2268. // Anyhow, this way of implementing the relations suffers limitations (not handling the redundancy)
  2269. // and you should consider defining those things in XML.
  2270. public static function GetRelationQueries($sRelCode)
  2271. {
  2272. return array();
  2273. }
  2274. // Reserved: do not overload
  2275. public static function GetRelationQueriesEx($sRelCode)
  2276. {
  2277. return array();
  2278. }
  2279. /**
  2280. * Will be deprecated soon - use GetRelatedObjectsDown/Up instead to take redundancy into account
  2281. */
  2282. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  2283. {
  2284. // Temporary patch: until the impact analysis GUI gets rewritten,
  2285. // let's consider that "depends on" is equivalent to "impacts/up"
  2286. // The current patch has been implemented in DBObject and MetaModel
  2287. $sHackedRelCode = $sRelCode;
  2288. $bDown = true;
  2289. if ($sRelCode == 'depends on')
  2290. {
  2291. $sHackedRelCode = 'impacts';
  2292. $bDown = false;
  2293. }
  2294. foreach (MetaModel::EnumRelationQueries(get_class($this), $sHackedRelCode, $bDown) as $sDummy => $aQueryInfo)
  2295. {
  2296. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo['sQueryDown']);
  2297. $sQuery = $bDown ? $aQueryInfo['sQueryDown'] : $aQueryInfo['sQueryUp'];
  2298. //$bPropagate = $aQueryInfo["bPropagate"];
  2299. //$iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  2300. $iDepth = $iMaxDepth - 1;
  2301. // Note: the loop over the result set has been written in an unusual way for error reporting purposes
  2302. // In the case of a wrong query parameter name, the error occurs on the first call to Fetch,
  2303. // thus we need to have this first call into the try/catch, but
  2304. // we do NOT want to nest the try/catch for the error message to be clear
  2305. try
  2306. {
  2307. $oFlt = DBObjectSearch::FromOQL($sQuery);
  2308. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgsForQuery());
  2309. $oObj = $oObjSet->Fetch();
  2310. }
  2311. catch (Exception $e)
  2312. {
  2313. $sClassOfDefinition = $aQueryInfo['_legacy_'] ? get_class($this).'(or a parent)::GetRelationQueries()' : $aQueryInfo['sDefinedInClass'];
  2314. throw new Exception("Wrong query for the relation $sRelCode/$sClassOfDefinition/{$aQueryInfo['sNeighbour']}: ".$e->getMessage());
  2315. }
  2316. if ($oObj)
  2317. {
  2318. do
  2319. {
  2320. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  2321. $sObjKey = $oObj->GetKey();
  2322. if (array_key_exists($sRootClass, $aResults))
  2323. {
  2324. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  2325. {
  2326. continue; // already visited, skip
  2327. }
  2328. }
  2329. $aResults[$sRootClass][$sObjKey] = $oObj;
  2330. if ($iDepth > 0)
  2331. {
  2332. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  2333. }
  2334. }
  2335. while ($oObj = $oObjSet->Fetch());
  2336. }
  2337. }
  2338. return $aResults;
  2339. }
  2340. /**
  2341. * Compute the "RelatedObjects" (forward or "down" direction) for the object
  2342. * for the specified relation
  2343. *
  2344. * @param string $sRelCode The code of the relation to use for the computation
  2345. * @param int $iMaxDepth Maximum recursion depth
  2346. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2347. *
  2348. * @return RelationGraph The graph of all the related objects
  2349. */
  2350. public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2351. {
  2352. $oGraph = new RelationGraph();
  2353. $oGraph->AddSourceObject($this);
  2354. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2355. return $oGraph;
  2356. }
  2357. /**
  2358. * Compute the "RelatedObjects" (reverse or "up" direction) for the object
  2359. * for the specified relation
  2360. *
  2361. * @param string $sRelCode The code of the relation to use for the computation
  2362. * @param int $iMaxDepth Maximum recursion depth
  2363. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  2364. *
  2365. * @return RelationGraph The graph of all the related objects
  2366. */
  2367. public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  2368. {
  2369. $oGraph = new RelationGraph();
  2370. $oGraph->AddSourceObject($this);
  2371. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  2372. return $oGraph;
  2373. }
  2374. public function GetReferencingObjects($bAllowAllData = false)
  2375. {
  2376. $aDependentObjects = array();
  2377. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  2378. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  2379. {
  2380. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  2381. {
  2382. // skip if this external key is behind an external field
  2383. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  2384. $oSearch = new DBObjectSearch($sRemoteClass);
  2385. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  2386. if ($bAllowAllData)
  2387. {
  2388. $oSearch->AllowAllData();
  2389. }
  2390. $oSet = new CMDBObjectSet($oSearch);
  2391. if ($oSet->Count() > 0)
  2392. {
  2393. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  2394. 'attribute' => $oExtKeyAttDef,
  2395. 'objects' => $oSet,
  2396. );
  2397. }
  2398. }
  2399. }
  2400. return $aDependentObjects;
  2401. }
  2402. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  2403. {
  2404. static $iLoopTimeLimit = null;
  2405. if ($iLoopTimeLimit == null)
  2406. {
  2407. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2408. }
  2409. $sClass = get_class($this);
  2410. $iThisId = $this->GetKey();
  2411. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  2412. if (array_key_exists($sClass, $aVisited))
  2413. {
  2414. if (in_array($iThisId, $aVisited[$sClass]))
  2415. {
  2416. return;
  2417. }
  2418. }
  2419. $aVisited[$sClass] = $iThisId;
  2420. if ($iDeleteOption == DEL_MANUAL)
  2421. {
  2422. // Stop the recursion here
  2423. return;
  2424. }
  2425. // Check the node itself
  2426. $this->DoCheckToDelete($oDeletionPlan);
  2427. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  2428. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  2429. // Getting and setting time limit are not symetric:
  2430. // www.php.net/manual/fr/function.set-time-limit.php#72305
  2431. $iPreviousTimeLimit = ini_get('max_execution_time');
  2432. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  2433. {
  2434. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  2435. {
  2436. set_time_limit($iLoopTimeLimit);
  2437. $oAttDef = $aData['attribute'];
  2438. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  2439. $oDepSet = $aData['objects'];
  2440. $oDepSet->Rewind();
  2441. while ($oDependentObj = $oDepSet->fetch())
  2442. {
  2443. $iId = $oDependentObj->GetKey();
  2444. if ($oAttDef->IsNullAllowed())
  2445. {
  2446. // Optional external key, list to reset
  2447. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  2448. {
  2449. // Move the child up one level i.e. set the same parent as the current object
  2450. $iParentId = $this->Get($oAttDef->GetCode());
  2451. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  2452. }
  2453. else
  2454. {
  2455. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  2456. }
  2457. }
  2458. else
  2459. {
  2460. // Mandatory external key, list to delete
  2461. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  2462. }
  2463. }
  2464. }
  2465. }
  2466. set_time_limit($iPreviousTimeLimit);
  2467. }
  2468. /**
  2469. * WILL DEPRECATED SOON
  2470. * Caching relying on an object set is not efficient since 2.0.3
  2471. * Use GetSynchroData instead
  2472. *
  2473. * Get all the synchro replica related to this object
  2474. * @param none
  2475. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  2476. */
  2477. public function GetMasterReplica()
  2478. {
  2479. $sOQL = "SELECT replica,datasource FROM SynchroReplica AS replica JOIN SynchroDataSource AS datasource ON replica.sync_source_id=datasource.id WHERE replica.dest_class = :dest_class AND replica.dest_id = :dest_id";
  2480. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2481. return $oReplicaSet;
  2482. }
  2483. /**
  2484. * Get all the synchro data related to this object
  2485. * @param none
  2486. * @return array of data_source_id => array
  2487. * 'source' => $oSource,
  2488. * 'attributes' => array of $oSynchroAttribute
  2489. * 'replica' => array of $oReplica (though only one should exist, misuse of the data sync can have this consequence)
  2490. */
  2491. public function GetSynchroData()
  2492. {
  2493. if ($this->m_aSynchroData == null)
  2494. {
  2495. $sOQL = "SELECT replica,datasource FROM SynchroReplica AS replica JOIN SynchroDataSource AS datasource ON replica.sync_source_id=datasource.id WHERE replica.dest_class = :dest_class AND replica.dest_id = :dest_id";
  2496. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2497. $this->m_aSynchroData = array();
  2498. while($aData = $oReplicaSet->FetchAssoc())
  2499. {
  2500. $iSourceId = $aData['datasource']->GetKey();
  2501. if (!array_key_exists($iSourceId, $this->m_aSynchroData))
  2502. {
  2503. $aAttributes = array();
  2504. $oAttrSet = $aData['datasource']->Get('attribute_list');
  2505. while($oSyncAttr = $oAttrSet->Fetch())
  2506. {
  2507. $aAttributes[$oSyncAttr->Get('attcode')] = $oSyncAttr;
  2508. }
  2509. $this->m_aSynchroData[$iSourceId] = array(
  2510. 'source' => $aData['datasource'],
  2511. 'attributes' => $aAttributes,
  2512. 'replica' => array()
  2513. );
  2514. }
  2515. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2516. $this->m_aSynchroData[$iSourceId]['replica'][] = $aData['replica'];
  2517. }
  2518. }
  2519. return $this->m_aSynchroData;
  2520. }
  2521. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2522. {
  2523. $iFlags = OPT_ATT_NORMAL;
  2524. foreach ($this->GetSynchroData() as $iSourceId => $aSourceData)
  2525. {
  2526. if ($iSourceId == SynchroExecution::GetCurrentTaskId())
  2527. {
  2528. // Ignore the current task (check to write => ok)
  2529. continue;
  2530. }
  2531. // Assumption: one replica - take the first one!
  2532. $oReplica = reset($aSourceData['replica']);
  2533. $oSource = $aSourceData['source'];
  2534. if (array_key_exists($sAttCode, $aSourceData['attributes']))
  2535. {
  2536. $oSyncAttr = $aSourceData['attributes'][$sAttCode];
  2537. if (($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2538. {
  2539. $iFlags |= OPT_ATT_SLAVE;
  2540. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2541. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2542. }
  2543. }
  2544. }
  2545. return $iFlags;
  2546. }
  2547. public function InSyncScope()
  2548. {
  2549. //
  2550. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2551. //
  2552. static $aSynchroClasses = null;
  2553. if (is_null($aSynchroClasses))
  2554. {
  2555. $aSynchroClasses = array();
  2556. $sOQL = "SELECT SynchroDataSource AS datasource";
  2557. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2558. while($oSource = $oSourceSet->Fetch())
  2559. {
  2560. $sTarget = $oSource->Get('scope_class');
  2561. $aSynchroClasses[] = $sTarget;
  2562. }
  2563. }
  2564. foreach($aSynchroClasses as $sClass)
  2565. {
  2566. if ($this instanceof $sClass)
  2567. {
  2568. return true;
  2569. }
  2570. }
  2571. return false;
  2572. }
  2573. /////////////////////////////////////////////////////////////////////////
  2574. //
  2575. // Experimental iDisplay implementation
  2576. //
  2577. /////////////////////////////////////////////////////////////////////////
  2578. public static function MapContextParam($sContextParam)
  2579. {
  2580. return null;
  2581. }
  2582. public function GetHilightClass()
  2583. {
  2584. $sCode = $this->ComputeHighlightCode();
  2585. if($sCode != '')
  2586. {
  2587. $aHighlightScale = MetaModel::GetHighlightScale(get_class($this));
  2588. if (array_key_exists($sCode, $aHighlightScale))
  2589. {
  2590. return $aHighlightScale[$sCode]['color'];
  2591. }
  2592. }
  2593. return HILIGHT_CLASS_NONE;
  2594. }
  2595. public function DisplayDetails(WebPage $oPage, $bEditMode = false)
  2596. {
  2597. $oPage->add('<h1>'.MetaModel::GetName(get_class($this)).': '.$this->GetName().'</h1>');
  2598. $aValues = array();
  2599. $aList = MetaModel::FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2600. if (empty($aList))
  2601. {
  2602. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2603. }
  2604. foreach($aList as $sAttCode)
  2605. {
  2606. $aValues[$sAttCode] = array('label' => MetaModel::GetLabel(get_class($this), $sAttCode), 'value' => $this->GetAsHTML($sAttCode));
  2607. }
  2608. $oPage->details($aValues);
  2609. }
  2610. const CALLBACK_AFTERINSERT = 0;
  2611. /**
  2612. * Register a call back that will be called when some internal event happens
  2613. *
  2614. * @param $iType string Any of the CALLBACK_x constants
  2615. * @param $callback callable Call specification like a function name, or array('<class>', '<method>') or array($object, '<method>')
  2616. * @param $aParameters Array Values that will be passed to the callback, after $this
  2617. */
  2618. public function RegisterCallback($iType, $callback, $aParameters = array())
  2619. {
  2620. $sCallBackName = '';
  2621. if (!is_callable($callback, false, $sCallBackName))
  2622. {
  2623. throw new Exception('Registering an unknown/protected function or wrong syntax for the call spec: '.$sCallBackName);
  2624. }
  2625. $this->m_aCallbacks[$iType][] = array(
  2626. 'callback' => $callback,
  2627. 'params' => $aParameters
  2628. );
  2629. }
  2630. }