dbobject.class.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  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. // If the object if not issued from a query but constructed programmatically
  465. // the label may be empty. In this case run a query to get the object's friendly name
  466. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey);
  467. $sLabel = $oTmpObj->GetName();
  468. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  469. }
  470. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  471. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  472. }
  473. public function GetHyperlink()
  474. {
  475. if ($this->IsNew()) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  476. $oAppContext = new ApplicationContext();
  477. $sPage = $this->GetUIPage();
  478. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  479. $sObjClass = get_class($this);
  480. $sObjKey = $this->GetKey();
  481. $sLabel = $this->GetName();
  482. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  483. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  484. }
  485. public static function ComputeUIPage($sClass)
  486. {
  487. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  488. if (!isset($aUIPagesCache[$sClass]))
  489. {
  490. $UIPage = false;
  491. if (is_callable("$sClass::GetUIPage"))
  492. {
  493. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  494. }
  495. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  496. }
  497. $sPage = $aUIPagesCache[$sClass];
  498. return $sPage;
  499. }
  500. public static function GetUIPage()
  501. {
  502. return 'UI.php';
  503. }
  504. // could be in the metamodel ?
  505. public static function IsValidPKey($value)
  506. {
  507. return ((string)$value === (string)(int)$value);
  508. }
  509. public function GetKey()
  510. {
  511. return $this->m_iKey;
  512. }
  513. public function SetKey($iNewKey)
  514. {
  515. if (!self::IsValidPKey($iNewKey))
  516. {
  517. throw new CoreException("An object id must be an integer value ($iNewKey)");
  518. }
  519. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  520. {
  521. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  522. }
  523. $this->m_iKey = $iNewKey;
  524. }
  525. /**
  526. * Get the icon representing this object
  527. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  528. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  529. */
  530. public function GetIcon($bImgTag = true)
  531. {
  532. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  533. }
  534. public function GetName()
  535. {
  536. $aNameSpec = MetaModel::GetNameSpec(get_class($this));
  537. $sFormat = $aNameSpec[0];
  538. $aAttributes = $aNameSpec[1];
  539. $aValues = array();
  540. foreach ($aAttributes as $sAttCode)
  541. {
  542. if (empty($sAttCode))
  543. {
  544. $aValues[] = $this->m_iKey;
  545. }
  546. else
  547. {
  548. $aValues[] = $this->Get($sAttCode);
  549. }
  550. }
  551. return vsprintf($sFormat, $aValues);
  552. }
  553. public function GetState()
  554. {
  555. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  556. if (empty($sStateAttCode))
  557. {
  558. return '';
  559. }
  560. else
  561. {
  562. return $this->Get($sStateAttCode);
  563. }
  564. }
  565. public function GetStateLabel()
  566. {
  567. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  568. if (empty($sStateAttCode))
  569. {
  570. return '';
  571. }
  572. else
  573. {
  574. $sStateValue = $this->Get($sStateAttCode);
  575. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  576. }
  577. }
  578. public function GetStateDescription()
  579. {
  580. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  581. if (empty($sStateAttCode))
  582. {
  583. return '';
  584. }
  585. else
  586. {
  587. $sStateValue = $this->Get($sStateAttCode);
  588. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  589. }
  590. }
  591. /**
  592. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  593. * for the given attribute in the current state of the object
  594. * @param string $sAttCode The code of the attribute
  595. * @return integer Flags: the binary combination of the flags applicable to this attribute
  596. */
  597. public function GetAttributeFlags($sAttCode)
  598. {
  599. $iFlags = 0; // By default (if no life cycle) no flag at all
  600. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  601. if (!empty($sStateAttCode))
  602. {
  603. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  604. }
  605. $aReasons = array();
  606. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  607. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  608. }
  609. // check if the given (or current) value is suitable for the attribute
  610. // return true if successfull
  611. // return the error desciption otherwise
  612. public function CheckValue($sAttCode, $value = null)
  613. {
  614. if (!is_null($value))
  615. {
  616. $toCheck = $value;
  617. }
  618. else
  619. {
  620. $toCheck = $this->Get($sAttCode);
  621. }
  622. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  623. if (!$oAtt->IsWritable())
  624. {
  625. return true;
  626. }
  627. elseif ($oAtt->IsNull($toCheck))
  628. {
  629. if ($oAtt->IsNullAllowed())
  630. {
  631. return true;
  632. }
  633. else
  634. {
  635. return "Null not allowed";
  636. }
  637. }
  638. elseif ($oAtt->IsExternalKey())
  639. {
  640. if (!MetaModel::SkipCheckExtKeys())
  641. {
  642. $sTargetClass = $oAtt->GetTargetClass();
  643. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  644. if (is_null($oTargetObj))
  645. {
  646. return "Target object not found ($sTargetClass::$toCheck)";
  647. }
  648. }
  649. }
  650. elseif ($oAtt->IsScalar())
  651. {
  652. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  653. if (count($aValues) > 0)
  654. {
  655. if (!array_key_exists($toCheck, $aValues))
  656. {
  657. return "Value not allowed [$toCheck]";
  658. }
  659. }
  660. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  661. {
  662. $iLen = strlen($toCheck);
  663. if ($iLen > $iMaxSize)
  664. {
  665. return "String too long (found $iLen, limited to $iMaxSize)";
  666. }
  667. }
  668. if (!$oAtt->CheckFormat($toCheck))
  669. {
  670. return "Wrong format [$toCheck]";
  671. }
  672. }
  673. return true;
  674. }
  675. // check attributes together
  676. public function CheckConsistency()
  677. {
  678. return true;
  679. }
  680. // check integrity rules (before inserting or updating the object)
  681. // a displayable error is returned
  682. public function DoCheckToWrite()
  683. {
  684. $this->DoComputeValues();
  685. $this->m_aCheckIssues = array();
  686. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  687. {
  688. $res = $this->CheckValue($sAttCode);
  689. if ($res !== true)
  690. {
  691. // $res contains the error description
  692. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  693. }
  694. }
  695. if (count($this->m_aCheckIssues) > 0)
  696. {
  697. // No need to check consistency between attributes if any of them has
  698. // an unexpected value
  699. return;
  700. }
  701. $res = $this->CheckConsistency();
  702. if ($res !== true)
  703. {
  704. // $res contains the error description
  705. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  706. }
  707. }
  708. final public function CheckToWrite()
  709. {
  710. if (MetaModel::SkipCheckToWrite())
  711. {
  712. return array(true, array());
  713. }
  714. if (is_null($this->m_bCheckStatus))
  715. {
  716. $oKPI = new ExecutionKPI();
  717. $this->DoCheckToWrite();
  718. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  719. if (count($this->m_aCheckIssues) == 0)
  720. {
  721. $this->m_bCheckStatus = true;
  722. }
  723. else
  724. {
  725. $this->m_bCheckStatus = false;
  726. }
  727. }
  728. return array($this->m_bCheckStatus, $this->m_aCheckIssues);
  729. }
  730. // check if it is allowed to delete the existing object from the database
  731. // a displayable error is returned
  732. protected function DoCheckToDelete()
  733. {
  734. $this->m_aDeleteIssues = array(); // Ok
  735. }
  736. // final public function CheckToDelete() - THE EQUIVALENT OF CheckToWrite IS NOT AVAILABLE
  737. // Todo - split the "DeleteObject()" function (UI.php) and move the generic part in cmdbAbstractObject, etc.
  738. protected function ListChangedValues(array $aProposal)
  739. {
  740. $aDelta = array();
  741. foreach ($aProposal as $sAtt => $proposedValue)
  742. {
  743. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  744. {
  745. // The value was not set
  746. $aDelta[$sAtt] = $proposedValue;
  747. }
  748. elseif(is_object($proposedValue))
  749. {
  750. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  751. // The value is an object, the comparison is not strict
  752. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  753. {
  754. $aDelta[$sAtt] = $proposedValue;
  755. }
  756. }
  757. else
  758. {
  759. // The value is a scalar, the comparison must be 100% strict
  760. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  761. {
  762. //echo "$sAtt:<pre>\n";
  763. //var_dump($this->m_aOrigValues[$sAtt]);
  764. //var_dump($proposedValue);
  765. //echo "</pre>\n";
  766. $aDelta[$sAtt] = $proposedValue;
  767. }
  768. }
  769. }
  770. return $aDelta;
  771. }
  772. // List the attributes that have been changed
  773. // Returns an array of attname => currentvalue
  774. public function ListChanges()
  775. {
  776. if ($this->m_bIsInDB)
  777. {
  778. return $this->ListChangedValues($this->m_aCurrValues);
  779. }
  780. else
  781. {
  782. return $this->m_aCurrValues;
  783. }
  784. }
  785. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  786. public function IsModified()
  787. {
  788. $aChanges = $this->ListChanges();
  789. return (count($aChanges) != 0);
  790. }
  791. public function Equals($oSibling)
  792. {
  793. if (get_class($oSibling) != get_class($this))
  794. {
  795. return false;
  796. }
  797. if ($this->GetKey() != $oSibling->GetKey())
  798. {
  799. return false;
  800. }
  801. if ($this->m_bIsInDB)
  802. {
  803. // If one has changed, then consider them as being different
  804. if ($this->IsModified() || $oSibling->IsModified())
  805. {
  806. return false;
  807. }
  808. }
  809. else
  810. {
  811. // Todo - implement this case (loop on every attribute)
  812. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  813. //{
  814. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  815. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  816. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  817. //{
  818. //return false;
  819. //}
  820. //}
  821. return false;
  822. }
  823. return true;
  824. }
  825. // used both by insert/update
  826. private function DBWriteLinks()
  827. {
  828. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  829. {
  830. if (!$oAttDef->IsLinkSet()) continue;
  831. $oLinks = $this->Get($sAttCode);
  832. $oLinks->Rewind();
  833. while ($oLinkedObject = $oLinks->Fetch())
  834. {
  835. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  836. if ($oLinkedObject->IsModified())
  837. {
  838. $oLinkedObject->DBWrite();
  839. }
  840. }
  841. // Delete the objects that were initialy present and disappeared from the list
  842. // (if any)
  843. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  844. if ($oOriginalSet != null)
  845. {
  846. $aOriginalList = $oOriginalSet->ToArray();
  847. $aNewSet = $oLinks->ToArray();
  848. foreach($aOriginalList as $iId => $oObject)
  849. {
  850. if (!array_key_exists($iId, $aNewSet))
  851. {
  852. // It disappeared from the list
  853. $oObject->DBDelete();
  854. }
  855. }
  856. }
  857. }
  858. }
  859. // Note: this is experimental - it was designed to speed up the setup of iTop
  860. // Known limitations:
  861. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  862. // - the id of the object is not updated
  863. static public final function BulkInsertStart()
  864. {
  865. self::$m_bBulkInsert = true;
  866. }
  867. static public final function BulkInsertFlush()
  868. {
  869. if (!self::$m_bBulkInsert) return;
  870. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  871. {
  872. foreach ($aTables as $sTable => $sColumns)
  873. {
  874. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  875. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  876. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  877. }
  878. }
  879. // Reset
  880. self::$m_aBulkInsertItems = array();
  881. self::$m_aBulkInsertCols = array();
  882. self::$m_bBulkInsert = false;
  883. }
  884. private function DBInsertSingleTable($sTableClass)
  885. {
  886. $sTable = MetaModel::DBGetTable($sTableClass);
  887. // Abstract classes or classes having no specific attribute do not have an associated table
  888. if ($sTable == '') return;
  889. $sClass = get_class($this);
  890. // fields in first array, values in the second
  891. $aFieldsToWrite = array();
  892. $aValuesToWrite = array();
  893. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  894. {
  895. // Add it to the list of fields to write
  896. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  897. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  898. }
  899. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  900. {
  901. // Skip this attribute if not defined in this table
  902. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  903. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  904. foreach($aAttColumns as $sColumn => $sValue)
  905. {
  906. $aFieldsToWrite[] = "`$sColumn`";
  907. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  908. }
  909. }
  910. if (count($aValuesToWrite) == 0) return false;
  911. if (MetaModel::DBIsReadOnly())
  912. {
  913. $iNewKey = -1;
  914. }
  915. else
  916. {
  917. if (self::$m_bBulkInsert)
  918. {
  919. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  920. {
  921. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  922. }
  923. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  924. $iNewKey = 999999; // TODO - compute next id....
  925. }
  926. else
  927. {
  928. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  929. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  930. }
  931. }
  932. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  933. if (empty($this->m_iKey))
  934. {
  935. // Take the autonumber
  936. $this->m_iKey = $iNewKey;
  937. }
  938. return $this->m_iKey;
  939. }
  940. // Insert of record for the new object into the database
  941. // Returns the key of the newly created object
  942. public function DBInsertNoReload()
  943. {
  944. if ($this->m_bIsInDB)
  945. {
  946. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  947. }
  948. $sClass = get_class($this);
  949. $sRootClass = MetaModel::GetRootClass($sClass);
  950. // Ensure the update of the values (we are accessing the data directly)
  951. $this->DoComputeValues();
  952. $this->OnInsert();
  953. if ($this->m_iKey < 0)
  954. {
  955. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  956. $this->m_iKey = null;
  957. }
  958. // If not automatically computed, then check that the key is given by the caller
  959. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  960. {
  961. if (empty($this->m_iKey))
  962. {
  963. 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));
  964. }
  965. }
  966. // Ultimate check - ensure DB integrity
  967. list($bRes, $aIssues) = $this->CheckToWrite();
  968. if (!$bRes)
  969. {
  970. throw new CoreException("Object not following integrity rules - it will not be written into the DB", array('class' => $sClass, 'id' => $this->GetKey(), 'issues' => $aIssues));
  971. }
  972. // First query built upon on the root class, because the ID must be created first
  973. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  974. // Then do the leaf class, if different from the root class
  975. if ($sClass != $sRootClass)
  976. {
  977. $this->DBInsertSingleTable($sClass);
  978. }
  979. // Then do the other classes
  980. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  981. {
  982. if ($sParentClass == $sRootClass) continue;
  983. $this->DBInsertSingleTable($sParentClass);
  984. }
  985. $this->DBWriteLinks();
  986. $this->m_bIsInDB = true;
  987. $this->m_bDirty = false;
  988. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  989. $this->m_aAsArgs = null;
  990. $this->AfterInsert();
  991. // Activate any existing trigger
  992. $sClass = get_class($this);
  993. $oSet = new DBObjectSet(new DBObjectSearch('TriggerOnObjectCreate'));
  994. while ($oTrigger = $oSet->Fetch())
  995. {
  996. if (MetaModel::IsParentClass($oTrigger->Get('target_class'), $sClass))
  997. {
  998. $oTrigger->DoActivate($this->ToArgs('this'));
  999. }
  1000. }
  1001. return $this->m_iKey;
  1002. }
  1003. public function DBInsert()
  1004. {
  1005. $this->DBInsertNoReload();
  1006. $this->Reload();
  1007. return $this->m_iKey;
  1008. }
  1009. public function DBInsertTracked(CMDBChange $oVoid)
  1010. {
  1011. return $this->DBInsert();
  1012. }
  1013. // Creates a copy of the current object into the database
  1014. // Returns the id of the newly created object
  1015. public function DBClone($iNewKey = null)
  1016. {
  1017. $this->m_bIsInDB = false;
  1018. $this->m_iKey = $iNewKey;
  1019. return $this->DBInsert();
  1020. }
  1021. /**
  1022. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1023. * The purpose of this method is to reset the appropriate attributes of the object in
  1024. * order to make sure that the newly cloned object is really distinct from its clone
  1025. */
  1026. public function __clone()
  1027. {
  1028. $this->m_bIsInDB = false;
  1029. $this->m_bDirty = true;
  1030. $this->m_iKey = self::GetNextTempId(get_class($this));
  1031. }
  1032. // Update a record
  1033. public function DBUpdate()
  1034. {
  1035. if (!$this->m_bIsInDB)
  1036. {
  1037. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1038. }
  1039. $this->DoComputeValues();
  1040. $this->OnUpdate();
  1041. $aChanges = $this->ListChanges();
  1042. if (count($aChanges) == 0)
  1043. {
  1044. //throw new CoreWarning("Attempting to update an unchanged object");
  1045. return;
  1046. }
  1047. // Ultimate check - ensure DB integrity
  1048. list($bRes, $aIssues) = $this->CheckToWrite();
  1049. if (!$bRes)
  1050. {
  1051. 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));
  1052. }
  1053. $bHasANewExternalKeyValue = false;
  1054. foreach($aChanges as $sAttCode => $valuecurr)
  1055. {
  1056. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1057. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1058. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1059. }
  1060. // Update scalar attributes
  1061. if (count($aChanges) != 0)
  1062. {
  1063. $oFilter = new DBObjectSearch(get_class($this));
  1064. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1065. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1066. if (!MetaModel::DBIsReadOnly())
  1067. {
  1068. CMDBSource::Query($sSQL);
  1069. }
  1070. }
  1071. $this->DBWriteLinks();
  1072. $this->m_bDirty = false;
  1073. $this->AfterUpdate();
  1074. // Reload to get the external attributes
  1075. if ($bHasANewExternalKeyValue)
  1076. {
  1077. $this->Reload();
  1078. }
  1079. return $this->m_iKey;
  1080. }
  1081. public function DBUpdateTracked(CMDBChange $oVoid)
  1082. {
  1083. return $this->DBUpdate();
  1084. }
  1085. // Make the current changes persistent - clever wrapper for Insert or Update
  1086. public function DBWrite()
  1087. {
  1088. if ($this->m_bIsInDB)
  1089. {
  1090. return $this->DBUpdate();
  1091. }
  1092. else
  1093. {
  1094. return $this->DBInsert();
  1095. }
  1096. }
  1097. private function DBDeleteSingleTable($sTableClass)
  1098. {
  1099. $sTable = MetaModel::DBGetTable($sTableClass);
  1100. // Abstract classes or classes having no specific attribute do not have an associated table
  1101. if ($sTable == '') return;
  1102. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1103. $sKey = CMDBSource::Quote($this->m_iKey);
  1104. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1105. CMDBSource::DeleteFrom($sDeleteSQL);
  1106. }
  1107. private function DBDeleteInternal()
  1108. {
  1109. $sClass = get_class($this);
  1110. foreach(MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1111. {
  1112. $this->DBDeleteSingleTable($sParentClass);
  1113. }
  1114. }
  1115. // Delete a record
  1116. public function DBDelete()
  1117. {
  1118. $this->OnDelete();
  1119. if (!MetaModel::DBIsReadOnly())
  1120. {
  1121. $this->DBDeleteInternal();
  1122. }
  1123. $this->AfterDelete();
  1124. $this->m_bIsInDB = false;
  1125. $this->m_iKey = null;
  1126. }
  1127. public function DBDeleteTracked(CMDBChange $oVoid)
  1128. {
  1129. $this->DBDelete();
  1130. }
  1131. public function EnumTransitions()
  1132. {
  1133. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1134. if (empty($sStateAttCode)) return array();
  1135. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1136. return MetaModel::EnumTransitions(get_class($this), $sState);
  1137. }
  1138. public function ApplyStimulus($sStimulusCode)
  1139. {
  1140. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1141. if (empty($sStateAttCode)) return false;
  1142. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1143. $aStateTransitions = $this->EnumTransitions();
  1144. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1145. // Change the state before proceeding to the actions, this is necessary because an action might
  1146. // trigger another stimuli (alternative: push the stimuli into a queue)
  1147. $sPreviousState = $this->Get($sStateAttCode);
  1148. $sNewState = $aTransitionDef['target_state'];
  1149. $this->Set($sStateAttCode, $sNewState);
  1150. // $aTransitionDef is an
  1151. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1152. $bSuccess = true;
  1153. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1154. {
  1155. // std PHP spec
  1156. $aActionCallSpec = array($this, $sActionHandler);
  1157. if (!is_callable($aActionCallSpec))
  1158. {
  1159. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1160. return;
  1161. }
  1162. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1163. // if one call fails, the whole is considered as failed
  1164. if (!$bRet) $bSuccess = false;
  1165. }
  1166. // Change state triggers...
  1167. $sClass = get_class($this);
  1168. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1169. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1170. while ($oTrigger = $oSet->Fetch())
  1171. {
  1172. $oTrigger->DoActivate($this->ToArgs('this'));
  1173. }
  1174. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1175. while ($oTrigger = $oSet->Fetch())
  1176. {
  1177. $oTrigger->DoActivate($this->ToArgs('this'));
  1178. }
  1179. return $bSuccess;
  1180. }
  1181. // Make standard context arguments
  1182. // Note: Needs to be reviewed because it is currently called once per attribute when an object is written (CheckToWrite / CheckValue)
  1183. // Several options here:
  1184. // 1) cache the result
  1185. // 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)
  1186. public function ToArgs($sArgName = 'this')
  1187. {
  1188. if (is_null($this->m_aAsArgs))
  1189. {
  1190. $oKPI = new ExecutionKPI();
  1191. $aScalarArgs = array();
  1192. $aScalarArgs[$sArgName] = $this->GetKey();
  1193. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1194. $aScalarArgs[$sArgName.'->object()'] = $this;
  1195. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink();
  1196. // #@# Prototype for a user portal - to be dehardcoded later
  1197. $sToPortal = utils::GetAbsoluteUrlPath().'../portal/index.php?operation=details&id='.$this->GetKey();
  1198. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = '<a href="'.$sToPortal.'">'.$this->GetName().'</a>';
  1199. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1200. $sClass = get_class($this);
  1201. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1202. {
  1203. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1204. if ($oAttDef->IsScalar())
  1205. {
  1206. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1207. $sAsHtml = $this->GetAsHtml($sAttCode);
  1208. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1209. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = strip_tags($sAsHtml);
  1210. }
  1211. }
  1212. $this->m_aAsArgs = $aScalarArgs;
  1213. $oKPI->ComputeStats('ToArgs', get_class($this));
  1214. }
  1215. return $this->m_aAsArgs;
  1216. }
  1217. // To be optionaly overloaded
  1218. protected function OnInsert()
  1219. {
  1220. }
  1221. // To be optionaly overloaded
  1222. protected function AfterInsert()
  1223. {
  1224. }
  1225. // To be optionaly overloaded
  1226. protected function OnUpdate()
  1227. {
  1228. }
  1229. // To be optionaly overloaded
  1230. protected function AfterUpdate()
  1231. {
  1232. }
  1233. // To be optionaly overloaded
  1234. protected function OnDelete()
  1235. {
  1236. }
  1237. // To be optionaly overloaded
  1238. protected function AfterDelete()
  1239. {
  1240. }
  1241. // Return an empty set for the parent of all
  1242. public static function GetRelationQueries($sRelCode)
  1243. {
  1244. return array();
  1245. }
  1246. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  1247. {
  1248. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  1249. {
  1250. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  1251. $sQuery = $aQueryInfo["sQuery"];
  1252. $bPropagate = $aQueryInfo["bPropagate"];
  1253. $iDistance = $aQueryInfo["iDistance"];
  1254. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  1255. $oFlt = DBObjectSearch::FromOQL($sQuery);
  1256. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgs());
  1257. while ($oObj = $oObjSet->Fetch())
  1258. {
  1259. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  1260. $sObjKey = $oObj->GetKey();
  1261. if (array_key_exists($sRootClass, $aResults))
  1262. {
  1263. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  1264. {
  1265. continue; // already visited, skip
  1266. }
  1267. }
  1268. $aResults[$sRootClass][$sObjKey] = $oObj;
  1269. if ($iDepth > 0)
  1270. {
  1271. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  1272. }
  1273. }
  1274. }
  1275. return $aResults;
  1276. }
  1277. public function GetReferencingObjects()
  1278. {
  1279. $aDependentObjects = array();
  1280. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  1281. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  1282. {
  1283. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  1284. {
  1285. // skip if this external key is behind an external field
  1286. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1287. $oSearch = new DBObjectSearch($sRemoteClass);
  1288. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  1289. $oSet = new CMDBObjectSet($oSearch);
  1290. if ($oSet->Count() > 0)
  1291. {
  1292. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  1293. 'attribute' => $oExtKeyAttDef,
  1294. 'objects' => $oSet,
  1295. );
  1296. }
  1297. }
  1298. }
  1299. return $aDependentObjects;
  1300. }
  1301. /**
  1302. * $aDeletedObjs = array(); // [class][key] => structure
  1303. * $aResetedObjs = array(); // [class][key] => object
  1304. */
  1305. public function GetDeletionScheme(&$aDeletedObjs, &$aResetedObjs, $aVisited = array())
  1306. {
  1307. $sClass = get_class($this);
  1308. $iThisId = $this->GetKey();
  1309. if (array_key_exists($sClass, $aVisited))
  1310. {
  1311. if (in_array($iThisId, $aVisited[$sClass]))
  1312. {
  1313. return;
  1314. }
  1315. }
  1316. $aVisited[$sClass] = $iThisId;
  1317. $aDeletedObjs[$sClass][$iThisId]['to_delete'] = $this;
  1318. $aDeletedObjs[$sClass][$iThisId]['auto_delete'] = true;
  1319. // Check the node itself
  1320. $this->DoCheckToDelete();
  1321. $aDeletedObjs[$sClass][$iThisId]['issues'] = $this->m_aDeleteIssues;
  1322. $aDependentObjects = $this->GetReferencingObjects();
  1323. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  1324. {
  1325. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  1326. {
  1327. $oAttDef = $aData['attribute'];
  1328. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  1329. $oDepSet = $aData['objects'];
  1330. $oDepSet->Rewind();
  1331. while ($oDependentObj = $oDepSet->fetch())
  1332. {
  1333. $iId = $oDependentObj->GetKey();
  1334. if ($oAttDef->IsNullAllowed())
  1335. {
  1336. // Optional external key, list to reset
  1337. if (!array_key_exists($sRemoteClass, $aResetedObjs) || !array_key_exists($iId, $aResetedObjs[$sRemoteClass]))
  1338. {
  1339. $aResetedObjs[$sRemoteClass][$iId]['to_reset'] = $oDependentObj;
  1340. }
  1341. $aResetedObjs[$sRemoteClass][$iId]['attributes'][$sRemoteExtKey] = $oAttDef;
  1342. }
  1343. else
  1344. {
  1345. // Mandatory external key, list to delete
  1346. if (array_key_exists($sRemoteClass, $aDeletedObjs) && array_key_exists($iId, $aDeletedObjs[$sRemoteClass]))
  1347. {
  1348. $iCurrentOption = $aDeletedObjs[$sRemoteClass][$iId];
  1349. if ($iCurrentOption == DEL_AUTO)
  1350. {
  1351. // be conservative, take the new option
  1352. // (DEL_MANUAL has precedence over DEL_AUTO)
  1353. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = ($iDeletePropagationOption == DEL_AUTO);
  1354. }
  1355. else
  1356. {
  1357. // DEL_MANUAL... leave it as is, it HAS to be verified anyway
  1358. }
  1359. }
  1360. else
  1361. {
  1362. // First time we find the given object in the list
  1363. // (and most likely case is that no other occurence will be found)
  1364. if ($iDeletePropagationOption == DEL_AUTO)
  1365. {
  1366. // Recursively inspect this object
  1367. $oDependentObj->GetDeletionScheme($aDeletedObjs, $aResetedObjs, $aVisited);
  1368. }
  1369. else
  1370. {
  1371. $aDeletedObjs[$sRemoteClass][$iId]['to_delete'] = $oDependentObj;
  1372. $aDeletedObjs[$sRemoteClass][$iId]['auto_delete'] = false;
  1373. }
  1374. }
  1375. }
  1376. }
  1377. }
  1378. }
  1379. }
  1380. /**
  1381. * Get all the synchro replica related to this object
  1382. * @param none
  1383. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  1384. */
  1385. public function GetMasterReplica()
  1386. {
  1387. if ($this->m_oMasterReplicaSet == null)
  1388. {
  1389. $aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  1390. $sClassesList = "'".implode("','", $aParentClasses)."'";
  1391. $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";
  1392. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_id' => $this->GetKey()));
  1393. $this->m_oMasterReplicaSet = $oReplicaSet;
  1394. }
  1395. else
  1396. {
  1397. $this->m_oMasterReplicaSet->Rewind();
  1398. }
  1399. return $this->m_oMasterReplicaSet;
  1400. }
  1401. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  1402. {
  1403. $iFlags = OPT_ATT_NORMAL;
  1404. $oSet = $this->GetMasterReplica();
  1405. while($aData = $oSet->FetchAssoc())
  1406. {
  1407. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  1408. $oReplica = $aData['replica'];
  1409. $oSource = $aData['datasource'];
  1410. $oAttrSet = $oSource->Get('attribute_list');
  1411. while($oSyncAttr = $oAttrSet->Fetch())
  1412. {
  1413. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  1414. {
  1415. $iFlags |= OPT_ATT_SLAVE;
  1416. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  1417. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  1418. }
  1419. }
  1420. }
  1421. return $iFlags;
  1422. }
  1423. }
  1424. ?>