dbobject.class.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. return MetaModel::GetStateLabel(get_class($this), $sStateAttCode);
  473. }
  474. }
  475. public function GetStateLabel()
  476. {
  477. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  478. if (empty($sStateAttCode))
  479. {
  480. return '';
  481. }
  482. else
  483. {
  484. $sStateValue = $this->Get($sStateAttCode);
  485. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  486. }
  487. }
  488. public function GetStateDescription()
  489. {
  490. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  491. if (empty($sStateAttCode))
  492. {
  493. return '';
  494. }
  495. else
  496. {
  497. $sStateValue = $this->Get($sStateAttCode);
  498. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  499. }
  500. }
  501. /**
  502. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  503. * for the given attribute in the current state of the object
  504. * @param string $sAttCode The code of the attribute
  505. * @return integer Flags: the binary combination of the flags applicable to this attribute
  506. */
  507. public function GetAttributeFlags($sAttCode)
  508. {
  509. $iFlags = 0; // By default (if no life cycle) no flag at all
  510. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  511. if (!empty($sStateAttCode))
  512. {
  513. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  514. }
  515. return $iFlags;
  516. }
  517. // check if the given (or current) value is suitable for the attribute
  518. public function CheckValue($sAttCode, $value = null)
  519. {
  520. if (!is_null($value))
  521. {
  522. $toCheck = $value;
  523. }
  524. else
  525. {
  526. $toCheck = $this->Get($sAttCode);
  527. }
  528. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  529. if ($oAtt->IsExternalKey())
  530. {
  531. if (!$oAtt->IsNullAllowed() || ($toCheck != 0) )
  532. {
  533. try
  534. {
  535. $oTargetObj = MetaModel::GetObject($oAtt->GetTargetClass(), $toCheck);
  536. return true;
  537. }
  538. catch (CoreException $e)
  539. {
  540. return false;
  541. }
  542. }
  543. }
  544. elseif ($oAtt->IsWritable() && $oAtt->IsScalar())
  545. {
  546. if (is_null($toCheck))
  547. {
  548. if ($oAtt->IsNullAllowed())
  549. {
  550. return true;
  551. }
  552. else
  553. {
  554. return false;
  555. }
  556. }
  557. $aValues = $oAtt->GetAllowedValues();
  558. if (count($aValues) > 0)
  559. {
  560. if (!array_key_exists($toCheck, $aValues))
  561. {
  562. return false;
  563. }
  564. }
  565. }
  566. return true;
  567. }
  568. // check attributes together
  569. public function CheckConsistency()
  570. {
  571. return true;
  572. }
  573. // check if it is allowed to record the new object into the database
  574. // a displayable error is returned
  575. // Note: checks the values and consistency
  576. public function CheckToInsert()
  577. {
  578. $aIssues = array();
  579. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  580. {
  581. if (!$this->CheckValue($sAttCode))
  582. {
  583. $aIssues[$sAttCode] = array(
  584. 'issue' => 'unexpected value'
  585. );
  586. }
  587. }
  588. if (count($aIssues) > 0)
  589. {
  590. return array(false, $aIssues);
  591. }
  592. if (!$this->CheckConsistency())
  593. {
  594. return array(false, $aIssues);
  595. }
  596. return array(true, $aIssues);
  597. }
  598. // check if it is allowed to update the existing object into the database
  599. // a displayable error is returned
  600. // Note: checks the values and consistency
  601. public function CheckToUpdate()
  602. {
  603. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  604. {
  605. if (!$this->CheckValue($sAttCode)) return false;
  606. }
  607. if (!$this->CheckConsistency()) return false;
  608. return true;
  609. }
  610. // check if it is allowed to delete the existing object from the database
  611. // a displayable error is returned
  612. public function CheckToDelete()
  613. {
  614. return true;
  615. }
  616. protected function ListChangedValues(array $aProposal)
  617. {
  618. $aDelta = array();
  619. foreach ($aProposal as $sAtt => $proposedValue)
  620. {
  621. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  622. {
  623. // The value was not set
  624. $aDelta[$sAtt] = $proposedValue;
  625. }
  626. elseif(is_object($proposedValue))
  627. {
  628. // The value is an object, the comparison is not strict
  629. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  630. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  631. {
  632. $aDelta[$sAtt] = $proposedValue;
  633. }
  634. }
  635. else
  636. {
  637. // The value is a scalar, the comparison must be 100% strict
  638. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  639. {
  640. //echo "$sAtt:<pre>\n";
  641. //var_dump($this->m_aOrigValues[$sAtt]);
  642. //var_dump($proposedValue);
  643. //echo "</pre>\n";
  644. $aDelta[$sAtt] = $proposedValue;
  645. }
  646. }
  647. }
  648. return $aDelta;
  649. }
  650. // List the attributes that have been changed
  651. // Returns an array of attname => currentvalue
  652. public function ListChanges()
  653. {
  654. return $this->ListChangedValues($this->m_aCurrValues);
  655. }
  656. // Tells whether or not an object was modified
  657. public function IsModified()
  658. {
  659. $aChanges = $this->ListChanges();
  660. return (count($aChanges) != 0);
  661. }
  662. // used both by insert/update
  663. private function DBWriteLinks()
  664. {
  665. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  666. {
  667. if (!$oAttDef->IsLinkSet()) continue;
  668. $oLinks = $this->Get($sAttCode);
  669. $oLinks->Rewind();
  670. while ($oLinkedObject = $oLinks->Fetch())
  671. {
  672. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  673. if ($oLinkedObject->IsModified())
  674. {
  675. $oLinkedObject->DBWrite();
  676. }
  677. }
  678. // Delete the objects that were initialy present and disappeared from the list
  679. // (if any)
  680. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  681. if ($oOriginalSet != null)
  682. {
  683. $aOriginalList = $oOriginalSet->ToArray();
  684. $aNewSet = $oLinks->ToArray();
  685. $aToDelete = array_diff($aOriginalList, $aNewSet);
  686. foreach ($aToDelete as $iKey => $oObject)
  687. {
  688. $oObject->DBDelete();
  689. }
  690. }
  691. }
  692. }
  693. private function DBInsertSingleTable($sTableClass)
  694. {
  695. $sClass = get_class($this);
  696. // fields in first array, values in the second
  697. $aFieldsToWrite = array();
  698. $aValuesToWrite = array();
  699. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  700. {
  701. // Add it to the list of fields to write
  702. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  703. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  704. }
  705. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  706. {
  707. // Skip this attribute if not defined in this table
  708. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  709. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  710. foreach($aAttColumns as $sColumn => $sValue)
  711. {
  712. $aFieldsToWrite[] = "`$sColumn`";
  713. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  714. }
  715. }
  716. if (count($aValuesToWrite) == 0) return false;
  717. $sTable = MetaModel::DBGetTable($sTableClass);
  718. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  719. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  720. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  721. if (empty($this->m_iKey))
  722. {
  723. // Take the autonumber
  724. $this->m_iKey = $iNewKey;
  725. }
  726. return $this->m_iKey;
  727. }
  728. // To be optionaly overloaded
  729. public function OnInsert()
  730. {
  731. }
  732. // Insert of record for the new object into the database
  733. // Returns the key of the newly created object
  734. public function DBInsertNoReload()
  735. {
  736. if ($this->m_bIsInDB)
  737. {
  738. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  739. }
  740. $sClass = get_class($this);
  741. $sRootClass = MetaModel::GetRootClass($sClass);
  742. // Ensure the update of the values (we are accessing the data directly)
  743. $this->DoComputeValues();
  744. $this->OnInsert();
  745. if ($this->m_iKey < 0)
  746. {
  747. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  748. $this->m_iKey = null;
  749. }
  750. // If not automatically computed, then check that the key is given by the caller
  751. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  752. {
  753. if (empty($this->m_iKey))
  754. {
  755. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber");
  756. }
  757. }
  758. // First query built upon on the root class, because the ID must be created first
  759. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  760. // Then do the leaf class, if different from the root class
  761. if ($sClass != $sRootClass)
  762. {
  763. $this->DBInsertSingleTable($sClass);
  764. }
  765. // Then do the other classes
  766. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  767. {
  768. if ($sParentClass == $sRootClass) continue;
  769. if (MetaModel::DBGetTable($sParentClass) == "") continue;
  770. $this->DBInsertSingleTable($sParentClass);
  771. }
  772. $this->DBWriteLinks();
  773. $this->m_bIsInDB = true;
  774. // Activate any existing trigger
  775. $sClass = get_class($this);
  776. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  777. while ($oTrigger = $oSet->Fetch())
  778. {
  779. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  780. {
  781. $oTrigger->DoActivate($this->ToArgs('this'));
  782. }
  783. }
  784. return $this->m_iKey;
  785. }
  786. public function DBInsert()
  787. {
  788. $this->DBInsertNoReload();
  789. $this->m_bDirty = false;
  790. $this->Reload();
  791. return $this->m_iKey;
  792. }
  793. // Creates a copy of the current object into the database
  794. // Returns the id of the newly created object
  795. public function DBClone($iNewKey = null)
  796. {
  797. $this->m_bIsInDB = false;
  798. $this->m_iKey = $iNewKey;
  799. return $this->DBInsert();
  800. }
  801. // Update a record
  802. public function DBUpdate()
  803. {
  804. if (!$this->m_bIsInDB)
  805. {
  806. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  807. }
  808. $this->DoComputeValues();
  809. $aChanges = $this->ListChanges();
  810. if (count($aChanges) == 0)
  811. {
  812. throw new CoreWarning("Attempting to update an unchanged object");
  813. return;
  814. }
  815. $bHasANewExternalKeyValue = false;
  816. foreach($aChanges as $sAttCode => $valuecurr)
  817. {
  818. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  819. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  820. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  821. }
  822. // Update scalar attributes
  823. if (count($aChanges) != 0)
  824. {
  825. $oFilter = new DBObjectSearch(get_class($this));
  826. $oFilter->AddCondition('id', $this->m_iKey, '=');
  827. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  828. CMDBSource::Query($sSQL);
  829. }
  830. $this->DBWriteLinks();
  831. $this->m_bDirty = false;
  832. // Reload to get the external attributes
  833. if ($bHasANewExternalKeyValue)
  834. {
  835. $this->Reload();
  836. }
  837. return $this->m_iKey;
  838. }
  839. // Make the current changes persistent - clever wrapper for Insert or Update
  840. public function DBWrite()
  841. {
  842. if ($this->m_bIsInDB)
  843. {
  844. return $this->DBUpdate();
  845. }
  846. else
  847. {
  848. return $this->DBInsert();
  849. }
  850. }
  851. // Delete a record
  852. public function DBDelete()
  853. {
  854. $oFilter = new DBObjectSearch(get_class($this));
  855. $oFilter->AddCondition('id', $this->m_iKey, '=');
  856. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  857. CMDBSource::Query($sSQL);
  858. $this->m_bIsInDB = false;
  859. $this->m_iKey = null;
  860. }
  861. public function EnumTransitions()
  862. {
  863. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  864. if (empty($sStateAttCode)) return array();
  865. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  866. return MetaModel::EnumTransitions(get_class($this), $sState);
  867. }
  868. public function ApplyStimulus($sStimulusCode)
  869. {
  870. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  871. if (empty($sStateAttCode)) return false;
  872. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  873. $aStateTransitions = $this->EnumTransitions();
  874. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  875. // Change the state before proceeding to the actions, this is necessary because an action might
  876. // trigger another stimuli (alternative: push the stimuli into a queue)
  877. $sPreviousState = $this->Get($sStateAttCode);
  878. $sNewState = $aTransitionDef['target_state'];
  879. $this->Set($sStateAttCode, $sNewState);
  880. // $aTransitionDef is an
  881. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  882. $bSuccess = true;
  883. foreach ($aTransitionDef['actions'] as $sActionHandler)
  884. {
  885. // std PHP spec
  886. $aActionCallSpec = array($this, $sActionHandler);
  887. if (!is_callable($aActionCallSpec))
  888. {
  889. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  890. return;
  891. }
  892. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  893. // if one call fails, the whole is considered as failed
  894. if (!$bRet) $bSuccess = false;
  895. }
  896. // Change state triggers...
  897. $sClass = get_class($this);
  898. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class='$sClass' AND t.state='$sPreviousState'"));
  899. while ($oTrigger = $oSet->Fetch())
  900. {
  901. $oTrigger->DoActivate($this->ToArgs('this'));
  902. }
  903. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class='$sClass' AND t.state='$sNewState'"));
  904. while ($oTrigger = $oSet->Fetch())
  905. {
  906. $oTrigger->DoActivate($this->ToArgs('this'));
  907. }
  908. return $bSuccess;
  909. }
  910. // Make standard context arguments
  911. public function ToArgs($sArgName = 'this')
  912. {
  913. $aScalarArgs = array();
  914. $aScalarArgs[$sArgName] = $this->GetKey();
  915. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  916. $aScalarArgs[$sArgName.'->object()'] = $this;
  917. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  918. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  919. $sClass = get_class($this);
  920. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  921. {
  922. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  923. }
  924. return $aScalarArgs;
  925. }
  926. // Return an empty set for the parent of all
  927. public static function GetRelationQueries($sRelCode)
  928. {
  929. return array();
  930. }
  931. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  932. {
  933. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  934. {
  935. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  936. $sQuery = $aQueryInfo["sQuery"];
  937. $bPropagate = $aQueryInfo["bPropagate"];
  938. $iDistance = $aQueryInfo["iDistance"];
  939. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  940. $oFlt = DBObjectSearch::FromOQL($sQuery);
  941. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  942. while ($oObj = $oObjSet->Fetch())
  943. {
  944. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  945. $sObjKey = $oObj->GetKey();
  946. if (array_key_exists($sRootClass, $aResults))
  947. {
  948. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  949. {
  950. continue; // already visited, skip
  951. }
  952. }
  953. $aResults[$sRootClass][$sObjKey] = $oObj;
  954. if ($iDepth > 0)
  955. {
  956. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  957. }
  958. }
  959. }
  960. return $aResults;
  961. }
  962. public function GetReferencingObjects()
  963. {
  964. $aDependentObjects = array();
  965. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  966. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  967. {
  968. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  969. {
  970. // skip if this external key is behind an external field
  971. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  972. $oSearch = new DBObjectSearch($sRemoteClass);
  973. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey());
  974. $oSet = new CMDBObjectSet($oSearch);
  975. if ($oSet->Count() > 0)
  976. {
  977. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  978. 'attribute' => $oExtKeyAttDef,
  979. 'objects' => $oSet,
  980. );
  981. }
  982. }
  983. }
  984. return $aDependentObjects;
  985. }
  986. public function GetDeletionScheme()
  987. {
  988. $aDependentObjects = $this->GetReferencingObjects();
  989. $aDeletedObjs = array(); // [class][key] => structure
  990. $aResetedObjs = array(); // [class][key] => object
  991. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  992. {
  993. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  994. {
  995. $oAttDef = $aData['attribute'];
  996. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  997. $oDepSet = $aData['objects'];
  998. $oDepSet->Rewind();
  999. while ($oDependentObj = $oDepSet->fetch())
  1000. {
  1001. $iId = $oDependentObj->GetKey();
  1002. if ($oAttDef->IsNullAllowed())
  1003. {
  1004. // Optional external key, list to reset
  1005. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1006. {
  1007. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1008. }
  1009. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1010. }
  1011. else
  1012. {
  1013. // Mandatory external key, list to delete
  1014. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1015. {
  1016. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1017. if ($iCurrentOption == DEL_AUTO)
  1018. {
  1019. // be conservative, take the new option
  1020. // (DEL_MANUAL has precedence over DEL_AUTO)
  1021. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1022. }
  1023. else
  1024. {
  1025. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1026. }
  1027. }
  1028. else
  1029. {
  1030. // First time we find the given object in the list
  1031. // (and most likely case is that no other occurence will be found)
  1032. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1033. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1034. }
  1035. }
  1036. }
  1037. }
  1038. }
  1039. return array($aDeletedObjs, $aResetedObjs);
  1040. }
  1041. }
  1042. ?>