bulkchange.class.inc.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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. /**
  19. * Bulk change facility (common to interactive and batch usages)
  20. *
  21. * @copyright Copyright (C) 2010-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. // The BOM is added at the head of exported UTF-8 CSV data, and removed (if present) from input UTF-8 data.
  25. // This helps MS-Excel (Version > 2007, Windows only) in changing its interpretation of a CSV file (by default Excel reads data as ISO-8859-1 -not 100% sure!)
  26. define('UTF8_BOM', chr(239).chr(187).chr(191)); // 0xEF, 0xBB, 0xBF
  27. /**
  28. * BulkChange
  29. * Interpret a given data set and update the DB accordingly (fake mode avail.)
  30. *
  31. * @package iTopORM
  32. */
  33. class BulkChangeException extends CoreException
  34. {
  35. }
  36. /**
  37. * CellChangeSpec
  38. * A series of classes, keeping the information about a given cell: could it be changed or not (and why)?
  39. *
  40. * @package iTopORM
  41. */
  42. abstract class CellChangeSpec
  43. {
  44. protected $m_proposedValue;
  45. protected $m_sOql; // in case of ambiguity
  46. public function __construct($proposedValue, $sOql = '')
  47. {
  48. $this->m_proposedValue = $proposedValue;
  49. $this->m_sOql = $sOql;
  50. }
  51. public function GetPureValue()
  52. {
  53. // Todo - distinguish both values
  54. return $this->m_proposedValue;
  55. }
  56. public function GetDisplayableValue()
  57. {
  58. return $this->m_proposedValue;
  59. }
  60. public function GetOql()
  61. {
  62. return $this->m_sOql;
  63. }
  64. abstract public function GetDescription();
  65. }
  66. class CellStatus_Void extends CellChangeSpec
  67. {
  68. public function GetDescription()
  69. {
  70. return '';
  71. }
  72. }
  73. class CellStatus_Modify extends CellChangeSpec
  74. {
  75. protected $m_previousValue;
  76. public function __construct($proposedValue, $previousValue = null)
  77. {
  78. // Unused (could be costly to know -see the case of reconciliation on ext keys)
  79. //$this->m_previousValue = $previousValue;
  80. parent::__construct($proposedValue);
  81. }
  82. public function GetDescription()
  83. {
  84. return Dict::S('UI:CSVReport-Value-Modified');
  85. }
  86. //public function GetPreviousValue()
  87. //{
  88. // return $this->m_previousValue;
  89. //}
  90. }
  91. class CellStatus_Issue extends CellStatus_Modify
  92. {
  93. protected $m_sReason;
  94. public function __construct($proposedValue, $previousValue, $sReason)
  95. {
  96. $this->m_sReason = $sReason;
  97. parent::__construct($proposedValue, $previousValue);
  98. }
  99. public function GetDescription()
  100. {
  101. if (is_null($this->m_proposedValue))
  102. {
  103. return Dict::Format('UI:CSVReport-Value-SetIssue', $this->m_sReason);
  104. }
  105. return Dict::Format('UI:CSVReport-Value-ChangeIssue', $this->m_proposedValue, $this->m_sReason);
  106. }
  107. }
  108. class CellStatus_SearchIssue extends CellStatus_Issue
  109. {
  110. public function __construct()
  111. {
  112. parent::__construct(null, null, null);
  113. }
  114. public function GetDescription()
  115. {
  116. return Dict::S('UI:CSVReport-Value-NoMatch');
  117. }
  118. }
  119. class CellStatus_NullIssue extends CellStatus_Issue
  120. {
  121. public function __construct()
  122. {
  123. parent::__construct(null, null, null);
  124. }
  125. public function GetDescription()
  126. {
  127. return Dict::S('UI:CSVReport-Value-Missing');
  128. }
  129. }
  130. class CellStatus_Ambiguous extends CellStatus_Issue
  131. {
  132. protected $m_iCount;
  133. public function __construct($previousValue, $iCount, $sOql)
  134. {
  135. $this->m_iCount = $iCount;
  136. $this->m_sQuery = $sOql;
  137. parent::__construct(null, $previousValue, '');
  138. }
  139. public function GetDescription()
  140. {
  141. $sCount = $this->m_iCount;
  142. return Dict::Format('UI:CSVReport-Value-Ambiguous', $sCount);
  143. }
  144. }
  145. /**
  146. * RowStatus
  147. * A series of classes, keeping the information about a given row: could it be changed or not (and why)?
  148. *
  149. * @package iTopORM
  150. */
  151. abstract class RowStatus
  152. {
  153. public function __construct()
  154. {
  155. }
  156. abstract public function GetDescription();
  157. }
  158. class RowStatus_NoChange extends RowStatus
  159. {
  160. public function GetDescription()
  161. {
  162. return Dict::S('UI:CSVReport-Row-Unchanged');
  163. }
  164. }
  165. class RowStatus_NewObj extends RowStatus
  166. {
  167. public function GetDescription()
  168. {
  169. return Dict::S('UI:CSVReport-Row-Created');
  170. }
  171. }
  172. class RowStatus_Modify extends RowStatus
  173. {
  174. protected $m_iChanged;
  175. public function __construct($iChanged)
  176. {
  177. $this->m_iChanged = $iChanged;
  178. }
  179. public function GetDescription()
  180. {
  181. return Dict::Format('UI:CSVReport-Row-Updated', $this->m_iChanged);
  182. }
  183. }
  184. class RowStatus_Disappeared extends RowStatus_Modify
  185. {
  186. public function GetDescription()
  187. {
  188. return Dict::Format('UI:CSVReport-Row-Disappeared', $this->m_iChanged);
  189. }
  190. }
  191. class RowStatus_Issue extends RowStatus
  192. {
  193. protected $m_sReason;
  194. public function __construct($sReason)
  195. {
  196. $this->m_sReason = $sReason;
  197. }
  198. public function GetDescription()
  199. {
  200. return Dict::Format('UI:CSVReport-Row-Issue', $this->m_sReason);
  201. }
  202. }
  203. /**
  204. * BulkChange
  205. *
  206. * @package iTopORM
  207. */
  208. class BulkChange
  209. {
  210. protected $m_sClass;
  211. protected $m_aData; // Note: hereafter, iCol maybe actually be any acceptable key (string)
  212. // #@# todo: rename the variables to sColIndex
  213. protected $m_aAttList; // attcode => iCol
  214. protected $m_aExtKeys; // aExtKeys[sExtKeyAttCode][sExtReconcKeyAttCode] = iCol;
  215. protected $m_aReconcilKeys; // attcode (attcode = 'id' for the pkey)
  216. protected $m_sSynchroScope; // OQL - if specified, then the missing items will be reported
  217. 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)
  218. protected $m_sDateFormat; // Date format specification, see DateTime::createFromFormat
  219. protected $m_bLocalizedValues; // Values in the data set are localized (see AttributeEnum)
  220. protected $m_aExtKeysMappingCache; // Cache for resolving external keys based on the given search criterias
  221. public function __construct($sClass, $aData, $aAttList, $aExtKeys, $aReconcilKeys, $sSynchroScope = null, $aOnDisappear = null, $sDateFormat = null, $bLocalize = false)
  222. {
  223. $this->m_sClass = $sClass;
  224. $this->m_aData = $aData;
  225. $this->m_aAttList = $aAttList;
  226. $this->m_aReconcilKeys = $aReconcilKeys;
  227. $this->m_aExtKeys = $aExtKeys;
  228. $this->m_sSynchroScope = $sSynchroScope;
  229. $this->m_aOnDisappear = $aOnDisappear;
  230. $this->m_sDateFormat = $sDateFormat;
  231. $this->m_bLocalizedValues = $bLocalize;
  232. $this->m_aExtKeysMappingCache = array();
  233. }
  234. protected $m_bReportHtml = false;
  235. protected $m_sReportCsvSep = ',';
  236. protected $m_sReportCsvDelimiter = '"';
  237. public function SetReportHtml()
  238. {
  239. $this->m_bReportHtml = true;
  240. }
  241. public function SetReportCsv($sSeparator = ',', $sDelimiter = '"')
  242. {
  243. $this->m_bReportHtml = false;
  244. $this->m_sReportCsvSep = $sSeparator;
  245. $this->m_sReportCsvDelimiter = $sDelimiter;
  246. }
  247. protected function ResolveExternalKey($aRowData, $sAttCode, &$aResults)
  248. {
  249. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  250. $oReconFilter = new DBObjectSearch($oExtKey->GetTargetClass());
  251. foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol)
  252. {
  253. if ($sForeignAttCode == 'id')
  254. {
  255. $value = (int) $aRowData[$iCol];
  256. }
  257. else
  258. {
  259. // The foreign attribute is one of our reconciliation key
  260. $oForeignAtt = MetaModel::GetAttributeDef($oExtKey->GetTargetClass(), $sForeignAttCode);
  261. $value = $oForeignAtt->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
  262. }
  263. $oReconFilter->AddCondition($sForeignAttCode, $value, '=');
  264. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  265. }
  266. $oExtObjects = new CMDBObjectSet($oReconFilter);
  267. $aKeys = $oExtObjects->ToArray();
  268. return array($oReconFilter->ToOql(), $aKeys);
  269. }
  270. // Returns true if the CSV data specifies that the external key must be left undefined
  271. protected function IsNullExternalKeySpec($aRowData, $sAttCode)
  272. {
  273. //$oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  274. foreach ($this->m_aExtKeys[$sAttCode] as $sForeignAttCode => $iCol)
  275. {
  276. // The foreign attribute is one of our reconciliation key
  277. if (strlen($aRowData[$iCol]) > 0)
  278. {
  279. return false;
  280. }
  281. }
  282. return true;
  283. }
  284. protected function PrepareObject(&$oTargetObj, $aRowData, &$aErrors)
  285. {
  286. $aResults = array();
  287. $aErrors = array();
  288. // External keys reconciliation
  289. //
  290. foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig)
  291. {
  292. // Skip external keys used for the reconciliation process
  293. // if (!array_key_exists($sAttCode, $this->m_aAttList)) continue;
  294. $oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
  295. if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
  296. {
  297. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  298. {
  299. // Default reporting
  300. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  301. }
  302. if ($oExtKey->IsNullAllowed())
  303. {
  304. $oTargetObj->Set($sAttCode, $oExtKey->GetNullValue());
  305. $aResults[$sAttCode]= new CellStatus_Void($oExtKey->GetNullValue());
  306. }
  307. else
  308. {
  309. $aErrors[$sAttCode] = Dict::S('UI:CSVReport-Value-Issue-Null');
  310. $aResults[$sAttCode]= new CellStatus_Issue(null, $oTargetObj->Get($sAttCode), Dict::S('UI:CSVReport-Value-Issue-Null'));
  311. }
  312. }
  313. else
  314. {
  315. // Check for additional rules
  316. $oReconFilter = $oExtKey->GetAllowedValuesAsFilter(array('this' => $oTargetObj));
  317. $aCacheKeys = array();
  318. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  319. {
  320. // The foreign attribute is one of our reconciliation key
  321. if ($sForeignAttCode == 'id')
  322. {
  323. $value = $aRowData[$iCol];
  324. }
  325. else
  326. {
  327. $oForeignAtt = MetaModel::GetAttributeDef($oExtKey->GetTargetClass(), $sForeignAttCode);
  328. $value = $oForeignAtt->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
  329. }
  330. $aCacheKeys[] = $value;
  331. $oReconFilter->AddCondition($sForeignAttCode, $value, '=');
  332. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  333. }
  334. $sCacheKey = implode('_|_', $aCacheKeys); // Unique key for this query...
  335. $iForeignKey = null;
  336. $sOQL = '';
  337. // TODO: check if *too long* keys can lead to collisions... and skip the cache in such a case...
  338. if (!array_key_exists($sAttCode, $this->m_aExtKeysMappingCache))
  339. {
  340. $this->m_aExtKeysMappingCache[$sAttCode] = array();
  341. }
  342. if (array_key_exists($sCacheKey, $this->m_aExtKeysMappingCache[$sAttCode]))
  343. {
  344. // Cache hit
  345. $iCount = $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['c'];
  346. $iForeignKey = $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['k'];
  347. $sOQL = $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['oql'];
  348. // Record the hit
  349. $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey]['h']++;
  350. }
  351. else
  352. {
  353. // Cache miss, let's initialize it
  354. $oExtObjects = new CMDBObjectSet($oReconFilter, array(), array('this' => $oTargetObj));
  355. $iCount = $oExtObjects->Count();
  356. if ($iCount == 1)
  357. {
  358. $oForeignObj = $oExtObjects->Fetch();
  359. $iForeignKey = $oForeignObj->GetKey();
  360. }
  361. $this->m_aExtKeysMappingCache[$sAttCode][$sCacheKey] = array(
  362. 'c' => $iCount,
  363. 'k' => $iForeignKey,
  364. 'oql' => $oReconFilter->ToOql(),
  365. 'h' => 0, // number of hits on this cache entry
  366. );
  367. }
  368. switch($iCount)
  369. {
  370. case 0:
  371. $aErrors[$sAttCode] = Dict::S('UI:CSVReport-Value-Issue-NotFound');
  372. $aResults[$sAttCode]= new CellStatus_SearchIssue();
  373. break;
  374. case 1:
  375. // Do change the external key attribute
  376. $oTargetObj->Set($sAttCode, $iForeignKey);
  377. break;
  378. default:
  379. $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-FoundMany', $iCount);
  380. $aResults[$sAttCode]= new CellStatus_Ambiguous($oTargetObj->Get($sAttCode), $iCount, $sOQL);
  381. }
  382. }
  383. // Report
  384. if (!array_key_exists($sAttCode, $aResults))
  385. {
  386. $iForeignObj = $oTargetObj->Get($sAttCode);
  387. if (array_key_exists($sAttCode, $oTargetObj->ListChanges()))
  388. {
  389. if ($oTargetObj->IsNew())
  390. {
  391. $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
  392. }
  393. else
  394. {
  395. $aResults[$sAttCode]= new CellStatus_Modify($iForeignObj, $oTargetObj->GetOriginal($sAttCode));
  396. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  397. {
  398. // Report the change on reconciliation values as well
  399. $aResults[$iCol] = new CellStatus_Modify($aRowData[$iCol]);
  400. }
  401. }
  402. }
  403. else
  404. {
  405. $aResults[$sAttCode]= new CellStatus_Void($iForeignObj);
  406. }
  407. }
  408. }
  409. // Set the object attributes
  410. //
  411. foreach ($this->m_aAttList as $sAttCode => $iCol)
  412. {
  413. // skip the private key, if any
  414. if ($sAttCode == 'id') continue;
  415. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  416. // skip reconciliation keys
  417. if (!$oAttDef->IsWritable() && in_array($sAttCode, $this->m_aReconcilKeys)){ continue; }
  418. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  419. $aReasons = array();
  420. $iFlags = $oTargetObj->GetAttributeFlags($sAttCode, $aReasons);
  421. if ( (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY) && ( $oTargetObj->Get($sAttCode) != $aRowData[$iCol]) )
  422. {
  423. $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Readonly', $sAttCode, $oTargetObj->Get($sAttCode), $aRowData[$iCol]);
  424. }
  425. else if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  426. {
  427. try
  428. {
  429. $oSet = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
  430. $oTargetObj->Set($sAttCode, $oSet);
  431. }
  432. catch(CoreException $e)
  433. {
  434. $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Format', $e->getMessage());
  435. }
  436. }
  437. else
  438. {
  439. $value = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
  440. if (is_null($value) && (strlen($aRowData[$iCol]) > 0))
  441. {
  442. $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-NoMatch', $sAttCode);
  443. }
  444. else
  445. {
  446. $res = $oTargetObj->CheckValue($sAttCode, $value);
  447. if ($res === true)
  448. {
  449. $oTargetObj->Set($sAttCode, $value);
  450. }
  451. else
  452. {
  453. // $res is a string with the error description
  454. $aErrors[$sAttCode] = Dict::Format('UI:CSVReport-Value-Issue-Unknown', $sAttCode, $res);
  455. }
  456. }
  457. }
  458. }
  459. // Reporting on fields
  460. //
  461. $aChangedFields = $oTargetObj->ListChanges();
  462. foreach ($this->m_aAttList as $sAttCode => $iCol)
  463. {
  464. if ($sAttCode == 'id')
  465. {
  466. $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
  467. }
  468. else
  469. {
  470. if ($this->m_bReportHtml)
  471. {
  472. $sCurValue = $oTargetObj->GetAsHTML($sAttCode, $this->m_bLocalizedValues);
  473. $sOrigValue = $oTargetObj->GetOriginalAsHTML($sAttCode, $this->m_bLocalizedValues);
  474. //$sInput = htmlentities($aRowData[$iCol], ENT_QUOTES, 'UTF-8');
  475. }
  476. else
  477. {
  478. $sCurValue = $oTargetObj->GetAsCSV($sAttCode, $this->m_sReportCsvSep, $this->m_sReportCsvDelimiter, $this->m_bLocalizedValues);
  479. $sOrigValue = $oTargetObj->GetOriginalAsCSV($sAttCode, $this->m_sReportCsvSep, $this->m_sReportCsvDelimiter, $this->m_bLocalizedValues);
  480. //$sInput = $aRowData[$iCol];
  481. }
  482. if (isset($aErrors[$sAttCode]))
  483. {
  484. $aResults[$iCol]= new CellStatus_Issue($aRowData[$iCol], $sOrigValue, $aErrors[$sAttCode]);
  485. }
  486. elseif (array_key_exists($sAttCode, $aChangedFields))
  487. {
  488. if ($oTargetObj->IsNew())
  489. {
  490. $aResults[$iCol]= new CellStatus_Void($sCurValue);
  491. }
  492. else
  493. {
  494. $aResults[$iCol]= new CellStatus_Modify($sCurValue, $sOrigValue);
  495. }
  496. }
  497. else
  498. {
  499. // By default... nothing happens
  500. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  501. if ($oAttDef instanceof AttributeDateTime)
  502. {
  503. $aResults[$iCol]= new CellStatus_Void($oAttDef->GetFormat()->Format($aRowData[$iCol]));
  504. }
  505. else
  506. {
  507. $aResults[$iCol]= new CellStatus_Void($aRowData[$iCol]);
  508. }
  509. }
  510. }
  511. }
  512. // Checks
  513. //
  514. $res = $oTargetObj->CheckConsistency();
  515. if ($res !== true)
  516. {
  517. // $res contains the error description
  518. $aErrors["GLOBAL"] = Dict::Format('UI:CSVReport-Row-Issue-Inconsistent', $res);
  519. }
  520. return $aResults;
  521. }
  522. protected function PrepareMissingObject(&$oTargetObj, &$aErrors)
  523. {
  524. $aResults = array();
  525. $aErrors = array();
  526. // External keys
  527. //
  528. foreach($this->m_aExtKeys as $sAttCode => $aKeyConfig)
  529. {
  530. //$oExtKey = MetaModel::GetAttributeDef(get_class($oTargetObj), $sAttCode);
  531. $aResults[$sAttCode]= new CellStatus_Void($oTargetObj->Get($sAttCode));
  532. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  533. {
  534. $aResults[$iCol] = new CellStatus_Void('?');
  535. }
  536. }
  537. // Update attributes
  538. //
  539. foreach($this->m_aOnDisappear as $sAttCode => $value)
  540. {
  541. if (!MetaModel::IsValidAttCode(get_class($oTargetObj), $sAttCode))
  542. {
  543. throw new BulkChangeException('Invalid attribute code', array('class' => get_class($oTargetObj), 'attcode' => $sAttCode));
  544. }
  545. $oTargetObj->Set($sAttCode, $value);
  546. }
  547. // Reporting on fields
  548. //
  549. $aChangedFields = $oTargetObj->ListChanges();
  550. foreach ($this->m_aAttList as $sAttCode => $iCol)
  551. {
  552. if ($sAttCode == 'id')
  553. {
  554. $aResults[$iCol]= new CellStatus_Void($oTargetObj->GetKey());
  555. }
  556. if (array_key_exists($sAttCode, $aChangedFields))
  557. {
  558. $aResults[$iCol]= new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode));
  559. }
  560. else
  561. {
  562. // By default... nothing happens
  563. $aResults[$iCol]= new CellStatus_Void($oTargetObj->Get($sAttCode));
  564. }
  565. }
  566. // Checks
  567. //
  568. $res = $oTargetObj->CheckConsistency();
  569. if ($res !== true)
  570. {
  571. // $res contains the error description
  572. $aErrors["GLOBAL"] = Dict::Format('UI:CSVReport-Row-Issue-Inconsistent', $res);
  573. }
  574. return $aResults;
  575. }
  576. protected function CreateObject(&$aResult, $iRow, $aRowData, CMDBChange $oChange = null)
  577. {
  578. $oTargetObj = MetaModel::NewObject($this->m_sClass);
  579. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  580. if (count($aErrors) > 0)
  581. {
  582. //$sErrors = implode(', ', $aErrors);
  583. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
  584. return $oTargetObj;
  585. }
  586. // Check that any external key will have a value proposed
  587. $aMissingKeys = array();
  588. foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey)
  589. {
  590. if (!$oExtKey->IsNullAllowed())
  591. {
  592. if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList))
  593. {
  594. $aMissingKeys[] = $oExtKey->GetLabel();
  595. }
  596. }
  597. }
  598. if (count($aMissingKeys) > 0)
  599. {
  600. $sMissingKeys = implode(', ', $aMissingKeys);
  601. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-MissingExtKey', $sMissingKeys));
  602. return $oTargetObj;
  603. }
  604. // Optionaly record the results
  605. //
  606. if ($oChange)
  607. {
  608. $newID = $oTargetObj->DBInsertTrackedNoReload($oChange);
  609. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj();
  610. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  611. $aResult[$iRow]["id"] = new CellStatus_Void($newID);
  612. }
  613. else
  614. {
  615. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj();
  616. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  617. $aResult[$iRow]["id"] = new CellStatus_Void(0);
  618. }
  619. return $oTargetObj;
  620. }
  621. protected function UpdateObject(&$aResult, $iRow, $oTargetObj, $aRowData, CMDBChange $oChange = null)
  622. {
  623. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  624. // Reporting
  625. //
  626. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  627. $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
  628. if (count($aErrors) > 0)
  629. {
  630. //$sErrors = implode(', ', $aErrors);
  631. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
  632. return;
  633. }
  634. $aChangedFields = $oTargetObj->ListChanges();
  635. if (count($aChangedFields) > 0)
  636. {
  637. $aResult[$iRow]["__STATUS__"] = new RowStatus_Modify(count($aChangedFields));
  638. // Optionaly record the results
  639. //
  640. if ($oChange)
  641. {
  642. try
  643. {
  644. $oTargetObj->DBUpdateTracked($oChange);
  645. }
  646. catch(CoreException $e)
  647. {
  648. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage());
  649. }
  650. }
  651. }
  652. else
  653. {
  654. $aResult[$iRow]["__STATUS__"] = new RowStatus_NoChange();
  655. }
  656. }
  657. protected function UpdateMissingObject(&$aResult, $iRow, $oTargetObj, CMDBChange $oChange = null)
  658. {
  659. $aResult[$iRow] = $this->PrepareMissingObject($oTargetObj, $aErrors);
  660. // Reporting
  661. //
  662. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  663. $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
  664. if (count($aErrors) > 0)
  665. {
  666. //$sErrors = implode(', ', $aErrors);
  667. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
  668. return;
  669. }
  670. $aChangedFields = $oTargetObj->ListChanges();
  671. if (count($aChangedFields) > 0)
  672. {
  673. $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(count($aChangedFields));
  674. // Optionaly record the results
  675. //
  676. if ($oChange)
  677. {
  678. try
  679. {
  680. $oTargetObj->DBUpdateTracked($oChange);
  681. }
  682. catch(CoreException $e)
  683. {
  684. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage());
  685. }
  686. }
  687. }
  688. else
  689. {
  690. $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(0);
  691. }
  692. }
  693. public function Process(CMDBChange $oChange = null)
  694. {
  695. // Note: $oChange can be null, in which case the aim is to check what would be done
  696. // Debug...
  697. //
  698. if (false)
  699. {
  700. echo "<pre>\n";
  701. echo "Attributes:\n";
  702. print_r($this->m_aAttList);
  703. echo "ExtKeys:\n";
  704. print_r($this->m_aExtKeys);
  705. echo "Reconciliation:\n";
  706. print_r($this->m_aReconcilKeys);
  707. echo "Synchro scope:\n";
  708. print_r($this->m_sSynchroScope);
  709. echo "Synchro changes:\n";
  710. print_r($this->m_aOnDisappear);
  711. //echo "Data:\n";
  712. //print_r($this->m_aData);
  713. echo "</pre>\n";
  714. exit;
  715. }
  716. $aResult = array();
  717. if (!is_null($this->m_sDateFormat) && (strlen($this->m_sDateFormat) > 0))
  718. {
  719. $sDateTimeFormat = $this->m_sDateFormat; // the specified format is actually the date AND time format
  720. $oDateTimeFormat = new DateTimeFormat($sDateTimeFormat);
  721. $sDateFormat = $oDateTimeFormat->ToDateFormat();
  722. AttributeDateTime::SetFormat($oDateTimeFormat);
  723. AttributeDate::SetFormat(new DateTimeFormat($sDateFormat));
  724. // Translate dates from the source data
  725. //
  726. foreach ($this->m_aAttList as $sAttCode => $iCol)
  727. {
  728. if ($sAttCode == 'id') continue;
  729. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  730. if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
  731. {
  732. foreach($this->m_aData as $iRow => $aRowData)
  733. {
  734. $sFormat = $sDateTimeFormat;
  735. $sValue = $this->m_aData[$iRow][$iCol];
  736. if (!empty($sValue))
  737. {
  738. if ($oAttDef instanceof AttributeDate)
  739. {
  740. $sFormat = $sDateFormat;
  741. }
  742. $oFormat = new DateTimeFormat($sFormat);
  743. $sRegExp = $oFormat->ToRegExpr('/');
  744. if (!preg_match($sRegExp, $this->m_aData[$iRow][$iCol]))
  745. {
  746. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
  747. }
  748. else
  749. {
  750. $oDate = DateTime::createFromFormat($sFormat, $this->m_aData[$iRow][$iCol]);
  751. if ($oDate !== false)
  752. {
  753. $sNewDate = $oDate->format($oAttDef->GetInternalFormat());
  754. $this->m_aData[$iRow][$iCol] = $sNewDate;
  755. }
  756. else
  757. {
  758. // Leave the cell unchanged
  759. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
  760. $aResult[$iRow][$sAttCode] = new CellStatus_Issue(null, $this->m_aData[$iRow][$iCol], Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
  761. }
  762. }
  763. }
  764. else
  765. {
  766. $this->m_aData[$iRow][$iCol] = '';
  767. }
  768. }
  769. }
  770. }
  771. }
  772. // Compute the results
  773. //
  774. if (!is_null($this->m_sSynchroScope))
  775. {
  776. $aVisited = array();
  777. }
  778. $iPreviousTimeLimit = ini_get('max_execution_time');
  779. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  780. foreach($this->m_aData as $iRow => $aRowData)
  781. {
  782. set_time_limit($iLoopTimeLimit);
  783. if (isset($aResult[$iRow]["__STATUS__"]))
  784. {
  785. // An issue at the earlier steps - skip the rest
  786. continue;
  787. }
  788. try
  789. {
  790. $oReconciliationFilter = new DBObjectSearch($this->m_sClass);
  791. $bSkipQuery = false;
  792. foreach($this->m_aReconcilKeys as $sAttCode)
  793. {
  794. $valuecondition = null;
  795. if (array_key_exists($sAttCode, $this->m_aExtKeys))
  796. {
  797. if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
  798. {
  799. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  800. if ($oExtKey->IsNullAllowed())
  801. {
  802. $valuecondition = $oExtKey->GetNullValue();
  803. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oExtKey->GetNullValue());
  804. }
  805. else
  806. {
  807. $aResult[$iRow][$sAttCode] = new CellStatus_NullIssue();
  808. }
  809. }
  810. else
  811. {
  812. // The value has to be found or verified
  813. list($sQuery, $aMatches) = $this->ResolveExternalKey($aRowData, $sAttCode, $aResult[$iRow]);
  814. if (count($aMatches) == 1)
  815. {
  816. $oRemoteObj = reset($aMatches); // first item
  817. $valuecondition = $oRemoteObj->GetKey();
  818. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oRemoteObj->GetKey());
  819. }
  820. elseif (count($aMatches) == 0)
  821. {
  822. $aResult[$iRow][$sAttCode] = new CellStatus_SearchIssue();
  823. }
  824. else
  825. {
  826. $aResult[$iRow][$sAttCode] = new CellStatus_Ambiguous(null, count($aMatches), $sQuery);
  827. }
  828. }
  829. }
  830. else
  831. {
  832. // The value is given in the data row
  833. $iCol = $this->m_aAttList[$sAttCode];
  834. if ($sAttCode == 'id')
  835. {
  836. $valuecondition = $aRowData[$iCol];
  837. }
  838. else
  839. {
  840. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  841. $valuecondition = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
  842. }
  843. }
  844. if (is_null($valuecondition))
  845. {
  846. $bSkipQuery = true;
  847. }
  848. else
  849. {
  850. $oReconciliationFilter->AddCondition($sAttCode, $valuecondition, '=');
  851. }
  852. }
  853. if ($bSkipQuery)
  854. {
  855. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Reconciliation'));
  856. }
  857. else
  858. {
  859. $oReconciliationSet = new CMDBObjectSet($oReconciliationFilter);
  860. switch($oReconciliationSet->Count())
  861. {
  862. case 0:
  863. $oTargetObj = $this->CreateObject($aResult, $iRow, $aRowData, $oChange);
  864. // $aResult[$iRow]["__STATUS__"]=> set in CreateObject
  865. $aVisited[] = $oTargetObj->GetKey();
  866. break;
  867. case 1:
  868. $oTargetObj = $oReconciliationSet->Fetch();
  869. $this->UpdateObject($aResult, $iRow, $oTargetObj, $aRowData, $oChange);
  870. // $aResult[$iRow]["__STATUS__"]=> set in UpdateObject
  871. if (!is_null($this->m_sSynchroScope))
  872. {
  873. $aVisited[] = $oTargetObj->GetKey();
  874. }
  875. break;
  876. default:
  877. // Found several matches, ambiguous
  878. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Ambiguous'));
  879. $aResult[$iRow]["id"]= new CellStatus_Ambiguous(0, $oReconciliationSet->Count(), $oReconciliationFilter->ToOql());
  880. $aResult[$iRow]["finalclass"]= 'n/a';
  881. }
  882. }
  883. }
  884. catch (Exception $e)
  885. {
  886. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-Internal', get_class($e), $e->getMessage()));
  887. }
  888. }
  889. if (!is_null($this->m_sSynchroScope))
  890. {
  891. // Compute the delta between the scope and visited objects
  892. $oScopeSearch = DBObjectSearch::FromOQL($this->m_sSynchroScope);
  893. $oScopeSet = new DBObjectSet($oScopeSearch);
  894. while ($oObj = $oScopeSet->Fetch())
  895. {
  896. $iObj = $oObj->GetKey();
  897. if (!in_array($iObj, $aVisited))
  898. {
  899. set_time_limit($iLoopTimeLimit);
  900. $iRow++;
  901. $this->UpdateMissingObject($aResult, $iRow, $oObj, $oChange);
  902. }
  903. }
  904. }
  905. set_time_limit($iPreviousTimeLimit);
  906. // Fill in the blanks - the result matrix is expected to be 100% complete
  907. //
  908. foreach($this->m_aData as $iRow => $aRowData)
  909. {
  910. foreach($this->m_aAttList as $iCol)
  911. {
  912. if (!array_key_exists($iCol, $aResult[$iRow]))
  913. {
  914. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  915. }
  916. }
  917. foreach($this->m_aExtKeys as $sAttCode => $aForeignAtts)
  918. {
  919. if (!array_key_exists($sAttCode, $aResult[$iRow]))
  920. {
  921. $aResult[$iRow][$sAttCode] = new CellStatus_Void('n/a');
  922. }
  923. foreach ($aForeignAtts as $sForeignAttCode => $iCol)
  924. {
  925. if (!array_key_exists($iCol, $aResult[$iRow]))
  926. {
  927. // The foreign attribute is one of our reconciliation key
  928. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  929. }
  930. }
  931. }
  932. }
  933. return $aResult;
  934. }
  935. /**
  936. * Display the history of bulk imports
  937. */
  938. static function DisplayImportHistory(WebPage $oPage, $bFromAjax = false, $bShowAll = false)
  939. {
  940. $sAjaxDivId = "CSVImportHistory";
  941. if (!$bFromAjax)
  942. {
  943. $oPage->add('<div id="'.$sAjaxDivId.'">');
  944. }
  945. $oPage->p(Dict::S('UI:History:BulkImports+').' <span id="csv_history_reload"></span>');
  946. $oBulkChangeSearch = DBObjectSearch::FromOQL("SELECT CMDBChange WHERE origin IN ('csv-interactive', 'csv-import.php')");
  947. $iQueryLimit = $bShowAll ? 0 : appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  948. $oBulkChanges = new DBObjectSet($oBulkChangeSearch, array('date' => false), array(), null, $iQueryLimit);
  949. $oAppContext = new ApplicationContext();
  950. $bLimitExceeded = false;
  951. if ($oBulkChanges->Count() > (appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit())))
  952. {
  953. $bLimitExceeded = true;
  954. if (!$bShowAll)
  955. {
  956. $iMaxObjects = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  957. $oBulkChanges->SetLimit($iMaxObjects);
  958. }
  959. }
  960. $oBulkChanges->Seek(0);
  961. $aDetails = array();
  962. while ($oChange = $oBulkChanges->Fetch())
  963. {
  964. $sDate = '<a href="csvimport.php?step=10&changeid='.$oChange->GetKey().'&'.$oAppContext->GetForLink().'">'.$oChange->Get('date').'</a>';
  965. $sUser = $oChange->GetUserName();
  966. if (preg_match('/^(.*)\\(CSV\\)$/i', $oChange->Get('userinfo'), $aMatches))
  967. {
  968. $sUser = $aMatches[1];
  969. }
  970. else
  971. {
  972. $sUser = $oChange->Get('userinfo');
  973. }
  974. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpCreate WHERE change = :change_id");
  975. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
  976. $iCreated = $oOpSet->Count();
  977. // Get the class from the first item found (assumption: a CSV load is done for a single class)
  978. if ($oCreateOp = $oOpSet->Fetch())
  979. {
  980. $sClass = $oCreateOp->Get('objclass');
  981. }
  982. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpSetAttribute WHERE change = :change_id");
  983. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
  984. $aModified = array();
  985. $aAttList = array();
  986. while ($oModified = $oOpSet->Fetch())
  987. {
  988. // Get the class (if not done earlier on object creation)
  989. $sClass = $oModified->Get('objclass');
  990. $iKey = $oModified->Get('objkey');
  991. $sAttCode = $oModified->Get('attcode');
  992. $aAttList[$sClass][$sAttCode] = true;
  993. $aModified["$sClass::$iKey"] = true;
  994. }
  995. $iModified = count($aModified);
  996. // Assumption: there is only one class of objects being loaded
  997. // Then the last class found gives us the class for every object
  998. if ( ($iModified > 0) || ($iCreated > 0))
  999. {
  1000. $aDetails[] = array('date' => $sDate, 'user' => $sUser, 'class' => $sClass, 'created' => $iCreated, 'modified' => $iModified);
  1001. }
  1002. }
  1003. $aConfig = array( 'date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1004. 'user' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1005. 'class' => array('label' => Dict::S('Core:AttributeClass'), 'description' => Dict::S('Core:AttributeClass+')),
  1006. 'created' => array('label' => Dict::S('UI:History:StatsCreations'), 'description' => Dict::S('UI:History:StatsCreations+')),
  1007. 'modified' => array('label' => Dict::S('UI:History:StatsModifs'), 'description' => Dict::S('UI:History:StatsModifs+')),
  1008. );
  1009. if ($bLimitExceeded)
  1010. {
  1011. if ($bShowAll)
  1012. {
  1013. // Collapsible list
  1014. $oPage->add('<p>'.Dict::Format('UI:CountOfResults', $oBulkChanges->Count()).'&nbsp;&nbsp;<a class="truncated" onclick="OnTruncatedHistoryToggle(false);">'.Dict::S('UI:CollapseList').'</a></p>');
  1015. }
  1016. else
  1017. {
  1018. // Truncated list
  1019. $iMinDisplayLimit = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  1020. $sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oBulkChanges->Count());
  1021. $sLinkLabel = Dict::S('UI:DisplayAll');
  1022. $oPage->add('<p>'.$sCollapsedLabel.'&nbsp;&nbsp;<a class="truncated" onclick="OnTruncatedHistoryToggle(true);">'.$sLinkLabel.'</p>');
  1023. $oPage->add_ready_script(
  1024. <<<EOF
  1025. $('#$sAjaxDivId table.listResults').addClass('truncated');
  1026. $('#$sAjaxDivId table.listResults tr:last td').addClass('truncated');
  1027. EOF
  1028. );
  1029. $sAppContext = $oAppContext->GetForLink();
  1030. $oPage->add_script(
  1031. <<<EOF
  1032. function OnTruncatedHistoryToggle(bShowAll)
  1033. {
  1034. $('#csv_history_reload').html('<img src="../images/indicator.gif"/>');
  1035. $.get(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?{$sAppContext}', {operation: 'displayCSVHistory', showall: bShowAll}, function(data)
  1036. {
  1037. $('#$sAjaxDivId').html(data);
  1038. var table = $('#$sAjaxDivId .listResults');
  1039. table.tableHover(); // hover tables
  1040. table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
  1041. }
  1042. );
  1043. }
  1044. EOF
  1045. );
  1046. }
  1047. }
  1048. else
  1049. {
  1050. // Normal display - full list without any decoration
  1051. }
  1052. $oPage->table($aConfig, $aDetails);
  1053. if (!$bFromAjax)
  1054. {
  1055. $oPage->add('</div>');
  1056. }
  1057. }
  1058. /**
  1059. * Display the details of an import
  1060. * @param iTopWebPage $oPage
  1061. * @param $iChange
  1062. * @throws Exception
  1063. */
  1064. static function DisplayImportHistoryDetails(iTopWebPage $oPage, $iChange)
  1065. {
  1066. if ($iChange == 0)
  1067. {
  1068. throw new Exception("Missing parameter changeid");
  1069. }
  1070. $oChange = MetaModel::GetObject('CMDBChange', $iChange, false);
  1071. if (is_null($oChange))
  1072. {
  1073. throw new Exception("Unknown change: $iChange");
  1074. }
  1075. $oPage->add("<div><p><h1>".Dict::Format('UI:History:BulkImportDetails', $oChange->Get('date'), $oChange->GetUserName())."</h1></p></div>\n");
  1076. // Assumption : change made one single class of objects
  1077. $aObjects = array();
  1078. $aAttributes = array(); // array of attcode => occurences
  1079. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOp WHERE change = :change_id");
  1080. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $iChange));
  1081. while ($oOperation = $oOpSet->Fetch())
  1082. {
  1083. $sClass = $oOperation->Get('objclass');
  1084. $iKey = $oOperation->Get('objkey');
  1085. $iObjId = "$sClass::$iKey";
  1086. if (!isset($aObjects[$iObjId]))
  1087. {
  1088. $aObjects[$iObjId] = array();
  1089. $aObjects[$iObjId]['__class__'] = $sClass;
  1090. $aObjects[$iObjId]['__id__'] = $iKey;
  1091. }
  1092. if (get_class($oOperation) == 'CMDBChangeOpCreate')
  1093. {
  1094. $aObjects[$iObjId]['__created__'] = true;
  1095. }
  1096. elseif ($oOperation instanceof CMDBChangeOpSetAttribute)
  1097. {
  1098. $sAttCode = $oOperation->Get('attcode');
  1099. if ((get_class($oOperation) == 'CMDBChangeOpSetAttributeScalar') || (get_class($oOperation) == 'CMDBChangeOpSetAttributeURL'))
  1100. {
  1101. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1102. if ($oAttDef->IsExternalKey())
  1103. {
  1104. $sOldValue = Dict::S('UI:UndefinedObject');
  1105. if ($oOperation->Get('oldvalue') != 0)
  1106. {
  1107. $oOldTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('oldvalue'));
  1108. $sOldValue = $oOldTarget->GetHyperlink();
  1109. }
  1110. $sNewValue = Dict::S('UI:UndefinedObject');
  1111. if ($oOperation->Get('newvalue') != 0)
  1112. {
  1113. $oNewTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('newvalue'));
  1114. $sNewValue = $oNewTarget->GetHyperlink();
  1115. }
  1116. }
  1117. else
  1118. {
  1119. $sOldValue = $oOperation->GetAsHTML('oldvalue');
  1120. $sNewValue = $oOperation->GetAsHTML('newvalue');
  1121. }
  1122. $aObjects[$iObjId][$sAttCode] = $sOldValue.' -&gt; '.$sNewValue;
  1123. }
  1124. else
  1125. {
  1126. $aObjects[$iObjId][$sAttCode] = 'n/a';
  1127. }
  1128. if (isset($aAttributes[$sAttCode]))
  1129. {
  1130. $aAttributes[$sAttCode]++;
  1131. }
  1132. else
  1133. {
  1134. $aAttributes[$sAttCode] = 1;
  1135. }
  1136. }
  1137. }
  1138. $aDetails = array();
  1139. foreach($aObjects as $iUId => $aObjData)
  1140. {
  1141. $aRow = array();
  1142. $oObject = MetaModel::GetObject($aObjData['__class__'], $aObjData['__id__'], false);
  1143. if (is_null($oObject))
  1144. {
  1145. $aRow['object'] = $aObjData['__class__'].'::'.$aObjData['__id__'].' (deleted)';
  1146. }
  1147. else
  1148. {
  1149. $aRow['object'] = $oObject->GetHyperlink();
  1150. }
  1151. if (isset($aObjData['__created__']))
  1152. {
  1153. $aRow['operation'] = Dict::S('Change:ObjectCreated');
  1154. }
  1155. else
  1156. {
  1157. $aRow['operation'] = Dict::S('Change:ObjectModified');
  1158. }
  1159. foreach ($aAttributes as $sAttCode => $iOccurences)
  1160. {
  1161. if (isset($aObjData[$sAttCode]))
  1162. {
  1163. $aRow[$sAttCode] = $aObjData[$sAttCode];
  1164. }
  1165. elseif (!is_null($oObject))
  1166. {
  1167. // This is the current vaslue: $oObject->GetAsHtml($sAttCode)
  1168. // whereas we are displaying the value that was set at the time
  1169. // the object was created
  1170. // This requires addtional coding...let's do that later
  1171. $aRow[$sAttCode] = '';
  1172. }
  1173. else
  1174. {
  1175. $aRow[$sAttCode] = '';
  1176. }
  1177. }
  1178. $aDetails[] = $aRow;
  1179. }
  1180. $aConfig = array();
  1181. $aConfig['object'] = array('label' => MetaModel::GetName($sClass), 'description' => MetaModel::GetClassDescription($sClass));
  1182. $aConfig['operation'] = array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+'));
  1183. foreach ($aAttributes as $sAttCode => $iOccurences)
  1184. {
  1185. $aConfig[$sAttCode] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'description' => MetaModel::GetDescription($sClass, $sAttCode));
  1186. }
  1187. $oPage->table($aConfig, $aDetails);
  1188. }
  1189. }