dbobject.class.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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. $this->ComputeFields();
  309. return $this->m_aCurrValues[$sAttCode];
  310. }
  311. public function GetOriginal($sAttCode)
  312. {
  313. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  314. {
  315. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  316. }
  317. return $this->m_aOrigValues[$sAttCode];
  318. }
  319. public function ComputeFields()
  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. // retrieve the "external fields" linked to this external key
  381. foreach (MetaModel::GetExternalFields(get_class($this), $sAttCode) as $oExtField)
  382. {
  383. $aAvailableFields[$oExtField->GetExtAttCode()] = $oExtField->GetAsHTML($this->Get($oExtField->GetCode()));
  384. }
  385. // Use the "name" of the target class as the label of the hyperlink
  386. // unless it's not available in the external fields...
  387. $sExtClassNameAtt = MetaModel::GetNameAttributeCode($sTargetClass);
  388. if (isset($aAvailableFields[$sExtClassNameAtt]))
  389. {
  390. $sEditValue = $aAvailableFields[$sExtClassNameAtt];
  391. }
  392. else
  393. {
  394. $sEditValue = implode(' / ', $aAvailableFields);
  395. }
  396. }
  397. }
  398. else
  399. {
  400. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  401. }
  402. return $sEditValue;
  403. }
  404. public function GetAsXML($sAttCode)
  405. {
  406. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  407. return $oAtt->GetAsXML($this->Get($sAttCode));
  408. }
  409. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  410. {
  411. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  412. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  413. }
  414. protected static function MakeHyperLink($sObjClass, $sObjKey, $aAvailableFields)
  415. {
  416. if ($sObjKey == 0) return '<em>undefined</em>';
  417. return MetaModel::GetName($sObjClass)."::$sObjKey";
  418. }
  419. public function GetHyperlink()
  420. {
  421. $aAvailableFields[MetaModel::GetNameAttributeCode(get_class($this))] = $this->GetName();
  422. return $this->MakeHyperLink(get_class($this), $this->GetKey(), $aAvailableFields);
  423. }
  424. // could be in the metamodel ?
  425. public static function IsValidPKey($value)
  426. {
  427. return ((string)$value === (string)(int)$value);
  428. }
  429. public function GetKey()
  430. {
  431. return $this->m_iKey;
  432. }
  433. public function SetKey($iNewKey)
  434. {
  435. if (!self::IsValidPKey($iNewKey))
  436. {
  437. throw new CoreException("An object id must be an integer value ($iNewKey)");
  438. }
  439. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  440. {
  441. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  442. }
  443. $this->m_iKey = $iNewKey;
  444. }
  445. public function GetIcon()
  446. {
  447. return MetaModel::GetClassIcon(get_class($this));
  448. }
  449. public function GetName()
  450. {
  451. $sNameAttCode = MetaModel::GetNameAttributeCode(get_class($this));
  452. if (empty($sNameAttCode))
  453. {
  454. return $this->m_iKey;
  455. }
  456. else
  457. {
  458. return $this->Get($sNameAttCode);
  459. }
  460. }
  461. public function GetState()
  462. {
  463. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  464. if (empty($sStateAttCode))
  465. {
  466. return '';
  467. }
  468. else
  469. {
  470. return $this->Get($sStateAttCode);
  471. return MetaModel::GetStateLabel(get_class($this), $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. $aValues = $oAtt->GetAllowedValues();
  546. if (count($aValues) > 0)
  547. {
  548. if (!array_key_exists($toCheck, $aValues))
  549. {
  550. return false;
  551. }
  552. }
  553. }
  554. return true;
  555. }
  556. // check attributes together
  557. public function CheckConsistency()
  558. {
  559. return true;
  560. }
  561. // check if it is allowed to record the new object into the database
  562. // a displayable error is returned
  563. // Note: checks the values and consistency
  564. public function CheckToInsert()
  565. {
  566. $aIssues = array();
  567. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  568. {
  569. if (!$this->CheckValue($sAttCode))
  570. {
  571. $aIssues[$sAttCode] = array(
  572. 'issue' => 'unexpected value'
  573. );
  574. }
  575. }
  576. if (count($aIssues) > 0)
  577. {
  578. return array(false, $aIssues);
  579. }
  580. if (!$this->CheckConsistency())
  581. {
  582. return array(false, $aIssues);
  583. }
  584. return array(true, $aIssues);
  585. }
  586. // check if it is allowed to update the existing object into the database
  587. // a displayable error is returned
  588. // Note: checks the values and consistency
  589. public function CheckToUpdate()
  590. {
  591. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  592. {
  593. if (!$this->CheckValue($sAttCode)) return false;
  594. }
  595. if (!$this->CheckConsistency()) return false;
  596. return true;
  597. }
  598. // check if it is allowed to delete the existing object from the database
  599. // a displayable error is returned
  600. public function CheckToDelete()
  601. {
  602. return true;
  603. }
  604. protected function ListChangedValues(array $aProposal)
  605. {
  606. $aDelta = array();
  607. foreach ($aProposal as $sAtt => $proposedValue)
  608. {
  609. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  610. {
  611. // The value was not set
  612. $aDelta[$sAtt] = $proposedValue;
  613. }
  614. elseif(is_object($proposedValue))
  615. {
  616. // The value is an object, the comparison is not strict
  617. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  618. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  619. {
  620. $aDelta[$sAtt] = $proposedValue;
  621. }
  622. }
  623. else
  624. {
  625. // The value is a scalar, the comparison must be 100% strict
  626. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  627. {
  628. //echo "$sAtt:<pre>\n";
  629. //var_dump($this->m_aOrigValues[$sAtt]);
  630. //var_dump($proposedValue);
  631. //echo "</pre>\n";
  632. $aDelta[$sAtt] = $proposedValue;
  633. }
  634. }
  635. }
  636. return $aDelta;
  637. }
  638. // List the attributes that have been changed
  639. // Returns an array of attname => currentvalue
  640. public function ListChanges()
  641. {
  642. return $this->ListChangedValues($this->m_aCurrValues);
  643. }
  644. // Tells whether or not an object was modified
  645. public function IsModified()
  646. {
  647. $aChanges = $this->ListChanges();
  648. return (count($aChanges) != 0);
  649. }
  650. // used both by insert/update
  651. private function DBWriteLinks()
  652. {
  653. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  654. {
  655. if (!$oAttDef->IsLinkSet()) continue;
  656. $oLinks = $this->Get($sAttCode);
  657. $oLinks->Rewind();
  658. while ($oLinkedObject = $oLinks->Fetch())
  659. {
  660. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  661. if ($oLinkedObject->IsModified())
  662. {
  663. $oLinkedObject->DBWrite();
  664. }
  665. }
  666. // Delete the objects that were initialy present and disappeared from the list
  667. // (if any)
  668. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  669. if ($oOriginalSet != null)
  670. {
  671. $aOriginalList = $oOriginalSet->ToArray();
  672. $aNewSet = $oLinks->ToArray();
  673. $aToDelete = array_diff($aOriginalList, $aNewSet);
  674. foreach ($aToDelete as $iKey => $oObject)
  675. {
  676. $oObject->DBDelete();
  677. }
  678. }
  679. }
  680. }
  681. private function DBInsertSingleTable($sTableClass)
  682. {
  683. $sClass = get_class($this);
  684. // fields in first array, values in the second
  685. $aFieldsToWrite = array();
  686. $aValuesToWrite = array();
  687. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  688. {
  689. // Add it to the list of fields to write
  690. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  691. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  692. }
  693. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  694. {
  695. // Skip this attribute if not defined in this table
  696. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  697. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  698. foreach($aAttColumns as $sColumn => $sValue)
  699. {
  700. $aFieldsToWrite[] = "`$sColumn`";
  701. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  702. }
  703. }
  704. if (count($aValuesToWrite) == 0) return false;
  705. $sTable = MetaModel::DBGetTable($sTableClass);
  706. $sInsertSQL = "INSERT INTO $sTable (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  707. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  708. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  709. if (empty($this->m_iKey))
  710. {
  711. // Take the autonumber
  712. $this->m_iKey = $iNewKey;
  713. }
  714. return $this->m_iKey;
  715. }
  716. // To be optionaly overloaded
  717. public function OnInsert()
  718. {
  719. }
  720. // Insert of record for the new object into the database
  721. // Returns the key of the newly created object
  722. public function DBInsertNoReload()
  723. {
  724. if ($this->m_bIsInDB)
  725. {
  726. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  727. }
  728. $sClass = get_class($this);
  729. $sRootClass = MetaModel::GetRootClass($sClass);
  730. // Ensure the update of the values (we are accessing the data directly)
  731. $this->ComputeFields();
  732. $this->OnInsert();
  733. if ($this->m_iKey < 0)
  734. {
  735. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  736. $this->m_iKey = null;
  737. }
  738. // If not automatically computed, then check that the key is given by the caller
  739. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  740. {
  741. if (empty($this->m_iKey))
  742. {
  743. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  744. }
  745. }
  746. // First query built upon on the root class, because the ID must be created first
  747. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  748. // Then do the leaf class, if different from the root class
  749. if ($sClass != $sRootClass)
  750. {
  751. $this->DBInsertSingleTable($sClass);
  752. }
  753. // Then do the other classes
  754. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  755. {
  756. if ($sParentClass == $sRootClass) continue;
  757. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  758. $this->DBInsertSingleTable($sParentClass);
  759. }
  760. $this->DBWriteLinks();
  761. $this->m_bIsInDB = true;
  762. // Activate any existing trigger
  763. $sClass = get_class($this);
  764. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  765. while ($oTrigger = $oSet->Fetch())
  766. {
  767. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  768. {
  769. $oTrigger->DoActivate($this->ToArgs('this'));
  770. }
  771. }
  772. return $this->m_iKey;
  773. }
  774. public function DBInsert()
  775. {
  776. $this->DBInsertNoReload();
  777. $this->m_bDirty = false;
  778. $this->Reload();
  779. return $this->m_iKey;
  780. }
  781. // Creates a copy of the current object into the database
  782. // Returns the id of the newly created object
  783. public function DBClone($iNewKey = null)
  784. {
  785. $this->m_bIsInDB = false;
  786. $this->m_iKey = $iNewKey;
  787. return $this->DBInsert();
  788. }
  789. // Update a record
  790. public function DBUpdate()
  791. {
  792. if (!$this->m_bIsInDB)
  793. {
  794. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  795. }
  796. $aChanges = $this->ListChanges();
  797. if (count($aChanges) == 0)
  798. {
  799. throw new CoreWarning("Attempting to update an unchanged object");
  800. return;
  801. }
  802. $bHasANewExternalKeyValue = false;
  803. foreach($aChanges as $sAttCode => $valuecurr)
  804. {
  805. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  806. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  807. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  808. }
  809. // Update scalar attributes
  810. if (count($aChanges) != 0)
  811. {
  812. $oFilter = new DBObjectSearch(get_class($this));
  813. $oFilter->AddCondition('id', $this->m_iKey, '=');
  814. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  815. CMDBSource::Query($sSQL);
  816. }
  817. $this->DBWriteLinks();
  818. $this->m_bDirty = false;
  819. // Reload to get the external attributes
  820. if ($bHasANewExternalKeyValue)
  821. {
  822. $this->Reload();
  823. }
  824. return $this->m_iKey;
  825. }
  826. // Make the current changes persistent - clever wrapper for Insert or Update
  827. public function DBWrite()
  828. {
  829. if ($this->m_bIsInDB)
  830. {
  831. return $this->DBUpdate();
  832. }
  833. else
  834. {
  835. return $this->DBInsert();
  836. }
  837. }
  838. // Delete a record
  839. public function DBDelete()
  840. {
  841. $oFilter = new DBObjectSearch(get_class($this));
  842. $oFilter->AddCondition('id', $this->m_iKey, '=');
  843. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  844. CMDBSource::Query($sSQL);
  845. $this->m_bIsInDB = false;
  846. $this->m_iKey = null;
  847. }
  848. public function EnumTransitions()
  849. {
  850. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  851. if (empty($sStateAttCode)) return array();
  852. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  853. return MetaModel::EnumTransitions(get_class($this), $sState);
  854. }
  855. public function ApplyStimulus($sStimulusCode)
  856. {
  857. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  858. if (empty($sStateAttCode)) return false;
  859. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  860. $aStateTransitions = $this->EnumTransitions();
  861. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  862. // Change the state before proceeding to the actions, this is necessary because an action might
  863. // trigger another stimuli (alternative: push the stimuli into a queue)
  864. $sPreviousState = $this->Get($sStateAttCode);
  865. $sNewState = $aTransitionDef['target_state'];
  866. $this->Set($sStateAttCode, $sNewState);
  867. // $aTransitionDef is an
  868. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  869. $bSuccess = true;
  870. foreach ($aTransitionDef['actions'] as $sActionHandler)
  871. {
  872. // std PHP spec
  873. $aActionCallSpec = array($this, $sActionHandler);
  874. if (!is_callable($aActionCallSpec))
  875. {
  876. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  877. return;
  878. }
  879. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  880. // if one call fails, the whole is considered as failed
  881. if (!$bRet) $bSuccess = false;
  882. }
  883. // Change state triggers...
  884. $sClass = get_class($this);
  885. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class='$sClass' AND t.state='$sPreviousState'"));
  886. while ($oTrigger = $oSet->Fetch())
  887. {
  888. $oTrigger->DoActivate($this->ToArgs('this'));
  889. }
  890. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class='$sClass' AND t.state='$sNewState'"));
  891. while ($oTrigger = $oSet->Fetch())
  892. {
  893. $oTrigger->DoActivate($this->ToArgs('this'));
  894. }
  895. return $bSuccess;
  896. }
  897. // Make standard context arguments
  898. public function ToArgs($sArgName = 'this')
  899. {
  900. $aScalarArgs = array();
  901. $aScalarArgs[$sArgName] = $this->GetKey();
  902. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  903. $aScalarArgs[$sArgName.'->object()'] = $this;
  904. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  905. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  906. $sClass = get_class($this);
  907. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  908. {
  909. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  910. }
  911. return $aScalarArgs;
  912. }
  913. // Return an empty set for the parent of all
  914. public static function GetRelationQueries($sRelCode)
  915. {
  916. return array();
  917. }
  918. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  919. {
  920. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  921. {
  922. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  923. $sQuery = $aQueryInfo["sQuery"];
  924. $bPropagate = $aQueryInfo["bPropagate"];
  925. $iDistance = $aQueryInfo["iDistance"];
  926. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  927. $oFlt = DBObjectSearch::FromOQL($sQuery);
  928. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  929. while ($oObj = $oObjSet->Fetch())
  930. {
  931. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  932. $sObjKey = $oObj->GetKey();
  933. if (array_key_exists($sRootClass, $aResults))
  934. {
  935. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  936. {
  937. continue; // already visited, skip
  938. }
  939. }
  940. $aResults[$sRootClass][$sObjKey] = $oObj;
  941. if ($iDepth > 0)
  942. {
  943. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  944. }
  945. }
  946. }
  947. return $aResults;
  948. }
  949. public function GetReferencingObjects()
  950. {
  951. $aDependentObjects = array();
  952. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  953. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  954. {
  955. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  956. {
  957. // skip if this external key is behind an external field
  958. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  959. $oSearch = new DBObjectSearch($sRemoteClass);
  960. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey());
  961. $oSet = new CMDBObjectSet($oSearch);
  962. if ($oSet->Count() > 0)
  963. {
  964. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  965. 'attribute' => $oExtKeyAttDef,
  966. 'objects' => $oSet,
  967. );
  968. }
  969. }
  970. }
  971. return $aDependentObjects;
  972. }
  973. public function GetDeletionScheme()
  974. {
  975. $aDependentObjects = $this->GetReferencingObjects();
  976. $aDeletedObjs = array(); // [class][key] => structure
  977. $aResetedObjs = array(); // [class][key] => object
  978. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  979. {
  980. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  981. {
  982. $oAttDef = $aData['attribute'];
  983. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  984. $oDepSet = $aData['objects'];
  985. $oDepSet->Rewind();
  986. while ($oDependentObj = $oDepSet->fetch())
  987. {
  988. $iId = $oDependentObj->GetKey();
  989. if ($oAttDef->IsNullAllowed())
  990. {
  991. // Optional external key, list to reset
  992. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  993. {
  994. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  995. }
  996. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  997. }
  998. else
  999. {
  1000. // Mandatory external key, list to delete
  1001. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1002. {
  1003. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1004. if ($iCurrentOption == DEL_AUTO)
  1005. {
  1006. // be conservative, take the new option
  1007. // (DEL_MANUAL has precedence over DEL_AUTO)
  1008. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1009. }
  1010. else
  1011. {
  1012. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1013. }
  1014. }
  1015. else
  1016. {
  1017. // First time we find the given object in the list
  1018. // (and most likely case is that no other occurence will be found)
  1019. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1020. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1021. }
  1022. }
  1023. }
  1024. }
  1025. }
  1026. return array($aDeletedObjs, $aResetedObjs);
  1027. }
  1028. }
  1029. ?>