dbobject.class.php 51 KB

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