dbobject.class.php 57 KB

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