dbobject.class.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Class dbObject: the root of persistent classes
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once('metamodel.class.php');
  25. require_once('deletionplan.class.inc.php');
  26. /**
  27. * A persistent object, as defined by the metamodel
  28. *
  29. * @package iTopORM
  30. */
  31. abstract class DBObject
  32. {
  33. private static $m_aMemoryObjectsByClass = array();
  34. private static $m_aBulkInsertItems = array(); // class => array of ('table' => array of (array of <sql_value>))
  35. private static $m_aBulkInsertCols = array(); // class => array of ('table' => array of <sql_column>)
  36. private static $m_bBulkInsert = false;
  37. private $m_bIsInDB = false; // true IIF the object is mapped to a DB record
  38. private $m_iKey = null;
  39. private $m_aCurrValues = array();
  40. protected $m_aOrigValues = array();
  41. protected $m_aExtendedData = null;
  42. private $m_bDirty = false; // Means: "a modification is ongoing"
  43. // The object may have incorrect external keys, then any attempt of reload must be avoided
  44. private $m_bCheckStatus = null; // Means: the object has been verified and is consistent with integrity rules
  45. // if null, then the check has to be performed again to know the status
  46. protected $m_bSecurityIssue = null;
  47. protected $m_aCheckIssues = null;
  48. protected $m_aDeleteIssues = null;
  49. protected $m_aAsArgs = null; // The current object as a standard argument (cache)
  50. private $m_bFullyLoaded = false; // Compound objects can be partially loaded
  51. private $m_aLoadedAtt = array(); // Compound objects can be partially loaded, array of sAttCode
  52. protected $m_oMasterReplicaSet = null; // Set of SynchroReplica related to this object
  53. // Use the MetaModel::NewObject to build an object (do we have to force it?)
  54. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  55. {
  56. if (!empty($aRow))
  57. {
  58. $this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  59. $this->m_bFullyLoaded = $this->IsFullyLoaded();
  60. return;
  61. }
  62. // Creation of a brand new object
  63. //
  64. $this->m_iKey = self::GetNextTempId(get_class($this));
  65. // set default values
  66. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  67. {
  68. $this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue();
  69. $this->m_aOrigValues[$sAttCode] = null;
  70. if ($oAttDef->IsExternalField())
  71. {
  72. // This field has to be read from the DB
  73. // Leave the flag unset (optimization)
  74. }
  75. else
  76. {
  77. // No need to trigger a reload for that attribute
  78. // Let's consider it as being already fully loaded
  79. $this->m_aLoadedAtt[$sAttCode] = true;
  80. }
  81. }
  82. }
  83. // Read-only <=> Written once (archive)
  84. public function RegisterAsDirty()
  85. {
  86. // While the object may be written to the DB, it is NOT possible to reload it
  87. // or at least not possible to reload it the same way
  88. $this->m_bDirty = true;
  89. }
  90. public function IsNew()
  91. {
  92. return (!$this->m_bIsInDB);
  93. }
  94. // Returns an Id for memory objects
  95. static protected function GetNextTempId($sClass)
  96. {
  97. $sRootClass = MetaModel::GetRootClass($sClass);
  98. if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
  99. {
  100. self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
  101. }
  102. self::$m_aMemoryObjectsByClass[$sRootClass]++;
  103. return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
  104. }
  105. public function __toString()
  106. {
  107. $sRet = '';
  108. $sClass = get_class($this);
  109. $sRootClass = MetaModel::GetRootClass($sClass);
  110. $iPKey = $this->GetKey();
  111. $sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey<br/>\n";
  112. $sRet .= "<ul class=\"treeview\">\n";
  113. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  114. {
  115. $sRet .= "<li>".$oAttDef->GetLabel()." = ".$this->GetAsHtml($sAttCode)."</li>\n";
  116. }
  117. $sRet .= "</ul>";
  118. return $sRet;
  119. }
  120. // Restore initial values... mmmm, to be discussed
  121. public function DBRevert()
  122. {
  123. $this->Reload();
  124. }
  125. protected function IsFullyLoaded()
  126. {
  127. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  128. {
  129. @$bIsLoaded = $this->m_aLoadedAtt[$sAttCode];
  130. if ($bIsLoaded !== true)
  131. {
  132. return false;
  133. }
  134. }
  135. return true;
  136. }
  137. protected function Reload()
  138. {
  139. assert($this->m_bIsInDB);
  140. $aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false/*, $this->m_bAllowAllData*/);
  141. if (empty($aRow))
  142. {
  143. throw new CoreException("Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey);
  144. }
  145. $this->FromRow($aRow);
  146. // Process linked set attributes
  147. //
  148. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  149. {
  150. if (!$oAttDef->IsLinkSet()) continue;
  151. // Load the link information
  152. $sLinkClass = $oAttDef->GetLinkedClass();
  153. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  154. // The class to target is not the current class, because if this is a derived class,
  155. // it may differ from the target class, then things start to become confusing
  156. $oRemoteExtKeyAtt = MetaModel::GetAttributeDef($sLinkClass, $sExtKeyToMe);
  157. $sMyClass = $oRemoteExtKeyAtt->GetTargetClass();
  158. $oMyselfSearch = new DBObjectSearch($sMyClass);
  159. $oMyselfSearch->AddCondition('id', $this->m_iKey, '=');
  160. $oLinkSearch = new DBObjectSearch($sLinkClass);
  161. $oLinkSearch->AddCondition_PointingTo($oMyselfSearch, $sExtKeyToMe);
  162. $oLinks = new DBObjectSet($oLinkSearch);
  163. $this->m_aCurrValues[$sAttCode] = $oLinks;
  164. $this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
  165. $this->m_aLoadedAtt[$sAttCode] = true;
  166. }
  167. $this->m_bFullyLoaded = true;
  168. }
  169. protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  170. {
  171. if (strlen($sClassAlias) == 0)
  172. {
  173. // Default to the current class
  174. $sClassAlias = get_class($this);
  175. }
  176. $this->m_iKey = null;
  177. $this->m_bIsInDB = true;
  178. $this->m_aCurrValues = array();
  179. $this->m_aOrigValues = array();
  180. $this->m_aLoadedAtt = array();
  181. $this->m_bCheckStatus = true;
  182. // Get the key
  183. //
  184. $sKeyField = $sClassAlias."id";
  185. if (!array_key_exists($sKeyField, $aRow))
  186. {
  187. // #@# Bug ?
  188. throw new CoreException("Missing key for class '".get_class($this)."'");
  189. }
  190. $iPKey = $aRow[$sKeyField];
  191. if (!self::IsValidPKey($iPKey))
  192. {
  193. if (is_null($iPKey))
  194. {
  195. throw new CoreException("Missing object id in query result (found null)");
  196. }
  197. else
  198. {
  199. throw new CoreException("An object id must be an integer value ($iPKey)");
  200. }
  201. }
  202. $this->m_iKey = $iPKey;
  203. // Build the object from an array of "attCode"=>"value")
  204. //
  205. $bFullyLoaded = true; // ... set to false if any attribute is not found
  206. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  207. {
  208. $aAttList = MetaModel::ListAttributeDefs(get_class($this));
  209. }
  210. else
  211. {
  212. $aAttList = $aAttToLoad[$sClassAlias];
  213. }
  214. foreach($aAttList as $sAttCode=>$oAttDef)
  215. {
  216. // Skip links (could not be loaded by the mean of this query)
  217. if ($oAttDef->IsLinkSet()) continue;
  218. // Note: we assume that, for a given attribute, if it can be loaded,
  219. // then one column will be found with an empty suffix, the others have a suffix
  220. // Take care: the function isset will return false in case the value is null,
  221. // which is something that could happen on open joins
  222. $sAttRef = $sClassAlias.$sAttCode;
  223. if (array_key_exists($sAttRef, $aRow))
  224. {
  225. $value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
  226. $this->m_aCurrValues[$sAttCode] = $value;
  227. $this->m_aOrigValues[$sAttCode] = $value;
  228. $this->m_aLoadedAtt[$sAttCode] = true;
  229. }
  230. else
  231. {
  232. // This attribute was expected and not found in the query columns
  233. $bFullyLoaded = false;
  234. }
  235. }
  236. // Load extended data
  237. if ($aExtendedDataSpec != null)
  238. {
  239. $aExtendedDataSpec['table'];
  240. foreach($aExtendedDataSpec['fields'] as $sColumn)
  241. {
  242. $sColRef = $sClassAlias.'_extdata_'.$sColumn;
  243. if (array_key_exists($sColRef, $aRow))
  244. {
  245. $this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
  246. }
  247. }
  248. }
  249. return $bFullyLoaded;
  250. }
  251. public function Set($sAttCode, $value)
  252. {
  253. if ($sAttCode == 'finalclass')
  254. {
  255. // Ignore it - this attribute is set upon object creation and that's it
  256. return;
  257. }
  258. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  259. if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty)
  260. {
  261. // First time Set is called... ensure that the object gets fully loaded
  262. // Otherwise we would lose the values on a further Reload
  263. // + consistency does not make sense !
  264. $this->Reload();
  265. }
  266. if ($oAttDef->IsExternalKey() && is_object($value))
  267. {
  268. // Setting an external key with a whole object (instead of just an ID)
  269. // let's initialize also the external fields that depend on it
  270. // (useful when building objects in memory and not from a query)
  271. if ( (get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass())))
  272. {
  273. throw new CoreUnexpectedValue("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
  274. }
  275. else
  276. {
  277. // The object has changed, reset caches
  278. $this->m_bCheckStatus = null;
  279. $this->m_aAsArgs = null;
  280. $this->m_aCurrValues[$sAttCode] = $value->GetKey();
  281. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef)
  282. {
  283. if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode))
  284. {
  285. $this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
  286. }
  287. }
  288. }
  289. return;
  290. }
  291. if(!$oAttDef->IsScalar() && !is_object($value))
  292. {
  293. throw new CoreUnexpectedValue("scalar not allowed for attribute '$sAttCode', setting default value (empty list)");
  294. }
  295. if($oAttDef->IsLinkSet())
  296. {
  297. if((get_class($value) != 'DBObjectSet') && !is_subclass_of($value, 'DBObjectSet'))
  298. {
  299. throw new CoreUnexpectedValue("expecting a set of persistent objects (found a '".get_class($value)."'), setting default value (empty list)");
  300. }
  301. $oObjectSet = $value;
  302. $sSetClass = $oObjectSet->GetClass();
  303. $sLinkClass = $oAttDef->GetLinkedClass();
  304. // not working fine :-( if (!is_subclass_of($sSetClass, $sLinkClass))
  305. if ($sSetClass != $sLinkClass)
  306. {
  307. throw new CoreUnexpectedValue("expecting a set of '$sLinkClass' objects (found a set of '$sSetClass'), setting default value (empty list)");
  308. }
  309. }
  310. $realvalue = $oAttDef->MakeRealValue($value, $this);
  311. $this->m_aCurrValues[$sAttCode] = $realvalue;
  312. // The object has changed, reset caches
  313. $this->m_bCheckStatus = null;
  314. $this->m_aAsArgs = null;
  315. // Make sure we do not reload it anymore... before saving it
  316. $this->RegisterAsDirty();
  317. }
  318. public function GetLabel($sAttCode)
  319. {
  320. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  321. return $oAttDef->GetLabel();
  322. }
  323. public function Get($sAttCode)
  324. {
  325. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  326. {
  327. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  328. }
  329. if ($this->m_bIsInDB && !isset($this->m_aLoadedAtt[$sAttCode]) && !$this->m_bDirty)
  330. {
  331. // #@# non-scalar attributes.... handle that differently
  332. $this->Reload();
  333. }
  334. $value = $this->m_aCurrValues[$sAttCode];
  335. if ($value instanceof DBObjectSet)
  336. {
  337. $value->Rewind();
  338. }
  339. return $value;
  340. }
  341. public function GetOriginal($sAttCode)
  342. {
  343. if (!array_key_exists($sAttCode, MetaModel::ListAttributeDefs(get_class($this))))
  344. {
  345. throw new CoreException("Unknown attribute code '$sAttCode' for the class ".get_class($this));
  346. }
  347. return $this->m_aOrigValues[$sAttCode];
  348. }
  349. /**
  350. * Returns data loaded by the mean of a dynamic and explicit JOIN
  351. */
  352. public function GetExtendedData()
  353. {
  354. return $this->m_aExtendedData;
  355. }
  356. /**
  357. * Updates the value of an external field by (re)loading the object
  358. * corresponding to the external key and getting the value from it
  359. * @param string $sAttCode Attribute code of the external field to update
  360. * @return void
  361. */
  362. protected function UpdateExternalField($sAttCode)
  363. {
  364. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  365. if ($oAttDef->IsExternalField())
  366. {
  367. $sTargetClass = $oAttDef->GetTargetClass();
  368. $objkey = $this->Get($oAttDef->GetKeyAttCode());
  369. $oObj = MetaModel::GetObject($sTargetClass, $objkey);
  370. if (is_object($oObj))
  371. {
  372. $value = $oObj->Get($oAttDef->GetExtAttCode());
  373. $this->Set($sAttCode, $value);
  374. }
  375. }
  376. }
  377. public function ComputeValues()
  378. {
  379. }
  380. // Compute scalar attributes that depend on any other type of attribute
  381. final public function DoComputeValues()
  382. {
  383. // TODO - use a flag rather than checking the call stack -> this will certainly accelerate things
  384. // First check that we are not currently computing the fields
  385. // (yes, we need to do some things like Set/Get to compute the fields which will in turn trigger the update...)
  386. foreach (debug_backtrace() as $aCallInfo)
  387. {
  388. if (!array_key_exists("class", $aCallInfo)) continue;
  389. if ($aCallInfo["class"] != get_class($this)) continue;
  390. if ($aCallInfo["function"] != "ComputeValues") continue;
  391. return; //skip!
  392. }
  393. $this->ComputeValues();
  394. }
  395. public function GetAsHTML($sAttCode)
  396. {
  397. $sClass = get_class($this);
  398. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  399. if ($oAtt->IsExternalKey(EXTKEY_ABSOLUTE))
  400. {
  401. //return $this->Get($sAttCode.'_friendlyname');
  402. $sTargetClass = $oAtt->GetTargetClass(EXTKEY_ABSOLUTE);
  403. $iTargetKey = $this->Get($sAttCode);
  404. $sLabel = $this->Get($sAttCode.'_friendlyname');
  405. return $this->MakeHyperLink($sTargetClass, $iTargetKey, $sLabel);
  406. }
  407. // That's a standard attribute (might be an ext field or a direct field, etc.)
  408. return $oAtt->GetAsHTML($this->Get($sAttCode));
  409. }
  410. public function GetEditValue($sAttCode)
  411. {
  412. $sClass = get_class($this);
  413. $oAtt = MetaModel::GetAttributeDef($sClass, $sAttCode);
  414. if ($oAtt->IsExternalKey())
  415. {
  416. $sTargetClass = $oAtt->GetTargetClass();
  417. if ($this->IsNew())
  418. {
  419. // The current object exists only in memory, don't try to query it in the DB !
  420. // instead let's query for the object pointed by the external key, and get its name
  421. $targetObjId = $this->Get($sAttCode);
  422. $oTargetObj = MetaModel::GetObject($sTargetClass, $targetObjId, false); // false => not sure it exists
  423. if (is_object($oTargetObj))
  424. {
  425. $sEditValue = $oTargetObj->GetName();
  426. }
  427. else
  428. {
  429. $sEditValue = 0;
  430. }
  431. }
  432. else
  433. {
  434. $sEditValue = $this->Get($sAttCode.'_friendlyname');
  435. }
  436. }
  437. else
  438. {
  439. $sEditValue = $oAtt->GetEditValue($this->Get($sAttCode));
  440. }
  441. return $sEditValue;
  442. }
  443. public function GetAsXML($sAttCode)
  444. {
  445. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  446. return $oAtt->GetAsXML($this->Get($sAttCode), $this);
  447. }
  448. public function GetAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  449. {
  450. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  451. return $oAtt->GetAsCSV($this->Get($sAttCode), $sSeparator, $sTextQualifier, $this);
  452. }
  453. public function GetOriginalAsHTML($sAttCode)
  454. {
  455. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  456. return $oAtt->GetAsHTML($this->GetOriginal($sAttCode), $this);
  457. }
  458. public function GetOriginalAsXML($sAttCode)
  459. {
  460. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  461. return $oAtt->GetAsXML($this->GetOriginal($sAttCode), $this);
  462. }
  463. public function GetOriginalAsCSV($sAttCode, $sSeparator = ',', $sTextQualifier = '"')
  464. {
  465. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  466. return $oAtt->GetAsCSV($this->GetOriginal($sAttCode), $sSeparator, $sTextQualifier, $this);
  467. }
  468. protected static function MakeHyperLink($sObjClass, $sObjKey, $sLabel = '')
  469. {
  470. if ($sObjKey <= 0) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  471. $oAppContext = new ApplicationContext();
  472. $sPage = self::ComputeUIPage($sObjClass);
  473. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  474. // Safety net
  475. //
  476. if (empty($sLabel))
  477. {
  478. // If the object if not issued from a query but constructed programmatically
  479. // the label may be empty. In this case run a query to get the object's friendly name
  480. $oTmpObj = MetaModel::GetObject($sObjClass, $sObjKey);
  481. $sLabel = $oTmpObj->GetName();
  482. //$sLabel = MetaModel::GetName($sObjClass)." #$sObjKey";
  483. }
  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 function GetHyperlink()
  488. {
  489. if ($this->IsNew()) return '<em>'.Dict::S('UI:UndefinedObject').'</em>'; // Objects built in memory have negative IDs
  490. $oAppContext = new ApplicationContext();
  491. $sPage = $this->GetUIPage();
  492. $sAbsoluteUrl = utils::GetAbsoluteUrlPath();
  493. $sObjClass = get_class($this);
  494. $sObjKey = $this->GetKey();
  495. $sLabel = $this->GetName();
  496. $sHint = MetaModel::GetName($sObjClass)."::$sObjKey";
  497. return "<a href=\"{$sAbsoluteUrl}{$sPage}?operation=details&class=$sObjClass&id=$sObjKey&".$oAppContext->GetForLink()."\" title=\"$sHint\">$sLabel</a>";
  498. }
  499. public static function ComputeUIPage($sClass)
  500. {
  501. static $aUIPagesCache = array(); // Cache to store the php page used to display each class of object
  502. if (!isset($aUIPagesCache[$sClass]))
  503. {
  504. $UIPage = false;
  505. if (is_callable("$sClass::GetUIPage"))
  506. {
  507. $UIPage = eval("return $sClass::GetUIPage();"); // May return false in case of error
  508. }
  509. $aUIPagesCache[$sClass] = $UIPage === false ? './UI.php' : $UIPage;
  510. }
  511. $sPage = $aUIPagesCache[$sClass];
  512. return $sPage;
  513. }
  514. public static function GetUIPage()
  515. {
  516. return 'UI.php';
  517. }
  518. // could be in the metamodel ?
  519. public static function IsValidPKey($value)
  520. {
  521. return ((string)$value === (string)(int)$value);
  522. }
  523. public function GetKey()
  524. {
  525. return $this->m_iKey;
  526. }
  527. public function SetKey($iNewKey)
  528. {
  529. if (!self::IsValidPKey($iNewKey))
  530. {
  531. throw new CoreException("An object id must be an integer value ($iNewKey)");
  532. }
  533. if ($this->m_bIsInDB && !empty($this->m_iKey) && ($this->m_iKey != $iNewKey))
  534. {
  535. throw new CoreException("Changing the key ({$this->m_iKey} to $iNewKey) on an object (class {".get_class($this).") wich already exists in the Database");
  536. }
  537. $this->m_iKey = $iNewKey;
  538. }
  539. /**
  540. * Get the icon representing this object
  541. * @param boolean $bImgTag If true the result is a full IMG tag (or an emtpy string if no icon is defined)
  542. * @return string Either the full IMG tag ($bImgTag == true) or just the path to the icon file
  543. */
  544. public function GetIcon($bImgTag = true)
  545. {
  546. return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  547. }
  548. public function GetName()
  549. {
  550. return $this->Get('friendlyname');
  551. }
  552. public function GetState()
  553. {
  554. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  555. if (empty($sStateAttCode))
  556. {
  557. return '';
  558. }
  559. else
  560. {
  561. return $this->Get($sStateAttCode);
  562. }
  563. }
  564. public function GetStateLabel()
  565. {
  566. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  567. if (empty($sStateAttCode))
  568. {
  569. return '';
  570. }
  571. else
  572. {
  573. $sStateValue = $this->Get($sStateAttCode);
  574. return MetaModel::GetStateLabel(get_class($this), $sStateValue);
  575. }
  576. }
  577. public function GetStateDescription()
  578. {
  579. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  580. if (empty($sStateAttCode))
  581. {
  582. return '';
  583. }
  584. else
  585. {
  586. $sStateValue = $this->Get($sStateAttCode);
  587. return MetaModel::GetStateDescription(get_class($this), $sStateValue);
  588. }
  589. }
  590. /**
  591. * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
  592. * for the given attribute in the current state of the object
  593. * @param string $sAttCode The code of the attribute
  594. * @return integer Flags: the binary combination of the flags applicable to this attribute
  595. */
  596. public function GetAttributeFlags($sAttCode, &$aReasons = array())
  597. {
  598. $iFlags = 0; // By default (if no life cycle) no flag at all
  599. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  600. if (!empty($sStateAttCode))
  601. {
  602. $iFlags = MetaModel::GetAttributeFlags(get_class($this), $this->Get($sStateAttCode), $sAttCode);
  603. }
  604. $aReasons = array();
  605. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  606. return $iFlags | $iSynchroFlags; // Combine both sets of flags
  607. }
  608. // check if the given (or current) value is suitable for the attribute
  609. // return true if successfull
  610. // return the error desciption otherwise
  611. public function CheckValue($sAttCode, $value = null)
  612. {
  613. if (!is_null($value))
  614. {
  615. $toCheck = $value;
  616. }
  617. else
  618. {
  619. $toCheck = $this->Get($sAttCode);
  620. }
  621. $oAtt = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  622. if (!$oAtt->IsWritable())
  623. {
  624. return true;
  625. }
  626. elseif ($oAtt->IsNull($toCheck))
  627. {
  628. if ($oAtt->IsNullAllowed())
  629. {
  630. return true;
  631. }
  632. else
  633. {
  634. return "Null not allowed";
  635. }
  636. }
  637. elseif ($oAtt->IsExternalKey())
  638. {
  639. if (!MetaModel::SkipCheckExtKeys())
  640. {
  641. $sTargetClass = $oAtt->GetTargetClass();
  642. $oTargetObj = MetaModel::GetObject($sTargetClass, $toCheck, false /*must be found*/, true /*allow all data*/);
  643. if (is_null($oTargetObj))
  644. {
  645. return "Target object not found ($sTargetClass::$toCheck)";
  646. }
  647. }
  648. }
  649. elseif ($oAtt->IsScalar())
  650. {
  651. $aValues = $oAtt->GetAllowedValues($this->ToArgs());
  652. if (count($aValues) > 0)
  653. {
  654. if (!array_key_exists($toCheck, $aValues))
  655. {
  656. return "Value not allowed [$toCheck]";
  657. }
  658. }
  659. if (!is_null($iMaxSize = $oAtt->GetMaxSize()))
  660. {
  661. $iLen = strlen($toCheck);
  662. if ($iLen > $iMaxSize)
  663. {
  664. return "String too long (found $iLen, limited to $iMaxSize)";
  665. }
  666. }
  667. if (!$oAtt->CheckFormat($toCheck))
  668. {
  669. return "Wrong format [$toCheck]";
  670. }
  671. }
  672. return true;
  673. }
  674. // check attributes together
  675. public function CheckConsistency()
  676. {
  677. return true;
  678. }
  679. // check integrity rules (before inserting or updating the object)
  680. // a displayable error is returned
  681. public function DoCheckToWrite()
  682. {
  683. $this->DoComputeValues();
  684. $this->m_aCheckIssues = array();
  685. $aChanges = $this->ListChanges();
  686. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
  687. {
  688. $res = $this->CheckValue($sAttCode);
  689. if ($res !== true)
  690. {
  691. // $res contains the error description
  692. $this->m_aCheckIssues[] = "Unexpected value for attribute '$sAttCode': $res";
  693. }
  694. }
  695. if (count($this->m_aCheckIssues) > 0)
  696. {
  697. // No need to check consistency between attributes if any of them has
  698. // an unexpected value
  699. return;
  700. }
  701. $res = $this->CheckConsistency();
  702. if ($res !== true)
  703. {
  704. // $res contains the error description
  705. $this->m_aCheckIssues[] = "Consistency rules not followed: $res";
  706. }
  707. // Synchronization: are we attempting to modify an attribute for which an external source is master?
  708. //
  709. if ($this->m_bIsInDB && $this->InSyncScope() && (count($aChanges) > 0))
  710. {
  711. foreach($aChanges as $sAttCode => $value)
  712. {
  713. $iFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  714. if ($iFlags & OPT_ATT_SLAVE)
  715. {
  716. // Note: $aReasonInfo['name'] could be reported (the task owning the attribute)
  717. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  718. $sAttLabel = $oAttDef->GetLabel();
  719. foreach($aReasons as $aReasonInfo)
  720. {
  721. // Todo: associate the attribute code with the error
  722. $this->m_aCheckIssues[] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $sAttLabel);
  723. }
  724. }
  725. }
  726. }
  727. }
  728. final public function CheckToWrite()
  729. {
  730. if (MetaModel::SkipCheckToWrite())
  731. {
  732. return array(true, array());
  733. }
  734. if (is_null($this->m_bCheckStatus))
  735. {
  736. $oKPI = new ExecutionKPI();
  737. $this->DoCheckToWrite();
  738. $oKPI->ComputeStats('CheckToWrite', get_class($this));
  739. if (count($this->m_aCheckIssues) == 0)
  740. {
  741. $this->m_bCheckStatus = true;
  742. }
  743. else
  744. {
  745. $this->m_bCheckStatus = false;
  746. }
  747. }
  748. return array($this->m_bCheckStatus, $this->m_aCheckIssues, $this->m_bSecurityIssue);
  749. }
  750. // check if it is allowed to delete the existing object from the database
  751. // a displayable error is returned
  752. protected function DoCheckToDelete(&$oDeletionPlan)
  753. {
  754. $this->m_aDeleteIssues = array(); // Ok
  755. if ($this->InSyncScope())
  756. {
  757. $oReplicaSet = $this->GetMasterReplica();
  758. if ($oReplicaSet->Count() > 0)
  759. {
  760. while($aData = $oReplicaSet->FetchAssoc())
  761. {
  762. $oDataSource = $aData['datasource'];
  763. $oReplica = $aData['replica'];
  764. $oDeletionPlan->AddToDelete($oReplica, DEL_SILENT);
  765. if ($oDataSource->GetKey() == SynchroDataSource::GetCurrentTaskId())
  766. {
  767. // The current task has the right to delete the object
  768. continue;
  769. }
  770. if ($oReplica->Get('status_dest_creator') != 1)
  771. {
  772. // The object is not owned by the task
  773. continue;
  774. }
  775. $sLink = $oDataSource->GetName();
  776. $sUserDeletePolicy = $oDataSource->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. protected 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($oDeletionPlan);
  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. ?>