dbobject.class.php 43 KB

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