dbobject.class.php 34 KB

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