dbobject.class.php 48 KB

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