-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathsynchro_import.php
More file actions
697 lines (634 loc) · 22.5 KB
/
synchro_import.php
File metadata and controls
697 lines (634 loc) · 22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
<?php
/**
* Copyright (C) 2013-2024 Combodo SAS
*
* This file is part of iTop.
*
* iTop is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* iTop is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
*/
//
// Known limitations
// - reconciliation is made on the column primary_key
//
use Combodo\iTop\Application\WebPage\CLILikeWebPage;
use Combodo\iTop\Application\WebPage\CLIPage;
require_once __DIR__.'/../approot.inc.php';
require_once APPROOT.'/application/application.inc.php';
require_once APPROOT.'/application/startup.inc.php';
class ExchangeException extends Exception
{
}
$aPageParams =
[
'auth_user' =>
[
'mandatory' => true,
'modes' => 'cli',
'default' => null,
'description' => 'login (must have enough rights to create objects of the given class)',
],
'auth_pwd' =>
[
'mandatory' => true,
'modes' => 'cli',
'default' => null,
'description' => 'password',
],
'data_source_id' =>
[
'mandatory' => true,
'modes' => 'http,cli',
'default' => null,
'description' => 'Synchro data source id',
],
'csvdata' =>
[
'mandatory' => true,
'modes' => 'http',
'default' => null,
'description' => 'data',
],
'csvfile' =>
[
'mandatory' => true,
'modes' => 'cli',
'default' => '',
'description' => 'local data file, replaces csvdata if specified',
],
'synchronize' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => '1',
'description' => 'If set to 1, then the synchronization will be executed right after the data load',
],
'charset' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => 'UTF-8',
'description' => 'Character set encoding of the CSV data: UTF-8, ISO-8859-1, WINDOWS-1251, WINDOWS-1252, ISO-8859-15',
],
'date_format' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => 'Y-m-d H:i:s',
'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. (note: old format specification using %Y %m %d is also supported for backward compatibility)',
],
'separator' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => ';',
'description' => 'column separator in CSV data (1 char, or \'tab\')',
],
'qualifier' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => '"',
'description' => 'test qualifier in CSV data',
],
'output' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => 'summary',
'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)',
],
'max_chunk_size' =>
[
'mandatory' => false,
'modes' => 'cli',
'default' => '0',
'description' => 'Limit on the count of records that can be loaded at once while performing the synchronization',
],
/*
'reportlevel' => array
(
'mandatory' => false,
'modes' => 'http,cli',
'default' => 'errors|warnings|created|changed|unchanged',
'description' => 'combination of flags to limit the detailed output',
),
*/
'simulate' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => '0',
'description' => 'If set to 1, then the load will not be executed, but the expected report will be produced',
],
'comment' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => '',
'description' => 'Comment to be added into the change log',
],
'no_stop_on_import_error' =>
[
'mandatory' => false,
'modes' => 'http,cli',
'default' => '0',
'description' => 'Don\'t stop the import in case of SQL import error. By default the import will stop at the first error (and rollback all changes). If this flag is set to 1 the import will continue anyway',
],
];
function UsageAndExit($oP)
{
global $aPageParams;
$sMode = utils::IsModeCLI() ? 'cli' : 'http';
$oP->p("USAGE:\n");
foreach ($aPageParams as $sParam => $aParamData) {
$aModes = explode(',', $aParamData['modes']);
if (in_array($sMode, $aModes, false)) {
$sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
$oP->p("$sParam = $sDesc");
}
}
$oP->output();
exit;
}
function ReadParam($oP, $sParam, $sSanitizationFilter = 'parameter')
{
global $aPageParams;
assert(isset($aPageParams[$sParam]));
assert(!$aPageParams[$sParam]['mandatory']);
$sValue = utils::ReadParam($sParam, $aPageParams[$sParam]['default'], true /* Allow CLI */, $sSanitizationFilter);
return trim($sValue);
}
function ReadMandatoryParam($oP, $sParam, $sSanitizationFilter)
{
global $aPageParams;
assert(isset($aPageParams[$sParam]));
assert($aPageParams[$sParam]['mandatory']);
$sValue = utils::ReadParam($sParam, null, true /* Allow CLI */, $sSanitizationFilter);
if ($sValue === null) {
$oP->p("ERROR: Missing argument '$sParam'\n");
UsageAndExit($oP);
}
return trim($sValue);
}
function ChangeDateFormat($sProposedDate, $sFormat, $bDateOnly)
{
if ($sProposedDate === '') {
// An empty string means 'reset'
return '';
}
// Convert to a valid MySQL datetime
$oFormat = new DateTimeFormat($sFormat);
$sRegExpr = $oFormat->ToRegExpr('/');
if (!preg_match($sRegExpr, $sProposedDate)) {
return false;
}
$oDate = $oFormat->Parse($sProposedDate);
if ($oDate !== null) {
$oTargetFormat = $bDateOnly ? AttributeDate::GetInternalFormat() : AttributeDateTime::GetInternalFormat();
$sDate = $oDate->format($oTargetFormat);
return $sDate;
}
return false;
}
/////////////////////////////////
// Main program
if (utils::IsModeCLI()) {
$oP = new CLIPage(Dict::S('TitleSynchroExecution'));
SetupUtils::CheckPhpAndExtensionsForCli($oP, -2);
try {
utils::UseParamFile();
} catch (Exception $e) {
$oP->p('Error: '.$e->GetMessage());
$oP->output();
exit - 2;
}
} else {
$oP = new CLILikeWebPage(Dict::S('TitleSynchroExecution'));
}
if (utils::IsModeCLI()) {
// Next steps:
// specific arguments: 'csvfile'
//
$sAuthUser = ReadMandatoryParam($oP, 'auth_user', 'raw_data');
$sAuthPwd = ReadMandatoryParam($oP, 'auth_pwd', 'raw_data');
$sCsvFile = ReadMandatoryParam($oP, 'csvfile', 'raw_data');
if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd)) {
UserRights::Login($sAuthUser); // Login & set the user's language
} else {
$oP->p("Access restricted or wrong credentials ('$sAuthUser')");
$oP->output();
exit -1;
}
if (!is_readable($sCsvFile)) {
$oP->p("Input file could not be found or could not be read: '$sCsvFile'");
$oP->output();
exit -1;
}
$sCSVData = file_get_contents($sCsvFile);
} else {
require_once APPROOT.'/application/loginwebpage.class.inc.php';
//N°6022 - Make synchro scripts work by http via token authentication with SYNCHRO scopes
$oCtx = new ContextTag(ContextTag::TAG_SYNCHRO);
LoginWebPage::ResetSession(true);
$iRet = LoginWebPage::DoLogin(false, false, LoginWebPage::EXIT_RETURN);
if ($iRet !== LoginWebPage::EXIT_CODE_OK) {
switch ($iRet) {
case LoginWebPage::EXIT_CODE_MISSINGLOGIN:
$oP->p("Missing parameter 'auth_user'");
break;
case LoginWebPage::EXIT_CODE_MISSINGPASSWORD:
$oP->p("Missing parameter 'auth_pwd'");
break;
case LoginWebPage::EXIT_CODE_WRONGCREDENTIALS:
$oP->p('Invalid login');
break;
case LoginWebPage::EXIT_CODE_PORTALUSERNOTAUTHORIZED:
$oP->p('Portal user is not allowed');
break;
case LoginWebPage::EXIT_CODE_NOTAUTHORIZED:
$oP->p('This user is not authorized to use the web services. (The profile REST Services User is required to access the REST web services)');
break;
default:
$oP->p("Unknown authentication error (retCode=$iRet)");
}
$oP->output();
exit -1;
}
$sCSVData = utils::ReadPostedParam('csvdata', '', 'raw_data');
}
try {
//////////////////////////////////////////////////
//
// Read parameters
//
$iDataSourceId = ReadMandatoryParam($oP, 'data_source_id', utils::ENUM_SANITIZATION_FILTER_INTEGER);
$sSynchronize = ReadParam($oP, 'synchronize');
$sSep = ReadParam($oP, 'separator', 'raw_data');
$sQualifier = ReadParam($oP, 'qualifier', 'raw_data');
$sCharSet = ReadParam($oP, 'charset', 'raw_data');
$sDateTimeFormat = ReadParam($oP, 'date_format', 'raw_data');
if ($sDateTimeFormat === '') {
$sDateTimeFormat = 'Y-m-d H:i:s'; // By default use the SQL date & time format
}
if (strpos($sDateTimeFormat, '%') !== false) {
$sDateTimeFormat = utils::DateTimeFormatToPHP($sDateTimeFormat);
}
$oDateTimeFormat = new DateTimeFormat($sDateTimeFormat);
$sDateFormat = $oDateTimeFormat->ToDateFormat(); // Keep only the date part
$sOutput = ReadParam($oP, 'output');
// $sReportLevel = ReadParam($oP, 'reportlevel');
$sSimulate = ReadParam($oP, 'simulate');
$sComment = ReadParam($oP, 'comment', 'raw_data');
$sNoStopOnImportError = ReadParam($oP, 'no_stop_on_import_error');
if (strtolower(trim($sSep)) === 'tab') {
$sSep = "\t";
}
// Saving script launch datetime : if we're doing both import AND exec phases (--synchronize=1 parameter)
// then exec phase will need this !
$oLoadStartDate = SynchroExecution::GetDataBaseCurrentDateTime();
// Note about date formatting: These MySQL settings are read-only... and in fact unused :-(
// SET SESSION date_format = '%d/%m/%Y';
// SET SESSION datetime_format = '%d/%m/%Y %H:%i:%s';
// Therefore, we have to allow users to transform the format according to a given specification: date_format
//////////////////////////////////////////////////
//
// Statistics
//
$iCountErrors = 0;
$iCountCreations = 0;
$iCountUpdates = 0;
//////////////////////////////////////////////////
//
// Check parameters format/consistency
//
if (strlen($sCSVData) === 0) {
throw new ExchangeException('Missing data - at least one line is expected');
}
/** @var \SynchroDataSource $oDataSource */
$oDataSource = MetaModel::GetObject('SynchroDataSource', $iDataSourceId, false);
if ($oDataSource === null) {
throw new ExchangeException("Unknown data source id: '$iDataSourceId'");
}
$sClass = $oDataSource->GetTargetClass();
if (strlen($sSep) > 1) {
throw new ExchangeException("Separator is limited to one character, found '$sSep'");
}
if (strlen($sQualifier) > 1) {
throw new ExchangeException("Text qualifier is limited to one character, found '$sQualifier'");
}
if (!in_array($sOutput, ['retcode', 'summary', 'details'])) {
throw new ExchangeException("Unknown output format: '$sOutput'");
}
/*
$aReportLevels = explode('|', $sReportLevel);
foreach($aReportLevels as $sLevel)
{
if (!in_array($sLevel, explode('|', 'errors|warnings|created|changed|unchanged')))
{
throw new ExchangeException("Unknown level in reporting level: '$sLevel'");
}
}
*/
if ($sSimulate === '1') {
$bSimulate = true;
} else {
$bSimulate = false;
}
if ($sSynchronize === '1') {
$bSynchronize = true;
} else {
$bSynchronize = false;
}
//////////////////////////////////////////////////
//
// Parse first line, check attributes, analyse the request
//
if ($sCharSet === 'UTF-8') {
$sUTF8Data = $sCSVData;
} else {
$sUTF8Data = iconv($sCharSet, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
}
$oCSVParser = new CSVParser($sUTF8Data, $sSep, $sQualifier, MetaModel::GetConfig()->Get('max_execution_time_per_loop'));
$aInputColumns = $oCSVParser->ListFields();
$iColCount = count($aInputColumns);
// Check columns
$aColumns = $oDataSource->GetSQLColumns();
$aDateColumns = [];
foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef) {
if ($oAttDef instanceof AttributeDate) {
$aDateColumns[$sAttCode] = 'DATE';
} elseif ($oAttDef instanceof AttributeDateTime) {
$aDateColumns[$sAttCode] = 'DATETIME';
}
}
$aIsDateToTransform = [];
$aDateToTransformReport = [];
$aIsBinaryToTransform = [];
foreach ($aInputColumns as $iFieldId => $sInputColumn) {
$aIsBinaryToTransform[$iFieldId] = false;
if (array_key_exists($sInputColumn, $aDateColumns)) {
$aIsDateToTransform[$iFieldId] = $aDateColumns[$sInputColumn]; // either DATE or DATETIME
$aDateToTransformReport[] = $sInputColumn;
} else {
$aIsDateToTransform[$iFieldId] = false;
}
if ($sInputColumn === 'primary_key') {
$iPrimaryKeyCol = $iFieldId;
$aIsBinaryToTransform[$iFieldId] = false;
continue;
}
if (!array_key_exists($sInputColumn, $aColumns)) {
throw new ExchangeException("Unknown column '$sInputColumn' (class: '$sClass')");
}
$aIsBinaryToTransform[$iFieldId] = ($aColumns[$sInputColumn] === 'LONGBLOB');
}
if (!isset($iPrimaryKeyCol)) {
throw new ExchangeException("Missing reconciliation column 'primary_key'");
}
//////////////////////////////////////////////////
//
// Go for parsing and interpretation
//
try {
if ($sOutput === 'details') {
$oP->add_comment('------------------------------------------------------------');
$oP->add_comment(' Import phase');
$oP->add_comment('------------------------------------------------------------');
}
if ($bSimulate) {
CMDBSource::Query('START TRANSACTION');
}
$aData = $oCSVParser->ToArray();
$iLineCount = count($aData);
$sTable = $oDataSource->GetDataTable();
// Prepare insert columns
$sInsertColumns = '`'.implode('`, `', $aInputColumns).'`';
$iPreviousTimeLimit = ini_get('max_execution_time');
$iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
$oMutex = new iTopMutex('synchro_import_'.$oDataSource->GetKey());
$oMutex->Lock();
foreach ($aData as $iRow => $aRow) {
/** @noinspection DisconnectedForeachInstructionInspection */
set_time_limit($iLoopTimeLimit);
$sReconciliationCondition = '`primary_key` = '.CMDBSource::Quote($aRow[$iPrimaryKeyCol]);
$sSelect = "SELECT COUNT(*) FROM `$sTable` WHERE $sReconciliationCondition";
$aRes = CMDBSource::QueryToArray($sSelect);
$iCount = (int)$aRes[0]['COUNT(*)'];
if ($iCount === 0) {
// No record... create it
//
$iCountCreations++;
if ($sOutput === 'details') {
$oP->add("$iRow: New entry, reconciliation: '$sReconciliationCondition'\n");
}
$aValues = []; // Used to build the insert query
foreach ($aRow as $iCol => $value) {
if ($aIsDateToTransform[$iCol] !== false) {
$bDateOnly = false;
$sFormat = $sDateTimeFormat;
if ($aIsDateToTransform[$iCol] === 'DATE') {
$bDateOnly = true;
$sFormat = $sDateFormat;
}
$sDate = ChangeDateFormat($value, $sFormat, $bDateOnly);
if ($sDate === false) {
$aValues[] = '';
if ($sOutput === 'details') {
$oP->add("$iRow: Wrong format for {$aIsDateToTransform[$iCol]} column $iCol: '$value' does not match the expected format: '$sFormat' (column skipped)\n");
}
} else {
$aValues[] = $sDate;
}
} elseif ($aIsBinaryToTransform[$iCol]) {
$aValues[] = base64_decode($value);
} else {
$aValues[] = $value;
}
}
$sValues = implode(', ', CMDBSource::Quote($aValues));
$sInsert = "INSERT INTO `$sTable` ($sInsertColumns) VALUES ($sValues)";
try {
CMDBSource::Query($sInsert);
} catch (Exception $e) {
if ($sNoStopOnImportError === '1') {
$iCountErrors++;
$oP->add("$iRow: Import error '".$e->getMessage()."' (continuing)...\n");
} else { // Fatal error
throw $e;
}
}
} elseif ($iCount === 1) {
// Found a match... update it
//
$iCountUpdates++;
if ($sOutput === 'details') {
$oP->add("$iRow: Update entry, reconciliation: '$sReconciliationCondition'\n");
}
$aValuePairs = []; // Used to build the update query
foreach ($aRow as $iCol => $value) {
// Skip reconciliation column
if ($iCol === $iPrimaryKeyCol) {
continue;
}
$sCol = $aInputColumns[$iCol];
if ($aIsDateToTransform[$iCol] !== false) {
$bDateOnly = false;
$sFormat = $sDateTimeFormat;
if ($aIsDateToTransform[$iCol] === 'DATE') {
$bDateOnly = true;
$sFormat = $sDateFormat;
}
$sDate = ChangeDateFormat($value, $sFormat, $bDateOnly);
if ($sDate === false) {
if ($sOutput === 'details') {
$oP->add("$iRow: Wrong format for {$aIsDateToTransform[$iCol]} column $iCol: '$value' does not match the expected format: '$sFormat' (column skipped)\n");
}
} else {
$aValuePairs[] = "`$sCol` = ".CMDBSource::Quote($sDate);
}
} elseif ($aIsBinaryToTransform[$iCol]) {
$aValuePairs[] = "`$sCol` = FROM_BASE64(".CMDBSource::Quote($aRow[$iCol], true).")";
} else {
$aValuePairs[] = "`$sCol` = ".CMDBSource::Quote($aRow[$iCol]);
}
}
$sValuePairs = implode(', ', $aValuePairs);
$sUpdateQuery = "UPDATE `$sTable` SET $sValuePairs WHERE $sReconciliationCondition";
try {
CMDBSource::Query($sUpdateQuery);
} catch (Exception $e) {
if ($sNoStopOnImportError === '1') {
$iCountErrors++;
$oP->add("$iRow: Import error '".$e->getMessage()."' (continuing)...\n");
} else { // Fatal error
throw $e;
}
}
} else {
// Too many records... ambiguity
//
$iCountErrors++;
$oP->add("$iRow: Error - Failed to reconcile, found $iCount rows having '$sReconciliationCondition'\n");
}
}
$oMutex->Unlock();
set_time_limit(intval($iPreviousTimeLimit));
if (($sOutput === 'summary') || ($sOutput === 'details')) {
$oP->add_comment('------------------------------------------------------------');
$oP->add_comment(' Import phase summary');
$oP->add_comment('------------------------------------------------------------');
$oP->add_comment('Data Source: '.$iDataSourceId);
$oP->add_comment('Synchronize: '.($bSynchronize ? '1' : '0'));
$oP->add_comment('Class: '.$sClass);
$oP->add_comment('Separator: '.$sSep);
$oP->add_comment('Qualifier: '.$sQualifier);
$oP->add_comment('Charset Encoding:'.$sCharSet);
if (strlen($sDateTimeFormat) > 0) {
$aDateTimeColumns = [];
$aDateColumns = [];
foreach ($aIsDateToTransform as $iCol => $sType) {
if ($sType !== false) {
$sCol = $aInputColumns[$iCol];
if ($sType === 'DATE') {
$aDateColumns[] = $sCol;
} else {
$aDateTimeColumns[] = $sCol;
}
}
}
$sFormatedDateTimeColumns = (count($aDateTimeColumns) > 0) ? ', applied to columns ['.implode(
', ',
$aDateTimeColumns
).']' : '';
$sFormatedDateColumns = (count($aDateColumns) > 0) ? ', applied to columns ['.implode(', ', $aDateColumns).']' : '';
$oP->add_comment("Date and time format: '$sDateTimeFormat' $sFormatedDateTimeColumns");
$oP->add_comment("Date only format: '$sDateFormat' $sFormatedDateColumns");
} else {
// shall never get there
$oP->add_comment('Date format: <none>');
}
$oP->add_comment('Data Size: '.strlen($sCSVData));
$oP->add_comment('Data Lines: '.$iLineCount);
$oP->add_comment('Columns: '.implode(', ', $aInputColumns));
$oP->add_comment('Output format: '.$sOutput);
// $oP->add_comment("Report level: ".$sReportLevel);
$oP->add_comment('Simulate: '.($bSimulate ? '1' : '0'));
$oP->add_comment('Change tracking comment: '.$sComment);
$oP->add_comment('Issues (before synchro): '.$iCountErrors);
// $oP->add_comment("Warnings: ".$iCountWarnings);
$oP->add_comment('Created (before synchro): '.$iCountCreations);
$oP->add_comment('Updated (before synchro): '.$iCountUpdates);
}
//////////////////////////////////////////////////
//
// Synchronize
//
if ($bSynchronize) {
$oSynchroExec = new SynchroExecution($oDataSource, $oLoadStartDate);
$oStatLog = $oSynchroExec->Process();
if ($sOutput === 'details') {
$oP->add_comment('------------------------------------------------------------');
$oP->add_comment(' Synchronization phase');
$oP->add_comment('------------------------------------------------------------');
$iCount = 0;
foreach ($oStatLog->GetTraces() as $sMessage) {
$iCount++;
$oP->add_comment($sMessage);
}
if ($iCount === 0) {
$oP->add_comment(' No traces. (To activate the traces set "synchro_trace" => true in the configuration file)');
}
}
if ($oStatLog->Get('status') === 'error') {
$oP->p('ERROR: '.$oStatLog->Get('last_error'));
}
$oP->add_comment('------------------------------------------------------------');
$oP->add_comment(' Synchronization phase summary');
$oP->add_comment('------------------------------------------------------------');
$oP->add_comment('Replicas: '.$oStatLog->Get('stats_nb_replica_total'));
$oP->add_comment('Replicas touched since last synchro: '.$oStatLog->Get('stats_nb_replica_seen'));
$oP->add_comment('Objects deleted: '.$oStatLog->Get('stats_nb_obj_deleted'));
$oP->add_comment('Objects deletion errors: '.$oStatLog->Get('stats_nb_obj_deleted_errors'));
$oP->add_comment('Objects obsoleted: '.$oStatLog->Get('stats_nb_obj_obsoleted'));
$oP->add_comment('Objects obsolescence errors: '.$oStatLog->Get('stats_nb_obj_obsoleted_errors'));
$oP->add_comment('Objects created: '.$oStatLog->Get('stats_nb_obj_created').' ('.$oStatLog->Get('stats_nb_obj_created_warnings').' warnings)');
$oP->add_comment('Objects creation errors: '.$oStatLog->Get('stats_nb_obj_created_errors'));
$oP->add_comment('Objects updated: '.$oStatLog->Get('stats_nb_obj_updated').' ('.$oStatLog->Get('stats_nb_obj_updated_warnings')." warnings)");
$oP->add_comment('Objects update errors: '.$oStatLog->Get('stats_nb_obj_updated_errors'));
$oP->add_comment('Objects reconciled (updated): '.$oStatLog->Get('stats_nb_obj_new_updated').' ('.$oStatLog->Get('stats_nb_obj_new_updated_warnings').' warnings)');
$oP->add_comment('Objects reconciled (unchanged): '.$oStatLog->Get('stats_nb_obj_new_unchanged').' ('.$oStatLog->Get('stats_nb_obj_new_unchanged_warnings').' warnings)');
$oP->add_comment('Objects reconciliation errors: '.$oStatLog->Get('stats_nb_replica_reconciled_errors'));
$oP->add_comment('Replica disappeared, no action taken: '.$oStatLog->Get('stats_nb_replica_disappeared_no_action'));
}
} catch (Exception $e) {
if ($bSimulate) {
CMDBSource::Query('ROLLBACK');
}
throw $e;
}
if ($bSimulate) {
CMDBSource::Query('ROLLBACK');
}
//////////////////////////////////////////////////
//
// Summary of settings and results
//
if ($sOutput === 'retcode') {
$oP->add($iCountErrors);
}
} catch (ExchangeException $e) {
$oP->add_comment($e->getMessage());
} catch (Exception $e) {
$oP->add_comment((string)$e);
}
$oP->output();