dbobject.class.php 46 KB

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