dbobjectset.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Object set management
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. /**
  25. * A set of persistent objects, could be heterogeneous
  26. *
  27. * @package iTopORM
  28. */
  29. class DBObjectSet
  30. {
  31. private $m_oFilter;
  32. private $m_aOrderBy;
  33. public $m_bLoaded;
  34. private $m_aData;
  35. private $m_aId2Row;
  36. private $m_iCurrRow;
  37. public function __construct(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0)
  38. {
  39. $this->m_oFilter = $oFilter;
  40. $this->m_aOrderBy = $aOrderBy;
  41. $this->m_aArgs = $aArgs;
  42. $this->m_aExtendedDataSpec = $aExtendedDataSpec;
  43. $this->m_iLimitCount = $iLimitCount;
  44. $this->m_iLimitStart = $iLimitStart;
  45. $this->m_iCount = null; // null if unknown yet
  46. $this->m_bLoaded = false; // true when the filter has been used OR the set is built step by step (AddObject...)
  47. $this->m_aData = array(); // array of (row => array of (classalias) => object/null)
  48. $this->m_aId2Row = array(); // array of (pkey => index in m_aData)
  49. $this->m_iCurrRow = 0;
  50. }
  51. public function __destruct()
  52. {
  53. }
  54. public function __toString()
  55. {
  56. $sRet = '';
  57. $this->Rewind();
  58. $sRet .= "Set (".$this->m_oFilter->ToOQL().")<br/>\n";
  59. $sRet .= "Query: <pre style=\"font-size: smaller; display:inline;\">".MetaModel::MakeSelectQuery($this->m_oFilter, array()).")</pre>\n";
  60. $sRet .= $this->Count()." records<br/>\n";
  61. if ($this->Count() > 0)
  62. {
  63. $sRet .= "<ul class=\"treeview\">\n";
  64. while ($oObj = $this->Fetch())
  65. {
  66. $sRet .= "<li>".$oObj->__toString()."</li>\n";
  67. }
  68. $sRet .= "</ul>\n";
  69. }
  70. return $sRet;
  71. }
  72. static public function FromObject($oObject)
  73. {
  74. $oRetSet = self::FromScratch(get_class($oObject));
  75. $oRetSet->AddObject($oObject);
  76. return $oRetSet;
  77. }
  78. static public function FromScratch($sClass)
  79. {
  80. $oFilter = new CMDBSearchFilter($sClass);
  81. $oRetSet = new self($oFilter);
  82. $oRetSet->m_bLoaded = true; // no DB load
  83. return $oRetSet;
  84. }
  85. // create an object set ex nihilo
  86. // input = array of objects
  87. static public function FromArray($sClass, $aObjects)
  88. {
  89. $oFilter = new CMDBSearchFilter($sClass);
  90. $oRetSet = new self($oFilter);
  91. $oRetSet->m_bLoaded = true; // no DB load
  92. $oRetSet->AddObjectArray($aObjects, $sClass);
  93. return $oRetSet;
  94. }
  95. // create an object set ex nihilo
  96. // aClasses = array of (alias => class)
  97. // input = array of (array of (classalias => object))
  98. static public function FromArrayAssoc($aClasses, $aObjects)
  99. {
  100. // In a perfect world, we should create a complete tree of DBObjectSearch,
  101. // but as we lack most of the information related to the objects,
  102. // let's create one search definition
  103. $sClass = reset($aClasses);
  104. $sAlias = key($aClasses);
  105. $oFilter = new CMDBSearchFilter($sClass, $sAlias);
  106. $oRetSet = new self($oFilter);
  107. $oRetSet->m_bLoaded = true; // no DB load
  108. foreach($aObjects as $rowIndex => $aObjectsByClassAlias)
  109. {
  110. $oRetSet->AddObjectExtended($aObjectsByClassAlias);
  111. }
  112. return $oRetSet;
  113. }
  114. static public function FromLinkSet($oObject, $sLinkSetAttCode, $sExtKeyToRemote)
  115. {
  116. $oLinkAttCode = MetaModel::GetAttributeDef(get_class($oObject), $sLinkSetAttCode);
  117. $oExtKeyAttDef = MetaModel::GetAttributeDef($oLinkAttCode->GetLinkedClass(), $sExtKeyToRemote);
  118. $sTargetClass = $oExtKeyAttDef->GetTargetClass();
  119. $oLinkSet = $oObject->Get($sLinkSetAttCode);
  120. $aTargets = array();
  121. while ($oLink = $oLinkSet->Fetch())
  122. {
  123. $aTargets[] = MetaModel::GetObject($sTargetClass, $oLink->Get($sExtKeyToRemote));
  124. }
  125. return self::FromArray($sTargetClass, $aTargets);
  126. }
  127. public function ToArray($bWithId = true)
  128. {
  129. $aRet = array();
  130. $this->Rewind();
  131. while ($oObject = $this->Fetch())
  132. {
  133. if ($bWithId)
  134. {
  135. $aRet[$oObject->GetKey()] = $oObject;
  136. }
  137. else
  138. {
  139. $aRet[] = $oObject;
  140. }
  141. }
  142. return $aRet;
  143. }
  144. public function ToArrayOfValues()
  145. {
  146. if (!$this->m_bLoaded) $this->Load();
  147. $aSelectedClasses = $this->m_oFilter->GetSelectedClasses();
  148. $aRet = array();
  149. foreach($this->m_aData as $iRow => $aObjects)
  150. {
  151. foreach($aObjects as $sClassAlias => $oObject)
  152. {
  153. if (is_null($oObject))
  154. {
  155. $aRet[$iRow][$sClassAlias.'.'.'id'] = null;
  156. }
  157. else
  158. {
  159. $aRet[$iRow][$sClassAlias.'.'.'id'] = $oObject->GetKey();
  160. }
  161. if (is_null($oObject))
  162. {
  163. $sClass = $aSelectedClasses[$sClassAlias];
  164. }
  165. else
  166. {
  167. $sClass = get_class($oObject);
  168. }
  169. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  170. {
  171. if ($oAttDef->IsScalar())
  172. {
  173. $sAttName = $sClassAlias.'.'.$sAttCode;
  174. if (is_null($oObject))
  175. {
  176. $aRet[$iRow][$sAttName] = null;
  177. }
  178. else
  179. {
  180. $aRet[$iRow][$sAttName] = $oObject->Get($sAttCode);
  181. }
  182. }
  183. }
  184. }
  185. }
  186. return $aRet;
  187. }
  188. public function GetColumnAsArray($sAttCode, $bWithId = true)
  189. {
  190. $aRet = array();
  191. $this->Rewind();
  192. while ($oObject = $this->Fetch())
  193. {
  194. if ($bWithId)
  195. {
  196. $aRet[$oObject->GetKey()] = $oObject->Get($sAttCode);
  197. }
  198. else
  199. {
  200. $aRet[] = $oObject->Get($sAttCode);
  201. }
  202. }
  203. return $aRet;
  204. }
  205. public function GetFilter()
  206. {
  207. // #@# This is false as soon as the set has been manipulated (AddObject...)
  208. return $this->m_oFilter;
  209. }
  210. public function GetClass()
  211. {
  212. return $this->m_oFilter->GetClass();
  213. }
  214. public function GetSelectedClasses()
  215. {
  216. return $this->m_oFilter->GetSelectedClasses();
  217. }
  218. public function GetRootClass()
  219. {
  220. return MetaModel::GetRootClass($this->GetClass());
  221. }
  222. public function SetLimit($iLimitCount, $iLimitStart = 0)
  223. {
  224. $this->m_iLimitCount = $iLimitCount;
  225. $this->m_iLimitStart = $iLimitStart;
  226. }
  227. public function GetLimitCount()
  228. {
  229. return $this->m_iLimitCount;
  230. }
  231. public function GetLimitStart()
  232. {
  233. return $this->m_iLimitStart;
  234. }
  235. public function Load()
  236. {
  237. if ($this->m_bLoaded) return;
  238. // Note: it is mandatory to set this value now, to protect against reentrance
  239. $this->m_bLoaded = true;
  240. if ($this->m_iLimitCount > 0)
  241. {
  242. $sSQL = MetaModel::MakeSelectQuery($this->m_oFilter, $this->m_aOrderBy, $this->m_aArgs, $this->m_aExtendedDataSpec, $this->m_iLimitCount, $this->m_iLimitStart);
  243. }
  244. else
  245. {
  246. $sSQL = MetaModel::MakeSelectQuery($this->m_oFilter, $this->m_aOrderBy, $this->m_aArgs, $this->m_aExtendedDataSpec);
  247. }
  248. $resQuery = CMDBSource::Query($sSQL);
  249. if (!$resQuery) return;
  250. $sClass = $this->m_oFilter->GetClass();
  251. while ($aRow = CMDBSource::FetchArray($resQuery))
  252. {
  253. $aObjects = array();
  254. foreach ($this->m_oFilter->GetSelectedClasses() as $sClassAlias => $sClass)
  255. {
  256. if (is_null($aRow[$sClassAlias.'id']))
  257. {
  258. $oObject = null;
  259. }
  260. else
  261. {
  262. $oObject = MetaModel::GetObjectByRow($sClass, $aRow, $sClassAlias, $this->m_aExtendedDataSpec);
  263. }
  264. $aObjects[$sClassAlias] = $oObject;
  265. }
  266. $this->AddObjectExtended($aObjects);
  267. }
  268. CMDBSource::FreeResult($resQuery);
  269. }
  270. public function Count()
  271. {
  272. if ($this->m_bLoaded && ($this->m_iLimitCount == 0) && ($this->m_iLimitStart == 0))
  273. {
  274. return count($this->m_aData);
  275. }
  276. else
  277. {
  278. if (is_null($this->m_iCount))
  279. {
  280. $sSQL = MetaModel::MakeSelectQuery($this->m_oFilter, $this->m_aOrderBy, $this->m_aArgs, null, 0, 0, true);
  281. $resQuery = CMDBSource::Query($sSQL);
  282. if (!$resQuery) return 0;
  283. $aRow = CMDBSource::FetchArray($resQuery);
  284. CMDBSource::FreeResult($resQuery);
  285. $this->m_iCount = $aRow['COUNT'];
  286. }
  287. return $this->m_iCount;
  288. }
  289. }
  290. public function Fetch($sClassAlias = '')
  291. {
  292. if (!$this->m_bLoaded) $this->Load();
  293. if ($this->m_iCurrRow >= count($this->m_aData))
  294. {
  295. return null;
  296. }
  297. if (strlen($sClassAlias) == 0)
  298. {
  299. $sClassAlias = $this->m_oFilter->GetClassAlias();
  300. }
  301. $oRetObj = $this->m_aData[$this->m_iCurrRow][$sClassAlias];
  302. $this->m_iCurrRow++;
  303. return $oRetObj;
  304. }
  305. // Return the whole line if several classes have been specified in the query
  306. //
  307. public function FetchAssoc()
  308. {
  309. if (!$this->m_bLoaded) $this->Load();
  310. if ($this->m_iCurrRow >= count($this->m_aData))
  311. {
  312. return null;
  313. }
  314. $aRetObjects = $this->m_aData[$this->m_iCurrRow];
  315. $this->m_iCurrRow++;
  316. return $aRetObjects;
  317. }
  318. public function Rewind()
  319. {
  320. if ($this->m_bLoaded)
  321. {
  322. $this->Seek(0);
  323. }
  324. }
  325. public function Seek($iRow)
  326. {
  327. if (!$this->m_bLoaded) $this->Load();
  328. $this->m_iCurrRow = min($iRow, count($this->m_aData));
  329. return $this->m_iCurrRow;
  330. }
  331. public function AddObject($oObject, $sClassAlias = '')
  332. {
  333. if (!$this->m_bLoaded) $this->Load();
  334. if (strlen($sClassAlias) == 0)
  335. {
  336. $sClassAlias = $this->m_oFilter->GetClassAlias();
  337. }
  338. $iNextPos = count($this->m_aData);
  339. $this->m_aData[$iNextPos][$sClassAlias] = $oObject;
  340. if (!is_null($oObject))
  341. {
  342. $this->m_aId2Row[$sClassAlias][$oObject->GetKey()] = $iNextPos;
  343. }
  344. }
  345. protected function AddObjectExtended($aObjectArray)
  346. {
  347. if (!$this->m_bLoaded) $this->Load();
  348. $iNextPos = count($this->m_aData);
  349. foreach ($aObjectArray as $sClassAlias => $oObject)
  350. {
  351. $this->m_aData[$iNextPos][$sClassAlias] = $oObject;
  352. if (!is_null($oObject))
  353. {
  354. $this->m_aId2Row[$sClassAlias][$oObject->GetKey()] = $iNextPos;
  355. }
  356. }
  357. }
  358. public function AddObjectArray($aObjects, $sClassAlias = '')
  359. {
  360. if (!$this->m_bLoaded) $this->Load();
  361. // #@# todo - add a check on the object class ?
  362. foreach ($aObjects as $oObj)
  363. {
  364. $this->AddObject($oObj, $sClassAlias);
  365. }
  366. }
  367. public function Merge($oObjectSet)
  368. {
  369. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  370. {
  371. throw new CoreException("Could not merge two objects sets if they don't have the same root class");
  372. }
  373. if (!$this->m_bLoaded) $this->Load();
  374. $oObjectSet->Seek(0);
  375. while ($oObject = $oObjectSet->Fetch())
  376. {
  377. $this->AddObject($oObject);
  378. }
  379. }
  380. public function CreateIntersect($oObjectSet)
  381. {
  382. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  383. {
  384. throw new CoreException("Could not 'intersect' two objects sets if they don't have the same root class");
  385. }
  386. if (!$this->m_bLoaded) $this->Load();
  387. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  388. $sClassAlias = $this->m_oFilter->GetClassAlias();
  389. $oObjectSet->Seek(0);
  390. while ($oObject = $oObjectSet->Fetch())
  391. {
  392. if (array_key_exists($oObject->GetKey(), $this->m_aId2Row[$sClassAlias]))
  393. {
  394. $oNewSet->AddObject($oObject);
  395. }
  396. }
  397. return $oNewSet;
  398. }
  399. // Note: This verb works only with objects existing in the database
  400. //
  401. public function HasSameContents($oObjectSet)
  402. {
  403. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  404. {
  405. return false;
  406. }
  407. if (!$this->m_bLoaded) $this->Load();
  408. if ($this->Count() != $oObjectSet->Count())
  409. {
  410. return false;
  411. }
  412. $sClassAlias = $this->m_oFilter->GetClassAlias();
  413. $oObjectSet->Rewind();
  414. while ($oObject = $oObjectSet->Fetch())
  415. {
  416. $iObjectKey = $oObject->GetKey();
  417. if ($iObjectKey < 0)
  418. {
  419. return false;
  420. }
  421. if (!array_key_exists($iObjectKey, $this->m_aId2Row[$sClassAlias]))
  422. {
  423. return false;
  424. }
  425. $iRow = $this->m_aId2Row[$sClassAlias][$iObjectKey];
  426. $oSibling = $this->m_aData[$iRow][$sClassAlias];
  427. if (!$oObject->Equals($oSibling))
  428. {
  429. return false;
  430. }
  431. }
  432. return true;
  433. }
  434. public function CreateDelta($oObjectSet)
  435. {
  436. if ($this->GetRootClass() != $oObjectSet->GetRootClass())
  437. {
  438. throw new CoreException("Could not 'delta' two objects sets if they don't have the same root class");
  439. }
  440. if (!$this->m_bLoaded) $this->Load();
  441. $oNewSet = DBObjectSet::FromScratch($this->GetClass());
  442. $sClassAlias = $this->m_oFilter->GetClassAlias();
  443. $oObjectSet->Seek(0);
  444. while ($oObject = $oObjectSet->Fetch())
  445. {
  446. if (!array_key_exists($oObject->GetKey(), $this->m_aId2Row[$sClassAlias]))
  447. {
  448. $oNewSet->AddObject($oObject);
  449. }
  450. }
  451. return $oNewSet;
  452. }
  453. public function GetRelatedObjects($sRelCode, $iMaxDepth = 99)
  454. {
  455. $aRelatedObjs = array();
  456. $aVisited = array(); // optimization for consecutive calls of MetaModel::GetRelatedObjects
  457. $this->Seek(0);
  458. while ($oObject = $this->Fetch())
  459. {
  460. $aMore = $oObject->GetRelatedObjects($sRelCode, $iMaxDepth, $aVisited);
  461. foreach ($aMore as $sClass => $aRelated)
  462. {
  463. foreach ($aRelated as $iObj => $oObj)
  464. {
  465. if (!isset($aRelatedObjs[$sClass][$iObj]))
  466. {
  467. $aRelatedObjs[$sClass][$iObj] = $oObj;
  468. }
  469. }
  470. }
  471. }
  472. return $aRelatedObjs;
  473. }
  474. /**
  475. * Builds an object that contains the values that are common to all the objects
  476. * in the set. If for a given attribute, objects in the set have various values
  477. * then the resulting object will contain null for this value.
  478. * @param $aValues Hash Output: the distribution of the values, in the set, for each attribute
  479. * @return Object
  480. */
  481. public function ComputeCommonObject(&$aValues)
  482. {
  483. $sClass = $this->GetClass();
  484. $aList = MetaModel::ListAttributeDefs($sClass);
  485. $aValues = array();
  486. foreach($aList as $sAttCode => $oAttDef)
  487. {
  488. if ($oAttDef->IsScalar())
  489. {
  490. $aValues[$sAttCode] = array();
  491. }
  492. }
  493. $this->Rewind();
  494. while($oObj = $this->Fetch())
  495. {
  496. foreach($aList as $sAttCode => $oAttDef)
  497. {
  498. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  499. {
  500. $currValue = $oObj->Get($sAttCode);
  501. if (is_object($currValue)) continue; // Skip non scalar values...
  502. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  503. {
  504. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  505. }
  506. else
  507. {
  508. $aValues[$sAttCode][$currValue]['count']++;
  509. }
  510. }
  511. }
  512. }
  513. foreach($aValues as $sAttCode => $aMultiValues)
  514. {
  515. if (count($aMultiValues) > 1)
  516. {
  517. uasort($aValues[$sAttCode], 'HashCountComparison');
  518. }
  519. }
  520. // Now create an object that has values for the homogenous values only
  521. $oCommonObj = new $sClass(); // @@ What if the class is abstract ?
  522. $aComments = array();
  523. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  524. $sReadyScript = '';
  525. $aDependsOn = array();
  526. $sFormPrefix = '2_';
  527. foreach($aList as $sAttCode => $oAttDef)
  528. {
  529. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  530. {
  531. if ($oAttDef->GetEditClass() == 'One Way Password')
  532. {
  533. $oCommonObj->Set($sAttCode, null);
  534. }
  535. else
  536. {
  537. $iCount = count($aValues[$sAttCode]);
  538. if ($iCount == 1)
  539. {
  540. // Homogenous value
  541. reset($aValues[$sAttCode]);
  542. $aKeys = array_keys($aValues[$sAttCode]);
  543. $currValue = $aKeys[0]; // The only value is the first key
  544. $oCommonObj->Set($sAttCode, $currValue);
  545. }
  546. else
  547. {
  548. // Non-homogenous value
  549. $oCommonObj->Set($sAttCode, null);
  550. }
  551. }
  552. }
  553. }
  554. $this->Rewind();
  555. return $oCommonObj;
  556. }
  557. }
  558. /**
  559. * Helper function to perform a custom sort of a hash array
  560. */
  561. function HashCountComparison($a, $b) // Sort descending on 'count'
  562. {
  563. if ($a['count'] == $b['count'])
  564. {
  565. return 0;
  566. }
  567. return ($a['count'] > $b['count']) ? -1 : 1;
  568. }
  569. ?>