dbobject.class.php 58 KB

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