dbobject.class.php 51 KB

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