dbobject.class.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Class dbObject: the root of persistent classes
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once('metamodel.class.php');
  25. /**
  26. * A persistent object, as defined by the metamodel
  27. *
  28. * @package iTopORM
  29. */
  30. abstract class DBObject
  31. {
  32. private static $m_aMemoryObjectsByClass = array();
  33. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  34. private $m_iKey = null;
  35. private $m_aCurrValues = array();
  36. protected $m_aOrigValues = array();
  37. protected $m_aExtendedData = null;
  38. private $m_bDirty = false; // Means: "a modification is ongoing"
  39. // The object may have incorrect external keys, then any attempt of reload must be avoided
  40. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  41. // if null, then the check has to be performed again to know the status
  42. protected $m_aCheckIssues = null;
  43. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  44. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  45. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  46. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  47. public function __construct($aRow = null, $sClassAlias = '', $aExtendedDataSpec = null)
  48. {
  49. if (!empty($aRow))
  50. {
  51. $this->FromRow($aRow, $sClassAlias, $aExtendedDataSpec);
  52. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  53. return;
  54. }
  55. // Creation of brand new object
  56. //
  57. $this->m_iKey = self::GetNextTempId(get_class($this));
  58. // set default values
  59. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  60. {
  61. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  62. $this->m_aOrigValues[$sAttCode] = null;
  63. if ($oAttDef->IsExternalField())
  64. {
  65. // This field has to be read from the DB
  66. $this->m_aLoadedAtt[$sAttCode] = false;
  67. }
  68. else
  69. {
  70. // No need to trigger a reload for that attribute
  71. // Let's consider it as being already fully loaded
  72. $this->m_aLoadedAtt[$sAttCode] = true;
  73. }
  74. }
  75. }
  76. // Read-only <=> Written once (archive)
  77. public function RegisterAsDirty()
  78. {
  79. // While the object may be written to the DB, it is NOT possible to reload it
  80. // or at least not possible to reload it the same way
  81. $this->m_bDirty = true;
  82. }
  83. public function IsNew()
  84. {
  85. return (!$this->m_bIsInDB);
  86. }
  87. // Returns an Id for memory objects
  88. static protected function GetNextTempId($sClass)
  89. {
  90. if (!array_key_exists($sClass, self::$m_aMemoryObjectsByClass))
  91. {
  92. self::$m_aMemoryObjectsByClass[$sClass] = 0;
  93. }
  94. self::$m_aMemoryObjectsByClass[$sClass]++;
  95. return (- self::$m_aMemoryObjectsByClass[$sClass]);
  96. }
  97. public function __toString()
  98. {
  99. $sRet = '';
  100. $sClass = get_class($this);
  101. $sRootClass = MetaModel::GetRootClass($sClass);
  102. $iPKey = $this->GetKey();
  103. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  104. $sRet .= "<ul class=\"treeview\">\n";
  105. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  106. {
  107. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  108. }
  109. $sRet .= "</ul>";
  110. return $sRet;
  111. }
  112. // Restore initial values... mmmm, to be discussed
  113. public function DBRevert()
  114. {
  115. $this->Reload();
  116. }
  117. protected function IsFullyLoaded()
  118. {
  119. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  120. {
  121. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  122. if ($bIsLoaded !== true)
  123. {
  124. return false;
  125. }
  126. }
  127. return true;
  128. }
  129. protected function Reload()
  130. {
  131. assert($this->m_bIsInDB);
  132. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey);
  133. if (empty($aRow))
  134. {
  135. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  136. }
  137. $this->FromRow($aRow);
  138. // Process linked set attributes
  139. //
  140. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  141. {
  142. if (!$oAttDef->IsLinkSet()) continue;
  143. // Load the link information
  144. $sLinkClass = $oAttDef->GetLinkedClass();
  145. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  146. // The class to target is not the current class, because if this is a derived class,
  147. // it may differ from the target class, then things start to become confusing
  148. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  149. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  150. $oMyselfSearch = new DBObjectSearch($sMyClass);
  151. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  152. $oLinkSearch = new DBObjectSearch($sLinkClass);
  153. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  154. $oLinks = new DBObjectSet($oLinkSearch);
  155. $this->m_aCurrValues[$sAttCode] = $oLinks;
  156. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  157. $this->m_aLoadedAtt[$sAttCode] = true;
  158. }
  159. $this->m_bFullyLoaded = true;
  160. }
  161. protected function FromRow($aRow, $sClassAlias = '', $aExtendedDataSpec = null)
  162. {
  163. if (strlen($sClassAlias) == 0)
  164. {
  165. // Default to the current class
  166. $sClassAlias = get_class($this);
  167. }
  168. $this->m_iKey = null;
  169. $this->m_bIsInDB = true;
  170. $this->m_aCurrValues = array();
  171. $this->m_aOrigValues = array();
  172. $this->m_aLoadedAtt = array();
  173. $this->m_bCheckStatus = true;
  174. // Get the key
  175. //
  176. $sKeyField = $sClassAlias."id";
  177. if (!array_key_exists($sKeyField, $aRow))
  178. {
  179. // #@# Bug ?
  180. throw new CoreException("Missing key for class '".get_class($this)."'");
  181. }
  182. else
  183. {
  184. $iPKey = $aRow[$sKeyField];
  185. if (!self::IsValidPKey($iPKey))
  186. {
  187. throw new CoreWarning("An object id must be an integer value ($iPKey)");
  188. }
  189. $this->m_iKey = $iPKey;
  190. }
  191. // Build the object from an array of "attCode"=>"value")
  192. //
  193. $bFullyLoaded = true; // ... set to false if any attribute is not found
  194. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  195. {
  196. // Say something, whatever the type of attribute
  197. $this->m_aLoadedAtt[$sAttCode] = false;
  198. // Skip links (could not be loaded by the mean of this query)
  199. if ($oAttDef->IsLinkSet()) continue;
  200. // Note: we assume that, for a given attribute, if it can be loaded,
  201. // then one column will be found with an empty suffix, the others have a suffix
  202. // Take care: the function isset will return false in case the value is null,
  203. // which is something that could happen on open joins
  204. $sAttRef = $sClassAlias.$sAttCode;
  205. if (array_key_exists($sAttRef, $aRow))
  206. {
  207. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  208. $this->m_aCurrValues[$sAttCode] = $value;
  209. $this->m_aOrigValues[$sAttCode] = $value;
  210. $this->m_aLoadedAtt[$sAttCode] = true;
  211. }
  212. else
  213. {
  214. // This attribute was expected and not found in the query columns
  215. $bFullyLoaded = false;
  216. }
  217. }
  218. // Load extended data
  219. if ($aExtendedDataSpec != null)
  220. {
  221. $aExtendedDataSpec['table'];
  222. foreach($aExtendedDataSpec['fields'] as $sColumn)
  223. {
  224. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  225. if (array_key_exists($sColRef, $aRow))
  226. {
  227. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  228. }
  229. }
  230. }
  231. return $bFullyLoaded;
  232. }
  233. public function Set($sAttCode, $value)
  234. {
  235. if ($sAttCode == 'finalclass')
  236. {
  237. // Ignore it - this attribute is set upon object creation and that's it
  238. return;
  239. }
  240. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  241. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  242. {
  243. // First time Set is called... ensure that the object gets fully loaded
  244. // Otherwise we would lose the values on a further Reload
  245. // + consistency does not make sense !
  246. $this->Reload();
  247. }
  248. if ($oAttDef->IsExternalKey() && is_object($value))
  249. {
  250. // Setting an external key with a whole object (instead of just an ID)
  251. // let's initialize also the external fields that depend on it
  252. // (useful when building objects in memory and not from a query)
  253. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  254. {
  255. 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");
  256. }
  257. else
  258. {
  259. // The object has changed, reset caches
  260. $this->m_bCheckStatus = null;
  261. $this->m_aAsArgs = null;
  262. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  263. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  264. {
  265. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  266. {
  267. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  268. }
  269. }
  270. }
  271. return;
  272. }
  273. if(!$oAttDef->IsScalar() && !is_object($value))
  274. {
  275. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  276. }
  277. if($oAttDef->IsLinkSet())
  278. {
  279. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  280. {
  281. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  282. }
  283. $oObjectSet = $value;
  284. $sSetClass = $oObjectSet->GetClass();
  285. $sLinkClass = $oAttDef->GetLinkedClass();
  286. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  287. if ($sSetClass != $sLinkClass)
  288. {
  289. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  290. }
  291. }
  292. $realvalue = $oAttDef->MakeRealValue($value);
  293. $this->m_aCurrValues[$sAttCode] = $realvalue;
  294. // The object has changed, reset caches
  295. $this->m_bCheckStatus = null;
  296. $this->m_aAsArgs = null;
  297. // Make sure we do not reload it anymore... before saving it
  298. $this->RegisterAsDirty();
  299. }
  300. public function Get($sAttCode)
  301. {
  302. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  303. {
  304. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  305. }
  306. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  307. {
  308. // #@# non-scalar attributes.... handle that differently
  309. $this->Reload();
  310. }
  311. $value = $this->m_aCurrValues[$sAttCode];
  312. if ($value instanceof DBObjectSet)
  313. {
  314. $value->Rewind();
  315. }
  316. return $value;
  317. }
  318. public function GetOriginal($sAttCode)
  319. {
  320. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  321. {
  322. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  323. }
  324. return $this->m_aOrigValues[$sAttCode];
  325. }
  326. /**
  327. * Returns data loaded by the mean of a dynamic and explicit JOIN
  328. */
  329. public function GetExtendedData()
  330. {
  331. return $this->m_aExtendedData;
  332. }
  333. /**
  334. * Updates the value of an external field by (re)loading the object
  335. * corresponding to the external key and getting the value from it
  336. * @param string $sAttCode Attribute code of the external field to update
  337. * @return void
  338. */
  339. protected function UpdateExternalField($sAttCode)
  340. {
  341. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  342. if ($oAttDef->IsExternalField())
  343. {
  344. $sTargetClass = $oAttDef->GetTargetClass();
  345. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  346. $oObj = MetaModel::GetObject($sTargetClass, $objkey);
  347. if (is_object($oObj))
  348. {
  349. $value = $oObj->Get($oAttDef->GetExtAttCode());
  350. $this->Set($sAttCode, $value);
  351. }
  352. }
  353. }
  354. public function ComputeValues()
  355. {
  356. }
  357. // Compute scalar attributes that depend on any other type of attribute
  358. final public function DoComputeValues()
  359. {
  360. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  361. // First check that we are not currently computing the fields
  362. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  363. foreach (debug_backtrace() as $aCallInfo)
  364. {
  365. if (!array_key_exists("class", $aCallInfo)) continue;
  366. if ($aCallInfo["class"] != get_class($this)) continue;
  367. if ($aCallInfo["function"] != "ComputeValues") continue;
  368. return; //skip!
  369. }
  370. $this->ComputeValues();
  371. }
  372. public function GetAsHTML($sAttCode)
  373. {
  374. $sClass = get_class($this);
  375. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  376. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  377. {
  378. //return $this->Get($sAttCode.'_friendlyname');
  379. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  380. $iTargetKey = $this->Get($sAttCode);
  381. $sLabel = $this->Get($sAttCode.'_friendlyname');
  382. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  383. }
  384. // That's a standard attribute (might be an ext field or a direct field, etc.)
  385. return $oAtt->GetAsHTML($this->Get($sAttCode));
  386. }
  387. public function GetEditValue($sAttCode)
  388. {
  389. $sClass = get_class($this);
  390. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  391. if ($oAtt->IsExternalKey())
  392. {
  393. $sTargetClass = $oAtt->GetTargetClass();
  394. if ($this->IsNew())
  395. {
  396. // The current object exists only in memory, don't try to query it in the DB !
  397. // instead let's query for the object pointed by the external key, and get its name
  398. $targetObjId = $this->Get($sAttCode);
  399. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  400. if (is_object($oTargetObj))
  401. {
  402. $sEditValue = $oTargetObj->GetName();
  403. }
  404. else
  405. {
  406. $sEditValue = 0;
  407. }
  408. }
  409. else
  410. {
  411. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  412. }
  413. }
  414. else
  415. {
  416. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  417. }
  418. return $sEditValue;
  419. }
  420. public function GetAsXML($sAttCode)
  421. {
  422. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  423. return $oAtt->GetAsXML($this->Get($sAttCode));
  424. }
  425. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  426. {
  427. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  428. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  429. }
  430. protected static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '')
  431. {
  432. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  433. $oAppContext = new ApplicationContext();
  434. $sPage = self::ComputeUIPage($sObjClass);
  435. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  436. // Safety net
  437. //
  438. if (empty($sLabel))
  439. {
  440. $sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  441. }
  442. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  443. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  444. }
  445. public function GetHyperlink()
  446. {
  447. if ($this->IsNew()) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  448. $oAppContext = new ApplicationContext();
  449. $sPage = $this->GetUIPage();
  450. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  451. $sObjClass = get_class($this);
  452. $sObjKey = $this->GetKey();
  453. $sLabel = $this->GetName();
  454. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  455. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  456. }
  457. public static function ComputeUIPage($sClass)
  458. {
  459. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  460. if (!isset($aUIPagesCache[$sClass]))
  461. {
  462. $UIPage = false;
  463. if (is_callable("$sClass::GetUIPage"))
  464. {
  465. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  466. }
  467. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  468. }
  469. $sPage = $aUIPagesCache[$sClass];
  470. return $sPage;
  471. }
  472. public static function GetUIPage()
  473. {
  474. return 'UI.php';
  475. }
  476. // could be in the metamodel ?
  477. public static function IsValidPKey($value)
  478. {
  479. return ((string)$value === (string)(int)$value);
  480. }
  481. public function GetKey()
  482. {
  483. return $this->m_iKey;
  484. }
  485. public function SetKey($iNewKey)
  486. {
  487. if (!self::IsValidPKey($iNewKey))
  488. {
  489. throw new CoreException("An object id must be an integer value ($iNewKey)");
  490. }
  491. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  492. {
  493. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  494. }
  495. $this->m_iKey = $iNewKey;
  496. }
  497. /**
  498. * Get the icon representing this object
  499. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  500. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  501. */
  502. public function GetIcon($bImgTag = true)
  503. {
  504. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  505. }
  506. public function GetName()
  507. {
  508. $aNameSpec = MetaModel::GetNameSpec(get_class($this));
  509. $sFormat = $aNameSpec[0];
  510. $aAttributes = $aNameSpec[1];
  511. $aValues = array();
  512. foreach ($aAttributes as $sAttCode)
  513. {
  514. if (empty($sAttCode))
  515. {
  516. $aValues[] = $this->m_iKey;
  517. }
  518. else
  519. {
  520. $aValues[] = $this->Get($sAttCode);
  521. }
  522. }
  523. return vsprintf($sFormat, $aValues);
  524. }
  525. public function GetState()
  526. {
  527. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  528. if (empty($sStateAttCode))
  529. {
  530. return '';
  531. }
  532. else
  533. {
  534. return $this->Get($sStateAttCode);
  535. }
  536. }
  537. public function GetStateLabel()
  538. {
  539. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  540. if (empty($sStateAttCode))
  541. {
  542. return '';
  543. }
  544. else
  545. {
  546. $sStateValue = $this->Get($sStateAttCode);
  547. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  548. }
  549. }
  550. public function GetStateDescription()
  551. {
  552. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  553. if (empty($sStateAttCode))
  554. {
  555. return '';
  556. }
  557. else
  558. {
  559. $sStateValue = $this->Get($sStateAttCode);
  560. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  561. }
  562. }
  563. /**
  564. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  565. * for the given attribute in the current state of the object
  566. * @param string $sAttCode The code of the attribute
  567. * @return integer Flags: the binary combination of the flags applicable to this attribute
  568. */
  569. public function GetAttributeFlags($sAttCode)
  570. {
  571. $iFlags = 0; // By default (if no life cycle) no flag at all
  572. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  573. if (!empty($sStateAttCode))
  574. {
  575. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  576. }
  577. return $iFlags;
  578. }
  579. // check if the given (or current) value is suitable for the attribute
  580. // return true if successfull
  581. // return the error desciption otherwise
  582. public function CheckValue($sAttCode, $value = null)
  583. {
  584. if (!is_null($value))
  585. {
  586. $toCheck = $value;
  587. }
  588. else
  589. {
  590. $toCheck = $this->Get($sAttCode);
  591. }
  592. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  593. if (!$oAtt->IsWritable())
  594. {
  595. return true;
  596. }
  597. elseif ($oAtt->IsNull($toCheck))
  598. {
  599. if ($oAtt->IsNullAllowed())
  600. {
  601. return true;
  602. }
  603. else
  604. {
  605. return "Null not allowed";
  606. }
  607. }
  608. elseif ($oAtt->IsExternalKey())
  609. {
  610. if (!MetaModel::SkipCheckExtKeys())
  611. {
  612. $sTargetClass = $oAtt->GetTargetClass();
  613. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  614. if (is_null($oTargetObj))
  615. {
  616. return "Target object not found ($sTargetClass::$toCheck)";
  617. }
  618. }
  619. }
  620. elseif ($oAtt->IsScalar())
  621. {
  622. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  623. if (count($aValues) > 0)
  624. {
  625. if (!array_key_exists($toCheck, $aValues))
  626. {
  627. return "Value not allowed [$toCheck]";
  628. }
  629. }
  630. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  631. {
  632. $iLen = strlen($toCheck);
  633. if ($iLen > $iMaxSize)
  634. {
  635. return "String too long (found $iLen, limited to $iMaxSize)";
  636. }
  637. }
  638. if (!$oAtt->CheckFormat($toCheck))
  639. {
  640. return "Wrong format [$toCheck]";
  641. }
  642. }
  643. return true;
  644. }
  645. // check attributes together
  646. public function CheckConsistency()
  647. {
  648. return true;
  649. }
  650. // check integrity rules (before inserting or updating the object)
  651. // a displayable error is returned
  652. public function DoCheckToWrite()
  653. {
  654. $this->DoComputeValues();
  655. $this->m_aCheckIssues = array();
  656. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  657. {
  658. $res = $this->CheckValue($sAttCode);
  659. if ($res !== true)
  660. {
  661. // $res contains the error description
  662. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  663. }
  664. }
  665. if (count($this->m_aCheckIssues) > 0)
  666. {
  667. // No need to check consistency between attributes if any of them has
  668. // an unexpected value
  669. return;
  670. }
  671. $res = $this->CheckConsistency();
  672. if ($res !== true)
  673. {
  674. // $res contains the error description
  675. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  676. }
  677. }
  678. final public function CheckToWrite()
  679. {
  680. if (MetaModel::SkipCheckToWrite())
  681. {
  682. return array(true, array());
  683. }
  684. if (is_null($this->m_bCheckStatus))
  685. {
  686. $oKPI = new ExecutionKPI();
  687. $this->DoCheckToWrite();
  688. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  689. if (count($this->m_aCheckIssues) == 0)
  690. {
  691. $this->m_bCheckStatus = true;
  692. }
  693. else
  694. {
  695. $this->m_bCheckStatus = false;
  696. }
  697. }
  698. return array($this->m_bCheckStatus, $this->m_aCheckIssues);
  699. }
  700. // check if it is allowed to delete the existing object from the database
  701. // a displayable error is returned
  702. public function CheckToDelete()
  703. {
  704. return true;
  705. }
  706. protected function ListChangedValues(array $aProposal)
  707. {
  708. $aDelta = array();
  709. foreach ($aProposal as $sAtt => $proposedValue)
  710. {
  711. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  712. {
  713. // The value was not set
  714. $aDelta[$sAtt] = $proposedValue;
  715. }
  716. elseif(is_object($proposedValue))
  717. {
  718. // The value is an object, the comparison is not strict
  719. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  720. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  721. {
  722. $aDelta[$sAtt] = $proposedValue;
  723. }
  724. }
  725. else
  726. {
  727. // The value is a scalar, the comparison must be 100% strict
  728. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  729. {
  730. //echo "$sAtt:<pre>\n";
  731. //var_dump($this->m_aOrigValues[$sAtt]);
  732. //var_dump($proposedValue);
  733. //echo "</pre>\n";
  734. $aDelta[$sAtt] = $proposedValue;
  735. }
  736. }
  737. }
  738. return $aDelta;
  739. }
  740. // List the attributes that have been changed
  741. // Returns an array of attname => currentvalue
  742. public function ListChanges()
  743. {
  744. return $this->ListChangedValues($this->m_aCurrValues);
  745. }
  746. // Tells whether or not an object was modified
  747. public function IsModified()
  748. {
  749. $aChanges = $this->ListChanges();
  750. return (count($aChanges) != 0);
  751. }
  752. // used both by insert/update
  753. private function DBWriteLinks()
  754. {
  755. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  756. {
  757. if (!$oAttDef->IsLinkSet()) continue;
  758. $oLinks = $this->Get($sAttCode);
  759. $oLinks->Rewind();
  760. while ($oLinkedObject = $oLinks->Fetch())
  761. {
  762. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  763. if ($oLinkedObject->IsModified())
  764. {
  765. $oLinkedObject->DBWrite();
  766. }
  767. }
  768. // Delete the objects that were initialy present and disappeared from the list
  769. // (if any)
  770. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  771. if ($oOriginalSet != null)
  772. {
  773. $aOriginalList = $oOriginalSet->ToArray();
  774. $aNewSet = $oLinks->ToArray();
  775. foreach($aOriginalList as $iId => $oObject)
  776. {
  777. if (!array_key_exists($iId, $aNewSet))
  778. {
  779. // It disappeared from the list
  780. $oObject->DBDelete();
  781. }
  782. }
  783. }
  784. }
  785. }
  786. private function DBInsertSingleTable($sTableClass)
  787. {
  788. $sTable = MetaModel::DBGetTable($sTableClass);
  789. // Abstract classes or classes having no specific attribute do not have an associated table
  790. if ($sTable == '') return;
  791. $sClass = get_class($this);
  792. // fields in first array, values in the second
  793. $aFieldsToWrite = array();
  794. $aValuesToWrite = array();
  795. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  796. {
  797. // Add it to the list of fields to write
  798. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  799. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  800. }
  801. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  802. {
  803. // Skip this attribute if not defined in this table
  804. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  805. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  806. foreach($aAttColumns as $sColumn => $sValue)
  807. {
  808. $aFieldsToWrite[] = "`$sColumn`";
  809. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  810. }
  811. }
  812. if (count($aValuesToWrite) == 0) return false;
  813. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  814. if (MetaModel::DBIsReadOnly())
  815. {
  816. $iNewKey = -1;
  817. }
  818. else
  819. {
  820. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  821. }
  822. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  823. if (empty($this->m_iKey))
  824. {
  825. // Take the autonumber
  826. $this->m_iKey = $iNewKey;
  827. }
  828. return $this->m_iKey;
  829. }
  830. // Insert of record for the new object into the database
  831. // Returns the key of the newly created object
  832. public function DBInsertNoReload()
  833. {
  834. if ($this->m_bIsInDB)
  835. {
  836. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  837. }
  838. $sClass = get_class($this);
  839. $sRootClass = MetaModel::GetRootClass($sClass);
  840. // Ensure the update of the values (we are accessing the data directly)
  841. $this->DoComputeValues();
  842. $this->OnInsert();
  843. if ($this->m_iKey < 0)
  844. {
  845. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  846. $this->m_iKey = null;
  847. }
  848. // If not automatically computed, then check that the key is given by the caller
  849. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  850. {
  851. if (empty($this->m_iKey))
  852. {
  853. 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));
  854. }
  855. }
  856. // Ultimate check - ensure DB integrity
  857. list($bRes, $aIssues) = $this->CheckToWrite();
  858. if (!$bRes)
  859. {
  860. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  861. }
  862. // First query built upon on the root class, because the ID must be created first
  863. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  864. // Then do the leaf class, if different from the root class
  865. if ($sClass != $sRootClass)
  866. {
  867. $this->DBInsertSingleTable($sClass);
  868. }
  869. // Then do the other classes
  870. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  871. {
  872. if ($sParentClass == $sRootClass) continue;
  873. $this->DBInsertSingleTable($sParentClass);
  874. }
  875. $this->DBWriteLinks();
  876. $this->m_bIsInDB = true;
  877. $this->m_bDirty = false;
  878. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  879. $this->m_aAsArgs = null;
  880. $this->AfterInsert();
  881. // Activate any existing trigger
  882. $sClass = get_class($this);
  883. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  884. while ($oTrigger = $oSet->Fetch())
  885. {
  886. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  887. {
  888. $oTrigger->DoActivate($this->ToArgs('this'));
  889. }
  890. }
  891. return $this->m_iKey;
  892. }
  893. public function DBInsert()
  894. {
  895. $this->DBInsertNoReload();
  896. $this->Reload();
  897. return $this->m_iKey;
  898. }
  899. public function DBInsertTracked(CMDBChange $oVoid)
  900. {
  901. return $this->DBInsert();
  902. }
  903. // Creates a copy of the current object into the database
  904. // Returns the id of the newly created object
  905. public function DBClone($iNewKey = null)
  906. {
  907. $this->m_bIsInDB = false;
  908. $this->m_iKey = $iNewKey;
  909. return $this->DBInsert();
  910. }
  911. /**
  912. * This function is automatically called after cloning an object with the "clone" PHP language construct
  913. * The purpose of this method is to reset the appropriate attributes of the object in
  914. * order to make sure that the newly cloned object is really distinct from its clone
  915. */
  916. public function __clone()
  917. {
  918. $this->m_bIsInDB = false;
  919. $this->m_bDirty = true;
  920. $this->m_iKey = self::GetNextTempId(get_class($this));
  921. }
  922. // Update a record
  923. public function DBUpdate()
  924. {
  925. if (!$this->m_bIsInDB)
  926. {
  927. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  928. }
  929. $this->DoComputeValues();
  930. $this->OnUpdate();
  931. $aChanges = $this->ListChanges();
  932. if (count($aChanges) == 0)
  933. {
  934. //throw new CoreWarning("Attempting to update an unchanged object");
  935. return;
  936. }
  937. // Ultimate check - ensure DB integrity
  938. list($bRes, $aIssues) = $this->CheckToWrite();
  939. if (!$bRes)
  940. {
  941. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => get_class($this), 'id' => $this->GetKey(), 'issues' => $aIssues));
  942. }
  943. $bHasANewExternalKeyValue = false;
  944. foreach($aChanges as $sAttCode => $valuecurr)
  945. {
  946. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  947. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  948. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  949. }
  950. // Update scalar attributes
  951. if (count($aChanges) != 0)
  952. {
  953. $oFilter = new DBObjectSearch(get_class($this));
  954. $oFilter->AddCondition('id', $this->m_iKey, '=');
  955. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  956. if (!MetaModel::DBIsReadOnly())
  957. {
  958. CMDBSource::Query($sSQL);
  959. }
  960. }
  961. $this->DBWriteLinks();
  962. $this->m_bDirty = false;
  963. $this->AfterUpdate();
  964. // Reload to get the external attributes
  965. if ($bHasANewExternalKeyValue)
  966. {
  967. $this->Reload();
  968. }
  969. return $this->m_iKey;
  970. }
  971. public function DBUpdateTracked(CMDBChange $oVoid)
  972. {
  973. return $this->DBUpdate();
  974. }
  975. // Make the current changes persistent - clever wrapper for Insert or Update
  976. public function DBWrite()
  977. {
  978. if ($this->m_bIsInDB)
  979. {
  980. return $this->DBUpdate();
  981. }
  982. else
  983. {
  984. return $this->DBInsert();
  985. }
  986. }
  987. // Delete a record
  988. public function DBDelete()
  989. {
  990. $oFilter = new DBObjectSearch(get_class($this));
  991. $oFilter->AddCondition('id', $this->m_iKey, '=');
  992. $this->OnDelete();
  993. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  994. if (!MetaModel::DBIsReadOnly())
  995. {
  996. CMDBSource::Query($sSQL);
  997. }
  998. $this->AfterDelete();
  999. $this->m_bIsInDB = false;
  1000. $this->m_iKey = null;
  1001. }
  1002. public function DBDeleteTracked(CMDBChange $oVoid)
  1003. {
  1004. $this->DBDelete();
  1005. }
  1006. public function EnumTransitions()
  1007. {
  1008. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1009. if (empty($sStateAttCode)) return array();
  1010. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1011. return MetaModel::EnumTransitions(get_class($this), $sState);
  1012. }
  1013. public function ApplyStimulus($sStimulusCode)
  1014. {
  1015. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1016. if (empty($sStateAttCode)) return false;
  1017. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1018. $aStateTransitions = $this->EnumTransitions();
  1019. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1020. // Change the state before proceeding to the actions, this is necessary because an action might
  1021. // trigger another stimuli (alternative: push the stimuli into a queue)
  1022. $sPreviousState = $this->Get($sStateAttCode);
  1023. $sNewState = $aTransitionDef['target_state'];
  1024. $this->Set($sStateAttCode, $sNewState);
  1025. // $aTransitionDef is an
  1026. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1027. $bSuccess = true;
  1028. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1029. {
  1030. // std PHP spec
  1031. $aActionCallSpec = array($this, $sActionHandler);
  1032. if (!is_callable($aActionCallSpec))
  1033. {
  1034. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1035. return;
  1036. }
  1037. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1038. // if one call fails, the whole is considered as failed
  1039. if (!$bRet) $bSuccess = false;
  1040. }
  1041. // Change state triggers...
  1042. $sClass = get_class($this);
  1043. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1044. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1045. while ($oTrigger = $oSet->Fetch())
  1046. {
  1047. $oTrigger->DoActivate($this->ToArgs('this'));
  1048. }
  1049. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1050. while ($oTrigger = $oSet->Fetch())
  1051. {
  1052. $oTrigger->DoActivate($this->ToArgs('this'));
  1053. }
  1054. return $bSuccess;
  1055. }
  1056. // Make standard context arguments
  1057. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1058. // Several options here:
  1059. // 1) cache the result
  1060. // 2) set only the object ref and resolve the values iif needed from contextual templates and queries (easy for the queries, not for the templates)
  1061. public function ToArgs($sArgName = 'this')
  1062. {
  1063. if (is_null($this->m_aAsArgs))
  1064. {
  1065. $oKPI = new ExecutionKPI();
  1066. $aScalarArgs = array();
  1067. $aScalarArgs[$sArgName] = $this->GetKey();
  1068. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1069. $aScalarArgs[$sArgName.'->object()'] = $this;
  1070. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  1071. // #@# Prototype for a user portal - to be dehardcoded later
  1072. $sToPortal = utils::GetAbsoluteUrlPath().'../portal/index.php?operation=details&id='.$this->GetKey();
  1073. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1074. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1075. $sClass = get_class($this);
  1076. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1077. {
  1078. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1079. if ($oAttDef->IsScalar())
  1080. {
  1081. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1082. $sAsHtml = $this->GetAsHtml($sAttCode);
  1083. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1084. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1085. }
  1086. }
  1087. $this->m_aAsArgs = $aScalarArgs;
  1088. $oKPI->ComputeStats('ToArgs', get_class($this));
  1089. }
  1090. return $this->m_aAsArgs;
  1091. }
  1092. // To be optionaly overloaded
  1093. protected function OnInsert()
  1094. {
  1095. }
  1096. // To be optionaly overloaded
  1097. protected function AfterInsert()
  1098. {
  1099. }
  1100. // To be optionaly overloaded
  1101. protected function OnUpdate()
  1102. {
  1103. }
  1104. // To be optionaly overloaded
  1105. protected function AfterUpdate()
  1106. {
  1107. }
  1108. // To be optionaly overloaded
  1109. protected function OnDelete()
  1110. {
  1111. }
  1112. // To be optionaly overloaded
  1113. protected function AfterDelete()
  1114. {
  1115. }
  1116. // Return an empty set for the parent of all
  1117. public static function GetRelationQueries($sRelCode)
  1118. {
  1119. return array();
  1120. }
  1121. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1122. {
  1123. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1124. {
  1125. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1126. $sQuery = $aQueryInfo["sQuery"];
  1127. $bPropagate = $aQueryInfo["bPropagate"];
  1128. $iDistance = $aQueryInfo["iDistance"];
  1129. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1130. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1131. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1132. while ($oObj = $oObjSet->Fetch())
  1133. {
  1134. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1135. $sObjKey = $oObj->GetKey();
  1136. if (array_key_exists($sRootClass, $aResults))
  1137. {
  1138. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1139. {
  1140. continue; // already visited, skip
  1141. }
  1142. }
  1143. $aResults[$sRootClass][$sObjKey] = $oObj;
  1144. if ($iDepth > 0)
  1145. {
  1146. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1147. }
  1148. }
  1149. }
  1150. return $aResults;
  1151. }
  1152. public function GetReferencingObjects()
  1153. {
  1154. $aDependentObjects = array();
  1155. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1156. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1157. {
  1158. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1159. {
  1160. // skip if this external key is behind an external field
  1161. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1162. $oSearch = new DBObjectSearch($sRemoteClass);
  1163. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1164. $oSet = new CMDBObjectSet($oSearch);
  1165. if ($oSet->Count() > 0)
  1166. {
  1167. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1168. 'attribute' => $oExtKeyAttDef,
  1169. 'objects' => $oSet,
  1170. );
  1171. }
  1172. }
  1173. }
  1174. return $aDependentObjects;
  1175. }
  1176. /**
  1177. * $aDeletedObjs = array(); // [class][key] => structure
  1178. * $aResetedObjs = array(); // [class][key] => object
  1179. */
  1180. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1181. {
  1182. if (array_key_exists(get_class($this), $aVisited))
  1183. {
  1184. if (in_array($this->GetKey(), $aVisited[get_class($this)]))
  1185. {
  1186. return;
  1187. }
  1188. }
  1189. $aVisited[get_class($this)] = $this->GetKey();
  1190. $aDependentObjects = $this->GetReferencingObjects();
  1191. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1192. {
  1193. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1194. {
  1195. $oAttDef = $aData['attribute'];
  1196. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1197. $oDepSet = $aData['objects'];
  1198. $oDepSet->Rewind();
  1199. while ($oDependentObj = $oDepSet->fetch())
  1200. {
  1201. $iId = $oDependentObj->GetKey();
  1202. if ($oAttDef->IsNullAllowed())
  1203. {
  1204. // Optional external key, list to reset
  1205. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1206. {
  1207. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1208. }
  1209. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1210. }
  1211. else
  1212. {
  1213. // Mandatory external key, list to delete
  1214. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1215. {
  1216. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1217. if ($iCurrentOption == DEL_AUTO)
  1218. {
  1219. // be conservative, take the new option
  1220. // (DEL_MANUAL has precedence over DEL_AUTO)
  1221. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1222. }
  1223. else
  1224. {
  1225. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1226. }
  1227. }
  1228. else
  1229. {
  1230. // First time we find the given object in the list
  1231. // (and most likely case is that no other occurence will be found)
  1232. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1233. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1234. // Recursively inspect this object
  1235. if ($iDeletePropagationOption == DEL_AUTO)
  1236. {
  1237. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1238. }
  1239. }
  1240. }
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. ?>