bulkchange.class.inc.php 38 KB

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