ormlinkset.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once('dbobjectiterator.php');
  19. /**
  20. * The value for an attribute representing a set of links between the host object and "remote" objects
  21. *
  22. * @package iTopORM
  23. * @copyright Copyright (C) 2010-2017 Combodo SARL
  24. * @license http://opensource.org/licenses/AGPL-3.0
  25. */
  26. class ormLinkSet implements iDBObjectSetIterator, Iterator, SeekableIterator
  27. {
  28. protected $sHostClass; // subclass of DBObject
  29. protected $sAttCode; // xxxxxx_list
  30. protected $sClass; // class of the links
  31. /**
  32. * @var DBObjectSet
  33. */
  34. protected $oOriginalSet;
  35. /**
  36. * @var DBObject[] array of iObjectId => DBObject
  37. */
  38. protected $aOriginalObjects = null;
  39. /**
  40. * @var bool
  41. */
  42. protected $bHasDelta = false;
  43. /**
  44. * Object from the original set, minus the removed objects
  45. * @var DBObject[] array of iObjectId => DBObject
  46. */
  47. protected $aPreserved = array();
  48. /**
  49. * @var DBObject[] New items
  50. */
  51. protected $aAdded = array();
  52. /**
  53. * @var DBObject[] Modified items (could also be found in aPreserved)
  54. */
  55. protected $aModified = array();
  56. /**
  57. * @var int[] Removed items
  58. */
  59. protected $aRemoved = array();
  60. /**
  61. * @var int Position in the collection
  62. */
  63. protected $iCursor = 0;
  64. /**
  65. * ormLinkSet constructor.
  66. * @param $sHostClass
  67. * @param $sAttCode
  68. * @param DBObjectSet|null $oOriginalSet
  69. * @throws Exception
  70. */
  71. public function __construct($sHostClass, $sAttCode, DBObjectSet $oOriginalSet = null)
  72. {
  73. $this->sHostClass = $sHostClass;
  74. $this->sAttCode = $sAttCode;
  75. $this->oOriginalSet = $oOriginalSet ? clone $oOriginalSet : null;
  76. $oAttDef = MetaModel::GetAttributeDef($sHostClass, $sAttCode);
  77. if (!$oAttDef instanceof AttributeLinkedSet)
  78. {
  79. throw new Exception("ormLinkSet: $sAttCode is not a link set");
  80. }
  81. $this->sClass = $oAttDef->GetLinkedClass();
  82. if ($oOriginalSet && ($oOriginalSet->GetClass() != $this->sClass))
  83. {
  84. throw new Exception("ormLinkSet: wrong class for the original set, found {$oOriginalSet->GetClass()} while expecting {$oAttDef->GetLinkedClass()}");
  85. }
  86. }
  87. public function GetFilter()
  88. {
  89. return clone $this->oOriginalSet->GetFilter();
  90. }
  91. /**
  92. * Specify the subset of attributes to load (for each class of objects) before performing the SQL query for retrieving the rows from the DB
  93. *
  94. * @param hash $aAttToLoad Format: alias => array of attribute_codes
  95. *
  96. * @return void
  97. */
  98. public function OptimizeColumnLoad($aAttToLoad)
  99. {
  100. $this->oOriginalSet->OptimizeColumnLoad($aAttToLoad);
  101. }
  102. /**
  103. * @param DBObject $oLink
  104. */
  105. public function AddItem(DBObject $oLink)
  106. {
  107. assert($oLink instanceof $this->sClass);
  108. // No impact on the iteration algorithm
  109. $this->aAdded[] = $oLink;
  110. $this->bHasDelta = true;
  111. }
  112. /**
  113. * @param DBObject $oObject
  114. * @param string $sClassAlias
  115. * @deprecated Since iTop 2.4, use ormLinkset->AddItem() instead.
  116. */
  117. public function AddObject(DBObject $oObject, $sClassAlias = '')
  118. {
  119. $this->AddItem($oObject);
  120. }
  121. /**
  122. * @param $iObjectId
  123. */
  124. public function RemoveItem($iObjectId)
  125. {
  126. if (array_key_exists($iObjectId, $this->aPreserved))
  127. {
  128. unset($this->aPreserved[$iObjectId]);
  129. $this->aRemoved[$iObjectId] = $iObjectId;
  130. $this->bHasDelta = true;
  131. }
  132. }
  133. /**
  134. * @param DBObject $oLink
  135. */
  136. public function ModifyItem(DBObject $oLink)
  137. {
  138. assert($oLink instanceof $this->sClass);
  139. $iObjectId = $oLink->GetKey();
  140. if (array_key_exists($iObjectId, $this->aPreserved))
  141. {
  142. unset($this->aPreserved[$iObjectId]);
  143. $this->aModified[$iObjectId] = $oLink;
  144. $this->bHasDelta = true;
  145. }
  146. }
  147. protected function LoadOriginalIds()
  148. {
  149. if ($this->aOriginalObjects === null)
  150. {
  151. if ($this->oOriginalSet)
  152. {
  153. $this->aOriginalObjects = $this->GetArrayOfIndex();
  154. $this->aPreserved = $this->aOriginalObjects; // Copy (not effective until aPreserved gets modified)
  155. foreach ($this->aRemoved as $iObjectId)
  156. {
  157. if (array_key_exists($iObjectId, $this->aPreserved))
  158. {
  159. unset($this->aPreserved[$iObjectId]);
  160. }
  161. }
  162. foreach ($this->aModified as $iObjectId => $oLink)
  163. {
  164. if (array_key_exists($iObjectId, $this->aPreserved))
  165. {
  166. unset($this->aPreserved[$iObjectId]);
  167. }
  168. }
  169. }
  170. else
  171. {
  172. // Nothing to load
  173. $this->aOriginalObjects = array();
  174. $this->aPreserved = array();
  175. }
  176. }
  177. }
  178. /**
  179. * Note: After calling this method, the set cursor will be at the end of the set. You might want to rewind it.
  180. * @return array
  181. */
  182. protected function GetArrayOfIndex()
  183. {
  184. $aRet = array();
  185. $this->oOriginalSet->Rewind();
  186. $iRow = 0;
  187. while ($oObject = $this->oOriginalSet->Fetch())
  188. {
  189. $aRet[$oObject->GetKey()] = $iRow++;
  190. }
  191. return $aRet;
  192. }
  193. /**
  194. * @param bool $bWithId
  195. * @return array
  196. * @deprecated Since iTop 2.4, use foreach($this as $oItem){} instead
  197. */
  198. public function ToArray($bWithId = true)
  199. {
  200. $aRet = array();
  201. foreach($this as $oItem)
  202. {
  203. if ($bWithId)
  204. {
  205. $aRet[$oItem->GetKey()] = $oItem;
  206. }
  207. else
  208. {
  209. $aRet[] = $oItem;
  210. }
  211. }
  212. return $aRet;
  213. }
  214. /**
  215. * @param string $sAttCode
  216. * @param bool $bWithId
  217. * @return array
  218. */
  219. public function GetColumnAsArray($sAttCode, $bWithId = true)
  220. {
  221. $aRet = array();
  222. foreach($this as $oItem)
  223. {
  224. if ($bWithId)
  225. {
  226. $aRet[$oItem->GetKey()] = $oItem->Get($sAttCode);
  227. }
  228. else
  229. {
  230. $aRet[] = $oItem->Get($sAttCode);
  231. }
  232. }
  233. return $aRet;
  234. }
  235. /**
  236. * The class of the objects of the collection (at least a common ancestor)
  237. *
  238. * @return string
  239. */
  240. public function GetClass()
  241. {
  242. return $this->sClass;
  243. }
  244. /**
  245. * The total number of objects in the collection
  246. *
  247. * @return int
  248. */
  249. public function Count()
  250. {
  251. $this->LoadOriginalIds();
  252. $iRet = count($this->aPreserved) + count($this->aAdded) + count($this->aModified);
  253. return $iRet;
  254. }
  255. /**
  256. * Position the cursor to the given 0-based position
  257. *
  258. * @param $iPosition
  259. * @throws Exception
  260. * @internal param int $iRow
  261. */
  262. public function Seek($iPosition)
  263. {
  264. $this->LoadOriginalIds();
  265. $iCount = $this->Count();
  266. if ($iPosition >= $iCount)
  267. {
  268. throw new Exception("Invalid position $iPosition: the link set is made of $iCount items.");
  269. }
  270. $this->rewind();
  271. for($iPos = 0 ; $iPos < $iPosition ; $iPos++)
  272. {
  273. $this->next();
  274. }
  275. }
  276. /**
  277. * Fetch the object at the current position in the collection and move the cursor to the next position.
  278. *
  279. * @return DBObject|null The fetched object or null when at the end
  280. */
  281. public function Fetch()
  282. {
  283. $this->LoadOriginalIds();
  284. $ret = $this->current();
  285. if ($ret === false)
  286. {
  287. $ret = null;
  288. }
  289. $this->next();
  290. return $ret;
  291. }
  292. /**
  293. * Return the current element
  294. * @link http://php.net/manual/en/iterator.current.php
  295. * @return mixed Can return any type.
  296. */
  297. public function current()
  298. {
  299. $this->LoadOriginalIds();
  300. $iPreservedCount = count($this->aPreserved);
  301. if ($this->iCursor < $iPreservedCount)
  302. {
  303. $iRet = current($this->aPreserved);
  304. $this->oOriginalSet->Seek($iRet);
  305. $oRet = $this->oOriginalSet->Fetch();
  306. }
  307. else
  308. {
  309. $iModifiedCount = count($this->aModified);
  310. if($this->iCursor < $iPreservedCount + $iModifiedCount)
  311. {
  312. $oRet = current($this->aModified);
  313. }
  314. else
  315. {
  316. $oRet = current($this->aAdded);
  317. }
  318. }
  319. return $oRet;
  320. }
  321. /**
  322. * Move forward to next element
  323. * @link http://php.net/manual/en/iterator.next.php
  324. * @return void Any returned value is ignored.
  325. */
  326. public function next()
  327. {
  328. $this->LoadOriginalIds();
  329. $iPreservedCount = count($this->aPreserved);
  330. if ($this->iCursor < $iPreservedCount)
  331. {
  332. next($this->aPreserved);
  333. }
  334. else
  335. {
  336. $iModifiedCount = count($this->aModified);
  337. if($this->iCursor < $iPreservedCount + $iModifiedCount)
  338. {
  339. next($this->aModified);
  340. }
  341. else
  342. {
  343. next($this->aAdded);
  344. }
  345. }
  346. // Increment AFTER moving the internal cursors because when starting aModified / aAdded, we must leave it intact
  347. $this->iCursor++;
  348. }
  349. /**
  350. * Return the key of the current element
  351. * @link http://php.net/manual/en/iterator.key.php
  352. * @return mixed scalar on success, or null on failure.
  353. */
  354. public function key()
  355. {
  356. return $this->iCursor;
  357. }
  358. /**
  359. * Checks if current position is valid
  360. * @link http://php.net/manual/en/iterator.valid.php
  361. * @return boolean The return value will be casted to boolean and then evaluated.
  362. * Returns true on success or false on failure.
  363. */
  364. public function valid()
  365. {
  366. $this->LoadOriginalIds();
  367. $iCount = $this->Count();
  368. $bRet = ($this->iCursor < $iCount);
  369. return $bRet;
  370. }
  371. /**
  372. * Rewind the Iterator to the first element
  373. * @link http://php.net/manual/en/iterator.rewind.php
  374. * @return void Any returned value is ignored.
  375. */
  376. public function rewind()
  377. {
  378. $this->LoadOriginalIds();
  379. $this->iCursor = 0;
  380. reset($this->aPreserved);
  381. reset($this->aAdded);
  382. reset($this->aModified);
  383. }
  384. public function HasDelta()
  385. {
  386. return $this->bHasDelta;
  387. }
  388. /**
  389. * This method has been designed specifically for AttributeLinkedSet:Equals and as such it assumes that the passed argument is a clone of this.
  390. * @param ormLinkSet $oFellow
  391. * @return bool|null
  392. * @throws Exception
  393. */
  394. public function Equals(ormLinkSet $oFellow)
  395. {
  396. $bRet = null;
  397. if ($this === $oFellow)
  398. {
  399. $bRet = true;
  400. }
  401. else
  402. {
  403. if ( ($this->oOriginalSet !== $oFellow->oOriginalSet)
  404. && ($this->oOriginalSet->GetFilter()->ToOQL() != $oFellow->oOriginalSet->GetFilter()->ToOQL()) )
  405. {
  406. throw new Exception('ormLinkSet::Equals assumes that compared link sets have the same original scope');
  407. }
  408. if ($this->HasDelta())
  409. {
  410. throw new Exception('ormLinkSet::Equals assumes that left link set had no delta');
  411. }
  412. $bRet = !$oFellow->HasDelta();
  413. }
  414. return $bRet;
  415. }
  416. public function UpdateFromCompleteList(iDBObjectSetIterator $oFellow)
  417. {
  418. if ($oFellow === $this)
  419. {
  420. throw new Exception('ormLinkSet::UpdateFromCompleteList assumes that the passed link set is at least a clone of the current one');
  421. }
  422. $bUpdateFromDelta = false;
  423. if ($oFellow instanceof ormLinkSet)
  424. {
  425. if ( ($this->oOriginalSet === $oFellow->oOriginalSet)
  426. || ($this->oOriginalSet->GetFilter()->ToOQL() == $oFellow->oOriginalSet->GetFilter()->ToOQL()) )
  427. {
  428. $bUpdateFromDelta = true;
  429. }
  430. }
  431. if ($bUpdateFromDelta)
  432. {
  433. // Same original set -> simply update the delta
  434. $this->iCursor = 0;
  435. $this->aAdded = $oFellow->aAdded;
  436. $this->aRemoved = $oFellow->aRemoved;
  437. $this->aModified = $oFellow->aModified;
  438. $this->aPreserved = $oFellow->aPreserved;
  439. $this->bHasDelta = $oFellow->bHasDelta;
  440. }
  441. else
  442. {
  443. // For backward compatibility reasons, let's rebuild a delta...
  444. // Reset the delta
  445. $this->iCursor = 0;
  446. $this->aAdded = array();
  447. $this->aRemoved = array();
  448. $this->aModified = array();
  449. $this->aPreserved = ($this->aOriginalObjects === null) ? array() : $this->aOriginalObjects;
  450. $this->bHasDelta = false;
  451. /** @var AttributeLinkedSet $oAttDef */
  452. $oAttDef = MetaModel::GetAttributeDef($this->sHostClass, $this->sAttCode);
  453. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  454. $sAdditionalKey = null;
  455. if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
  456. {
  457. $sAdditionalKey = $oAttDef->GetExtKeyToRemote();
  458. }
  459. // Compare both collections by iterating the whole sets, order them, a build a fingerprint based on meaningful data (what make the difference)
  460. $oComparator = new DBObjectSetComparator($this, $oFellow, array($sExtKeyToMe), $sAdditionalKey);
  461. $aChanges = $oComparator->GetDifferences();
  462. foreach ($aChanges['added'] as $oLink)
  463. {
  464. $this->AddItem($oLink);
  465. }
  466. foreach ($aChanges['modified'] as $oLink)
  467. {
  468. $this->ModifyItem($oLink);
  469. }
  470. foreach ($aChanges['removed'] as $oLink)
  471. {
  472. $this->RemoveItem($oLink->GetKey());
  473. }
  474. }
  475. }
  476. /**
  477. * @param DBObject $oHostObject
  478. */
  479. public function DBWrite(DBObject $oHostObject)
  480. {
  481. /** @var AttributeLinkedSet $oAttDef */
  482. $oAttDef = MetaModel::GetAttributeDef(get_class($oHostObject), $this->sAttCode);
  483. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  484. $sExtKeyToRemote = $oAttDef->IsIndirect() ? $oAttDef->GetExtKeyToRemote() : 'n/a';
  485. $aCheckLinks = array();
  486. $aCheckRemote = array();
  487. foreach ($this->aAdded as $oLink)
  488. {
  489. if ($oLink->IsNew())
  490. {
  491. if ($oAttDef->IsIndirect() && !$oAttDef->DuplicatesAllowed())
  492. {
  493. //todo: faire un test qui passe dans cette branche !
  494. $aCheckRemote[] = $oLink->Get($sExtKeyToRemote);
  495. }
  496. }
  497. else
  498. {
  499. //todo: faire un test qui passe dans cette branche !
  500. $aCheckLinks[] = $oLink->GetKey();
  501. }
  502. }
  503. foreach ($this->aRemoved as $iLinkId)
  504. {
  505. $aCheckLinks[] = $iLinkId;
  506. }
  507. foreach ($this->aModified as $iLinkId => $oLink)
  508. {
  509. $aCheckLinks[] = $oLink->GetKey();
  510. }
  511. // Critical section : serialize any write access to these links
  512. //
  513. $oMtx = new iTopMutex('Write-'.$this->sClass);
  514. $oMtx->Lock();
  515. // Check for the existing links
  516. //
  517. /** @var DBObject[] $aExistingLinks */
  518. $aExistingLinks = array();
  519. /** @var Int[] $aExistingRemote */
  520. $aExistingRemote = array();
  521. if (count($aCheckLinks) > 0)
  522. {
  523. $oSearch = new DBObjectSearch($this->sClass);
  524. $oSearch->AddCondition('id', $aCheckLinks, 'IN');
  525. $oSet = new DBObjectSet($oSearch);
  526. $aExistingLinks = $oSet->ToArray();
  527. }
  528. // Check for the existing remote objects
  529. //
  530. if (count($aCheckRemote) > 0)
  531. {
  532. $oSearch = new DBObjectSearch($this->sClass);
  533. $oSearch->AddCondition($sExtKeyToMe, $oHostObject->GetKey(), '=');
  534. $oSearch->AddCondition($sExtKeyToRemote, $aCheckRemote, 'IN');
  535. $oSet = new DBObjectSet($oSearch);
  536. $aExistingRemote = $oSet->GetColumnAsArray($sExtKeyToRemote);
  537. }
  538. // Write the links according to the existing links
  539. //
  540. foreach ($this->aAdded as $oLink)
  541. {
  542. // Make sure that the objects in the set point to "this"
  543. $oLink->Set($sExtKeyToMe, $oHostObject->GetKey());
  544. if ($oLink->IsNew())
  545. {
  546. if (count($aCheckRemote) > 0)
  547. {
  548. if (in_array($oLink->Get($sExtKeyToRemote), $aExistingRemote))
  549. {
  550. // Do not create a duplicate
  551. continue;
  552. }
  553. }
  554. }
  555. else
  556. {
  557. if (!array_key_exists($oLink->GetKey(), $aExistingLinks))
  558. {
  559. $oLink->DBClone();
  560. }
  561. }
  562. $oLink->DBWrite();
  563. }
  564. foreach ($this->aRemoved as $iLinkId)
  565. {
  566. if (array_key_exists($iLinkId, $aExistingLinks))
  567. {
  568. $oLink = $aExistingLinks[$iLinkId];
  569. if ($oAttDef->IsIndirect())
  570. {
  571. $oLink->DBDelete();
  572. }
  573. else
  574. {
  575. $oExtKeyToRemote = MetaModel::GetAttributeDef($this->sClass, $sExtKeyToMe);
  576. if ($oExtKeyToRemote->IsNullAllowed())
  577. {
  578. if ($oLink->Get($sExtKeyToMe) == $oHostObject->GetKey())
  579. {
  580. // Detach the link object from this
  581. $oLink->Set($sExtKeyToMe, 0);
  582. $oLink->DBUpdate();
  583. }
  584. }
  585. else
  586. {
  587. $oLink->DBDelete();
  588. }
  589. }
  590. }
  591. }
  592. // Note: process modifications at the end: if a link to remove has also been listed as modified, then it will be gracefully ignored
  593. foreach ($this->aModified as $iLinkId => $oLink)
  594. {
  595. if (array_key_exists($oLink->GetKey(), $aExistingLinks))
  596. {
  597. $oLink->DBUpdate();
  598. }
  599. else
  600. {
  601. $oLink->DBClone();
  602. }
  603. }
  604. // End of the critical section
  605. //
  606. $oMtx->Unlock();
  607. }
  608. }