import.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Import web service
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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. require_once('../application/application.inc.php');
  34. require_once('../application/webpage.class.inc.php');
  35. require_once('../application/csvpage.class.inc.php');
  36. require_once('../application/xmlpage.class.inc.php');
  37. require_once('../application/startup.inc.php');
  38. class BulkLoadException extends Exception
  39. {
  40. }
  41. $aPageParams = array
  42. (
  43. 'class' => array
  44. (
  45. 'mandatory' => true,
  46. 'default' => null,
  47. 'description' => 'class of loaded objects',
  48. ),
  49. 'csvdata' => array
  50. (
  51. 'mandatory' => true,
  52. 'default' => null,
  53. 'description' => 'data',
  54. ),
  55. 'charset' => array
  56. (
  57. 'mandatory' => false,
  58. 'default' => 'UTF-8',
  59. 'description' => 'Character set encoding of the CSV data: UTF-8, ISO-8859-1, WINDOWS-1251, WINDOWS-1252, ISO-8859-15',
  60. ),
  61. // 'csvfile' => array
  62. // (
  63. // 'mandatory' => false,
  64. // 'default' => '',
  65. // 'description' => 'local data file, replaces csvdata if specified',
  66. // ),
  67. 'separator' => array
  68. (
  69. 'mandatory' => false,
  70. 'default' => ';',
  71. 'description' => 'column separator in CSV data',
  72. ),
  73. 'qualifier' => array
  74. (
  75. 'mandatory' => false,
  76. 'default' => '"',
  77. 'description' => 'test qualifier in CSV data',
  78. ),
  79. 'output' => array
  80. (
  81. 'mandatory' => false,
  82. 'default' => 'summary',
  83. '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)',
  84. ),
  85. /*
  86. 'reportlevel' => array
  87. (
  88. 'mandatory' => false,
  89. 'default' => 'errors|warnings|created|changed|unchanged',
  90. 'description' => 'combination of flags to limit the detailed output',
  91. ),
  92. */
  93. 'reconciliationkeys' => array
  94. (
  95. 'mandatory' => false,
  96. 'default' => '',
  97. 'description' => 'name of the columns used to identify existing objects and update them, or create a new one',
  98. ),
  99. 'simulate' => array
  100. (
  101. 'mandatory' => false,
  102. 'default' => '0',
  103. 'description' => 'If set to 1, then the load will not be executed, but the expected report will be produced',
  104. ),
  105. 'comment' => array
  106. (
  107. 'mandatory' => false,
  108. 'default' => '',
  109. 'description' => 'Comment to be added into the change log',
  110. ),
  111. );
  112. function UsageAndExit($oP)
  113. {
  114. global $aPageParams;
  115. $oP->p("USAGE:\n");
  116. foreach($aPageParams as $sParam => $aParamData)
  117. {
  118. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  119. $oP->p("$sParam = $sDesc\n");
  120. }
  121. $oP->output();
  122. exit;
  123. }
  124. function ReadParam($oP, $sParam)
  125. {
  126. global $aPageParams;
  127. assert(isset($aPageParams[$sParam]));
  128. assert(!$aPageParams[$sParam]['mandatory']);
  129. $sValue = utils::ReadParam($sParam, $aPageParams[$sParam]['default'], true /* Allow CLI */);
  130. return trim($sValue);
  131. }
  132. function ReadMandatoryParam($oP, $sParam)
  133. {
  134. global $aPageParams;
  135. assert(isset($aPageParams[$sParam]));
  136. assert($aPageParams[$sParam]['mandatory']);
  137. $sValue = utils::ReadParam($sParam, null, true /* Allow CLI */);
  138. if (is_null($sValue))
  139. {
  140. $oP->p("ERROR: Missing argument '$sParam'\n");
  141. UsageAndExit($oP);
  142. }
  143. return trim($sValue);
  144. }
  145. /////////////////////////////////
  146. // Main program
  147. if (false && utils::IsModeCLI())
  148. {
  149. // Mode CLI under construction... sorry!
  150. // Next steps:
  151. // implement a new page: CLIPage, that does a very clean output
  152. // branch if in CLI mode
  153. // enable the new argument 'csvfile'
  154. $sAuthUser = ReadMandatoryParam($oP, 'auth_user');
  155. $sAuthPwd = ReadMandatoryParam($oP, 'auth_user');
  156. $sCsvFile = ReadMandatoryParam($oP, 'csv_file');
  157. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  158. {
  159. UserRights::Login($sAuthUser); // Login & set the user's language
  160. }
  161. else
  162. {
  163. $oP->p("Access restricted or wrong credentials ('$sAuthUser')");
  164. exit;
  165. }
  166. }
  167. else
  168. {
  169. require_once('../application/loginwebpage.class.inc.php');
  170. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  171. $oP = new CSVPage("iTop - Bulk import");
  172. }
  173. try
  174. {
  175. //////////////////////////////////////////////////
  176. //
  177. // Read parameters
  178. //
  179. $sClass = ReadMandatoryParam($oP, 'class');
  180. $sSep = ReadParam($oP, 'separator');
  181. $sQualifier = ReadParam($oP, 'qualifier');
  182. $sCSVData = utils::ReadPostedParam('csvdata');
  183. $sCharSet = ReadParam($oP, 'charset');
  184. $sOutput = ReadParam($oP, 'output');
  185. // $sReportLevel = ReadParam($oP, 'reportlevel');
  186. $sReconcKeys = ReadParam($oP, 'reconciliationkeys');
  187. $sSimulate = ReadParam($oP, 'simulate');
  188. $sComment = ReadParam($oP, 'comment');
  189. //////////////////////////////////////////////////
  190. //
  191. // Check parameters format/consistency
  192. //
  193. if (!MetaModel::IsValidClass($sClass))
  194. {
  195. throw new BulkLoadException("Unknown class: '$sClass'");
  196. }
  197. if (strlen($sSep) > 1)
  198. {
  199. throw new BulkLoadException("Separator is limited to one character, found '$sSep'");
  200. }
  201. if (strlen($sQualifier) > 1)
  202. {
  203. throw new BulkLoadException("Text qualifier is limited to one character, found '$sQualifier'");
  204. }
  205. if (!in_array($sOutput, array('retcode', 'summary', 'details')))
  206. {
  207. throw new BulkLoadException("Unknown output format: '$sOutput'");
  208. }
  209. /*
  210. $aReportLevels = explode('|', $sReportLevel);
  211. foreach($aReportLevels as $sLevel)
  212. {
  213. if (!in_array($sLevel, explode('|', 'errors|warnings|created|changed|unchanged')))
  214. {
  215. throw new BulkLoadException("Unknown level in reporting level: '$sLevel'");
  216. }
  217. }
  218. */
  219. if ($sSimulate == '1')
  220. {
  221. $bSimulate = true;
  222. }
  223. else
  224. {
  225. $bSimulate = false;
  226. }
  227. //////////////////////////////////////////////////
  228. //
  229. // Parse first line, check attributes, analyse the request
  230. //
  231. if ($sCharSet == 'UTF-8')
  232. {
  233. $sUTF8Data = $sCSVData;
  234. }
  235. else
  236. {
  237. $sUTF8Data = iconv($sCharSet, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  238. }
  239. $oCSVParser = new CSVParser($sUTF8Data, $sSep, $sQualifier);
  240. // Limitation: as the attribute list is in the first line, we can not match external key by a third-party attribute
  241. $aRawFieldList = $oCSVParser->ListFields();
  242. $iColCount = count($aRawFieldList);
  243. $aAttList = array();
  244. $aExtKeys = array();
  245. foreach($aRawFieldList as $iFieldId => $sFieldName)
  246. {
  247. if (preg_match('/^(.*)->(.*)$/', trim($sFieldName), $aMatches))
  248. {
  249. // The column has been specified as "extkey->attcode"
  250. //
  251. $sExtKeyAttCode = $aMatches[1];
  252. $sRemoteAttCode = $aMatches[2];
  253. if (!MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  254. {
  255. throw new BulkLoadException("Unknown attribute '$sExtKeyAttCode' (class: '$sClass')");
  256. }
  257. $oAtt = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  258. if (!$oAtt->IsExternalKey())
  259. {
  260. throw new BulkLoadException("Not an external key '$sExtKeyAttCode' (class: '$sClass')");
  261. }
  262. $sTargetClass = $oAtt->GetTargetClass();
  263. if (!MetaModel::IsValidAttCode($sTargetClass, $sRemoteAttCode))
  264. {
  265. throw new BulkLoadException("Unknown attribute '$sRemoteAttCode' (key: '$sExtKeyAttCode', class: '$sTargetClass')");
  266. }
  267. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  268. }
  269. else
  270. {
  271. // The column has been specified as "attcode"
  272. //
  273. if (!MetaModel::IsValidAttCode($sClass, $sFieldName))
  274. {
  275. throw new BulkLoadException("Unknown attribute '$sFieldName' (class: '$sClass')");
  276. }
  277. $oAtt = MetaModel::GetAttributeDef($sClass, $sFieldName);
  278. if ($oAtt->IsExternalKey())
  279. {
  280. $aExtKeys[$sFieldName]['id'] = $iFieldId;
  281. $aAttList[$sFieldName] = $iFieldId;
  282. }
  283. elseif ($oAtt->IsExternalField())
  284. {
  285. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  286. $sRemoteAttCode = $oAtt->GetExtAttCode();
  287. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  288. }
  289. else
  290. {
  291. $aAttList[$sFieldName] = $iFieldId;
  292. }
  293. }
  294. }
  295. // Make sure there are some reconciliation keys
  296. //
  297. if (empty($sReconcKeys))
  298. {
  299. $aReconcSpec = array();
  300. // Base reconciliation scheme on the default one
  301. // The reconciliation attributes not present in the data will be ignored
  302. foreach(MetaModel::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  303. {
  304. if (in_array($sReconcKeyAttCode, $aRawFieldList))
  305. {
  306. $aReconcSpec[] = $sReconcKeyAttCode;
  307. }
  308. }
  309. if (count($aReconcSpec) == 0)
  310. {
  311. 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)).")");
  312. }
  313. $sReconcKeys = implode(',', $aReconcSpec);
  314. }
  315. if (false)
  316. {
  317. echo "Reconciliation keys<pre class=\"vardump\">";
  318. print_r($sReconcKeys);
  319. throw new BulkLoadException("testing");
  320. }
  321. // Interpret the list of reconciliation keys
  322. //
  323. $aFinalReconcilKeys = array();
  324. $aReconcilKeysReport = array();
  325. foreach (explode(',', $sReconcKeys) as $sReconcKey)
  326. {
  327. $sReconcKey = trim($sReconcKey);
  328. if (empty($sReconcKey)) continue; // skip empty spec
  329. if (!in_array($sReconcKey, $aRawFieldList))
  330. {
  331. throw new BulkLoadException("Reconciliation keys not found in the input columns '$sReconcKey' (class: '$sClass')");
  332. }
  333. if (preg_match('/^(.*)->(.*)$/', trim($sReconcKey), $aMatches))
  334. {
  335. // The column has been specified as "extkey->attcode"
  336. //
  337. $sExtKeyAttCode = $aMatches[1];
  338. $sRemoteAttCode = $aMatches[2];
  339. $aFinalReconcilKeys[] = $sExtKeyAttCode;
  340. $aReconcilKeysReport[$sExtKeyAttCode][] = $sRemoteAttCode;
  341. }
  342. else
  343. {
  344. if (!MetaModel::IsValidAttCode($sClass, $sReconcKey))
  345. {
  346. // Safety net: should never happen, but...
  347. throw new BulkLoadException("Unknown reconciliation attribute '$sReconcKey' (class: '$sClass')");
  348. }
  349. $oAtt = MetaModel::GetAttributeDef($sClass, $sReconcKey);
  350. if ($oAtt->IsExternalKey())
  351. {
  352. $aFinalReconcilKeys[] = $sReconcKey;
  353. $aReconcilKeysReport[$sReconcKey][] = 'id';
  354. }
  355. elseif ($oAtt->IsExternalField())
  356. {
  357. $sReconcAttCode = $oAtt->GetKeyAttCode();
  358. $sReconcKeyReport = "$sReconcAttCode ($sReconcKey)";
  359. $aFinalReconcilKeys[] = $sReconcAttCode;
  360. $aReconcilKeysReport[$sReconcAttCode][] = $sReconcKeyReport;
  361. }
  362. else
  363. {
  364. $aFinalReconcilKeys[] = $sReconcKey;
  365. $aReconcilKeysReport[$sReconcKey] = array();
  366. }
  367. }
  368. }
  369. //////////////////////////////////////////////////
  370. //
  371. // Go for parsing and interpretation
  372. //
  373. $aData = $oCSVParser->ToArray();
  374. $iLineCount = count($aData);
  375. $oBulk = new BulkChange(
  376. $sClass,
  377. $aData,
  378. $aAttList,
  379. $aExtKeys,
  380. $aFinalReconcilKeys
  381. );
  382. if ($bSimulate)
  383. {
  384. $oMyChange = null;
  385. }
  386. else
  387. {
  388. $oMyChange = MetaModel::NewObject("CMDBChange");
  389. $oMyChange->Set("date", time());
  390. if (UserRights::IsImpersonated())
  391. {
  392. $sUserString = Dict::Format('UI:Archive_User_OnBehalfOf_User', UserRights::GetRealUser(), UserRights::GetUser());
  393. }
  394. else
  395. {
  396. $sUserString = UserRights::GetUser();
  397. }
  398. if (strlen($sComment) > 0)
  399. {
  400. $sMoreInfo = 'Web Service (CSV) - '.$sComment;
  401. }
  402. else
  403. {
  404. $sMoreInfo = 'Web Service (CSV)';
  405. }
  406. $oMyChange->Set("userinfo", $sUserString.' '.$sMoreInfo);
  407. $iChangeId = $oMyChange->DBInsert();
  408. }
  409. $aRes = $oBulk->Process($oMyChange);
  410. //////////////////////////////////////////////////
  411. //
  412. // Compute statistics
  413. //
  414. $iCountErrors = 0;
  415. $iCountWarnings = 0;
  416. $iCountCreations = 0;
  417. $iCountUpdates = 0;
  418. $iCountUnchanged = 0;
  419. foreach($aRes as $iRow => $aRowData)
  420. {
  421. $bWritten = false;
  422. $oStatus = $aRowData["__STATUS__"];
  423. switch(get_class($oStatus))
  424. {
  425. case 'RowStatus_NoChange':
  426. $iCountUnchanged++;
  427. break;
  428. case 'RowStatus_Modify':
  429. $iCountUpdates++;
  430. $bWritten = true;
  431. break;
  432. case 'RowStatus_NewObj':
  433. $iCountCreations++;
  434. $bWritten = true;
  435. break;
  436. case 'RowStatus_Issue':
  437. $iCountErrors++;
  438. break;
  439. }
  440. if ($bWritten)
  441. {
  442. // Something has been done, still there may be some issues to report
  443. foreach($aRowData as $key => $value)
  444. {
  445. if (!is_object($value)) continue;
  446. switch (get_class($value))
  447. {
  448. case 'CellStatus_Void':
  449. case 'CellStatus_Modify':
  450. break;
  451. case 'CellStatus_Issue':
  452. case 'CellStatus_Ambiguous':
  453. $iCountWarnings++;
  454. break;
  455. }
  456. }
  457. }
  458. }
  459. //////////////////////////////////////////////////
  460. //
  461. // Summary of settings and results
  462. //
  463. if ($sOutput == 'retcode')
  464. {
  465. $oP->add($iCountErrors);
  466. }
  467. if (($sOutput == "summary") || ($sOutput == 'details'))
  468. {
  469. $aReconciliationReport = array();
  470. foreach($aReconcilKeysReport as $sKey => $aKeyDetails)
  471. {
  472. if (count($aKeyDetails) > 0)
  473. {
  474. $aReconciliationReport[] = $sKey.' ('.implode(',', $aKeyDetails).')';
  475. }
  476. else
  477. {
  478. $aReconciliationReport[] = $sKey;
  479. }
  480. }
  481. $oP->add_comment("Class: ".$sClass);
  482. $oP->add_comment("Separator: ".$sSep);
  483. $oP->add_comment("Qualifier: ".$sQualifier);
  484. $oP->add_comment("Charset Encoding:".$sCharSet);
  485. $oP->add_comment("Data Size: ".strlen($sCSVData));
  486. $oP->add_comment("Data Lines: ".$iLineCount);
  487. $oP->add_comment("Columns: ".implode(', ', $aRawFieldList));
  488. $oP->add_comment("Reconciliation Keys: ".implode(', ', $aReconciliationReport));
  489. $oP->add_comment("Output format: ".$sOutput);
  490. // $oP->add_comment("Report level: ".$sReportLevel);
  491. $oP->add_comment("Simulate: ".($bSimulate ? '1' : '0'));
  492. $oP->add_comment("Change tracking comment: ".$sComment);
  493. $oP->add_comment("Issues: ".$iCountErrors);
  494. $oP->add_comment("Warnings: ".$iCountWarnings);
  495. $oP->add_comment("Created: ".$iCountCreations);
  496. $oP->add_comment("Updated: ".$iCountUpdates);
  497. $oP->add_comment("Unchanged: ".$iCountUnchanged);
  498. }
  499. if ($sOutput == 'details')
  500. {
  501. // Setup result presentation
  502. //
  503. $aDisplayConfig = array();
  504. $aDisplayConfig["__LINE__"] = array("label"=>"Line", "description"=>"");
  505. $aDisplayConfig["__STATUS__"] = array("label"=>"Status", "description"=>"");
  506. $aDisplayConfig["__OBJECT_CLASS__"] = array("label"=>"Object Class", "description"=>"");
  507. $aDisplayConfig["__OBJECT_ID__"] = array("label"=>"Object Id", "description"=>"");
  508. foreach($aExtKeys as $sExtKeyAttCode => $aRemoteAtt)
  509. {
  510. $sLabel = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode)->GetLabel();
  511. $aDisplayConfig["$sExtKeyAttCode"] = array("label"=>$sExtKeyAttCode, "description"=>$sLabel." - ext key");
  512. }
  513. foreach($aFinalReconcilKeys as $iCol => $sAttCode)
  514. {
  515. // $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  516. // $aDisplayConfig["$iCol"] = array("label"=>"$sLabel", "description"=>"");
  517. }
  518. foreach ($aAttList as $sAttCode => $iCol)
  519. {
  520. $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  521. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  522. }
  523. $aResultDisp = array(); // to be displayed
  524. foreach($aRes as $iRow => $aRowData)
  525. {
  526. $aRowDisp = array();
  527. $aRowDisp["__LINE__"] = $iRow;
  528. if (is_object($aRowData["__STATUS__"]))
  529. {
  530. $aRowDisp["__STATUS__"] = $aRowData["__STATUS__"]->GetDescription();
  531. }
  532. else
  533. {
  534. $aRowDisp["__STATUS__"] = "*No status available*";
  535. }
  536. if (isset($aRowData["finalclass"]) && isset($aRowData["id"]))
  537. {
  538. $aRowDisp["__OBJECT_CLASS__"] = $aRowData["finalclass"];
  539. $aRowDisp["__OBJECT_ID__"] = $aRowData["id"]->GetValue();
  540. }
  541. else
  542. {
  543. $aRowDisp["__OBJECT_CLASS__"] = "n/a";
  544. $aRowDisp["__OBJECT_ID__"] = "n/a";
  545. }
  546. foreach($aRowData as $key => $value)
  547. {
  548. $sKey = (string) $key;
  549. if ($sKey == '__STATUS__') continue;
  550. if ($sKey == 'finalclass') continue;
  551. if ($sKey == 'id') continue;
  552. if (is_object($value))
  553. {
  554. $aRowDisp["$sKey"] = $value->GetValue().$value->GetDescription();
  555. }
  556. else
  557. {
  558. $aRowDisp["$sKey"] = $value;
  559. }
  560. }
  561. $aResultDisp[$iRow] = $aRowDisp;
  562. }
  563. $oP->table($aDisplayConfig, $aResultDisp);
  564. }
  565. }
  566. catch(BulkLoadException $e)
  567. {
  568. $oP->add_comment($e->getMessage());
  569. }
  570. catch(Exception $e)
  571. {
  572. $oP->add_comment((string)$e);
  573. }
  574. $oP->output();
  575. ?>