import.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. <?php
  2. // Copyright (C) 2010-2012 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. * Import web service
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. //
  25. // Known limitations
  26. // - reconciliation is made on the first column
  27. //
  28. // Known issues
  29. // - ALMOST impossible to troubleshoot when an externl key has a wrong value
  30. // - no character escaping in the xml output (yes !?!?!)
  31. // - not outputing xml when a wrong input is given (class, attribute names)
  32. //
  33. if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  34. require_once(__DIR__.'/../approot.inc.php');
  35. require_once(APPROOT.'/application/application.inc.php');
  36. require_once(APPROOT.'/application/webpage.class.inc.php');
  37. require_once(APPROOT.'/application/csvpage.class.inc.php');
  38. require_once(APPROOT.'/application/clipage.class.inc.php');
  39. require_once(APPROOT.'/application/startup.inc.php');
  40. class BulkLoadException extends Exception
  41. {
  42. }
  43. $aPageParams = array
  44. (
  45. 'auth_user' => array
  46. (
  47. 'mandatory' => true,
  48. 'modes' => 'cli',
  49. 'default' => null,
  50. 'description' => 'login (must have enough rights to create objects of the given class)',
  51. ),
  52. 'auth_pwd' => array
  53. (
  54. 'mandatory' => true,
  55. 'modes' => 'cli',
  56. 'default' => null,
  57. 'description' => 'password',
  58. ),
  59. 'class' => array
  60. (
  61. 'mandatory' => true,
  62. 'modes' => 'http,cli',
  63. 'default' => null,
  64. 'description' => 'class of loaded objects',
  65. ),
  66. 'csvdata' => array
  67. (
  68. 'mandatory' => true,
  69. 'modes' => 'http',
  70. 'default' => null,
  71. 'description' => 'data',
  72. ),
  73. 'csvfile' => array
  74. (
  75. 'mandatory' => true,
  76. 'modes' => 'cli',
  77. 'default' => '',
  78. 'description' => 'local data file, replaces csvdata if specified',
  79. ),
  80. 'charset' => array
  81. (
  82. 'mandatory' => false,
  83. 'modes' => 'http,cli',
  84. 'default' => '',
  85. 'description' => 'Character set encoding of the CSV data: UTF-8, ISO-8859-1, WINDOWS-1251, WINDOWS-1252, ISO-8859-15, If blank, then the charset is set to config(csv_file_default_charset)',
  86. ),
  87. 'date_format' => array
  88. (
  89. 'mandatory' => false,
  90. 'modes' => 'http,cli',
  91. 'default' => '',
  92. 'description' => 'Input date format (used both for dates and datetimes) - Examples: Y-m-d H:i:s, d/m/Y H:i:s (Europe) - no transformation is applied if the argument is omitted. (note: old format specification using %Y %m %d is also supported for backward compatibility)',
  93. ),
  94. 'separator' => array
  95. (
  96. 'mandatory' => false,
  97. 'modes' => 'http,cli',
  98. 'default' => ',',
  99. 'description' => 'column separator in CSV data (1 char, or \'tab\')',
  100. ),
  101. 'qualifier' => array
  102. (
  103. 'mandatory' => false,
  104. 'modes' => 'http,cli',
  105. 'default' => '"',
  106. 'description' => 'test qualifier in CSV data',
  107. ),
  108. 'output' => array
  109. (
  110. 'mandatory' => false,
  111. 'modes' => 'http,cli',
  112. 'default' => 'summary',
  113. 'description' => '[retcode] to return the count of lines in error, [summary] to return a concise report, [details] to get a detailed report (each line listed)',
  114. ),
  115. /*
  116. 'reportlevel' => array
  117. (
  118. 'mandatory' => false,
  119. 'modes' => 'http,cli',
  120. 'default' => 'errors|warnings|created|changed|unchanged',
  121. 'description' => 'combination of flags to limit the detailed output',
  122. ),
  123. */
  124. 'reconciliationkeys' => array
  125. (
  126. 'mandatory' => false,
  127. 'modes' => 'http,cli',
  128. 'default' => '',
  129. 'description' => 'name of the columns used to identify existing objects and update them, or create a new one',
  130. ),
  131. 'simulate' => array
  132. (
  133. 'mandatory' => false,
  134. 'modes' => 'http,cli',
  135. 'default' => '0',
  136. 'description' => 'If set to 1, then the load will not be executed, but the expected report will be produced',
  137. ),
  138. 'comment' => array
  139. (
  140. 'mandatory' => false,
  141. 'modes' => 'http,cli',
  142. 'default' => '',
  143. 'description' => 'Comment to be added into the change log',
  144. ),
  145. 'no_localize' => array
  146. (
  147. 'mandatory' => false,
  148. 'modes' => 'http,cli',
  149. 'default' => '0',
  150. 'description' => 'If set to 0, then header and values are supposed to be localized in the language of the logged in user. Set to 1 to use internal attribute codes and values (enums)',
  151. ),
  152. );
  153. function UsageAndExit($oP)
  154. {
  155. global $aPageParams;
  156. $bModeCLI = utils::IsModeCLI();
  157. $oP->p("USAGE:\n");
  158. foreach($aPageParams as $sParam => $aParamData)
  159. {
  160. $aModes = explode(',', $aParamData['modes']);
  161. if ($bModeCLI)
  162. {
  163. if (in_array('cli', $aModes))
  164. {
  165. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  166. $oP->p("$sParam = $sDesc");
  167. }
  168. }
  169. else
  170. {
  171. if (in_array('http', $aModes))
  172. {
  173. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  174. $oP->p("$sParam = $sDesc");
  175. }
  176. }
  177. }
  178. $oP->output();
  179. exit;
  180. }
  181. function ReadParam($oP, $sParam, $sSanitizationFilter = 'parameter')
  182. {
  183. global $aPageParams;
  184. assert(isset($aPageParams[$sParam]));
  185. assert(!$aPageParams[$sParam]['mandatory']);
  186. $sValue = utils::ReadParam($sParam, $aPageParams[$sParam]['default'], true /* Allow CLI */, $sSanitizationFilter);
  187. return trim($sValue);
  188. }
  189. function ReadMandatoryParam($oP, $sParam, $sSanitizationFilter)
  190. {
  191. global $aPageParams;
  192. assert(isset($aPageParams[$sParam]));
  193. assert($aPageParams[$sParam]['mandatory']);
  194. $sValue = utils::ReadParam($sParam, null, true /* Allow CLI */, $sSanitizationFilter);
  195. if (is_null($sValue))
  196. {
  197. $oP->p("ERROR: Missing argument '$sParam'\n");
  198. UsageAndExit($oP);
  199. }
  200. return trim($sValue);
  201. }
  202. /////////////////////////////////
  203. // Main program
  204. if (utils::IsModeCLI())
  205. {
  206. $oP = new CLIPage("iTop - Bulk import");
  207. }
  208. else
  209. {
  210. $oP = new CSVPage("iTop - Bulk import");
  211. }
  212. try
  213. {
  214. utils::UseParamFile();
  215. }
  216. catch(Exception $e)
  217. {
  218. $oP->p("Error: ".$e->GetMessage());
  219. $oP->output();
  220. exit -2;
  221. }
  222. if (utils::IsModeCLI())
  223. {
  224. // Next steps:
  225. // specific arguments: 'csvfile'
  226. //
  227. $sAuthUser = ReadMandatoryParam($oP, 'auth_user', 'raw_data');
  228. $sAuthPwd = ReadMandatoryParam($oP, 'auth_pwd', 'raw_data');
  229. $sCsvFile = ReadMandatoryParam($oP, 'csvfile', 'raw_data');
  230. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  231. {
  232. UserRights::Login($sAuthUser); // Login & set the user's language
  233. }
  234. else
  235. {
  236. $oP->p("Access restricted or wrong credentials ('$sAuthUser')");
  237. $oP->output();
  238. exit -1;
  239. }
  240. if (!is_readable($sCsvFile))
  241. {
  242. $oP->p("Input file could not be found or could not be read: '$sCsvFile'");
  243. $oP->output();
  244. exit -1;
  245. }
  246. $sCSVData = file_get_contents($sCsvFile);
  247. }
  248. else
  249. {
  250. $_SESSION['login_mode'] = 'basic';
  251. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  252. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  253. $sCSVData = utils::ReadPostedParam('csvdata', '', 'raw_data');
  254. }
  255. try
  256. {
  257. $aWarnings = array();
  258. //////////////////////////////////////////////////
  259. //
  260. // Read parameters
  261. //
  262. $sClass = ReadMandatoryParam($oP, 'class', 'raw_data'); // do not filter as a valid class, we want to produce the report "wrong class" ourselves
  263. $sSep = ReadParam($oP, 'separator', 'raw_data');
  264. $sQualifier = ReadParam($oP, 'qualifier', 'raw_data');
  265. $sCharSet = ReadParam($oP, 'charset', 'raw_data');
  266. $sDateFormat = ReadParam($oP, 'date_format', 'raw_data');
  267. if (strpos($sDateFormat, '%') !== false)
  268. {
  269. $sDateFormat = utils::DateTimeFormatToPHP($sDateFormat);
  270. }
  271. $sOutput = ReadParam($oP, 'output', 'string');
  272. $sReconcKeys = ReadParam($oP, 'reconciliationkeys', 'raw_data');
  273. $sSimulate = ReadParam($oP, 'simulate');
  274. $sComment = ReadParam($oP, 'comment', 'raw_data');
  275. $bLocalize = (ReadParam($oP, 'no_localize') != 1);
  276. if (strtolower(trim($sSep)) == 'tab')
  277. {
  278. $sSep = "\t";
  279. }
  280. //////////////////////////////////////////////////
  281. //
  282. // Check parameters format/consistency
  283. //
  284. if (strlen($sCSVData) == 0)
  285. {
  286. throw new BulkLoadException("Missing data - at least one line is expected");
  287. }
  288. if (!MetaModel::IsValidClass($sClass))
  289. {
  290. throw new BulkLoadException("Unknown class: '$sClass'");
  291. }
  292. if (strlen($sSep) > 1)
  293. {
  294. throw new BulkLoadException("Separator is limited to one character, found '$sSep'");
  295. }
  296. if (strlen($sQualifier) > 1)
  297. {
  298. throw new BulkLoadException("Text qualifier is limited to one character, found '$sQualifier'");
  299. }
  300. if (!in_array($sOutput, array('retcode', 'summary', 'details')))
  301. {
  302. throw new BulkLoadException("Unknown output format: '$sOutput'");
  303. }
  304. if (strlen($sDateFormat) == 0)
  305. {
  306. $sDateFormat = null;
  307. }
  308. if ($sCharSet == '')
  309. {
  310. $sCharSet = MetaModel::GetConfig()->Get('csv_file_default_charset');
  311. }
  312. if ($sSimulate == '1')
  313. {
  314. $bSimulate = true;
  315. }
  316. else
  317. {
  318. $bSimulate = false;
  319. }
  320. if (($sOutput == "summary") || ($sOutput == 'details'))
  321. {
  322. $oP->add_comment("Output format: ".$sOutput);
  323. $oP->add_comment("Class: ".$sClass);
  324. $oP->add_comment("Separator: ".$sSep);
  325. $oP->add_comment("Qualifier: ".$sQualifier);
  326. $oP->add_comment("Charset Encoding:".$sCharSet);
  327. if (strlen($sDateFormat) > 0)
  328. {
  329. $oP->add_comment("Date format: '$sDateFormat'");
  330. }
  331. else
  332. {
  333. $oP->add_comment("Date format: <none>");
  334. }
  335. $oP->add_comment("Localize: ".($bLocalize?'yes':'no'));
  336. $oP->add_comment("Data Size: ".strlen($sCSVData));
  337. }
  338. //////////////////////////////////////////////////
  339. //
  340. // Security
  341. //
  342. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY))
  343. {
  344. throw new SecurityException(Dict::Format('UI:Error:BulkModifyNotAllowedOn_Class', $sClass));
  345. }
  346. //////////////////////////////////////////////////
  347. //
  348. // Create an index of the known column names (in lower case)
  349. // If data is localized, an array of <TranslatedName> => array of <ExtendedAttCode> (several leads to ambiguity)
  350. // Otherwise an array of <ExtendedAttCode> => array of <ExtendedAttCode> (1 element by construction)
  351. //
  352. // Examples (localized in french):
  353. // 'lieu' => 'location_id'
  354. // 'lieu->name' => 'location_id->name'
  355. //
  356. // Note: it may happen that an external field has the same label as the external key
  357. // in that case, we consider that the external key has precedence
  358. //
  359. $aKnownColumnNames = array();
  360. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  361. {
  362. if ($bLocalize)
  363. {
  364. $sColName = strtolower(MetaModel::GetLabel($sClass, $sAttCode));
  365. }
  366. else
  367. {
  368. $sColName = strtolower($sAttCode);
  369. }
  370. if (!$oAttDef->IsExternalField() || !array_key_exists($sColName, $aKnownColumnNames))
  371. {
  372. $aKnownColumnNames[$sColName][] = $sAttCode;
  373. }
  374. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  375. {
  376. $sRemoteClass = $oAttDef->GetTargetClass();
  377. foreach(MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  378. {
  379. $sAttCodeEx = $sAttCode.'->'.$sRemoteAttCode;
  380. if ($bLocalize)
  381. {
  382. $sColName = strtolower(MetaModel::GetLabel($sClass, $sAttCodeEx));
  383. }
  384. else
  385. {
  386. $sColName = strtolower($sAttCodeEx);
  387. }
  388. if (!array_key_exists($sColName, $aKnownColumnNames))
  389. {
  390. $aKnownColumnNames[$sColName][] = $sAttCodeEx;
  391. }
  392. }
  393. }
  394. }
  395. //print_r($aKnownColumnNames);
  396. //print_r(array_keys($aKnownColumnNames));
  397. //exit;
  398. //////////////////////////////////////////////////
  399. //
  400. // Parse first line, check attributes, analyse the request
  401. //
  402. if ($sCharSet == 'UTF-8')
  403. {
  404. // Remove the BOM if any
  405. if (substr($sCSVData, 0, 3) == UTF8_BOM)
  406. {
  407. $sCSVData = substr($sCSVData, 3);
  408. }
  409. // Clean the input
  410. // Todo: warn the user if some characters are lost/substituted
  411. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  412. }
  413. else
  414. {
  415. $sUTF8Data = iconv($sCharSet, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  416. }
  417. $oCSVParser = new CSVParser($sUTF8Data, $sSep, $sQualifier);
  418. // Limitation: as the attribute list is in the first line, we can not match external key by a third-party attribute
  419. $aRawFieldList = $oCSVParser->ListFields();
  420. $iColCount = count($aRawFieldList);
  421. // Translate into internal names
  422. $aFieldList = array();
  423. foreach($aRawFieldList as $iFieldId => $sFieldName)
  424. {
  425. $sFieldName = trim($sFieldName);
  426. $aMatches = array();
  427. if (preg_match('/^(.+)\*$/', $sFieldName, $aMatches))
  428. {
  429. // Ignore any trailing "star" (*) that simply indicates a mandatory field
  430. $sFieldName = $aMatches[1];
  431. }
  432. else if (preg_match('/^(.+)\*->(.+)$/', $sFieldName, $aMatches))
  433. {
  434. // Remove any trailing "star" character before the arrow (->)
  435. // A star character at the end can be used to indicate a mandatory field
  436. $sFieldName = $aMatches[1].'->'.$aMatches[2];
  437. }
  438. if (array_key_exists(strtolower($sFieldName), $aKnownColumnNames))
  439. {
  440. $aColumns = $aKnownColumnNames[strtolower($sFieldName)];
  441. if (count($aColumns) > 1)
  442. {
  443. $aCompetitors = array();
  444. foreach ($aColumns as $sAttCodeEx)
  445. {
  446. $aCompetitors[] = $sAttCodeEx;
  447. }
  448. $aWarnings[] = "Input column '$sFieldName' is ambiguous. Could be related to ".implode (' or ', $aCompetitors).". The first one will be used: ".$aColumns[0];
  449. }
  450. $aFieldList[$iFieldId] = $aColumns[0];
  451. }
  452. else
  453. {
  454. // Protect against XSS injection
  455. $sSafeName = str_replace(array('"', '<', '>'), '', $sFieldName);
  456. throw new BulkLoadException("Unknown column: '$sSafeName'. Possible columns: ".implode(', ', array_keys($aKnownColumnNames)));
  457. }
  458. }
  459. // Note: at this stage the list of fields is supposed to be made of attcodes (and the symbol '->')
  460. $aAttList = array();
  461. $aExtKeys = array();
  462. foreach($aFieldList as $iFieldId => $sFieldName)
  463. {
  464. $aMatches = array();
  465. if (preg_match('/^(.+)->(.+)$/', trim($sFieldName), $aMatches))
  466. {
  467. // The column has been specified as "extkey->attcode"
  468. //
  469. $sExtKeyAttCode = $aMatches[1];
  470. $sRemoteAttCode = $aMatches[2];
  471. if (!MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  472. {
  473. // Safety net - should not happen now that column names are checked against known names
  474. throw new BulkLoadException("Unknown attribute '$sExtKeyAttCode' (class: '$sClass')");
  475. }
  476. $oAtt = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  477. if (!$oAtt->IsExternalKey())
  478. {
  479. // Safety net - should not happen now that column names are checked against known names
  480. throw new BulkLoadException("Not an external key '$sExtKeyAttCode' (class: '$sClass')");
  481. }
  482. $sTargetClass = $oAtt->GetTargetClass();
  483. if (!MetaModel::IsValidAttCode($sTargetClass, $sRemoteAttCode))
  484. {
  485. // Safety net - should not happen now that column names are checked against known names
  486. throw new BulkLoadException("Unknown attribute '$sRemoteAttCode' (key: '$sExtKeyAttCode', class: '$sTargetClass')");
  487. }
  488. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  489. }
  490. elseif ($sFieldName == 'id')
  491. {
  492. $aAttList[$sFieldName] = $iFieldId;
  493. }
  494. else
  495. {
  496. // The column has been specified as "attcode"
  497. //
  498. if (!MetaModel::IsValidAttCode($sClass, $sFieldName))
  499. {
  500. // Safety net - should not happen now that column names are checked against known names
  501. throw new BulkLoadException("Unknown attribute '$sFieldName' (class: '$sClass')");
  502. }
  503. $oAtt = MetaModel::GetAttributeDef($sClass, $sFieldName);
  504. if ($oAtt->IsExternalKey())
  505. {
  506. $aExtKeys[$sFieldName]['id'] = $iFieldId;
  507. $aAttList[$sFieldName] = $iFieldId;
  508. }
  509. elseif ($oAtt->IsExternalField())
  510. {
  511. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  512. $sRemoteAttCode = $oAtt->GetExtAttCode();
  513. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  514. }
  515. else
  516. {
  517. $aAttList[$sFieldName] = $iFieldId;
  518. }
  519. }
  520. }
  521. // Make sure there are some reconciliation keys
  522. //
  523. if (empty($sReconcKeys))
  524. {
  525. $aReconcSpec = array();
  526. // Base reconciliation scheme on the default one
  527. // The reconciliation attributes not present in the data will be ignored
  528. foreach(MetaModel::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  529. {
  530. if (in_array($sReconcKeyAttCode, $aFieldList))
  531. {
  532. if ($bLocalize)
  533. {
  534. $aReconcSpec[] = MetaModel::GetLabel($sClass, $sReconcKeyAttCode);
  535. }
  536. else
  537. {
  538. $aReconcSpec[] = $sReconcKeyAttCode;
  539. }
  540. }
  541. }
  542. if (count($aReconcSpec) == 0)
  543. {
  544. throw new BulkLoadException("No reconciliation scheme could be defined, please add a column corresponding to one defined reconciliation key (class: '$sClass', reconciliation:".implode(',', MetaModel::GetReconcKeys($sClass)).")");
  545. }
  546. $sReconcKeys = implode(',', $aReconcSpec);
  547. }
  548. // Interpret the list of reconciliation keys
  549. //
  550. $aFinalReconcilKeys = array();
  551. $aReconcilKeysReport = array();
  552. foreach (explode(',', $sReconcKeys) as $sReconcKey)
  553. {
  554. $sReconcKey = trim($sReconcKey);
  555. if (empty($sReconcKey)) continue; // skip empty spec
  556. if (array_key_exists(strtolower($sReconcKey), $aKnownColumnNames))
  557. {
  558. // Translate from a translated name to codes
  559. $aColumns = $aKnownColumnNames[strtolower($sReconcKey)];
  560. if (count($aColumns) > 1)
  561. {
  562. $aCompetitors = array();
  563. foreach ($aColumns as $sAttCodeEx)
  564. {
  565. $aCompetitors[] = $sAttCodeEx;
  566. }
  567. $aWarnings[] = "Reconciliation key '$sReconcKey' is ambiguous. Could be related to ".implode (' or ', $aCompetitors).". The first one will be used: ".$aColumns[0];
  568. }
  569. $sReconcKey = $aColumns[0];
  570. }
  571. else
  572. {
  573. // Protect against XSS injection
  574. $sSafeName = str_replace(array('"', '<', '>'), '', $sReconcKey);
  575. throw new BulkLoadException("Unknown reconciliation key: '$sSafeName'");
  576. }
  577. // Check that the reconciliation key is either a given column, or an external key
  578. if (!in_array($sReconcKey, $aFieldList))
  579. {
  580. if (!array_key_exists($sReconcKey, $aExtKeys))
  581. {
  582. // Protect against XSS injection
  583. $sSafeName = str_replace(array('"', '<', '>'), '', $sReconcKey);
  584. throw new BulkLoadException("Reconciliation key not found in the input columns: '$sSafeName'");
  585. }
  586. }
  587. if (preg_match('/^(.+)->(.+)$/', trim($sReconcKey), $aMatches))
  588. {
  589. // The column has been specified as "extkey->attcode"
  590. //
  591. $sExtKeyAttCode = $aMatches[1];
  592. $sRemoteAttCode = $aMatches[2];
  593. $aFinalReconcilKeys[] = $sExtKeyAttCode;
  594. $aReconcilKeysReport[$sExtKeyAttCode][] = $sRemoteAttCode;
  595. }
  596. else
  597. {
  598. if (!MetaModel::IsValidAttCode($sClass, $sReconcKey))
  599. {
  600. // Safety net - should not happen now that column names are checked against known names
  601. throw new BulkLoadException("Unknown reconciliation attribute '$sReconcKey' (class: '$sClass')");
  602. }
  603. $oAtt = MetaModel::GetAttributeDef($sClass, $sReconcKey);
  604. if ($oAtt->IsExternalKey())
  605. {
  606. $aFinalReconcilKeys[] = $sReconcKey;
  607. $aReconcilKeysReport[$sReconcKey][] = 'id';
  608. }
  609. elseif ($oAtt->IsExternalField())
  610. {
  611. $sReconcAttCode = $oAtt->GetKeyAttCode();
  612. $sReconcKeyReport = "$sReconcAttCode ($sReconcKey)";
  613. $aFinalReconcilKeys[] = $sReconcAttCode;
  614. $aReconcilKeysReport[$sReconcAttCode][] = $sReconcKeyReport;
  615. }
  616. else
  617. {
  618. $aFinalReconcilKeys[] = $sReconcKey;
  619. $aReconcilKeysReport[$sReconcKey] = array();
  620. }
  621. }
  622. }
  623. //////////////////////////////////////////////////
  624. //
  625. // Go for parsing and interpretation
  626. //
  627. $aData = $oCSVParser->ToArray();
  628. $iLineCount = count($aData);
  629. if (($sOutput == "summary") || ($sOutput == 'details'))
  630. {
  631. $oP->add_comment("Data Lines: ".$iLineCount);
  632. $oP->add_comment("Simulate: ".($bSimulate ? '1' : '0'));
  633. $oP->add_comment("Columns: ".implode(', ', $aFieldList));
  634. $aReconciliationReport = array();
  635. foreach($aReconcilKeysReport as $sKey => $aKeyDetails)
  636. {
  637. if (count($aKeyDetails) > 0)
  638. {
  639. $aReconciliationReport[] = $sKey.' ('.implode(',', $aKeyDetails).')';
  640. }
  641. else
  642. {
  643. $aReconciliationReport[] = $sKey;
  644. }
  645. }
  646. $oP->add_comment("Reconciliation Keys: ".implode(', ', $aReconciliationReport));
  647. foreach ($aWarnings as $sWarning)
  648. {
  649. $oP->add_comment("Warning: ".$sWarning);
  650. }
  651. }
  652. $oBulk = new BulkChange(
  653. $sClass,
  654. $aData,
  655. $aAttList,
  656. $aExtKeys,
  657. $aFinalReconcilKeys,
  658. null, // synchro scope
  659. null, // on delete
  660. $sDateFormat,
  661. $bLocalize
  662. );
  663. if ($bSimulate)
  664. {
  665. $oMyChange = null;
  666. }
  667. else
  668. {
  669. if (strlen($sComment) > 0)
  670. {
  671. $sMoreInfo = CMDBChange::GetCurrentUserName().', Web Service (CSV) - '.$sComment;
  672. }
  673. else
  674. {
  675. $sMoreInfo = CMDBChange::GetCurrentUserName().', Web Service (CSV)';
  676. }
  677. CMDBObject::SetTrackInfo($sMoreInfo);
  678. CMDBObject::SetTrackOrigin('csv-import.php');
  679. $oMyChange = CMDBObject::GetCurrentChange();
  680. }
  681. $aRes = $oBulk->Process($oMyChange);
  682. //////////////////////////////////////////////////
  683. //
  684. // Compute statistics
  685. //
  686. $iCountErrors = 0;
  687. $iCountWarnings = 0;
  688. $iCountCreations = 0;
  689. $iCountUpdates = 0;
  690. $iCountUnchanged = 0;
  691. foreach($aRes as $iRow => $aRowData)
  692. {
  693. $bWritten = false;
  694. $oStatus = $aRowData["__STATUS__"];
  695. switch(get_class($oStatus))
  696. {
  697. case 'RowStatus_NoChange':
  698. $iCountUnchanged++;
  699. break;
  700. case 'RowStatus_Modify':
  701. $iCountUpdates++;
  702. $bWritten = true;
  703. break;
  704. case 'RowStatus_NewObj':
  705. $iCountCreations++;
  706. $bWritten = true;
  707. break;
  708. case 'RowStatus_Issue':
  709. $iCountErrors++;
  710. break;
  711. }
  712. if ($bWritten)
  713. {
  714. // Something has been done, still there may be some issues to report
  715. foreach($aRowData as $key => $value)
  716. {
  717. if (!is_object($value)) continue;
  718. switch (get_class($value))
  719. {
  720. case 'CellStatus_Void':
  721. case 'CellStatus_Modify':
  722. break;
  723. case 'CellStatus_Issue':
  724. case 'CellStatus_SearchIssue':
  725. case 'CellStatus_NullIssue':
  726. case 'CellStatus_Ambiguous':
  727. $iCountWarnings++;
  728. break;
  729. }
  730. }
  731. }
  732. }
  733. //////////////////////////////////////////////////
  734. //
  735. // Summary of settings and results
  736. //
  737. if ($sOutput == 'retcode')
  738. {
  739. $oP->add($iCountErrors);
  740. }
  741. if (($sOutput == "summary") || ($sOutput == 'details'))
  742. {
  743. $oP->add_comment("Change tracking comment: ".$sComment);
  744. $oP->add_comment("Issues: ".$iCountErrors);
  745. $oP->add_comment("Warnings: ".$iCountWarnings);
  746. $oP->add_comment("Created: ".$iCountCreations);
  747. $oP->add_comment("Updated: ".$iCountUpdates);
  748. $oP->add_comment("Unchanged: ".$iCountUnchanged);
  749. }
  750. if ($sOutput == 'details')
  751. {
  752. // Setup result presentation
  753. //
  754. $aDisplayConfig = array();
  755. $aDisplayConfig["__LINE__"] = array("label"=>"Line", "description"=>"");
  756. $aDisplayConfig["__STATUS__"] = array("label"=>"Status", "description"=>"");
  757. $aDisplayConfig["__OBJECT_CLASS__"] = array("label"=>"Object Class", "description"=>"");
  758. $aDisplayConfig["__OBJECT_ID__"] = array("label"=>"Object Id", "description"=>"");
  759. foreach($aExtKeys as $sExtKeyAttCode => $aRemoteAtt)
  760. {
  761. $sLabel = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode)->GetLabel();
  762. $aDisplayConfig["$sExtKeyAttCode"] = array("label"=>$sExtKeyAttCode, "description"=>$sLabel." - ext key");
  763. }
  764. foreach($aFinalReconcilKeys as $iCol => $sAttCode)
  765. {
  766. // $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  767. // $aDisplayConfig["$iCol"] = array("label"=>"$sLabel", "description"=>"");
  768. }
  769. foreach ($aAttList as $sAttCode => $iCol)
  770. {
  771. if ($sAttCode == 'id')
  772. {
  773. $sLabel = Dict::S('UI:CSVImport:idField');
  774. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  775. }
  776. else
  777. {
  778. $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  779. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  780. }
  781. }
  782. $aResultDisp = array(); // to be displayed
  783. foreach($aRes as $iRow => $aRowData)
  784. {
  785. $aRowDisp = array();
  786. $aRowDisp["__LINE__"] = $iRow;
  787. if (is_object($aRowData["__STATUS__"]))
  788. {
  789. $aRowDisp["__STATUS__"] = $aRowData["__STATUS__"]->GetDescription();
  790. }
  791. else
  792. {
  793. $aRowDisp["__STATUS__"] = "*No status available*";
  794. }
  795. if (isset($aRowData["finalclass"]) && isset($aRowData["id"]))
  796. {
  797. $aRowDisp["__OBJECT_CLASS__"] = $aRowData["finalclass"];
  798. $aRowDisp["__OBJECT_ID__"] = $aRowData["id"]->GetDisplayableValue();
  799. }
  800. else
  801. {
  802. $aRowDisp["__OBJECT_CLASS__"] = "n/a";
  803. $aRowDisp["__OBJECT_ID__"] = "n/a";
  804. }
  805. foreach($aRowData as $key => $value)
  806. {
  807. $sKey = (string) $key;
  808. if ($sKey == '__STATUS__') continue;
  809. if ($sKey == 'finalclass') continue;
  810. if ($sKey == 'id') continue;
  811. if (is_object($value))
  812. {
  813. $aRowDisp["$sKey"] = $value->GetDisplayableValue().$value->GetDescription();
  814. }
  815. else
  816. {
  817. $aRowDisp["$sKey"] = $value;
  818. }
  819. }
  820. $aResultDisp[$iRow] = $aRowDisp;
  821. }
  822. $oP->table($aDisplayConfig, $aResultDisp);
  823. }
  824. }
  825. catch(BulkLoadException $e)
  826. {
  827. $oP->add_comment($e->getMessage());
  828. }
  829. catch(SecurityException $e)
  830. {
  831. $oP->add_comment($e->getMessage());
  832. }
  833. catch(Exception $e)
  834. {
  835. $oP->add_comment((string)$e);
  836. }
  837. $oP->output();
  838. ?>