synchro_import.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. 'date_format' => array
  89. (
  90. 'mandatory' => false,
  91. 'modes' => 'http,cli',
  92. 'default' => '',
  93. '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',
  94. ),
  95. 'separator' => array
  96. (
  97. 'mandatory' => false,
  98. 'modes' => 'http,cli',
  99. 'default' => ';',
  100. 'description' => 'column separator in CSV data',
  101. ),
  102. 'qualifier' => array
  103. (
  104. 'mandatory' => false,
  105. 'modes' => 'http,cli',
  106. 'default' => '"',
  107. 'description' => 'test qualifier in CSV data',
  108. ),
  109. 'output' => array
  110. (
  111. 'mandatory' => false,
  112. 'modes' => 'http,cli',
  113. 'default' => 'summary',
  114. '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)',
  115. ),
  116. /*
  117. 'reportlevel' => array
  118. (
  119. 'mandatory' => false,
  120. 'modes' => 'http,cli',
  121. 'default' => 'errors|warnings|created|changed|unchanged',
  122. 'description' => 'combination of flags to limit the detailed output',
  123. ),
  124. */
  125. 'simulate' => array
  126. (
  127. 'mandatory' => false,
  128. 'modes' => 'http,cli',
  129. 'default' => '0',
  130. 'description' => 'If set to 1, then the load will not be executed, but the expected report will be produced',
  131. ),
  132. 'comment' => array
  133. (
  134. 'mandatory' => false,
  135. 'modes' => 'http,cli',
  136. 'default' => '',
  137. 'description' => 'Comment to be added into the change log',
  138. ),
  139. );
  140. function UsageAndExit($oP)
  141. {
  142. global $aPageParams;
  143. $bModeCLI = utils::IsModeCLI();
  144. $oP->p("USAGE:\n");
  145. foreach($aPageParams as $sParam => $aParamData)
  146. {
  147. $aModes = explode(',', $aParamData['modes']);
  148. if ($bModeCLI)
  149. {
  150. if (in_array('cli', $aModes))
  151. {
  152. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  153. $oP->p("$sParam = $sDesc");
  154. }
  155. }
  156. else
  157. {
  158. if (in_array('http', $aModes))
  159. {
  160. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  161. $oP->p("$sParam = $sDesc");
  162. }
  163. }
  164. }
  165. $oP->output();
  166. exit;
  167. }
  168. function ReadParam($oP, $sParam)
  169. {
  170. global $aPageParams;
  171. assert(isset($aPageParams[$sParam]));
  172. assert(!$aPageParams[$sParam]['mandatory']);
  173. $sValue = utils::ReadParam($sParam, $aPageParams[$sParam]['default'], true /* Allow CLI */);
  174. return trim($sValue);
  175. }
  176. function ReadMandatoryParam($oP, $sParam)
  177. {
  178. global $aPageParams;
  179. assert(isset($aPageParams[$sParam]));
  180. assert($aPageParams[$sParam]['mandatory']);
  181. $sValue = utils::ReadParam($sParam, null, true /* Allow CLI */);
  182. if (is_null($sValue))
  183. {
  184. $oP->p("ERROR: Missing argument '$sParam'\n");
  185. UsageAndExit($oP);
  186. }
  187. return trim($sValue);
  188. }
  189. function ChangeDateFormat($sProposedDate, $sDateFormat)
  190. {
  191. // Make sure this is a valid MySQL datetime
  192. $iTime = utils::StringToTime($sProposedDate, $sDateFormat);
  193. if ($iTime !== false)
  194. {
  195. $sDate = date('Y-m-d H:i:s', $iTime);
  196. return $sDate;
  197. }
  198. else
  199. {
  200. return false;
  201. }
  202. }
  203. /////////////////////////////////
  204. // Main program
  205. if (utils::IsModeCLI())
  206. {
  207. $oP = new CLIPage(Dict::S("TitleSynchroExecution"));
  208. }
  209. else
  210. {
  211. $oP = new WebPage(Dict::S("TitleSynchroExecution"));
  212. }
  213. try
  214. {
  215. utils::UseParamFile();
  216. }
  217. catch(Exception $e)
  218. {
  219. $oP->p("Error: ".$e->GetMessage());
  220. $oP->output();
  221. exit -2;
  222. }
  223. if (utils::IsModeCLI())
  224. {
  225. // Next steps:
  226. // specific arguments: 'csvfile'
  227. //
  228. $sAuthUser = ReadMandatoryParam($oP, 'auth_user');
  229. $sAuthPwd = ReadMandatoryParam($oP, 'auth_pwd');
  230. $sCsvFile = ReadMandatoryParam($oP, 'csvfile');
  231. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  232. {
  233. UserRights::Login($sAuthUser); // Login & set the user's language
  234. }
  235. else
  236. {
  237. $oP->p("Access restricted or wrong credentials ('$sAuthUser')");
  238. $oP->output();
  239. exit -1;
  240. }
  241. if (!is_readable($sCsvFile))
  242. {
  243. $oP->p("Input file could not be found or could not be read: '$sCsvFile'");
  244. $oP->output();
  245. exit -1;
  246. }
  247. $sCSVData = file_get_contents($sCsvFile);
  248. }
  249. else
  250. {
  251. $_SESSION['login_mode'] = 'basic';
  252. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  253. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  254. $sCSVData = utils::ReadPostedParam('csvdata');
  255. }
  256. try
  257. {
  258. //////////////////////////////////////////////////
  259. //
  260. // Read parameters
  261. //
  262. $iDataSourceId = ReadMandatoryParam($oP, 'data_source_id');
  263. $sSynchronize = ReadParam($oP, 'synchronize');
  264. $sSep = ReadParam($oP, 'separator');
  265. $sQualifier = ReadParam($oP, 'qualifier');
  266. $sCharSet = ReadParam($oP, 'charset');
  267. $sDateFormat = ReadParam($oP, 'date_format');
  268. $sOutput = ReadParam($oP, 'output');
  269. // $sReportLevel = ReadParam($oP, 'reportlevel');
  270. $sSimulate = ReadParam($oP, 'simulate');
  271. $sComment = ReadParam($oP, 'comment');
  272. $oLoadStartDate = new DateTime(); // Now
  273. // Note about date formatting: These MySQL settings are read-only... and in fact unused :-(
  274. // SET SESSION date_format = '%d/%m/%Y';
  275. // SET SESSION datetime_format = '%d/%m/%Y %H:%i:%s';
  276. // Therefore, we have to allow users to transform the format according to a given specification: date_format
  277. //////////////////////////////////////////////////
  278. //
  279. // Statistics
  280. //
  281. $iCountErrors = 0;
  282. $iCountCreations = 0;
  283. $iCountUpdates = 0;
  284. //////////////////////////////////////////////////
  285. //
  286. // Check parameters format/consistency
  287. //
  288. if (strlen($sCSVData) == 0)
  289. {
  290. throw new ExchangeException("Missing data - at least one line is expected");
  291. }
  292. $oDataSource = MetaModel::GetObject('SynchroDataSource', $iDataSourceId, false);
  293. if (is_null($oDataSource))
  294. {
  295. throw new ExchangeException("Unknown data source id: '$iDataSourceId'");
  296. }
  297. $sClass = $oDataSource->GetTargetClass();
  298. if (strlen($sSep) > 1)
  299. {
  300. throw new ExchangeException("Separator is limited to one character, found '$sSep'");
  301. }
  302. if (strlen($sQualifier) > 1)
  303. {
  304. throw new ExchangeException("Text qualifier is limited to one character, found '$sQualifier'");
  305. }
  306. if (!in_array($sOutput, array('retcode', 'summary', 'details')))
  307. {
  308. throw new ExchangeException("Unknown output format: '$sOutput'");
  309. }
  310. /*
  311. $aReportLevels = explode('|', $sReportLevel);
  312. foreach($aReportLevels as $sLevel)
  313. {
  314. if (!in_array($sLevel, explode('|', 'errors|warnings|created|changed|unchanged')))
  315. {
  316. throw new ExchangeException("Unknown level in reporting level: '$sLevel'");
  317. }
  318. }
  319. */
  320. if ($sSimulate == '1')
  321. {
  322. $bSimulate = true;
  323. }
  324. else
  325. {
  326. $bSimulate = false;
  327. }
  328. if ($sSynchronize == '1')
  329. {
  330. $bSynchronize = true;
  331. }
  332. else
  333. {
  334. $bSynchronize = false;
  335. }
  336. //////////////////////////////////////////////////
  337. //
  338. // Parse first line, check attributes, analyse the request
  339. //
  340. if ($sCharSet == 'UTF-8')
  341. {
  342. $sUTF8Data = $sCSVData;
  343. }
  344. else
  345. {
  346. $sUTF8Data = iconv($sCharSet, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  347. }
  348. $oCSVParser = new CSVParser($sUTF8Data, $sSep, $sQualifier);
  349. $aInputColumns = $oCSVParser->ListFields();
  350. $iColCount = count($aInputColumns);
  351. // Check columns
  352. $aColumns = $oDataSource->GetSQLColumns();
  353. $aDateColumns = $oDataSource->GetDateSQLColumns();
  354. $aIsDateToTransform = array();
  355. $aDateToTransformReport = array();
  356. foreach($aInputColumns as $iFieldId => $sInputColumn)
  357. {
  358. if ((strlen($sDateFormat) > 0) && (array_key_exists($sInputColumn, $aDateColumns)))
  359. {
  360. $aIsDateToTransform[$iFieldId] = true;
  361. $aDateToTransformReport[] = $sInputColumn;
  362. }
  363. else
  364. {
  365. $aIsDateToTransform[$iFieldId] = false;
  366. }
  367. if ($sInputColumn == 'primary_key')
  368. {
  369. $iPrimaryKeyCol = $iFieldId;
  370. continue;
  371. }
  372. if (!array_key_exists($sInputColumn, $aColumns))
  373. {
  374. throw new ExchangeException("Unknown column '$sInputColumn' (class: '$sClass')");
  375. }
  376. }
  377. if (!isset($iPrimaryKeyCol))
  378. {
  379. throw new ExchangeException("Missing reconciliation column 'primary_key'");
  380. }
  381. //////////////////////////////////////////////////
  382. //
  383. // Go for parsing and interpretation
  384. //
  385. try
  386. {
  387. $oP->add_comment('Load--------------');
  388. $oP->add_comment('------------------');
  389. if ($bSimulate)
  390. {
  391. CMDBSource::Query('START TRANSACTION');
  392. }
  393. $aData = $oCSVParser->ToArray();
  394. $iLineCount = count($aData);
  395. $sTable = $oDataSource->GetDataTable();
  396. // Prepare insert columns
  397. $sInsertColumns = '`'.implode('`, `', $aInputColumns).'`';
  398. foreach($aData as $iRow => $aRow)
  399. {
  400. $sReconciliationCondition = "`primary_key` = ".CMDBSource::Quote($aRow[$iPrimaryKeyCol]);
  401. $sSelect = "SELECT COUNT(*) FROM `$sTable` WHERE $sReconciliationCondition";
  402. $aRes = CMDBSource::QueryToArray($sSelect);
  403. $iCount = $aRes[0]['COUNT(*)'];
  404. if ($iCount == 0)
  405. {
  406. // No record... create it
  407. //
  408. $iCountCreations++;
  409. if ($sOutput == 'details')
  410. {
  411. $oP->add("$iRow: New entry, reconciliation: '$sReconciliationCondition'\n");
  412. }
  413. $aValues = array(); // Used to build the insert query
  414. foreach ($aRow as $iCol => $value)
  415. {
  416. if (is_null($value))
  417. {
  418. $aValues[] = 'NULL';
  419. }
  420. elseif ($aIsDateToTransform[$iCol])
  421. {
  422. $sDate = ChangeDateFormat($value, $sDateFormat);
  423. if ($sDate === false)
  424. {
  425. $aValues[] = CMDBSource::Quote('');
  426. if ($sOutput == 'details')
  427. {
  428. $oP->add("$iRow: Wrong format for date field: '$value' (skipped column)\n");
  429. }
  430. }
  431. else
  432. {
  433. $aValues[] = CMDBSource::Quote($sDate);
  434. }
  435. }
  436. else
  437. {
  438. $aValues[] = CMDBSource::Quote($value);
  439. }
  440. }
  441. $sValues = implode(', ', $aValues);
  442. $sInsert = "INSERT INTO `$sTable` ($sInsertColumns) VALUES ($sValues)";
  443. CMDBSource::Query($sInsert);
  444. }
  445. elseif ($iCount == 1)
  446. {
  447. // Found a match... update it
  448. //
  449. $iCountUpdates++;
  450. if ($sOutput == 'details')
  451. {
  452. $oP->add("$iRow: Update entry, reconciliation: '$sReconciliationCondition'\n");
  453. }
  454. $aValuePairs = array(); // Used to build the update query
  455. foreach ($aRow as $iCol => $value)
  456. {
  457. // Skip reconciliation column
  458. if ($iCol == $iPrimaryKeyCol) continue;
  459. $sCol = $aInputColumns[$iCol];
  460. if ($aIsDateToTransform[$iCol])
  461. {
  462. $sDate = ChangeDateFormat($aRow[$iCol], $sDateFormat);
  463. if ($sDate === false)
  464. {
  465. // Skip this column spec
  466. if ($sOutput == 'details')
  467. {
  468. $oP->add("$iRow: Wrong format for date field: '".$aRow[$iCol]."' (skipped column)\n");
  469. }
  470. }
  471. else
  472. {
  473. $aValuePairs[] = "`$sCol` = ".CMDBSource::Quote($sDate);
  474. }
  475. }
  476. else
  477. {
  478. $aValuePairs[] = "`$sCol` = ".CMDBSource::Quote($aRow[$iCol]);
  479. }
  480. }
  481. $sValuePairs = implode(', ', $aValuePairs);
  482. $sUpdateQuery = "UPDATE `$sTable` SET $sValuePairs WHERE $sReconciliationCondition";
  483. CMDBSource::Query($sUpdateQuery);
  484. }
  485. else
  486. {
  487. // Too many records... ambiguity
  488. //
  489. $iCountErrors++;
  490. $oP->add("$iRow: Error - Failed to reconcile, found $iCount rows having '$sReconciliationCondition'\n");
  491. }
  492. }
  493. if (($sOutput == "summary") || ($sOutput == 'details'))
  494. {
  495. $oP->add_comment("Data Source: ".$iDataSourceId);
  496. $oP->add_comment("Synchronize: ".($bSynchronize ? '1' : '0'));
  497. $oP->add_comment("Class: ".$sClass);
  498. $oP->add_comment("Separator: ".$sSep);
  499. $oP->add_comment("Qualifier: ".$sQualifier);
  500. $oP->add_comment("Charset Encoding:".$sCharSet);
  501. if (strlen($sDateFormat) > 0)
  502. {
  503. $oP->add_comment("Date format: '$sDateFormat', applied to columns {".implode(', ', $aDateToTransformReport)."}");
  504. }
  505. else
  506. {
  507. $oP->add_comment("Date format: <none>");
  508. }
  509. $oP->add_comment("Data Size: ".strlen($sCSVData));
  510. $oP->add_comment("Data Lines: ".$iLineCount);
  511. $oP->add_comment("Columns: ".implode(', ', $aInputColumns));
  512. $oP->add_comment("Output format: ".$sOutput);
  513. // $oP->add_comment("Report level: ".$sReportLevel);
  514. $oP->add_comment("Simulate: ".($bSimulate ? '1' : '0'));
  515. $oP->add_comment("Change tracking comment: ".$sComment);
  516. $oP->add_comment("Issues (before synchro): ".$iCountErrors);
  517. // $oP->add_comment("Warnings: ".$iCountWarnings);
  518. $oP->add_comment("Created (before synchro): ".$iCountCreations);
  519. $oP->add_comment("Updated (before synchro): ".$iCountUpdates);
  520. }
  521. //////////////////////////////////////////////////
  522. //
  523. // Synchronize
  524. //
  525. if ($bSynchronize)
  526. {
  527. $oStatLog = $oDataSource->Synchronize($oLoadStartDate);
  528. $oP->add_comment('Synchronization---');
  529. $oP->add_comment('------------------');
  530. if ($sOutput == 'details')
  531. {
  532. foreach ($oStatLog->GetTraces() as $sMessage)
  533. {
  534. $oP->add_comment($sMessage);
  535. }
  536. }
  537. if ($oStatLog->Get('status') == 'error')
  538. {
  539. $oP->p("ERROR: ".$oStatLog->Get('last_error'));
  540. }
  541. $oP->add_comment("Replicas: ".$oStatLog->Get('stats_nb_replica_total'));
  542. $oP->add_comment("Replicas touched since last synchro: ".$oStatLog->Get('stats_nb_replica_seen'));
  543. $oP->add_comment("Objects deleted: ".$oStatLog->Get('stats_nb_obj_deleted'));
  544. $oP->add_comment("Objects deletion errors: ".$oStatLog->Get('stats_nb_obj_deleted_errors'));
  545. $oP->add_comment("Objects obsoleted: ".$oStatLog->Get('stats_nb_obj_obsoleted'));
  546. $oP->add_comment("Objects obsolescence errors: ".$oStatLog->Get('stats_nb_obj_obsoleted_errors'));
  547. $oP->add_comment("Objects created: ".$oStatLog->Get('stats_nb_obj_created'));
  548. $oP->add_comment("Objects creation errors: ".$oStatLog->Get('stats_nb_obj_created_errors'));
  549. $oP->add_comment("Objects updated: ".$oStatLog->Get('stats_nb_obj_updated'));
  550. $oP->add_comment("Objects update errors: ".$oStatLog->Get('stats_nb_obj_updated_errors'));
  551. $oP->add_comment("Objects reconciled (updated): ".$oStatLog->Get('stats_nb_obj_new_updated'));
  552. $oP->add_comment("Objects reconciled (unchanged): ".$oStatLog->Get('stats_nb_obj_new_unchanged'));
  553. $oP->add_comment("Objects reconciliation errors: ".$oStatLog->Get('stats_nb_replica_reconciled_errors'));
  554. $oP->add_comment("Replica disappeared, no action taken: ".$oStatLog->Get('stats_nb_replica_disappeared_no_action'));
  555. }
  556. }
  557. catch(Exception $e)
  558. {
  559. if ($bSimulate)
  560. {
  561. CMDBSource::Query('ROLLBACK');
  562. }
  563. throw $e;
  564. }
  565. if ($bSimulate)
  566. {
  567. CMDBSource::Query('ROLLBACK');
  568. }
  569. //////////////////////////////////////////////////
  570. //
  571. // Summary of settings and results
  572. //
  573. if ($sOutput == 'retcode')
  574. {
  575. $oP->add($iCountErrors);
  576. }
  577. }
  578. catch(ExchangeException $e)
  579. {
  580. $oP->add_comment($e->getMessage());
  581. }
  582. catch(SecurityException $e)
  583. {
  584. $oP->add_comment($e->getMessage());
  585. }
  586. catch(Exception $e)
  587. {
  588. $oP->add_comment((string)$e);
  589. }
  590. $oP->output();
  591. ?>