dbobjectset.class.php 41 KB

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