dbobjectset.class.php 43 KB

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