dbobjectset.class.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  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. $sSQL = $this->_makeSelectQuery($this->m_aAttToLoad);
  579. if (is_object($this->m_oSQLResult))
  580. {
  581. // Free previous resultset if any
  582. $this->m_oSQLResult->free();
  583. $this->m_oSQLResult = null;
  584. }
  585. $this->m_iNumTotalDBRows = null;
  586. try
  587. {
  588. $this->m_oSQLResult = CMDBSource::Query($sSQL);
  589. } catch (MySQLException $e)
  590. {
  591. // 1116 = ER_TOO_MANY_TABLES
  592. // https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html#error_er_too_many_tables
  593. if ($e->getCode() != 1116)
  594. {
  595. throw $e;
  596. }
  597. // N.689 Workaround for the 61 max joins in MySQL : full lazy load !
  598. $aAttToLoad = array();
  599. foreach($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  600. {
  601. $aAttToLoad[$sClassAlias] = array();
  602. $bIsAbstractClass = MetaModel::IsAbstract($sClass);
  603. $bIsClassWithChildren = MetaModel::HasChildrenClasses($sClass);
  604. if ($bIsAbstractClass || $bIsClassWithChildren)
  605. {
  606. // we need finalClass field at least to be able to instantiate the real corresponding object !
  607. $aAttToLoad[$sClassAlias]['finalclass'] = MetaModel::GetAttributeDef($sClass, 'finalclass');
  608. }
  609. }
  610. $sSQL = $this->_makeSelectQuery($aAttToLoad);
  611. $this->m_oSQLResult = CMDBSource::Query($sSQL); // may fail again
  612. }
  613. if ($this->m_oSQLResult === false) return;
  614. if (($this->m_iLimitCount == 0) && ($this->m_iLimitStart == 0))
  615. {
  616. $this->m_iNumTotalDBRows = $this->m_oSQLResult->num_rows;
  617. }
  618. $this->m_iNumLoadedDBRows = $this->m_oSQLResult->num_rows;
  619. }
  620. /**
  621. * @param string[] $aAttToLoad
  622. *
  623. * @return string SQL query
  624. */
  625. private function _makeSelectQuery($aAttToLoad)
  626. {
  627. if ($this->m_iLimitCount > 0)
  628. {
  629. $sSQL = $this->m_oFilter->MakeSelectQuery($this->GetRealSortOrder(), $this->m_aArgs, $aAttToLoad,
  630. $this->m_aExtendedDataSpec, $this->m_iLimitCount, $this->m_iLimitStart);
  631. }
  632. else
  633. {
  634. $sSQL = $this->m_oFilter->MakeSelectQuery($this->GetRealSortOrder(), $this->m_aArgs, $aAttToLoad,
  635. $this->m_aExtendedDataSpec);
  636. }
  637. return $sSQL;
  638. }
  639. /**
  640. * The total number of rows in this set. Independently of the SetLimit used for loading the set and taking into
  641. * account the rows added in-memory.
  642. *
  643. * May actually perform the SQL query SELECT COUNT... if the set was not previously loaded, or loaded with a
  644. * SetLimit
  645. *
  646. * @return int The total number of rows for this set.
  647. */
  648. public function Count()
  649. {
  650. if (is_null($this->m_iNumTotalDBRows))
  651. {
  652. $sSQL = $this->m_oFilter->MakeSelectQuery(array(), $this->m_aArgs, null, null, 0, 0, true);
  653. $resQuery = CMDBSource::Query($sSQL);
  654. if (!$resQuery) return 0;
  655. $aRow = CMDBSource::FetchArray($resQuery);
  656. CMDBSource::FreeResult($resQuery);
  657. $this->m_iNumTotalDBRows = $aRow['COUNT'];
  658. }
  659. return $this->m_iNumTotalDBRows + count($this->m_aAddedObjects); // Does it fix Trac #887 ??
  660. }
  661. /**
  662. * Number of rows available in memory (loaded from DB + added in memory)
  663. *
  664. * @return number The number of rows available for Fetch'ing
  665. */
  666. protected function CountLoaded()
  667. {
  668. return $this->m_iNumLoadedDBRows + count($this->m_aAddedObjects);
  669. }
  670. /**
  671. * Fetch the object (with the given class alias) at the current position in the set and move the cursor to the next position.
  672. *
  673. * @param string $sRequestedClassAlias The class alias to fetch (if there are several objects/classes per row)
  674. * @return DBObject The fetched object or null when at the end
  675. */
  676. public function Fetch($sRequestedClassAlias = '')
  677. {
  678. if (!$this->m_bLoaded) $this->Load();
  679. if ($this->m_iCurrRow >= $this->CountLoaded())
  680. {
  681. return null;
  682. }
  683. if (strlen($sRequestedClassAlias) == 0)
  684. {
  685. $sRequestedClassAlias = $this->m_oFilter->GetClassAlias();
  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. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  692. {
  693. if ($sRequestedClassAlias == $sClassAlias)
  694. {
  695. if (is_null($aRow[$sClassAlias.'id']))
  696. {
  697. $oRetObj = null;
  698. }
  699. else
  700. {
  701. $oRetObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  702. }
  703. break;
  704. }
  705. }
  706. }
  707. else
  708. {
  709. // Pick the row from the objects added *in memory*
  710. $oRetObj = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sRequestedClassAlias];
  711. }
  712. $this->m_iCurrRow++;
  713. return $oRetObj;
  714. }
  715. /**
  716. * Fetch the whole row of objects (if several classes have been specified in the query) and move the cursor to the next position
  717. *
  718. * @return hash A hash with the format 'classAlias' => $oObj representing the current row of the set. Returns null when at the end.
  719. */
  720. public function FetchAssoc()
  721. {
  722. if (!$this->m_bLoaded) $this->Load();
  723. if ($this->m_iCurrRow >= $this->CountLoaded())
  724. {
  725. return null;
  726. }
  727. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  728. {
  729. // Pick the row from the database
  730. $aRow = CMDBSource::FetchArray($this->m_oSQLResult);
  731. $aRetObjects = array();
  732. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  733. {
  734. if (is_null($aRow[$sClassAlias.'id']))
  735. {
  736. $oObj = null;
  737. }
  738. else
  739. {
  740. $oObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  741. }
  742. $aRetObjects[$sClassAlias] = $oObj;
  743. }
  744. }
  745. else
  746. {
  747. // Pick the row from the objects added *in memory*
  748. $aRetObjects = array();
  749. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  750. {
  751. $aRetObjects[$sClassAlias] = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sClassAlias];
  752. }
  753. }
  754. $this->m_iCurrRow++;
  755. return $aRetObjects;
  756. }
  757. /**
  758. * Position the cursor (for iterating in the set) to the first position (equivalent to Seek(0))
  759. */
  760. public function Rewind()
  761. {
  762. if ($this->m_bLoaded)
  763. {
  764. $this->Seek(0);
  765. }
  766. }
  767. /**
  768. * Position the cursor (for iterating in the set) to the given position
  769. *
  770. * @param int $iRow
  771. */
  772. public function Seek($iRow)
  773. {
  774. if (!$this->m_bLoaded) $this->Load();
  775. $this->m_iCurrRow = min($iRow, $this->Count());
  776. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  777. {
  778. $this->m_oSQLResult->data_seek($this->m_iCurrRow);
  779. }
  780. return $this->m_iCurrRow;
  781. }
  782. /**
  783. * Add an object to the current set (in-memory only, nothing is written to the database)
  784. *
  785. * Limitation:
  786. * Sets with several objects per row are NOT supported
  787. *
  788. * @param DBObject $oObject The object to add
  789. * @param string $sClassAlias The alias for the class of the object
  790. */
  791. public function AddObject($oObject, $sClassAlias = '')
  792. {
  793. if (!$this->m_bLoaded) $this->Load();
  794. if (strlen($sClassAlias) == 0)
  795. {
  796. $sClassAlias = $this->m_oFilter->GetClassAlias();
  797. }
  798. $iNextPos = count($this->m_aAddedObjects);
  799. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  800. if (!is_null($oObject))
  801. {
  802. $this->m_aAddedIds[$oObject->GetKey()] = true;
  803. }
  804. }
  805. /**
  806. * Add a hash containig objects into the current set.
  807. *
  808. * The expected format for the hash is: $aObjectArray[$idx][$sClassAlias] => $oObject
  809. * Limitation:
  810. * The aliases MUST match the ones used in the current set
  811. * Only the ID of the objects associated to the first alias (column) is remembered.. in case we have to rebuild a filter
  812. *
  813. * @param hash $aObjectArray
  814. */
  815. protected function AddObjectExtended($aObjectArray)
  816. {
  817. if (!$this->m_bLoaded) $this->Load();
  818. $iNextPos = count($this->m_aAddedObjects);
  819. $sFirstAlias = $this->m_oFilter->GetClassAlias();
  820. foreach ($aObjectArray as $sClassAlias => $oObject)
  821. {
  822. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  823. if (!is_null($oObject) && ($sFirstAlias == $sClassAlias))
  824. {
  825. $this->m_aAddedIds[$oObject->GetKey()] = true;
  826. }
  827. }
  828. }
  829. /**
  830. * Add an array of objects into the current set
  831. *
  832. * Limitation:
  833. * Sets with several classes per row are not supported (use AddObjectExtended instead)
  834. *
  835. * @param array $aObjects The array of objects to add
  836. * @param string $sClassAlias The Alias of the class for the added objects
  837. */
  838. public function AddObjectArray($aObjects, $sClassAlias = '')
  839. {
  840. if (!$this->m_bLoaded) $this->Load();
  841. // #@# todo - add a check on the object class ?
  842. foreach ($aObjects as $oObj)
  843. {
  844. $this->AddObject($oObj, $sClassAlias);
  845. }
  846. }
  847. /**
  848. * Append a given set to the current object. (This method used to be named Merge)
  849. *
  850. * Limitation:
  851. * 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).
  852. *
  853. * @param DBObjectSet $oObjectSet The set to append
  854. * @throws CoreException
  855. */
  856. public function Append(DBObjectSet $oObjectSet)
  857. {
  858. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  859. {
  860. throw new CoreException("Could not merge two objects sets if they don't have the same root class");
  861. }
  862. if (!$this->m_bLoaded) $this->Load();
  863. $oObjectSet->Seek(0);
  864. while ($oObject = $oObjectSet->Fetch())
  865. {
  866. $this->AddObject($oObject);
  867. }
  868. }
  869. /**
  870. * Create a set containing the objects present in both the current set and another specified set
  871. *
  872. * Limitations:
  873. * Will NOT work if only a subset of the sets was loaded with SetLimit.
  874. * Works only with sets made of objects loaded from the database since the comparison is based on the objects identifiers
  875. *
  876. * @param DBObjectSet $oObjectSet The set to intersect with. The current position inside the set will be lost (= at the end)
  877. * @throws CoreException
  878. * @return DBObjectSet A new set of objects, containing the objects present in both sets (based on their identifier)
  879. */
  880. public function CreateIntersect(DBObjectSet $oObjectSet)
  881. {
  882. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  883. {
  884. throw new CoreException("Could not 'intersect' two objects sets if they don't have the same root class");
  885. }
  886. if (!$this->m_bLoaded) $this->Load();
  887. $aId2Row = array();
  888. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  889. $idx = 0;
  890. while($oObj = $this->Fetch())
  891. {
  892. $aId2Row[$oObj->GetKey()] = $idx;
  893. $idx++;
  894. }
  895. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  896. $oObjectSet->Seek(0);
  897. while ($oObject = $oObjectSet->Fetch())
  898. {
  899. if (array_key_exists($oObject->GetKey(), $aId2Row))
  900. {
  901. $oNewSet->AddObject($oObject);
  902. }
  903. }
  904. $this->Seek($iCurrPos); // Restore the cursor
  905. return $oNewSet;
  906. }
  907. /**
  908. * Compare two sets of objects to determine if their content is identical or not.
  909. *
  910. * Limitation:
  911. * Works only for sets of 1 column (i.e. one class of object selected)
  912. *
  913. * @param DBObjectSet $oObjectSet
  914. * @param array $aExcludeColumns The list of columns to exclude frop the comparison
  915. * @return boolean True if the sets are identical, false otherwise
  916. */
  917. public function HasSameContents(DBObjectSet $oObjectSet, $aExcludeColumns = array())
  918. {
  919. $oComparator = new DBObjectSetComparator($this, $oObjectSet, $aExcludeColumns);
  920. return $oComparator->SetsAreEquivalent();
  921. }
  922. /**
  923. * Build a new set (in memory) made of objects of the given set which are NOT present in the current set
  924. *
  925. * Limitations:
  926. * The objects inside the set must be written in the database since the comparison is based on their identifiers
  927. * Sets with several objects per row are NOT supported
  928. *
  929. * @param DBObjectSet $oObjectSet
  930. * @throws CoreException
  931. *
  932. * @return DBObjectSet The "delta" set.
  933. */
  934. public function CreateDelta(DBObjectSet $oObjectSet)
  935. {
  936. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  937. {
  938. throw new CoreException("Could not 'delta' two objects sets if they don't have the same root class");
  939. }
  940. if (!$this->m_bLoaded) $this->Load();
  941. $aId2Row = array();
  942. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  943. $idx = 0;
  944. while($oObj = $this->Fetch())
  945. {
  946. $aId2Row[$oObj->GetKey()] = $idx;
  947. $idx++;
  948. }
  949. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  950. $oObjectSet->Seek(0);
  951. while ($oObject = $oObjectSet->Fetch())
  952. {
  953. if (!array_key_exists($oObject->GetKey(), $aId2Row))
  954. {
  955. $oNewSet->AddObject($oObject);
  956. }
  957. }
  958. $this->Seek($iCurrPos); // Restore the cursor
  959. return $oNewSet;
  960. }
  961. /**
  962. * Will be deprecated soon - use MetaModel::GetRelatedObjectsDown/Up instead to take redundancy into account
  963. */
  964. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99)
  965. {
  966. $aRelatedObjs = array();
  967. $aVisited = array(); // optimization for consecutive calls of MetaModel::GetRelatedObjects
  968. $this->Seek(0);
  969. while ($oObject = $this->Fetch())
  970. {
  971. $aMore = $oObject->GetRelatedObjects($sRelCode, $iMaxDepth, $aVisited);
  972. foreach ($aMore as $sClass => $aRelated)
  973. {
  974. foreach ($aRelated as $iObj => $oObj)
  975. {
  976. if (!isset($aRelatedObjs[$sClass][$iObj]))
  977. {
  978. $aRelatedObjs[$sClass][$iObj] = $oObj;
  979. }
  980. }
  981. }
  982. }
  983. return $aRelatedObjs;
  984. }
  985. /**
  986. * Compute the "RelatedObjects" (forward or "down" direction) for the set
  987. * for the specified relation
  988. *
  989. * @param string $sRelCode The code of the relation to use for the computation
  990. * @param int $iMaxDepth Maximum recursion depth
  991. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  992. *
  993. * @return RelationGraph The graph of all the related objects
  994. */
  995. public function GetRelatedObjectsDown($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  996. {
  997. $oGraph = new RelationGraph();
  998. $this->Rewind();
  999. while($oObj = $this->Fetch())
  1000. {
  1001. $oGraph->AddSourceObject($oObj);
  1002. }
  1003. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy);
  1004. return $oGraph;
  1005. }
  1006. /**
  1007. * Compute the "RelatedObjects" (reverse or "up" direction) for the set
  1008. * for the specified relation
  1009. *
  1010. * @param string $sRelCode The code of the relation to use for the computation
  1011. * @param int $iMaxDepth Maximum recursion depth
  1012. * @param boolean $bEnableReduncancy Whether or not to take into account the redundancy
  1013. *
  1014. * @return RelationGraph The graph of all the related objects
  1015. */
  1016. public function GetRelatedObjectsUp($sRelCode, $iMaxDepth = 99, $bEnableRedundancy = true)
  1017. {
  1018. $oGraph = new RelationGraph();
  1019. $this->Rewind();
  1020. while($oObj = $this->Fetch())
  1021. {
  1022. $oGraph->AddSinkObject($oObj);
  1023. }
  1024. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  1025. return $oGraph;
  1026. }
  1027. /**
  1028. * Builds an object that contains the values that are common to all the objects
  1029. * in the set. If for a given attribute, objects in the set have various values
  1030. * then the resulting object will contain null for this value.
  1031. * @param $aValues Hash Output: the distribution of the values, in the set, for each attribute
  1032. * @return DBObject The object with the common values
  1033. */
  1034. public function ComputeCommonObject(&$aValues)
  1035. {
  1036. $sClass = $this->GetClass();
  1037. $aList = MetaModel::ListAttributeDefs($sClass);
  1038. $aValues = array();
  1039. foreach($aList as $sAttCode => $oAttDef)
  1040. {
  1041. if ($oAttDef->IsScalar())
  1042. {
  1043. $aValues[$sAttCode] = array();
  1044. }
  1045. }
  1046. $this->Rewind();
  1047. while($oObj = $this->Fetch())
  1048. {
  1049. foreach($aList as $sAttCode => $oAttDef)
  1050. {
  1051. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  1052. {
  1053. $currValue = $oObj->Get($sAttCode);
  1054. if (is_object($currValue)) continue; // Skip non scalar values...
  1055. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  1056. {
  1057. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  1058. }
  1059. else
  1060. {
  1061. $aValues[$sAttCode][$currValue]['count']++;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. foreach($aValues as $sAttCode => $aMultiValues)
  1067. {
  1068. if (count($aMultiValues) > 1)
  1069. {
  1070. uasort($aValues[$sAttCode], 'HashCountComparison');
  1071. }
  1072. }
  1073. // Now create an object that has values for the homogenous values only
  1074. $oCommonObj = new $sClass(); // @@ What if the class is abstract ?
  1075. $aComments = array();
  1076. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  1077. $sReadyScript = '';
  1078. $aDependsOn = array();
  1079. $sFormPrefix = '2_';
  1080. foreach($aList as $sAttCode => $oAttDef)
  1081. {
  1082. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  1083. {
  1084. if ($oAttDef->GetEditClass() == 'One Way Password')
  1085. {
  1086. $oCommonObj->Set($sAttCode, null);
  1087. }
  1088. else
  1089. {
  1090. $iCount = count($aValues[$sAttCode]);
  1091. if ($iCount == 1)
  1092. {
  1093. // Homogenous value
  1094. reset($aValues[$sAttCode]);
  1095. $aKeys = array_keys($aValues[$sAttCode]);
  1096. $currValue = $aKeys[0]; // The only value is the first key
  1097. $oCommonObj->Set($sAttCode, $currValue);
  1098. }
  1099. else
  1100. {
  1101. // Non-homogenous value
  1102. $oCommonObj->Set($sAttCode, null);
  1103. }
  1104. }
  1105. }
  1106. }
  1107. $this->Rewind();
  1108. return $oCommonObj;
  1109. }
  1110. /**
  1111. * List the constant fields (and their value) in the given query
  1112. * @return Hash [Alias][AttCode] => value
  1113. */
  1114. public function ListConstantFields()
  1115. {
  1116. // The complete list of arguments will include magic arguments (e.g. current_user->attcode)
  1117. $aScalarArgs = MetaModel::PrepareQueryArguments($this->m_oFilter->GetInternalParams(), $this->m_aArgs);
  1118. $aConst = $this->m_oFilter->ListConstantFields();
  1119. foreach($aConst as $sClassAlias => $aVals)
  1120. {
  1121. foreach($aVals as $sCode => $oExpr)
  1122. {
  1123. if (is_object($oExpr)) // Array_merge_recursive creates an array when the same key is present multiple times... ignore them
  1124. {
  1125. $oScalarExpr = $oExpr->GetAsScalar($aScalarArgs);
  1126. $aConst[$sClassAlias][$sCode] = $oScalarExpr->GetValue();
  1127. }
  1128. }
  1129. }
  1130. return $aConst;
  1131. }
  1132. public function ApplyParameters()
  1133. {
  1134. $aAllArgs = MetaModel::PrepareQueryArguments($this->m_oFilter->GetInternalParams(), $this->m_aArgs);
  1135. $this->m_oFilter->ApplyParameters($aAllArgs);
  1136. }
  1137. }
  1138. /**
  1139. * Helper function to perform a custom sort of a hash array
  1140. */
  1141. function HashCountComparison($a, $b) // Sort descending on 'count'
  1142. {
  1143. if ($a['count'] == $b['count'])
  1144. {
  1145. return 0;
  1146. }
  1147. return ($a['count'] > $b['count']) ? -1 : 1;
  1148. }
  1149. /**
  1150. * Helper class to compare the content of two DBObjectSets based on the fingerprints of the contained objects
  1151. * The FIRST SET MUST BE LOADED FROM THE DATABASE, the second one can be a set of objects in memory
  1152. * When computing the actual differences, the algorithm tries to preserve as much as possible the EXISTING
  1153. * objects (i.e. prefers 'modified' to 'removed' + 'added')
  1154. *
  1155. * LIMITATIONS:
  1156. * - only DBObjectSets with one column (i.e. one class of object selected) are supported
  1157. * - the first set must be the one loaded from the database
  1158. */
  1159. class DBObjectSetComparator
  1160. {
  1161. protected $aFingerprints1;
  1162. protected $aFingerprints2;
  1163. protected $aIDs1;
  1164. protected $aIDs2;
  1165. protected $aExcludedColumns;
  1166. /**
  1167. * @var iDBObjectSetIterator
  1168. */
  1169. protected $oSet1;
  1170. /**
  1171. * @var iDBObjectSetIterator
  1172. */
  1173. protected $oSet2;
  1174. protected $sAdditionalKeyColumn;
  1175. protected $aAdditionalKeys;
  1176. /**
  1177. * Initializes the comparator
  1178. * @param iDBObjectSetIterator $oSet1 The first set of objects to compare, or null
  1179. * @param iDBObjectSetIterator $oSet2 The second set of objects to compare, or null
  1180. * @param array $aExcludedColumns The list of columns (= attribute codes) to exclude from the comparison
  1181. * @param string $sAdditionalKeyColumn The attribute code of an additional column to be considered as a key indentifying the object (useful for n:n links)
  1182. */
  1183. public function __construct(iDBObjectSetIterator $oSet1, iDBObjectSetIterator $oSet2, $aExcludedColumns = array(), $sAdditionalKeyColumn = null)
  1184. {
  1185. $this->aFingerprints1 = null;
  1186. $this->aFingerprints2 = null;
  1187. $this->aIDs1 = array();
  1188. $this->aIDs2 = array();
  1189. $this->aExcludedColumns = $aExcludedColumns;
  1190. $this->sAdditionalKeyColumn = $sAdditionalKeyColumn;
  1191. $this->aAdditionalKeys = null;
  1192. $this->oSet1 = $oSet1;
  1193. $this->oSet2 = $oSet2;
  1194. }
  1195. /**
  1196. * Builds the lists of fingerprints and initializes internal structures, if it was not already done
  1197. */
  1198. protected function ComputeFingerprints()
  1199. {
  1200. if ($this->aFingerprints1 === null)
  1201. {
  1202. $this->aFingerprints1 = array();
  1203. $this->aFingerprints2 = array();
  1204. $this->aAdditionalKeys = array();
  1205. if ($this->oSet1 !== null)
  1206. {
  1207. $this->oSet1->Rewind();
  1208. while($oObj = $this->oSet1->Fetch())
  1209. {
  1210. $sFingerprint = $oObj->Fingerprint($this->aExcludedColumns);
  1211. $this->aFingerprints1[$sFingerprint] = $oObj;
  1212. if (!$oObj->IsNew())
  1213. {
  1214. $this->aIDs1[$oObj->GetKey()] = $oObj;
  1215. }
  1216. }
  1217. $this->oSet1->Rewind();
  1218. }
  1219. if ($this->oSet2 !== null)
  1220. {
  1221. $this->oSet2->Rewind();
  1222. while($oObj = $this->oSet2->Fetch())
  1223. {
  1224. $sFingerprint = $oObj->Fingerprint($this->aExcludedColumns);
  1225. $this->aFingerprints2[$sFingerprint] = $oObj;
  1226. if (!$oObj->IsNew())
  1227. {
  1228. $this->aIDs2[$oObj->GetKey()] = $oObj;
  1229. }
  1230. if ($this->sAdditionalKeyColumn !== null)
  1231. {
  1232. $this->aAdditionalKeys[$oObj->Get($this->sAdditionalKeyColumn)] = $oObj;
  1233. }
  1234. }
  1235. $this->oSet2->Rewind();
  1236. }
  1237. }
  1238. }
  1239. /**
  1240. * Tells if the sets are equivalent or not. Returns as soon as the first difference is found.
  1241. * @return boolean true if the set have an equivalent content, false otherwise
  1242. */
  1243. public function SetsAreEquivalent()
  1244. {
  1245. if (($this->oSet1 === null) && ($this->oSet2 === null))
  1246. {
  1247. // Both sets are empty, they are equal
  1248. return true;
  1249. }
  1250. else if (($this->oSet1 === null) || ($this->oSet2 === null))
  1251. {
  1252. // one of them is empty, they are different
  1253. return false;
  1254. }
  1255. if (($this->oSet1->GetRootClass() != $this->oSet2->GetRootClass()) || ($this->oSet1->Count() != $this->oSet2->Count())) return false;
  1256. $this->ComputeFingerprints();
  1257. // Check that all objects in Set1 are also in Set2
  1258. foreach($this->aFingerprints1 as $sFingerprint => $oObj)
  1259. {
  1260. if (!array_key_exists($sFingerprint, $this->aFingerprints2))
  1261. {
  1262. return false;
  1263. }
  1264. }
  1265. // Vice versa
  1266. // Check that all objects in Set2 are also in Set1
  1267. foreach($this->aFingerprints2 as $sFingerprint => $oObj)
  1268. {
  1269. if (!array_key_exists($sFingerprint, $this->aFingerprints1))
  1270. {
  1271. return false;
  1272. }
  1273. }
  1274. return true;
  1275. }
  1276. /**
  1277. * Get the list of differences between the two sets. In ordeer to write back into the database only the minimum changes
  1278. * THE FIRST SET MUST BE THE ONE LOADED FROM THE DATABASE
  1279. * Returns a hash: 'added' => DBObject(s), 'removed' => DBObject(s), 'modified' => DBObjects(s)
  1280. * @return Ambigous <int:DBObject: , unknown>
  1281. */
  1282. public function GetDifferences()
  1283. {
  1284. $aResult = array('added' => array(), 'removed' => array(), 'modified' => array());
  1285. $this->ComputeFingerprints();
  1286. // Check that all objects in Set1 are also in Set2
  1287. foreach($this->aFingerprints1 as $sFingerprint => $oObj)
  1288. {
  1289. // Beware: the elements from the first set MUST come from the database, otherwise the result will be irrelevant
  1290. if ($oObj->IsNew()) throw new Exception('Cannot compute differences when elements from the first set are NOT in the database');
  1291. if (array_key_exists($oObj->GetKey(), $this->aIDs2) && ($this->aIDs2[$oObj->GetKey()]->IsModified()))
  1292. {
  1293. // The very same object exists in both set, but was modified since its load
  1294. $aResult['modified'][$oObj->GetKey()] = $this->aIDs2[$oObj->GetKey()];
  1295. }
  1296. else if (($this->sAdditionalKeyColumn !== null) && array_key_exists($oObj->Get($this->sAdditionalKeyColumn), $this->aAdditionalKeys))
  1297. {
  1298. // Special case for n:n links where the link is recreated between the very same 2 objects, but some of its attributes are modified
  1299. // Let's consider this as a "modification" instead of "deletion" + "creation" in order to have a "clean" history for the objects
  1300. $oDestObj = $this->aAdditionalKeys[$oObj->Get($this->sAdditionalKeyColumn)];
  1301. $oCloneObj = $this->CopyFrom($oObj, $oDestObj);
  1302. $aResult['modified'][$oObj->GetKey()] = $oCloneObj;
  1303. // Mark this as processed, so that the pass on aFingerprints2 below ignores this object
  1304. $sNewFingerprint = $oDestObj->Fingerprint($this->aExcludedColumns);
  1305. $this->aFingerprints2[$sNewFingerprint] = $oCloneObj;
  1306. }
  1307. else if (!array_key_exists($sFingerprint, $this->aFingerprints2))
  1308. {
  1309. $aResult['removed'][] = $oObj;
  1310. }
  1311. }
  1312. // Vice versa
  1313. // Check that all objects in Set2 are also in Set1
  1314. foreach($this->aFingerprints2 as $sFingerprint => $oObj)
  1315. {
  1316. if (array_key_exists($oObj->GetKey(), $this->aIDs1) && ($oObj->IsModified()))
  1317. {
  1318. // Already marked as modified above
  1319. //$aResult['modified'][$oObj->GetKey()] = $oObj;
  1320. }
  1321. else if (!array_key_exists($sFingerprint, $this->aFingerprints1))
  1322. {
  1323. $aResult['added'][] = $oObj;
  1324. }
  1325. }
  1326. return $aResult;
  1327. }
  1328. /**
  1329. * Helpr to clone (in memory) an object and to apply to it the values taken from a second object
  1330. * @param DBObject $oObjToClone
  1331. * @param DBObject $oObjWithValues
  1332. * @return DBObject The modified clone
  1333. */
  1334. protected function CopyFrom($oObjToClone, $oObjWithValues)
  1335. {
  1336. $oObj = MetaModel::GetObject(get_class($oObjToClone), $oObjToClone->GetKey());
  1337. foreach(MetaModel::ListAttributeDefs(get_class($oObj)) as $sAttCode => $oAttDef)
  1338. {
  1339. if (!in_array($sAttCode, $this->aExcludedColumns) && $oAttDef->IsWritable())
  1340. {
  1341. $oObj->Set($sAttCode, $oObjWithValues->Get($sAttCode));
  1342. }
  1343. }
  1344. return $oObj;
  1345. }
  1346. }