dbobjectset.class.php 32 KB

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