bulkchange.class.inc.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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. $oReconFilter = new DBObjectSearch($oExtKey->GetTargetClass());
  316. $aCacheKeys = array();
  317. foreach ($aKeyConfig as $sForeignAttCode => $iCol)
  318. {
  319. // The foreign attribute is one of our reconciliation key
  320. if ($sForeignAttCode == 'id')
  321. {
  322. $value = $aRowData[$iCol];
  323. }
  324. else
  325. {
  326. $oForeignAtt = MetaModel::GetAttributeDef($oExtKey->GetTargetClass(), $sForeignAttCode);
  327. $value = $oForeignAtt->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
  328. }
  329. $aCacheKeys[] = $value;
  330. $oReconFilter->AddCondition($sForeignAttCode, $value, '=');
  331. $aResults[$iCol] = new CellStatus_Void($aRowData[$iCol]);
  332. }
  333. $sCacheKey = implode('_|_', $aCacheKeys); // Unique key for this query...
  334. $iCount = 0;
  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);
  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. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  414. // skip the private key, if any
  415. if ($sAttCode == 'id') continue;
  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. if (!array_key_exists($sAttCode, $this->m_aAttList))
  547. {
  548. // #@# will be out of the reporting... (counted anyway)
  549. }
  550. }
  551. // Reporting on fields
  552. //
  553. $aChangedFields = $oTargetObj->ListChanges();
  554. foreach ($this->m_aAttList as $sAttCode => $iCol)
  555. {
  556. if ($sAttCode == 'id')
  557. {
  558. $aResults[$iCol]= new CellStatus_Void($oTargetObj->GetKey());
  559. }
  560. if (array_key_exists($sAttCode, $aChangedFields))
  561. {
  562. $aResults[$iCol]= new CellStatus_Modify($oTargetObj->Get($sAttCode), $oTargetObj->GetOriginal($sAttCode));
  563. }
  564. else
  565. {
  566. // By default... nothing happens
  567. $aResults[$iCol]= new CellStatus_Void($oTargetObj->Get($sAttCode));
  568. }
  569. }
  570. // Checks
  571. //
  572. $res = $oTargetObj->CheckConsistency();
  573. if ($res !== true)
  574. {
  575. // $res contains the error description
  576. $aErrors["GLOBAL"] = Dict::Format('UI:CSVReport-Row-Issue-Inconsistent', $res);
  577. }
  578. return $aResults;
  579. }
  580. protected function CreateObject(&$aResult, $iRow, $aRowData, CMDBChange $oChange = null)
  581. {
  582. $oTargetObj = MetaModel::NewObject($this->m_sClass);
  583. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  584. if (count($aErrors) > 0)
  585. {
  586. $sErrors = implode(', ', $aErrors);
  587. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
  588. return $oTargetObj;
  589. }
  590. // Check that any external key will have a value proposed
  591. $aMissingKeys = array();
  592. foreach (MetaModel::GetExternalKeys($this->m_sClass) as $sExtKeyAttCode => $oExtKey)
  593. {
  594. if (!$oExtKey->IsNullAllowed())
  595. {
  596. if (!array_key_exists($sExtKeyAttCode, $this->m_aExtKeys) && !array_key_exists($sExtKeyAttCode, $this->m_aAttList))
  597. {
  598. $aMissingKeys[] = $oExtKey->GetLabel();
  599. }
  600. }
  601. }
  602. if (count($aMissingKeys) > 0)
  603. {
  604. $sMissingKeys = implode(', ', $aMissingKeys);
  605. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-MissingExtKey', $sMissingKeys));
  606. return $oTargetObj;
  607. }
  608. // Optionaly record the results
  609. //
  610. if ($oChange)
  611. {
  612. $newID = $oTargetObj->DBInsertTrackedNoReload($oChange);
  613. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj($this->m_sClass, $newID);
  614. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  615. $aResult[$iRow]["id"] = new CellStatus_Void($newID);
  616. }
  617. else
  618. {
  619. $aResult[$iRow]["__STATUS__"] = new RowStatus_NewObj();
  620. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  621. $aResult[$iRow]["id"] = new CellStatus_Void(0);
  622. }
  623. return $oTargetObj;
  624. }
  625. protected function UpdateObject(&$aResult, $iRow, $oTargetObj, $aRowData, CMDBChange $oChange = null)
  626. {
  627. $aResult[$iRow] = $this->PrepareObject($oTargetObj, $aRowData, $aErrors);
  628. // Reporting
  629. //
  630. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  631. $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
  632. if (count($aErrors) > 0)
  633. {
  634. $sErrors = implode(', ', $aErrors);
  635. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
  636. return;
  637. }
  638. $aChangedFields = $oTargetObj->ListChanges();
  639. if (count($aChangedFields) > 0)
  640. {
  641. $aResult[$iRow]["__STATUS__"] = new RowStatus_Modify(count($aChangedFields));
  642. // Optionaly record the results
  643. //
  644. if ($oChange)
  645. {
  646. try
  647. {
  648. $oTargetObj->DBUpdateTracked($oChange);
  649. }
  650. catch(CoreException $e)
  651. {
  652. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage());
  653. }
  654. }
  655. }
  656. else
  657. {
  658. $aResult[$iRow]["__STATUS__"] = new RowStatus_NoChange();
  659. }
  660. }
  661. protected function UpdateMissingObject(&$aResult, $iRow, $oTargetObj, CMDBChange $oChange = null)
  662. {
  663. $aResult[$iRow] = $this->PrepareMissingObject($oTargetObj, $aErrors);
  664. // Reporting
  665. //
  666. $aResult[$iRow]["finalclass"] = get_class($oTargetObj);
  667. $aResult[$iRow]["id"] = new CellStatus_Void($oTargetObj->GetKey());
  668. if (count($aErrors) > 0)
  669. {
  670. $sErrors = implode(', ', $aErrors);
  671. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Attribute'));
  672. return;
  673. }
  674. $aChangedFields = $oTargetObj->ListChanges();
  675. if (count($aChangedFields) > 0)
  676. {
  677. $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(count($aChangedFields));
  678. // Optionaly record the results
  679. //
  680. if ($oChange)
  681. {
  682. try
  683. {
  684. $oTargetObj->DBUpdateTracked($oChange);
  685. }
  686. catch(CoreException $e)
  687. {
  688. $aResult[$iRow]["__STATUS__"] = new RowStatus_Issue($e->getMessage());
  689. }
  690. }
  691. }
  692. else
  693. {
  694. $aResult[$iRow]["__STATUS__"] = new RowStatus_Disappeared(0);
  695. }
  696. }
  697. public function Process(CMDBChange $oChange = null)
  698. {
  699. // Note: $oChange can be null, in which case the aim is to check what would be done
  700. // Debug...
  701. //
  702. if (false)
  703. {
  704. echo "<pre>\n";
  705. echo "Attributes:\n";
  706. print_r($this->m_aAttList);
  707. echo "ExtKeys:\n";
  708. print_r($this->m_aExtKeys);
  709. echo "Reconciliation:\n";
  710. print_r($this->m_aReconcilKeys);
  711. echo "Synchro scope:\n";
  712. print_r($this->m_sSynchroScope);
  713. echo "Synchro changes:\n";
  714. print_r($this->m_aOnDisappear);
  715. //echo "Data:\n";
  716. //print_r($this->m_aData);
  717. echo "</pre>\n";
  718. exit;
  719. }
  720. $aResult = array();
  721. if (!is_null($this->m_sDateFormat) && (strlen($this->m_sDateFormat) > 0))
  722. {
  723. $sDateTimeFormat = $this->m_sDateFormat; // the specified format is actually the date AND time format
  724. $oDateTimeFormat = new DateTimeFormat($sDateTimeFormat);
  725. $sDateFormat = $oDateTimeFormat->ToDateFormat();
  726. AttributeDateTime::SetFormat($oDateTimeFormat);
  727. AttributeDate::SetFormat(new DateTimeFormat($sDateFormat));
  728. // Translate dates from the source data
  729. //
  730. foreach ($this->m_aAttList as $sAttCode => $iCol)
  731. {
  732. if ($sAttCode == 'id') continue;
  733. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  734. if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
  735. {
  736. foreach($this->m_aData as $iRow => $aRowData)
  737. {
  738. $sFormat = $sDateTimeFormat;
  739. $sValue = $this->m_aData[$iRow][$iCol];
  740. if (!empty($sValue))
  741. {
  742. if ($oAttDef instanceof AttributeDate)
  743. {
  744. $sFormat = $sDateFormat;
  745. }
  746. $oFormat = new DateTimeFormat($sFormat);
  747. $sRegExp = $oFormat->ToRegExpr('/');
  748. if (!preg_match($sRegExp, $this->m_aData[$iRow][$iCol]))
  749. {
  750. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
  751. }
  752. else
  753. {
  754. $oDate = DateTime::createFromFormat($sFormat, $this->m_aData[$iRow][$iCol]);
  755. if ($oDate !== false)
  756. {
  757. $sNewDate = $oDate->format($oAttDef->GetInternalFormat());
  758. $this->m_aData[$iRow][$iCol] = $sNewDate;
  759. }
  760. else
  761. {
  762. // Leave the cell unchanged
  763. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
  764. $aResult[$iRow][$sAttCode] = new CellStatus_Issue(null, $this->m_aData[$iRow][$iCol], Dict::S('UI:CSVReport-Row-Issue-DateFormat'));
  765. }
  766. }
  767. }
  768. else
  769. {
  770. $this->m_aData[$iRow][$iCol] = '';
  771. }
  772. }
  773. }
  774. }
  775. }
  776. // Compute the results
  777. //
  778. if (!is_null($this->m_sSynchroScope))
  779. {
  780. $aVisited = array();
  781. }
  782. $iPreviousTimeLimit = ini_get('max_execution_time');
  783. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  784. foreach($this->m_aData as $iRow => $aRowData)
  785. {
  786. set_time_limit($iLoopTimeLimit);
  787. if (isset($aResult[$iRow]["__STATUS__"]))
  788. {
  789. // An issue at the earlier steps - skip the rest
  790. continue;
  791. }
  792. try
  793. {
  794. $oReconciliationFilter = new DBObjectSearch($this->m_sClass);
  795. $bSkipQuery = false;
  796. foreach($this->m_aReconcilKeys as $sAttCode)
  797. {
  798. $valuecondition = null;
  799. if (array_key_exists($sAttCode, $this->m_aExtKeys))
  800. {
  801. if ($this->IsNullExternalKeySpec($aRowData, $sAttCode))
  802. {
  803. $oExtKey = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  804. if ($oExtKey->IsNullAllowed())
  805. {
  806. $valuecondition = $oExtKey->GetNullValue();
  807. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oExtKey->GetNullValue());
  808. }
  809. else
  810. {
  811. $aResult[$iRow][$sAttCode] = new CellStatus_NullIssue();
  812. }
  813. }
  814. else
  815. {
  816. // The value has to be found or verified
  817. list($sQuery, $aMatches) = $this->ResolveExternalKey($aRowData, $sAttCode, $aResult[$iRow]);
  818. if (count($aMatches) == 1)
  819. {
  820. $oRemoteObj = reset($aMatches); // first item
  821. $valuecondition = $oRemoteObj->GetKey();
  822. $aResult[$iRow][$sAttCode] = new CellStatus_Void($oRemoteObj->GetKey());
  823. }
  824. elseif (count($aMatches) == 0)
  825. {
  826. $aResult[$iRow][$sAttCode] = new CellStatus_SearchIssue();
  827. }
  828. else
  829. {
  830. $aResult[$iRow][$sAttCode] = new CellStatus_Ambiguous(null, count($aMatches), $sQuery);
  831. }
  832. }
  833. }
  834. else
  835. {
  836. // The value is given in the data row
  837. $iCol = $this->m_aAttList[$sAttCode];
  838. if ($sAttCode == 'id')
  839. {
  840. $valuecondition = $aRowData[$iCol];
  841. }
  842. else
  843. {
  844. $oAttDef = MetaModel::GetAttributeDef($this->m_sClass, $sAttCode);
  845. $valuecondition = $oAttDef->MakeValueFromString($aRowData[$iCol], $this->m_bLocalizedValues);
  846. }
  847. }
  848. if (is_null($valuecondition))
  849. {
  850. $bSkipQuery = true;
  851. }
  852. else
  853. {
  854. $oReconciliationFilter->AddCondition($sAttCode, $valuecondition, '=');
  855. }
  856. }
  857. if ($bSkipQuery)
  858. {
  859. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Reconciliation'));
  860. }
  861. else
  862. {
  863. $oReconciliationSet = new CMDBObjectSet($oReconciliationFilter);
  864. switch($oReconciliationSet->Count())
  865. {
  866. case 0:
  867. $oTargetObj = $this->CreateObject($aResult, $iRow, $aRowData, $oChange);
  868. // $aResult[$iRow]["__STATUS__"]=> set in CreateObject
  869. $aVisited[] = $oTargetObj->GetKey();
  870. break;
  871. case 1:
  872. $oTargetObj = $oReconciliationSet->Fetch();
  873. $this->UpdateObject($aResult, $iRow, $oTargetObj, $aRowData, $oChange);
  874. // $aResult[$iRow]["__STATUS__"]=> set in UpdateObject
  875. if (!is_null($this->m_sSynchroScope))
  876. {
  877. $aVisited[] = $oTargetObj->GetKey();
  878. }
  879. break;
  880. default:
  881. // Found several matches, ambiguous
  882. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::S('UI:CSVReport-Row-Issue-Ambiguous'));
  883. $aResult[$iRow]["id"]= new CellStatus_Ambiguous(0, $oReconciliationSet->Count(), $oReconciliationFilter->ToOql());
  884. $aResult[$iRow]["finalclass"]= 'n/a';
  885. }
  886. }
  887. }
  888. catch (Exception $e)
  889. {
  890. $aResult[$iRow]["__STATUS__"]= new RowStatus_Issue(Dict::Format('UI:CSVReport-Row-Issue-Internal', get_class($e), $e->getMessage()));
  891. }
  892. }
  893. if (!is_null($this->m_sSynchroScope))
  894. {
  895. // Compute the delta between the scope and visited objects
  896. $oScopeSearch = DBObjectSearch::FromOQL($this->m_sSynchroScope);
  897. $oScopeSet = new DBObjectSet($oScopeSearch);
  898. while ($oObj = $oScopeSet->Fetch())
  899. {
  900. $iObj = $oObj->GetKey();
  901. if (!in_array($iObj, $aVisited))
  902. {
  903. set_time_limit($iLoopTimeLimit);
  904. $iRow++;
  905. $this->UpdateMissingObject($aResult, $iRow, $oObj, $oChange);
  906. }
  907. }
  908. }
  909. set_time_limit($iPreviousTimeLimit);
  910. // Fill in the blanks - the result matrix is expected to be 100% complete
  911. //
  912. foreach($this->m_aData as $iRow => $aRowData)
  913. {
  914. foreach($this->m_aAttList as $iCol)
  915. {
  916. if (!array_key_exists($iCol, $aResult[$iRow]))
  917. {
  918. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  919. }
  920. }
  921. foreach($this->m_aExtKeys as $sAttCode => $aForeignAtts)
  922. {
  923. if (!array_key_exists($sAttCode, $aResult[$iRow]))
  924. {
  925. $aResult[$iRow][$sAttCode] = new CellStatus_Void('n/a');
  926. }
  927. foreach ($aForeignAtts as $sForeignAttCode => $iCol)
  928. {
  929. if (!array_key_exists($iCol, $aResult[$iRow]))
  930. {
  931. // The foreign attribute is one of our reconciliation key
  932. $aResult[$iRow][$iCol] = new CellStatus_Void($aRowData[$iCol]);
  933. }
  934. }
  935. }
  936. }
  937. return $aResult;
  938. }
  939. /**
  940. * Display the history of bulk imports
  941. */
  942. static function DisplayImportHistory(WebPage $oPage, $bFromAjax = false, $bShowAll = false)
  943. {
  944. $sAjaxDivId = "CSVImportHistory";
  945. if (!$bFromAjax)
  946. {
  947. $oPage->add('<div id="'.$sAjaxDivId.'">');
  948. }
  949. $oPage->p(Dict::S('UI:History:BulkImports+').' <span id="csv_history_reload"></span>');
  950. $oBulkChangeSearch = DBObjectSearch::FromOQL("SELECT CMDBChange WHERE origin IN ('csv-interactive', 'csv-import.php')");
  951. $iQueryLimit = $bShowAll ? 0 : appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  952. $oBulkChanges = new DBObjectSet($oBulkChangeSearch, array('date' => false), array(), null, $iQueryLimit);
  953. $oAppContext = new ApplicationContext();
  954. $bLimitExceeded = false;
  955. if ($oBulkChanges->Count() > (appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit())))
  956. {
  957. $bLimitExceeded = true;
  958. if (!$bShowAll)
  959. {
  960. $iMaxObjects = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  961. $oBulkChanges->SetLimit($iMaxObjects);
  962. }
  963. }
  964. $oBulkChanges->Seek(0);
  965. $aDetails = array();
  966. while ($oChange = $oBulkChanges->Fetch())
  967. {
  968. $sDate = '<a href="csvimport.php?step=10&changeid='.$oChange->GetKey().'&'.$oAppContext->GetForLink().'">'.$oChange->Get('date').'</a>';
  969. $sUser = $oChange->GetUserName();
  970. if (preg_match('/^(.*)\\(CSV\\)$/i', $oChange->Get('userinfo'), $aMatches))
  971. {
  972. $sUser = $aMatches[1];
  973. }
  974. else
  975. {
  976. $sUser = $oChange->Get('userinfo');
  977. }
  978. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpCreate WHERE change = :change_id");
  979. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
  980. $iCreated = $oOpSet->Count();
  981. // Get the class from the first item found (assumption: a CSV load is done for a single class)
  982. if ($oCreateOp = $oOpSet->Fetch())
  983. {
  984. $sClass = $oCreateOp->Get('objclass');
  985. }
  986. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOpSetAttribute WHERE change = :change_id");
  987. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $oChange->GetKey()));
  988. $aModified = array();
  989. $aAttList = array();
  990. while ($oModified = $oOpSet->Fetch())
  991. {
  992. // Get the class (if not done earlier on object creation)
  993. $sClass = $oModified->Get('objclass');
  994. $iKey = $oModified->Get('objkey');
  995. $sAttCode = $oModified->Get('attcode');
  996. $aAttList[$sClass][$sAttCode] = true;
  997. $aModified["$sClass::$iKey"] = true;
  998. }
  999. $iModified = count($aModified);
  1000. // Assumption: there is only one class of objects being loaded
  1001. // Then the last class found gives us the class for every object
  1002. if ( ($iModified > 0) || ($iCreated > 0))
  1003. {
  1004. $aDetails[] = array('date' => $sDate, 'user' => $sUser, 'class' => $sClass, 'created' => $iCreated, 'modified' => $iModified);
  1005. }
  1006. }
  1007. $aConfig = array( 'date' => array('label' => Dict::S('UI:History:Date'), 'description' => Dict::S('UI:History:Date+')),
  1008. 'user' => array('label' => Dict::S('UI:History:User'), 'description' => Dict::S('UI:History:User+')),
  1009. 'class' => array('label' => Dict::S('Core:AttributeClass'), 'description' => Dict::S('Core:AttributeClass+')),
  1010. 'created' => array('label' => Dict::S('UI:History:StatsCreations'), 'description' => Dict::S('UI:History:StatsCreations+')),
  1011. 'modified' => array('label' => Dict::S('UI:History:StatsModifs'), 'description' => Dict::S('UI:History:StatsModifs+')),
  1012. );
  1013. if ($bLimitExceeded)
  1014. {
  1015. if ($bShowAll)
  1016. {
  1017. // Collapsible list
  1018. $oPage->add('<p>'.Dict::Format('UI:CountOfResults', $oBulkChanges->Count()).'&nbsp;&nbsp;<a class="truncated" onclick="OnTruncatedHistoryToggle(false);">'.Dict::S('UI:CollapseList').'</a></p>');
  1019. }
  1020. else
  1021. {
  1022. // Truncated list
  1023. $iMinDisplayLimit = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  1024. $sCollapsedLabel = Dict::Format('UI:TruncatedResults', $iMinDisplayLimit, $oBulkChanges->Count());
  1025. $sLinkLabel = Dict::S('UI:DisplayAll');
  1026. $oPage->add('<p>'.$sCollapsedLabel.'&nbsp;&nbsp;<a class="truncated" onclick="OnTruncatedHistoryToggle(true);">'.$sLinkLabel.'</p>');
  1027. $oPage->add_ready_script(
  1028. <<<EOF
  1029. $('#$sAjaxDivId table.listResults').addClass('truncated');
  1030. $('#$sAjaxDivId table.listResults tr:last td').addClass('truncated');
  1031. EOF
  1032. );
  1033. $sAppContext = $oAppContext->GetForLink();
  1034. $oPage->add_script(
  1035. <<<EOF
  1036. function OnTruncatedHistoryToggle(bShowAll)
  1037. {
  1038. $('#csv_history_reload').html('<img src="../images/indicator.gif"/>');
  1039. $.get(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?{$sAppContext}', {operation: 'displayCSVHistory', showall: bShowAll}, function(data)
  1040. {
  1041. $('#$sAjaxDivId').html(data);
  1042. var table = $('#$sAjaxDivId .listResults');
  1043. table.tableHover(); // hover tables
  1044. table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
  1045. }
  1046. );
  1047. }
  1048. EOF
  1049. );
  1050. }
  1051. }
  1052. else
  1053. {
  1054. // Normal display - full list without any decoration
  1055. }
  1056. $oPage->table($aConfig, $aDetails);
  1057. if (!$bFromAjax)
  1058. {
  1059. $oPage->add('</div>');
  1060. }
  1061. }
  1062. /**
  1063. * Display the details of an import
  1064. */
  1065. static function DisplayImportHistoryDetails(iTopWebPage $oPage, $iChange)
  1066. {
  1067. if ($iChange == 0)
  1068. {
  1069. throw new Exception("Missing parameter changeid");
  1070. }
  1071. $oChange = MetaModel::GetObject('CMDBChange', $iChange, false);
  1072. if (is_null($oChange))
  1073. {
  1074. throw new Exception("Unknown change: $iChange");
  1075. }
  1076. $oPage->add("<div><p><h1>".Dict::Format('UI:History:BulkImportDetails', $oChange->Get('date'), $oChange->GetUserName())."</h1></p></div>\n");
  1077. // Assumption : change made one single class of objects
  1078. $aObjects = array();
  1079. $aAttributes = array(); // array of attcode => occurences
  1080. $oOpSearch = DBObjectSearch::FromOQL("SELECT CMDBChangeOp WHERE change = :change_id");
  1081. $oOpSet = new DBObjectSet($oOpSearch, array(), array('change_id' => $iChange));
  1082. while ($oOperation = $oOpSet->Fetch())
  1083. {
  1084. $sClass = $oOperation->Get('objclass');
  1085. $iKey = $oOperation->Get('objkey');
  1086. $iObjId = "$sClass::$iKey";
  1087. if (!isset($aObjects[$iObjId]))
  1088. {
  1089. $aObjects[$iObjId] = array();
  1090. $aObjects[$iObjId]['__class__'] = $sClass;
  1091. $aObjects[$iObjId]['__id__'] = $iKey;
  1092. }
  1093. if (get_class($oOperation) == 'CMDBChangeOpCreate')
  1094. {
  1095. $aObjects[$iObjId]['__created__'] = true;
  1096. }
  1097. elseif ($oOperation instanceof CMDBChangeOpSetAttribute)
  1098. {
  1099. $sAttCode = $oOperation->Get('attcode');
  1100. if ((get_class($oOperation) == 'CMDBChangeOpSetAttributeScalar') || (get_class($oOperation) == 'CMDBChangeOpSetAttributeURL'))
  1101. {
  1102. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1103. if ($oAttDef->IsExternalKey())
  1104. {
  1105. $sOldValue = Dict::S('UI:UndefinedObject');
  1106. if ($oOperation->Get('oldvalue') != 0)
  1107. {
  1108. $oOldTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('oldvalue'));
  1109. $sOldValue = $oOldTarget->GetHyperlink();
  1110. }
  1111. $sNewValue = Dict::S('UI:UndefinedObject');
  1112. if ($oOperation->Get('newvalue') != 0)
  1113. {
  1114. $oNewTarget = MetaModel::GetObject($oAttDef->GetTargetClass(), $oOperation->Get('newvalue'));
  1115. $sNewValue = $oNewTarget->GetHyperlink();
  1116. }
  1117. }
  1118. else
  1119. {
  1120. $sOldValue = $oOperation->GetAsHTML('oldvalue');
  1121. $sNewValue = $oOperation->GetAsHTML('newvalue');
  1122. }
  1123. $aObjects[$iObjId][$sAttCode] = $sOldValue.' -&gt; '.$sNewValue;
  1124. }
  1125. else
  1126. {
  1127. $aObjects[$iObjId][$sAttCode] = 'n/a';
  1128. }
  1129. if (isset($aAttributes[$sAttCode]))
  1130. {
  1131. $aAttributes[$sAttCode]++;
  1132. }
  1133. else
  1134. {
  1135. $aAttributes[$sAttCode] = 1;
  1136. }
  1137. }
  1138. }
  1139. $aDetails = array();
  1140. foreach($aObjects as $iUId => $aObjData)
  1141. {
  1142. $aRow = array();
  1143. $oObject = MetaModel::GetObject($aObjData['__class__'], $aObjData['__id__'], false);
  1144. if (is_null($oObject))
  1145. {
  1146. $aRow['object'] = $aObjData['__class__'].'::'.$aObjData['__id__'].' (deleted)';
  1147. }
  1148. else
  1149. {
  1150. $aRow['object'] = $oObject->GetHyperlink();
  1151. }
  1152. if (isset($aObjData['__created__']))
  1153. {
  1154. $aRow['operation'] = Dict::S('Change:ObjectCreated');
  1155. }
  1156. else
  1157. {
  1158. $aRow['operation'] = Dict::S('Change:ObjectModified');
  1159. }
  1160. foreach ($aAttributes as $sAttCode => $iOccurences)
  1161. {
  1162. if (isset($aObjData[$sAttCode]))
  1163. {
  1164. $aRow[$sAttCode] = $aObjData[$sAttCode];
  1165. }
  1166. elseif (!is_null($oObject))
  1167. {
  1168. // This is the current vaslue: $oObject->GetAsHtml($sAttCode)
  1169. // whereas we are displaying the value that was set at the time
  1170. // the object was created
  1171. // This requires addtional coding...let's do that later
  1172. $aRow[$sAttCode] = '';
  1173. }
  1174. else
  1175. {
  1176. $aRow[$sAttCode] = '';
  1177. }
  1178. }
  1179. $aDetails[] = $aRow;
  1180. }
  1181. $aConfig = array();
  1182. $aConfig['object'] = array('label' => MetaModel::GetName($sClass), 'description' => MetaModel::GetClassDescription($sClass));
  1183. $aConfig['operation'] = array('label' => Dict::S('UI:History:Changes'), 'description' => Dict::S('UI:History:Changes+'));
  1184. foreach ($aAttributes as $sAttCode => $iOccurences)
  1185. {
  1186. $aConfig[$sAttCode] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'description' => MetaModel::GetDescription($sClass, $sAttCode));
  1187. }
  1188. $oPage->table($aConfig, $aDetails);
  1189. }
  1190. }