dbobject.class.php 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497
  1. <?php
  2. // Copyright (C) 2010-2014 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Class dbObject: the root of persistent classes
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('metamodel.class.php');
  25. require_once('deletionplan.class.inc.php');
  26. require_once('mutex.class.inc.php');
  27. /**
  28. * A persistent object, as defined by the metamodel
  29. *
  30. * @package iTopORM
  31. */
  32. abstract class DBObject
  33. {
  34. private static $m_aMemoryObjectsByClass = array();
  35. private static $m_aBulkInsertItems = array(); // class => array of ('table' => array of (array of <sql_value>))
  36. private static $m_aBulkInsertCols = array(); // class => array of ('table' => array of <sql_column>)
  37. private static $m_bBulkInsert = false;
  38. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  39. private $m_iKey = null;
  40. private $m_aCurrValues = array();
  41. protected $m_aOrigValues = array();
  42. protected $m_aExtendedData = null;
  43. private $m_bDirty = false; // Means: "a modification is ongoing"
  44. // The object may have incorrect external keys, then any attempt of reload must be avoided
  45. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  46. // if null, then the check has to be performed again to know the status
  47. protected $m_bSecurityIssue = null;
  48. protected $m_aCheckIssues = null;
  49. protected $m_aDeleteIssues = null;
  50. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  51. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  52. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  53. protected $m_aModifiedAtt = array(); // list of (potentially) modified sAttCodes
  54. protected $m_oMasterReplicaSet = null; // Set of SynchroReplica related to this object
  55. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  56. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  57. {
  58. if (!empty($aRow))
  59. {
  60. $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  61. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  62. $this->m_aModifiedAtt = array();
  63. return;
  64. }
  65. // Creation of a brand new object
  66. //
  67. $this->m_iKey = self::GetNextTempId(get_class($this));
  68. // set default values
  69. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  70. {
  71. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  72. $this->m_aOrigValues[$sAttCode] = null;
  73. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  74. {
  75. // This field has to be read from the DB
  76. // Leave the flag unset (optimization)
  77. }
  78. else
  79. {
  80. // No need to trigger a reload for that attribute
  81. // Let's consider it as being already fully loaded
  82. $this->m_aLoadedAtt[$sAttCode] = true;
  83. }
  84. }
  85. }
  86. // Read-only <=> Written once (archive)
  87. public function RegisterAsDirty()
  88. {
  89. // While the object may be written to the DB, it is NOT possible to reload it
  90. // or at least not possible to reload it the same way
  91. $this->m_bDirty = true;
  92. }
  93. public function IsNew()
  94. {
  95. return (!$this->m_bIsInDB);
  96. }
  97. // Returns an Id for memory objects
  98. static protected function GetNextTempId($sClass)
  99. {
  100. $sRootClass = MetaModel::GetRootClass($sClass);
  101. if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
  102. {
  103. self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
  104. }
  105. self::$m_aMemoryObjectsByClass[$sRootClass]++;
  106. return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
  107. }
  108. public function __toString()
  109. {
  110. $sRet = '';
  111. $sClass = get_class($this);
  112. $sRootClass = MetaModel::GetRootClass($sClass);
  113. $iPKey = $this->GetKey();
  114. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  115. $sRet .= "<ul class=\"treeview\">\n";
  116. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  117. {
  118. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  119. }
  120. $sRet .= "</ul>";
  121. return $sRet;
  122. }
  123. // Restore initial values... mmmm, to be discussed
  124. public function DBRevert()
  125. {
  126. $this->Reload();
  127. }
  128. protected function IsFullyLoaded()
  129. {
  130. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  131. {
  132. if (!$oAttDef->LoadInObject()) continue;
  133. if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
  134. {
  135. return false;
  136. }
  137. }
  138. return true;
  139. }
  140. public function Reload()
  141. {
  142. assert($this->m_bIsInDB);
  143. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false/*, $this->m_bAllowAllData*/);
  144. if (empty($aRow))
  145. {
  146. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  147. }
  148. $this->FromRow($aRow);
  149. // Process linked set attributes
  150. //
  151. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  152. {
  153. if (!$oAttDef->IsLinkSet()) continue;
  154. // Load the link information
  155. $sLinkClass = $oAttDef->GetLinkedClass();
  156. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  157. // The class to target is not the current class, because if this is a derived class,
  158. // it may differ from the target class, then things start to become confusing
  159. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  160. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  161. $oMyselfSearch = new DBObjectSearch($sMyClass);
  162. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  163. $oLinkSearch = new DBObjectSearch($sLinkClass);
  164. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  165. $oLinks = new DBObjectSet($oLinkSearch);
  166. $this->m_aCurrValues[$sAttCode] = $oLinks;
  167. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  168. $this->m_aLoadedAtt[$sAttCode] = true;
  169. }
  170. $this->m_bFullyLoaded = true;
  171. $this->m_aModifiedAtt = array();
  172. }
  173. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  174. {
  175. if (strlen($sClassAlias) == 0)
  176. {
  177. // Default to the current class
  178. $sClassAlias = get_class($this);
  179. }
  180. $this->m_iKey = null;
  181. $this->m_bIsInDB = true;
  182. $this->m_aCurrValues = array();
  183. $this->m_aOrigValues = array();
  184. $this->m_aLoadedAtt = array();
  185. $this->m_bCheckStatus = true;
  186. // Get the key
  187. //
  188. $sKeyField = $sClassAlias."id";
  189. if (!array_key_exists($sKeyField, $aRow))
  190. {
  191. // #@# Bug ?
  192. throw new CoreException("Missing key for class '".get_class($this)."'");
  193. }
  194. $iPKey = $aRow[$sKeyField];
  195. if (!self::IsValidPKey($iPKey))
  196. {
  197. if (is_null($iPKey))
  198. {
  199. throw new CoreException("Missing object id in query result (found null)");
  200. }
  201. else
  202. {
  203. throw new CoreException("An object id must be an integer value ($iPKey)");
  204. }
  205. }
  206. $this->m_iKey = $iPKey;
  207. // Build the object from an array of "attCode"=>"value")
  208. //
  209. $bFullyLoaded = true; // ... set to false if any attribute is not found
  210. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  211. {
  212. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  213. }
  214. else
  215. {
  216. $aAttList = $aAttToLoad[$sClassAlias];
  217. }
  218. foreach($aAttList as $sAttCode=>$oAttDef)
  219. {
  220. // Skip links (could not be loaded by the mean of this query)
  221. if ($oAttDef->IsLinkSet()) continue;
  222. if (!$oAttDef->LoadInObject()) continue;
  223. // Note: we assume that, for a given attribute, if it can be loaded,
  224. // then one column will be found with an empty suffix, the others have a suffix
  225. // Take care: the function isset will return false in case the value is null,
  226. // which is something that could happen on open joins
  227. $sAttRef = $sClassAlias.$sAttCode;
  228. if (array_key_exists($sAttRef, $aRow))
  229. {
  230. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  231. $this->m_aCurrValues[$sAttCode] = $value;
  232. if (is_object($value))
  233. {
  234. $this->m_aOrigValues[$sAttCode] = clone $value;
  235. }
  236. else
  237. {
  238. $this->m_aOrigValues[$sAttCode] = $value;
  239. }
  240. $this->m_aLoadedAtt[$sAttCode] = true;
  241. }
  242. else
  243. {
  244. // This attribute was expected and not found in the query columns
  245. $bFullyLoaded = false;
  246. }
  247. }
  248. // Load extended data
  249. if ($aExtendedDataSpec != null)
  250. {
  251. $aExtendedDataSpec['table'];
  252. foreach($aExtendedDataSpec['fields'] as $sColumn)
  253. {
  254. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  255. if (array_key_exists($sColRef, $aRow))
  256. {
  257. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  258. }
  259. }
  260. }
  261. return $bFullyLoaded;
  262. }
  263. public function Set($sAttCode, $value)
  264. {
  265. if ($sAttCode == 'finalclass')
  266. {
  267. // Ignore it - this attribute is set upon object creation and that's it
  268. return;
  269. }
  270. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  271. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  272. {
  273. // First time Set is called... ensure that the object gets fully loaded
  274. // Otherwise we would lose the values on a further Reload
  275. // + consistency does not make sense !
  276. $this->Reload();
  277. }
  278. if ($oAttDef->IsExternalKey())
  279. {
  280. if (is_object($value))
  281. {
  282. // Setting an external key with a whole object (instead of just an ID)
  283. // let's initialize also the external fields that depend on it
  284. // (useful when building objects in memory and not from a query)
  285. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  286. {
  287. 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");
  288. }
  289. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  290. {
  291. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  292. {
  293. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  294. }
  295. }
  296. }
  297. else if ($this->m_aCurrValues[$sAttCode] != $value)
  298. {
  299. // Setting an external key, but no any other information is available...
  300. // Invalidate the corresponding fields so that they get reloaded in case they are needed (See Get())
  301. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  302. {
  303. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sAttCode))
  304. {
  305. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  306. unset($this->m_aLoadedAtt[$sCode]);
  307. }
  308. }
  309. }
  310. }
  311. if(!$oAttDef->IsScalar() && !is_object($value))
  312. {
  313. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  314. }
  315. if($oAttDef->IsLinkSet())
  316. {
  317. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  318. {
  319. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  320. }
  321. $oObjectSet = $value;
  322. $sSetClass = $oObjectSet->GetClass();
  323. $sLinkClass = $oAttDef->GetLinkedClass();
  324. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  325. if ($sSetClass != $sLinkClass)
  326. {
  327. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  328. }
  329. }
  330. $realvalue = $oAttDef->MakeRealValue($value, $this);
  331. $this->m_aCurrValues[$sAttCode] = $realvalue;
  332. $this->m_aModifiedAtt[$sAttCode] = true;
  333. // The object has changed, reset caches
  334. $this->m_bCheckStatus = null;
  335. $this->m_aAsArgs = null;
  336. // Make sure we do not reload it anymore... before saving it
  337. $this->RegisterAsDirty();
  338. }
  339. public function GetLabel($sAttCode)
  340. {
  341. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  342. return $oAttDef->GetLabel();
  343. }
  344. public function Get($sAttCode)
  345. {
  346. if (($iPos = strpos($sAttCode, '->')) === false)
  347. {
  348. return $this->GetStrict($sAttCode);
  349. }
  350. else
  351. {
  352. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  353. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  354. if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
  355. {
  356. throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
  357. }
  358. $oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode);
  359. if (!is_null($oExtFieldAtt))
  360. {
  361. return $this->GetStrict($oExtFieldAtt->GetCode());
  362. }
  363. else
  364. {
  365. $oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  366. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  367. $oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
  368. if (is_null($oRemoteObj))
  369. {
  370. return '';
  371. }
  372. else
  373. {
  374. return $oRemoteObj->Get($sRemoteAttCode);
  375. }
  376. }
  377. }
  378. }
  379. public function GetStrict($sAttCode)
  380. {
  381. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  382. if (!$oAttDef->LoadInObject())
  383. {
  384. $sParentAttCode = $oAttDef->GetParentAttCode();
  385. $parentValue = $this->GetStrict($sParentAttCode);
  386. $value = $oAttDef->GetValue($parentValue, $this);
  387. }
  388. else
  389. {
  390. if (isset($this->m_aLoadedAtt[$sAttCode]))
  391. {
  392. // Standard case... we have the information directly
  393. }
  394. elseif ($this->m_bIsInDB && !$this->m_bDirty)
  395. {
  396. // Lazy load (polymorphism): complete by reloading the entire object
  397. // #@# non-scalar attributes.... handle that differently?
  398. $oKPI = new ExecutionKPI();
  399. $this->Reload();
  400. $oKPI->ComputeStats('Reload', get_class($this).'/'.$sAttCode);
  401. }
  402. elseif ($sAttCode == 'friendlyname')
  403. {
  404. // The friendly name is not computed and the object is dirty
  405. // Todo: implement the computation of the friendly name based on sprintf()
  406. //
  407. $this->m_aCurrValues[$sAttCode] = '';
  408. }
  409. else
  410. {
  411. // Not loaded... is it related to an external key?
  412. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  413. {
  414. // Let's get the object and compute all of the corresponding attributes
  415. // (i.e not only the requested attribute)
  416. //
  417. $sExtKeyAttCode = $oAttDef->GetKeyAttCode();
  418. if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
  419. {
  420. $oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
  421. // Note: "allow all data" must be enabled because the external fields are always visible
  422. // to the current user even if this is not the case for the remote object
  423. // This is consistent with the behavior of the lists
  424. $oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
  425. }
  426. else
  427. {
  428. $oRemote = null;
  429. }
  430. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  431. {
  432. if (($oDef->IsExternalField() || ($oDef instanceof AttributeFriendlyName)) && ($oDef->GetKeyAttCode() == $sExtKeyAttCode))
  433. {
  434. if ($oRemote)
  435. {
  436. $this->m_aCurrValues[$sCode] = $oRemote->Get($oDef->GetExtAttCode());
  437. }
  438. else
  439. {
  440. $this->m_aCurrValues[$sCode] = $oDef->GetDefaultValue();
  441. }
  442. $this->m_aLoadedAtt[$sCode] = true;
  443. }
  444. }
  445. }
  446. }
  447. $value = $this->m_aCurrValues[$sAttCode];
  448. }
  449. if ($value instanceof DBObjectSet)
  450. {
  451. $value->Rewind();
  452. }
  453. return $value;
  454. }
  455. public function GetOriginal($sAttCode)
  456. {
  457. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  458. {
  459. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  460. }
  461. return $this->m_aOrigValues[$sAttCode];
  462. }
  463. /**
  464. * Returns data loaded by the mean of a dynamic and explicit JOIN
  465. */
  466. public function GetExtendedData()
  467. {
  468. return $this->m_aExtendedData;
  469. }
  470. /**
  471. * Updates the value of an external field by (re)loading the object
  472. * corresponding to the external key and getting the value from it
  473. *
  474. * UNUSED ?
  475. *
  476. * @param string $sAttCode Attribute code of the external field to update
  477. * @return void
  478. */
  479. protected function UpdateExternalField($sAttCode)
  480. {
  481. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  482. if ($oAttDef->IsExternalField())
  483. {
  484. $sTargetClass = $oAttDef->GetTargetClass();
  485. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  486. // Note: "allow all data" must be enabled because the external fields are always visible
  487. // to the current user even if this is not the case for the remote object
  488. // This is consistent with the behavior of the lists
  489. $oObj = MetaModel::GetObject($sTargetClass, $objkey, true, true);
  490. if (is_object($oObj))
  491. {
  492. $value = $oObj->Get($oAttDef->GetExtAttCode());
  493. $this->Set($sAttCode, $value);
  494. }
  495. }
  496. }
  497. public function ComputeValues()
  498. {
  499. }
  500. // Compute scalar attributes that depend on any other type of attribute
  501. final public function DoComputeValues()
  502. {
  503. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  504. // First check that we are not currently computing the fields
  505. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  506. foreach (debug_backtrace() as $aCallInfo)
  507. {
  508. if (!array_key_exists("class", $aCallInfo)) continue;
  509. if ($aCallInfo["class"] != get_class($this)) continue;
  510. if ($aCallInfo["function"] != "ComputeValues") continue;
  511. return; //skip!
  512. }
  513. $this->ComputeValues();
  514. }
  515. public function GetAsHTML($sAttCode, $bLocalize = true)
  516. {
  517. $sClass = get_class($this);
  518. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  519. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  520. {
  521. //return $this->Get($sAttCode.'_friendlyname');
  522. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  523. $iTargetKey = $this->Get($sAttCode);
  524. if ($iTargetKey < 0)
  525. {
  526. // the key points to an object that exists only in memory... no hyperlink points to it yet
  527. return '';
  528. }
  529. else
  530. {
  531. $sLabel = $this->Get($sAttCode.'_friendlyname');
  532. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  533. }
  534. }
  535. // That's a standard attribute (might be an ext field or a direct field, etc.)
  536. return $oAtt->GetAsHTML($this->Get($sAttCode), $this, $bLocalize);
  537. }
  538. public function GetEditValue($sAttCode)
  539. {
  540. $sClass = get_class($this);
  541. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  542. if ($oAtt->IsExternalKey())
  543. {
  544. $sTargetClass = $oAtt->GetTargetClass();
  545. if ($this->IsNew())
  546. {
  547. // The current object exists only in memory, don't try to query it in the DB !
  548. // instead let's query for the object pointed by the external key, and get its name
  549. $targetObjId = $this->Get($sAttCode);
  550. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  551. if (is_object($oTargetObj))
  552. {
  553. $sEditValue = $oTargetObj->GetName();
  554. }
  555. else
  556. {
  557. $sEditValue = 0;
  558. }
  559. }
  560. else
  561. {
  562. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  563. }
  564. }
  565. else
  566. {
  567. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode), $this);
  568. }
  569. return $sEditValue;
  570. }
  571. public function GetAsXML($sAttCode, $bLocalize = true)
  572. {
  573. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  574. return $oAtt->GetAsXML($this->Get($sAttCode), $this, $bLocalize);
  575. }
  576. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  577. {
  578. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  579. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  580. }
  581. public function GetOriginalAsHTML($sAttCode, $bLocalize = true)
  582. {
  583. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  584. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this, $bLocalize);
  585. }
  586. public function GetOriginalAsXML($sAttCode, $bLocalize = true)
  587. {
  588. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  589. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this, $bLocalize);
  590. }
  591. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"', $bLocalize = true)
  592. {
  593. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  594. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this, $bLocalize);
  595. }
  596. public static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '', $sUrlMakerClass = null, $bWithNavigationContext = true)
  597. {
  598. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  599. // Safety net
  600. //
  601. if (empty($sLabel))
  602. {
  603. // If the object if not issued from a query but constructed programmatically
  604. // the label may be empty. In this case run a query to get the object's friendly name
  605. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey, false);
  606. if (is_object($oTmpObj))
  607. {
  608. $sLabel = $oTmpObj->GetName();
  609. }
  610. else
  611. {
  612. // May happen in case the target object is not in the list of allowed values for this attribute
  613. $sLabel = "<em>$sObjClass::$sObjKey</em>";
  614. }
  615. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  616. }
  617. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  618. $sUrl = ApplicationContext::MakeObjectUrl($sObjClass, $sObjKey, $sUrlMakerClass, $bWithNavigationContext);
  619. if (strlen($sUrl) > 0)
  620. {
  621. return "<a href=\"$sUrl\" title=\"$sHint\">$sLabel</a>";
  622. }
  623. else
  624. {
  625. return $sLabel;
  626. }
  627. }
  628. public function GetHyperlink($sUrlMakerClass = null, $bWithNavigationContext = true)
  629. {
  630. return self::MakeHyperLink(get_class($this), $this->GetKey(), $this->GetName(), $sUrlMakerClass, $bWithNavigationContext);
  631. }
  632. public static function ComputeStandardUIPage($sClass)
  633. {
  634. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  635. if (!isset($aUIPagesCache[$sClass]))
  636. {
  637. $UIPage = false;
  638. if (is_callable("$sClass::GetUIPage"))
  639. {
  640. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  641. }
  642. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  643. }
  644. $sPage = $aUIPagesCache[$sClass];
  645. return $sPage;
  646. }
  647. public static function GetUIPage()
  648. {
  649. return 'UI.php';
  650. }
  651. // could be in the metamodel ?
  652. public static function IsValidPKey($value)
  653. {
  654. return ((string)$value === (string)(int)$value);
  655. }
  656. public function GetKey()
  657. {
  658. return $this->m_iKey;
  659. }
  660. public function SetKey($iNewKey)
  661. {
  662. if (!self::IsValidPKey($iNewKey))
  663. {
  664. throw new CoreException("An object id must be an integer value ($iNewKey)");
  665. }
  666. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  667. {
  668. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  669. }
  670. $this->m_iKey = $iNewKey;
  671. }
  672. /**
  673. * Get the icon representing this object
  674. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  675. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  676. */
  677. public function GetIcon($bImgTag = true)
  678. {
  679. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  680. }
  681. /**
  682. * Gets the name of an object in a safe manner for displaying inside a web page
  683. * @return string
  684. */
  685. public function GetName()
  686. {
  687. return htmlentities($this->GetRawName(), ENT_QUOTES, 'UTF-8');
  688. }
  689. /**
  690. * Gets the raw name of an object, this is not safe for displaying inside a web page
  691. * since the " < > characters are not escaped and the name may contain some XSS script
  692. * instructions.
  693. * Use this function only for internal computations or for an output to a non-HTML destination
  694. * @return string
  695. */
  696. public function GetRawName()
  697. {
  698. return $this->Get('friendlyname');
  699. }
  700. public function GetState()
  701. {
  702. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  703. if (empty($sStateAttCode))
  704. {
  705. return '';
  706. }
  707. else
  708. {
  709. return $this->Get($sStateAttCode);
  710. }
  711. }
  712. public function GetStateLabel()
  713. {
  714. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  715. if (empty($sStateAttCode))
  716. {
  717. return '';
  718. }
  719. else
  720. {
  721. $sStateValue = $this->Get($sStateAttCode);
  722. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  723. }
  724. }
  725. public function GetStateDescription()
  726. {
  727. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  728. if (empty($sStateAttCode))
  729. {
  730. return '';
  731. }
  732. else
  733. {
  734. $sStateValue = $this->Get($sStateAttCode);
  735. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  736. }
  737. }
  738. /**
  739. * Overridable - Define attributes read-only from the end-user perspective
  740. *
  741. * @return array List of attcodes
  742. */
  743. public static function GetReadOnlyAttributes()
  744. {
  745. return null;
  746. }
  747. /**
  748. * Overridable - Get predefined objects (could be hardcoded)
  749. * The predefined objects will be synchronized with the DB at each install/upgrade
  750. * As soon as a class has predefined objects, then nobody can create nor delete objects
  751. * @return array An array of id => array of attcode => php value(so-called "real value": integer, string, ormDocument, DBObjectSet, etc.)
  752. */
  753. public static function GetPredefinedObjects()
  754. {
  755. return null;
  756. }
  757. /**
  758. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  759. * for the given attribute in the current state of the object
  760. * @param $sAttCode string $sAttCode The code of the attribute
  761. * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
  762. * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
  763. * @return integer Flags: the binary combination of the flags applicable to this attribute
  764. */
  765. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  766. {
  767. $iFlags = 0; // By default (if no life cycle) no flag at all
  768. $aReadOnlyAtts = $this->GetReadOnlyAttributes();
  769. if ($aReadOnlyAtts != null)
  770. {
  771. if (in_array($sAttCode, $aReadOnlyAtts))
  772. {
  773. return OPT_ATT_READONLY;
  774. }
  775. }
  776. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  777. if (!empty($sStateAttCode))
  778. {
  779. if ($sTargetState != '')
  780. {
  781. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $sTargetState, $sAttCode);
  782. }
  783. else
  784. {
  785. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  786. }
  787. }
  788. $aReasons = array();
  789. $iSynchroFlags = 0;
  790. if ($this->InSyncScope())
  791. {
  792. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  793. }
  794. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  795. }
  796. /**
  797. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  798. * for the given attribute for the current state of the object considered as an INITIAL state
  799. * @param string $sAttCode The code of the attribute
  800. * @return integer Flags: the binary combination of the flags applicable to this attribute
  801. */
  802. public function GetInitialStateAttributeFlags($sAttCode, &$aReasons = array())
  803. {
  804. $iFlags = 0;
  805. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  806. if (!empty($sStateAttCode))
  807. {
  808. $iFlags = MetaModel::GetInitialStateAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  809. }
  810. return $iFlags; // No need to care about the synchro flags since we'll be creating a new object anyway
  811. }
  812. // check if the given (or current) value is suitable for the attribute
  813. // return true if successfull
  814. // return the error desciption otherwise
  815. public function CheckValue($sAttCode, $value = null)
  816. {
  817. if (!is_null($value))
  818. {
  819. $toCheck = $value;
  820. }
  821. else
  822. {
  823. $toCheck = $this->Get($sAttCode);
  824. }
  825. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  826. if (!$oAtt->IsWritable())
  827. {
  828. return true;
  829. }
  830. elseif ($oAtt->IsNull($toCheck))
  831. {
  832. if ($oAtt->IsNullAllowed())
  833. {
  834. return true;
  835. }
  836. else
  837. {
  838. return "Null not allowed";
  839. }
  840. }
  841. elseif ($oAtt->IsExternalKey())
  842. {
  843. if (!MetaModel::SkipCheckExtKeys())
  844. {
  845. $sTargetClass = $oAtt->GetTargetClass();
  846. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  847. if (is_null($oTargetObj))
  848. {
  849. return "Target object not found ($sTargetClass::$toCheck)";
  850. }
  851. }
  852. if ($oAtt->IsHierarchicalKey())
  853. {
  854. // This check cannot be deactivated since otherwise the user may break things by a CSV import of a bulk modify
  855. if ($toCheck == $this->GetKey())
  856. {
  857. return "An object can not be its own parent in a hierarchy (".$oAtt->Getlabel()." = $toCheck)";
  858. }
  859. }
  860. }
  861. elseif ($oAtt->IsScalar())
  862. {
  863. $aValues = $oAtt->GetAllowedValues($this->ToArgsForQuery());
  864. if (count($aValues) > 0)
  865. {
  866. if (!array_key_exists($toCheck, $aValues))
  867. {
  868. return "Value not allowed [$toCheck]";
  869. }
  870. }
  871. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  872. {
  873. $iLen = strlen($toCheck);
  874. if ($iLen > $iMaxSize)
  875. {
  876. return "String too long (found $iLen, limited to $iMaxSize)";
  877. }
  878. }
  879. if (!$oAtt->CheckFormat($toCheck))
  880. {
  881. return "Wrong format [$toCheck]";
  882. }
  883. }
  884. return true;
  885. }
  886. // check attributes together
  887. public function CheckConsistency()
  888. {
  889. return true;
  890. }
  891. // check integrity rules (before inserting or updating the object)
  892. // a displayable error is returned
  893. public function DoCheckToWrite()
  894. {
  895. $this->DoComputeValues();
  896. $aChanges = $this->ListChanges();
  897. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  898. {
  899. $res = $this->CheckValue($sAttCode);
  900. if ($res !== true)
  901. {
  902. // $res contains the error description
  903. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  904. }
  905. }
  906. if (count($this->m_aCheckIssues) > 0)
  907. {
  908. // No need to check consistency between attributes if any of them has
  909. // an unexpected value
  910. return;
  911. }
  912. $res = $this->CheckConsistency();
  913. if ($res !== true)
  914. {
  915. // $res contains the error description
  916. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  917. }
  918. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  919. //
  920. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  921. {
  922. foreach($aChanges as $sAttCode => $value)
  923. {
  924. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  925. if ($iFlags & OPT_ATT_SLAVE)
  926. {
  927. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  928. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  929. $sAttLabel = $oAttDef->GetLabel();
  930. foreach($aReasons as $aReasonInfo)
  931. {
  932. // Todo: associate the attribute code with the error
  933. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  934. }
  935. }
  936. }
  937. }
  938. }
  939. final public function CheckToWrite()
  940. {
  941. if (MetaModel::SkipCheckToWrite())
  942. {
  943. return array(true, array());
  944. }
  945. if (is_null($this->m_bCheckStatus))
  946. {
  947. $this->m_aCheckIssues = array();
  948. $oKPI = new ExecutionKPI();
  949. $this->DoCheckToWrite();
  950. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  951. if (count($this->m_aCheckIssues) == 0)
  952. {
  953. $this->m_bCheckStatus = true;
  954. }
  955. else
  956. {
  957. $this->m_bCheckStatus = false;
  958. }
  959. }
  960. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  961. }
  962. // check if it is allowed to delete the existing object from the database
  963. // a displayable error is returned
  964. protected function DoCheckToDelete(&$oDeletionPlan)
  965. {
  966. $this->m_aDeleteIssues = array(); // Ok
  967. if ($this->InSyncScope())
  968. {
  969. $oReplicaSet = $this->GetMasterReplica();
  970. if ($oReplicaSet->Count() > 0)
  971. {
  972. while($aData = $oReplicaSet->FetchAssoc())
  973. {
  974. $oDataSource = $aData['datasource'];
  975. $oReplica = $aData['replica'];
  976. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  977. if ($oDataSource->GetKey() == SynchroExecution::GetCurrentTaskId())
  978. {
  979. // The current task has the right to delete the object
  980. continue;
  981. }
  982. if ($oReplica->Get('status_dest_creator') != 1)
  983. {
  984. // The object is not owned by the task
  985. continue;
  986. }
  987. $sLink = $oDataSource->GetName();
  988. $sUserDeletePolicy = $oDataSource->Get('user_delete_policy');
  989. switch($sUserDeletePolicy)
  990. {
  991. case 'nobody':
  992. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  993. break;
  994. case 'administrators':
  995. if (!UserRights::IsAdministrator())
  996. {
  997. $this->m_aDeleteIssues[] = Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sLink);
  998. }
  999. break;
  1000. case 'everybody':
  1001. default:
  1002. // Ok
  1003. break;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. }
  1009. final public function CheckToDelete(&$oDeletionPlan)
  1010. {
  1011. $this->MakeDeletionPlan($oDeletionPlan);
  1012. $oDeletionPlan->ComputeResults();
  1013. return (!$oDeletionPlan->FoundStopper());
  1014. }
  1015. protected function ListChangedValues(array $aProposal)
  1016. {
  1017. $aDelta = array();
  1018. foreach ($aProposal as $sAtt => $proposedValue)
  1019. {
  1020. if (!array_key_exists($sAtt, $this->m_aOrigValues))
  1021. {
  1022. // The value was not set
  1023. $aDelta[$sAtt] = $proposedValue;
  1024. }
  1025. elseif(!array_key_exists($sAtt, $this->m_aModifiedAtt))
  1026. {
  1027. // This attCode was never set, canno tbe modified
  1028. continue;
  1029. }
  1030. elseif(is_object($proposedValue))
  1031. {
  1032. $oLinkAttDef = MetaModel::GetAttributeDef(get_class($this), $sAtt);
  1033. // The value is an object, the comparison is not strict
  1034. if (!$oLinkAttDef->Equals($proposedValue, $this->m_aOrigValues[$sAtt]))
  1035. {
  1036. $aDelta[$sAtt] = $proposedValue;
  1037. }
  1038. }
  1039. else
  1040. {
  1041. // The value is a scalar, the comparison must be 100% strict
  1042. if($this->m_aOrigValues[$sAtt] !== $proposedValue)
  1043. {
  1044. //echo "$sAtt:<pre>\n";
  1045. //var_dump($this->m_aOrigValues[$sAtt]);
  1046. //var_dump($proposedValue);
  1047. //echo "</pre>\n";
  1048. $aDelta[$sAtt] = $proposedValue;
  1049. }
  1050. }
  1051. }
  1052. return $aDelta;
  1053. }
  1054. // List the attributes that have been changed
  1055. // Returns an array of attname => currentvalue
  1056. public function ListChanges()
  1057. {
  1058. if ($this->m_bIsInDB)
  1059. {
  1060. return $this->ListChangedValues($this->m_aCurrValues);
  1061. }
  1062. else
  1063. {
  1064. return $this->m_aCurrValues;
  1065. }
  1066. }
  1067. // Tells whether or not an object was modified since last read (ie: does it differ from the DB ?)
  1068. public function IsModified()
  1069. {
  1070. $aChanges = $this->ListChanges();
  1071. return (count($aChanges) != 0);
  1072. }
  1073. public function Equals($oSibling)
  1074. {
  1075. if (get_class($oSibling) != get_class($this))
  1076. {
  1077. return false;
  1078. }
  1079. if ($this->GetKey() != $oSibling->GetKey())
  1080. {
  1081. return false;
  1082. }
  1083. if ($this->m_bIsInDB)
  1084. {
  1085. // If one has changed, then consider them as being different
  1086. if ($this->IsModified() || $oSibling->IsModified())
  1087. {
  1088. return false;
  1089. }
  1090. }
  1091. else
  1092. {
  1093. // Todo - implement this case (loop on every attribute)
  1094. //foreach(MetaModel::ListAttributeDefs(get_class($this) as $sAttCode => $oAttDef)
  1095. //{
  1096. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1097. //if (!isset($this->m_CurrentValues[$sAttCode])) continue;
  1098. //if (!$oAttDef->Equals($this->m_CurrentValues[$sAttCode], $oSibling->m_CurrentValues[$sAttCode]))
  1099. //{
  1100. //return false;
  1101. //}
  1102. //}
  1103. return false;
  1104. }
  1105. return true;
  1106. }
  1107. // used both by insert/update
  1108. private function DBWriteLinks()
  1109. {
  1110. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  1111. {
  1112. if (!$oAttDef->IsLinkSet()) continue;
  1113. $oOriginalSet = $this->m_aOrigValues[$sAttCode];
  1114. if ($oOriginalSet != null)
  1115. {
  1116. $aOriginalList = $oOriginalSet->ToArray();
  1117. }
  1118. else
  1119. {
  1120. $aOriginalList = array();
  1121. }
  1122. $oLinks = $this->Get($sAttCode);
  1123. $oLinks->Rewind();
  1124. while ($oLinkedObject = $oLinks->Fetch())
  1125. {
  1126. if (!array_key_exists($oLinkedObject->GetKey(), $aOriginalList))
  1127. {
  1128. // New object added to the set, make it point properly
  1129. $oLinkedObject->Set($oAttDef->GetExtKeyToMe(), $this->m_iKey);
  1130. }
  1131. if ($oLinkedObject->IsModified())
  1132. {
  1133. // Objects can be modified because:
  1134. // 1) They've just been added into the set, so their ExtKey is modified
  1135. // 2) They are about to be removed from the set BUT NOT deleted, their ExtKey has been reset
  1136. $oLinkedObject->DBWrite();
  1137. }
  1138. }
  1139. // Delete the objects that were initialy present and disappeared from the list
  1140. // (if any)
  1141. if (count($aOriginalList) > 0)
  1142. {
  1143. $aNewSet = $oLinks->ToArray();
  1144. foreach($aOriginalList as $iId => $oObject)
  1145. {
  1146. if (!array_key_exists($iId, $aNewSet))
  1147. {
  1148. // It disappeared from the list
  1149. $oObject->DBDelete();
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. // Note: this is experimental - it was designed to speed up the setup of iTop
  1156. // Known limitations:
  1157. // - does not work with multi-table classes (issue with the unique id to maintain in several tables)
  1158. // - the id of the object is not updated
  1159. static public final function BulkInsertStart()
  1160. {
  1161. self::$m_bBulkInsert = true;
  1162. }
  1163. static public final function BulkInsertFlush()
  1164. {
  1165. if (!self::$m_bBulkInsert) return;
  1166. foreach(self::$m_aBulkInsertCols as $sClass => $aTables)
  1167. {
  1168. foreach ($aTables as $sTable => $sColumns)
  1169. {
  1170. $sValues = implode(', ', self::$m_aBulkInsertItems[$sClass][$sTable]);
  1171. $sInsertSQL = "INSERT INTO `$sTable` ($sColumns) VALUES $sValues";
  1172. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1173. }
  1174. }
  1175. // Reset
  1176. self::$m_aBulkInsertItems = array();
  1177. self::$m_aBulkInsertCols = array();
  1178. self::$m_bBulkInsert = false;
  1179. }
  1180. private function DBInsertSingleTable($sTableClass)
  1181. {
  1182. $sTable = MetaModel::DBGetTable($sTableClass);
  1183. // Abstract classes or classes having no specific attribute do not have an associated table
  1184. if ($sTable == '') return;
  1185. $sClass = get_class($this);
  1186. // fields in first array, values in the second
  1187. $aFieldsToWrite = array();
  1188. $aValuesToWrite = array();
  1189. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1190. {
  1191. // Add it to the list of fields to write
  1192. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1193. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1194. }
  1195. $aHierarchicalKeys = array();
  1196. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1197. {
  1198. // Skip this attribute if not defined in this table
  1199. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1200. $aAttColumns = $oAttDef->GetSQLValues($this->m_aCurrValues[$sAttCode]);
  1201. foreach($aAttColumns as $sColumn => $sValue)
  1202. {
  1203. $aFieldsToWrite[] = "`$sColumn`";
  1204. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1205. }
  1206. if ($oAttDef->IsHierarchicalKey())
  1207. {
  1208. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1209. }
  1210. }
  1211. if (count($aValuesToWrite) == 0) return false;
  1212. if (MetaModel::DBIsReadOnly())
  1213. {
  1214. $iNewKey = -1;
  1215. }
  1216. else
  1217. {
  1218. if (self::$m_bBulkInsert)
  1219. {
  1220. if (!isset(self::$m_aBulkInsertCols[$sClass][$sTable]))
  1221. {
  1222. self::$m_aBulkInsertCols[$sClass][$sTable] = implode(', ', $aFieldsToWrite);
  1223. }
  1224. self::$m_aBulkInsertItems[$sClass][$sTable][] = '('.implode (', ', $aValuesToWrite).')';
  1225. $iNewKey = 999999; // TODO - compute next id....
  1226. }
  1227. else
  1228. {
  1229. if (count($aHierarchicalKeys) > 0)
  1230. {
  1231. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1232. {
  1233. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1234. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1235. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1236. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1237. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1238. }
  1239. }
  1240. $sInsertSQL = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).")";
  1241. $iNewKey = CMDBSource::InsertInto($sInsertSQL);
  1242. }
  1243. }
  1244. // Note that it is possible to have a key defined here, and the autoincrement expected, this is acceptable in a non root class
  1245. if (empty($this->m_iKey))
  1246. {
  1247. // Take the autonumber
  1248. $this->m_iKey = $iNewKey;
  1249. }
  1250. return $this->m_iKey;
  1251. }
  1252. // Insert of record for the new object into the database
  1253. // Returns the key of the newly created object
  1254. public function DBInsertNoReload()
  1255. {
  1256. if ($this->m_bIsInDB)
  1257. {
  1258. throw new CoreException("The object already exists into the Database, you may want to use the clone function");
  1259. }
  1260. $sClass = get_class($this);
  1261. $sRootClass = MetaModel::GetRootClass($sClass);
  1262. // Ensure the update of the values (we are accessing the data directly)
  1263. $this->DoComputeValues();
  1264. $this->OnInsert();
  1265. if ($this->m_iKey < 0)
  1266. {
  1267. // This was a temporary "memory" key: discard it so that DBInsertSingleTable will not try to use it!
  1268. $this->m_iKey = null;
  1269. }
  1270. // If not automatically computed, then check that the key is given by the caller
  1271. if (!MetaModel::IsAutoIncrementKey($sRootClass))
  1272. {
  1273. if (empty($this->m_iKey))
  1274. {
  1275. 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));
  1276. }
  1277. }
  1278. // Ultimate check - ensure DB integrity
  1279. list($bRes, $aIssues) = $this->CheckToWrite();
  1280. if (!$bRes)
  1281. {
  1282. $sIssues = implode(', ', $aIssues);
  1283. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1284. }
  1285. // Stop watches
  1286. $sState = $this->GetState();
  1287. if ($sState != '')
  1288. {
  1289. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1290. {
  1291. if ($oAttDef instanceof AttributeStopWatch)
  1292. {
  1293. if (in_array($sState, $oAttDef->GetStates()))
  1294. {
  1295. // Start the stop watch and compute the deadlines
  1296. $oSW = $this->Get($sAttCode);
  1297. $oSW->Start($this, $oAttDef);
  1298. $oSW->ComputeDeadlines($this, $oAttDef);
  1299. $this->Set($sAttCode, $oSW);
  1300. }
  1301. }
  1302. }
  1303. }
  1304. // First query built upon on the root class, because the ID must be created first
  1305. $this->m_iKey = $this->DBInsertSingleTable($sRootClass);
  1306. // Then do the leaf class, if different from the root class
  1307. if ($sClass != $sRootClass)
  1308. {
  1309. $this->DBInsertSingleTable($sClass);
  1310. }
  1311. // Then do the other classes
  1312. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1313. {
  1314. if ($sParentClass == $sRootClass) continue;
  1315. $this->DBInsertSingleTable($sParentClass);
  1316. }
  1317. $this->DBWriteLinks();
  1318. $this->m_bIsInDB = true;
  1319. $this->m_bDirty = false;
  1320. // Arg cache invalidated (in particular, it needs the object key -could be improved later)
  1321. $this->m_aAsArgs = null;
  1322. $this->AfterInsert();
  1323. // Activate any existing trigger
  1324. $sClass = get_class($this);
  1325. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1326. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObjectCreate AS t WHERE t.target_class IN ('$sClassList')"));
  1327. while ($oTrigger = $oSet->Fetch())
  1328. {
  1329. $oTrigger->DoActivate($this->ToArgs('this'));
  1330. }
  1331. $this->RecordObjCreation();
  1332. return $this->m_iKey;
  1333. }
  1334. protected function MakeInsertStatementSingleTable($aAuthorizedExtKeys, &$aStatements, $sTableClass)
  1335. {
  1336. $sTable = MetaModel::DBGetTable($sTableClass);
  1337. // Abstract classes or classes having no specific attribute do not have an associated table
  1338. if ($sTable == '') return;
  1339. $sClass = get_class($this);
  1340. // fields in first array, values in the second
  1341. $aFieldsToWrite = array();
  1342. $aValuesToWrite = array();
  1343. if (!empty($this->m_iKey) && ($this->m_iKey >= 0))
  1344. {
  1345. // Add it to the list of fields to write
  1346. $aFieldsToWrite[] = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1347. $aValuesToWrite[] = CMDBSource::Quote($this->m_iKey);
  1348. }
  1349. $aHierarchicalKeys = array();
  1350. foreach(MetaModel::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1351. {
  1352. // Skip this attribute if not defined in this table
  1353. if (!MetaModel::IsAttributeOrigin($sTableClass, $sAttCode)) continue;
  1354. // Skip link set that can still be undefined though the object is 100% loaded
  1355. if ($oAttDef->IsLinkSet()) continue;
  1356. $value = $this->m_aCurrValues[$sAttCode];
  1357. if ($oAttDef->IsExternalKey())
  1358. {
  1359. $sTargetClass = $oAttDef->GetTargetClass();
  1360. if (is_array($aAuthorizedExtKeys))
  1361. {
  1362. if (!array_key_exists($sTargetClass, $aAuthorizedExtKeys) || !array_key_exists($value, $aAuthorizedExtKeys[$sTargetClass]))
  1363. {
  1364. $value = 0;
  1365. }
  1366. }
  1367. }
  1368. $aAttColumns = $oAttDef->GetSQLValues($value);
  1369. foreach($aAttColumns as $sColumn => $sValue)
  1370. {
  1371. $aFieldsToWrite[] = "`$sColumn`";
  1372. $aValuesToWrite[] = CMDBSource::Quote($sValue);
  1373. }
  1374. if ($oAttDef->IsHierarchicalKey())
  1375. {
  1376. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1377. }
  1378. }
  1379. if (count($aValuesToWrite) == 0) return false;
  1380. if (count($aHierarchicalKeys) > 0)
  1381. {
  1382. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1383. {
  1384. $aValues = MetaModel::HKInsertChildUnder($this->m_aCurrValues[$sAttCode], $oAttDef, $sTable);
  1385. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLRight().'`';
  1386. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLRight()];
  1387. $aFieldsToWrite[] = '`'.$oAttDef->GetSQLLeft().'`';
  1388. $aValuesToWrite[] = $aValues[$oAttDef->GetSQLLeft()];
  1389. }
  1390. }
  1391. $aStatements[] = "INSERT INTO `$sTable` (".join(",", $aFieldsToWrite).") VALUES (".join(", ", $aValuesToWrite).");";
  1392. }
  1393. public function MakeInsertStatements($aAuthorizedExtKeys, &$aStatements)
  1394. {
  1395. $sClass = get_class($this);
  1396. $sRootClass = MetaModel::GetRootClass($sClass);
  1397. // First query built upon on the root class, because the ID must be created first
  1398. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sRootClass);
  1399. // Then do the leaf class, if different from the root class
  1400. if ($sClass != $sRootClass)
  1401. {
  1402. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sClass);
  1403. }
  1404. // Then do the other classes
  1405. foreach(MetaModel::EnumParentClasses($sClass) as $sParentClass)
  1406. {
  1407. if ($sParentClass == $sRootClass) continue;
  1408. $this->MakeInsertStatementSingleTable($aAuthorizedExtKeys, $aStatements, $sParentClass);
  1409. }
  1410. }
  1411. public function DBInsert()
  1412. {
  1413. $this->DBInsertNoReload();
  1414. $this->Reload();
  1415. return $this->m_iKey;
  1416. }
  1417. public function DBInsertTracked(CMDBChange $oChange)
  1418. {
  1419. CMDBObject::SetCurrentChange($oChange);
  1420. return $this->DBInsert();
  1421. }
  1422. public function DBInsertTrackedNoReload(CMDBChange $oChange)
  1423. {
  1424. CMDBObject::SetCurrentChange($oChange);
  1425. return $this->DBInsertNoReload();
  1426. }
  1427. // Creates a copy of the current object into the database
  1428. // Returns the id of the newly created object
  1429. public function DBClone($iNewKey = null)
  1430. {
  1431. $this->m_bIsInDB = false;
  1432. $this->m_iKey = $iNewKey;
  1433. $ret = $this->DBInsert();
  1434. $this->RecordObjCreation();
  1435. return $ret;
  1436. }
  1437. /**
  1438. * This function is automatically called after cloning an object with the "clone" PHP language construct
  1439. * The purpose of this method is to reset the appropriate attributes of the object in
  1440. * order to make sure that the newly cloned object is really distinct from its clone
  1441. */
  1442. public function __clone()
  1443. {
  1444. $this->m_bIsInDB = false;
  1445. $this->m_bDirty = true;
  1446. $this->m_iKey = self::GetNextTempId(get_class($this));
  1447. }
  1448. // Update a record
  1449. public function DBUpdate()
  1450. {
  1451. if (!$this->m_bIsInDB)
  1452. {
  1453. throw new CoreException("DBUpdate: could not update a newly created object, please call DBInsert instead");
  1454. }
  1455. // Stop watches
  1456. $sState = $this->GetState();
  1457. if ($sState != '')
  1458. {
  1459. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1460. {
  1461. if ($oAttDef instanceof AttributeStopWatch)
  1462. {
  1463. if (in_array($sState, $oAttDef->GetStates()))
  1464. {
  1465. // Compute or recompute the deadlines
  1466. $oSW = $this->Get($sAttCode);
  1467. $oSW->ComputeDeadlines($this, $oAttDef);
  1468. $this->Set($sAttCode, $oSW);
  1469. }
  1470. }
  1471. }
  1472. }
  1473. $this->DoComputeValues();
  1474. $this->OnUpdate();
  1475. $aChanges = $this->ListChanges();
  1476. if (count($aChanges) == 0)
  1477. {
  1478. // Attempting to update an unchanged object
  1479. return;
  1480. }
  1481. // Ultimate check - ensure DB integrity
  1482. list($bRes, $aIssues) = $this->CheckToWrite();
  1483. if (!$bRes)
  1484. {
  1485. $sIssues = implode(', ', $aIssues);
  1486. throw new CoreException("Object not following integrity rules", array('issues' => $sIssues, 'class' => get_class($this), 'id' => $this->GetKey()));
  1487. }
  1488. // Save the original values (will be reset to the new values when the object get written to the DB)
  1489. $aOriginalValues = $this->m_aOrigValues;
  1490. $bHasANewExternalKeyValue = false;
  1491. $aHierarchicalKeys = array();
  1492. foreach($aChanges as $sAttCode => $valuecurr)
  1493. {
  1494. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1495. if ($oAttDef->IsExternalKey()) $bHasANewExternalKeyValue = true;
  1496. if (!$oAttDef->IsDirectField()) unset($aChanges[$sAttCode]);
  1497. if ($oAttDef->IsHierarchicalKey())
  1498. {
  1499. $aHierarchicalKeys[$sAttCode] = $oAttDef;
  1500. }
  1501. }
  1502. if (!MetaModel::DBIsReadOnly())
  1503. {
  1504. // Update the left & right indexes for each hierarchical key
  1505. foreach($aHierarchicalKeys as $sAttCode => $oAttDef)
  1506. {
  1507. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1508. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".$this->GetKey();
  1509. $aRes = CMDBSource::QueryToArray($sSQL);
  1510. $iMyLeft = $aRes[0]['left'];
  1511. $iMyRight = $aRes[0]['right'];
  1512. $iDelta =$iMyRight - $iMyLeft + 1;
  1513. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1514. if ($aChanges[$sAttCode] == 0)
  1515. {
  1516. // No new parent, insert completely at the right of the tree
  1517. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1518. $aRes = CMDBSource::QueryToArray($sSQL);
  1519. if (count($aRes) == 0)
  1520. {
  1521. $iNewLeft = 1;
  1522. }
  1523. else
  1524. {
  1525. $iNewLeft = $aRes[0]['max']+1;
  1526. }
  1527. }
  1528. else
  1529. {
  1530. // Insert at the right of the specified parent
  1531. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".((int)$aChanges[$sAttCode]);
  1532. $iNewLeft = CMDBSource::QueryToScalar($sSQL);
  1533. }
  1534. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1535. $aHKChanges = array();
  1536. $aHKChanges[$sAttCode] = $aChanges[$sAttCode];
  1537. $aHKChanges[$oAttDef->GetSQLLeft()] = $iNewLeft;
  1538. $aHKChanges[$oAttDef->GetSQLRight()] = $iNewLeft + $iDelta - 1;
  1539. $aChanges[$sAttCode] = $aHKChanges; // the 3 values will be stored by MakeUpdateQuery below
  1540. }
  1541. // Update scalar attributes
  1542. if (count($aChanges) != 0)
  1543. {
  1544. $oFilter = new DBObjectSearch(get_class($this));
  1545. $oFilter->AddCondition('id', $this->m_iKey, '=');
  1546. $sSQL = MetaModel::MakeUpdateQuery($oFilter, $aChanges);
  1547. CMDBSource::Query($sSQL);
  1548. }
  1549. }
  1550. $this->DBWriteLinks();
  1551. $this->m_bDirty = false;
  1552. $this->AfterUpdate();
  1553. // Reload to get the external attributes
  1554. if ($bHasANewExternalKeyValue)
  1555. {
  1556. $this->Reload();
  1557. }
  1558. else
  1559. {
  1560. // Reset original values although the object has not been reloaded
  1561. foreach ($this->m_aLoadedAtt as $sAttCode => $bLoaded)
  1562. {
  1563. if ($bLoaded)
  1564. {
  1565. $value = $this->m_aCurrValues[$sAttCode];
  1566. $this->m_aOrigValues[$sAttCode] = is_object($value) ? clone $value : $value;
  1567. }
  1568. }
  1569. }
  1570. if (count($aChanges) != 0)
  1571. {
  1572. $this->RecordAttChanges($aChanges, $aOriginalValues);
  1573. }
  1574. return $this->m_iKey;
  1575. }
  1576. public function DBUpdateTracked(CMDBChange $oChange)
  1577. {
  1578. CMDBObject::SetCurrentChange($oChange);
  1579. return $this->DBUpdate();
  1580. }
  1581. // Make the current changes persistent - clever wrapper for Insert or Update
  1582. public function DBWrite()
  1583. {
  1584. if ($this->m_bIsInDB)
  1585. {
  1586. return $this->DBUpdate();
  1587. }
  1588. else
  1589. {
  1590. return $this->DBInsert();
  1591. }
  1592. }
  1593. private function DBDeleteSingleTable($sTableClass)
  1594. {
  1595. $sTable = MetaModel::DBGetTable($sTableClass);
  1596. // Abstract classes or classes having no specific attribute do not have an associated table
  1597. if ($sTable == '') return;
  1598. $sPKField = '`'.MetaModel::DBGetKey($sTableClass).'`';
  1599. $sKey = CMDBSource::Quote($this->m_iKey);
  1600. $sDeleteSQL = "DELETE FROM `$sTable` WHERE $sPKField = $sKey";
  1601. CMDBSource::DeleteFrom($sDeleteSQL);
  1602. }
  1603. protected function DBDeleteSingleObject()
  1604. {
  1605. if (!MetaModel::DBIsReadOnly())
  1606. {
  1607. $this->OnDelete();
  1608. $this->RecordObjDeletion($this->m_iKey); // May cause a reload for storing history information
  1609. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  1610. {
  1611. if ($oAttDef->IsHierarchicalKey())
  1612. {
  1613. // Update the left & right indexes for each hierarchical key
  1614. $sTable = $sTable = MetaModel::DBGetTable(get_class($this), $sAttCode);
  1615. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` AS `right`, `".$oAttDef->GetSQLLeft()."` AS `left` FROM `$sTable` WHERE id=".CMDBSource::Quote($this->m_iKey);
  1616. $aRes = CMDBSource::QueryToArray($sSQL);
  1617. $iMyLeft = $aRes[0]['left'];
  1618. $iMyRight = $aRes[0]['right'];
  1619. $iDelta =$iMyRight - $iMyLeft + 1;
  1620. MetaModel::HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable);
  1621. // No new parent for now, insert completely at the right of the tree
  1622. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  1623. $aRes = CMDBSource::QueryToArray($sSQL);
  1624. if (count($aRes) == 0)
  1625. {
  1626. $iNewLeft = 1;
  1627. }
  1628. else
  1629. {
  1630. $iNewLeft = $aRes[0]['max']+1;
  1631. }
  1632. MetaModel::HKReplugBranch($iNewLeft, $iNewLeft + $iDelta - 1, $oAttDef, $sTable);
  1633. }
  1634. }
  1635. foreach(MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL) as $sParentClass)
  1636. {
  1637. $this->DBDeleteSingleTable($sParentClass);
  1638. }
  1639. $this->AfterDelete();
  1640. $this->m_bIsInDB = false;
  1641. $this->m_iKey = null;
  1642. }
  1643. }
  1644. // Delete an object... and guarantee data integrity
  1645. //
  1646. public function DBDelete(&$oDeletionPlan = null)
  1647. {
  1648. static $iLoopTimeLimit = null;
  1649. if ($iLoopTimeLimit == null)
  1650. {
  1651. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  1652. }
  1653. if (is_null($oDeletionPlan))
  1654. {
  1655. $oDeletionPlan = new DeletionPlan();
  1656. }
  1657. $this->MakeDeletionPlan($oDeletionPlan);
  1658. $oDeletionPlan->ComputeResults();
  1659. if ($oDeletionPlan->FoundStopper())
  1660. {
  1661. $aIssues = $oDeletionPlan->GetIssues();
  1662. throw new DeleteException('Found issue(s)', array('target_class' => get_class($this), 'target_id' => $this->GetKey(), 'issues' => implode(', ', $aIssues)));
  1663. }
  1664. else
  1665. {
  1666. // Getting and setting time limit are not symetric:
  1667. // www.php.net/manual/fr/function.set-time-limit.php#72305
  1668. $iPreviousTimeLimit = ini_get('max_execution_time');
  1669. foreach ($oDeletionPlan->ListDeletes() as $sClass => $aToDelete)
  1670. {
  1671. foreach ($aToDelete as $iId => $aData)
  1672. {
  1673. $oToDelete = $aData['to_delete'];
  1674. // The deletion based on a deletion plan should not be done for each oject if the deletion plan is common (Trac #457)
  1675. // because for each object we would try to update all the preceding ones... that are already deleted
  1676. // A better approach would be to change the API to apply the DBDelete on the deletion plan itself... just once
  1677. // As a temporary fix: delete only the objects that are still to be deleted...
  1678. if ($oToDelete->m_bIsInDB)
  1679. {
  1680. set_time_limit($iLoopTimeLimit);
  1681. $oToDelete->DBDeleteSingleObject();
  1682. }
  1683. }
  1684. }
  1685. foreach ($oDeletionPlan->ListUpdates() as $sClass => $aToUpdate)
  1686. {
  1687. foreach ($aToUpdate as $iId => $aData)
  1688. {
  1689. $oToUpdate = $aData['to_reset'];
  1690. foreach ($aData['attributes'] as $sRemoteExtKey => $aRemoteAttDef)
  1691. {
  1692. $oToUpdate->Set($sRemoteExtKey, $aData['values'][$sRemoteExtKey]);
  1693. set_time_limit($iLoopTimeLimit);
  1694. $oToUpdate->DBUpdate();
  1695. }
  1696. }
  1697. }
  1698. set_time_limit($iPreviousTimeLimit);
  1699. }
  1700. return $oDeletionPlan;
  1701. }
  1702. public function DBDeleteTracked(CMDBChange $oChange, $bSkipStrongSecurity = null, &$oDeletionPlan = null)
  1703. {
  1704. CMDBObject::SetCurrentChange($oChange);
  1705. $this->DBDelete($oDeletionPlan);
  1706. }
  1707. public function EnumTransitions()
  1708. {
  1709. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1710. if (empty($sStateAttCode)) return array();
  1711. $sState = $this->Get(MetaModel::GetStateAttributeCode(get_class($this)));
  1712. return MetaModel::EnumTransitions(get_class($this), $sState);
  1713. }
  1714. /**
  1715. * Designed as an action to be called when a stop watch threshold times out
  1716. * or from within the framework
  1717. */
  1718. public function ApplyStimulus($sStimulusCode, $bDoNotWrite = false)
  1719. {
  1720. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  1721. if (empty($sStateAttCode)) return false;
  1722. MyHelpers::CheckKeyInArray('object lifecycle stimulus', $sStimulusCode, MetaModel::EnumStimuli(get_class($this)));
  1723. $aStateTransitions = $this->EnumTransitions();
  1724. if (!array_key_exists($sStimulusCode, $aStateTransitions))
  1725. {
  1726. // This simulus has no effect in the current state... do nothing
  1727. return;
  1728. }
  1729. $aTransitionDef = $aStateTransitions[$sStimulusCode];
  1730. // Change the state before proceeding to the actions, this is necessary because an action might
  1731. // trigger another stimuli (alternative: push the stimuli into a queue)
  1732. $sPreviousState = $this->Get($sStateAttCode);
  1733. $sNewState = $aTransitionDef['target_state'];
  1734. $this->Set($sStateAttCode, $sNewState);
  1735. // $aTransitionDef is an
  1736. // array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD
  1737. $bSuccess = true;
  1738. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1739. {
  1740. // std PHP spec
  1741. $aActionCallSpec = array($this, $sActionHandler);
  1742. if (!is_callable($aActionCallSpec))
  1743. {
  1744. throw new CoreException("Unable to call action: ".get_class($this)."::$sActionHandler");
  1745. return;
  1746. }
  1747. $bRet = call_user_func($aActionCallSpec, $sStimulusCode);
  1748. // if one call fails, the whole is considered as failed
  1749. if (!$bRet) $bSuccess = false;
  1750. }
  1751. if ($bSuccess)
  1752. {
  1753. $sClass = get_class($this);
  1754. // Stop watches
  1755. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1756. {
  1757. if ($oAttDef instanceof AttributeStopWatch)
  1758. {
  1759. $oSW = $this->Get($sAttCode);
  1760. if (in_array($sNewState, $oAttDef->GetStates()))
  1761. {
  1762. $oSW->Start($this, $oAttDef);
  1763. }
  1764. else
  1765. {
  1766. $oSW->Stop($this, $oAttDef);
  1767. }
  1768. $this->Set($sAttCode, $oSW);
  1769. }
  1770. }
  1771. if (!$bDoNotWrite)
  1772. {
  1773. $this->DBWrite();
  1774. }
  1775. // Change state triggers...
  1776. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  1777. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateLeave AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sPreviousState'"));
  1778. while ($oTrigger = $oSet->Fetch())
  1779. {
  1780. $oTrigger->DoActivate($this->ToArgs('this'));
  1781. }
  1782. $oSet = new DBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnStateEnter AS t WHERE t.target_class IN ('$sClassList') AND t.state='$sNewState'"));
  1783. while ($oTrigger = $oSet->Fetch())
  1784. {
  1785. $oTrigger->DoActivate($this->ToArgs('this'));
  1786. }
  1787. }
  1788. return $bSuccess;
  1789. }
  1790. /**
  1791. * Designed as an action to be called when a stop watch threshold times out
  1792. */
  1793. public function ResetStopWatch($sAttCode)
  1794. {
  1795. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  1796. if (!$oAttDef instanceof AttributeStopWatch)
  1797. {
  1798. throw new CoreException("Invalid stop watch id: '$sAttCode'");
  1799. }
  1800. $oSW = $this->Get($sAttCode);
  1801. $oSW->Reset($this, $oAttDef);
  1802. $this->Set($sAttCode, $oSW);
  1803. }
  1804. /*
  1805. * Create query parameters (SELECT ... WHERE service = :this->service_id)
  1806. * to be used with the APIs DBObjectSearch/DBObjectSet
  1807. *
  1808. * Starting 2.0.2 the parameters are computed on demand, at the lowest level,
  1809. * in VariableExpression::Render()
  1810. */
  1811. public function ToArgsForQuery($sArgName = 'this')
  1812. {
  1813. return array($sArgName.'->object()' => $this);
  1814. }
  1815. /*
  1816. * Create template placeholders
  1817. * An improvement could be to compute the values on demand
  1818. * (i.e. interpret the template to determine the placeholders)
  1819. */
  1820. public function ToArgs($sArgName = 'this')
  1821. {
  1822. if (is_null($this->m_aAsArgs))
  1823. {
  1824. $oKPI = new ExecutionKPI();
  1825. $aScalarArgs = $this->ToArgsForQuery($sArgName);
  1826. $aScalarArgs[$sArgName] = $this->GetKey();
  1827. $aScalarArgs[$sArgName.'->id'] = $this->GetKey();
  1828. $aScalarArgs[$sArgName.'->hyperlink()'] = $this->GetHyperlink('iTopStandardURLMaker', false);
  1829. $aScalarArgs[$sArgName.'->hyperlink(portal)'] = $this->GetHyperlink('PortalURLMaker', false);
  1830. $aScalarArgs[$sArgName.'->name()'] = $this->GetName();
  1831. $sClass = get_class($this);
  1832. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1833. {
  1834. if ($oAttDef instanceof AttributeCaseLog)
  1835. {
  1836. $oCaseLog = $this->Get($sAttCode);
  1837. $aScalarArgs[$sArgName.'->'.$sAttCode] = $oCaseLog->GetText();
  1838. $aScalarArgs[$sArgName.'->head('.$sAttCode.')'] = $oCaseLog->GetLatestEntry();
  1839. }
  1840. elseif ($oAttDef->IsScalar())
  1841. {
  1842. $aScalarArgs[$sArgName.'->'.$sAttCode] = $this->Get($sAttCode);
  1843. // #@# Note: This has been proven to be quite slow, this can slow down bulk load
  1844. $sAsHtml = $this->GetAsHtml($sAttCode);
  1845. $aScalarArgs[$sArgName.'->html('.$sAttCode.')'] = $sAsHtml;
  1846. $aScalarArgs[$sArgName.'->label('.$sAttCode.')'] = $this->GetEditValue($sAttCode); // "Nice" display value, but without HTML tags and entities
  1847. }
  1848. elseif ($oAttDef->IsLinkSet())
  1849. {
  1850. $sRemoteName = $oAttDef->IsIndirect() ? $oAttDef->GetExtKeyToRemote().'_friendlyname' : 'friendlyname';
  1851. $oLinkSet = clone $this->Get($sAttCode); // Workaround/Safety net for Trac #887
  1852. $iLimit = MetaModel::GetConfig()->Get('max_linkset_output');
  1853. if ($iLimit > 0)
  1854. {
  1855. $oLinkSet->SetLimit($iLimit);
  1856. }
  1857. $aNames = $oLinkSet->GetColumnAsArray($sRemoteName);
  1858. if ($iLimit > 0)
  1859. {
  1860. $iTotal = $oLinkSet->Count();
  1861. if ($iTotal > count($aNames))
  1862. {
  1863. $aNames[] = '... '.Dict::Format('UI:TruncatedResults', count($aNames), $iTotal);
  1864. }
  1865. }
  1866. $sNames = implode("\n", $aNames);
  1867. $aScalarArgs[$sArgName.'->'.$sAttCode] = $sNames;
  1868. }
  1869. }
  1870. $this->m_aAsArgs = $aScalarArgs;
  1871. $oKPI->ComputeStats('ToArgs', get_class($this));
  1872. }
  1873. return $this->m_aAsArgs;
  1874. }
  1875. // To be optionaly overloaded
  1876. protected function OnInsert()
  1877. {
  1878. }
  1879. // To be optionaly overloaded
  1880. protected function AfterInsert()
  1881. {
  1882. }
  1883. // To be optionaly overloaded
  1884. protected function OnUpdate()
  1885. {
  1886. }
  1887. // To be optionaly overloaded
  1888. protected function AfterUpdate()
  1889. {
  1890. }
  1891. // To be optionaly overloaded
  1892. protected function OnDelete()
  1893. {
  1894. }
  1895. // To be optionaly overloaded
  1896. protected function AfterDelete()
  1897. {
  1898. }
  1899. /**
  1900. * Common to the recording of link set changes (add/remove/modify)
  1901. */
  1902. private function PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, $sChangeOpClass, $aOriginalValues = null)
  1903. {
  1904. if ($iLinkSetOwnerId <= 0)
  1905. {
  1906. return null;
  1907. }
  1908. if (!is_subclass_of($oLinkSet->GetHostClass(), 'CMDBObject'))
  1909. {
  1910. // The link set owner class does not keep track of its history
  1911. return null;
  1912. }
  1913. // Determine the linked item class and id
  1914. //
  1915. if ($oLinkSet->IsIndirect())
  1916. {
  1917. // The "item" is on the other end (N-N links)
  1918. $sExtKeyToRemote = $oLinkSet->GetExtKeyToRemote();
  1919. $oExtKeyToRemote = MetaModel::GetAttributeDef(get_class($this), $sExtKeyToRemote);
  1920. $sItemClass = $oExtKeyToRemote->GetTargetClass();
  1921. if ($aOriginalValues)
  1922. {
  1923. // Get the value from the original values
  1924. $iItemId = $aOriginalValues[$sExtKeyToRemote];
  1925. }
  1926. else
  1927. {
  1928. $iItemId = $this->Get($sExtKeyToRemote);
  1929. }
  1930. }
  1931. else
  1932. {
  1933. // I am the "item" (1-N links)
  1934. $sItemClass = get_class($this);
  1935. $iItemId = $this->GetKey();
  1936. }
  1937. // Get the remote object, to determine its exact class
  1938. // Possible optimization: implement a tool in MetaModel, to get the final class of an object (not always querying + query reduced to a select on the root table!
  1939. $oOwner = MetaModel::GetObject($oLinkSet->GetHostClass(), $iLinkSetOwnerId, false);
  1940. if ($oOwner)
  1941. {
  1942. $sLinkSetOwnerClass = get_class($oOwner);
  1943. $oMyChangeOp = MetaModel::NewObject($sChangeOpClass);
  1944. $oMyChangeOp->Set("objclass", $sLinkSetOwnerClass);
  1945. $oMyChangeOp->Set("objkey", $iLinkSetOwnerId);
  1946. $oMyChangeOp->Set("attcode", $oLinkSet->GetCode());
  1947. $oMyChangeOp->Set("item_class", $sItemClass);
  1948. $oMyChangeOp->Set("item_id", $iItemId);
  1949. return $oMyChangeOp;
  1950. }
  1951. else
  1952. {
  1953. // Depending on the deletion order, it may happen that the id is already invalid... ignore
  1954. return null;
  1955. }
  1956. }
  1957. /**
  1958. * This object has been created/deleted, record that as a change in link sets pointing to this (if any)
  1959. */
  1960. private function RecordLinkSetListChange($bAdd = true)
  1961. {
  1962. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1963. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1964. {
  1965. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1966. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  1967. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  1968. if ($oMyChangeOp)
  1969. {
  1970. if ($bAdd)
  1971. {
  1972. $oMyChangeOp->Set("type", "added");
  1973. }
  1974. else
  1975. {
  1976. $oMyChangeOp->Set("type", "removed");
  1977. }
  1978. $iId = $oMyChangeOp->DBInsertNoReload();
  1979. }
  1980. }
  1981. }
  1982. protected function RecordObjCreation()
  1983. {
  1984. $this->RecordLinkSetListChange(true);
  1985. }
  1986. protected function RecordObjDeletion($objkey)
  1987. {
  1988. $this->RecordLinkSetListChange(false);
  1989. }
  1990. protected function RecordAttChanges(array $aValues, array $aOrigValues)
  1991. {
  1992. $aForwardChangeTracking = MetaModel::GetTrackForwardExternalKeys(get_class($this));
  1993. foreach(MetaModel::GetTrackForwardExternalKeys(get_class($this)) as $sExtKeyAttCode => $oLinkSet)
  1994. {
  1995. if (array_key_exists($sExtKeyAttCode, $aValues))
  1996. {
  1997. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_LIST) == 0) continue;
  1998. // Keep track of link added/removed
  1999. //
  2000. $iLinkSetOwnerNext = $aValues[$sExtKeyAttCode];
  2001. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerNext, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove');
  2002. if ($oMyChangeOp)
  2003. {
  2004. $oMyChangeOp->Set("type", "added");
  2005. $oMyChangeOp->DBInsertNoReload();
  2006. }
  2007. $iLinkSetOwnerPrevious = $aOrigValues[$sExtKeyAttCode];
  2008. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerPrevious, $oLinkSet, 'CMDBChangeOpSetAttributeLinksAddRemove', $aOrigValues);
  2009. if ($oMyChangeOp)
  2010. {
  2011. $oMyChangeOp->Set("type", "removed");
  2012. $oMyChangeOp->DBInsertNoReload();
  2013. }
  2014. }
  2015. else
  2016. {
  2017. // Keep track of link changes
  2018. //
  2019. if (($oLinkSet->GetTrackingLevel() & LINKSET_TRACKING_DETAILS) == 0) continue;
  2020. $iLinkSetOwnerId = $this->Get($sExtKeyAttCode);
  2021. $oMyChangeOp = $this->PrepareChangeOpLinkSet($iLinkSetOwnerId, $oLinkSet, 'CMDBChangeOpSetAttributeLinksTune');
  2022. if ($oMyChangeOp)
  2023. {
  2024. $oMyChangeOp->Set("link_id", $this->GetKey());
  2025. $iId = $oMyChangeOp->DBInsertNoReload();
  2026. }
  2027. }
  2028. }
  2029. }
  2030. // Return an empty set for the parent of all
  2031. public static function GetRelationQueries($sRelCode)
  2032. {
  2033. return array();
  2034. }
  2035. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99, &$aResults = array())
  2036. {
  2037. foreach (MetaModel::EnumRelationQueries(get_class($this), $sRelCode) as $sDummy => $aQueryInfo)
  2038. {
  2039. MetaModel::DbgTrace("object=".$this->GetKey().", depth=$iMaxDepth, rel=".$aQueryInfo["sQuery"]);
  2040. $sQuery = $aQueryInfo["sQuery"];
  2041. $bPropagate = $aQueryInfo["bPropagate"];
  2042. $iDistance = $aQueryInfo["iDistance"];
  2043. $iDepth = $bPropagate ? $iMaxDepth - 1 : 0;
  2044. $oFlt = DBObjectSearch::FromOQL($sQuery);
  2045. $oObjSet = new DBObjectSet($oFlt, array(), $this->ToArgsForQuery());
  2046. while ($oObj = $oObjSet->Fetch())
  2047. {
  2048. $sRootClass = MetaModel::GetRootClass(get_class($oObj));
  2049. $sObjKey = $oObj->GetKey();
  2050. if (array_key_exists($sRootClass, $aResults))
  2051. {
  2052. if (array_key_exists($sObjKey, $aResults[$sRootClass]))
  2053. {
  2054. continue; // already visited, skip
  2055. }
  2056. }
  2057. $aResults[$sRootClass][$sObjKey] = $oObj;
  2058. if ($iDepth > 0)
  2059. {
  2060. $oObj->GetRelatedObjects($sRelCode, $iDepth, $aResults);
  2061. }
  2062. }
  2063. }
  2064. return $aResults;
  2065. }
  2066. public function GetReferencingObjects($bAllowAllData = false)
  2067. {
  2068. $aDependentObjects = array();
  2069. $aRererencingMe = MetaModel::EnumReferencingClasses(get_class($this));
  2070. foreach($aRererencingMe as $sRemoteClass => $aExtKeys)
  2071. {
  2072. foreach($aExtKeys as $sExtKeyAttCode => $oExtKeyAttDef)
  2073. {
  2074. // skip if this external key is behind an external field
  2075. if (!$oExtKeyAttDef->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  2076. $oSearch = new DBObjectSearch($sRemoteClass);
  2077. $oSearch->AddCondition($sExtKeyAttCode, $this->GetKey(), '=');
  2078. if ($bAllowAllData)
  2079. {
  2080. $oSearch->AllowAllData();
  2081. }
  2082. $oSet = new CMDBObjectSet($oSearch);
  2083. if ($oSet->Count() > 0)
  2084. {
  2085. $aDependentObjects[$sRemoteClass][$sExtKeyAttCode] = array(
  2086. 'attribute' => $oExtKeyAttDef,
  2087. 'objects' => $oSet,
  2088. );
  2089. }
  2090. }
  2091. }
  2092. return $aDependentObjects;
  2093. }
  2094. private function MakeDeletionPlan(&$oDeletionPlan, $aVisited = array(), $iDeleteOption = null)
  2095. {
  2096. static $iLoopTimeLimit = null;
  2097. if ($iLoopTimeLimit == null)
  2098. {
  2099. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2100. }
  2101. $sClass = get_class($this);
  2102. $iThisId = $this->GetKey();
  2103. $iDeleteOption = $oDeletionPlan->AddToDelete($this, $iDeleteOption);
  2104. if (array_key_exists($sClass, $aVisited))
  2105. {
  2106. if (in_array($iThisId, $aVisited[$sClass]))
  2107. {
  2108. return;
  2109. }
  2110. }
  2111. $aVisited[$sClass] = $iThisId;
  2112. if ($iDeleteOption == DEL_MANUAL)
  2113. {
  2114. // Stop the recursion here
  2115. return;
  2116. }
  2117. // Check the node itself
  2118. $this->DoCheckToDelete($oDeletionPlan);
  2119. $oDeletionPlan->SetDeletionIssues($this, $this->m_aDeleteIssues, $this->m_bSecurityIssue);
  2120. $aDependentObjects = $this->GetReferencingObjects(true /* allow all data */);
  2121. // Getting and setting time limit are not symetric:
  2122. // www.php.net/manual/fr/function.set-time-limit.php#72305
  2123. $iPreviousTimeLimit = ini_get('max_execution_time');
  2124. foreach ($aDependentObjects as $sRemoteClass => $aPotentialDeletes)
  2125. {
  2126. foreach ($aPotentialDeletes as $sRemoteExtKey => $aData)
  2127. {
  2128. set_time_limit($iLoopTimeLimit);
  2129. $oAttDef = $aData['attribute'];
  2130. $iDeletePropagationOption = $oAttDef->GetDeletionPropagationOption();
  2131. $oDepSet = $aData['objects'];
  2132. $oDepSet->Rewind();
  2133. while ($oDependentObj = $oDepSet->fetch())
  2134. {
  2135. $iId = $oDependentObj->GetKey();
  2136. if ($oAttDef->IsNullAllowed())
  2137. {
  2138. // Optional external key, list to reset
  2139. if (($iDeletePropagationOption == DEL_MOVEUP) && ($oAttDef->IsHierarchicalKey()))
  2140. {
  2141. // Move the child up one level i.e. set the same parent as the current object
  2142. $iParentId = $this->Get($oAttDef->GetCode());
  2143. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef, $iParentId);
  2144. }
  2145. else
  2146. {
  2147. $oDeletionPlan->AddToUpdate($oDependentObj, $oAttDef);
  2148. }
  2149. }
  2150. else
  2151. {
  2152. // Mandatory external key, list to delete
  2153. $oDependentObj->MakeDeletionPlan($oDeletionPlan, $aVisited, $iDeletePropagationOption);
  2154. }
  2155. }
  2156. }
  2157. }
  2158. set_time_limit($iPreviousTimeLimit);
  2159. }
  2160. /**
  2161. * Get all the synchro replica related to this object
  2162. * @param none
  2163. * @return DBObjectSet Set with two columns: R=SynchroReplica S=SynchroDataSource
  2164. */
  2165. public function GetMasterReplica()
  2166. {
  2167. if ($this->m_oMasterReplicaSet == null)
  2168. {
  2169. //$aParentClasses = MetaModel::EnumParentClasses(get_class($this), ENUM_PARENT_CLASSES_ALL);
  2170. //$sClassesList = "'".implode("','", $aParentClasses)."'";
  2171. $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";
  2172. $oReplicaSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array('dest_class' => get_class($this), 'dest_id' => $this->GetKey()));
  2173. $this->m_oMasterReplicaSet = $oReplicaSet;
  2174. }
  2175. else
  2176. {
  2177. $this->m_oMasterReplicaSet->Rewind();
  2178. }
  2179. return $this->m_oMasterReplicaSet;
  2180. }
  2181. public function GetSynchroReplicaFlags($sAttCode, &$aReason)
  2182. {
  2183. $iFlags = OPT_ATT_NORMAL;
  2184. $oSet = $this->GetMasterReplica();
  2185. while($aData = $oSet->FetchAssoc())
  2186. {
  2187. if ($aData['datasource']->GetKey() == SynchroExecution::GetCurrentTaskId())
  2188. {
  2189. // Ignore the current task (check to write => ok)
  2190. continue;
  2191. }
  2192. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  2193. $oReplica = $aData['replica'];
  2194. $oSource = $aData['datasource'];
  2195. $oAttrSet = $oSource->Get('attribute_list');
  2196. while($oSyncAttr = $oAttrSet->Fetch())
  2197. {
  2198. if (($oSyncAttr->Get('attcode') == $sAttCode) && ($oSyncAttr->Get('update') == 1) && ($oSyncAttr->Get('update_policy') == 'master_locked'))
  2199. {
  2200. $iFlags |= OPT_ATT_SLAVE;
  2201. $sUrl = $oSource->GetApplicationUrl($this, $oReplica);
  2202. $aReason[] = array('name' => $oSource->GetName(), 'description' => $oSource->Get('description'), 'url_application' => $sUrl);
  2203. }
  2204. }
  2205. }
  2206. return $iFlags;
  2207. }
  2208. public function InSyncScope()
  2209. {
  2210. //
  2211. // Optimization: cache the list of Data Sources and classes candidates for synchro
  2212. //
  2213. static $aSynchroClasses = null;
  2214. if (is_null($aSynchroClasses))
  2215. {
  2216. $aSynchroClasses = array();
  2217. $sOQL = "SELECT SynchroDataSource AS datasource";
  2218. $oSourceSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array() /* order by*/, array());
  2219. while($oSource = $oSourceSet->Fetch())
  2220. {
  2221. $sTarget = $oSource->Get('scope_class');
  2222. $aSynchroClasses[] = $sTarget;
  2223. }
  2224. }
  2225. foreach($aSynchroClasses as $sClass)
  2226. {
  2227. if ($this instanceof $sClass)
  2228. {
  2229. return true;
  2230. }
  2231. }
  2232. return false;
  2233. }
  2234. }