dbobjectset.class.php 42 KB

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