synchro_import.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. // Copyright (C) 2011 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. * Data Exchange 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 column primary_key
  27. //
  28. require_once('../approot.inc.php');
  29. require_once(APPROOT.'/application/application.inc.php');
  30. require_once(APPROOT.'/application/webpage.class.inc.php');
  31. require_once(APPROOT.'/application/csvpage.class.inc.php');
  32. require_once(APPROOT.'/application/clipage.class.inc.php');
  33. require_once(APPROOT.'/application/startup.inc.php');
  34. class ExchangeException extends Exception
  35. {
  36. }
  37. $aPageParams = array
  38. (
  39. 'auth_user' => array
  40. (
  41. 'mandatory' => true,
  42. 'modes' => 'cli',
  43. 'default' => null,
  44. 'description' => 'login (must have enough rights to create objects of the given class)',
  45. ),
  46. 'auth_pwd' => array
  47. (
  48. 'mandatory' => true,
  49. 'modes' => 'cli',
  50. 'default' => null,
  51. 'description' => 'password',
  52. ),
  53. 'data_source_id' => array
  54. (
  55. 'mandatory' => true,
  56. 'modes' => 'http,cli',
  57. 'default' => null,
  58. 'description' => 'Synchro data source id',
  59. ),
  60. 'csvdata' => array
  61. (
  62. 'mandatory' => true,
  63. 'modes' => 'http',
  64. 'default' => null,
  65. 'description' => 'data',
  66. ),
  67. 'csvfile' => array
  68. (
  69. 'mandatory' => true,
  70. 'modes' => 'cli',
  71. 'default' => '',
  72. 'description' => 'local data file, replaces csvdata if specified',
  73. ),
  74. 'synchronize' => array
  75. (
  76. 'mandatory' => false,
  77. 'modes' => 'http,cli',
  78. 'default' => '1',
  79. 'description' => 'If set to 1, then the synchronization will be executed right after the data load',
  80. ),
  81. 'charset' => array
  82. (
  83. 'mandatory' => false,
  84. 'modes' => 'http,cli',
  85. 'default' => 'UTF-8',
  86. 'description' => 'Character set encoding of the CSV data: UTF-8, ISO-8859-1, WINDOWS-1251, WINDOWS-1252, ISO-8859-15',
  87. ),
  88. 'separator' => array
  89. (
  90. 'mandatory' => false,
  91. 'modes' => 'http,cli',
  92. 'default' => ';',
  93. 'description' => 'column separator in CSV data',
  94. ),
  95. 'qualifier' => array
  96. (
  97. 'mandatory' => false,
  98. 'modes' => 'http,cli',
  99. 'default' => '"',
  100. 'description' => 'test qualifier in CSV data',
  101. ),
  102. 'output' => array
  103. (
  104. 'mandatory' => false,
  105. 'modes' => 'http,cli',
  106. 'default' => 'summary',
  107. '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)',
  108. ),
  109. /*
  110. 'reportlevel' => array
  111. (
  112. 'mandatory' => false,
  113. 'modes' => 'http,cli',
  114. 'default' => 'errors|warnings|created|changed|unchanged',
  115. 'description' => 'combination of flags to limit the detailed output',
  116. ),
  117. */
  118. 'simulate' => array
  119. (
  120. 'mandatory' => false,
  121. 'modes' => 'http,cli',
  122. 'default' => '0',
  123. 'description' => 'If set to 1, then the load will not be executed, but the expected report will be produced',
  124. ),
  125. 'comment' => array
  126. (
  127. 'mandatory' => false,
  128. 'modes' => 'http,cli',
  129. 'default' => '',
  130. 'description' => 'Comment to be added into the change log',
  131. ),
  132. );
  133. function UsageAndExit($oP)
  134. {
  135. global $aPageParams;
  136. $bModeCLI = utils::IsModeCLI();
  137. $oP->p("USAGE:\n");
  138. foreach($aPageParams as $sParam => $aParamData)
  139. {
  140. $aModes = explode(',', $aParamData['modes']);
  141. if ($bModeCLI)
  142. {
  143. if (in_array('cli', $aModes))
  144. {
  145. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  146. $oP->p("$sParam = $sDesc");
  147. }
  148. }
  149. else
  150. {
  151. if (in_array('http', $aModes))
  152. {
  153. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  154. $oP->p("$sParam = $sDesc");
  155. }
  156. }
  157. }
  158. $oP->output();
  159. exit;
  160. }
  161. function ReadParam($oP, $sParam)
  162. {
  163. global $aPageParams;
  164. assert(isset($aPageParams[$sParam]));
  165. assert(!$aPageParams[$sParam]['mandatory']);
  166. $sValue = utils::ReadParam($sParam, $aPageParams[$sParam]['default'], true /* Allow CLI */);
  167. return trim($sValue);
  168. }
  169. function ReadMandatoryParam($oP, $sParam)
  170. {
  171. global $aPageParams;
  172. assert(isset($aPageParams[$sParam]));
  173. assert($aPageParams[$sParam]['mandatory']);
  174. $sValue = utils::ReadParam($sParam, null, true /* Allow CLI */);
  175. if (is_null($sValue))
  176. {
  177. $oP->p("ERROR: Missing argument '$sParam'\n");
  178. UsageAndExit($oP);
  179. }
  180. return trim($sValue);
  181. }
  182. /////////////////////////////////
  183. // Main program
  184. if (utils::IsModeCLI())
  185. {
  186. $oP = new CLIPage("iTop - Data Exchange");
  187. // Next steps:
  188. // specific arguments: 'csvfile'
  189. //
  190. $sAuthUser = ReadMandatoryParam($oP, 'auth_user');
  191. $sAuthPwd = ReadMandatoryParam($oP, 'auth_pwd');
  192. $sCsvFile = ReadMandatoryParam($oP, 'csvfile');
  193. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  194. {
  195. UserRights::Login($sAuthUser); // Login & set the user's language
  196. }
  197. else
  198. {
  199. $oP->p("Access restricted or wrong credentials ('$sAuthUser')");
  200. exit;
  201. }
  202. if (!is_readable($sCsvFile))
  203. {
  204. $oP->p("Input file could not be found or could not be read: '$sCsvFile'");
  205. exit;
  206. }
  207. $sCSVData = file_get_contents($sCsvFile);
  208. }
  209. else
  210. {
  211. $_SESSION['login_mode'] = 'basic';
  212. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  213. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  214. $oP = new CSVPage("iTop - Data Exchange");
  215. $sCSVData = utils::ReadPostedParam('csvdata');
  216. }
  217. try
  218. {
  219. //////////////////////////////////////////////////
  220. //
  221. // Read parameters
  222. //
  223. $iDataSourceId = ReadMandatoryParam($oP, 'data_source_id');
  224. $sSynchronize = ReadParam($oP, 'synchronize');
  225. $sSep = ReadParam($oP, 'separator');
  226. $sQualifier = ReadParam($oP, 'qualifier');
  227. $sCharSet = ReadParam($oP, 'charset');
  228. $sOutput = ReadParam($oP, 'output');
  229. // $sReportLevel = ReadParam($oP, 'reportlevel');
  230. $sSimulate = ReadParam($oP, 'simulate');
  231. $sComment = ReadParam($oP, 'comment');
  232. $oLoadStartDate = new DateTime(); // Now
  233. //////////////////////////////////////////////////
  234. //
  235. // Statistics
  236. //
  237. $iCountErrors = 0;
  238. $iCountCreations = 0;
  239. $iCountUpdates = 0;
  240. //////////////////////////////////////////////////
  241. //
  242. // Check parameters format/consistency
  243. //
  244. if (strlen($sCSVData) == 0)
  245. {
  246. throw new ExchangeException("Missing data - at least one line is expected");
  247. }
  248. $oDataSource = MetaModel::GetObject('SynchroDataSource', $iDataSourceId, false);
  249. if (is_null($oDataSource))
  250. {
  251. throw new ExchangeException("Unknown data source id: '$iDataSourceId'");
  252. }
  253. $sClass = $oDataSource->GetTargetClass();
  254. if (strlen($sSep) > 1)
  255. {
  256. throw new ExchangeException("Separator is limited to one character, found '$sSep'");
  257. }
  258. if (strlen($sQualifier) > 1)
  259. {
  260. throw new ExchangeException("Text qualifier is limited to one character, found '$sQualifier'");
  261. }
  262. if (!in_array($sOutput, array('retcode', 'summary', 'details')))
  263. {
  264. throw new ExchangeException("Unknown output format: '$sOutput'");
  265. }
  266. /*
  267. $aReportLevels = explode('|', $sReportLevel);
  268. foreach($aReportLevels as $sLevel)
  269. {
  270. if (!in_array($sLevel, explode('|', 'errors|warnings|created|changed|unchanged')))
  271. {
  272. throw new ExchangeException("Unknown level in reporting level: '$sLevel'");
  273. }
  274. }
  275. */
  276. if ($sSimulate == '1')
  277. {
  278. $bSimulate = true;
  279. }
  280. else
  281. {
  282. $bSimulate = false;
  283. }
  284. if ($sSynchronize == '1')
  285. {
  286. $bSynchronize = true;
  287. }
  288. else
  289. {
  290. $bSynchronize = false;
  291. }
  292. //////////////////////////////////////////////////
  293. //
  294. // Security
  295. //
  296. // #@# todo - implement
  297. /*
  298. if (!$oDataSource->IsUserAllowed(UserRights::GetUserId())
  299. {
  300. throw new SecurityException(Dict::Format('UI:Error:DataExchangeNotAllowed', UserRights::GetUserFriendlyName()));
  301. }
  302. */
  303. //////////////////////////////////////////////////
  304. //
  305. // Parse first line, check attributes, analyse the request
  306. //
  307. if ($sCharSet == 'UTF-8')
  308. {
  309. $sUTF8Data = $sCSVData;
  310. }
  311. else
  312. {
  313. $sUTF8Data = iconv($sCharSet, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  314. }
  315. $oCSVParser = new CSVParser($sUTF8Data, $sSep, $sQualifier);
  316. $aInputColumns = $oCSVParser->ListFields();
  317. $iColCount = count($aInputColumns);
  318. // Check columns
  319. $aColumns = $oDataSource->GetSQLColumns();
  320. foreach($aInputColumns as $iFieldId => $sInputColumn)
  321. {
  322. if ($sInputColumn == 'primary_key')
  323. {
  324. $iPrimaryKeyCol = $iFieldId;
  325. continue;
  326. }
  327. if (!array_key_exists($sInputColumn, $aColumns))
  328. {
  329. throw new ExchangeException("Unknown column '$sInputColumn' (class: '$sClass')");
  330. }
  331. }
  332. if (!isset($iPrimaryKeyCol))
  333. {
  334. throw new ExchangeException("Missing reconciliation column 'primary_key'");
  335. }
  336. //////////////////////////////////////////////////
  337. //
  338. // Go for parsing and interpretation
  339. //
  340. $aData = $oCSVParser->ToArray();
  341. $iLineCount = count($aData);
  342. $sTable = $oDataSource->GetDataTable();
  343. // Prepare insert columns
  344. $sInsertColumns = '`'.implode('`, `', $aInputColumns).'`';
  345. foreach($aData as $iRow => $aRow)
  346. {
  347. $sReconciliationCondition = "`primary_key` = ".CMDBSource::Quote($aRow[$iPrimaryKeyCol]);
  348. $sSelect = "SELECT COUNT(*) FROM `$sTable` WHERE $sReconciliationCondition";
  349. $aRes = CMDBSource::QueryToArray($sSelect);
  350. $iCount = $aRes[0]['COUNT(*)'];
  351. if ($iCount == 0)
  352. {
  353. // No record... create it
  354. //
  355. $iCountCreations++;
  356. if ($sOutput == 'details')
  357. {
  358. $oP->add("$iRow: New entry, reconciliation: '$sReconciliationCondition'\n");
  359. }
  360. $aValues = array(); // Used to build the insert query
  361. foreach ($aRow as $iCol => $value)
  362. {
  363. $aValues[] = CMDBSource::Quote($value);
  364. }
  365. $sValues = implode(', ', $aValues);
  366. $sInsert = "INSERT INTO `$sTable` ($sInsertColumns) VALUES ($sValues)";
  367. if ($bSimulate)
  368. {
  369. if ($sOutput == 'details')
  370. {
  371. $oP->add("$iRow: SIMULATE - Planned query: $sInsert'\n");
  372. }
  373. }
  374. else
  375. {
  376. CMDBSource::Query($sInsert);
  377. }
  378. }
  379. elseif ($iCount == 1)
  380. {
  381. // Found a match... update it
  382. //
  383. $iCountUpdates++;
  384. if ($sOutput == 'details')
  385. {
  386. $oP->add("$iRow: Update entry, reconciliation: '$sReconciliationCondition'\n");
  387. }
  388. $aValuePairs = array(); // Used to build the update query
  389. foreach ($aRow as $iCol => $value)
  390. {
  391. // Skip reconciliation column
  392. if ($iCol == $iPrimaryKeyCol) continue;
  393. $sCol = $aInputColumns[$iCol];
  394. $aValuePairs[] = "`$sCol` = ".CMDBSource::Quote($aRow[$iCol]);
  395. }
  396. $sValuePairs = implode(', ', $aValuePairs);
  397. $sUpdateQuery = "UPDATE `$sTable` SET $sValuePairs WHERE $sReconciliationCondition";
  398. if ($bSimulate)
  399. {
  400. if ($sOutput == 'details')
  401. {
  402. $oP->add("$iRow: SIMULATE - Planned query: $sUpdateQuery'\n");
  403. }
  404. }
  405. else
  406. {
  407. CMDBSource::Query($sUpdateQuery);
  408. }
  409. }
  410. else
  411. {
  412. // Too many records... ambiguity
  413. //
  414. $iCountErrors++;
  415. $oP->add("$iRow: Error - Failed to reconcile, found $iCount rows having '$sReconciliationCondition'\n");
  416. }
  417. }
  418. //////////////////////////////////////////////////
  419. //
  420. // Synchronize
  421. //
  422. if ($bSynchronize && !$bSimulate)
  423. {
  424. $aDataToReplica = array();
  425. $oDataSource->Synchronize($aDataToReplica, $oLoadStartDate);
  426. //echo "#@# Synchronize() returned :<br/>\n";
  427. //echo "<pre>\n";
  428. //print_r($aDataToReplica);
  429. //echo "</pre>\n";
  430. }
  431. //////////////////////////////////////////////////
  432. //
  433. // Summary of settings and results
  434. //
  435. if ($sOutput == 'retcode')
  436. {
  437. $oP->add($iCountErrors);
  438. }
  439. if (($sOutput == "summary") || ($sOutput == 'details'))
  440. {
  441. $oP->add_comment("Data Source: ".$iDataSourceId);
  442. $oP->add_comment("Synchronize: ".($bSynchronize ? '1' : '0'));
  443. $oP->add_comment("Class: ".$sClass);
  444. $oP->add_comment("Separator: ".$sSep);
  445. $oP->add_comment("Qualifier: ".$sQualifier);
  446. $oP->add_comment("Charset Encoding:".$sCharSet);
  447. $oP->add_comment("Data Size: ".strlen($sCSVData));
  448. $oP->add_comment("Data Lines: ".$iLineCount);
  449. $oP->add_comment("Columns: ".implode(', ', $aInputColumns));
  450. $oP->add_comment("Output format: ".$sOutput);
  451. // $oP->add_comment("Report level: ".$sReportLevel);
  452. $oP->add_comment("Simulate: ".($bSimulate ? '1' : '0'));
  453. $oP->add_comment("Change tracking comment: ".$sComment);
  454. $oP->add_comment("Issues: ".$iCountErrors);
  455. // $oP->add_comment("Warnings: ".$iCountWarnings);
  456. $oP->add_comment("Created: ".$iCountCreations);
  457. $oP->add_comment("Updated: ".$iCountUpdates);
  458. }
  459. }
  460. catch(ExchangeException $e)
  461. {
  462. $oP->add_comment($e->getMessage());
  463. }
  464. catch(SecurityException $e)
  465. {
  466. $oP->add_comment($e->getMessage());
  467. }
  468. catch(Exception $e)
  469. {
  470. $oP->add_comment((string)$e);
  471. }
  472. $oP->output();
  473. ?>