dbobject.class.php 58 KB

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