import.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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. if (array_key_exists(strtolower($sFieldName), $aKnownColumnNames))
  429. {
  430. $aColumns = $aKnownColumnNames[strtolower($sFieldName)];
  431. if (count($aColumns) > 1)
  432. {
  433. $aCompetitors = array();
  434. foreach ($aColumns as $sAttCodeEx)
  435. {
  436. $aCompetitors[] = $sAttCodeEx;
  437. }
  438. $aWarnings[] = "Input column '$sFieldName' is ambiguous. Could be related to ".implode (' or ', $aCompetitors).". The first one will be used: ".$aColumns[0];
  439. }
  440. $aFieldList[$iFieldId] = $aColumns[0];
  441. }
  442. else
  443. {
  444. // Protect against XSS injection
  445. $sSafeName = str_replace(array('"', '<', '>'), '', $sFieldName);
  446. throw new BulkLoadException("Unknown column: '$sSafeName'");
  447. }
  448. }
  449. // Note: at this stage the list of fields is supposed to be made of attcodes (and the symbol '->')
  450. $aAttList = array();
  451. $aExtKeys = array();
  452. foreach($aFieldList as $iFieldId => $sFieldName)
  453. {
  454. $aMatches = array();
  455. if (preg_match('/^(.+)->(.+)$/', trim($sFieldName), $aMatches))
  456. {
  457. // The column has been specified as "extkey->attcode"
  458. //
  459. $sExtKeyAttCode = $aMatches[1];
  460. $sRemoteAttCode = $aMatches[2];
  461. if (!MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  462. {
  463. // Safety net - should not happen now that column names are checked against known names
  464. throw new BulkLoadException("Unknown attribute '$sExtKeyAttCode' (class: '$sClass')");
  465. }
  466. $oAtt = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  467. if (!$oAtt->IsExternalKey())
  468. {
  469. // Safety net - should not happen now that column names are checked against known names
  470. throw new BulkLoadException("Not an external key '$sExtKeyAttCode' (class: '$sClass')");
  471. }
  472. $sTargetClass = $oAtt->GetTargetClass();
  473. if (!MetaModel::IsValidAttCode($sTargetClass, $sRemoteAttCode))
  474. {
  475. // Safety net - should not happen now that column names are checked against known names
  476. throw new BulkLoadException("Unknown attribute '$sRemoteAttCode' (key: '$sExtKeyAttCode', class: '$sTargetClass')");
  477. }
  478. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  479. }
  480. elseif ($sFieldName == 'id')
  481. {
  482. $aAttList[$sFieldName] = $iFieldId;
  483. }
  484. else
  485. {
  486. // The column has been specified as "attcode"
  487. //
  488. if (!MetaModel::IsValidAttCode($sClass, $sFieldName))
  489. {
  490. // Safety net - should not happen now that column names are checked against known names
  491. throw new BulkLoadException("Unknown attribute '$sFieldName' (class: '$sClass')");
  492. }
  493. $oAtt = MetaModel::GetAttributeDef($sClass, $sFieldName);
  494. if ($oAtt->IsExternalKey())
  495. {
  496. $aExtKeys[$sFieldName]['id'] = $iFieldId;
  497. $aAttList[$sFieldName] = $iFieldId;
  498. }
  499. elseif ($oAtt->IsExternalField())
  500. {
  501. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  502. $sRemoteAttCode = $oAtt->GetExtAttCode();
  503. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  504. }
  505. else
  506. {
  507. $aAttList[$sFieldName] = $iFieldId;
  508. }
  509. }
  510. }
  511. // Make sure there are some reconciliation keys
  512. //
  513. if (empty($sReconcKeys))
  514. {
  515. $aReconcSpec = array();
  516. // Base reconciliation scheme on the default one
  517. // The reconciliation attributes not present in the data will be ignored
  518. foreach(MetaModel::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  519. {
  520. if (in_array($sReconcKeyAttCode, $aFieldList))
  521. {
  522. if ($bLocalize)
  523. {
  524. $aReconcSpec[] = MetaModel::GetLabel($sClass, $sReconcKeyAttCode);
  525. }
  526. else
  527. {
  528. $aReconcSpec[] = $sReconcKeyAttCode;
  529. }
  530. }
  531. }
  532. if (count($aReconcSpec) == 0)
  533. {
  534. 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)).")");
  535. }
  536. $sReconcKeys = implode(',', $aReconcSpec);
  537. }
  538. // Interpret the list of reconciliation keys
  539. //
  540. $aFinalReconcilKeys = array();
  541. $aReconcilKeysReport = array();
  542. foreach (explode(',', $sReconcKeys) as $sReconcKey)
  543. {
  544. $sReconcKey = trim($sReconcKey);
  545. if (empty($sReconcKey)) continue; // skip empty spec
  546. if (array_key_exists(strtolower($sReconcKey), $aKnownColumnNames))
  547. {
  548. // Translate from a translated name to codes
  549. $aColumns = $aKnownColumnNames[strtolower($sReconcKey)];
  550. if (count($aColumns) > 1)
  551. {
  552. $aCompetitors = array();
  553. foreach ($aColumns as $sAttCodeEx)
  554. {
  555. $aCompetitors[] = $sAttCodeEx;
  556. }
  557. $aWarnings[] = "Reconciliation key '$sReconcKey' is ambiguous. Could be related to ".implode (' or ', $aCompetitors).". The first one will be used: ".$aColumns[0];
  558. }
  559. $sReconcKey = $aColumns[0];
  560. }
  561. else
  562. {
  563. // Protect against XSS injection
  564. $sSafeName = str_replace(array('"', '<', '>'), '', $sReconcKey);
  565. throw new BulkLoadException("Unknown reconciliation key: '$sSafeName'");
  566. }
  567. // Check that the reconciliation key is either a given column, or an external key
  568. if (!in_array($sReconcKey, $aFieldList))
  569. {
  570. if (!array_key_exists($sReconcKey, $aExtKeys))
  571. {
  572. // Protect against XSS injection
  573. $sSafeName = str_replace(array('"', '<', '>'), '', $sReconcKey);
  574. throw new BulkLoadException("Reconciliation key not found in the input columns: '$sSafeName'");
  575. }
  576. }
  577. if (preg_match('/^(.+)->(.+)$/', trim($sReconcKey), $aMatches))
  578. {
  579. // The column has been specified as "extkey->attcode"
  580. //
  581. $sExtKeyAttCode = $aMatches[1];
  582. $sRemoteAttCode = $aMatches[2];
  583. $aFinalReconcilKeys[] = $sExtKeyAttCode;
  584. $aReconcilKeysReport[$sExtKeyAttCode][] = $sRemoteAttCode;
  585. }
  586. else
  587. {
  588. if (!MetaModel::IsValidAttCode($sClass, $sReconcKey))
  589. {
  590. // Safety net - should not happen now that column names are checked against known names
  591. throw new BulkLoadException("Unknown reconciliation attribute '$sReconcKey' (class: '$sClass')");
  592. }
  593. $oAtt = MetaModel::GetAttributeDef($sClass, $sReconcKey);
  594. if ($oAtt->IsExternalKey())
  595. {
  596. $aFinalReconcilKeys[] = $sReconcKey;
  597. $aReconcilKeysReport[$sReconcKey][] = 'id';
  598. }
  599. elseif ($oAtt->IsExternalField())
  600. {
  601. $sReconcAttCode = $oAtt->GetKeyAttCode();
  602. $sReconcKeyReport = "$sReconcAttCode ($sReconcKey)";
  603. $aFinalReconcilKeys[] = $sReconcAttCode;
  604. $aReconcilKeysReport[$sReconcAttCode][] = $sReconcKeyReport;
  605. }
  606. else
  607. {
  608. $aFinalReconcilKeys[] = $sReconcKey;
  609. $aReconcilKeysReport[$sReconcKey] = array();
  610. }
  611. }
  612. }
  613. //////////////////////////////////////////////////
  614. //
  615. // Go for parsing and interpretation
  616. //
  617. $aData = $oCSVParser->ToArray();
  618. $iLineCount = count($aData);
  619. if (($sOutput == "summary") || ($sOutput == 'details'))
  620. {
  621. $oP->add_comment("Data Lines: ".$iLineCount);
  622. $oP->add_comment("Simulate: ".($bSimulate ? '1' : '0'));
  623. $oP->add_comment("Columns: ".implode(', ', $aFieldList));
  624. $aReconciliationReport = array();
  625. foreach($aReconcilKeysReport as $sKey => $aKeyDetails)
  626. {
  627. if (count($aKeyDetails) > 0)
  628. {
  629. $aReconciliationReport[] = $sKey.' ('.implode(',', $aKeyDetails).')';
  630. }
  631. else
  632. {
  633. $aReconciliationReport[] = $sKey;
  634. }
  635. }
  636. $oP->add_comment("Reconciliation Keys: ".implode(', ', $aReconciliationReport));
  637. foreach ($aWarnings as $sWarning)
  638. {
  639. $oP->add_comment("Warning: ".$sWarning);
  640. }
  641. }
  642. $oBulk = new BulkChange(
  643. $sClass,
  644. $aData,
  645. $aAttList,
  646. $aExtKeys,
  647. $aFinalReconcilKeys,
  648. null, // synchro scope
  649. null, // on delete
  650. $sDateFormat,
  651. $bLocalize
  652. );
  653. if ($bSimulate)
  654. {
  655. $oMyChange = null;
  656. }
  657. else
  658. {
  659. if (strlen($sComment) > 0)
  660. {
  661. $sMoreInfo = CMDBChange::GetCurrentUserName().', Web Service (CSV) - '.$sComment;
  662. }
  663. else
  664. {
  665. $sMoreInfo = CMDBChange::GetCurrentUserName().', Web Service (CSV)';
  666. }
  667. CMDBObject::SetTrackInfo($sMoreInfo);
  668. $oMyChange = CMDBObject::GetCurrentChange();
  669. }
  670. $aRes = $oBulk->Process($oMyChange);
  671. //////////////////////////////////////////////////
  672. //
  673. // Compute statistics
  674. //
  675. $iCountErrors = 0;
  676. $iCountWarnings = 0;
  677. $iCountCreations = 0;
  678. $iCountUpdates = 0;
  679. $iCountUnchanged = 0;
  680. foreach($aRes as $iRow => $aRowData)
  681. {
  682. $bWritten = false;
  683. $oStatus = $aRowData["__STATUS__"];
  684. switch(get_class($oStatus))
  685. {
  686. case 'RowStatus_NoChange':
  687. $iCountUnchanged++;
  688. break;
  689. case 'RowStatus_Modify':
  690. $iCountUpdates++;
  691. $bWritten = true;
  692. break;
  693. case 'RowStatus_NewObj':
  694. $iCountCreations++;
  695. $bWritten = true;
  696. break;
  697. case 'RowStatus_Issue':
  698. $iCountErrors++;
  699. break;
  700. }
  701. if ($bWritten)
  702. {
  703. // Something has been done, still there may be some issues to report
  704. foreach($aRowData as $key => $value)
  705. {
  706. if (!is_object($value)) continue;
  707. switch (get_class($value))
  708. {
  709. case 'CellStatus_Void':
  710. case 'CellStatus_Modify':
  711. break;
  712. case 'CellStatus_Issue':
  713. case 'CellStatus_SearchIssue':
  714. case 'CellStatus_NullIssue':
  715. case 'CellStatus_Ambiguous':
  716. $iCountWarnings++;
  717. break;
  718. }
  719. }
  720. }
  721. }
  722. //////////////////////////////////////////////////
  723. //
  724. // Summary of settings and results
  725. //
  726. if ($sOutput == 'retcode')
  727. {
  728. $oP->add($iCountErrors);
  729. }
  730. if (($sOutput == "summary") || ($sOutput == 'details'))
  731. {
  732. $oP->add_comment("Change tracking comment: ".$sComment);
  733. $oP->add_comment("Issues: ".$iCountErrors);
  734. $oP->add_comment("Warnings: ".$iCountWarnings);
  735. $oP->add_comment("Created: ".$iCountCreations);
  736. $oP->add_comment("Updated: ".$iCountUpdates);
  737. $oP->add_comment("Unchanged: ".$iCountUnchanged);
  738. }
  739. if ($sOutput == 'details')
  740. {
  741. // Setup result presentation
  742. //
  743. $aDisplayConfig = array();
  744. $aDisplayConfig["__LINE__"] = array("label"=>"Line", "description"=>"");
  745. $aDisplayConfig["__STATUS__"] = array("label"=>"Status", "description"=>"");
  746. $aDisplayConfig["__OBJECT_CLASS__"] = array("label"=>"Object Class", "description"=>"");
  747. $aDisplayConfig["__OBJECT_ID__"] = array("label"=>"Object Id", "description"=>"");
  748. foreach($aExtKeys as $sExtKeyAttCode => $aRemoteAtt)
  749. {
  750. $sLabel = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode)->GetLabel();
  751. $aDisplayConfig["$sExtKeyAttCode"] = array("label"=>$sExtKeyAttCode, "description"=>$sLabel." - ext key");
  752. }
  753. foreach($aFinalReconcilKeys as $iCol => $sAttCode)
  754. {
  755. // $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  756. // $aDisplayConfig["$iCol"] = array("label"=>"$sLabel", "description"=>"");
  757. }
  758. foreach ($aAttList as $sAttCode => $iCol)
  759. {
  760. if ($sAttCode == 'id')
  761. {
  762. $sLabel = Dict::S('UI:CSVImport:idField');
  763. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  764. }
  765. else
  766. {
  767. $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  768. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  769. }
  770. }
  771. $aResultDisp = array(); // to be displayed
  772. foreach($aRes as $iRow => $aRowData)
  773. {
  774. $aRowDisp = array();
  775. $aRowDisp["__LINE__"] = $iRow;
  776. if (is_object($aRowData["__STATUS__"]))
  777. {
  778. $aRowDisp["__STATUS__"] = $aRowData["__STATUS__"]->GetDescription();
  779. }
  780. else
  781. {
  782. $aRowDisp["__STATUS__"] = "*No status available*";
  783. }
  784. if (isset($aRowData["finalclass"]) && isset($aRowData["id"]))
  785. {
  786. $aRowDisp["__OBJECT_CLASS__"] = $aRowData["finalclass"];
  787. $aRowDisp["__OBJECT_ID__"] = $aRowData["id"]->GetDisplayableValue();
  788. }
  789. else
  790. {
  791. $aRowDisp["__OBJECT_CLASS__"] = "n/a";
  792. $aRowDisp["__OBJECT_ID__"] = "n/a";
  793. }
  794. foreach($aRowData as $key => $value)
  795. {
  796. $sKey = (string) $key;
  797. if ($sKey == '__STATUS__') continue;
  798. if ($sKey == 'finalclass') continue;
  799. if ($sKey == 'id') continue;
  800. if (is_object($value))
  801. {
  802. $aRowDisp["$sKey"] = $value->GetDisplayableValue().$value->GetDescription();
  803. }
  804. else
  805. {
  806. $aRowDisp["$sKey"] = $value;
  807. }
  808. }
  809. $aResultDisp[$iRow] = $aRowDisp;
  810. }
  811. $oP->table($aDisplayConfig, $aResultDisp);
  812. }
  813. }
  814. catch(BulkLoadException $e)
  815. {
  816. $oP->add_comment($e->getMessage());
  817. }
  818. catch(SecurityException $e)
  819. {
  820. $oP->add_comment($e->getMessage());
  821. }
  822. catch(Exception $e)
  823. {
  824. $oP->add_comment((string)$e);
  825. }
  826. $oP->output();
  827. ?>