dbobject.class.php 51 KB

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