bulkchange.class.inc.php 40 KB

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