dbobject.class.php 63 KB

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