dbobjectset.class.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. <?php
  2. // Copyright (C) 2010-2014 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Object set management
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. /**
  25. * A set of persistent objects, could be heterogeneous as long as the objects in the set have a common ancestor class
  26. *
  27. * @package iTopORM
  28. */
  29. class DBObjectSet
  30. {
  31. protected $m_aAddedIds; // Ids of objects added (discrete lists)
  32. protected $m_aAddedObjects;
  33. protected $m_aArgs;
  34. protected $m_aAttToLoad;
  35. protected $m_aOrderBy;
  36. public $m_bLoaded;
  37. protected $m_iNumTotalDBRows;
  38. protected $m_iNumLoadedDBRows;
  39. protected $m_iCurrRow;
  40. protected $m_oFilter;
  41. protected $m_oSQLResult;
  42. /**
  43. * Create a new set based on a Search definition.
  44. *
  45. * @param DBObjectSearch $oFilter The search filter defining the objects which are part of the set (multiple columns/objects per row are supported)
  46. * @param hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  47. * @param hash $aArgs Values to substitute for the search/query parameters (if any). Format: param_name => value
  48. * @param hash $aExtendedDataSpec
  49. * @param int $iLimitCount Maximum number of rows to load (i.e. equivalent to MySQL's LIMIT start, count)
  50. * @param int $iLimitStart Index of the first row to load (i.e. equivalent to MySQL's LIMIT start, count)
  51. */
  52. public function __construct(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0)
  53. {
  54. $this->m_oFilter = $oFilter->DeepClone();
  55. $this->m_aAddedIds = array();
  56. $this->m_aOrderBy = $aOrderBy;
  57. $this->m_aArgs = $aArgs;
  58. $this->m_aAttToLoad = null;
  59. $this->m_aExtendedDataSpec = $aExtendedDataSpec;
  60. $this->m_iLimitCount = $iLimitCount;
  61. $this->m_iLimitStart = $iLimitStart;
  62. $this->m_iNumTotalDBRows = null; // Total number of rows for the query without LIMIT. null if unknown yet
  63. $this->m_iNumLoadedDBRows = 0; // Total number of rows LOADED in $this->m_oSQLResult via a SQL query. 0 by default
  64. $this->m_bLoaded = false; // true when the filter has been used OR the set is built step by step (AddObject...)
  65. $this->m_aAddedObjects = array(); // array of (row => array of (classalias) => object/null) storing the objects added "in memory"
  66. $this->m_iCurrRow = 0;
  67. $this->m_oSQLResult = null;
  68. }
  69. public function __destruct()
  70. {
  71. if (is_object($this->m_oSQLResult))
  72. {
  73. $this->m_oSQLResult->free();
  74. }
  75. }
  76. public function __toString()
  77. {
  78. $sRet = '';
  79. $this->Rewind();
  80. $sRet .= "Set (".$this->m_oFilter->ToOQL().")<br/>\n";
  81. $sRet .= "Query: <pre style=\"font-size: smaller; display:inline;\">".MetaModel::MakeSelectQuery($this->m_oFilter, array()).")</pre>\n";
  82. $sRet .= $this->Count()." records<br/>\n";
  83. if ($this->Count() > 0)
  84. {
  85. $sRet .= "<ul class=\"treeview\">\n";
  86. while ($oObj = $this->Fetch())
  87. {
  88. $sRet .= "<li>".$oObj->__toString()."</li>\n";
  89. }
  90. $sRet .= "</ul>\n";
  91. }
  92. return $sRet;
  93. }
  94. public function __clone()
  95. {
  96. $this->m_oFilter = $this->m_oFilter->DeepClone();
  97. $this->m_iNumTotalDBRows = null; // Total number of rows for the query without LIMIT. null if unknown yet
  98. $this->m_iNumLoadedDBRows = 0; // Total number of rows LOADED in $this->m_oSQLResult via a SQL query. 0 by default
  99. $this->m_bLoaded = false; // true when the filter has been used OR the set is built step by step (AddObject...)
  100. $this->m_iCurrRow = 0;
  101. $this->m_oSQLResult = null;
  102. }
  103. /**
  104. * Called when unserializing a DBObjectSet
  105. */
  106. public function __wakeup()
  107. {
  108. $this->m_iNumTotalDBRows = null; // Total number of rows for the query without LIMIT. null if unknown yet
  109. $this->m_iNumLoadedDBRows = 0; // Total number of rows LOADED in $this->m_oSQLResult via a SQL query. 0 by default
  110. $this->m_bLoaded = false; // true when the filter has been used OR the set is built step by step (AddObject...)
  111. $this->m_iCurrRow = 0;
  112. $this->m_oSQLResult = null;
  113. }
  114. /**
  115. * Specify the subset of attributes to load (for each class of objects) before performing the SQL query for retrieving the rows from the DB
  116. *
  117. * @param hash $aAttToLoad Format: alias => array of attribute_codes
  118. *
  119. * @return void
  120. */
  121. public function OptimizeColumnLoad($aAttToLoad)
  122. {
  123. if (is_null($aAttToLoad))
  124. {
  125. $this->m_aAttToLoad = null;
  126. }
  127. else
  128. {
  129. // Complete the attribute list with the attribute codes
  130. $aAttToLoadWithAttDef = array();
  131. foreach($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  132. {
  133. $aAttToLoadWithAttDef[$sClassAlias] = array();
  134. if (array_key_exists($sClassAlias, $aAttToLoad))
  135. {
  136. $aAttList = $aAttToLoad[$sClassAlias];
  137. foreach($aAttList as $sAttToLoad)
  138. {
  139. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad);
  140. $aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad] = $oAttDef;
  141. if ($oAttDef->IsExternalKey())
  142. {
  143. // Add the external key friendly name anytime
  144. $oFriendlyNameAttDef = MetaModel::GetAttributeDef($sClass, $sAttToLoad.'_friendlyname');
  145. $aAttToLoadWithAttDef[$sClassAlias][$sAttToLoad.'_friendlyname'] = $oFriendlyNameAttDef;
  146. }
  147. }
  148. }
  149. // Add the friendly name anytime
  150. $oFriendlyNameAttDef = MetaModel::GetAttributeDef($sClass, 'friendlyname');
  151. $aAttToLoadWithAttDef[$sClassAlias]['friendlyname'] = $oFriendlyNameAttDef;
  152. // Make sure that the final class is requested anytime, whatever the specification (needed for object construction!)
  153. if (!MetaModel::IsStandaloneClass($sClass) && !array_key_exists('finalclass', $aAttToLoadWithAttDef[$sClassAlias]))
  154. {
  155. $aAttToLoadWithAttDef[$sClassAlias]['finalclass'] = MetaModel::GetAttributeDef($sClass, 'finalclass');
  156. }
  157. }
  158. $this->m_aAttToLoad = $aAttToLoadWithAttDef;
  159. }
  160. }
  161. /**
  162. * Create a set (in-memory) containing just the given object
  163. *
  164. * @param DBobject $oObject
  165. *
  166. * @return DBObjectSet The singleton set
  167. */
  168. static public function FromObject($oObject)
  169. {
  170. $oRetSet = self::FromScratch(get_class($oObject));
  171. $oRetSet->AddObject($oObject);
  172. return $oRetSet;
  173. }
  174. /**
  175. * Create an empty set (in-memory), for the given class (and its subclasses) of objects
  176. *
  177. * @param string $sClass The class (or an ancestor) for the objects to be added in this set
  178. *
  179. * @return DBObject The empty set
  180. */
  181. static public function FromScratch($sClass)
  182. {
  183. $oFilter = new DBObjectSearch($sClass);
  184. $oFilter->AddConditionExpression(new FalseExpression());
  185. $oRetSet = new self($oFilter);
  186. $oRetSet->m_bLoaded = true; // no DB load
  187. $oRetSet->m_iNumTotalDBRows = 0; // Nothing from the DB
  188. return $oRetSet;
  189. }
  190. /**
  191. * Create a set (in-memory) with just one column (i.e. one object per row) and filled with the given array of objects
  192. *
  193. * @param string $sClass The class of the objects (must be a common ancestor to all objects in the set)
  194. * @param array $aObjects The list of objects to add into the set
  195. *
  196. * @return DBObjectSet
  197. */
  198. static public function FromArray($sClass, $aObjects)
  199. {
  200. $oRetSet = self::FromScratch($sClass);
  201. $oRetSet->AddObjectArray($aObjects, $sClass);
  202. return $oRetSet;
  203. }
  204. /**
  205. * Create a set in-memory with several classes of objects per row (with one alias per "column")
  206. *
  207. * Limitation:
  208. * The filter/OQL query representing such a set can not be rebuilt (only the first column will be taken into account)
  209. *
  210. * @param hash $aClasses Format: array of (alias => class)
  211. * @param hash $aObjects Format: array of (array of (classalias => object))
  212. *
  213. * @return DBObjectSet
  214. */
  215. static public function FromArrayAssoc($aClasses, $aObjects)
  216. {
  217. // In a perfect world, we should create a complete tree of DBObjectSearch,
  218. // but as we lack most of the information related to the objects,
  219. // let's create one search definition corresponding only to the first column
  220. $sClass = reset($aClasses);
  221. $sAlias = key($aClasses);
  222. $oFilter = new CMDBSearchFilter($sClass, $sAlias);
  223. $oRetSet = new self($oFilter);
  224. $oRetSet->m_bLoaded = true; // no DB load
  225. $oRetSet->m_iNumTotalDBRows = 0; // Nothing from the DB
  226. foreach($aObjects as $rowIndex => $aObjectsByClassAlias)
  227. {
  228. $oRetSet->AddObjectExtended($aObjectsByClassAlias);
  229. }
  230. return $oRetSet;
  231. }
  232. static public function FromLinkSet($oObject, $sLinkSetAttCode, $sExtKeyToRemote)
  233. {
  234. $oLinkAttCode = MetaModel::GetAttributeDef(get_class($oObject), $sLinkSetAttCode);
  235. $oExtKeyAttDef = MetaModel::GetAttributeDef($oLinkAttCode->GetLinkedClass(), $sExtKeyToRemote);
  236. $sTargetClass = $oExtKeyAttDef->GetTargetClass();
  237. $oLinkSet = $oObject->Get($sLinkSetAttCode);
  238. $aTargets = array();
  239. while ($oLink = $oLinkSet->Fetch())
  240. {
  241. $aTargets[] = MetaModel::GetObject($sTargetClass, $oLink->Get($sExtKeyToRemote));
  242. }
  243. return self::FromArray($sTargetClass, $aTargets);
  244. }
  245. public function ToArray($bWithId = true)
  246. {
  247. $aRet = array();
  248. $this->Rewind();
  249. while ($oObject = $this->Fetch())
  250. {
  251. if ($bWithId)
  252. {
  253. $aRet[$oObject->GetKey()] = $oObject;
  254. }
  255. else
  256. {
  257. $aRet[] = $oObject;
  258. }
  259. }
  260. return $aRet;
  261. }
  262. public function ToArrayOfValues()
  263. {
  264. if (!$this->m_bLoaded) $this->Load();
  265. $this->Rewind();
  266. $aSelectedClasses = $this->m_oFilter->GetSelectedClasses();
  267. $aRet = array();
  268. $iRow = 0;
  269. while($aObjects = $this->FetchAssoc())
  270. {
  271. foreach($aObjects as $sClassAlias => $oObject)
  272. {
  273. if (is_null($oObject))
  274. {
  275. $aRet[$iRow][$sClassAlias.'.'.'id'] = null;
  276. }
  277. else
  278. {
  279. $aRet[$iRow][$sClassAlias.'.'.'id'] = $oObject->GetKey();
  280. }
  281. if (is_null($oObject))
  282. {
  283. $sClass = $aSelectedClasses[$sClassAlias];
  284. }
  285. else
  286. {
  287. $sClass = get_class($oObject);
  288. }
  289. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  290. {
  291. if ($oAttDef->IsScalar())
  292. {
  293. $sAttName = $sClassAlias.'.'.$sAttCode;
  294. if (is_null($oObject))
  295. {
  296. $aRet[$iRow][$sAttName] = null;
  297. }
  298. else
  299. {
  300. $aRet[$iRow][$sAttName] = $oObject->Get($sAttCode);
  301. }
  302. }
  303. }
  304. }
  305. $iRow++;
  306. }
  307. return $aRet;
  308. }
  309. public function GetColumnAsArray($sAttCode, $bWithId = true)
  310. {
  311. $aRet = array();
  312. $this->Rewind();
  313. while ($oObject = $this->Fetch())
  314. {
  315. if ($bWithId)
  316. {
  317. $aRet[$oObject->GetKey()] = $oObject->Get($sAttCode);
  318. }
  319. else
  320. {
  321. $aRet[] = $oObject->Get($sAttCode);
  322. }
  323. }
  324. return $aRet;
  325. }
  326. /**
  327. * Retrieve the DBObjectSearch corresponding to the objects present in this set
  328. *
  329. * Limitation:
  330. * This method will NOT work for sets with several columns (i.e. several objects per row)
  331. *
  332. * @return DBObjectSearch
  333. */
  334. public function GetFilter()
  335. {
  336. // Make sure that we carry on the parameters of the set with the filter
  337. $oFilter = $this->m_oFilter->DeepClone();
  338. // Note: the arguments found within a set can be object (but not in a filter)
  339. // That's why PrepareQueryArguments must be invoked there
  340. $oFilter->SetInternalParams(array_merge($oFilter->GetInternalParams(), MetaModel::PrepareQueryArguments($this->m_aArgs)));
  341. if (count($this->m_aAddedIds) == 0)
  342. {
  343. return $oFilter;
  344. }
  345. else
  346. {
  347. $oIdListExpr = ListExpression::FromScalars(array_keys($this->m_aAddedIds));
  348. $oIdExpr = new FieldExpression('id', $oFilter->GetClassAlias());
  349. $oIdInList = new BinaryExpression($oIdExpr, 'IN', $oIdListExpr);
  350. $oFilter->MergeConditionExpression($oIdInList);
  351. return $oFilter;
  352. }
  353. }
  354. /**
  355. * The (common ancestor) class of the objects in the first column of this set
  356. *
  357. * @return string The class of the objects in the first column
  358. */
  359. public function GetClass()
  360. {
  361. return $this->m_oFilter->GetClass();
  362. }
  363. /**
  364. * The alias for the class of the objects in the first column of this set
  365. *
  366. * @return string The alias of the class in the first column
  367. */
  368. public function GetClassAlias()
  369. {
  370. return $this->m_oFilter->GetClassAlias();
  371. }
  372. /**
  373. * The list of all classes (one per column) which are part of this set
  374. *
  375. * @return hash Format: alias => class
  376. */
  377. public function GetSelectedClasses()
  378. {
  379. return $this->m_oFilter->GetSelectedClasses();
  380. }
  381. /**
  382. * The root class (i.e. highest ancestor in the MeaModel class hierarchy) for the first column on this set
  383. *
  384. * @return string The root class for the objects in the first column of the set
  385. */
  386. public function GetRootClass()
  387. {
  388. return MetaModel::GetRootClass($this->GetClass());
  389. }
  390. /**
  391. * The arguments used for building this set
  392. *
  393. * @return hash Format: parameter_name => value
  394. */
  395. public function GetArgs()
  396. {
  397. return $this->m_aArgs;
  398. }
  399. /**
  400. * Sets the limits for loading the rows from the DB. Equivalent to MySQL's LIMIT start,count clause.
  401. * @param int $iLimitCount The number of rows to load
  402. * @param int $iLimitStart The index of the first row to load
  403. */
  404. public function SetLimit($iLimitCount, $iLimitStart = 0)
  405. {
  406. $this->m_iLimitCount = $iLimitCount;
  407. $this->m_iLimitStart = $iLimitStart;
  408. }
  409. /**
  410. * Sets the sort order for loading the rows from the DB. Changing the order by causes a Reload.
  411. *
  412. * @param hash $aOrderBy Format: field_code => boolean (true = ascending, false = descending)
  413. */
  414. public function SetOrderBy($aOrderBy)
  415. {
  416. if ($this->m_aOrderBy != $aOrderBy)
  417. {
  418. $this->m_aOrderBy = $aOrderBy;
  419. if ($this->m_bLoaded)
  420. {
  421. $this->m_bLoaded = false;
  422. $this->Load();
  423. }
  424. }
  425. }
  426. /**
  427. * Returns the 'count' limit for loading the rows from the DB
  428. *
  429. * @return int
  430. */
  431. public function GetLimitCount()
  432. {
  433. return $this->m_iLimitCount;
  434. }
  435. /**
  436. * Returns the 'start' limit for loading the rows from the DB
  437. *
  438. * @return int
  439. */
  440. public function GetLimitStart()
  441. {
  442. return $this->m_iLimitStart;
  443. }
  444. /**
  445. * Get the sort order used for loading this set from the database
  446. *
  447. * Limitation: the sort order has no effect on objects added in-memory
  448. *
  449. * @return hash Format: field_code => boolean (true = ascending, false = descending)
  450. */
  451. public function GetRealSortOrder()
  452. {
  453. // Get the class default sort order if not specified with the API
  454. //
  455. if (empty($this->m_aOrderBy))
  456. {
  457. return MetaModel::GetOrderByDefault($this->m_oFilter->GetClass());
  458. }
  459. else
  460. {
  461. return $this->m_aOrderBy;
  462. }
  463. }
  464. /**
  465. * Loads the set from the database. Actually performs the SQL query to retrieve the records from the DB.
  466. */
  467. public function Load()
  468. {
  469. if ($this->m_bLoaded) return;
  470. // Note: it is mandatory to set this value now, to protect against reentrance
  471. $this->m_bLoaded = true;
  472. if ($this->m_iLimitCount > 0)
  473. {
  474. $sSQL = MetaModel::MakeSelectQuery($this->m_oFilter, $this->GetRealSortOrder(), $this->m_aArgs, $this->m_aAttToLoad, $this->m_aExtendedDataSpec, $this->m_iLimitCount, $this->m_iLimitStart);
  475. }
  476. else
  477. {
  478. $sSQL = MetaModel::MakeSelectQuery($this->m_oFilter, $this->GetRealSortOrder(), $this->m_aArgs, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  479. }
  480. if (is_object($this->m_oSQLResult))
  481. {
  482. // Free previous resultset if any
  483. $this->m_oSQLResult->free();
  484. $this->m_oSQLResult = null;
  485. }
  486. $this->m_iNumTotalDBRows = null;
  487. $this->m_oSQLResult = CMDBSource::Query($sSQL);
  488. if ($this->m_oSQLResult === false) return;
  489. if (($this->m_iLimitCount == 0) && ($this->m_iLimitStart == 0))
  490. {
  491. $this->m_iNumTotalDBRows = $this->m_oSQLResult->num_rows;
  492. }
  493. $this->m_iNumLoadedDBRows = $this->m_oSQLResult->num_rows;
  494. }
  495. /**
  496. * The total number of rows in this set. Independently of the SetLimit used for loading the set and taking into account the rows added in-memory.
  497. *
  498. * May actually perform the SQL query SELECT COUNT... if the set was not previously loaded, or loaded with a SetLimit
  499. *
  500. * @return int The total number of rows for this set.
  501. */
  502. public function Count()
  503. {
  504. if (is_null($this->m_iNumTotalDBRows))
  505. {
  506. $sSQL = MetaModel::MakeSelectQuery($this->m_oFilter, array(), $this->m_aArgs, null, null, 0, 0, true);
  507. $resQuery = CMDBSource::Query($sSQL);
  508. if (!$resQuery) return 0;
  509. $aRow = CMDBSource::FetchArray($resQuery);
  510. CMDBSource::FreeResult($resQuery);
  511. $this->m_iNumTotalDBRows = $aRow['COUNT'];
  512. }
  513. return $this->m_iNumTotalDBRows + count($this->m_aAddedObjects); // Does it fix Trac #887 ??
  514. }
  515. /**
  516. * Number of rows available in memory (loaded from DB + added in memory)
  517. *
  518. * @return number The number of rows available for Fetch'ing
  519. */
  520. protected function CountLoaded()
  521. {
  522. return $this->m_iNumLoadedDBRows + count($this->m_aAddedObjects);
  523. }
  524. /**
  525. * Fetch the object (with the given class alias) at the current position in the set and move the cursor to the next position.
  526. *
  527. * @param string $sRequestedClassAlias The class alias to fetch (if there are several objects/classes per row)
  528. * @return DBObject The fetched object or null when at the end
  529. */
  530. public function Fetch($sRequestedClassAlias = '')
  531. {
  532. if (!$this->m_bLoaded) $this->Load();
  533. if ($this->m_iCurrRow >= $this->CountLoaded())
  534. {
  535. return null;
  536. }
  537. if (strlen($sRequestedClassAlias) == 0)
  538. {
  539. $sRequestedClassAlias = $this->m_oFilter->GetClassAlias();
  540. }
  541. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  542. {
  543. // Pick the row from the database
  544. $aRow = CMDBSource::FetchArray($this->m_oSQLResult);
  545. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  546. {
  547. if ($sRequestedClassAlias == $sClassAlias)
  548. {
  549. if (is_null($aRow[$sClassAlias.'id']))
  550. {
  551. $oRetObj = null;
  552. }
  553. else
  554. {
  555. $oRetObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  556. }
  557. break;
  558. }
  559. }
  560. }
  561. else
  562. {
  563. // Pick the row from the objects added *in memory*
  564. $oRetObj = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sRequestedClassAlias];
  565. }
  566. $this->m_iCurrRow++;
  567. return $oRetObj;
  568. }
  569. /**
  570. * Fetch the whole row of objects (if several classes have been specified in the query) and move the cursor to the next position
  571. *
  572. * @return hash A hash with the format 'classAlias' => $oObj representing the current row of the set. Returns null when at the end.
  573. */
  574. public function FetchAssoc()
  575. {
  576. if (!$this->m_bLoaded) $this->Load();
  577. if ($this->m_iCurrRow >= $this->CountLoaded())
  578. {
  579. return null;
  580. }
  581. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  582. {
  583. // Pick the row from the database
  584. $aRow = CMDBSource::FetchArray($this->m_oSQLResult);
  585. $aRetObjects = array();
  586. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  587. {
  588. if (is_null($aRow[$sClassAlias.'id']))
  589. {
  590. $oObj = null;
  591. }
  592. else
  593. {
  594. $oObj = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aAttToLoad, $this->m_aExtendedDataSpec);
  595. }
  596. $aRetObjects[$sClassAlias] = $oObj;
  597. }
  598. }
  599. else
  600. {
  601. // Pick the row from the objects added *in memory*
  602. $aRetObjects = array();
  603. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  604. {
  605. $aRetObjects[$sClassAlias] = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sClassAlias];
  606. }
  607. }
  608. $this->m_iCurrRow++;
  609. return $aRetObjects;
  610. }
  611. /**
  612. * Position the cursor (for iterating in the set) to the first position (equivalent to Seek(0))
  613. */
  614. public function Rewind()
  615. {
  616. if ($this->m_bLoaded)
  617. {
  618. $this->Seek(0);
  619. }
  620. }
  621. /**
  622. * Position the cursor (for iterating in the set) to the given position
  623. *
  624. * @param int $iRow
  625. */
  626. public function Seek($iRow)
  627. {
  628. if (!$this->m_bLoaded) $this->Load();
  629. $this->m_iCurrRow = min($iRow, $this->Count());
  630. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  631. {
  632. $this->m_oSQLResult->data_seek($this->m_iCurrRow);
  633. }
  634. return $this->m_iCurrRow;
  635. }
  636. /**
  637. * Add an object to the current set (in-memory only, nothing is written to the database)
  638. *
  639. * Limitation:
  640. * Sets with several objects per row are NOT supported
  641. *
  642. * @param DBObject $oObject The object to add
  643. * @param string $sClassAlias The alias for the class of the object
  644. */
  645. public function AddObject($oObject, $sClassAlias = '')
  646. {
  647. if (!$this->m_bLoaded) $this->Load();
  648. if (strlen($sClassAlias) == 0)
  649. {
  650. $sClassAlias = $this->m_oFilter->GetClassAlias();
  651. }
  652. $iNextPos = count($this->m_aAddedObjects);
  653. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  654. if (!is_null($oObject))
  655. {
  656. $this->m_aAddedIds[$oObject->GetKey()] = true;
  657. }
  658. }
  659. /**
  660. * Add a hash containig objects into the current set.
  661. *
  662. * The expected format for the hash is: $aObjectArray[$idx][$sClassAlias] => $oObject
  663. * Limitation:
  664. * The aliases MUST match the ones used in the current set
  665. * Only the ID of the objects associated to the first alias (column) is remembered.. in case we have to rebuild a filter
  666. *
  667. * @param hash $aObjectArray
  668. */
  669. protected function AddObjectExtended($aObjectArray)
  670. {
  671. if (!$this->m_bLoaded) $this->Load();
  672. $iNextPos = count($this->m_aAddedObjects);
  673. $sFirstAlias = $this->m_oFilter->GetClassAlias();
  674. foreach ($aObjectArray as $sClassAlias => $oObject)
  675. {
  676. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  677. if (!is_null($oObject) && ($sFirstAlias == $sClassAlias))
  678. {
  679. $this->m_aAddedIds[$oObject->GetKey()] = true;
  680. }
  681. }
  682. }
  683. /**
  684. * Add an array of objects into the current set
  685. *
  686. * Limitation:
  687. * Sets with several classes per row are not supported (use AddObjectExtended instead)
  688. *
  689. * @param array $aObjects The array of objects to add
  690. * @param string $sClassAlias The Alias of the class for the added objects
  691. */
  692. public function AddObjectArray($aObjects, $sClassAlias = '')
  693. {
  694. if (!$this->m_bLoaded) $this->Load();
  695. // #@# todo - add a check on the object class ?
  696. foreach ($aObjects as $oObj)
  697. {
  698. $this->AddObject($oObj, $sClassAlias);
  699. }
  700. }
  701. /**
  702. * Append a given set to the current object. (This method used to be named Merge)
  703. *
  704. * Limitation:
  705. * The added objects are not checked for duplicates (i.e. one cann add several times the same object, or add an object already present in the set).
  706. *
  707. * @param DBObjectSet $oObjectSet The set to append
  708. * @throws CoreException
  709. */
  710. public function Append(DBObjectSet $oObjectSet)
  711. {
  712. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  713. {
  714. throw new CoreException("Could not merge two objects sets if they don't have the same root class");
  715. }
  716. if (!$this->m_bLoaded) $this->Load();
  717. $oObjectSet->Seek(0);
  718. while ($oObject = $oObjectSet->Fetch())
  719. {
  720. $this->AddObject($oObject);
  721. }
  722. }
  723. /**
  724. * Create a set containing the objects present in both the current set and another specified set
  725. *
  726. * Limitations:
  727. * Will NOT work if only a subset of the sets was loaded with SetLimit.
  728. * Works only with sets made of objects loaded from the database since the comparison is based on the objects identifiers
  729. *
  730. * @param DBObjectSet $oObjectSet The set to intersect with. The current position inside the set will be lost (= at the end)
  731. * @throws CoreException
  732. * @return DBObjectSet A new set of objects, containing the objects present in both sets (based on their identifier)
  733. */
  734. public function CreateIntersect(DBObjectSet $oObjectSet)
  735. {
  736. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  737. {
  738. throw new CoreException("Could not 'intersect' two objects sets if they don't have the same root class");
  739. }
  740. if (!$this->m_bLoaded) $this->Load();
  741. $aId2Row = array();
  742. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  743. $idx = 0;
  744. while($oObj = $this->Fetch())
  745. {
  746. $aId2Row[$oObj->GetKey()] = $idx;
  747. $idx++;
  748. }
  749. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  750. $oObjectSet->Seek(0);
  751. while ($oObject = $oObjectSet->Fetch())
  752. {
  753. if (array_key_exists($oObject->GetKey(), $aId2Row))
  754. {
  755. $oNewSet->AddObject($oObject);
  756. }
  757. }
  758. $this->Seek($iCurrPos); // Restore the cursor
  759. return $oNewSet;
  760. }
  761. /**
  762. * Compare two sets of objects to determine if their content is identical or not.
  763. *
  764. * Limitation:
  765. * Works only on objects written to the DB, since we rely on their identifiers
  766. *
  767. * @param DBObjectSet $oObjectSet
  768. * @return boolean True if the sets are identical, false otherwise
  769. */
  770. public function HasSameContents(DBObjectSet $oObjectSet)
  771. {
  772. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  773. {
  774. return false;
  775. }
  776. if ($this->Count() != $oObjectSet->Count())
  777. {
  778. return false;
  779. }
  780. $aId2Row = array();
  781. $bRet = true;
  782. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  783. $idx = 0;
  784. // Optimization: we retain the first $iMaxObjects objects in memory
  785. // to speed up the comparison of small sets (see below: $oObject->Equals($oSibling))
  786. $iMaxObjects = 20;
  787. $aCachedObjects = array();
  788. while($oObj = $this->Fetch())
  789. {
  790. $aId2Row[$oObj->GetKey()] = $idx;
  791. if ($idx <= $iMaxObjects)
  792. {
  793. $aCachedObjects[$idx] = $oObj;
  794. }
  795. $idx++;
  796. }
  797. $oObjectSet->Rewind();
  798. while ($oObject = $oObjectSet->Fetch())
  799. {
  800. $iObjectKey = $oObject->GetKey();
  801. if ($iObjectKey < 0)
  802. {
  803. $bRet = false;
  804. break;
  805. }
  806. if (!array_key_exists($iObjectKey, $aId2Row))
  807. {
  808. $bRet = false;
  809. break;
  810. }
  811. $iRow = $aId2Row[$iObjectKey];
  812. if (array_key_exists($iRow, $aCachedObjects))
  813. {
  814. // Cache hit
  815. $oSibling = $aCachedObjects[$iRow];
  816. }
  817. else
  818. {
  819. // Go fetch it from the DB, unless it's an object added in-memory
  820. $oSibling = $this->GetObjectAt($iRow);
  821. }
  822. if (!$oObject->Equals($oSibling))
  823. {
  824. $bRet = false;
  825. break;
  826. }
  827. }
  828. $this->Seek($iCurrPos); // Restore the cursor
  829. return $bRet;
  830. }
  831. protected function GetObjectAt($iIndex)
  832. {
  833. if (!$this->m_bLoaded) $this->Load();
  834. // Save the current position for iteration
  835. $iCurrPos = $this->m_iCurrRow;
  836. $this->Seek($iIndex);
  837. $oObject = $this->Fetch();
  838. // Restore the current position for iteration
  839. $this->Seek($this->m_iCurrRow);
  840. return $oObject;
  841. }
  842. /**
  843. * Build a new set (in memory) made of objects of the given set which are NOT present in the current set
  844. *
  845. * Limitations:
  846. * The objects inside the set must be written in the database since the comparison is based on their identifiers
  847. * Sets with several objects per row are NOT supported
  848. *
  849. * @param DBObjectSet $oObjectSet
  850. * @throws CoreException
  851. *
  852. * @return DBObjectSet The "delta" set.
  853. */
  854. public function CreateDelta(DBObjectSet $oObjectSet)
  855. {
  856. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  857. {
  858. throw new CoreException("Could not 'delta' two objects sets if they don't have the same root class");
  859. }
  860. if (!$this->m_bLoaded) $this->Load();
  861. $aId2Row = array();
  862. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  863. $idx = 0;
  864. while($oObj = $this->Fetch())
  865. {
  866. $aId2Row[$oObj->GetKey()] = $idx;
  867. $idx++;
  868. }
  869. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  870. $oObjectSet->Seek(0);
  871. while ($oObject = $oObjectSet->Fetch())
  872. {
  873. if (!array_key_exists($oObject->GetKey(), $aId2Row))
  874. {
  875. $oNewSet->AddObject($oObject);
  876. }
  877. }
  878. $this->Seek($iCurrPos); // Restore the cursor
  879. return $oNewSet;
  880. }
  881. /**
  882. * Will be deprecated soon - use MetaModel::GetRelatedObjectsDown/Up instead to take redundancy into account
  883. */
  884. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99)
  885. {
  886. $aRelatedObjs = array();
  887. $aVisited = array(); // optimization for consecutive calls of MetaModel::GetRelatedObjects
  888. $this->Seek(0);
  889. while ($oObject = $this->Fetch())
  890. {
  891. $aMore = $oObject->GetRelatedObjects($sRelCode, $iMaxDepth, $aVisited);
  892. foreach ($aMore as $sClass => $aRelated)
  893. {
  894. foreach ($aRelated as $iObj => $oObj)
  895. {
  896. if (!isset($aRelatedObjs[$sClass][$iObj]))
  897. {
  898. $aRelatedObjs[$sClass][$iObj] = $oObj;
  899. }
  900. }
  901. }
  902. }
  903. return $aRelatedObjs;
  904. }
  905. /**
  906. * Builds an object that contains the values that are common to all the objects
  907. * in the set. If for a given attribute, objects in the set have various values
  908. * then the resulting object will contain null for this value.
  909. * @param $aValues Hash Output: the distribution of the values, in the set, for each attribute
  910. * @return DBObject The object with the common values
  911. */
  912. public function ComputeCommonObject(&$aValues)
  913. {
  914. $sClass = $this->GetClass();
  915. $aList = MetaModel::ListAttributeDefs($sClass);
  916. $aValues = array();
  917. foreach($aList as $sAttCode => $oAttDef)
  918. {
  919. if ($oAttDef->IsScalar())
  920. {
  921. $aValues[$sAttCode] = array();
  922. }
  923. }
  924. $this->Rewind();
  925. while($oObj = $this->Fetch())
  926. {
  927. foreach($aList as $sAttCode => $oAttDef)
  928. {
  929. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  930. {
  931. $currValue = $oObj->Get($sAttCode);
  932. if (is_object($currValue)) continue; // Skip non scalar values...
  933. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  934. {
  935. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  936. }
  937. else
  938. {
  939. $aValues[$sAttCode][$currValue]['count']++;
  940. }
  941. }
  942. }
  943. }
  944. foreach($aValues as $sAttCode => $aMultiValues)
  945. {
  946. if (count($aMultiValues) > 1)
  947. {
  948. uasort($aValues[$sAttCode], 'HashCountComparison');
  949. }
  950. }
  951. // Now create an object that has values for the homogenous values only
  952. $oCommonObj = new $sClass(); // @@ What if the class is abstract ?
  953. $aComments = array();
  954. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  955. $sReadyScript = '';
  956. $aDependsOn = array();
  957. $sFormPrefix = '2_';
  958. foreach($aList as $sAttCode => $oAttDef)
  959. {
  960. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  961. {
  962. if ($oAttDef->GetEditClass() == 'One Way Password')
  963. {
  964. $oCommonObj->Set($sAttCode, null);
  965. }
  966. else
  967. {
  968. $iCount = count($aValues[$sAttCode]);
  969. if ($iCount == 1)
  970. {
  971. // Homogenous value
  972. reset($aValues[$sAttCode]);
  973. $aKeys = array_keys($aValues[$sAttCode]);
  974. $currValue = $aKeys[0]; // The only value is the first key
  975. $oCommonObj->Set($sAttCode, $currValue);
  976. }
  977. else
  978. {
  979. // Non-homogenous value
  980. $oCommonObj->Set($sAttCode, null);
  981. }
  982. }
  983. }
  984. }
  985. $this->Rewind();
  986. return $oCommonObj;
  987. }
  988. /**
  989. * List the constant fields (and their value) in the given query
  990. * @return Hash [Alias][AttCode] => value
  991. */
  992. public function ListConstantFields()
  993. {
  994. $aScalarArgs = $this->ExpandArgs();
  995. $aConst = $this->m_oFilter->ListConstantFields();
  996. foreach($aConst as $sClassAlias => $aVals)
  997. {
  998. foreach($aVals as $sCode => $oExpr)
  999. {
  1000. if (is_object($oExpr)) // Array_merge_recursive creates an array when the same key is present multiple times... ignore them
  1001. {
  1002. $oScalarExpr = $oExpr->GetAsScalar($aScalarArgs);
  1003. $aConst[$sClassAlias][$sCode] = $oScalarExpr->GetValue();
  1004. }
  1005. }
  1006. }
  1007. return $aConst;
  1008. }
  1009. protected function ExpandArgs()
  1010. {
  1011. $aScalarArgs = $this->m_oFilter->GetInternalParams();
  1012. foreach($this->m_aArgs as $sArgName => $value)
  1013. {
  1014. if (MetaModel::IsValidObject($value))
  1015. {
  1016. if (strpos($sArgName, '->object()') === false)
  1017. {
  1018. // Lazy syntax - develop the object contextual parameters
  1019. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgsForQuery($sArgName));
  1020. }
  1021. else
  1022. {
  1023. // Leave as is
  1024. $aScalarArgs[$sArgName] = $value;
  1025. }
  1026. }
  1027. else
  1028. {
  1029. if (!is_array($value)) // Sometimes ExtraParams contains a mix (like defaults[]) so non scalar parameters are ignored
  1030. {
  1031. $aScalarArgs[$sArgName] = (string) $value;
  1032. }
  1033. }
  1034. }
  1035. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1036. return $aScalarArgs;
  1037. }
  1038. public function ApplyParameters()
  1039. {
  1040. $aScalarArgs = $this->ExpandArgs();
  1041. $this->m_oFilter->ApplyParameters($aScalarArgs);
  1042. }
  1043. }
  1044. /**
  1045. * Helper function to perform a custom sort of a hash array
  1046. */
  1047. function HashCountComparison($a, $b) // Sort descending on 'count'
  1048. {
  1049. if ($a['count'] == $b['count'])
  1050. {
  1051. return 0;
  1052. }
  1053. return ($a['count'] > $b['count']) ? -1 : 1;
  1054. }