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
  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. $oRetObj = $this->m_aAddedObjects[$this->m_iCurrRow - $this->m_iNumLoadedDBRows][$sRequestedClassAlias];
  603. }
  604. $this->m_iCurrRow++;
  605. return $aRetObjects;
  606. }
  607. /**
  608. * Position the cursor (for iterating in the set) to the first position (equivalent to Seek(0))
  609. */
  610. public function Rewind()
  611. {
  612. if ($this->m_bLoaded)
  613. {
  614. $this->Seek(0);
  615. }
  616. }
  617. /**
  618. * Position the cursor (for iterating in the set) to the given position
  619. *
  620. * @param int $iRow
  621. */
  622. public function Seek($iRow)
  623. {
  624. if (!$this->m_bLoaded) $this->Load();
  625. $this->m_iCurrRow = min($iRow, $this->Count());
  626. if ($this->m_iCurrRow < $this->m_iNumLoadedDBRows)
  627. {
  628. $this->m_oSQLResult->data_seek($this->m_iCurrRow);
  629. }
  630. return $this->m_iCurrRow;
  631. }
  632. /**
  633. * Add an object to the current set (in-memory only, nothing is written to the database)
  634. *
  635. * Limitation:
  636. * Sets with several objects per row are NOT supported
  637. *
  638. * @param DBObject $oObject The object to add
  639. * @param string $sClassAlias The alias for the class of the object
  640. */
  641. public function AddObject($oObject, $sClassAlias = '')
  642. {
  643. if (!$this->m_bLoaded) $this->Load();
  644. if (strlen($sClassAlias) == 0)
  645. {
  646. $sClassAlias = $this->m_oFilter->GetClassAlias();
  647. }
  648. $iNextPos = count($this->m_aAddedObjects);
  649. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  650. if (!is_null($oObject))
  651. {
  652. $this->m_aAddedIds[$oObject->GetKey()] = true;
  653. }
  654. }
  655. /**
  656. * Add a hash containig objects into the current set.
  657. *
  658. * The expected format for the hash is: $aObjectArray[$idx][$sClassAlias] => $oObject
  659. * Limitation:
  660. * The aliases MUST match the ones used in the current set
  661. * Only the ID of the objects associated to the first alias (column) is remembered.. in case we have to rebuild a filter
  662. *
  663. * @param hash $aObjectArray
  664. */
  665. protected function AddObjectExtended($aObjectArray)
  666. {
  667. if (!$this->m_bLoaded) $this->Load();
  668. $iNextPos = count($this->m_aAddedObjects);
  669. $sFirstAlias = $this->m_oFilter->GetClassAlias();
  670. foreach ($aObjectArray as $sClassAlias => $oObject)
  671. {
  672. $this->m_aAddedObjects[$iNextPos][$sClassAlias] = $oObject;
  673. if (!is_null($oObject) && ($sFirstAlias == $sClassAlias))
  674. {
  675. $this->m_aAddedIds[$oObject->GetKey()] = true;
  676. }
  677. }
  678. }
  679. /**
  680. * Add an array of objects into the current set
  681. *
  682. * Limitation:
  683. * Sets with several classes per row are not supported (use AddObjectExtended instead)
  684. *
  685. * @param array $aObjects The array of objects to add
  686. * @param string $sClassAlias The Alias of the class for the added objects
  687. */
  688. public function AddObjectArray($aObjects, $sClassAlias = '')
  689. {
  690. if (!$this->m_bLoaded) $this->Load();
  691. // #@# todo - add a check on the object class ?
  692. foreach ($aObjects as $oObj)
  693. {
  694. $this->AddObject($oObj, $sClassAlias);
  695. }
  696. }
  697. /**
  698. * Append a given set to the current object. (This method used to be named Merge)
  699. *
  700. * Limitation:
  701. * 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).
  702. *
  703. * @param DBObjectSet $oObjectSet The set to append
  704. * @throws CoreException
  705. */
  706. public function Append(DBObjectSet $oObjectSet)
  707. {
  708. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  709. {
  710. throw new CoreException("Could not merge two objects sets if they don't have the same root class");
  711. }
  712. if (!$this->m_bLoaded) $this->Load();
  713. $oObjectSet->Seek(0);
  714. while ($oObject = $oObjectSet->Fetch())
  715. {
  716. $this->AddObject($oObject);
  717. }
  718. }
  719. /**
  720. * Create a set containing the objects present in both the current set and another specified set
  721. *
  722. * Limitations:
  723. * Will NOT work if only a subset of the sets was loaded with SetLimit.
  724. * Works only with sets made of objects loaded from the database since the comparison is based on the objects identifiers
  725. *
  726. * @param DBObjectSet $oObjectSet The set to intersect with. The current position inside the set will be lost (= at the end)
  727. * @throws CoreException
  728. * @return DBObjectSet A new set of objects, containing the objects present in both sets (based on their identifier)
  729. */
  730. public function CreateIntersect(DBObjectSet $oObjectSet)
  731. {
  732. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  733. {
  734. throw new CoreException("Could not 'intersect' two objects sets if they don't have the same root class");
  735. }
  736. if (!$this->m_bLoaded) $this->Load();
  737. $aId2Row = array();
  738. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  739. $idx = 0;
  740. while($oObj = $this->Fetch())
  741. {
  742. $aId2Row[$oObj->GetKey()] = $idx;
  743. $idx++;
  744. }
  745. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  746. $oObjectSet->Seek(0);
  747. while ($oObject = $oObjectSet->Fetch())
  748. {
  749. if (array_key_exists($oObject->GetKey(), $aId2Row))
  750. {
  751. $oNewSet->AddObject($oObject);
  752. }
  753. }
  754. $this->Seek($iCurrPos); // Restore the cursor
  755. return $oNewSet;
  756. }
  757. /**
  758. * Compare two sets of objects to determine if their content is identical or not.
  759. *
  760. * Limitation:
  761. * Works only on objects written to the DB, since we rely on their identifiers
  762. *
  763. * @param DBObjectSet $oObjectSet
  764. * @return boolean True if the sets are identical, false otherwise
  765. */
  766. public function HasSameContents(DBObjectSet $oObjectSet)
  767. {
  768. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  769. {
  770. return false;
  771. }
  772. if ($this->Count() != $oObjectSet->Count())
  773. {
  774. return false;
  775. }
  776. $aId2Row = array();
  777. $bRet = true;
  778. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  779. $idx = 0;
  780. // Optimization: we retain the first $iMaxObjects objects in memory
  781. // to speed up the comparison of small sets (see below: $oObject->Equals($oSibling))
  782. $iMaxObjects = 20;
  783. $aCachedObjects = array();
  784. while($oObj = $this->Fetch())
  785. {
  786. $aId2Row[$oObj->GetKey()] = $idx;
  787. if ($idx <= $iMaxObjects)
  788. {
  789. $aCachedObjects[$idx] = $oObj;
  790. }
  791. $idx++;
  792. }
  793. $oObjectSet->Rewind();
  794. while ($oObject = $oObjectSet->Fetch())
  795. {
  796. $iObjectKey = $oObject->GetKey();
  797. if ($iObjectKey < 0)
  798. {
  799. $bRet = false;
  800. break;
  801. }
  802. if (!array_key_exists($iObjectKey, $aId2Row))
  803. {
  804. $bRet = false;
  805. break;
  806. }
  807. $iRow = $aId2Row[$iObjectKey];
  808. if (array_key_exists($iRow, $aCachedObjects))
  809. {
  810. // Cache hit
  811. $oSibling = $aCachedObjects[$iRow];
  812. }
  813. else
  814. {
  815. // Go fetch it from the DB, unless it's an object added in-memory
  816. $oSibling = $this->GetObjectAt($iRow);
  817. }
  818. if (!$oObject->Equals($oSibling))
  819. {
  820. $bRet = false;
  821. break;
  822. }
  823. }
  824. $this->Seek($iCurrPos); // Restore the cursor
  825. return $bRet;
  826. }
  827. protected function GetObjectAt($iIndex)
  828. {
  829. if (!$this->m_bLoaded) $this->Load();
  830. // Save the current position for iteration
  831. $iCurrPos = $this->m_iCurrRow;
  832. $this->Seek($iIndex);
  833. $oObject = $this->Fetch();
  834. // Restore the current position for iteration
  835. $this->Seek($this->m_iCurrRow);
  836. return $oObject;
  837. }
  838. /**
  839. * Build a new set (in memory) made of objects of the given set which are NOT present in the current set
  840. *
  841. * Limitations:
  842. * The objects inside the set must be written in the database since the comparison is based on their identifiers
  843. * Sets with several objects per row are NOT supported
  844. *
  845. * @param DBObjectSet $oObjectSet
  846. * @throws CoreException
  847. *
  848. * @return DBObjectSet The "delta" set.
  849. */
  850. public function CreateDelta(DBObjectSet $oObjectSet)
  851. {
  852. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  853. {
  854. throw new CoreException("Could not 'delta' two objects sets if they don't have the same root class");
  855. }
  856. if (!$this->m_bLoaded) $this->Load();
  857. $aId2Row = array();
  858. $iCurrPos = $this->m_iCurrRow; // Save the cursor
  859. $idx = 0;
  860. while($oObj = $this->Fetch())
  861. {
  862. $aId2Row[$oObj->GetKey()] = $idx;
  863. $idx++;
  864. }
  865. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  866. $oObjectSet->Seek(0);
  867. while ($oObject = $oObjectSet->Fetch())
  868. {
  869. if (!array_key_exists($oObject->GetKey(), $aId2Row))
  870. {
  871. $oNewSet->AddObject($oObject);
  872. }
  873. }
  874. $this->Seek($iCurrPos); // Restore the cursor
  875. return $oNewSet;
  876. }
  877. /**
  878. * Compute the "RelatedObjects" (for the given relation, as defined by MetaModel::GetRelatedObjects) for a whole set of DBObjects
  879. *
  880. * @param string $sRelCode The code of the relation to use for the computation
  881. * @param int $iMaxDepth Teh maximum recursion depth
  882. *
  883. * @return Array An array containg all the "related" objects
  884. */
  885. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99)
  886. {
  887. $aRelatedObjs = array();
  888. $aVisited = array(); // optimization for consecutive calls of MetaModel::GetRelatedObjects
  889. $this->Seek(0);
  890. while ($oObject = $this->Fetch())
  891. {
  892. $aMore = $oObject->GetRelatedObjects($sRelCode, $iMaxDepth, $aVisited);
  893. foreach ($aMore as $sClass => $aRelated)
  894. {
  895. foreach ($aRelated as $iObj => $oObj)
  896. {
  897. if (!isset($aRelatedObjs[$sClass][$iObj]))
  898. {
  899. $aRelatedObjs[$sClass][$iObj] = $oObj;
  900. }
  901. }
  902. }
  903. }
  904. return $aRelatedObjs;
  905. }
  906. /**
  907. * Builds an object that contains the values that are common to all the objects
  908. * in the set. If for a given attribute, objects in the set have various values
  909. * then the resulting object will contain null for this value.
  910. * @param $aValues Hash Output: the distribution of the values, in the set, for each attribute
  911. * @return DBObject The object with the common values
  912. */
  913. public function ComputeCommonObject(&$aValues)
  914. {
  915. $sClass = $this->GetClass();
  916. $aList = MetaModel::ListAttributeDefs($sClass);
  917. $aValues = array();
  918. foreach($aList as $sAttCode => $oAttDef)
  919. {
  920. if ($oAttDef->IsScalar())
  921. {
  922. $aValues[$sAttCode] = array();
  923. }
  924. }
  925. $this->Rewind();
  926. while($oObj = $this->Fetch())
  927. {
  928. foreach($aList as $sAttCode => $oAttDef)
  929. {
  930. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  931. {
  932. $currValue = $oObj->Get($sAttCode);
  933. if (is_object($currValue)) continue; // Skip non scalar values...
  934. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  935. {
  936. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  937. }
  938. else
  939. {
  940. $aValues[$sAttCode][$currValue]['count']++;
  941. }
  942. }
  943. }
  944. }
  945. foreach($aValues as $sAttCode => $aMultiValues)
  946. {
  947. if (count($aMultiValues) > 1)
  948. {
  949. uasort($aValues[$sAttCode], 'HashCountComparison');
  950. }
  951. }
  952. // Now create an object that has values for the homogenous values only
  953. $oCommonObj = new $sClass(); // @@ What if the class is abstract ?
  954. $aComments = array();
  955. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  956. $sReadyScript = '';
  957. $aDependsOn = array();
  958. $sFormPrefix = '2_';
  959. foreach($aList as $sAttCode => $oAttDef)
  960. {
  961. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  962. {
  963. if ($oAttDef->GetEditClass() == 'One Way Password')
  964. {
  965. $oCommonObj->Set($sAttCode, null);
  966. }
  967. else
  968. {
  969. $iCount = count($aValues[$sAttCode]);
  970. if ($iCount == 1)
  971. {
  972. // Homogenous value
  973. reset($aValues[$sAttCode]);
  974. $aKeys = array_keys($aValues[$sAttCode]);
  975. $currValue = $aKeys[0]; // The only value is the first key
  976. $oCommonObj->Set($sAttCode, $currValue);
  977. }
  978. else
  979. {
  980. // Non-homogenous value
  981. $oCommonObj->Set($sAttCode, null);
  982. }
  983. }
  984. }
  985. }
  986. $this->Rewind();
  987. return $oCommonObj;
  988. }
  989. /**
  990. * List the constant fields (and their value) in the given query
  991. * @return Hash [Alias][AttCode] => value
  992. */
  993. public function ListConstantFields()
  994. {
  995. $aScalarArgs = $this->ExpandArgs();
  996. $aConst = $this->m_oFilter->ListConstantFields();
  997. foreach($aConst as $sClassAlias => $aVals)
  998. {
  999. foreach($aVals as $sCode => $oExpr)
  1000. {
  1001. $oScalarExpr = $oExpr->GetAsScalar($aScalarArgs);
  1002. $aConst[$sClassAlias][$sCode] = $oScalarExpr->GetValue();
  1003. }
  1004. }
  1005. return $aConst;
  1006. }
  1007. protected function ExpandArgs()
  1008. {
  1009. $aScalarArgs = $this->m_oFilter->GetInternalParams();
  1010. foreach($this->m_aArgs as $sArgName => $value)
  1011. {
  1012. if (MetaModel::IsValidObject($value))
  1013. {
  1014. if (strpos($sArgName, '->object()') === false)
  1015. {
  1016. // Lazy syntax - develop the object contextual parameters
  1017. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgsForQuery($sArgName));
  1018. }
  1019. else
  1020. {
  1021. // Leave as is
  1022. $aScalarArgs[$sArgName] = $value;
  1023. }
  1024. }
  1025. else
  1026. {
  1027. if (!is_array($value)) // Sometimes ExtraParams contains a mix (like defaults[]) so non scalar parameters are ignored
  1028. {
  1029. $aScalarArgs[$sArgName] = (string) $value;
  1030. }
  1031. }
  1032. }
  1033. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1034. return $aScalarArgs;
  1035. }
  1036. public function ApplyParameters()
  1037. {
  1038. $aScalarArgs = $this->ExpandArgs();
  1039. $this->m_oFilter->ApplyParameters($aScalarArgs);
  1040. }
  1041. }
  1042. /**
  1043. * Helper function to perform a custom sort of a hash array
  1044. */
  1045. function HashCountComparison($a, $b) // Sort descending on 'count'
  1046. {
  1047. if ($a['count'] == $b['count'])
  1048. {
  1049. return 0;
  1050. }
  1051. return ($a['count'] > $b['count']) ? -1 : 1;
  1052. }
  1053. ?>