dbobject.class.php 35 KB

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