dbobject.class.php 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. <?php
  2. /**
  3. * ???
  4. * the class a persistent object must be derived from
  5. *
  6. * @package iTopORM
  7. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  8. * @author Denis Flaven <denisflave@free.fr>
  9. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  10. * @link www.itop.com
  11. * @since 1.0
  12. * @version 1.1.1.1 $
  13. */
  14. require_once('metamodel.class.php');
  15. /**
  16. * A persistent object, as defined by the metamodel
  17. *
  18. * @package iTopORM
  19. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  20. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  21. * @link www.itop.com
  22. * @since 1.0
  23. * @version $itopversion$
  24. */
  25. abstract class DBObject
  26. {
  27. private static $m_aMemoryObjectsByClass = array();
  28. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  29. private $m_iKey = null;
  30. private $m_aCurrValues = array();
  31. protected $m_aOrigValues = array();
  32. private $m_bDirty = false; // The object may have incorrect external keys, then any attempt of reload must be avoided
  33. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  34. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  35. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  36. public function __construct($aRow = null)
  37. {
  38. if (!empty($aRow))
  39. {
  40. $this->FromRow($aRow);
  41. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  42. return;
  43. }
  44. // Creation of brand new object
  45. //
  46. $this->m_iKey = self::GetNextTempId(get_class($this));
  47. // set default values
  48. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  49. {
  50. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  51. $this->m_aOrigValues[$sAttCode] = null;
  52. if ($oAttDef->IsExternalField())
  53. {
  54. // This field has to be read from the DB
  55. $this->m_aLoadedAtt[$sAttCode] = false;
  56. }
  57. else
  58. {
  59. // No need to trigger a reload for that attribute
  60. // Let's consider it as being already fully loaded
  61. $this->m_aLoadedAtt[$sAttCode] = true;
  62. }
  63. }
  64. }
  65. public function RegisterAsDirty()
  66. {
  67. // While the object may be written to the DB, it is NOT possible to reload it
  68. // or at least not possible to reload it the same way
  69. $this->m_bDirty = true;
  70. }
  71. public function IsNew()
  72. {
  73. return (!$this->m_bIsInDB);
  74. }
  75. // Returns an Id for memory objects
  76. static protected function GetNextTempId($sClass)
  77. {
  78. if (!array_key_exists($sClass, self::$m_aMemoryObjectsByClass))
  79. {
  80. self::$m_aMemoryObjectsByClass[$sClass] = 0;
  81. }
  82. self::$m_aMemoryObjectsByClass[$sClass]++;
  83. return (- self::$m_aMemoryObjectsByClass[$sClass]);
  84. }
  85. public function __toString()
  86. {
  87. $sRet = '';
  88. $sClass = get_class($this);
  89. $sRootClass = MetaModel::GetRootClass($sClass);
  90. $iPKey = $this->GetKey();
  91. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  92. $sRet .= "<ul class=\"treeview\">\n";
  93. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  94. {
  95. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  96. }
  97. $sRet .= "</ul>";
  98. return $sRet;
  99. }
  100. // Restore initial values... mmmm, to be discussed
  101. public function DBRevert()
  102. {
  103. $this->Reload();
  104. }
  105. protected function IsFullyLoaded()
  106. {
  107. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  108. {
  109. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  110. if ($bIsLoaded !== true)
  111. {
  112. return false;
  113. }
  114. }
  115. return true;
  116. }
  117. protected function Reload()
  118. {
  119. assert($this->m_bIsInDB);
  120. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey);
  121. if (empty($aRow))
  122. {
  123. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  124. }
  125. $this->FromRow($aRow);
  126. // Process linked set attributes
  127. //
  128. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  129. {
  130. if (!$oAttDef->IsLinkSet()) continue;
  131. // Load the link information
  132. $sLinkClass = $oAttDef->GetLinkedClass();
  133. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  134. // The class to target is not the current class, because if this is a derived class,
  135. // it may differ from the target class, then things start to become confusing
  136. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  137. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  138. $oMyselfSearch = new DBObjectSearch($sMyClass);
  139. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  140. $oLinkSearch = new DBObjectSearch($sLinkClass);
  141. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  142. $oLinks = new DBObjectSet($oLinkSearch);
  143. $this->m_aCurrValues[$sAttCode] = $oLinks;
  144. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  145. $this->m_aLoadedAtt[$sAttCode] = true;
  146. }
  147. $this->m_bFullyLoaded = true;
  148. }
  149. protected function FromRow($aRow)
  150. {
  151. $this->m_iKey = null;
  152. $this->m_bIsInDB = true;
  153. $this->m_aCurrValues = array();
  154. $this->m_aOrigValues = array();
  155. $this->m_aLoadedAtt = array();
  156. // Get the key
  157. //
  158. $sKeyField = "id";
  159. if (!array_key_exists($sKeyField, $aRow))
  160. {
  161. // #@# Bug ?
  162. throw new CoreException("Missing key for class '".get_class($this)."'");
  163. }
  164. else
  165. {
  166. $iPKey = $aRow[$sKeyField];
  167. if (!self::IsValidPKey($iPKey))
  168. {
  169. throw new CoreWarning("An object id must be an integer value ($iPKey)");
  170. }
  171. $this->m_iKey = $iPKey;
  172. }
  173. // Build the object from an array of "attCode"=>"value")
  174. //
  175. $bFullyLoaded = true; // ... set to false if any attribute is not found
  176. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  177. {
  178. // Say something, whatever the type of attribute
  179. $this->m_aLoadedAtt[$sAttCode] = false;
  180. // Skip links (could not be loaded by the mean of this query)
  181. if ($oAttDef->IsLinkSet()) continue;
  182. // Note: we assume that, for a given attribute, if it can be loaded,
  183. // then one column will be found with an empty suffix, the others have a suffix
  184. // Take care: the function isset will return false in case the value is null,
  185. // which is something that could happen on open joins
  186. if (array_key_exists($sAttCode, $aRow))
  187. {
  188. $value = $oAttDef->FromSQLToValue($aRow, $sAttCode);
  189. $this->m_aCurrValues[$sAttCode] = $value;
  190. $this->m_aOrigValues[$sAttCode] = $value;
  191. $this->m_aLoadedAtt[$sAttCode] = true;
  192. }
  193. else
  194. {
  195. // This attribute was expected and not found in the query columns
  196. $bFullyLoaded = false;
  197. }
  198. }
  199. return $bFullyLoaded;
  200. }
  201. public function Set($sAttCode, $value)
  202. {
  203. if ($sAttCode == 'finalclass')
  204. {
  205. // Ignore it - this attribute is set upon object creation and that's it
  206. //throw new CoreWarning('Attempting to set the value for the internal attribute \"finalclass\"', array('current value'=>$this->Get('finalclass'), 'new value'=>$value));
  207. return;
  208. }
  209. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  210. {
  211. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  212. }
  213. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  214. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  215. {
  216. // First time Set is called... ensure that the object gets fully loaded
  217. // Otherwise we would lose the values on a further Reload
  218. // + consistency does not make sense !
  219. $this->Reload();
  220. }
  221. if($oAttDef->IsScalar() && !$oAttDef->IsNullAllowed() && is_null($value))
  222. {
  223. throw new CoreWarning("null not allowed for attribute '$sAttCode', setting default value");
  224. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  225. return;
  226. }
  227. if ($oAttDef->IsExternalKey() && is_object($value))
  228. {
  229. // Setting an external key with a whole object (instead of just an ID)
  230. // let's initialize also the external fields that depend on it
  231. // (useful when building objects in memory and not from a query)
  232. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  233. {
  234. throw new CoreWarning("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
  235. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  236. }
  237. else
  238. {
  239. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  240. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  241. {
  242. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  243. {
  244. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  245. }
  246. }
  247. }
  248. return;
  249. }
  250. if(!$oAttDef->IsScalar() && !is_object($value))
  251. {
  252. throw new CoreWarning("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  253. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  254. return;
  255. }
  256. if($oAttDef->IsLinkSet())
  257. {
  258. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  259. {
  260. throw new CoreWarning("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  261. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  262. return;
  263. }
  264. $oObjectSet = $value;
  265. $sSetClass = $oObjectSet->GetClass();
  266. $sLinkClass = $oAttDef->GetLinkedClass();
  267. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  268. if ($sSetClass != $sLinkClass)
  269. {
  270. throw new CoreWarning("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  271. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  272. return;
  273. }
  274. }
  275. $this->m_aCurrValues[$sAttCode] = $oAttDef->MakeRealValue($value);
  276. $this->RegisterAsDirty(); // Make sure we do not reload it anymore... before saving it
  277. }
  278. public function Get($sAttCode)
  279. {
  280. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  281. {
  282. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  283. }
  284. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  285. {
  286. // #@# non-scalar attributes.... handle that differentely
  287. $this->Reload();
  288. }
  289. $this->ComputeFields();
  290. return $this->m_aCurrValues[$sAttCode];
  291. }
  292. public function GetOriginal($sAttCode)
  293. {
  294. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  295. {
  296. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  297. }
  298. return $this->m_aOrigValues[$sAttCode];
  299. }
  300. public function ComputeFields()
  301. {
  302. if (is_callable(array($this, 'ComputeValues')))
  303. {
  304. // First check that we are not currently computing the fields
  305. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  306. foreach (debug_backtrace() as $aCallInfo)
  307. {
  308. if (!array_key_exists("class", $aCallInfo)) continue;
  309. if ($aCallInfo["class"] != get_class($this)) continue;
  310. if ($aCallInfo["function"] != "ComputeValues") continue;
  311. return; //skip!
  312. }
  313. $this->ComputeValues();
  314. }
  315. }
  316. public function GetAsHTML($sAttCode)
  317. {
  318. $sClass = get_class($this);
  319. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  320. $aExtKeyFriends = MetaModel::GetExtKeyFriends($sClass, $sAttCode);
  321. if (count($aExtKeyFriends) > 0)
  322. {
  323. // This attribute is an ext key (in this class or in another class)
  324. // The corresponding value is an id of the remote object
  325. // Let's try to use the corresponding external fields for a sexy display
  326. $aAvailableFields = array();
  327. foreach ($aExtKeyFriends as $sDispAttCode => $oExtField)
  328. {
  329. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  330. }
  331. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  332. return $this->MakeHyperLink($sTargetClass, $this->Get($sAttCode), $aAvailableFields);
  333. }
  334. // That's a standard attribute (might be an ext field or a direct field, etc.)
  335. return $oAtt->GetAsHTML($this->Get($sAttCode));
  336. }
  337. public function GetAsXML($sAttCode)
  338. {
  339. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  340. return $oAtt->GetAsXML($this->Get($sAttCode));
  341. }
  342. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  343. {
  344. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  345. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  346. }
  347. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  348. {
  349. if ($sObjKey == 0) return '<em>undefined</em>';
  350. return MetaModel::GetName($sObjClass)."::$sObjKey";
  351. }
  352. public function GetHyperlink()
  353. {
  354. $aAvailableFields[MetaModel::GetNameAttributeCode(get_class($this))] = $this->GetName();
  355. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $aAvailableFields);
  356. }
  357. // could be in the metamodel ?
  358. public static function IsValidPKey($value)
  359. {
  360. return ((string)$value === (string)(int)$value);
  361. }
  362. public function GetKey()
  363. {
  364. return $this->m_iKey;
  365. }
  366. public function SetKey($iNewKey)
  367. {
  368. if (!self::IsValidPKey($iNewKey))
  369. {
  370. throw new CoreException("An object id must be an integer value ($iNewKey)");
  371. }
  372. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  373. {
  374. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  375. }
  376. $this->m_iKey = $iNewKey;
  377. }
  378. public function GetName()
  379. {
  380. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  381. if (empty($sNameAttCode))
  382. {
  383. return $this->m_iKey;
  384. }
  385. else
  386. {
  387. return $this->Get($sNameAttCode);
  388. }
  389. }
  390. public function GetState()
  391. {
  392. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  393. if (empty($sStateAttCode))
  394. {
  395. return '';
  396. }
  397. else
  398. {
  399. $aStates = MetaModel::EnumStates(get_class($this));
  400. return $aStates[$this->Get($sStateAttCode)]['label'];
  401. }
  402. }
  403. /**
  404. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  405. * for the given attribute in the current state of the object
  406. * @param string $sAttCode The code of the attribute
  407. * @return integer Flags: the binary combination of the flags applicable to this attribute
  408. */
  409. public function GetAttributeFlags($sAttCode)
  410. {
  411. $iFlags = 0; // By default (if no life cycle) no flag at all
  412. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  413. if (!empty($sStateAttCode))
  414. {
  415. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  416. }
  417. return $iFlags;
  418. }
  419. // check if the given (or current) value is suitable for the attribute
  420. public function CheckValue($sAttCode, $value = null)
  421. {
  422. if (!is_null($value))
  423. {
  424. $toCheck = $value;
  425. }
  426. else
  427. {
  428. $toCheck = $this->Get($sAttCode);
  429. }
  430. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  431. if ($oAtt->IsExternalKey())
  432. {
  433. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  434. {
  435. try
  436. {
  437. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  438. return true;
  439. }
  440. catch (CoreException $e)
  441. {
  442. return false;
  443. }
  444. }
  445. }
  446. elseif ($oAtt->IsWritable() && $oAtt->IsScalar())
  447. {
  448. $aValues = $oAtt->GetAllowedValues();
  449. if (count($aValues) > 0)
  450. {
  451. if (!array_key_exists($toCheck, $aValues))
  452. {
  453. return false;
  454. }
  455. }
  456. }
  457. return true;
  458. }
  459. // check attributes together
  460. public function CheckConsistency()
  461. {
  462. return true;
  463. }
  464. // check if it is allowed to record the new object into the database
  465. // a displayable error is returned
  466. // Note: checks the values and consistency
  467. public function CheckToInsert()
  468. {
  469. $aIssues = array();
  470. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  471. {
  472. if (!$this->CheckValue($sAttCode))
  473. {
  474. $aIssues[$sAttCode] = array(
  475. 'issue' => 'unexpected value'
  476. );
  477. }
  478. }
  479. if (count($aIssues) > 0)
  480. {
  481. return array(false, $aIssues);
  482. }
  483. if (!$this->CheckConsistency())
  484. {
  485. return array(false, $aIssues);
  486. }
  487. return array(true, $aIssues);
  488. }
  489. // check if it is allowed to update the existing object into the database
  490. // a displayable error is returned
  491. // Note: checks the values and consistency
  492. public function CheckToUpdate()
  493. {
  494. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  495. {
  496. if (!$this->CheckValue($sAttCode)) return false;
  497. }
  498. if (!$this->CheckConsistency()) return false;
  499. return true;
  500. }
  501. // check if it is allowed to delete the existing object from the database
  502. // a displayable error is returned
  503. public function CheckToDelete()
  504. {
  505. return true;
  506. }
  507. protected function ListChangedValues(array $aProposal)
  508. {
  509. $aDelta = array();
  510. foreach ($aProposal as $sAtt => $proposedValue)
  511. {
  512. if (!array_key_exists($sAtt, $this->m_aOrigValues) || ($this->m_aOrigValues[$sAtt] !== $proposedValue))
  513. {
  514. $aDelta[$sAtt] = $proposedValue;
  515. }
  516. }
  517. return $aDelta;
  518. }
  519. // List the attributes that have been changed
  520. // Returns an array of attname => currentvalue
  521. public function ListChanges()
  522. {
  523. return $this->ListChangedValues($this->m_aCurrValues);
  524. }
  525. // Tells whether or not an object was modified
  526. public function IsModified()
  527. {
  528. $aChanges = $this->ListChanges();
  529. return (count($aChanges) != 0);
  530. }
  531. // used both by insert/update
  532. private function DBWriteLinks()
  533. {
  534. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  535. {
  536. if (!$oAttDef->IsLinkSet()) continue;
  537. $oLinks = $this->Get($sAttCode);
  538. $oLinks->Rewind();
  539. while ($oLinkedObject = $oLinks->Fetch())
  540. {
  541. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  542. if ($oLinkedObject->IsModified())
  543. {
  544. $oLinkedObject->DBWrite();
  545. }
  546. }
  547. // Delete the objects that were initialy present and disappeared from the list
  548. // (if any)
  549. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  550. if ($oOriginalSet != null)
  551. {
  552. $aOriginalList = $oOriginalSet->ToArray();
  553. $aNewSet = $oLinks->ToArray();
  554. $aToDelete = array_diff($aOriginalList, $aNewSet);
  555. foreach ($aToDelete as $iKey => $oObject)
  556. {
  557. $oObject->DBDelete();
  558. }
  559. }
  560. }
  561. }
  562. private function DBInsertSingleTable($sTableClass)
  563. {
  564. $sClass = get_class($this);
  565. // fields in first array, values in the second
  566. $aFieldsToWrite = array();
  567. $aValuesToWrite = array();
  568. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  569. {
  570. // Add it to the list of fields to write
  571. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  572. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  573. }
  574. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  575. {
  576. // Skip this attribute if not defined in this table
  577. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  578. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  579. foreach($aAttColumns as $sColumn => $sValue)
  580. {
  581. $aFieldsToWrite[] = "`$sColumn`";
  582. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  583. }
  584. }
  585. if (count($aValuesToWrite) == 0) return false;
  586. $sTable = MetaModel::DBGetTable($sTableClass);
  587. $sInsertSQL = "INSERT INTO $sTable (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  588. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  589. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  590. if (empty($this->m_iKey))
  591. {
  592. // Take the autonumber
  593. $this->m_iKey = $iNewKey;
  594. }
  595. return $this->m_iKey;
  596. }
  597. // To be optionaly overloaded
  598. public function OnInsert()
  599. {
  600. }
  601. // Insert of record for the new object into the database
  602. // Returns the key of the newly created object
  603. public function DBInsertNoReload()
  604. {
  605. if ($this->m_bIsInDB)
  606. {
  607. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  608. }
  609. $sClass = get_class($this);
  610. $sRootClass = MetaModel::GetRootClass($sClass);
  611. // Ensure the update of the values (we are accessing the data directly)
  612. $this->ComputeFields();
  613. $this->OnInsert();
  614. if ($this->m_iKey < 0)
  615. {
  616. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  617. $this->m_iKey = null;
  618. }
  619. // If not automatically computed, then check that the key is given by the caller
  620. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  621. {
  622. if (empty($this->m_iKey))
  623. {
  624. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  625. }
  626. }
  627. // First query built upon on the root class, because the ID must be created first
  628. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  629. // Then do the leaf class, if different from the root class
  630. if ($sClass != $sRootClass)
  631. {
  632. $this->DBInsertSingleTable($sClass);
  633. }
  634. // Then do the other classes
  635. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  636. {
  637. if ($sParentClass == $sRootClass) continue;
  638. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  639. $this->DBInsertSingleTable($sParentClass);
  640. }
  641. $this->DBWriteLinks();
  642. $this->m_bIsInDB = true;
  643. // Activate any existing trigger
  644. $sClass = get_class($this);
  645. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  646. while ($oTrigger = $oSet->Fetch())
  647. {
  648. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  649. {
  650. $oTrigger->DoActivate($this->ToArgs('this'));
  651. }
  652. }
  653. return $this->m_iKey;
  654. }
  655. public function DBInsert()
  656. {
  657. $this->DBInsertNoReload();
  658. $this->m_bDirty = false;
  659. $this->Reload();
  660. return $this->m_iKey;
  661. }
  662. // Creates a copy of the current object into the database
  663. // Returns the id of the newly created object
  664. public function DBClone($iNewKey = null)
  665. {
  666. $this->m_bIsInDB = false;
  667. $this->m_iKey = $iNewKey;
  668. return $this->DBInsert();
  669. }
  670. // Update a record
  671. public function DBUpdate()
  672. {
  673. if (!$this->m_bIsInDB)
  674. {
  675. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  676. }
  677. $aChanges = $this->ListChanges();
  678. if (count($aChanges) == 0)
  679. {
  680. throw new CoreWarning("Attempting to update an unchanged object");
  681. return;
  682. }
  683. $bHasANewExternalKeyValue = false;
  684. foreach($aChanges as $sAttCode => $valuecurr)
  685. {
  686. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  687. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  688. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  689. }
  690. // Update scalar attributes
  691. if (count($aChanges) != 0)
  692. {
  693. $oFilter = new DBObjectSearch(get_class($this));
  694. $oFilter->AddCondition('id', $this->m_iKey, '=');
  695. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  696. CMDBSource::Query($sSQL);
  697. }
  698. $this->DBWriteLinks();
  699. $this->m_bDirty = false;
  700. // Reload to get the external attributes
  701. if ($bHasANewExternalKeyValue)
  702. {
  703. $this->Reload();
  704. }
  705. return $this->m_iKey;
  706. }
  707. // Make the current changes persistent - clever wrapper for Insert or Update
  708. public function DBWrite()
  709. {
  710. if ($this->m_bIsInDB)
  711. {
  712. return $this->DBUpdate();
  713. }
  714. else
  715. {
  716. return $this->DBInsert();
  717. }
  718. }
  719. // Delete a record
  720. public function DBDelete()
  721. {
  722. $oFilter = new DBObjectSearch(get_class($this));
  723. $oFilter->AddCondition('id', $this->m_iKey, '=');
  724. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  725. CMDBSource::Query($sSQL);
  726. $this->m_bIsInDB = false;
  727. $this->m_iKey = null;
  728. }
  729. public function EnumTransitions()
  730. {
  731. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  732. if (empty($sStateAttCode)) return array();
  733. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  734. return MetaModel::EnumTransitions(get_class($this), $sState);
  735. }
  736. public function ApplyStimulus($sStimulusCode)
  737. {
  738. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  739. if (empty($sStateAttCode)) return false;
  740. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  741. $aStateTransitions = $this->EnumTransitions();
  742. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  743. // Change the state before proceeding to the actions, this is necessary because an action might
  744. // trigger another stimuli (alternative: push the stimuli into a queue)
  745. $sPreviousState = $this->Get($sStateAttCode);
  746. $sNewState = $aTransitionDef['target_state'];
  747. $this->Set($sStateAttCode, $sNewState);
  748. // $aTransitionDef is an
  749. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  750. $bSuccess = true;
  751. foreach ($aTransitionDef['actions'] as $sActionHandler)
  752. {
  753. // std PHP spec
  754. $aActionCallSpec = array($this, $sActionHandler);
  755. if (!is_callable($aActionCallSpec))
  756. {
  757. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  758. return;
  759. }
  760. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  761. // if one call fails, the whole is considered as failed
  762. if (!$bRet) $bSuccess = false;
  763. }
  764. // Change state triggers...
  765. $sClass = get_class($this);
  766. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class='$sClass' AND t.state='$sPreviousState'"));
  767. while ($oTrigger = $oSet->Fetch())
  768. {
  769. $oTrigger->DoActivate($this->ToArgs('this'));
  770. }
  771. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class='$sClass' AND t.state='$sNewState'"));
  772. while ($oTrigger = $oSet->Fetch())
  773. {
  774. $oTrigger->DoActivate($this->ToArgs('this'));
  775. }
  776. return $bSuccess;
  777. }
  778. // Make standard context arguments
  779. public function ToArgs($sArgName = 'this')
  780. {
  781. $aScalarArgs = array();
  782. $aScalarArgs[$sArgName] = $this->GetKey();
  783. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  784. $aScalarArgs[$sArgName.'->object()'] = $this;
  785. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  786. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  787. $sClass = get_class($this);
  788. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  789. {
  790. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  791. }
  792. return $aScalarArgs;
  793. }
  794. // Return an empty set for the parent of all
  795. public static function GetRelationQueries($sRelCode)
  796. {
  797. return array();
  798. }
  799. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  800. {
  801. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  802. {
  803. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  804. $sQuery = $aQueryInfo["sQuery"];
  805. $bPropagate = $aQueryInfo["bPropagate"];
  806. $iDistance = $aQueryInfo["iDistance"];
  807. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  808. $oFlt = DBObjectSearch::FromOQL($sQuery);
  809. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  810. while ($oObj = $oObjSet->Fetch())
  811. {
  812. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  813. $sObjKey = $oObj->GetKey();
  814. if (array_key_exists($sRootClass, $aResults))
  815. {
  816. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  817. {
  818. continue; // already visited, skip
  819. }
  820. }
  821. $aResults[$sRootClass][$sObjKey] = $oObj;
  822. if ($iDepth > 0)
  823. {
  824. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  825. }
  826. }
  827. }
  828. return $aResults;
  829. }
  830. public function GetReferencingObjects()
  831. {
  832. $aDependentObjects = array();
  833. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  834. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  835. {
  836. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  837. {
  838. // skip if this external key is behind an external field
  839. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  840. $oSearch = new DBObjectSearch($sRemoteClass);
  841. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey());
  842. $oSet = new CMDBObjectSet($oSearch);
  843. if ($oSet->Count() > 0)
  844. {
  845. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  846. 'attribute' => $oExtKeyAttDef,
  847. 'objects' => $oSet,
  848. );
  849. }
  850. }
  851. }
  852. return $aDependentObjects;
  853. }
  854. public function GetDeletionScheme()
  855. {
  856. $aDependentObjects = $this->GetReferencingObjects();
  857. $aDeletedObjs = array(); // [class][key] => structure
  858. $aResetedObjs = array(); // [class][key] => object
  859. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  860. {
  861. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  862. {
  863. $oAttDef = $aData['attribute'];
  864. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  865. $oDepSet = $aData['objects'];
  866. $oDepSet->Rewind();
  867. while ($oDependentObj = $oDepSet->fetch())
  868. {
  869. $iId = $oDependentObj->GetKey();
  870. if ($oAttDef->IsNullAllowed())
  871. {
  872. // Optional external key, list to reset
  873. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  874. {
  875. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  876. }
  877. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  878. }
  879. else
  880. {
  881. // Mandatory external key, list to delete
  882. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  883. {
  884. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  885. if ($iCurrentOption == DEL_AUTO)
  886. {
  887. // be conservative, take the new option
  888. // (DEL_MANUAL has precedence over DEL_AUTO)
  889. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  890. }
  891. else
  892. {
  893. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  894. }
  895. }
  896. else
  897. {
  898. // First time we find the given object in the list
  899. // (and most likely case is that no other occurence will be found)
  900. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  901. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  902. }
  903. }
  904. }
  905. }
  906. }
  907. return array($aDeletedObjs, $aResetedObjs);
  908. }
  909. }
  910. ?>