bulkchange.class.inc.php 40 KB

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