dbobjectset.class.php 40 KB

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