dbobjectset.class.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Object set management
  20. *
  21. * @copyright Copyright (C) 2010-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. /**
  25. * A set of persistent objects, could be heterogeneous as long as the objects in the set have a common ancestor class
  26. *
  27. * @package iTopORM
  28. */
  29. class DBObjectSet
  30. {
  31. protected $m_aAddedIds; // Ids of objects added (discrete lists)
  32. protected $m_aAddedObjects;
  33. protected $m_aArgs;
  34. protected $m_aAttToLoad;
  35. protected $m_aOrderBy;
  36. public $m_bLoaded;
  37. protected $m_iNumTotalDBRows;
  38. protected $m_iNumLoadedDBRows;
  39. protected $m_iCurrRow;
  40. protected $m_oFilter;
  41. protected $m_oSQLResult;
  42. /**
  43. * Create a new set based on a Search definition.
  44. *
  45. * @param DBSearch $oFilter The search filter defining the objects which are part of the set (multiple columns/objects per row are supported)
  46. * @param hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  47. * @param hash $aArgs Values to substitute for the search/query parameters (if any). Format: param_name => value
  48. * @param hash $aExtendedDataSpec
  49. * @param int $iLimitCount Maximum number of rows to load (i.e. equivalent to MySQL's LIMIT start, count)
  50. * @param int $iLimitStart Index of the first row to load (i.e. equivalent to MySQL's LIMIT start, count)
  51. */
  52. public function __construct(DBSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0)
  53. {
  54. $this->m_oFilter = $oFilter->DeepClone();
  55. $this->m_aAddedIds = array();
  56. $this->m_aOrderBy = $aOrderBy;
  57. $this->m_aArgs = $aArgs;
  58. $this->m_aAttToLoad = null;
  59. $this->m_aExtendedDataSpec = $aExtendedDataSpec;
  60. $this->m_iLimitCount = $iLimitCount;
  61. $this->m_iLimitStart = $iLimitStart;
  62. $this->m_iNumTotalDBRows = null; // Total number of rows for the query without LIMIT. null if unknown yet
  63. $this->m_iNumLoadedDBRows = 0; // Total number of rows LOADED in $this->m_oSQLResult via a SQL query. 0 by default
  64. $this->m_bLoaded = false; // true when the filter has been used OR the set is built step by step (AddObject...)
  65. $this->m_aAddedObjects = array(); // array of (row => array of (classalias) => object/null) storing the objects added "in memory"
  66. $this->m_iCurrRow = 0;
  67. $this->m_oSQLResult = null;
  68. }
  69. public function __destruct()
  70. {
  71. if (is_object($this->m_oSQLResult))
  72. {
  73. $this->m_oSQLResult->free();
  74. }
  75. }
  76. public function __toString()
  77. {
  78. $sRet = '';
  79. $this->Rewind();
  80. $sRet .= "Set (".$this->m_oFilter->ToOQL().")<br/>\n";
  81. $sRet .= "Query: <pre style=\"font-size: smaller; display:inline;\">".$this->m_oFilter->MakeSelectQuery().")</pre>\n";
  82. $sRet .= $this->Count()." records<br/>\n";
  83. if ($this->Count() > 0)
  84. {
  85. $sRet .= "<ul class=\"treeview\">\n";
  86. while ($oObj = $this->Fetch())
  87. {
  88. $sRet .= "<li>".$oObj->__toString()."</li>\n";
  89. }
  90. $sRet .= "</ul>\n";
  91. }
  92. return $sRet;
  93. }
  94. public function __clone()
  95. {
  96. $this->m_oFilter = $this->m_oFilter->DeepClone();
  97. $this->m_iNumTotalDBRows = null; // Total number of rows for the query without LIMIT. null if unknown yet
  98. $this->m_iNumLoadedDBRows = 0; // Total number of rows LOADED in $this->m_oSQLResult via a SQL query. 0 by default
  99. $this->m_bLoaded = false; // true when the filter has been used OR the set is built step by step (AddObject...)
  100. $this->m_iCurrRow = 0;
  101. $this->m_oSQLResult = null;
  102. }
  103. /**
  104. * Called when unserializing a DBObjectSet
  105. */
  106. public function __wakeup()
  107. {
  108. $this->m_iNumTotalDBRows = null; // Total number of rows for the query without LIMIT. null if unknown yet
  109. $this->m_iNumLoadedDBRows = 0; // Total number of rows LOADED in $this->m_oSQLResult via a SQL query. 0 by default
  110. $this->m_bLoaded = false; // true when the filter has been used OR the set is built step by step (AddObject...)
  111. $this->m_iCurrRow = 0;
  112. $this->m_oSQLResult = null;
  113. }
  114. /**
  115. * Specify the subset of attributes to load (for each class of objects) before performing the SQL query for retrieving the rows from the DB
  116. *
  117. * @param hash $aAttToLoad Format: alias => array of attribute_codes
  118. *
  119. * @return void
  120. */
  121. public function OptimizeColumnLoad($aAttToLoad)
  122. {
  123. if (is_null($aAttToLoad))
  124. {
  125. $this->m_aAttToLoad = null;
  126. }
  127. else
  128. {
  129. // Complete the attribute list with the attribute codes
  130. $aAttToLoadWithAttDef = array();
  131. foreach($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  132. {
  133. $aAttToLoadWithAttDef[$sClassAlias] = array();
  134. if (array_key_exists($sClassAlias, $aAttToLoad))
  135. {
  136. $aAttList = $aAttToLoad[$sClassAlias];
  137. foreach($aAttList as $sAttToLoad)
  138. {
  139. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad);
  140. $aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad] = $oAttDef;
  141. if ($oAttDef->IsExternalKey())
  142. {
  143. // Add the external key friendly name anytime
  144. $oFriendlyNameAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad.'_friendlyname');
  145. $aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad.'_friendlyname'] = $oFriendlyNameAttDef;
  146. }
  147. }
  148. }
  149. // Add the friendly name anytime
  150. $oFriendlyNameAttDef = MetaModel::GetAttributeDef($sClass, 'friendlyname');
  151. $aAttToLoadWithAttDef[$sClassAlias]['friendlyname'] = $oFriendlyNameAttDef;
  152. // Make sure that the final class is requested anytime, whatever the specification (needed for object construction!)
  153. if (!MetaModel::IsStandaloneClass($sClass) && !array_key_exists('finalclass', $aAttToLoadWithAttDef[$sClassAlias]))
  154. {
  155. $aAttToLoadWithAttDef[$sClassAlias]['finalclass'] = MetaModel::GetAttributeDef($sClass, 'finalclass');
  156. }
  157. }
  158. $this->m_aAttToLoad = $aAttToLoadWithAttDef;
  159. }
  160. }
  161. /**
  162. * Create a set (in-memory) containing just the given object
  163. *
  164. * @param DBobject $oObject
  165. *
  166. * @return DBObjectSet The singleton set
  167. */
  168. static public function FromObject($oObject)
  169. {
  170. $oRetSet = self::FromScratch(get_class($oObject));
  171. $oRetSet->AddObject($oObject);
  172. return $oRetSet;
  173. }
  174. /**
  175. * Create an empty set (in-memory), for the given class (and its subclasses) of objects
  176. *
  177. * @param string $sClass The class (or an ancestor) for the objects to be added in this set
  178. *
  179. * @return DBObject The empty set
  180. */
  181. static public function FromScratch($sClass)
  182. {
  183. $oFilter = new DBObjectSearch($sClass);
  184. $oFilter->AddConditionExpression(new FalseExpression());
  185. $oRetSet = new self($oFilter);
  186. $oRetSet->m_bLoaded = true; // no DB load
  187. $oRetSet->m_iNumTotalDBRows = 0; // Nothing from the DB
  188. return $oRetSet;
  189. }
  190. /**
  191. * Create a set (in-memory) with just one column (i.e. one object per row) and filled with the given array of objects
  192. *
  193. * @param string $sClass The class of the objects (must be a common ancestor to all objects in the set)
  194. * @param array $aObjects The list of objects to add into the set
  195. *
  196. * @return DBObjectSet
  197. */
  198. static public function FromArray($sClass, $aObjects)
  199. {
  200. $oRetSet = self::FromScratch($sClass);
  201. $oRetSet->AddObjectArray($aObjects, $sClass);
  202. return $oRetSet;
  203. }
  204. /**
  205. * Create a set in-memory with several classes of objects per row (with one alias per "column")
  206. *
  207. * Limitation:
  208. * The filter/OQL query representing such a set can not be rebuilt (only the first column will be taken into account)
  209. *
  210. * @param hash $aClasses Format: array of (alias => class)
  211. * @param hash $aObjects Format: array of (array of (classalias => object))
  212. *
  213. * @return DBObjectSet
  214. */
  215. static public function FromArrayAssoc($aClasses, $aObjects)
  216. {
  217. // In a perfect world, we should create a complete tree of DBObjectSearch,
  218. // but as we lack most of the information related to the objects,
  219. // let's create one search definition corresponding only to the first column
  220. $sClass = reset($aClasses);
  221. $sAlias = key($aClasses);
  222. $oFilter = new DBObjectSearch($sClass, $sAlias);
  223. $oRetSet = new self($oFilter);
  224. $oRetSet->m_bLoaded = true; // no DB load
  225. $oRetSet->m_iNumTotalDBRows = 0; // Nothing from the DB
  226. foreach($aObjects as $rowIndex => $aObjectsByClassAlias)
  227. {
  228. $oRetSet->AddObjectExtended($aObjectsByClassAlias);
  229. }
  230. return $oRetSet;
  231. }
  232. static public function FromLinkSet($oObject, $sLinkSetAttCode, $sExtKeyToRemote)
  233. {
  234. $oLinkAttCode = MetaModel::GetAttributeDef(get_class($oObject), $sLinkSetAttCode);
  235. $oExtKeyAttDef = MetaModel::GetAttributeDef($oLinkAttCode->GetLinkedClass(), $sExtKeyToRemote);
  236. $sTargetClass = $oExtKeyAttDef->GetTargetClass();
  237. $oLinkSet = $oObject->Get($sLinkSetAttCode);
  238. $aTargets = array();
  239. while ($oLink = $oLinkSet->Fetch())
  240. {
  241. $aTargets[] = MetaModel::GetObject($sTargetClass, $oLink->Get($sExtKeyToRemote));
  242. }
  243. return self::FromArray($sTargetClass, $aTargets);
  244. }
  245. public function ToArray($bWithId = true)
  246. {
  247. $aRet = array();
  248. $this->Rewind();
  249. while ($oObject = $this->Fetch())
  250. {
  251. if ($bWithId)
  252. {
  253. $aRet[$oObject->GetKey()] = $oObject;
  254. }
  255. else
  256. {
  257. $aRet[] = $oObject;
  258. }
  259. }
  260. return $aRet;
  261. }
  262. public function ToArrayOfValues()
  263. {
  264. if (!$this->m_bLoaded) $this->Load();
  265. $this->Rewind();
  266. $aSelectedClasses = $this->m_oFilter->GetSelectedClasses();
  267. $aRet = array();
  268. $iRow = 0;
  269. while($aObjects = $this->FetchAssoc())
  270. {
  271. foreach($aObjects as $sClassAlias => $oObject)
  272. {
  273. if (is_null($oObject))
  274. {
  275. $aRet[$iRow][$sClassAlias.'.'.'id'] = null;
  276. }
  277. else
  278. {
  279. $aRet[$iRow][$sClassAlias.'.'.'id'] = $oObject->GetKey();
  280. }
  281. if (is_null($oObject))
  282. {
  283. $sClass = $aSelectedClasses[$sClassAlias];
  284. }
  285. else
  286. {
  287. $sClass = get_class($oObject);
  288. }
  289. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  290. {
  291. if ($oAttDef->IsScalar())
  292. {
  293. $sAttName = $sClassAlias.'.'.$sAttCode;
  294. if (is_null($oObject))
  295. {
  296. $aRet[$iRow][$sAttName] = null;
  297. }
  298. else
  299. {
  300. $aRet[$iRow][$sAttName] = $oObject->Get($sAttCode);
  301. }
  302. }
  303. }
  304. }
  305. $iRow++;
  306. }
  307. return $aRet;
  308. }
  309. public function GetColumnAsArray($sAttCode, $bWithId = true)
  310. {
  311. $aRet = array();
  312. $this->Rewind();
  313. while ($oObject = $this->Fetch())
  314. {
  315. if ($bWithId)
  316. {
  317. $aRet[$oObject->GetKey()] = $oObject->Get($sAttCode);
  318. }
  319. else
  320. {
  321. $aRet[] = $oObject->Get($sAttCode);
  322. }
  323. }
  324. return $aRet;
  325. }
  326. /**
  327. * Retrieve the DBSearch corresponding to the objects present in this set
  328. *
  329. * Limitation:
  330. * This method will NOT work for sets with several columns (i.e. several objects per row)
  331. *
  332. * @return DBObjectSearch
  333. */
  334. public function GetFilter()
  335. {
  336. // Make sure that we carry on the parameters of the set with the filter
  337. $oFilter = $this->m_oFilter->DeepClone();
  338. // Note: the arguments found within a set can be object (but not in a filter)
  339. // That's why PrepareQueryArguments must be invoked there
  340. $oFilter->SetInternalParams(array_merge($oFilter->GetInternalParams(), MetaModel::PrepareQueryArguments($this->m_aArgs)));
  341. if (count($this->m_aAddedIds) == 0)
  342. {
  343. return $oFilter;
  344. }
  345. else
  346. {
  347. $oIdListExpr = ListExpression::FromScalars(array_keys($this->m_aAddedIds));
  348. $oIdExpr = new FieldExpression('id', $oFilter->GetClassAlias());
  349. $oIdInList = new BinaryExpression($oIdExpr, 'IN', $oIdListExpr);
  350. $oFilter->MergeConditionExpression($oIdInList);
  351. return $oFilter;
  352. }
  353. }
  354. /**
  355. * The (common ancestor) class of the objects in the first column of this set
  356. *
  357. * @return string The class of the objects in the first column
  358. */
  359. public function GetClass()
  360. {
  361. return $this->m_oFilter->GetClass();
  362. }
  363. /**
  364. * The alias for the class of the objects in the first column of this set
  365. *
  366. * @return string The alias of the class in the first column
  367. */
  368. public function GetClassAlias()
  369. {
  370. return $this->m_oFilter->GetClassAlias();
  371. }
  372. /**
  373. * The list of all classes (one per column) which are part of this set
  374. *
  375. * @return hash Format: alias => class
  376. */
  377. public function GetSelectedClasses()
  378. {
  379. return $this->m_oFilter->GetSelectedClasses();
  380. }
  381. /**
  382. * The root class (i.e. highest ancestor in the MeaModel class hierarchy) for the first column on this set
  383. *
  384. * @return string The root class for the objects in the first column of the set
  385. */
  386. public function GetRootClass()
  387. {
  388. return MetaModel::GetRootClass($this->GetClass());
  389. }
  390. /**
  391. * The arguments used for building this set
  392. *
  393. * @return hash Format: parameter_name => value
  394. */
  395. public function GetArgs()
  396. {
  397. return $this->m_aArgs;
  398. }
  399. /**
  400. * Sets the limits for loading the rows from the DB. Equivalent to MySQL's LIMIT start,count clause.
  401. * @param int $iLimitCount The number of rows to load
  402. * @param int $iLimitStart The index of the first row to load
  403. */
  404. public function SetLimit($iLimitCount, $iLimitStart = 0)
  405. {
  406. $this->m_iLimitCount = $iLimitCount;
  407. $this->m_iLimitStart = $iLimitStart;
  408. }
  409. /**
  410. * Sets the sort order for loading the rows from the DB. Changing the order by causes a Reload.
  411. *
  412. * @param hash $aOrderBy Format: field_code => boolean (true = ascending, false = descending)
  413. */
  414. public function SetOrderBy($aOrderBy)
  415. {
  416. if ($this->m_aOrderBy != $aOrderBy)
  417. {
  418. $this->m_aOrderBy = $aOrderBy;
  419. if ($this->m_bLoaded)
  420. {
  421. $this->m_bLoaded = false;
  422. $this->Load();
  423. }
  424. }
  425. }
  426. /**
  427. * Returns the 'count' limit for loading the rows from the DB
  428. *
  429. * @return int
  430. */
  431. public function GetLimitCount()
  432. {
  433. return $this->m_iLimitCount;
  434. }
  435. /**
  436. * Returns the 'start' limit for loading the rows from the DB
  437. *
  438. * @return int
  439. */
  440. public function GetLimitStart()
  441. {
  442. return $this->m_iLimitStart;
  443. }
  444. /**
  445. * Get the sort order used for loading this set from the database
  446. *
  447. * Limitation: the sort order has no effect on objects added in-memory
  448. *
  449. * @return hash Format: field_code => boolean (true = ascending, false = descending)
  450. */
  451. public function GetRealSortOrder()
  452. {
  453. // Get the class default sort order if not specified with the API
  454. //
  455. if (empty($this->m_aOrderBy))
  456. {
  457. return MetaModel::GetOrderByDefault($this->m_oFilter->GetClass());
  458. }
  459. else
  460. {
  461. return $this->m_aOrderBy;
  462. }
  463. }
  464. /**
  465. * Loads the set from the database. Actually performs the SQL query to retrieve the records from the DB.
  466. */
  467. public function Load()
  468. {
  469. if ($this->m_bLoaded) return;
  470. // Note: it is mandatory to set this value now, to protect against reentrance
  471. $this->m_bLoaded = true;
  472. if ($this->m_iLimitCount > 0)
  473. {
  474. $sSQL = $this->m_oFilter->MakeSelectQuery($this->GetRealSortOrder(), $this->m_aArgs, $this->m_aAttToLoad, $this->m_aExtendedDataSpec, $this->m_iLimitCount, $this->m_iLimitStart);
  475. }
  476. else
  477. {
  478. $sSQL = $this->m_oFilter->MakeSelectQuery($this->GetRealSortOrder(), $this->m_aArgs, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  479. }
  480. if (is_object($this->m_oSQLResult))
  481. {
  482. // Free previous resultset if any
  483. $this->m_oSQLResult->free();
  484. $this->m_oSQLResult = null;
  485. }
  486. $this->m_iNumTotalDBRows = null;
  487. $this->m_oSQLResult = CMDBSource::Query($sSQL);
  488. if ($this->m_oSQLResult === false) return;
  489. if (($this->m_iLimitCount == 0) && ($this->m_iLimitStart == 0))
  490. {
  491. $this->m_iNumTotalDBRows = $this->m_oSQLResult->num_rows;
  492. }
  493. $this->m_iNumLoadedDBRows = $this->m_oSQLResult->num_rows;
  494. }
  495. /**
  496. * The total number of rows in this set. Independently of the SetLimit used for loading the set and taking into account the rows added in-memory.
  497. *
  498. * May actually perform the SQL query SELECT COUNT... if the set was not previously loaded, or loaded with a SetLimit
  499. *
  500. * @return int The total number of rows for this set.
  501. */
  502. public function Count()
  503. {
  504. if (is_null($this->m_iNumTotalDBRows))
  505. {
  506. $sSQL = $this->m_oFilter->MakeSelectQuery(array(), $this->m_aArgs, null, null, 0, 0, true);
  507. $resQuery = CMDBSource::Query($sSQL);
  508. if (!$resQuery) return 0;
  509. $aRow = CMDBSource::FetchArray($resQuery);
  510. CMDBSource::FreeResult($resQuery);
  511. $this->m_iNumTotalDBRows = $aRow['COUNT'];
  512. }
  513. return $this->m_iNumTotalDBRows + count($this->m_aAddedObjects); // Does it fix Trac #887 ??
  514. }
  515. /**
  516. * Number of rows available in memory (loaded from DB + added in memory)
  517. *
  518. * @return number The number of rows available for Fetch'ing
  519. */
  520. protected function CountLoaded()
  521. {
  522. return $this->m_iNumLoadedDBRows + count($this->m_aAddedObjects);
  523. }
  524. /**
  525. * Fetch the object (with the given class alias) at the current position in the set and move the cursor to the next position.
  526. *
  527. * @param string $sRequestedClassAlias The class alias to fetch (if there are several objects/classes per row)
  528. * @return DBObject The fetched object or null when at the end
  529. */
  530. public function Fetch($sRequestedClassAlias = '')
  531. {
  532. if (!$this->m_bLoaded) $this->Load();
  533. if ($this->m_iCurrRow >= $this->CountLoaded())
  534. {
  535. return null;
  536. }
  537. if (strlen($sRequestedClassAlias) == 0)
  538. {
  539. $sRequestedClassAlias = $this->m_oFilter->GetClassAlias();
  540. }
  541. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  542. {
  543. // Pick the row from the database
  544. $aRow = CMDBSource::FetchArray($this->m_oSQLResult);
  545. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  546. {
  547. if ($sRequestedClassAlias == $sClassAlias)
  548. {
  549. if (is_null($aRow[$sClassAlias.'id']))
  550. {
  551. $oRetObj = null;
  552. }
  553. else
  554. {
  555. $oRetObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  556. }
  557. break;
  558. }
  559. }
  560. }
  561. else
  562. {
  563. // Pick the row from the objects added *in memory*
  564. $oRetObj = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sRequestedClassAlias];
  565. }
  566. $this->m_iCurrRow++;
  567. return $oRetObj;
  568. }
  569. /**
  570. * Fetch the whole row of objects (if several classes have been specified in the query) and move the cursor to the next position
  571. *
  572. * @return hash A hash with the format 'classAlias' => $oObj representing the current row of the set. Returns null when at the end.
  573. */
  574. public function FetchAssoc()
  575. {
  576. if (!$this->m_bLoaded) $this->Load();
  577. if ($this->m_iCurrRow >= $this->CountLoaded())
  578. {
  579. return null;
  580. }
  581. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  582. {
  583. // Pick the row from the database
  584. $aRow = CMDBSource::FetchArray($this->m_oSQLResult);
  585. $aRetObjects = array();
  586. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  587. {
  588. if (is_null($aRow[$sClassAlias.'id']))
  589. {
  590. $oObj = null;
  591. }
  592. else
  593. {
  594. $oObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  595. }
  596. $aRetObjects[$sClassAlias] = $oObj;
  597. }
  598. }
  599. else
  600. {
  601. // Pick the row from the objects added *in memory*
  602. $aRetObjects = array();
  603. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  604. {
  605. $aRetObjects[$sClassAlias] = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sClassAlias];
  606. }
  607. }
  608. $this->m_iCurrRow++;
  609. return $aRetObjects;
  610. }
  611. /**
  612. * Position the cursor (for iterating in the set) to the first position (equivalent to Seek(0))
  613. */
  614. public function Rewind()
  615. {
  616. if ($this->m_bLoaded)
  617. {
  618. $this->Seek(0);
  619. }
  620. }
  621. /**
  622. * Position the cursor (for iterating in the set) to the given position
  623. *
  624. * @param int $iRow
  625. */
  626. public function Seek($iRow)
  627. {
  628. if (!$this->m_bLoaded) $this->Load();
  629. $this->m_iCurrRow = min($iRow, $this->Count());
  630. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  631. {
  632. $this->m_oSQLResult->data_seek($this->m_iCurrRow);
  633. }
  634. return $this->m_iCurrRow;
  635. }
  636. /**
  637. * Add an object to the current set (in-memory only, nothing is written to the database)
  638. *
  639. * Limitation:
  640. * Sets with several objects per row are NOT supported
  641. *
  642. * @param DBObject $oObject The object to add
  643. * @param string $sClassAlias The alias for the class of the object
  644. */
  645. public function AddObject($oObject, $sClassAlias = '')
  646. {
  647. if (!$this->m_bLoaded) $this->Load();
  648. if (strlen($sClassAlias) == 0)
  649. {
  650. $sClassAlias = $this->m_oFilter->GetClassAlias();
  651. }
  652. $iNextPos = count($this->m_aAddedObjects);
  653. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  654. if (!is_null($oObject))
  655. {
  656. $this->m_aAddedIds[$oObject->GetKey()] = true;
  657. }
  658. }
  659. /**
  660. * Add a hash containig objects into the current set.
  661. *
  662. * The expected format for the hash is: $aObjectArray[$idx][$sClassAlias] => $oObject
  663. * Limitation:
  664. * The aliases MUST match the ones used in the current set
  665. * Only the ID of the objects associated to the first alias (column) is remembered.. in case we have to rebuild a filter
  666. *
  667. * @param hash $aObjectArray
  668. */
  669. protected function AddObjectExtended($aObjectArray)
  670. {
  671. if (!$this->m_bLoaded) $this->Load();
  672. $iNextPos = count($this->m_aAddedObjects);
  673. $sFirstAlias = $this->m_oFilter->GetClassAlias();
  674. foreach ($aObjectArray as $sClassAlias => $oObject)
  675. {
  676. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  677. if (!is_null($oObject) && ($sFirstAlias == $sClassAlias))
  678. {
  679. $this->m_aAddedIds[$oObject->GetKey()] = true;
  680. }
  681. }
  682. }
  683. /**
  684. * Add an array of objects into the current set
  685. *
  686. * Limitation:
  687. * Sets with several classes per row are not supported (use AddObjectExtended instead)
  688. *
  689. * @param array $aObjects The array of objects to add
  690. * @param string $sClassAlias The Alias of the class for the added objects
  691. */
  692. public function AddObjectArray($aObjects, $sClassAlias = '')
  693. {
  694. if (!$this->m_bLoaded) $this->Load();
  695. // #@# todo - add a check on the object class ?
  696. foreach ($aObjects as $oObj)
  697. {
  698. $this->AddObject($oObj, $sClassAlias);
  699. }
  700. }
  701. /**
  702. * Append a given set to the current object. (This method used to be named Merge)
  703. *
  704. * Limitation:
  705. * The added objects are not checked for duplicates (i.e. one cann add several times the same object, or add an object already present in the set).
  706. *
  707. * @param DBObjectSet $oObjectSet The set to append
  708. * @throws CoreException
  709. */
  710. public function Append(DBObjectSet $oObjectSet)
  711. {
  712. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  713. {
  714. throw new CoreException("Could not merge two objects sets if they don't have the same root class");
  715. }
  716. if (!$this->m_bLoaded) $this->Load();
  717. $oObjectSet->Seek(0);
  718. while ($oObject = $oObjectSet->Fetch())
  719. {
  720. $this->AddObject($oObject);
  721. }
  722. }
  723. /**
  724. * Create a set containing the objects present in both the current set and another specified set
  725. *
  726. * Limitations:
  727. * Will NOT work if only a subset of the sets was loaded with SetLimit.
  728. * Works only with sets made of objects loaded from the database since the comparison is based on the objects identifiers
  729. *
  730. * @param DBObjectSet $oObjectSet The set to intersect with. The current position inside the set will be lost (= at the end)
  731. * @throws CoreException
  732. * @return DBObjectSet A new set of objects, containing the objects present in both sets (based on their identifier)
  733. */
  734. public function CreateIntersect(DBObjectSet $oObjectSet)
  735. {
  736. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  737. {
  738. throw new CoreException("Could not 'intersect' two objects sets if they don't have the same root class");
  739. }
  740. if (!$this->m_bLoaded) $this->Load();
  741. $aId2Row = array();
  742. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  743. $idx = 0;
  744. while($oObj = $this->Fetch())
  745. {
  746. $aId2Row[$oObj->GetKey()] = $idx;
  747. $idx++;
  748. }
  749. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  750. $oObjectSet->Seek(0);
  751. while ($oObject = $oObjectSet->Fetch())
  752. {
  753. if (array_key_exists($oObject->GetKey(), $aId2Row))
  754. {
  755. $oNewSet->AddObject($oObject);
  756. }
  757. }
  758. $this->Seek($iCurrPos); // Restore the cursor
  759. return $oNewSet;
  760. }
  761. /**
  762. * Compare two sets of objects to determine if their content is identical or not.
  763. *
  764. * Limitation:
  765. * Works only for sets of 1 column (i.e. one class of object selected)
  766. *
  767. * @param DBObjectSet $oObjectSet
  768. * @param array $aExcludeColumns The list of columns to exclude frop the comparison
  769. * @return boolean True if the sets are identical, false otherwise
  770. */
  771. public function HasSameContents(DBObjectSet $oObjectSet, $aExcludeColumns = array())
  772. {
  773. $oComparator = new DBObjectSetComparator($this, $oObjectSet, $aExcludeColumns);
  774. return $oComparator->SetsAreEquivalent();
  775. }
  776. protected function GetObjectAt($iIndex)
  777. {
  778. if (!$this->m_bLoaded) $this->Load();
  779. // Save the current position for iteration
  780. $iCurrPos = $this->m_iCurrRow;
  781. $this->Seek($iIndex);
  782. $oObject = $this->Fetch();
  783. // Restore the current position for iteration
  784. $this->Seek($this->m_iCurrRow);
  785. return $oObject;
  786. }
  787. /**
  788. * Build a new set (in memory) made of objects of the given set which are NOT present in the current set
  789. *
  790. * Limitations:
  791. * The objects inside the set must be written in the database since the comparison is based on their identifiers
  792. * Sets with several objects per row are NOT supported
  793. *
  794. * @param DBObjectSet $oObjectSet
  795. * @throws CoreException
  796. *
  797. * @return DBObjectSet The "delta" set.
  798. */
  799. public function CreateDelta(DBObjectSet $oObjectSet)
  800. {
  801. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  802. {
  803. throw new CoreException("Could not 'delta' two objects sets if they don't have the same root class");
  804. }
  805. if (!$this->m_bLoaded) $this->Load();
  806. $aId2Row = array();
  807. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  808. $idx = 0;
  809. while($oObj = $this->Fetch())
  810. {
  811. $aId2Row[$oObj->GetKey()] = $idx;
  812. $idx++;
  813. }
  814. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  815. $oObjectSet->Seek(0);
  816. while ($oObject = $oObjectSet->Fetch())
  817. {
  818. if (!array_key_exists($oObject->GetKey(), $aId2Row))
  819. {
  820. $oNewSet->AddObject($oObject);
  821. }
  822. }
  823. $this->Seek($iCurrPos); // Restore the cursor
  824. return $oNewSet;
  825. }
  826. /**
  827. * Will be deprecated soon - use MetaModel::GetRelatedObjectsDown/Up instead to take redundancy into account
  828. */
  829. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99)
  830. {
  831. $aRelatedObjs = array();
  832. $aVisited = array(); // optimization for consecutive calls of MetaModel::GetRelatedObjects
  833. $this->Seek(0);
  834. while ($oObject = $this->Fetch())
  835. {
  836. $aMore = $oObject->GetRelatedObjects($sRelCode, $iMaxDepth, $aVisited);
  837. foreach ($aMore as $sClass => $aRelated)
  838. {
  839. foreach ($aRelated as $iObj => $oObj)
  840. {
  841. if (!isset($aRelatedObjs[$sClass][$iObj]))
  842. {
  843. $aRelatedObjs[$sClass][$iObj] = $oObj;
  844. }
  845. }
  846. }
  847. }
  848. return $aRelatedObjs;
  849. }
  850. /**
  851. * Compute the "RelatedObjects" (forward or "down" direction) for the set
  852. * for the specified relation
  853. *
  854. * @param string $sRelCode The code of the relation to use for the computation
  855. * @param int $iMaxDepth Maximum recursion depth
  856. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  857. *
  858. * @return RelationGraph The graph of all the related objects
  859. */
  860. public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  861. {
  862. $oGraph = new RelationGraph();
  863. $this->Rewind();
  864. while($oObj = $this->Fetch())
  865. {
  866. $oGraph->AddSourceObject($oObj);
  867. }
  868. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy);
  869. return $oGraph;
  870. }
  871. /**
  872. * Compute the "RelatedObjects" (reverse or "up" direction) for the set
  873. * for the specified relation
  874. *
  875. * @param string $sRelCode The code of the relation to use for the computation
  876. * @param int $iMaxDepth Maximum recursion depth
  877. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  878. *
  879. * @return RelationGraph The graph of all the related objects
  880. */
  881. public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  882. {
  883. $oGraph = new RelationGraph();
  884. $this->Rewind();
  885. while($oObj = $this->Fetch())
  886. {
  887. $oGraph->AddSinkObject($oObj);
  888. }
  889. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  890. return $oGraph;
  891. }
  892. /**
  893. * Builds an object that contains the values that are common to all the objects
  894. * in the set. If for a given attribute, objects in the set have various values
  895. * then the resulting object will contain null for this value.
  896. * @param $aValues Hash Output: the distribution of the values, in the set, for each attribute
  897. * @return DBObject The object with the common values
  898. */
  899. public function ComputeCommonObject(&$aValues)
  900. {
  901. $sClass = $this->GetClass();
  902. $aList = MetaModel::ListAttributeDefs($sClass);
  903. $aValues = array();
  904. foreach($aList as $sAttCode => $oAttDef)
  905. {
  906. if ($oAttDef->IsScalar())
  907. {
  908. $aValues[$sAttCode] = array();
  909. }
  910. }
  911. $this->Rewind();
  912. while($oObj = $this->Fetch())
  913. {
  914. foreach($aList as $sAttCode => $oAttDef)
  915. {
  916. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  917. {
  918. $currValue = $oObj->Get($sAttCode);
  919. if (is_object($currValue)) continue; // Skip non scalar values...
  920. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  921. {
  922. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  923. }
  924. else
  925. {
  926. $aValues[$sAttCode][$currValue]['count']++;
  927. }
  928. }
  929. }
  930. }
  931. foreach($aValues as $sAttCode => $aMultiValues)
  932. {
  933. if (count($aMultiValues) > 1)
  934. {
  935. uasort($aValues[$sAttCode], 'HashCountComparison');
  936. }
  937. }
  938. // Now create an object that has values for the homogenous values only
  939. $oCommonObj = new $sClass(); // @@ What if the class is abstract ?
  940. $aComments = array();
  941. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  942. $sReadyScript = '';
  943. $aDependsOn = array();
  944. $sFormPrefix = '2_';
  945. foreach($aList as $sAttCode => $oAttDef)
  946. {
  947. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  948. {
  949. if ($oAttDef->GetEditClass() == 'One Way Password')
  950. {
  951. $oCommonObj->Set($sAttCode, null);
  952. }
  953. else
  954. {
  955. $iCount = count($aValues[$sAttCode]);
  956. if ($iCount == 1)
  957. {
  958. // Homogenous value
  959. reset($aValues[$sAttCode]);
  960. $aKeys = array_keys($aValues[$sAttCode]);
  961. $currValue = $aKeys[0]; // The only value is the first key
  962. $oCommonObj->Set($sAttCode, $currValue);
  963. }
  964. else
  965. {
  966. // Non-homogenous value
  967. $oCommonObj->Set($sAttCode, null);
  968. }
  969. }
  970. }
  971. }
  972. $this->Rewind();
  973. return $oCommonObj;
  974. }
  975. /**
  976. * List the constant fields (and their value) in the given query
  977. * @return Hash [Alias][AttCode] => value
  978. */
  979. public function ListConstantFields()
  980. {
  981. $aScalarArgs = $this->ExpandArgs();
  982. $aConst = $this->m_oFilter->ListConstantFields();
  983. foreach($aConst as $sClassAlias => $aVals)
  984. {
  985. foreach($aVals as $sCode => $oExpr)
  986. {
  987. if (is_object($oExpr)) // Array_merge_recursive creates an array when the same key is present multiple times... ignore them
  988. {
  989. $oScalarExpr = $oExpr->GetAsScalar($aScalarArgs);
  990. $aConst[$sClassAlias][$sCode] = $oScalarExpr->GetValue();
  991. }
  992. }
  993. }
  994. return $aConst;
  995. }
  996. protected function ExpandArgs()
  997. {
  998. $aScalarArgs = $this->m_oFilter->GetInternalParams();
  999. foreach($this->m_aArgs as $sArgName => $value)
  1000. {
  1001. if (MetaModel::IsValidObject($value))
  1002. {
  1003. if (strpos($sArgName, '->object()') === false)
  1004. {
  1005. // Lazy syntax - develop the object contextual parameters
  1006. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgsForQuery($sArgName));
  1007. }
  1008. else
  1009. {
  1010. // Leave as is
  1011. $aScalarArgs[$sArgName] = $value;
  1012. }
  1013. }
  1014. else
  1015. {
  1016. if (!is_array($value)) // Sometimes ExtraParams contains a mix (like defaults[]) so non scalar parameters are ignored
  1017. {
  1018. $aScalarArgs[$sArgName] = (string) $value;
  1019. }
  1020. }
  1021. }
  1022. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1023. return $aScalarArgs;
  1024. }
  1025. public function ApplyParameters()
  1026. {
  1027. $aScalarArgs = $this->ExpandArgs();
  1028. $this->m_oFilter->ApplyParameters($aScalarArgs);
  1029. }
  1030. }
  1031. /**
  1032. * Helper function to perform a custom sort of a hash array
  1033. */
  1034. function HashCountComparison($a, $b) // Sort descending on 'count'
  1035. {
  1036. if ($a['count'] == $b['count'])
  1037. {
  1038. return 0;
  1039. }
  1040. return ($a['count'] > $b['count']) ? -1 : 1;
  1041. }
  1042. /**
  1043. * Helper class to compare the content of two DBObjectSets based on the fingerprints of the contained objects
  1044. * When computing the actual differences, the algorithm tries to preserve as much as possible the existing
  1045. * objects (i.e. prefers 'modified' to 'removed' + 'added')
  1046. *
  1047. * LIMITATION: only DBObjectSets with one column (i.e. one class of object selected) are supported
  1048. */
  1049. class DBObjectSetComparator
  1050. {
  1051. protected $aFingerprints1;
  1052. protected $aFingerprints2;
  1053. protected $aIDs1;
  1054. protected $aIDs2;
  1055. protected $aExcludedColumns;
  1056. protected $oSet1;
  1057. protected $oSet2;
  1058. protected $sAdditionalKeyColumn;
  1059. protected $aAdditionalKeys;
  1060. /**
  1061. * Initializes the comparator
  1062. * @param DBObjectSet $oSet1 The first set of objects to compare, or null
  1063. * @param DBObjectSet $oSet2 The second set of objects to compare, or null
  1064. * @param array $aExcludedColumns The list of columns (= attribute codes) to exclude from the comparison
  1065. * @param string $sAdditionalKeyColumn The attribute code of an additional column to be considered as a key indentifying the object (useful for n:n links)
  1066. */
  1067. public function __construct($oSet1, $oSet2, $aExcludedColumns = array(), $sAdditionalKeyColumn = null)
  1068. {
  1069. $this->aFingerprints1 = null;
  1070. $this->aFingerprints2 = null;
  1071. $this->aIDs1 = array();
  1072. $this->aIDs2 = array();
  1073. $this->aExcludedColumns = $aExcludedColumns;
  1074. $this->sAdditionalKeyColumn = $sAdditionalKeyColumn;
  1075. $this->aAdditionalKeys = null;
  1076. $this->oSet1 = $oSet1;
  1077. $this->oSet2 = $oSet2;
  1078. }
  1079. /**
  1080. * Builds the lists of fingerprints and initializes internal structures, if it was not already done
  1081. */
  1082. protected function ComputeFingerprints()
  1083. {
  1084. if ($this->aFingerprints1 === null)
  1085. {
  1086. $this->aFingerprints1 = array();
  1087. $this->aFingerprints2 = array();
  1088. $this->aAdditionalKeys = array();
  1089. if ($this->oSet1 !== null)
  1090. {
  1091. $aAliases = $this->oSet1->GetSelectedClasses();
  1092. if (count($aAliases) > 1) throw new Exception('DBObjectSetComparator does not support Sets with more than one column. $oSet1: ('.print_r($aAliases, true).')');
  1093. $this->oSet1->Rewind();
  1094. while($oObj = $this->oSet1->Fetch())
  1095. {
  1096. $sFingerprint = $oObj->Fingerprint($this->aExcludedColumns);
  1097. $this->aFingerprints1[$sFingerprint] = $oObj;
  1098. if (!$oObj->IsNew())
  1099. {
  1100. $this->aIDs1[$oObj->GetKey()] = $oObj;
  1101. }
  1102. }
  1103. $this->oSet1->Rewind();
  1104. }
  1105. if ($this->oSet2 !== null)
  1106. {
  1107. $aAliases = $this->oSet2->GetSelectedClasses();
  1108. if (count($aAliases) > 1) throw new Exception('DBObjectSetComparator does not support Sets with more than one column. $oSet2: ('.print_r($aAliases, true).')');
  1109. $this->oSet2->Rewind();
  1110. while($oObj = $this->oSet2->Fetch())
  1111. {
  1112. $sFingerprint = $oObj->Fingerprint($this->aExcludedColumns);
  1113. $this->aFingerprints2[$sFingerprint] = $oObj;
  1114. if (!$oObj->IsNew())
  1115. {
  1116. $this->aIDs2[$oObj->GetKey()] = $oObj;
  1117. }
  1118. if ($this->sAdditionalKeyColumn !== null)
  1119. {
  1120. $this->aAdditionalKeys[$oObj->Get($this->sAdditionalKeyColumn)] = $oObj;
  1121. }
  1122. }
  1123. $this->oSet2->Rewind();
  1124. }
  1125. }
  1126. }
  1127. /**
  1128. * Tells if the sets are equivalent or not. Returns as soon as the first difference is found.
  1129. * @return boolean true if the set have an equivalent content, false otherwise
  1130. */
  1131. public function SetsAreEquivalent()
  1132. {
  1133. if (($this->oSet1 === null) && ($this->oSet2 === null))
  1134. {
  1135. // Both sets are empty, they are equal
  1136. return true;
  1137. }
  1138. else if (($this->oSet1 === null) || ($this->oSet2 === null))
  1139. {
  1140. // one of them is empty, they are different
  1141. return false;
  1142. }
  1143. if (($this->oSet1->GetRootClass() != $this->oSet2->GetRootClass()) || ($this->oSet1->Count() != $this->oSet2->Count())) return false;
  1144. $this->ComputeFingerprints();
  1145. // Check that all objects in Set1 are also in Set2
  1146. foreach($this->aFingerprints1 as $sFingerprint => $oObj)
  1147. {
  1148. if (!array_key_exists($sFingerprint, $this->aFingerprints2))
  1149. {
  1150. return false;
  1151. }
  1152. }
  1153. // Vice versa
  1154. // Check that all objects in Set2 are also in Set1
  1155. foreach($this->aFingerprints2 as $sFingerprint => $oObj)
  1156. {
  1157. if (!array_key_exists($sFingerprint, $this->aFingerprints1))
  1158. {
  1159. return false;
  1160. }
  1161. }
  1162. return true;
  1163. }
  1164. /**
  1165. * Get the list of differences between the two sets.
  1166. * Returns a hash: 'added' => DBObject(s), 'removed' => DBObject(s), 'modified' => DBObjects(s)
  1167. * @return Ambigous <int:DBObject: , unknown>
  1168. */
  1169. public function GetDifferences()
  1170. {
  1171. $aResult = array('added' => array(), 'removed' => array(), 'modified' => array());
  1172. $this->ComputeFingerprints();
  1173. // Check that all objects in Set1 are also in Set2
  1174. foreach($this->aFingerprints1 as $sFingerprint => $oObj)
  1175. {
  1176. if (array_key_exists($oObj->GetKey(), $this->aIDs2) && ($this->aIDs2[$oObj->GetKey()]->IsModified()))
  1177. {
  1178. // The very same object exists in both set, but was modified since its load
  1179. $aResult['modified'][$oObj->GetKey()] = $this->aIDs2[$oObj->GetKey()];
  1180. }
  1181. else if (($this->sAdditionalKeyColumn !== null) && array_key_exists($oObj->Get($this->sAdditionalKeyColumn), $this->aAdditionalKeys))
  1182. {
  1183. // Special case for n:n links where the link is recreated between the very same 2 objects, but some of its attributes are modified
  1184. // Let's consider this as a "modification" instead of "deletion" + "creation" in order to have a "clean" history for the objects
  1185. $oDestObj = $this->aAdditionalKeys[$oObj->Get($this->sAdditionalKeyColumn)];
  1186. $oCloneObj = $this->CopyFrom($oObj, $oDestObj);
  1187. $aResult['modified'][$oObj->GetKey()] = $oCloneObj;
  1188. // Mark this as processed, so that the pass on aFingerprints2 below ignores this object
  1189. $sNewFingerprint = $oDestObj->Fingerprint($this->aExcludedColumns);
  1190. $this->aFingerprints2[$sNewFingerprint] = $oCloneObj;
  1191. }
  1192. else if (!array_key_exists($sFingerprint, $this->aFingerprints2))
  1193. {
  1194. $aResult['removed'][] = $oObj;
  1195. }
  1196. }
  1197. // Vice versa
  1198. // Check that all objects in Set2 are also in Set1
  1199. foreach($this->aFingerprints2 as $sFingerprint => $oObj)
  1200. {
  1201. if (array_key_exists($oObj->GetKey(), $this->aIDs1) && ($oObj->IsModified()))
  1202. {
  1203. // Already marked as modified above
  1204. //$aResult['modified'][$oObj->GetKey()] = $oObj;
  1205. }
  1206. else if (!array_key_exists($sFingerprint, $this->aFingerprints1))
  1207. {
  1208. $aResult['added'][] = $oObj;
  1209. }
  1210. }
  1211. return $aResult;
  1212. }
  1213. /**
  1214. * Helpr to clone (in memory) an object and to apply to it the values taken from a second object
  1215. * @param DBObject $oObjToClone
  1216. * @param DBObject $oObjWithValues
  1217. * @return DBObject The modified clone
  1218. */
  1219. protected function CopyFrom($oObjToClone, $oObjWithValues)
  1220. {
  1221. $oObj = MetaModel::GetObject(get_class($oObjToClone), $oObjToClone->GetKey());
  1222. foreach(MetaModel::ListAttributeDefs(get_class($oObj)) as $sAttCode => $oAttDef)
  1223. {
  1224. if (!in_array($sAttCode, $this->aExcludedColumns) && $oAttDef->IsWritable())
  1225. {
  1226. $oObj->Set($sAttCode, $oObjWithValues->Get($sAttCode));
  1227. }
  1228. }
  1229. return $oObj;
  1230. }
  1231. }