dbobjectset.class.php 41 KB

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