dbobject.class.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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, $sClassAlias = '')
  37. {
  38. if (!empty($aRow))
  39. {
  40. $this->FromRow($aRow, $sClassAlias);
  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, $sClassAlias = '')
  150. {
  151. if (strlen($sClassAlias) == 0)
  152. {
  153. // Default to the current class
  154. $sClassAlias = get_class($this);
  155. }
  156. $this->m_iKey = null;
  157. $this->m_bIsInDB = true;
  158. $this->m_aCurrValues = array();
  159. $this->m_aOrigValues = array();
  160. $this->m_aLoadedAtt = array();
  161. // Get the key
  162. //
  163. $sKeyField = $sClassAlias."id";
  164. if (!array_key_exists($sKeyField, $aRow))
  165. {
  166. // #@# Bug ?
  167. throw new CoreException("Missing key for class '".get_class($this)."'");
  168. }
  169. else
  170. {
  171. $iPKey = $aRow[$sKeyField];
  172. if (!self::IsValidPKey($iPKey))
  173. {
  174. throw new CoreWarning("An object id must be an integer value ($iPKey)");
  175. }
  176. $this->m_iKey = $iPKey;
  177. }
  178. // Build the object from an array of "attCode"=>"value")
  179. //
  180. $bFullyLoaded = true; // ... set to false if any attribute is not found
  181. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  182. {
  183. // Say something, whatever the type of attribute
  184. $this->m_aLoadedAtt[$sAttCode] = false;
  185. // Skip links (could not be loaded by the mean of this query)
  186. if ($oAttDef->IsLinkSet()) continue;
  187. // Note: we assume that, for a given attribute, if it can be loaded,
  188. // then one column will be found with an empty suffix, the others have a suffix
  189. // Take care: the function isset will return false in case the value is null,
  190. // which is something that could happen on open joins
  191. $sAttRef = $sClassAlias.$sAttCode;
  192. if (array_key_exists($sAttRef, $aRow))
  193. {
  194. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  195. $this->m_aCurrValues[$sAttCode] = $value;
  196. $this->m_aOrigValues[$sAttCode] = $value;
  197. $this->m_aLoadedAtt[$sAttCode] = true;
  198. }
  199. else
  200. {
  201. // This attribute was expected and not found in the query columns
  202. $bFullyLoaded = false;
  203. }
  204. }
  205. return $bFullyLoaded;
  206. }
  207. public function Set($sAttCode, $value)
  208. {
  209. if ($sAttCode == 'finalclass')
  210. {
  211. // Ignore it - this attribute is set upon object creation and that's it
  212. //throw new CoreWarning('Attempting to set the value for the internal attribute \"finalclass\"', array('current value'=>$this->Get('finalclass'), 'new value'=>$value));
  213. return;
  214. }
  215. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  216. {
  217. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  218. }
  219. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  220. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  221. {
  222. // First time Set is called... ensure that the object gets fully loaded
  223. // Otherwise we would lose the values on a further Reload
  224. // + consistency does not make sense !
  225. $this->Reload();
  226. }
  227. if($oAttDef->IsScalar() && !$oAttDef->IsNullAllowed() && is_null($value))
  228. {
  229. throw new CoreWarning("null not allowed for attribute '$sAttCode', setting default value");
  230. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  231. return;
  232. }
  233. if ($oAttDef->IsExternalKey() && is_object($value))
  234. {
  235. // Setting an external key with a whole object (instead of just an ID)
  236. // let's initialize also the external fields that depend on it
  237. // (useful when building objects in memory and not from a query)
  238. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  239. {
  240. 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");
  241. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  242. }
  243. else
  244. {
  245. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  246. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  247. {
  248. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  249. {
  250. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  251. }
  252. }
  253. }
  254. return;
  255. }
  256. if(!$oAttDef->IsScalar() && !is_object($value))
  257. {
  258. throw new CoreWarning("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  259. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  260. return;
  261. }
  262. if($oAttDef->IsLinkSet())
  263. {
  264. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  265. {
  266. throw new CoreWarning("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  267. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  268. return;
  269. }
  270. $oObjectSet = $value;
  271. $sSetClass = $oObjectSet->GetClass();
  272. $sLinkClass = $oAttDef->GetLinkedClass();
  273. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  274. if ($sSetClass != $sLinkClass)
  275. {
  276. throw new CoreWarning("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  277. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  278. return;
  279. }
  280. }
  281. $this->m_aCurrValues[$sAttCode] = $oAttDef->MakeRealValue($value);
  282. $this->RegisterAsDirty(); // Make sure we do not reload it anymore... before saving it
  283. }
  284. public function Get($sAttCode)
  285. {
  286. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  287. {
  288. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  289. }
  290. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  291. {
  292. // #@# non-scalar attributes.... handle that differentely
  293. $this->Reload();
  294. }
  295. $this->ComputeFields();
  296. return $this->m_aCurrValues[$sAttCode];
  297. }
  298. public function GetOriginal($sAttCode)
  299. {
  300. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  301. {
  302. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  303. }
  304. return $this->m_aOrigValues[$sAttCode];
  305. }
  306. public function ComputeFields()
  307. {
  308. if (is_callable(array($this, 'ComputeValues')))
  309. {
  310. // First check that we are not currently computing the fields
  311. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  312. foreach (debug_backtrace() as $aCallInfo)
  313. {
  314. if (!array_key_exists("class", $aCallInfo)) continue;
  315. if ($aCallInfo["class"] != get_class($this)) continue;
  316. if ($aCallInfo["function"] != "ComputeValues") continue;
  317. return; //skip!
  318. }
  319. $this->ComputeValues();
  320. }
  321. }
  322. public function GetAsHTML($sAttCode)
  323. {
  324. $sClass = get_class($this);
  325. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  326. $aExtKeyFriends = MetaModel::GetExtKeyFriends($sClass, $sAttCode);
  327. if (count($aExtKeyFriends) > 0)
  328. {
  329. // This attribute is an ext key (in this class or in another class)
  330. // The corresponding value is an id of the remote object
  331. // Let's try to use the corresponding external fields for a sexy display
  332. $aAvailableFields = array();
  333. foreach ($aExtKeyFriends as $sDispAttCode => $oExtField)
  334. {
  335. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  336. }
  337. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  338. return $this->MakeHyperLink($sTargetClass, $this->Get($sAttCode), $aAvailableFields);
  339. }
  340. // That's a standard attribute (might be an ext field or a direct field, etc.)
  341. return $oAtt->GetAsHTML($this->Get($sAttCode));
  342. }
  343. public function GetEditValue($sAttCode)
  344. {
  345. $sClass = get_class($this);
  346. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  347. if ($oAtt->IsExternalKey())
  348. {
  349. $sTargetClass = $oAtt->GetTargetClass();
  350. if ($this->IsNew())
  351. {
  352. // The current object exists only in memory, don't try to query it in the DB !
  353. // instead let's query for the object pointed by the external key, and get its name
  354. $targetObjId = $this->Get($sAttCode);
  355. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  356. if (is_object($oTargetObj))
  357. {
  358. $sEditValue = $oTargetObj->GetName();
  359. }
  360. }
  361. else
  362. {
  363. // retrieve the "external fields" linked to this external key
  364. foreach (MetaModel::GetExternalFields(get_class($this), $sAttCode) as $oExtField)
  365. {
  366. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  367. }
  368. // Use the "name" of the target class as the label of the hyperlink
  369. // unless it's not available in the external fields...
  370. $sExtClassNameAtt = MetaModel::GetNameAttributeCode($sTargetClass);
  371. if (isset($aAvailableFields[$sExtClassNameAtt]))
  372. {
  373. $sEditValue = $aAvailableFields[$sExtClassNameAtt];
  374. }
  375. else
  376. {
  377. $sEditValue = implode(' / ', $aAvailableFields);
  378. }
  379. }
  380. }
  381. else
  382. {
  383. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  384. }
  385. return $sEditValue;
  386. }
  387. public function GetAsXML($sAttCode)
  388. {
  389. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  390. return $oAtt->GetAsXML($this->Get($sAttCode));
  391. }
  392. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  393. {
  394. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  395. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  396. }
  397. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  398. {
  399. if ($sObjKey == 0) return '<em>undefined</em>';
  400. return MetaModel::GetName($sObjClass)."::$sObjKey";
  401. }
  402. public function GetHyperlink()
  403. {
  404. $aAvailableFields[MetaModel::GetNameAttributeCode(get_class($this))] = $this->GetName();
  405. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $aAvailableFields);
  406. }
  407. // could be in the metamodel ?
  408. public static function IsValidPKey($value)
  409. {
  410. return ((string)$value === (string)(int)$value);
  411. }
  412. public function GetKey()
  413. {
  414. return $this->m_iKey;
  415. }
  416. public function SetKey($iNewKey)
  417. {
  418. if (!self::IsValidPKey($iNewKey))
  419. {
  420. throw new CoreException("An object id must be an integer value ($iNewKey)");
  421. }
  422. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  423. {
  424. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  425. }
  426. $this->m_iKey = $iNewKey;
  427. }
  428. public function GetName()
  429. {
  430. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  431. if (empty($sNameAttCode))
  432. {
  433. return $this->m_iKey;
  434. }
  435. else
  436. {
  437. return $this->Get($sNameAttCode);
  438. }
  439. }
  440. public function GetState()
  441. {
  442. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  443. if (empty($sStateAttCode))
  444. {
  445. return '';
  446. }
  447. else
  448. {
  449. return $this->Get($sStateAttCode);
  450. return MetaModel::GetStateLabel(get_class($this), $sStateAttCode);
  451. }
  452. }
  453. public function GetStateLabel()
  454. {
  455. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  456. if (empty($sStateAttCode))
  457. {
  458. return '';
  459. }
  460. else
  461. {
  462. $sStateValue = $this->Get($sStateAttCode);
  463. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  464. }
  465. }
  466. public function GetStateDescription()
  467. {
  468. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  469. if (empty($sStateAttCode))
  470. {
  471. return '';
  472. }
  473. else
  474. {
  475. $sStateValue = $this->Get($sStateAttCode);
  476. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  477. }
  478. }
  479. /**
  480. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  481. * for the given attribute in the current state of the object
  482. * @param string $sAttCode The code of the attribute
  483. * @return integer Flags: the binary combination of the flags applicable to this attribute
  484. */
  485. public function GetAttributeFlags($sAttCode)
  486. {
  487. $iFlags = 0; // By default (if no life cycle) no flag at all
  488. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  489. if (!empty($sStateAttCode))
  490. {
  491. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  492. }
  493. return $iFlags;
  494. }
  495. // check if the given (or current) value is suitable for the attribute
  496. public function CheckValue($sAttCode, $value = null)
  497. {
  498. if (!is_null($value))
  499. {
  500. $toCheck = $value;
  501. }
  502. else
  503. {
  504. $toCheck = $this->Get($sAttCode);
  505. }
  506. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  507. if ($oAtt->IsExternalKey())
  508. {
  509. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  510. {
  511. try
  512. {
  513. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  514. return true;
  515. }
  516. catch (CoreException $e)
  517. {
  518. return false;
  519. }
  520. }
  521. }
  522. elseif ($oAtt->IsWritable() && $oAtt->IsScalar())
  523. {
  524. $aValues = $oAtt->GetAllowedValues();
  525. if (count($aValues) > 0)
  526. {
  527. if (!array_key_exists($toCheck, $aValues))
  528. {
  529. return false;
  530. }
  531. }
  532. }
  533. return true;
  534. }
  535. // check attributes together
  536. public function CheckConsistency()
  537. {
  538. return true;
  539. }
  540. // check if it is allowed to record the new object into the database
  541. // a displayable error is returned
  542. // Note: checks the values and consistency
  543. public function CheckToInsert()
  544. {
  545. $aIssues = array();
  546. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  547. {
  548. if (!$this->CheckValue($sAttCode))
  549. {
  550. $aIssues[$sAttCode] = array(
  551. 'issue' => 'unexpected value'
  552. );
  553. }
  554. }
  555. if (count($aIssues) > 0)
  556. {
  557. return array(false, $aIssues);
  558. }
  559. if (!$this->CheckConsistency())
  560. {
  561. return array(false, $aIssues);
  562. }
  563. return array(true, $aIssues);
  564. }
  565. // check if it is allowed to update the existing object into the database
  566. // a displayable error is returned
  567. // Note: checks the values and consistency
  568. public function CheckToUpdate()
  569. {
  570. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  571. {
  572. if (!$this->CheckValue($sAttCode)) return false;
  573. }
  574. if (!$this->CheckConsistency()) return false;
  575. return true;
  576. }
  577. // check if it is allowed to delete the existing object from the database
  578. // a displayable error is returned
  579. public function CheckToDelete()
  580. {
  581. return true;
  582. }
  583. protected function ListChangedValues(array $aProposal)
  584. {
  585. $aDelta = array();
  586. foreach ($aProposal as $sAtt => $proposedValue)
  587. {
  588. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  589. {
  590. // The value was not set
  591. $aDelta[$sAtt] = $proposedValue;
  592. }
  593. elseif(is_object($proposedValue))
  594. {
  595. // The value is an object, the comparison is not strict
  596. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  597. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  598. {
  599. $aDelta[$sAtt] = $proposedValue;
  600. }
  601. }
  602. else
  603. {
  604. // The value is a scalar, the comparison must be 100% strict
  605. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  606. {
  607. //echo "$sAtt:<pre>\n";
  608. //var_dump($this->m_aOrigValues[$sAtt]);
  609. //var_dump($proposedValue);
  610. //echo "</pre>\n";
  611. $aDelta[$sAtt] = $proposedValue;
  612. }
  613. }
  614. }
  615. return $aDelta;
  616. }
  617. // List the attributes that have been changed
  618. // Returns an array of attname => currentvalue
  619. public function ListChanges()
  620. {
  621. return $this->ListChangedValues($this->m_aCurrValues);
  622. }
  623. // Tells whether or not an object was modified
  624. public function IsModified()
  625. {
  626. $aChanges = $this->ListChanges();
  627. return (count($aChanges) != 0);
  628. }
  629. // used both by insert/update
  630. private function DBWriteLinks()
  631. {
  632. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  633. {
  634. if (!$oAttDef->IsLinkSet()) continue;
  635. $oLinks = $this->Get($sAttCode);
  636. $oLinks->Rewind();
  637. while ($oLinkedObject = $oLinks->Fetch())
  638. {
  639. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  640. if ($oLinkedObject->IsModified())
  641. {
  642. $oLinkedObject->DBWrite();
  643. }
  644. }
  645. // Delete the objects that were initialy present and disappeared from the list
  646. // (if any)
  647. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  648. if ($oOriginalSet != null)
  649. {
  650. $aOriginalList = $oOriginalSet->ToArray();
  651. $aNewSet = $oLinks->ToArray();
  652. $aToDelete = array_diff($aOriginalList, $aNewSet);
  653. foreach ($aToDelete as $iKey => $oObject)
  654. {
  655. $oObject->DBDelete();
  656. }
  657. }
  658. }
  659. }
  660. private function DBInsertSingleTable($sTableClass)
  661. {
  662. $sClass = get_class($this);
  663. // fields in first array, values in the second
  664. $aFieldsToWrite = array();
  665. $aValuesToWrite = array();
  666. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  667. {
  668. // Add it to the list of fields to write
  669. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  670. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  671. }
  672. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  673. {
  674. // Skip this attribute if not defined in this table
  675. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  676. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  677. foreach($aAttColumns as $sColumn => $sValue)
  678. {
  679. $aFieldsToWrite[] = "`$sColumn`";
  680. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  681. }
  682. }
  683. if (count($aValuesToWrite) == 0) return false;
  684. $sTable = MetaModel::DBGetTable($sTableClass);
  685. $sInsertSQL = "INSERT INTO $sTable (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  686. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  687. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  688. if (empty($this->m_iKey))
  689. {
  690. // Take the autonumber
  691. $this->m_iKey = $iNewKey;
  692. }
  693. return $this->m_iKey;
  694. }
  695. // To be optionaly overloaded
  696. public function OnInsert()
  697. {
  698. }
  699. // Insert of record for the new object into the database
  700. // Returns the key of the newly created object
  701. public function DBInsertNoReload()
  702. {
  703. if ($this->m_bIsInDB)
  704. {
  705. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  706. }
  707. $sClass = get_class($this);
  708. $sRootClass = MetaModel::GetRootClass($sClass);
  709. // Ensure the update of the values (we are accessing the data directly)
  710. $this->ComputeFields();
  711. $this->OnInsert();
  712. if ($this->m_iKey < 0)
  713. {
  714. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  715. $this->m_iKey = null;
  716. }
  717. // If not automatically computed, then check that the key is given by the caller
  718. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  719. {
  720. if (empty($this->m_iKey))
  721. {
  722. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  723. }
  724. }
  725. // First query built upon on the root class, because the ID must be created first
  726. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  727. // Then do the leaf class, if different from the root class
  728. if ($sClass != $sRootClass)
  729. {
  730. $this->DBInsertSingleTable($sClass);
  731. }
  732. // Then do the other classes
  733. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  734. {
  735. if ($sParentClass == $sRootClass) continue;
  736. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  737. $this->DBInsertSingleTable($sParentClass);
  738. }
  739. $this->DBWriteLinks();
  740. $this->m_bIsInDB = true;
  741. // Activate any existing trigger
  742. $sClass = get_class($this);
  743. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  744. while ($oTrigger = $oSet->Fetch())
  745. {
  746. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  747. {
  748. $oTrigger->DoActivate($this->ToArgs('this'));
  749. }
  750. }
  751. return $this->m_iKey;
  752. }
  753. public function DBInsert()
  754. {
  755. $this->DBInsertNoReload();
  756. $this->m_bDirty = false;
  757. $this->Reload();
  758. return $this->m_iKey;
  759. }
  760. // Creates a copy of the current object into the database
  761. // Returns the id of the newly created object
  762. public function DBClone($iNewKey = null)
  763. {
  764. $this->m_bIsInDB = false;
  765. $this->m_iKey = $iNewKey;
  766. return $this->DBInsert();
  767. }
  768. // Update a record
  769. public function DBUpdate()
  770. {
  771. if (!$this->m_bIsInDB)
  772. {
  773. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  774. }
  775. $aChanges = $this->ListChanges();
  776. if (count($aChanges) == 0)
  777. {
  778. throw new CoreWarning("Attempting to update an unchanged object");
  779. return;
  780. }
  781. $bHasANewExternalKeyValue = false;
  782. foreach($aChanges as $sAttCode => $valuecurr)
  783. {
  784. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  785. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  786. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  787. }
  788. // Update scalar attributes
  789. if (count($aChanges) != 0)
  790. {
  791. $oFilter = new DBObjectSearch(get_class($this));
  792. $oFilter->AddCondition('id', $this->m_iKey, '=');
  793. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  794. CMDBSource::Query($sSQL);
  795. }
  796. $this->DBWriteLinks();
  797. $this->m_bDirty = false;
  798. // Reload to get the external attributes
  799. if ($bHasANewExternalKeyValue)
  800. {
  801. $this->Reload();
  802. }
  803. return $this->m_iKey;
  804. }
  805. // Make the current changes persistent - clever wrapper for Insert or Update
  806. public function DBWrite()
  807. {
  808. if ($this->m_bIsInDB)
  809. {
  810. return $this->DBUpdate();
  811. }
  812. else
  813. {
  814. return $this->DBInsert();
  815. }
  816. }
  817. // Delete a record
  818. public function DBDelete()
  819. {
  820. $oFilter = new DBObjectSearch(get_class($this));
  821. $oFilter->AddCondition('id', $this->m_iKey, '=');
  822. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  823. CMDBSource::Query($sSQL);
  824. $this->m_bIsInDB = false;
  825. $this->m_iKey = null;
  826. }
  827. public function EnumTransitions()
  828. {
  829. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  830. if (empty($sStateAttCode)) return array();
  831. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  832. return MetaModel::EnumTransitions(get_class($this), $sState);
  833. }
  834. public function ApplyStimulus($sStimulusCode)
  835. {
  836. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  837. if (empty($sStateAttCode)) return false;
  838. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  839. $aStateTransitions = $this->EnumTransitions();
  840. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  841. // Change the state before proceeding to the actions, this is necessary because an action might
  842. // trigger another stimuli (alternative: push the stimuli into a queue)
  843. $sPreviousState = $this->Get($sStateAttCode);
  844. $sNewState = $aTransitionDef['target_state'];
  845. $this->Set($sStateAttCode, $sNewState);
  846. // $aTransitionDef is an
  847. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  848. $bSuccess = true;
  849. foreach ($aTransitionDef['actions'] as $sActionHandler)
  850. {
  851. // std PHP spec
  852. $aActionCallSpec = array($this, $sActionHandler);
  853. if (!is_callable($aActionCallSpec))
  854. {
  855. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  856. return;
  857. }
  858. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  859. // if one call fails, the whole is considered as failed
  860. if (!$bRet) $bSuccess = false;
  861. }
  862. // Change state triggers...
  863. $sClass = get_class($this);
  864. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class='$sClass' AND t.state='$sPreviousState'"));
  865. while ($oTrigger = $oSet->Fetch())
  866. {
  867. $oTrigger->DoActivate($this->ToArgs('this'));
  868. }
  869. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class='$sClass' AND t.state='$sNewState'"));
  870. while ($oTrigger = $oSet->Fetch())
  871. {
  872. $oTrigger->DoActivate($this->ToArgs('this'));
  873. }
  874. return $bSuccess;
  875. }
  876. // Make standard context arguments
  877. public function ToArgs($sArgName = 'this')
  878. {
  879. $aScalarArgs = array();
  880. $aScalarArgs[$sArgName] = $this->GetKey();
  881. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  882. $aScalarArgs[$sArgName.'->object()'] = $this;
  883. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  884. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  885. $sClass = get_class($this);
  886. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  887. {
  888. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  889. }
  890. return $aScalarArgs;
  891. }
  892. // Return an empty set for the parent of all
  893. public static function GetRelationQueries($sRelCode)
  894. {
  895. return array();
  896. }
  897. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  898. {
  899. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  900. {
  901. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  902. $sQuery = $aQueryInfo["sQuery"];
  903. $bPropagate = $aQueryInfo["bPropagate"];
  904. $iDistance = $aQueryInfo["iDistance"];
  905. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  906. $oFlt = DBObjectSearch::FromOQL($sQuery);
  907. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  908. while ($oObj = $oObjSet->Fetch())
  909. {
  910. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  911. $sObjKey = $oObj->GetKey();
  912. if (array_key_exists($sRootClass, $aResults))
  913. {
  914. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  915. {
  916. continue; // already visited, skip
  917. }
  918. }
  919. $aResults[$sRootClass][$sObjKey] = $oObj;
  920. if ($iDepth > 0)
  921. {
  922. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  923. }
  924. }
  925. }
  926. return $aResults;
  927. }
  928. public function GetReferencingObjects()
  929. {
  930. $aDependentObjects = array();
  931. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  932. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  933. {
  934. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  935. {
  936. // skip if this external key is behind an external field
  937. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  938. $oSearch = new DBObjectSearch($sRemoteClass);
  939. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey());
  940. $oSet = new CMDBObjectSet($oSearch);
  941. if ($oSet->Count() > 0)
  942. {
  943. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  944. 'attribute' => $oExtKeyAttDef,
  945. 'objects' => $oSet,
  946. );
  947. }
  948. }
  949. }
  950. return $aDependentObjects;
  951. }
  952. public function GetDeletionScheme()
  953. {
  954. $aDependentObjects = $this->GetReferencingObjects();
  955. $aDeletedObjs = array(); // [class][key] => structure
  956. $aResetedObjs = array(); // [class][key] => object
  957. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  958. {
  959. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  960. {
  961. $oAttDef = $aData['attribute'];
  962. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  963. $oDepSet = $aData['objects'];
  964. $oDepSet->Rewind();
  965. while ($oDependentObj = $oDepSet->fetch())
  966. {
  967. $iId = $oDependentObj->GetKey();
  968. if ($oAttDef->IsNullAllowed())
  969. {
  970. // Optional external key, list to reset
  971. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  972. {
  973. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  974. }
  975. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  976. }
  977. else
  978. {
  979. // Mandatory external key, list to delete
  980. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  981. {
  982. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  983. if ($iCurrentOption == DEL_AUTO)
  984. {
  985. // be conservative, take the new option
  986. // (DEL_MANUAL has precedence over DEL_AUTO)
  987. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  988. }
  989. else
  990. {
  991. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  992. }
  993. }
  994. else
  995. {
  996. // First time we find the given object in the list
  997. // (and most likely case is that no other occurence will be found)
  998. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  999. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. return array($aDeletedObjs, $aResetedObjs);
  1006. }
  1007. }
  1008. ?>