bulkchange.class.inc.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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_Disappeared extends RowStatus_Modify
  187. {
  188. public function GetDescription()
  189. {
  190. return "disappeared, changed ".$this->m_iChanged." cols";
  191. }
  192. }
  193. class RowStatus_Issue extends RowStatus
  194. {
  195. protected $m_sReason;
  196. public function __construct($sReason)
  197. {
  198. $this->m_sReason = $sReason;
  199. }
  200. public function GetDescription()
  201. {
  202. return 'Issue: '.$this->m_sReason;
  203. }
  204. }
  205. /**
  206. * BulkChange
  207. *
  208. * @package iTopORM
  209. */
  210. class BulkChange
  211. {
  212. protected $m_sClass;
  213. protected $m_aData; // Note: hereafter, iCol maybe actually be any acceptable key (string)
  214. // #@# todo: rename the variables to sColIndex
  215. protected $m_aAttList; // attcode => iCol
  216. protected $m_aExtKeys; // aExtKeys[sExtKeyAttCode][sExtReconcKeyAttCode] = iCol;
  217. protected $m_aReconcilKeys; // attcode (attcode = 'id' for the pkey)
  218. protected $m_sSynchroScope; // OQL - if specified, then the missing items will be reported
  219. protected $m_aOnDisappear; // array of attcode => value, values to be set when an object gets out of scope (ignored if no scope has been defined)
  220. public function __construct($sClass, $aData, $aAttList, $aExtKeys, $aReconcilKeys, $sSynchroScope = null, $aOnDisappear = null)
  221. {
  222. $this->m_sClass = $sClass;
  223. $this->m_aData = $aData;
  224. $this->m_aAttList = $aAttList;
  225. $this->m_aReconcilKeys = $aReconcilKeys;
  226. $this->m_aExtKeys = $aExtKeys;
  227. $this->m_sSynchroScope = $sSynchroScope;
  228. $this->m_aOnDisappear = $aOnDisappear;
  229. }
  230. protected function ResolveExternalKey($aRowData, $sAttCode, &$aResults)
  231. {
  232. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  233. $oReconFilter = new CMDBSearchFilter($oExtKey->GetTargetClass());
  234. foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol)
  235. {
  236. // The foreign attribute is one of our reconciliation key
  237. $oReconFilter->AddCondition($sForeignAttCode, $aRowData[$iCol], '=');
  238. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  239. }
  240. $oExtObjects = new CMDBObjectSet($oReconFilter);
  241. $aKeys = $oExtObjects->ToArray();
  242. return array($oReconFilter->ToOql(), $aKeys);
  243. }
  244. // Returns true if the CSV data specifies that the external key must be left undefined
  245. protected function IsNullExternalKeySpec($aRowData, $sAttCode)
  246. {
  247. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  248. foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol)
  249. {
  250. // The foreign attribute is one of our reconciliation key
  251. if (strlen($aRowData[$iCol]) > 0)
  252. {
  253. return false;
  254. }
  255. }
  256. return true;
  257. }
  258. protected function PrepareObject(&$oTargetObj, $aRowData, &$aErrors)
  259. {
  260. $aResults = array();
  261. $aErrors = array();
  262. // External keys reconciliation
  263. //
  264. foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig)
  265. {
  266. // Skip external keys used for the reconciliation process
  267. // if (!array_key_exists($sAttCode, $this->m_aAttList)) continue;
  268. $oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
  269. if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
  270. {
  271. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  272. {
  273. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  274. }
  275. if ($oExtKey->IsNullAllowed())
  276. {
  277. $oTargetObj->Set($sAttCode, $oExtKey->GetNullValue());
  278. $aResults[$sAttCode]= new CellStatus_Void($oExtKey->GetNullValue());
  279. }
  280. else
  281. {
  282. $aErrors[$sAttCode] = "Null not allowed";
  283. $aResults[$sAttCode]= new CellStatus_Issue(null, $oTargetObj->Get($sAttCode), 'Null not allowed');
  284. }
  285. }
  286. else
  287. {
  288. $oReconFilter = new CMDBSearchFilter($oExtKey->GetTargetClass());
  289. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  290. {
  291. // The foreign attribute is one of our reconciliation key
  292. $oReconFilter->AddCondition($sForeignAttCode, $aRowData[$iCol], '=');
  293. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  294. }
  295. $oExtObjects = new CMDBObjectSet($oReconFilter);
  296. switch($oExtObjects->Count())
  297. {
  298. case 0:
  299. $aErrors[$sAttCode] = "Object not found";
  300. $aResults[$sAttCode]= new CellStatus_SearchIssue();
  301. break;
  302. case 1:
  303. // Do change the external key attribute
  304. $oForeignObj = $oExtObjects->Fetch();
  305. $oTargetObj->Set($sAttCode, $oForeignObj->GetKey());
  306. break;
  307. default:
  308. $aErrors[$sAttCode] = "Found ".$oExtObjects->Count()." matches";
  309. $aResults[$sAttCode]= new CellStatus_Ambiguous($oTargetObj->Get($sAttCode), $oExtObjects->Count(), $oReconFilter->ToOql());
  310. }
  311. }
  312. // Report
  313. if (!array_key_exists($sAttCode, $aResults))
  314. {
  315. $iForeignObj = $oTargetObj->Get($sAttCode);
  316. if (array_key_exists($sAttCode, $oTargetObj->ListChanges()))
  317. {
  318. if ($oTargetObj->IsNew())
  319. {
  320. $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
  321. }
  322. else
  323. {
  324. $aResults[$sAttCode]= new CellStatus_Modify($iForeignObj, $oTargetObj->GetOriginal($sAttCode));
  325. }
  326. }
  327. else
  328. {
  329. $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
  330. }
  331. }
  332. }
  333. // Set the object attributes
  334. //
  335. foreach ($this->m_aAttList as $sAttCode => $iCol)
  336. {
  337. // skip the private key, if any
  338. if ($sAttCode == 'id') continue;
  339. $res = $oTargetObj->CheckValue($sAttCode, $aRowData[$iCol]);
  340. if ($res === true)
  341. {
  342. $oTargetObj->Set($sAttCode, $aRowData[$iCol]);
  343. }
  344. else
  345. {
  346. // $res is a string with the error description
  347. $aErrors[$sAttCode] = "Unexpected value for attribute '$sAttCode': $res";
  348. }
  349. }
  350. // Reporting on fields
  351. //
  352. $aChangedFields = $oTargetObj->ListChanges();
  353. foreach ($this->m_aAttList as $sAttCode => $iCol)
  354. {
  355. if ($sAttCode == 'id')
  356. {
  357. $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
  358. }
  359. if (isset($aErrors[$sAttCode]))
  360. {
  361. $aResults[$iCol]= new CellStatus_Issue($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode), $aErrors[$sAttCode]);
  362. }
  363. elseif (array_key_exists($sAttCode, $aChangedFields))
  364. {
  365. if ($oTargetObj->IsNew())
  366. {
  367. $aResults[$iCol]= new CellStatus_Void($oTargetObj->Get($sAttCode));
  368. }
  369. else
  370. {
  371. $aResults[$iCol]= new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode));
  372. }
  373. }
  374. else
  375. {
  376. // By default... nothing happens
  377. $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
  378. }
  379. }
  380. // Checks
  381. //
  382. $res = $oTargetObj->CheckConsistency();
  383. if ($res !== true)
  384. {
  385. // $res contains the error description
  386. $aErrors["GLOBAL"] = "Attributes not consistent with each others: $res";
  387. }
  388. return $aResults;
  389. }
  390. protected function PrepareMissingObject(&$oTargetObj, &$aErrors)
  391. {
  392. $aResults = array();
  393. $aErrors = array();
  394. // External keys
  395. //
  396. foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig)
  397. {
  398. //$oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
  399. $aResults[$sAttCode]= new CellStatus_Void($oTargetObj->Get($sAttCode));
  400. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  401. {
  402. $aResults[$iCol] = new CellStatus_Void('?');
  403. }
  404. }
  405. // Update attributes
  406. //
  407. foreach($this->m_aOnDisappear as $sAttCode => $value)
  408. {
  409. if (!MetaModel::IsValidAttCode(get_class($oTargetObj), $sAttCode))
  410. {
  411. throw new BulkChangeException('Invalid attribute code', array('class' => get_class($oTargetObj), 'attcode' => $sAttCode));
  412. }
  413. $oTargetObj->Set($sAttCode, $value);
  414. if (!array_key_exists($sAttCode, $this->m_aAttList))
  415. {
  416. // #@# will be out of the reporting... (counted anyway)
  417. }
  418. }
  419. // Reporting on fields
  420. //
  421. $aChangedFields = $oTargetObj->ListChanges();
  422. foreach ($this->m_aAttList as $sAttCode => $iCol)
  423. {
  424. if ($sAttCode == 'id')
  425. {
  426. $aResults[$iCol]= new CellStatus_Void($oTargetObj->GetKey());
  427. }
  428. if (array_key_exists($sAttCode, $aChangedFields))
  429. {
  430. $aResults[$iCol]= new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode));
  431. }
  432. else
  433. {
  434. // By default... nothing happens
  435. $aResults[$iCol]= new CellStatus_Void($oTargetObj->Get($sAttCode));
  436. }
  437. }
  438. // Checks
  439. //
  440. $res = $oTargetObj->CheckConsistency();
  441. if ($res !== true)
  442. {
  443. // $res contains the error description
  444. $aErrors["GLOBAL"] = "Attributes not consistent with each others: $res";
  445. }
  446. return $aResults;
  447. }
  448. protected function CreateObject(&$aResult, $iRow, $aRowData, CMDBChange $oChange = null)
  449. {
  450. $oTargetObj = MetaModel::NewObject($this->m_sClass);
  451. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  452. if (count($aErrors) > 0)
  453. {
  454. $sErrors = implode(', ', $aErrors);
  455. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue("Unexpected attribute value(s)");
  456. return $oTargetObj;
  457. }
  458. // Check that any external key will have a value proposed
  459. $aMissingKeys = array();
  460. foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey)
  461. {
  462. if (!$oExtKey->IsNullAllowed())
  463. {
  464. if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList))
  465. {
  466. $aMissingKeys[] = $oExtKey->GetLabel();
  467. }
  468. }
  469. }
  470. if (count($aMissingKeys) > 0)
  471. {
  472. $sMissingKeys = implode(', ', $aMissingKeys);
  473. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue("Could not be created, due to missing external key(s): $sMissingKeys");
  474. return $oTargetObj;
  475. }
  476. // Optionaly record the results
  477. //
  478. if ($oChange)
  479. {
  480. $newID = $oTargetObj->DBInsertTrackedNoReload($oChange);
  481. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj($this->m_sClass, $newID);
  482. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  483. $aResult[$iRow]["id"] = new CellStatus_Void($newID);
  484. }
  485. else
  486. {
  487. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj();
  488. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  489. $aResult[$iRow]["id"] = new CellStatus_Void(0);
  490. }
  491. return $oTargetObj;
  492. }
  493. protected function UpdateObject(&$aResult, $iRow, $oTargetObj, $aRowData, CMDBChange $oChange = null)
  494. {
  495. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  496. // Reporting
  497. //
  498. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  499. $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
  500. if (count($aErrors) > 0)
  501. {
  502. $sErrors = implode(', ', $aErrors);
  503. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue("Unexpected attribute value(s)");
  504. return;
  505. }
  506. $aChangedFields = $oTargetObj->ListChanges();
  507. if (count($aChangedFields) > 0)
  508. {
  509. $aResult[$iRow]["__STATUS__"] = new RowStatus_Modify(count($aChangedFields));
  510. // Optionaly record the results
  511. //
  512. if ($oChange)
  513. {
  514. $oTargetObj->DBUpdateTracked($oChange);
  515. }
  516. }
  517. else
  518. {
  519. $aResult[$iRow]["__STATUS__"] = new RowStatus_NoChange();
  520. }
  521. }
  522. protected function UpdateMissingObject(&$aResult, $iRow, $oTargetObj, CMDBChange $oChange = null)
  523. {
  524. $aResult[$iRow] = $this->PrepareMissingObject($oTargetObj, $aErrors);
  525. // Reporting
  526. //
  527. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  528. $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
  529. if (count($aErrors) > 0)
  530. {
  531. $sErrors = implode(', ', $aErrors);
  532. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue("Unexpected attribute value(s)");
  533. return;
  534. }
  535. $aChangedFields = $oTargetObj->ListChanges();
  536. if (count($aChangedFields) > 0)
  537. {
  538. $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(count($aChangedFields));
  539. // Optionaly record the results
  540. //
  541. if ($oChange)
  542. {
  543. $oTargetObj->DBUpdateTracked($oChange);
  544. }
  545. }
  546. else
  547. {
  548. $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(0);
  549. }
  550. }
  551. public function Process(CMDBChange $oChange = null)
  552. {
  553. // Note: $oChange can be null, in which case the aim is to check what would be done
  554. // Debug...
  555. //
  556. if (false)
  557. {
  558. echo "<pre>\n";
  559. echo "Attributes:\n";
  560. print_r($this->m_aAttList);
  561. echo "ExtKeys:\n";
  562. print_r($this->m_aExtKeys);
  563. echo "Reconciliation:\n";
  564. print_r($this->m_aReconcilKeys);
  565. echo "Synchro scope:\n";
  566. print_r($this->m_sSynchroScope);
  567. echo "Synchro changes:\n";
  568. print_r($this->m_aOnDisappear);
  569. //echo "Data:\n";
  570. //print_r($this->m_aData);
  571. echo "</pre>\n";
  572. exit;
  573. }
  574. // Compute the results
  575. //
  576. if (!is_null($this->m_sSynchroScope))
  577. {
  578. $aVisited = array();
  579. }
  580. $aResult = array();
  581. foreach($this->m_aData as $iRow => $aRowData)
  582. {
  583. $oReconciliationFilter = new CMDBSearchFilter($this->m_sClass);
  584. $bSkipQuery = false;
  585. foreach($this->m_aReconcilKeys as $sAttCode)
  586. {
  587. $valuecondition = null;
  588. if (array_key_exists($sAttCode, $this->m_aExtKeys))
  589. {
  590. if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
  591. {
  592. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  593. if ($oExtKey->IsNullAllowed())
  594. {
  595. $valuecondition = $oExtKey->GetNullValue();
  596. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oExtKey->GetNullValue());
  597. }
  598. else
  599. {
  600. $aResult[$iRow][$sAttCode] = new CellStatus_NullIssue();
  601. }
  602. }
  603. else
  604. {
  605. // The value has to be found or verified
  606. list($sQuery, $aMatches) = $this->ResolveExternalKey($aRowData, $sAttCode, $aResult[$iRow]);
  607. if (count($aMatches) == 1)
  608. {
  609. $oRemoteObj = reset($aMatches); // first item
  610. $valuecondition = $oRemoteObj->GetKey();
  611. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oRemoteObj->GetKey());
  612. }
  613. elseif (count($aMatches) == 0)
  614. {
  615. $aResult[$iRow][$sAttCode] = new CellStatus_SearchIssue();
  616. }
  617. else
  618. {
  619. $aResult[$iRow][$sAttCode] = new CellStatus_Ambiguous(null, count($aMatches), $sQuery);
  620. }
  621. }
  622. }
  623. else
  624. {
  625. // The value is given in the data row
  626. $iCol = $this->m_aAttList[$sAttCode];
  627. $valuecondition = $aRowData[$iCol];
  628. }
  629. if (is_null($valuecondition))
  630. {
  631. $bSkipQuery = true;
  632. }
  633. else
  634. {
  635. $oReconciliationFilter->AddCondition($sAttCode, $valuecondition, '=');
  636. }
  637. }
  638. if ($bSkipQuery)
  639. {
  640. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue("failed to reconcile");
  641. }
  642. else
  643. {
  644. $oReconciliationSet = new CMDBObjectSet($oReconciliationFilter);
  645. switch($oReconciliationSet->Count())
  646. {
  647. case 0:
  648. $oTargetObj = $this->CreateObject($aResult, $iRow, $aRowData, $oChange);
  649. // $aResult[$iRow]["__STATUS__"]=> set in CreateObject
  650. $aVisited[] = $oTargetObj->GetKey();
  651. break;
  652. case 1:
  653. $oTargetObj = $oReconciliationSet->Fetch();
  654. $this->UpdateObject($aResult, $iRow, $oTargetObj, $aRowData, $oChange);
  655. // $aResult[$iRow]["__STATUS__"]=> set in UpdateObject
  656. if (!is_null($this->m_sSynchroScope))
  657. {
  658. $aVisited[] = $oTargetObj->GetKey();
  659. }
  660. break;
  661. default:
  662. // Found several matches, ambiguous
  663. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue("ambiguous reconciliation");
  664. $aResult[$iRow]["id"]= new CellStatus_Ambiguous(0, $oReconciliationSet->Count(), $oReconciliationFilter->ToOql());
  665. $aResult[$iRow]["finalclass"]= 'n/a';
  666. }
  667. }
  668. // Whatever happened, do report the reconciliation values
  669. foreach($this->m_aAttList as $iCol)
  670. {
  671. if (!array_key_exists($iCol, $aResult[$iRow]))
  672. {
  673. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  674. }
  675. }
  676. foreach($this->m_aExtKeys as $sAttCode => $aForeignAtts)
  677. {
  678. if (!array_key_exists($sAttCode, $aResult[$iRow]))
  679. {
  680. $aResult[$iRow][$sAttCode] = new CellStatus_Void('n/a');
  681. }
  682. foreach ($aForeignAtts as $sForeignAttCode => $iCol)
  683. {
  684. if (!array_key_exists($iCol, $aResult[$iRow]))
  685. {
  686. // The foreign attribute is one of our reconciliation key
  687. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  688. }
  689. }
  690. }
  691. }
  692. if (!is_null($this->m_sSynchroScope))
  693. {
  694. // Compute the delta between the scope and visited objects
  695. $oScopeSearch = DBObjectSearch::FromOQL($this->m_sSynchroScope);
  696. $oScopeSet = new DBObjectSet($oScopeSearch);
  697. while ($oObj = $oScopeSet->Fetch())
  698. {
  699. $iObj = $oObj->GetKey();
  700. if (!in_array($iObj, $aVisited))
  701. {
  702. $iRow++;
  703. $this->UpdateMissingObject($aResult, $iRow, $oObj, $oChange);
  704. }
  705. }
  706. }
  707. return $aResult;
  708. }
  709. /**
  710. * Display the history of bulk imports
  711. */
  712. static function DisplayImportHistory(WebPage $oPage, $bFromAjax = false, $bShowAll = false)
  713. {
  714. $sAjaxDivId = "CSVImportHistory";
  715. if (!$bFromAjax)
  716. {
  717. $oPage->add('<div id="'.$sAjaxDivId.'">');
  718. }
  719. $oPage->p(Dict::S('UI:History:BulkImports+'));
  720. $oBulkChangeSearch = DBObjectSearch::FromOQL("SELECT CMDBChange WHERE userinfo LIKE '%(CSV)'");
  721. $iQueryLimit = $bShowAll ? 0 : MetaModel::GetConfig()->GetMaxDisplayLimit() + 1;
  722. $oBulkChanges = new DBObjectSet($oBulkChangeSearch, array('date' => false), array(), $iQueryLimit);
  723. $oAppContext = new ApplicationContext();
  724. $bLimitExceeded = false;
  725. if ($oBulkChanges->Count() > MetaModel::GetConfig()->GetMaxDisplayLimit())
  726. {
  727. $bLimitExceeded = true;
  728. if (!$bShowAll)
  729. {
  730. $iMaxObjects = MetaModel::GetConfig()->GetMinDisplayLimit();
  731. $oBulkChanges->SetLimit($iMaxObjects);
  732. }
  733. }
  734. $oBulkChanges->Seek(0);
  735. $aDetails = array();
  736. while ($oChange = $oBulkChanges->Fetch())
  737. {
  738. $sDate = '<a href="?step=10&changeid='.$oChange->GetKey().'&'.$oAppContext->GetForLink().'">'.$oChange->Get('date').'</a>';
  739. $sUser = $oChange->GetUserName();
  740. if (preg_match('/^(.*)\\(CSV\\)$/i', $oChange->Get('userinfo'), $aMatches))
  741. {
  742. $sUser = $aMatches[1];
  743. }
  744. else
  745. {
  746. $sUser = $oChange->Get('userinfo');
  747. }
  748. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpCreate WHERE change = :change_id");
  749. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
  750. $iCreated = $oOpSet->Count();
  751. //while ($oCreated = $oOpSet->Fetch())
  752. //{
  753. // $oPage->p("Created ".$oCreated->Get('objclass')."::".$oCreated->Get('objkey'));
  754. //}
  755. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpSetAttribute WHERE change = :change_id");
  756. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
  757. $aModified = array();
  758. $aAttList = array();
  759. while ($oModified = $oOpSet->Fetch())
  760. {
  761. $sClass = $oModified->Get('objclass');
  762. $iKey = $oModified->Get('objkey');
  763. $sAttCode = $oModified->Get('attcode');
  764. $aAttList[$sClass][$sAttCode] = true;
  765. $aModified["$sClass::$iKey"] = true;
  766. }
  767. $iModified = count($aModified);
  768. // Assumption: there is only one class of objects being loaded
  769. // Then the last class found gives us the class for every object
  770. $aDetails[] = array('date' => $sDate, 'user' => $sUser, 'class' => $sClass, 'created' => $iCreated, 'modified' => $iModified);
  771. }
  772. $aConfig = array( 'date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  773. 'user' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  774. 'class' => array('label' => Dict::S('Core:AttributeClass'), 'description' => Dict::S('Core:AttributeClass+')),
  775. 'created' => array('label' => Dict::S('UI:History:StatsCreations'), 'description' => Dict::S('UI:History:StatsCreations+')),
  776. 'modified' => array('label' => Dict::S('UI:History:StatsModifs'), 'description' => Dict::S('UI:History:StatsModifs+')),
  777. );
  778. if ($bLimitExceeded)
  779. {
  780. if ($bShowAll)
  781. {
  782. // Collapsible list
  783. $oPage->add('<p>'.Dict::Format('UI:CountOfResults', $oBulkChanges->Count()).'&nbsp;&nbsp;<a class="truncated" onclick="OnTruncatedHistoryToggle(false);">'.Dict::S('UI:CollapseList').'</a></p>');
  784. }
  785. else
  786. {
  787. // Truncated list
  788. $iMinDisplayLimit = MetaModel::GetConfig()->GetMinDisplayLimit();
  789. $sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oBulkChanges->Count());
  790. $sLinkLabel = Dict::S('UI:DisplayAll');
  791. $oPage->add('<p>'.$sCollapsedLabel.'&nbsp;&nbsp;<a class="truncated" onclick="OnTruncatedHistoryToggle(true);">'.$sLinkLabel.'</p>');
  792. $oPage->add_ready_script(
  793. <<<EOF
  794. $('#$sAjaxDivId table.listResults').addClass('truncated');
  795. $('#$sAjaxDivId table.listResults tr:last td').addClass('truncated');
  796. EOF
  797. );
  798. $sAppContext = $oAppContext->GetForLink();
  799. $oPage->add_script(
  800. <<<EOF
  801. function OnTruncatedHistoryToggle(bShowAll)
  802. {
  803. $.get('../pages/ajax.render.php?{$sAppContext}', {operation: 'displayCSVHistory', showall: bShowAll}, function(data)
  804. {
  805. $('#$sAjaxDivId').html(data);
  806. var table = $('#$sAjaxDivId .listResults');
  807. table.tableHover(); // hover tables
  808. table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
  809. }
  810. );
  811. }
  812. EOF
  813. );
  814. }
  815. }
  816. else
  817. {
  818. // Normal display - full list without any decoration
  819. }
  820. $oPage->table($aConfig, $aDetails);
  821. if (!$bFromAjax)
  822. {
  823. $oPage->add('</div>');
  824. }
  825. }
  826. /**
  827. * Display the details of an import
  828. */
  829. static function DisplayImportHistoryDetails(iTopWebPage $oPage, $iChange)
  830. {
  831. if ($iChange == 0)
  832. {
  833. throw new Exception("Missing parameter changeid");
  834. }
  835. $oChange = MetaModel::GetObject('CMDBChange', $iChange, false);
  836. if (is_null($oChange))
  837. {
  838. throw new Exception("Unknown change: $iChange");
  839. }
  840. $oPage->add("<div><p><h1>".Dict::Format('UI:History:BulkImportDetails', $oChange->Get('date'), $oChange->GetUserName())."</h1></p></div>\n");
  841. // Assumption : change made one single class of objects
  842. $aObjects = array();
  843. $aAttributes = array(); // array of attcode => occurences
  844. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOp WHERE change = :change_id");
  845. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $iChange));
  846. while ($oOperation = $oOpSet->Fetch())
  847. {
  848. $sClass = $oOperation->Get('objclass');
  849. $iKey = $oOperation->Get('objkey');
  850. $iObjId = "$sClass::$iKey";
  851. if (!isset($aObjects[$iObjId]))
  852. {
  853. $aObjects[$iObjId] = array();
  854. $aObjects[$iObjId]['__class__'] = $sClass;
  855. $aObjects[$iObjId]['__id__'] = $iKey;
  856. }
  857. if (get_class($oOperation) == 'CMDBChangeOpCreate')
  858. {
  859. $aObjects[$iObjId]['__created__'] = true;
  860. }
  861. elseif (is_subclass_of($oOperation, 'CMDBChangeOpSetAttribute'))
  862. {
  863. $sAttCode = $oOperation->Get('attcode');
  864. if (get_class($oOperation) == 'CMDBChangeOpSetAttributeScalar')
  865. {
  866. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  867. if ($oAttDef->IsExternalKey())
  868. {
  869. $oOldTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('oldvalue'));
  870. $oNewTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('newvalue'));
  871. $sOldValue = $oOldTarget->GetHyperlink();
  872. $sNewValue = $oNewTarget->GetHyperlink();
  873. }
  874. else
  875. {
  876. $sOldValue = $oOperation->GetAsHTML('oldvalue');
  877. $sNewValue = $oOperation->GetAsHTML('newvalue');
  878. }
  879. $aObjects[$iObjId][$sAttCode] = $sOldValue.' -&gt; '.$sNewValue;
  880. }
  881. else
  882. {
  883. $aObjects[$iObjId][$sAttCode] = 'n/a';
  884. }
  885. if (isset($aAttributes[$sAttCode]))
  886. {
  887. $aAttributes[$sAttCode]++;
  888. }
  889. else
  890. {
  891. $aAttributes[$sAttCode] = 1;
  892. }
  893. }
  894. }
  895. $aDetails = array();
  896. foreach($aObjects as $iUId => $aObjData)
  897. {
  898. $aRow = array();
  899. $oObject = MetaModel::GetObject($aObjData['__class__'], $aObjData['__id__'], false);
  900. if (is_null($oObject))
  901. {
  902. $aRow['object'] = $aObjData['__class__'].'::'.$aObjData['__id__'].' (deleted)';
  903. }
  904. else
  905. {
  906. $aRow['object'] = $oObject->GetHyperlink();
  907. }
  908. if (isset($aObjData['__created__']))
  909. {
  910. $aRow['operation'] = Dict::S('Change:ObjectCreated');
  911. }
  912. else
  913. {
  914. $aRow['operation'] = Dict::S('Change:ObjectModified');
  915. }
  916. foreach ($aAttributes as $sAttCode => $iOccurences)
  917. {
  918. if (isset($aObjData[$sAttCode]))
  919. {
  920. $aRow[$sAttCode] = $aObjData[$sAttCode];
  921. }
  922. elseif (!is_null($oObject))
  923. {
  924. // This is the current vaslue: $oObject->GetAsHtml($sAttCode)
  925. // whereas we are displaying the value that was set at the time
  926. // the object was created
  927. // This requires addtional coding...let's do that later
  928. $aRow[$sAttCode] = '';
  929. }
  930. else
  931. {
  932. $aRow[$sAttCode] = '';
  933. }
  934. }
  935. $aDetails[] = $aRow;
  936. }
  937. $aConfig = array();
  938. $aConfig['object'] = array('label' => MetaModel::GetName($sClass), 'description' => MetaModel::GetClassDescription($sClass));
  939. $aConfig['operation'] = array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+'));
  940. foreach ($aAttributes as $sAttCode => $iOccurences)
  941. {
  942. $aConfig[$sAttCode] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'description' => MetaModel::GetDescription($sClass, $sAttCode));
  943. }
  944. $oPage->table($aConfig, $aDetails);
  945. }
  946. }
  947. ?>