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