import.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  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 (($sDateFormat !== null) && (strlen($sDateFormat) > 0))
  328. {
  329. $oP->add_comment("Date and time format: '$sDateFormat'");
  330. $oDateTimeFormat = new DateTimeFormat($sDateFormat);
  331. $sDateOnlyFormat = $oDateTimeFormat->ToDateFormat();
  332. $oP->add_comment("Date format: '$sDateOnlyFormat'");
  333. }
  334. else
  335. {
  336. $oP->add_comment("Date format: <none>");
  337. }
  338. $oP->add_comment("Localize: ".($bLocalize?'yes':'no'));
  339. $oP->add_comment("Data Size: ".strlen($sCSVData));
  340. }
  341. //////////////////////////////////////////////////
  342. //
  343. // Security
  344. //
  345. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY))
  346. {
  347. throw new SecurityException(Dict::Format('UI:Error:BulkModifyNotAllowedOn_Class', $sClass));
  348. }
  349. //////////////////////////////////////////////////
  350. //
  351. // Create an index of the known column names (in lower case)
  352. // If data is localized, an array of <TranslatedName> => array of <ExtendedAttCode> (several leads to ambiguity)
  353. // Otherwise an array of <ExtendedAttCode> => array of <ExtendedAttCode> (1 element by construction)
  354. //
  355. // Examples (localized in french):
  356. // 'lieu' => 'location_id'
  357. // 'lieu->name' => 'location_id->name'
  358. //
  359. // Note: it may happen that an external field has the same label as the external key
  360. // in that case, we consider that the external key has precedence
  361. //
  362. $aKnownColumnNames = array();
  363. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  364. {
  365. if ($bLocalize)
  366. {
  367. $sColName = strtolower(MetaModel::GetLabel($sClass, $sAttCode));
  368. }
  369. else
  370. {
  371. $sColName = strtolower($sAttCode);
  372. }
  373. if (!$oAttDef->IsExternalField() || !array_key_exists($sColName, $aKnownColumnNames))
  374. {
  375. $aKnownColumnNames[$sColName][] = $sAttCode;
  376. }
  377. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  378. {
  379. $sRemoteClass = $oAttDef->GetTargetClass();
  380. foreach(MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  381. {
  382. $sAttCodeEx = $sAttCode.'->'.$sRemoteAttCode;
  383. if ($bLocalize)
  384. {
  385. $sColName = strtolower(MetaModel::GetLabel($sClass, $sAttCodeEx));
  386. }
  387. else
  388. {
  389. $sColName = strtolower($sAttCodeEx);
  390. }
  391. if (!array_key_exists($sColName, $aKnownColumnNames))
  392. {
  393. $aKnownColumnNames[$sColName][] = $sAttCodeEx;
  394. }
  395. }
  396. }
  397. }
  398. //print_r($aKnownColumnNames);
  399. //print_r(array_keys($aKnownColumnNames));
  400. //exit;
  401. //////////////////////////////////////////////////
  402. //
  403. // Parse first line, check attributes, analyse the request
  404. //
  405. if ($sCharSet == 'UTF-8')
  406. {
  407. // Remove the BOM if any
  408. if (substr($sCSVData, 0, 3) == UTF8_BOM)
  409. {
  410. $sCSVData = substr($sCSVData, 3);
  411. }
  412. // Clean the input
  413. // Todo: warn the user if some characters are lost/substituted
  414. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  415. }
  416. else
  417. {
  418. $sUTF8Data = iconv($sCharSet, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  419. }
  420. $oCSVParser = new CSVParser($sUTF8Data, $sSep, $sQualifier);
  421. // Limitation: as the attribute list is in the first line, we can not match external key by a third-party attribute
  422. $aRawFieldList = $oCSVParser->ListFields();
  423. $iColCount = count($aRawFieldList);
  424. // Translate into internal names
  425. $aFieldList = array();
  426. foreach($aRawFieldList as $iFieldId => $sFieldName)
  427. {
  428. $sFieldName = trim($sFieldName);
  429. $aMatches = array();
  430. if (preg_match('/^(.+)\*$/', $sFieldName, $aMatches))
  431. {
  432. // Ignore any trailing "star" (*) that simply indicates a mandatory field
  433. $sFieldName = $aMatches[1];
  434. }
  435. else if (preg_match('/^(.+)\*->(.+)$/', $sFieldName, $aMatches))
  436. {
  437. // Remove any trailing "star" character before the arrow (->)
  438. // A star character at the end can be used to indicate a mandatory field
  439. $sFieldName = $aMatches[1].'->'.$aMatches[2];
  440. }
  441. if (array_key_exists(strtolower($sFieldName), $aKnownColumnNames))
  442. {
  443. $aColumns = $aKnownColumnNames[strtolower($sFieldName)];
  444. if (count($aColumns) > 1)
  445. {
  446. $aCompetitors = array();
  447. foreach ($aColumns as $sAttCodeEx)
  448. {
  449. $aCompetitors[] = $sAttCodeEx;
  450. }
  451. $aWarnings[] = "Input column '$sFieldName' is ambiguous. Could be related to ".implode (' or ', $aCompetitors).". The first one will be used: ".$aColumns[0];
  452. }
  453. $aFieldList[$iFieldId] = $aColumns[0];
  454. }
  455. else
  456. {
  457. // Protect against XSS injection
  458. $sSafeName = str_replace(array('"', '<', '>'), '', $sFieldName);
  459. throw new BulkLoadException("Unknown column: '$sSafeName'. Possible columns: ".implode(', ', array_keys($aKnownColumnNames)));
  460. }
  461. }
  462. // Note: at this stage the list of fields is supposed to be made of attcodes (and the symbol '->')
  463. $aAttList = array();
  464. $aExtKeys = array();
  465. foreach($aFieldList as $iFieldId => $sFieldName)
  466. {
  467. $aMatches = array();
  468. if (preg_match('/^(.+)->(.+)$/', trim($sFieldName), $aMatches))
  469. {
  470. // The column has been specified as "extkey->attcode"
  471. //
  472. $sExtKeyAttCode = $aMatches[1];
  473. $sRemoteAttCode = $aMatches[2];
  474. if (!MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  475. {
  476. // Safety net - should not happen now that column names are checked against known names
  477. throw new BulkLoadException("Unknown attribute '$sExtKeyAttCode' (class: '$sClass')");
  478. }
  479. $oAtt = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  480. if (!$oAtt->IsExternalKey())
  481. {
  482. // Safety net - should not happen now that column names are checked against known names
  483. throw new BulkLoadException("Not an external key '$sExtKeyAttCode' (class: '$sClass')");
  484. }
  485. $sTargetClass = $oAtt->GetTargetClass();
  486. if (!MetaModel::IsValidAttCode($sTargetClass, $sRemoteAttCode))
  487. {
  488. // Safety net - should not happen now that column names are checked against known names
  489. throw new BulkLoadException("Unknown attribute '$sRemoteAttCode' (key: '$sExtKeyAttCode', class: '$sTargetClass')");
  490. }
  491. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  492. }
  493. elseif ($sFieldName == 'id')
  494. {
  495. $aAttList[$sFieldName] = $iFieldId;
  496. }
  497. else
  498. {
  499. // The column has been specified as "attcode"
  500. //
  501. if (!MetaModel::IsValidAttCode($sClass, $sFieldName))
  502. {
  503. // Safety net - should not happen now that column names are checked against known names
  504. throw new BulkLoadException("Unknown attribute '$sFieldName' (class: '$sClass')");
  505. }
  506. $oAtt = MetaModel::GetAttributeDef($sClass, $sFieldName);
  507. if ($oAtt->IsExternalKey())
  508. {
  509. $aExtKeys[$sFieldName]['id'] = $iFieldId;
  510. $aAttList[$sFieldName] = $iFieldId;
  511. }
  512. elseif ($oAtt->IsExternalField())
  513. {
  514. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  515. $sRemoteAttCode = $oAtt->GetExtAttCode();
  516. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  517. }
  518. else
  519. {
  520. $aAttList[$sFieldName] = $iFieldId;
  521. }
  522. }
  523. }
  524. // Make sure there are some reconciliation keys
  525. //
  526. if (empty($sReconcKeys))
  527. {
  528. $aReconcSpec = array();
  529. // Base reconciliation scheme on the default one
  530. // The reconciliation attributes not present in the data will be ignored
  531. foreach(MetaModel::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  532. {
  533. if (in_array($sReconcKeyAttCode, $aFieldList))
  534. {
  535. if ($bLocalize)
  536. {
  537. $aReconcSpec[] = MetaModel::GetLabel($sClass, $sReconcKeyAttCode);
  538. }
  539. else
  540. {
  541. $aReconcSpec[] = $sReconcKeyAttCode;
  542. }
  543. }
  544. }
  545. if (count($aReconcSpec) == 0)
  546. {
  547. 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)).")");
  548. }
  549. $sReconcKeys = implode(',', $aReconcSpec);
  550. }
  551. // Interpret the list of reconciliation keys
  552. //
  553. $aFinalReconcilKeys = array();
  554. $aReconcilKeysReport = array();
  555. foreach (explode(',', $sReconcKeys) as $sReconcKey)
  556. {
  557. $sReconcKey = trim($sReconcKey);
  558. if (empty($sReconcKey)) continue; // skip empty spec
  559. if (array_key_exists(strtolower($sReconcKey), $aKnownColumnNames))
  560. {
  561. // Translate from a translated name to codes
  562. $aColumns = $aKnownColumnNames[strtolower($sReconcKey)];
  563. if (count($aColumns) > 1)
  564. {
  565. $aCompetitors = array();
  566. foreach ($aColumns as $sAttCodeEx)
  567. {
  568. $aCompetitors[] = $sAttCodeEx;
  569. }
  570. $aWarnings[] = "Reconciliation key '$sReconcKey' is ambiguous. Could be related to ".implode (' or ', $aCompetitors).". The first one will be used: ".$aColumns[0];
  571. }
  572. $sReconcKey = $aColumns[0];
  573. }
  574. else
  575. {
  576. // Protect against XSS injection
  577. $sSafeName = str_replace(array('"', '<', '>'), '', $sReconcKey);
  578. throw new BulkLoadException("Unknown reconciliation key: '$sSafeName'");
  579. }
  580. // Check that the reconciliation key is either a given column, or an external key
  581. if (!in_array($sReconcKey, $aFieldList))
  582. {
  583. if (!array_key_exists($sReconcKey, $aExtKeys))
  584. {
  585. // Protect against XSS injection
  586. $sSafeName = str_replace(array('"', '<', '>'), '', $sReconcKey);
  587. throw new BulkLoadException("Reconciliation key not found in the input columns: '$sSafeName'");
  588. }
  589. }
  590. if (preg_match('/^(.+)->(.+)$/', trim($sReconcKey), $aMatches))
  591. {
  592. // The column has been specified as "extkey->attcode"
  593. //
  594. $sExtKeyAttCode = $aMatches[1];
  595. $sRemoteAttCode = $aMatches[2];
  596. $aFinalReconcilKeys[] = $sExtKeyAttCode;
  597. $aReconcilKeysReport[$sExtKeyAttCode][] = $sRemoteAttCode;
  598. }
  599. else
  600. {
  601. if (!MetaModel::IsValidAttCode($sClass, $sReconcKey))
  602. {
  603. // Safety net - should not happen now that column names are checked against known names
  604. throw new BulkLoadException("Unknown reconciliation attribute '$sReconcKey' (class: '$sClass')");
  605. }
  606. $oAtt = MetaModel::GetAttributeDef($sClass, $sReconcKey);
  607. if ($oAtt->IsExternalKey())
  608. {
  609. $aFinalReconcilKeys[] = $sReconcKey;
  610. $aReconcilKeysReport[$sReconcKey][] = 'id';
  611. }
  612. elseif ($oAtt->IsExternalField())
  613. {
  614. $sReconcAttCode = $oAtt->GetKeyAttCode();
  615. $sReconcKeyReport = "$sReconcAttCode ($sReconcKey)";
  616. $aFinalReconcilKeys[] = $sReconcAttCode;
  617. $aReconcilKeysReport[$sReconcAttCode][] = $sReconcKeyReport;
  618. }
  619. else
  620. {
  621. $aFinalReconcilKeys[] = $sReconcKey;
  622. $aReconcilKeysReport[$sReconcKey] = array();
  623. }
  624. }
  625. }
  626. //////////////////////////////////////////////////
  627. //
  628. // Go for parsing and interpretation
  629. //
  630. $aData = $oCSVParser->ToArray();
  631. $iLineCount = count($aData);
  632. if (($sOutput == "summary") || ($sOutput == 'details'))
  633. {
  634. $oP->add_comment("Data Lines: ".$iLineCount);
  635. $oP->add_comment("Simulate: ".($bSimulate ? '1' : '0'));
  636. $oP->add_comment("Columns: ".implode(', ', $aFieldList));
  637. $aReconciliationReport = array();
  638. foreach($aReconcilKeysReport as $sKey => $aKeyDetails)
  639. {
  640. if (count($aKeyDetails) > 0)
  641. {
  642. $aReconciliationReport[] = $sKey.' ('.implode(',', $aKeyDetails).')';
  643. }
  644. else
  645. {
  646. $aReconciliationReport[] = $sKey;
  647. }
  648. }
  649. $oP->add_comment("Reconciliation Keys: ".implode(', ', $aReconciliationReport));
  650. foreach ($aWarnings as $sWarning)
  651. {
  652. $oP->add_comment("Warning: ".$sWarning);
  653. }
  654. }
  655. $oBulk = new BulkChange(
  656. $sClass,
  657. $aData,
  658. $aAttList,
  659. $aExtKeys,
  660. $aFinalReconcilKeys,
  661. null, // synchro scope
  662. null, // on delete
  663. $sDateFormat,
  664. $bLocalize
  665. );
  666. if ($bSimulate)
  667. {
  668. $oMyChange = null;
  669. }
  670. else
  671. {
  672. if (strlen($sComment) > 0)
  673. {
  674. $sMoreInfo = CMDBChange::GetCurrentUserName().', Web Service (CSV) - '.$sComment;
  675. }
  676. else
  677. {
  678. $sMoreInfo = CMDBChange::GetCurrentUserName().', Web Service (CSV)';
  679. }
  680. CMDBObject::SetTrackInfo($sMoreInfo);
  681. CMDBObject::SetTrackOrigin('csv-import.php');
  682. $oMyChange = CMDBObject::GetCurrentChange();
  683. }
  684. $aRes = $oBulk->Process($oMyChange);
  685. //////////////////////////////////////////////////
  686. //
  687. // Compute statistics
  688. //
  689. $iCountErrors = 0;
  690. $iCountWarnings = 0;
  691. $iCountCreations = 0;
  692. $iCountUpdates = 0;
  693. $iCountUnchanged = 0;
  694. foreach($aRes as $iRow => $aRowData)
  695. {
  696. $bWritten = false;
  697. $oStatus = $aRowData["__STATUS__"];
  698. switch(get_class($oStatus))
  699. {
  700. case 'RowStatus_NoChange':
  701. $iCountUnchanged++;
  702. break;
  703. case 'RowStatus_Modify':
  704. $iCountUpdates++;
  705. $bWritten = true;
  706. break;
  707. case 'RowStatus_NewObj':
  708. $iCountCreations++;
  709. $bWritten = true;
  710. break;
  711. case 'RowStatus_Issue':
  712. $iCountErrors++;
  713. break;
  714. }
  715. if ($bWritten)
  716. {
  717. // Something has been done, still there may be some issues to report
  718. foreach($aRowData as $key => $value)
  719. {
  720. if (!is_object($value)) continue;
  721. switch (get_class($value))
  722. {
  723. case 'CellStatus_Void':
  724. case 'CellStatus_Modify':
  725. break;
  726. case 'CellStatus_Issue':
  727. case 'CellStatus_SearchIssue':
  728. case 'CellStatus_NullIssue':
  729. case 'CellStatus_Ambiguous':
  730. $iCountWarnings++;
  731. break;
  732. }
  733. }
  734. }
  735. }
  736. //////////////////////////////////////////////////
  737. //
  738. // Summary of settings and results
  739. //
  740. if ($sOutput == 'retcode')
  741. {
  742. $oP->add($iCountErrors);
  743. }
  744. if (($sOutput == "summary") || ($sOutput == 'details'))
  745. {
  746. $oP->add_comment("Change tracking comment: ".$sComment);
  747. $oP->add_comment("Issues: ".$iCountErrors);
  748. $oP->add_comment("Warnings: ".$iCountWarnings);
  749. $oP->add_comment("Created: ".$iCountCreations);
  750. $oP->add_comment("Updated: ".$iCountUpdates);
  751. $oP->add_comment("Unchanged: ".$iCountUnchanged);
  752. }
  753. if ($sOutput == 'details')
  754. {
  755. // Setup result presentation
  756. //
  757. $aDisplayConfig = array();
  758. $aDisplayConfig["__LINE__"] = array("label"=>"Line", "description"=>"");
  759. $aDisplayConfig["__STATUS__"] = array("label"=>"Status", "description"=>"");
  760. $aDisplayConfig["__OBJECT_CLASS__"] = array("label"=>"Object Class", "description"=>"");
  761. $aDisplayConfig["__OBJECT_ID__"] = array("label"=>"Object Id", "description"=>"");
  762. foreach($aExtKeys as $sExtKeyAttCode => $aRemoteAtt)
  763. {
  764. $sLabel = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode)->GetLabel();
  765. $aDisplayConfig["$sExtKeyAttCode"] = array("label"=>$sExtKeyAttCode, "description"=>$sLabel." - ext key");
  766. }
  767. foreach($aFinalReconcilKeys as $iCol => $sAttCode)
  768. {
  769. // $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  770. // $aDisplayConfig["$iCol"] = array("label"=>"$sLabel", "description"=>"");
  771. }
  772. foreach ($aAttList as $sAttCode => $iCol)
  773. {
  774. if ($sAttCode == 'id')
  775. {
  776. $sLabel = Dict::S('UI:CSVImport:idField');
  777. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  778. }
  779. else
  780. {
  781. $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  782. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  783. }
  784. }
  785. $aResultDisp = array(); // to be displayed
  786. foreach($aRes as $iRow => $aRowData)
  787. {
  788. $aRowDisp = array();
  789. $aRowDisp["__LINE__"] = $iRow;
  790. if (is_object($aRowData["__STATUS__"]))
  791. {
  792. $aRowDisp["__STATUS__"] = $aRowData["__STATUS__"]->GetDescription();
  793. }
  794. else
  795. {
  796. $aRowDisp["__STATUS__"] = "*No status available*";
  797. }
  798. if (isset($aRowData["finalclass"]) && isset($aRowData["id"]))
  799. {
  800. $aRowDisp["__OBJECT_CLASS__"] = $aRowData["finalclass"];
  801. $aRowDisp["__OBJECT_ID__"] = $aRowData["id"]->GetDisplayableValue();
  802. }
  803. else
  804. {
  805. $aRowDisp["__OBJECT_CLASS__"] = "n/a";
  806. $aRowDisp["__OBJECT_ID__"] = "n/a";
  807. }
  808. foreach($aRowData as $key => $value)
  809. {
  810. $sKey = (string) $key;
  811. if ($sKey == '__STATUS__') continue;
  812. if ($sKey == 'finalclass') continue;
  813. if ($sKey == 'id') continue;
  814. if (is_object($value))
  815. {
  816. $aRowDisp["$sKey"] = $value->GetDisplayableValue().$value->GetDescription();
  817. }
  818. else
  819. {
  820. $aRowDisp["$sKey"] = $value;
  821. }
  822. }
  823. $aResultDisp[$iRow] = $aRowDisp;
  824. }
  825. $oP->table($aDisplayConfig, $aResultDisp);
  826. }
  827. }
  828. catch(BulkLoadException $e)
  829. {
  830. $oP->add_comment($e->getMessage());
  831. }
  832. catch(SecurityException $e)
  833. {
  834. $oP->add_comment($e->getMessage());
  835. }
  836. catch(Exception $e)
  837. {
  838. $oP->add_comment((string)$e);
  839. }
  840. $oP->output();
  841. ?>