synchro_import.php 13 KB

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