bulkchange.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. * Bulk change facility (common to interactive and batch usages)
  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. * BulkChange
  26. * Interpret a given data set and update the DB accordingly (fake mode avail.)
  27. *
  28. * @package iTopORM
  29. */
  30. class BulkChangeException extends CoreException
  31. {
  32. }
  33. /**
  34. * CellChangeSpec
  35. * A series of classes, keeping the information about a given cell: could it be changed or not (and why)?
  36. *
  37. * @package iTopORM
  38. */
  39. abstract class CellChangeSpec
  40. {
  41. protected $m_proposedValue;
  42. protected $m_sOql; // in case of ambiguity
  43. public function __construct($proposedValue, $sOql = '')
  44. {
  45. $this->m_proposedValue = $proposedValue;
  46. $this->m_sOql = $sOql;
  47. }
  48. static protected function ValueAsHtml($value)
  49. {
  50. if (MetaModel::IsValidObject($value))
  51. {
  52. return $value->GetHyperLink();
  53. }
  54. else
  55. {
  56. return htmlentities($value, ENT_QUOTES, 'UTF-8');
  57. }
  58. }
  59. public function GetValue()
  60. {
  61. return $this->m_proposedValue;
  62. }
  63. public function GetOql()
  64. {
  65. return $this->m_sOql;
  66. }
  67. abstract public function GetDescription();
  68. }
  69. class CellStatus_Void extends CellChangeSpec
  70. {
  71. public function GetDescription()
  72. {
  73. return '';
  74. }
  75. }
  76. class CellStatus_Modify extends CellChangeSpec
  77. {
  78. protected $m_previousValue;
  79. public function __construct($proposedValue, $previousValue)
  80. {
  81. $this->m_previousValue = $previousValue;
  82. parent::__construct($proposedValue);
  83. }
  84. public function GetDescription()
  85. {
  86. return 'Modified';
  87. }
  88. public function GetPreviousValue()
  89. {
  90. return $this->m_previousValue;
  91. }
  92. }
  93. class CellStatus_Issue extends CellStatus_Modify
  94. {
  95. protected $m_sReason;
  96. public function __construct($proposedValue, $previousValue, $sReason)
  97. {
  98. $this->m_sReason = $sReason;
  99. parent::__construct($proposedValue, $previousValue);
  100. }
  101. public function GetDescription()
  102. {
  103. if (is_null($this->m_proposedValue))
  104. {
  105. return 'Could not be changed - reason: '.$this->m_sReason;
  106. }
  107. return 'Could not be changed to '.$this->m_proposedValue.' - reason: '.$this->m_sReason;
  108. }
  109. }
  110. class CellStatus_SearchIssue extends CellStatus_Issue
  111. {
  112. public function __construct()
  113. {
  114. parent::__construct(null, null, null);
  115. }
  116. public function GetDescription()
  117. {
  118. return 'No match';
  119. }
  120. }
  121. class CellStatus_NullIssue extends CellStatus_Issue
  122. {
  123. public function __construct()
  124. {
  125. parent::__construct(null, null, null);
  126. }
  127. public function GetDescription()
  128. {
  129. return 'Missing mandatory value';
  130. }
  131. }
  132. class CellStatus_Ambiguous extends CellStatus_Issue
  133. {
  134. protected $m_iCount;
  135. public function __construct($previousValue, $iCount, $sOql)
  136. {
  137. $this->m_iCount = $iCount;
  138. $this->m_sQuery = $sOql;
  139. parent::__construct(null, $previousValue, '');
  140. }
  141. public function GetDescription()
  142. {
  143. $sCount = $this->m_iCount;
  144. return "Ambiguous: found $sCount objects";
  145. }
  146. }
  147. /**
  148. * RowStatus
  149. * A series of classes, keeping the information about a given row: could it be changed or not (and why)?
  150. *
  151. * @package iTopORM
  152. */
  153. abstract class RowStatus
  154. {
  155. public function __construct()
  156. {
  157. }
  158. abstract public function GetDescription();
  159. }
  160. class RowStatus_NoChange extends RowStatus
  161. {
  162. public function GetDescription()
  163. {
  164. return "unchanged";
  165. }
  166. }
  167. class RowStatus_NewObj extends RowStatus
  168. {
  169. public function GetDescription()
  170. {
  171. return "created";
  172. }
  173. }
  174. class RowStatus_Modify extends RowStatus
  175. {
  176. protected $m_iChanged;
  177. public function __construct($iChanged)
  178. {
  179. $this->m_iChanged = $iChanged;
  180. }
  181. public function GetDescription()
  182. {
  183. return "updated ".$this->m_iChanged." cols";
  184. }
  185. }
  186. class RowStatus_Issue extends RowStatus
  187. {
  188. protected $m_sReason;
  189. public function __construct($sReason)
  190. {
  191. $this->m_sReason = $sReason;
  192. }
  193. public function GetDescription()
  194. {
  195. return 'Issue: '.$this->m_sReason;
  196. }
  197. }
  198. /**
  199. * BulkChange
  200. *
  201. * @package iTopORM
  202. */
  203. class BulkChange
  204. {
  205. protected $m_sClass;
  206. protected $m_aData; // Note: hereafter, iCol maybe actually be any acceptable key (string)
  207. // #@# todo: rename the variables to sColIndex
  208. protected $m_aAttList; // attcode => iCol
  209. protected $m_aExtKeys; // aExtKeys[sExtKeyAttCode][sExtReconcKeyAttCode] = iCol;
  210. protected $m_aReconcilKeys;// attcode (attcode = 'id' for the pkey)
  211. public function __construct($sClass, $aData, $aAttList, $aExtKeys, $aReconcilKeys)
  212. {
  213. $this->m_sClass = $sClass;
  214. $this->m_aData = $aData;
  215. $this->m_aAttList = $aAttList;
  216. $this->m_aReconcilKeys = $aReconcilKeys;
  217. $this->m_aExtKeys = $aExtKeys;
  218. }
  219. protected function ResolveExternalKey($aRowData, $sAttCode, &$aResults)
  220. {
  221. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  222. $oReconFilter = new CMDBSearchFilter($oExtKey->GetTargetClass());
  223. foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol)
  224. {
  225. // The foreign attribute is one of our reconciliation key
  226. $oReconFilter->AddCondition($sForeignAttCode, $aRowData[$iCol], '=');
  227. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  228. }
  229. $oExtObjects = new CMDBObjectSet($oReconFilter);
  230. $aKeys = $oExtObjects->ToArray();
  231. return array($oReconFilter->ToOql(), $aKeys);
  232. }
  233. // Returns true if the CSV data specifies that the external key must be left undefined
  234. protected function IsNullExternalKeySpec($aRowData, $sAttCode)
  235. {
  236. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  237. foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol)
  238. {
  239. // The foreign attribute is one of our reconciliation key
  240. if (strlen($aRowData[$iCol]) > 0)
  241. {
  242. return false;
  243. }
  244. }
  245. return true;
  246. }
  247. protected function PrepareObject(&$oTargetObj, $aRowData, &$aErrors)
  248. {
  249. $aResults = array();
  250. $aErrors = array();
  251. // External keys reconciliation
  252. //
  253. foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig)
  254. {
  255. // Skip external keys used for the reconciliation process
  256. // if (!array_key_exists($sAttCode, $this->m_aAttList)) continue;
  257. $oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
  258. if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
  259. {
  260. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  261. {
  262. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  263. }
  264. if ($oExtKey->IsNullAllowed())
  265. {
  266. $oTargetObj->Set($sAttCode, $oExtKey->GetNullValue());
  267. $aResults[$sAttCode]= new CellStatus_Void($oExtKey->GetNullValue());
  268. }
  269. else
  270. {
  271. $aErrors[$sAttCode] = "Null not allowed";
  272. $aResults[$sAttCode]= new CellStatus_Issue(null, $oTargetObj->Get($sAttCode), 'Null not allowed');
  273. }
  274. }
  275. else
  276. {
  277. $oReconFilter = new CMDBSearchFilter($oExtKey->GetTargetClass());
  278. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  279. {
  280. // The foreign attribute is one of our reconciliation key
  281. $oReconFilter->AddCondition($sForeignAttCode, $aRowData[$iCol], '=');
  282. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  283. }
  284. $oExtObjects = new CMDBObjectSet($oReconFilter);
  285. switch($oExtObjects->Count())
  286. {
  287. case 0:
  288. $aErrors[$sAttCode] = "Object not found";
  289. $aResults[$sAttCode]= new CellStatus_SearchIssue();
  290. break;
  291. case 1:
  292. // Do change the external key attribute
  293. $oForeignObj = $oExtObjects->Fetch();
  294. $oTargetObj->Set($sAttCode, $oForeignObj->GetKey());
  295. break;
  296. default:
  297. $aErrors[$sAttCode] = "Found ".$oExtObjects->Count()." matches";
  298. $aResults[$sAttCode]= new CellStatus_Ambiguous($oTargetObj->Get($sAttCode), $oExtObjects->Count(), $oReconFilter->ToOql());
  299. }
  300. }
  301. // Report
  302. if (!array_key_exists($sAttCode, $aResults))
  303. {
  304. $iForeignObj = $oTargetObj->Get($sAttCode);
  305. if (array_key_exists($sAttCode, $oTargetObj->ListChanges()))
  306. {
  307. if ($oTargetObj->IsNew())
  308. {
  309. $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
  310. }
  311. else
  312. {
  313. $aResults[$sAttCode]= new CellStatus_Modify($iForeignObj, $oTargetObj->GetOriginal($sAttCode));
  314. }
  315. }
  316. else
  317. {
  318. $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
  319. }
  320. }
  321. }
  322. // Set the object attributes
  323. //
  324. foreach ($this->m_aAttList as $sAttCode => $iCol)
  325. {
  326. // skip the private key, if any
  327. if ($sAttCode == 'id') continue;
  328. $res = $oTargetObj->CheckValue($sAttCode, $aRowData[$iCol]);
  329. if ($res === true)
  330. {
  331. $oTargetObj->Set($sAttCode, $aRowData[$iCol]);
  332. }
  333. else
  334. {
  335. // $res is a string with the error description
  336. $aErrors[$sAttCode] = "Unexpected value for attribute '$sAttCode': $res";
  337. }
  338. }
  339. // Reporting on fields
  340. //
  341. $aChangedFields = $oTargetObj->ListChanges();
  342. foreach ($this->m_aAttList as $sAttCode => $iCol)
  343. {
  344. if ($sAttCode == 'id')
  345. {
  346. $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
  347. }
  348. if (isset($aErrors[$sAttCode]))
  349. {
  350. $aResults[$iCol]= new CellStatus_Issue($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode), $aErrors[$sAttCode]);
  351. }
  352. elseif (array_key_exists($sAttCode, $aChangedFields))
  353. {
  354. if ($oTargetObj->IsNew())
  355. {
  356. $aResults[$iCol]= new CellStatus_Void($oTargetObj->Get($sAttCode));
  357. }
  358. else
  359. {
  360. $aResults[$iCol]= new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode));
  361. }
  362. }
  363. else
  364. {
  365. // By default... nothing happens
  366. $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
  367. }
  368. }
  369. // Checks
  370. //
  371. $res = $oTargetObj->CheckConsistency();
  372. if ($res !== true)
  373. {
  374. // $res contains the error description
  375. $aErrors["GLOBAL"] = "Attributes not consistent with each others: $res";
  376. }
  377. return $aResults;
  378. }
  379. protected function CreateObject(&$aResult, $iRow, $aRowData, CMDBChange $oChange = null)
  380. {
  381. $oTargetObj = MetaModel::NewObject($this->m_sClass);
  382. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  383. if (count($aErrors) > 0)
  384. {
  385. $sErrors = implode(', ', $aErrors);
  386. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue("Unexpected attribute value(s)");
  387. return;
  388. }
  389. // Check that any external key will have a value proposed
  390. $aMissingKeys = array();
  391. foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey)
  392. {
  393. if (!$oExtKey->IsNullAllowed())
  394. {
  395. if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList))
  396. {
  397. $aMissingKeys[] = $oExtKey->GetLabel();
  398. }
  399. }
  400. }
  401. if (count($aMissingKeys) > 0)
  402. {
  403. $sMissingKeys = implode(', ', $aMissingKeys);
  404. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue("Could not be created, due to missing external key(s): $sMissingKeys");
  405. return;
  406. }
  407. // Optionaly record the results
  408. //
  409. if ($oChange)
  410. {
  411. $newID = $oTargetObj->DBInsertTrackedNoReload($oChange);
  412. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj($this->m_sClass, $newID);
  413. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  414. $aResult[$iRow]["id"] = new CellStatus_Void($newID);
  415. }
  416. else
  417. {
  418. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj();
  419. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  420. $aResult[$iRow]["id"] = new CellStatus_Void(0);
  421. }
  422. }
  423. protected function UpdateObject(&$aResult, $iRow, $oTargetObj, $aRowData, CMDBChange $oChange = null)
  424. {
  425. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  426. // Reporting
  427. //
  428. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  429. $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
  430. if (count($aErrors) > 0)
  431. {
  432. $sErrors = implode(', ', $aErrors);
  433. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue("Unexpected attribute value(s)");
  434. return;
  435. }
  436. $aChangedFields = $oTargetObj->ListChanges();
  437. if (count($aChangedFields) > 0)
  438. {
  439. $aResult[$iRow]["__STATUS__"] = new RowStatus_Modify(count($aChangedFields));
  440. // Optionaly record the results
  441. //
  442. if ($oChange)
  443. {
  444. $oTargetObj->DBUpdateTracked($oChange);
  445. }
  446. }
  447. else
  448. {
  449. $aResult[$iRow]["__STATUS__"] = new RowStatus_NoChange();
  450. }
  451. }
  452. public function Process(CMDBChange $oChange = null)
  453. {
  454. // Note: $oChange can be null, in which case the aim is to check what would be done
  455. // Debug...
  456. //
  457. if (false)
  458. {
  459. echo "<pre>\n";
  460. echo "Attributes:\n";
  461. print_r($this->m_aAttList);
  462. echo "ExtKeys:\n";
  463. print_r($this->m_aExtKeys);
  464. echo "Reconciliation:\n";
  465. print_r($this->m_aReconcilKeys);
  466. //echo "Data:\n";
  467. //print_r($this->m_aData);
  468. echo "</pre>\n";
  469. exit;
  470. }
  471. // Compute the results
  472. //
  473. $aResult = array();
  474. foreach($this->m_aData as $iRow => $aRowData)
  475. {
  476. $oReconciliationFilter = new CMDBSearchFilter($this->m_sClass);
  477. $bSkipQuery = false;
  478. foreach($this->m_aReconcilKeys as $sAttCode)
  479. {
  480. $valuecondition = null;
  481. if (array_key_exists($sAttCode, $this->m_aExtKeys))
  482. {
  483. if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
  484. {
  485. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  486. if ($oExtKey->IsNullAllowed())
  487. {
  488. $valuecondition = $oExtKey->GetNullValue();
  489. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oExtKey->GetNullValue());
  490. }
  491. else
  492. {
  493. $aResult[$iRow][$sAttCode] = new CellStatus_NullIssue();
  494. }
  495. }
  496. else
  497. {
  498. // The value has to be found or verified
  499. list($sQuery, $aMatches) = $this->ResolveExternalKey($aRowData, $sAttCode, $aResult[$iRow]);
  500. if (count($aMatches) == 1)
  501. {
  502. $oRemoteObj = reset($aMatches); // first item
  503. $valuecondition = $oRemoteObj->GetKey();
  504. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oRemoteObj->GetKey());
  505. }
  506. elseif (count($aMatches) == 0)
  507. {
  508. $aResult[$iRow][$sAttCode] = new CellStatus_SearchIssue();
  509. }
  510. else
  511. {
  512. $aResult[$iRow][$sAttCode] = new CellStatus_Ambiguous(null, count($aMatches), $sQuery);
  513. }
  514. }
  515. }
  516. else
  517. {
  518. // The value is given in the data row
  519. $iCol = $this->m_aAttList[$sAttCode];
  520. $valuecondition = $aRowData[$iCol];
  521. }
  522. if (is_null($valuecondition))
  523. {
  524. $bSkipQuery = true;
  525. }
  526. else
  527. {
  528. $oReconciliationFilter->AddCondition($sAttCode, $valuecondition, '=');
  529. }
  530. }
  531. if ($bSkipQuery)
  532. {
  533. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue("failed to reconcile");
  534. }
  535. else
  536. {
  537. $oReconciliationSet = new CMDBObjectSet($oReconciliationFilter);
  538. switch($oReconciliationSet->Count())
  539. {
  540. case 0:
  541. $this->CreateObject($aResult, $iRow, $aRowData, $oChange);
  542. // $aResult[$iRow]["__STATUS__"]=> set in CreateObject
  543. break;
  544. case 1:
  545. $oTargetObj = $oReconciliationSet->Fetch();
  546. $this->UpdateObject($aResult, $iRow, $oTargetObj, $aRowData, $oChange);
  547. // $aResult[$iRow]["__STATUS__"]=> set in UpdateObject
  548. break;
  549. default:
  550. // Found several matches, ambiguous
  551. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue("ambiguous reconciliation");
  552. $aResult[$iRow]["id"]= new CellStatus_Ambiguous(0, $oReconciliationSet->Count(), $oReconciliationFilter->ToOql());
  553. $aResult[$iRow]["finalclass"]= 'n/a';
  554. }
  555. }
  556. // Whatever happened, do report the reconciliation values
  557. foreach($this->m_aAttList as $iCol)
  558. {
  559. if (!array_key_exists($iCol, $aResult[$iRow]))
  560. {
  561. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  562. }
  563. }
  564. foreach($this->m_aExtKeys as $sAttCode => $aForeignAtts)
  565. {
  566. if (!array_key_exists($sAttCode, $aResult[$iRow]))
  567. {
  568. $aResult[$iRow][$sAttCode] = new CellStatus_Void('n/a');
  569. }
  570. foreach ($aForeignAtts as $sForeignAttCode => $iCol)
  571. {
  572. if (!array_key_exists($iCol, $aResult[$iRow]))
  573. {
  574. // The foreign attribute is one of our reconciliation key
  575. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  576. }
  577. }
  578. }
  579. }
  580. return $aResult;
  581. }
  582. }
  583. ?>