import.php 25 KB

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