dbobject.class.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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. protected $m_aExtendedData = null;
  38. private $m_bDirty = false; // Means: "a modification is ongoing"
  39. // The object may have incorrect external keys, then any attempt of reload must be avoided
  40. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  41. // if null, then the check has to be performed again to know the status
  42. protected $m_aCheckIssues = null;
  43. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  44. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  45. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  46. protected $m_oMasterReplicaSet = null; // Set of SynchroReplica related to this object
  47. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  48. public function __construct($aRow = null, $sClassAlias = '', $aExtendedDataSpec = null)
  49. {
  50. if (!empty($aRow))
  51. {
  52. $this->FromRow($aRow, $sClassAlias, $aExtendedDataSpec);
  53. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  54. return;
  55. }
  56. // Creation of brand new object
  57. //
  58. $this->m_iKey = self::GetNextTempId(get_class($this));
  59. // set default values
  60. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  61. {
  62. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  63. $this->m_aOrigValues[$sAttCode] = null;
  64. if ($oAttDef->IsExternalField())
  65. {
  66. // This field has to be read from the DB
  67. $this->m_aLoadedAtt[$sAttCode] = false;
  68. }
  69. else
  70. {
  71. // No need to trigger a reload for that attribute
  72. // Let's consider it as being already fully loaded
  73. $this->m_aLoadedAtt[$sAttCode] = true;
  74. }
  75. }
  76. }
  77. // Read-only <=> Written once (archive)
  78. public function RegisterAsDirty()
  79. {
  80. // While the object may be written to the DB, it is NOT possible to reload it
  81. // or at least not possible to reload it the same way
  82. $this->m_bDirty = true;
  83. }
  84. public function IsNew()
  85. {
  86. return (!$this->m_bIsInDB);
  87. }
  88. // Returns an Id for memory objects
  89. static protected function GetNextTempId($sClass)
  90. {
  91. if (!array_key_exists($sClass, self::$m_aMemoryObjectsByClass))
  92. {
  93. self::$m_aMemoryObjectsByClass[$sClass] = 0;
  94. }
  95. self::$m_aMemoryObjectsByClass[$sClass]++;
  96. return (- self::$m_aMemoryObjectsByClass[$sClass]);
  97. }
  98. public function __toString()
  99. {
  100. $sRet = '';
  101. $sClass = get_class($this);
  102. $sRootClass = MetaModel::GetRootClass($sClass);
  103. $iPKey = $this->GetKey();
  104. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  105. $sRet .= "<ul class=\"treeview\">\n";
  106. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  107. {
  108. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  109. }
  110. $sRet .= "</ul>";
  111. return $sRet;
  112. }
  113. // Restore initial values... mmmm, to be discussed
  114. public function DBRevert()
  115. {
  116. $this->Reload();
  117. }
  118. protected function IsFullyLoaded()
  119. {
  120. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  121. {
  122. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  123. if ($bIsLoaded !== true)
  124. {
  125. return false;
  126. }
  127. }
  128. return true;
  129. }
  130. protected function Reload()
  131. {
  132. assert($this->m_bIsInDB);
  133. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey);
  134. if (empty($aRow))
  135. {
  136. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  137. }
  138. $this->FromRow($aRow);
  139. // Process linked set attributes
  140. //
  141. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  142. {
  143. if (!$oAttDef->IsLinkSet()) continue;
  144. // Load the link information
  145. $sLinkClass = $oAttDef->GetLinkedClass();
  146. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  147. // The class to target is not the current class, because if this is a derived class,
  148. // it may differ from the target class, then things start to become confusing
  149. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  150. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  151. $oMyselfSearch = new DBObjectSearch($sMyClass);
  152. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  153. $oLinkSearch = new DBObjectSearch($sLinkClass);
  154. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  155. $oLinks = new DBObjectSet($oLinkSearch);
  156. $this->m_aCurrValues[$sAttCode] = $oLinks;
  157. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  158. $this->m_aLoadedAtt[$sAttCode] = true;
  159. }
  160. $this->m_bFullyLoaded = true;
  161. }
  162. protected function FromRow($aRow, $sClassAlias = '', $aExtendedDataSpec = null)
  163. {
  164. if (strlen($sClassAlias) == 0)
  165. {
  166. // Default to the current class
  167. $sClassAlias = get_class($this);
  168. }
  169. $this->m_iKey = null;
  170. $this->m_bIsInDB = true;
  171. $this->m_aCurrValues = array();
  172. $this->m_aOrigValues = array();
  173. $this->m_aLoadedAtt = array();
  174. $this->m_bCheckStatus = true;
  175. // Get the key
  176. //
  177. $sKeyField = $sClassAlias."id";
  178. if (!array_key_exists($sKeyField, $aRow))
  179. {
  180. // #@# Bug ?
  181. throw new CoreException("Missing key for class '".get_class($this)."'");
  182. }
  183. else
  184. {
  185. $iPKey = $aRow[$sKeyField];
  186. if (!self::IsValidPKey($iPKey))
  187. {
  188. throw new CoreWarning("An object id must be an integer value ($iPKey)");
  189. }
  190. $this->m_iKey = $iPKey;
  191. }
  192. // Build the object from an array of "attCode"=>"value")
  193. //
  194. $bFullyLoaded = true; // ... set to false if any attribute is not found
  195. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  196. {
  197. // Say something, whatever the type of attribute
  198. $this->m_aLoadedAtt[$sAttCode] = false;
  199. // Skip links (could not be loaded by the mean of this query)
  200. if ($oAttDef->IsLinkSet()) continue;
  201. // Note: we assume that, for a given attribute, if it can be loaded,
  202. // then one column will be found with an empty suffix, the others have a suffix
  203. // Take care: the function isset will return false in case the value is null,
  204. // which is something that could happen on open joins
  205. $sAttRef = $sClassAlias.$sAttCode;
  206. if (array_key_exists($sAttRef, $aRow))
  207. {
  208. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  209. $this->m_aCurrValues[$sAttCode] = $value;
  210. $this->m_aOrigValues[$sAttCode] = $value;
  211. $this->m_aLoadedAtt[$sAttCode] = true;
  212. }
  213. else
  214. {
  215. // This attribute was expected and not found in the query columns
  216. $bFullyLoaded = false;
  217. }
  218. }
  219. // Load extended data
  220. if ($aExtendedDataSpec != null)
  221. {
  222. $aExtendedDataSpec['table'];
  223. foreach($aExtendedDataSpec['fields'] as $sColumn)
  224. {
  225. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  226. if (array_key_exists($sColRef, $aRow))
  227. {
  228. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  229. }
  230. }
  231. }
  232. return $bFullyLoaded;
  233. }
  234. public function Set($sAttCode, $value)
  235. {
  236. if ($sAttCode == 'finalclass')
  237. {
  238. // Ignore it - this attribute is set upon object creation and that's it
  239. return;
  240. }
  241. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  242. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  243. {
  244. // First time Set is called... ensure that the object gets fully loaded
  245. // Otherwise we would lose the values on a further Reload
  246. // + consistency does not make sense !
  247. $this->Reload();
  248. }
  249. if ($oAttDef->IsExternalKey() && is_object($value))
  250. {
  251. // Setting an external key with a whole object (instead of just an ID)
  252. // let's initialize also the external fields that depend on it
  253. // (useful when building objects in memory and not from a query)
  254. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  255. {
  256. throw new CoreUnexpectedValue("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
  257. }
  258. else
  259. {
  260. // The object has changed, reset caches
  261. $this->m_bCheckStatus = null;
  262. $this->m_aAsArgs = null;
  263. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  264. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  265. {
  266. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  267. {
  268. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  269. }
  270. }
  271. }
  272. return;
  273. }
  274. if(!$oAttDef->IsScalar() && !is_object($value))
  275. {
  276. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  277. }
  278. if($oAttDef->IsLinkSet())
  279. {
  280. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  281. {
  282. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  283. }
  284. $oObjectSet = $value;
  285. $sSetClass = $oObjectSet->GetClass();
  286. $sLinkClass = $oAttDef->GetLinkedClass();
  287. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  288. if ($sSetClass != $sLinkClass)
  289. {
  290. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  291. }
  292. }
  293. $realvalue = $oAttDef->MakeRealValue($value);
  294. $this->m_aCurrValues[$sAttCode] = $realvalue;
  295. // The object has changed, reset caches
  296. $this->m_bCheckStatus = null;
  297. $this->m_aAsArgs = null;
  298. // Make sure we do not reload it anymore... before saving it
  299. $this->RegisterAsDirty();
  300. }
  301. public function Get($sAttCode)
  302. {
  303. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  304. {
  305. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  306. }
  307. if ($this->m_bIsInDB && !$this->m_aLoadedAtt[$sAttCode] && !$this->m_bDirty)
  308. {
  309. // #@# non-scalar attributes.... handle that differently
  310. $this->Reload();
  311. }
  312. $value = $this->m_aCurrValues[$sAttCode];
  313. if ($value instanceof DBObjectSet)
  314. {
  315. $value->Rewind();
  316. }
  317. return $value;
  318. }
  319. public function GetOriginal($sAttCode)
  320. {
  321. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  322. {
  323. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  324. }
  325. return $this->m_aOrigValues[$sAttCode];
  326. }
  327. /**
  328. * Returns data loaded by the mean of a dynamic and explicit JOIN
  329. */
  330. public function GetExtendedData()
  331. {
  332. return $this->m_aExtendedData;
  333. }
  334. /**
  335. * Updates the value of an external field by (re)loading the object
  336. * corresponding to the external key and getting the value from it
  337. * @param string $sAttCode Attribute code of the external field to update
  338. * @return void
  339. */
  340. protected function UpdateExternalField($sAttCode)
  341. {
  342. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  343. if ($oAttDef->IsExternalField())
  344. {
  345. $sTargetClass = $oAttDef->GetTargetClass();
  346. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  347. $oObj = MetaModel::GetObject($sTargetClass, $objkey);
  348. if (is_object($oObj))
  349. {
  350. $value = $oObj->Get($oAttDef->GetExtAttCode());
  351. $this->Set($sAttCode, $value);
  352. }
  353. }
  354. }
  355. public function ComputeValues()
  356. {
  357. }
  358. // Compute scalar attributes that depend on any other type of attribute
  359. final public function DoComputeValues()
  360. {
  361. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  362. // First check that we are not currently computing the fields
  363. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  364. foreach (debug_backtrace() as $aCallInfo)
  365. {
  366. if (!array_key_exists("class", $aCallInfo)) continue;
  367. if ($aCallInfo["class"] != get_class($this)) continue;
  368. if ($aCallInfo["function"] != "ComputeValues") continue;
  369. return; //skip!
  370. }
  371. $this->ComputeValues();
  372. }
  373. public function GetAsHTML($sAttCode)
  374. {
  375. $sClass = get_class($this);
  376. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  377. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  378. {
  379. //return $this->Get($sAttCode.'_friendlyname');
  380. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  381. $iTargetKey = $this->Get($sAttCode);
  382. $sLabel = $this->Get($sAttCode.'_friendlyname');
  383. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  384. }
  385. // That's a standard attribute (might be an ext field or a direct field, etc.)
  386. return $oAtt->GetAsHTML($this->Get($sAttCode));
  387. }
  388. public function GetEditValue($sAttCode)
  389. {
  390. $sClass = get_class($this);
  391. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  392. if ($oAtt->IsExternalKey())
  393. {
  394. $sTargetClass = $oAtt->GetTargetClass();
  395. if ($this->IsNew())
  396. {
  397. // The current object exists only in memory, don't try to query it in the DB !
  398. // instead let's query for the object pointed by the external key, and get its name
  399. $targetObjId = $this->Get($sAttCode);
  400. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  401. if (is_object($oTargetObj))
  402. {
  403. $sEditValue = $oTargetObj->GetName();
  404. }
  405. else
  406. {
  407. $sEditValue = 0;
  408. }
  409. }
  410. else
  411. {
  412. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  413. }
  414. }
  415. else
  416. {
  417. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  418. }
  419. return $sEditValue;
  420. }
  421. public function GetAsXML($sAttCode)
  422. {
  423. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  424. return $oAtt->GetAsXML($this->Get($sAttCode));
  425. }
  426. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  427. {
  428. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  429. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier);
  430. }
  431. protected static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '')
  432. {
  433. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  434. $oAppContext = new ApplicationContext();
  435. $sPage = self::ComputeUIPage($sObjClass);
  436. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  437. // Safety net
  438. //
  439. if (empty($sLabel))
  440. {
  441. $sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  442. }
  443. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  444. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  445. }
  446. public function GetHyperlink()
  447. {
  448. if ($this->IsNew()) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  449. $oAppContext = new ApplicationContext();
  450. $sPage = $this->GetUIPage();
  451. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  452. $sObjClass = get_class($this);
  453. $sObjKey = $this->GetKey();
  454. $sLabel = $this->GetName();
  455. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  456. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  457. }
  458. public static function ComputeUIPage($sClass)
  459. {
  460. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  461. if (!isset($aUIPagesCache[$sClass]))
  462. {
  463. $UIPage = false;
  464. if (is_callable("$sClass::GetUIPage"))
  465. {
  466. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  467. }
  468. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  469. }
  470. $sPage = $aUIPagesCache[$sClass];
  471. return $sPage;
  472. }
  473. public static function GetUIPage()
  474. {
  475. return 'UI.php';
  476. }
  477. // could be in the metamodel ?
  478. public static function IsValidPKey($value)
  479. {
  480. return ((string)$value === (string)(int)$value);
  481. }
  482. public function GetKey()
  483. {
  484. return $this->m_iKey;
  485. }
  486. public function SetKey($iNewKey)
  487. {
  488. if (!self::IsValidPKey($iNewKey))
  489. {
  490. throw new CoreException("An object id must be an integer value ($iNewKey)");
  491. }
  492. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  493. {
  494. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  495. }
  496. $this->m_iKey = $iNewKey;
  497. }
  498. /**
  499. * Get the icon representing this object
  500. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  501. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  502. */
  503. public function GetIcon($bImgTag = true)
  504. {
  505. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  506. }
  507. public function GetName()
  508. {
  509. $aNameSpec = MetaModel::GetNameSpec(get_class($this));
  510. $sFormat = $aNameSpec[0];
  511. $aAttributes = $aNameSpec[1];
  512. $aValues = array();
  513. foreach ($aAttributes as $sAttCode)
  514. {
  515. if (empty($sAttCode))
  516. {
  517. $aValues[] = $this->m_iKey;
  518. }
  519. else
  520. {
  521. $aValues[] = $this->Get($sAttCode);
  522. }
  523. }
  524. return vsprintf($sFormat, $aValues);
  525. }
  526. public function GetState()
  527. {
  528. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  529. if (empty($sStateAttCode))
  530. {
  531. return '';
  532. }
  533. else
  534. {
  535. return $this->Get($sStateAttCode);
  536. }
  537. }
  538. public function GetStateLabel()
  539. {
  540. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  541. if (empty($sStateAttCode))
  542. {
  543. return '';
  544. }
  545. else
  546. {
  547. $sStateValue = $this->Get($sStateAttCode);
  548. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  549. }
  550. }
  551. public function GetStateDescription()
  552. {
  553. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  554. if (empty($sStateAttCode))
  555. {
  556. return '';
  557. }
  558. else
  559. {
  560. $sStateValue = $this->Get($sStateAttCode);
  561. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  562. }
  563. }
  564. /**
  565. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  566. * for the given attribute in the current state of the object
  567. * @param string $sAttCode The code of the attribute
  568. * @return integer Flags: the binary combination of the flags applicable to this attribute
  569. */
  570. public function GetAttributeFlags($sAttCode)
  571. {
  572. $iFlags = 0; // By default (if no life cycle) no flag at all
  573. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  574. if (!empty($sStateAttCode))
  575. {
  576. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  577. }
  578. $aReasons = array();
  579. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  580. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  581. }
  582. // check if the given (or current) value is suitable for the attribute
  583. // return true if successfull
  584. // return the error desciption otherwise
  585. public function CheckValue($sAttCode, $value = null)
  586. {
  587. if (!is_null($value))
  588. {
  589. $toCheck = $value;
  590. }
  591. else
  592. {
  593. $toCheck = $this->Get($sAttCode);
  594. }
  595. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  596. if (!$oAtt->IsWritable())
  597. {
  598. return true;
  599. }
  600. elseif ($oAtt->IsNull($toCheck))
  601. {
  602. if ($oAtt->IsNullAllowed())
  603. {
  604. return true;
  605. }
  606. else
  607. {
  608. return "Null not allowed";
  609. }
  610. }
  611. elseif ($oAtt->IsExternalKey())
  612. {
  613. if (!MetaModel::SkipCheckExtKeys())
  614. {
  615. $sTargetClass = $oAtt->GetTargetClass();
  616. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  617. if (is_null($oTargetObj))
  618. {
  619. return "Target object not found ($sTargetClass::$toCheck)";
  620. }
  621. }
  622. }
  623. elseif ($oAtt->IsScalar())
  624. {
  625. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  626. if (count($aValues) > 0)
  627. {
  628. if (!array_key_exists($toCheck, $aValues))
  629. {
  630. return "Value not allowed [$toCheck]";
  631. }
  632. }
  633. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  634. {
  635. $iLen = strlen($toCheck);
  636. if ($iLen > $iMaxSize)
  637. {
  638. return "String too long (found $iLen, limited to $iMaxSize)";
  639. }
  640. }
  641. if (!$oAtt->CheckFormat($toCheck))
  642. {
  643. return "Wrong format [$toCheck]";
  644. }
  645. }
  646. return true;
  647. }
  648. // check attributes together
  649. public function CheckConsistency()
  650. {
  651. return true;
  652. }
  653. // check integrity rules (before inserting or updating the object)
  654. // a displayable error is returned
  655. public function DoCheckToWrite()
  656. {
  657. $this->DoComputeValues();
  658. $this->m_aCheckIssues = array();
  659. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  660. {
  661. $res = $this->CheckValue($sAttCode);
  662. if ($res !== true)
  663. {
  664. // $res contains the error description
  665. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  666. }
  667. }
  668. if (count($this->m_aCheckIssues) > 0)
  669. {
  670. // No need to check consistency between attributes if any of them has
  671. // an unexpected value
  672. return;
  673. }
  674. $res = $this->CheckConsistency();
  675. if ($res !== true)
  676. {
  677. // $res contains the error description
  678. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  679. }
  680. }
  681. final public function CheckToWrite()
  682. {
  683. if (MetaModel::SkipCheckToWrite())
  684. {
  685. return array(true, array());
  686. }
  687. if (is_null($this->m_bCheckStatus))
  688. {
  689. $oKPI = new ExecutionKPI();
  690. $this->DoCheckToWrite();
  691. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  692. if (count($this->m_aCheckIssues) == 0)
  693. {
  694. $this->m_bCheckStatus = true;
  695. }
  696. else
  697. {
  698. $this->m_bCheckStatus = false;
  699. }
  700. }
  701. return array($this->m_bCheckStatus, $this->m_aCheckIssues);
  702. }
  703. // check if it is allowed to delete the existing object from the database
  704. // a displayable error is returned
  705. public function CheckToDelete()
  706. {
  707. return true;
  708. }
  709. protected function ListChangedValues(array $aProposal)
  710. {
  711. $aDelta = array();
  712. foreach ($aProposal as $sAtt => $proposedValue)
  713. {
  714. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  715. {
  716. // The value was not set
  717. $aDelta[$sAtt] = $proposedValue;
  718. }
  719. elseif(is_object($proposedValue))
  720. {
  721. // The value is an object, the comparison is not strict
  722. // #@# todo - should be even less strict => add verb on AttributeDefinition: Compare($a, $b)
  723. if ($this->m_aOrigValues[$sAtt] != $proposedValue)
  724. {
  725. $aDelta[$sAtt] = $proposedValue;
  726. }
  727. }
  728. else
  729. {
  730. // The value is a scalar, the comparison must be 100% strict
  731. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  732. {
  733. //echo "$sAtt:<pre>\n";
  734. //var_dump($this->m_aOrigValues[$sAtt]);
  735. //var_dump($proposedValue);
  736. //echo "</pre>\n";
  737. $aDelta[$sAtt] = $proposedValue;
  738. }
  739. }
  740. }
  741. return $aDelta;
  742. }
  743. // List the attributes that have been changed
  744. // Returns an array of attname => currentvalue
  745. public function ListChanges()
  746. {
  747. return $this->ListChangedValues($this->m_aCurrValues);
  748. }
  749. // Tells whether or not an object was modified
  750. public function IsModified()
  751. {
  752. $aChanges = $this->ListChanges();
  753. return (count($aChanges) != 0);
  754. }
  755. // used both by insert/update
  756. private function DBWriteLinks()
  757. {
  758. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  759. {
  760. if (!$oAttDef->IsLinkSet()) continue;
  761. $oLinks = $this->Get($sAttCode);
  762. $oLinks->Rewind();
  763. while ($oLinkedObject = $oLinks->Fetch())
  764. {
  765. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  766. if ($oLinkedObject->IsModified())
  767. {
  768. $oLinkedObject->DBWrite();
  769. }
  770. }
  771. // Delete the objects that were initialy present and disappeared from the list
  772. // (if any)
  773. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  774. if ($oOriginalSet != null)
  775. {
  776. $aOriginalList = $oOriginalSet->ToArray();
  777. $aNewSet = $oLinks->ToArray();
  778. foreach($aOriginalList as $iId => $oObject)
  779. {
  780. if (!array_key_exists($iId, $aNewSet))
  781. {
  782. // It disappeared from the list
  783. $oObject->DBDelete();
  784. }
  785. }
  786. }
  787. }
  788. }
  789. private function DBInsertSingleTable($sTableClass)
  790. {
  791. $sTable = MetaModel::DBGetTable($sTableClass);
  792. // Abstract classes or classes having no specific attribute do not have an associated table
  793. if ($sTable == '') return;
  794. $sClass = get_class($this);
  795. // fields in first array, values in the second
  796. $aFieldsToWrite = array();
  797. $aValuesToWrite = array();
  798. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  799. {
  800. // Add it to the list of fields to write
  801. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  802. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  803. }
  804. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  805. {
  806. // Skip this attribute if not defined in this table
  807. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  808. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  809. foreach($aAttColumns as $sColumn => $sValue)
  810. {
  811. $aFieldsToWrite[] = "`$sColumn`";
  812. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  813. }
  814. }
  815. if (count($aValuesToWrite) == 0) return false;
  816. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  817. if (MetaModel::DBIsReadOnly())
  818. {
  819. $iNewKey = -1;
  820. }
  821. else
  822. {
  823. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  824. }
  825. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  826. if (empty($this->m_iKey))
  827. {
  828. // Take the autonumber
  829. $this->m_iKey = $iNewKey;
  830. }
  831. return $this->m_iKey;
  832. }
  833. // Insert of record for the new object into the database
  834. // Returns the key of the newly created object
  835. public function DBInsertNoReload()
  836. {
  837. if ($this->m_bIsInDB)
  838. {
  839. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  840. }
  841. $sClass = get_class($this);
  842. $sRootClass = MetaModel::GetRootClass($sClass);
  843. // Ensure the update of the values (we are accessing the data directly)
  844. $this->DoComputeValues();
  845. $this->OnInsert();
  846. if ($this->m_iKey < 0)
  847. {
  848. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  849. $this->m_iKey = null;
  850. }
  851. // If not automatically computed, then check that the key is given by the caller
  852. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  853. {
  854. if (empty($this->m_iKey))
  855. {
  856. throw new CoreWarning("Missing key for the object to write - This class is supposed to have a user defined key, not an autonumber", array('class' => $sRootClass));
  857. }
  858. }
  859. // Ultimate check - ensure DB integrity
  860. list($bRes, $aIssues) = $this->CheckToWrite();
  861. if (!$bRes)
  862. {
  863. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  864. }
  865. // First query built upon on the root class, because the ID must be created first
  866. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  867. // Then do the leaf class, if different from the root class
  868. if ($sClass != $sRootClass)
  869. {
  870. $this->DBInsertSingleTable($sClass);
  871. }
  872. // Then do the other classes
  873. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  874. {
  875. if ($sParentClass == $sRootClass) continue;
  876. $this->DBInsertSingleTable($sParentClass);
  877. }
  878. $this->DBWriteLinks();
  879. $this->m_bIsInDB = true;
  880. $this->m_bDirty = false;
  881. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  882. $this->m_aAsArgs = null;
  883. $this->AfterInsert();
  884. // Activate any existing trigger
  885. $sClass = get_class($this);
  886. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  887. while ($oTrigger = $oSet->Fetch())
  888. {
  889. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  890. {
  891. $oTrigger->DoActivate($this->ToArgs('this'));
  892. }
  893. }
  894. return $this->m_iKey;
  895. }
  896. public function DBInsert()
  897. {
  898. $this->DBInsertNoReload();
  899. $this->Reload();
  900. return $this->m_iKey;
  901. }
  902. public function DBInsertTracked(CMDBChange $oVoid)
  903. {
  904. return $this->DBInsert();
  905. }
  906. // Creates a copy of the current object into the database
  907. // Returns the id of the newly created object
  908. public function DBClone($iNewKey = null)
  909. {
  910. $this->m_bIsInDB = false;
  911. $this->m_iKey = $iNewKey;
  912. return $this->DBInsert();
  913. }
  914. /**
  915. * This function is automatically called after cloning an object with the "clone" PHP language construct
  916. * The purpose of this method is to reset the appropriate attributes of the object in
  917. * order to make sure that the newly cloned object is really distinct from its clone
  918. */
  919. public function __clone()
  920. {
  921. $this->m_bIsInDB = false;
  922. $this->m_bDirty = true;
  923. $this->m_iKey = self::GetNextTempId(get_class($this));
  924. }
  925. // Update a record
  926. public function DBUpdate()
  927. {
  928. if (!$this->m_bIsInDB)
  929. {
  930. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  931. }
  932. $this->DoComputeValues();
  933. $this->OnUpdate();
  934. $aChanges = $this->ListChanges();
  935. if (count($aChanges) == 0)
  936. {
  937. //throw new CoreWarning("Attempting to update an unchanged object");
  938. return;
  939. }
  940. // Ultimate check - ensure DB integrity
  941. list($bRes, $aIssues) = $this->CheckToWrite();
  942. if (!$bRes)
  943. {
  944. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => get_class($this), 'id' => $this->GetKey(), 'issues' => $aIssues));
  945. }
  946. $bHasANewExternalKeyValue = false;
  947. foreach($aChanges as $sAttCode => $valuecurr)
  948. {
  949. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  950. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  951. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  952. }
  953. // Update scalar attributes
  954. if (count($aChanges) != 0)
  955. {
  956. $oFilter = new DBObjectSearch(get_class($this));
  957. $oFilter->AddCondition('id', $this->m_iKey, '=');
  958. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  959. if (!MetaModel::DBIsReadOnly())
  960. {
  961. CMDBSource::Query($sSQL);
  962. }
  963. }
  964. $this->DBWriteLinks();
  965. $this->m_bDirty = false;
  966. $this->AfterUpdate();
  967. // Reload to get the external attributes
  968. if ($bHasANewExternalKeyValue)
  969. {
  970. $this->Reload();
  971. }
  972. return $this->m_iKey;
  973. }
  974. public function DBUpdateTracked(CMDBChange $oVoid)
  975. {
  976. return $this->DBUpdate();
  977. }
  978. // Make the current changes persistent - clever wrapper for Insert or Update
  979. public function DBWrite()
  980. {
  981. if ($this->m_bIsInDB)
  982. {
  983. return $this->DBUpdate();
  984. }
  985. else
  986. {
  987. return $this->DBInsert();
  988. }
  989. }
  990. // Delete a record
  991. public function DBDelete()
  992. {
  993. $oFilter = new DBObjectSearch(get_class($this));
  994. $oFilter->AddCondition('id', $this->m_iKey, '=');
  995. $this->OnDelete();
  996. $sSQL = MetaModel::MakeDeleteQuery($oFilter);
  997. if (!MetaModel::DBIsReadOnly())
  998. {
  999. CMDBSource::Query($sSQL);
  1000. }
  1001. $this->AfterDelete();
  1002. $this->m_bIsInDB = false;
  1003. $this->m_iKey = null;
  1004. }
  1005. public function DBDeleteTracked(CMDBChange $oVoid)
  1006. {
  1007. $this->DBDelete();
  1008. }
  1009. public function EnumTransitions()
  1010. {
  1011. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1012. if (empty($sStateAttCode)) return array();
  1013. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1014. return MetaModel::EnumTransitions(get_class($this), $sState);
  1015. }
  1016. public function ApplyStimulus($sStimulusCode)
  1017. {
  1018. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1019. if (empty($sStateAttCode)) return false;
  1020. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1021. $aStateTransitions = $this->EnumTransitions();
  1022. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1023. // Change the state before proceeding to the actions, this is necessary because an action might
  1024. // trigger another stimuli (alternative: push the stimuli into a queue)
  1025. $sPreviousState = $this->Get($sStateAttCode);
  1026. $sNewState = $aTransitionDef['target_state'];
  1027. $this->Set($sStateAttCode, $sNewState);
  1028. // $aTransitionDef is an
  1029. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1030. $bSuccess = true;
  1031. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1032. {
  1033. // std PHP spec
  1034. $aActionCallSpec = array($this, $sActionHandler);
  1035. if (!is_callable($aActionCallSpec))
  1036. {
  1037. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1038. return;
  1039. }
  1040. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1041. // if one call fails, the whole is considered as failed
  1042. if (!$bRet) $bSuccess = false;
  1043. }
  1044. // Change state triggers...
  1045. $sClass = get_class($this);
  1046. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1047. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1048. while ($oTrigger = $oSet->Fetch())
  1049. {
  1050. $oTrigger->DoActivate($this->ToArgs('this'));
  1051. }
  1052. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1053. while ($oTrigger = $oSet->Fetch())
  1054. {
  1055. $oTrigger->DoActivate($this->ToArgs('this'));
  1056. }
  1057. return $bSuccess;
  1058. }
  1059. // Make standard context arguments
  1060. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1061. // Several options here:
  1062. // 1) cache the result
  1063. // 2) set only the object ref and resolve the values iif needed from contextual templates and queries (easy for the queries, not for the templates)
  1064. public function ToArgs($sArgName = 'this')
  1065. {
  1066. if (is_null($this->m_aAsArgs))
  1067. {
  1068. $oKPI = new ExecutionKPI();
  1069. $aScalarArgs = array();
  1070. $aScalarArgs[$sArgName] = $this->GetKey();
  1071. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1072. $aScalarArgs[$sArgName.'->object()'] = $this;
  1073. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  1074. // #@# Prototype for a user portal - to be dehardcoded later
  1075. $sToPortal = utils::GetAbsoluteUrlPath().'../portal/index.php?operation=details&id='.$this->GetKey();
  1076. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1077. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1078. $sClass = get_class($this);
  1079. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1080. {
  1081. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1082. if ($oAttDef->IsScalar())
  1083. {
  1084. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1085. $sAsHtml = $this->GetAsHtml($sAttCode);
  1086. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1087. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1088. }
  1089. }
  1090. $this->m_aAsArgs = $aScalarArgs;
  1091. $oKPI->ComputeStats('ToArgs', get_class($this));
  1092. }
  1093. return $this->m_aAsArgs;
  1094. }
  1095. // To be optionaly overloaded
  1096. protected function OnInsert()
  1097. {
  1098. }
  1099. // To be optionaly overloaded
  1100. protected function AfterInsert()
  1101. {
  1102. }
  1103. // To be optionaly overloaded
  1104. protected function OnUpdate()
  1105. {
  1106. }
  1107. // To be optionaly overloaded
  1108. protected function AfterUpdate()
  1109. {
  1110. }
  1111. // To be optionaly overloaded
  1112. protected function OnDelete()
  1113. {
  1114. }
  1115. // To be optionaly overloaded
  1116. protected function AfterDelete()
  1117. {
  1118. }
  1119. // Return an empty set for the parent of all
  1120. public static function GetRelationQueries($sRelCode)
  1121. {
  1122. return array();
  1123. }
  1124. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1125. {
  1126. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1127. {
  1128. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1129. $sQuery = $aQueryInfo["sQuery"];
  1130. $bPropagate = $aQueryInfo["bPropagate"];
  1131. $iDistance = $aQueryInfo["iDistance"];
  1132. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1133. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1134. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1135. while ($oObj = $oObjSet->Fetch())
  1136. {
  1137. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1138. $sObjKey = $oObj->GetKey();
  1139. if (array_key_exists($sRootClass, $aResults))
  1140. {
  1141. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1142. {
  1143. continue; // already visited, skip
  1144. }
  1145. }
  1146. $aResults[$sRootClass][$sObjKey] = $oObj;
  1147. if ($iDepth > 0)
  1148. {
  1149. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1150. }
  1151. }
  1152. }
  1153. return $aResults;
  1154. }
  1155. public function GetReferencingObjects()
  1156. {
  1157. $aDependentObjects = array();
  1158. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1159. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1160. {
  1161. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1162. {
  1163. // skip if this external key is behind an external field
  1164. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1165. $oSearch = new DBObjectSearch($sRemoteClass);
  1166. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1167. $oSet = new CMDBObjectSet($oSearch);
  1168. if ($oSet->Count() > 0)
  1169. {
  1170. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1171. 'attribute' => $oExtKeyAttDef,
  1172. 'objects' => $oSet,
  1173. );
  1174. }
  1175. }
  1176. }
  1177. return $aDependentObjects;
  1178. }
  1179. /**
  1180. * $aDeletedObjs = array(); // [class][key] => structure
  1181. * $aResetedObjs = array(); // [class][key] => object
  1182. */
  1183. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1184. {
  1185. if (array_key_exists(get_class($this), $aVisited))
  1186. {
  1187. if (in_array($this->GetKey(), $aVisited[get_class($this)]))
  1188. {
  1189. return;
  1190. }
  1191. }
  1192. $aVisited[get_class($this)] = $this->GetKey();
  1193. $aDependentObjects = $this->GetReferencingObjects();
  1194. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1195. {
  1196. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1197. {
  1198. $oAttDef = $aData['attribute'];
  1199. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1200. $oDepSet = $aData['objects'];
  1201. $oDepSet->Rewind();
  1202. while ($oDependentObj = $oDepSet->fetch())
  1203. {
  1204. $iId = $oDependentObj->GetKey();
  1205. if ($oAttDef->IsNullAllowed())
  1206. {
  1207. // Optional external key, list to reset
  1208. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1209. {
  1210. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1211. }
  1212. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1213. }
  1214. else
  1215. {
  1216. // Mandatory external key, list to delete
  1217. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1218. {
  1219. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1220. if ($iCurrentOption == DEL_AUTO)
  1221. {
  1222. // be conservative, take the new option
  1223. // (DEL_MANUAL has precedence over DEL_AUTO)
  1224. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1225. }
  1226. else
  1227. {
  1228. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1229. }
  1230. }
  1231. else
  1232. {
  1233. // First time we find the given object in the list
  1234. // (and most likely case is that no other occurence will be found)
  1235. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1236. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1237. // Recursively inspect this object
  1238. if ($iDeletePropagationOption == DEL_AUTO)
  1239. {
  1240. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1241. }
  1242. }
  1243. }
  1244. }
  1245. }
  1246. }
  1247. }
  1248. /**
  1249. * Get all the synchro replica related to this object
  1250. * @param none
  1251. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  1252. */
  1253. public function GetMasterReplica()
  1254. {
  1255. if ($this->m_oMasterReplicaSet == null)
  1256. {
  1257. $aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  1258. $sClassesList = "'".implode("','", $aParentClasses)."'";
  1259. $sOQL = "SELECT replica,datasource FROM SynchroReplica AS replica JOIN SynchroDataSource AS datasource ON replica.sync_source_id=datasource.id WHERE datasource.scope_class IN ($sClassesList) AND replica.dest_id = :dest_id";
  1260. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_id' => $this->GetKey()));
  1261. $this->m_oMasterReplicaSet = $oReplicaSet;
  1262. }
  1263. else
  1264. {
  1265. $this->m_oMasterReplicaSet->Rewind();
  1266. }
  1267. return $this->m_oMasterReplicaSet;
  1268. }
  1269. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  1270. {
  1271. $iFlags = OPT_ATT_NORMAL;
  1272. $oSet = $this->GetMasterReplica();
  1273. while($aData = $oSet->FetchAssoc())
  1274. {
  1275. $oReplica = $aData['replica'];
  1276. $oSource = $aData['datasource'];
  1277. $oAttrSet = $oSource->Get('attribute_list');
  1278. while($oSyncAttr = $oAttrSet->Fetch())
  1279. {
  1280. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  1281. {
  1282. $iFlags |= OPT_ATT_READONLY;
  1283. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  1284. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  1285. }
  1286. }
  1287. }
  1288. return $iFlags;
  1289. }
  1290. }
  1291. ?>