dbobjectset.class.php 41 KB

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