dbobject.class.php 51 KB

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