import.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  34. require_once(__DIR__.'/../approot.inc.php');
  35. require_once(APPROOT.'/application/application.inc.php');
  36. require_once(APPROOT.'/application/webpage.class.inc.php');
  37. require_once(APPROOT.'/application/csvpage.class.inc.php');
  38. require_once(APPROOT.'/application/clipage.class.inc.php');
  39. require_once(APPROOT.'/application/startup.inc.php');
  40. class BulkLoadException extends Exception
  41. {
  42. }
  43. $aPageParams = array
  44. (
  45. 'auth_user' => array
  46. (
  47. 'mandatory' => true,
  48. 'modes' => 'cli',
  49. 'default' => null,
  50. 'description' => 'login (must have enough rights to create objects of the given class)',
  51. ),
  52. 'auth_pwd' => array
  53. (
  54. 'mandatory' => true,
  55. 'modes' => 'cli',
  56. 'default' => null,
  57. 'description' => 'password',
  58. ),
  59. 'class' => array
  60. (
  61. 'mandatory' => true,
  62. 'modes' => 'http,cli',
  63. 'default' => null,
  64. 'description' => 'class of loaded objects',
  65. ),
  66. 'csvdata' => array
  67. (
  68. 'mandatory' => true,
  69. 'modes' => 'http',
  70. 'default' => null,
  71. 'description' => 'data',
  72. ),
  73. 'csvfile' => array
  74. (
  75. 'mandatory' => true,
  76. 'modes' => 'cli',
  77. 'default' => '',
  78. 'description' => 'local data file, replaces csvdata if specified',
  79. ),
  80. 'charset' => array
  81. (
  82. 'mandatory' => false,
  83. 'modes' => 'http,cli',
  84. 'default' => 'UTF-8',
  85. 'description' => 'Character set encoding of the CSV data: UTF-8, ISO-8859-1, WINDOWS-1251, WINDOWS-1252, ISO-8859-15',
  86. ),
  87. 'separator' => array
  88. (
  89. 'mandatory' => false,
  90. 'modes' => 'http,cli',
  91. 'default' => ',',
  92. 'description' => 'column separator in CSV data',
  93. ),
  94. 'qualifier' => array
  95. (
  96. 'mandatory' => false,
  97. 'modes' => 'http,cli',
  98. 'default' => '"',
  99. 'description' => 'test qualifier in CSV data',
  100. ),
  101. 'output' => array
  102. (
  103. 'mandatory' => false,
  104. 'modes' => 'http,cli',
  105. 'default' => 'summary',
  106. '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)',
  107. ),
  108. /*
  109. 'reportlevel' => array
  110. (
  111. 'mandatory' => false,
  112. 'modes' => 'http,cli',
  113. 'default' => 'errors|warnings|created|changed|unchanged',
  114. 'description' => 'combination of flags to limit the detailed output',
  115. ),
  116. */
  117. 'reconciliationkeys' => array
  118. (
  119. 'mandatory' => false,
  120. 'modes' => 'http,cli',
  121. 'default' => '',
  122. 'description' => 'name of the columns used to identify existing objects and update them, or create a new one',
  123. ),
  124. 'simulate' => array
  125. (
  126. 'mandatory' => false,
  127. 'modes' => 'http,cli',
  128. 'default' => '0',
  129. 'description' => 'If set to 1, then the load will not be executed, but the expected report will be produced',
  130. ),
  131. 'comment' => array
  132. (
  133. 'mandatory' => false,
  134. 'modes' => 'http,cli',
  135. 'default' => '',
  136. 'description' => 'Comment to be added into the change log',
  137. ),
  138. );
  139. function UsageAndExit($oP)
  140. {
  141. global $aPageParams;
  142. $bModeCLI = utils::IsModeCLI();
  143. $oP->p("USAGE:\n");
  144. foreach($aPageParams as $sParam => $aParamData)
  145. {
  146. $aModes = explode(',', $aParamData['modes']);
  147. if ($bModeCLI)
  148. {
  149. if (in_array('cli', $aModes))
  150. {
  151. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  152. $oP->p("$sParam = $sDesc");
  153. }
  154. }
  155. else
  156. {
  157. if (in_array('http', $aModes))
  158. {
  159. $sDesc = $aParamData['description'].', '.($aParamData['mandatory'] ? 'mandatory' : 'optional, defaults to ['.$aParamData['default'].']');
  160. $oP->p("$sParam = $sDesc");
  161. }
  162. }
  163. }
  164. $oP->output();
  165. exit;
  166. }
  167. function ReadParam($oP, $sParam)
  168. {
  169. global $aPageParams;
  170. assert(isset($aPageParams[$sParam]));
  171. assert(!$aPageParams[$sParam]['mandatory']);
  172. $sValue = utils::ReadParam($sParam, $aPageParams[$sParam]['default'], true /* Allow CLI */);
  173. return trim($sValue);
  174. }
  175. function ReadMandatoryParam($oP, $sParam)
  176. {
  177. global $aPageParams;
  178. assert(isset($aPageParams[$sParam]));
  179. assert($aPageParams[$sParam]['mandatory']);
  180. $sValue = utils::ReadParam($sParam, null, true /* Allow CLI */);
  181. if (is_null($sValue))
  182. {
  183. $oP->p("ERROR: Missing argument '$sParam'\n");
  184. UsageAndExit($oP);
  185. }
  186. return trim($sValue);
  187. }
  188. /////////////////////////////////
  189. // Main program
  190. if (utils::IsModeCLI())
  191. {
  192. $oP = new CLIPage("iTop - Bulk import");
  193. }
  194. else
  195. {
  196. $oP = new CSVPage("iTop - Bulk import");
  197. }
  198. try
  199. {
  200. utils::UseParamFile();
  201. }
  202. catch(Exception $e)
  203. {
  204. $oP->p("Error: ".$e->GetMessage());
  205. $oP->output();
  206. exit -2;
  207. }
  208. if (utils::IsModeCLI())
  209. {
  210. // Next steps:
  211. // specific arguments: 'csvfile'
  212. //
  213. $sAuthUser = ReadMandatoryParam($oP, 'auth_user');
  214. $sAuthPwd = ReadMandatoryParam($oP, 'auth_pwd');
  215. $sCsvFile = ReadMandatoryParam($oP, 'csvfile');
  216. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  217. {
  218. UserRights::Login($sAuthUser); // Login & set the user's language
  219. }
  220. else
  221. {
  222. $oP->p("Access restricted or wrong credentials ('$sAuthUser')");
  223. $oP->output();
  224. exit -1;
  225. }
  226. if (!is_readable($sCsvFile))
  227. {
  228. $oP->p("Input file could not be found or could not be read: '$sCsvFile'");
  229. $oP->output();
  230. exit -1;
  231. }
  232. $sCSVData = file_get_contents($sCsvFile);
  233. }
  234. else
  235. {
  236. $_SESSION['login_mode'] = 'basic';
  237. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  238. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  239. $sCSVData = utils::ReadPostedParam('csvdata');
  240. }
  241. try
  242. {
  243. //////////////////////////////////////////////////
  244. //
  245. // Read parameters
  246. //
  247. $sClass = ReadMandatoryParam($oP, 'class');
  248. $sSep = ReadParam($oP, 'separator');
  249. $sQualifier = ReadParam($oP, 'qualifier');
  250. $sCharSet = ReadParam($oP, 'charset');
  251. $sOutput = ReadParam($oP, 'output');
  252. // $sReportLevel = ReadParam($oP, 'reportlevel');
  253. $sReconcKeys = ReadParam($oP, 'reconciliationkeys');
  254. $sSimulate = ReadParam($oP, 'simulate');
  255. $sComment = ReadParam($oP, 'comment');
  256. //////////////////////////////////////////////////
  257. //
  258. // Check parameters format/consistency
  259. //
  260. if (strlen($sCSVData) == 0)
  261. {
  262. throw new ExchangeException("Missing data - at least one line is expected");
  263. }
  264. if (!MetaModel::IsValidClass($sClass))
  265. {
  266. throw new BulkLoadException("Unknown class: '$sClass'");
  267. }
  268. if (strlen($sSep) > 1)
  269. {
  270. throw new BulkLoadException("Separator is limited to one character, found '$sSep'");
  271. }
  272. if (strlen($sQualifier) > 1)
  273. {
  274. throw new BulkLoadException("Text qualifier is limited to one character, found '$sQualifier'");
  275. }
  276. if (!in_array($sOutput, array('retcode', 'summary', 'details')))
  277. {
  278. throw new BulkLoadException("Unknown output format: '$sOutput'");
  279. }
  280. /*
  281. $aReportLevels = explode('|', $sReportLevel);
  282. foreach($aReportLevels as $sLevel)
  283. {
  284. if (!in_array($sLevel, explode('|', 'errors|warnings|created|changed|unchanged')))
  285. {
  286. throw new BulkLoadException("Unknown level in reporting level: '$sLevel'");
  287. }
  288. }
  289. */
  290. if ($sSimulate == '1')
  291. {
  292. $bSimulate = true;
  293. }
  294. else
  295. {
  296. $bSimulate = false;
  297. }
  298. if (($sOutput == "summary") || ($sOutput == 'details'))
  299. {
  300. $oP->add_comment("Output format: ".$sOutput);
  301. $oP->add_comment("Class: ".$sClass);
  302. $oP->add_comment("Separator: ".$sSep);
  303. $oP->add_comment("Qualifier: ".$sQualifier);
  304. $oP->add_comment("Charset Encoding:".$sCharSet);
  305. $oP->add_comment("Data Size: ".strlen($sCSVData));
  306. }
  307. //////////////////////////////////////////////////
  308. //
  309. // Security
  310. //
  311. if (!UserRights::IsActionAllowed($sClass, UR_ACTION_BULK_MODIFY))
  312. {
  313. throw new SecurityException(Dict::Format('UI:Error:BulkModifyNotAllowedOn_Class', $sClass));
  314. }
  315. //////////////////////////////////////////////////
  316. //
  317. // Make translated column reference
  318. //
  319. // array of <LowercaseTranslatedName> => <ExtendedAttCode>
  320. //
  321. // Examples:
  322. // 'organization' => 'org_id'
  323. // 'organization->name' => 'org_id->name'
  324. //
  325. // Note: it may happen that an external field has the same label as the external key
  326. // in that case, we consider that the external key has precedence
  327. //
  328. $aFriendlyToInternalAttCode = array();
  329. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  330. {
  331. $sFriendlyName = strtolower(BulkChange::GetFriendlyAttCodeName($sClass, $sAttCode));
  332. if (!$oAttDef->IsExternalField() || !array_key_exists($sFriendlyName, $aFriendlyToInternalAttCode))
  333. {
  334. $aFriendlyToInternalAttCode[$sFriendlyName] = $sAttCode;
  335. }
  336. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  337. {
  338. $sRemoteClass = $oAttDef->GetTargetClass();
  339. foreach(MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  340. {
  341. $sAttCodeEx = $sAttCode.'->'.$sRemoteAttCode;
  342. $sFriendlyName = strtolower(BulkChange::GetFriendlyAttCodeName($sClass, $sAttCodeEx));
  343. if (!array_key_exists($sFriendlyName, $aFriendlyToInternalAttCode))
  344. {
  345. $aFriendlyToInternalAttCode[$sFriendlyName] = $sAttCodeEx;
  346. }
  347. }
  348. }
  349. }
  350. //////////////////////////////////////////////////
  351. //
  352. // Parse first line, check attributes, analyse the request
  353. //
  354. if ($sCharSet == 'UTF-8')
  355. {
  356. $sUTF8Data = $sCSVData;
  357. }
  358. else
  359. {
  360. $sUTF8Data = iconv($sCharSet, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  361. }
  362. $oCSVParser = new CSVParser($sUTF8Data, $sSep, $sQualifier);
  363. // Limitation: as the attribute list is in the first line, we can not match external key by a third-party attribute
  364. $aRawFieldList = $oCSVParser->ListFields();
  365. $iColCount = count($aRawFieldList);
  366. // Translate into internal names
  367. $aFieldList = array();
  368. foreach($aRawFieldList as $iFieldId => $sFieldName)
  369. {
  370. $sFieldName = trim($sFieldName);
  371. if (array_key_exists(strtolower($sFieldName), $aFriendlyToInternalAttCode))
  372. {
  373. $aFieldList[$iFieldId] = $aFriendlyToInternalAttCode[strtolower($sFieldName)];
  374. }
  375. else
  376. {
  377. $aFieldList[$iFieldId] = $sFieldName;
  378. }
  379. }
  380. $aAttList = array();
  381. $aExtKeys = array();
  382. foreach($aFieldList as $iFieldId => $sFieldName)
  383. {
  384. $aMatches = array();
  385. if (preg_match('/^(.+)\*$/', $sFieldName, $aMatches))
  386. {
  387. // Ignore any trailing "star" (*) that simply indicates a mandatory field
  388. $sFieldName = $aMatches[1];
  389. }
  390. if (preg_match('/^(.+)->(.+)$/', trim($sFieldName), $aMatches))
  391. {
  392. // The column has been specified as "extkey->attcode"
  393. //
  394. $sExtKeyAttCode = $aMatches[1];
  395. $sRemoteAttCode = $aMatches[2];
  396. if (!MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  397. {
  398. throw new BulkLoadException("Unknown attribute '$sExtKeyAttCode' (class: '$sClass')");
  399. }
  400. $oAtt = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  401. if (!$oAtt->IsExternalKey())
  402. {
  403. throw new BulkLoadException("Not an external key '$sExtKeyAttCode' (class: '$sClass')");
  404. }
  405. $sTargetClass = $oAtt->GetTargetClass();
  406. if (!MetaModel::IsValidAttCode($sTargetClass, $sRemoteAttCode))
  407. {
  408. throw new BulkLoadException("Unknown attribute '$sRemoteAttCode' (key: '$sExtKeyAttCode', class: '$sTargetClass')");
  409. }
  410. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  411. }
  412. elseif ($sFieldName == 'id')
  413. {
  414. $aAttList[$sFieldName] = $iFieldId;
  415. }
  416. else
  417. {
  418. // The column has been specified as "attcode"
  419. //
  420. if (!MetaModel::IsValidAttCode($sClass, $sFieldName))
  421. {
  422. throw new BulkLoadException("Unknown attribute '$sFieldName' (class: '$sClass')");
  423. }
  424. $oAtt = MetaModel::GetAttributeDef($sClass, $sFieldName);
  425. if ($oAtt->IsExternalKey())
  426. {
  427. $aExtKeys[$sFieldName]['id'] = $iFieldId;
  428. $aAttList[$sFieldName] = $iFieldId;
  429. }
  430. elseif ($oAtt->IsExternalField())
  431. {
  432. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  433. $sRemoteAttCode = $oAtt->GetExtAttCode();
  434. $aExtKeys[$sExtKeyAttCode][$sRemoteAttCode] = $iFieldId;
  435. }
  436. else
  437. {
  438. $aAttList[$sFieldName] = $iFieldId;
  439. }
  440. }
  441. }
  442. // Make sure there are some reconciliation keys
  443. //
  444. if (empty($sReconcKeys))
  445. {
  446. $aReconcSpec = array();
  447. // Base reconciliation scheme on the default one
  448. // The reconciliation attributes not present in the data will be ignored
  449. foreach(MetaModel::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  450. {
  451. if (in_array($sReconcKeyAttCode, $aFieldList))
  452. {
  453. $aReconcSpec[] = $sReconcKeyAttCode;
  454. }
  455. }
  456. if (count($aReconcSpec) == 0)
  457. {
  458. 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)).")");
  459. }
  460. $sReconcKeys = implode(',', $aReconcSpec);
  461. }
  462. // Interpret the list of reconciliation keys
  463. //
  464. $aFinalReconcilKeys = array();
  465. $aReconcilKeysReport = array();
  466. foreach (explode(',', $sReconcKeys) as $sReconcKey)
  467. {
  468. $sReconcKey = trim($sReconcKey);
  469. if (empty($sReconcKey)) continue; // skip empty spec
  470. if (array_key_exists(strtolower($sReconcKey), $aFriendlyToInternalAttCode))
  471. {
  472. // Translate from a translated name to codes
  473. $sReconcKey = $aFriendlyToInternalAttCode[strtolower($sReconcKey)];
  474. }
  475. // Check that the reconciliation key is either a given column, or an external key
  476. if (!in_array($sReconcKey, $aFieldList))
  477. {
  478. if (!array_key_exists($sReconcKey, $aExtKeys))
  479. {
  480. throw new BulkLoadException("Reconciliation keys not found in the input columns '$sReconcKey' (class: '$sClass')");
  481. }
  482. }
  483. if (preg_match('/^(.+)->(.+)$/', trim($sReconcKey), $aMatches))
  484. {
  485. // The column has been specified as "extkey->attcode"
  486. //
  487. $sExtKeyAttCode = $aMatches[1];
  488. $sRemoteAttCode = $aMatches[2];
  489. $aFinalReconcilKeys[] = $sExtKeyAttCode;
  490. $aReconcilKeysReport[$sExtKeyAttCode][] = $sRemoteAttCode;
  491. }
  492. else
  493. {
  494. if (!MetaModel::IsValidAttCode($sClass, $sReconcKey))
  495. {
  496. // Safety net: should never happen, but...
  497. throw new BulkLoadException("Unknown reconciliation attribute '$sReconcKey' (class: '$sClass')");
  498. }
  499. $oAtt = MetaModel::GetAttributeDef($sClass, $sReconcKey);
  500. if ($oAtt->IsExternalKey())
  501. {
  502. $aFinalReconcilKeys[] = $sReconcKey;
  503. $aReconcilKeysReport[$sReconcKey][] = 'id';
  504. }
  505. elseif ($oAtt->IsExternalField())
  506. {
  507. $sReconcAttCode = $oAtt->GetKeyAttCode();
  508. $sReconcKeyReport = "$sReconcAttCode ($sReconcKey)";
  509. $aFinalReconcilKeys[] = $sReconcAttCode;
  510. $aReconcilKeysReport[$sReconcAttCode][] = $sReconcKeyReport;
  511. }
  512. else
  513. {
  514. $aFinalReconcilKeys[] = $sReconcKey;
  515. $aReconcilKeysReport[$sReconcKey] = array();
  516. }
  517. }
  518. }
  519. //////////////////////////////////////////////////
  520. //
  521. // Go for parsing and interpretation
  522. //
  523. $aData = $oCSVParser->ToArray();
  524. $iLineCount = count($aData);
  525. if (($sOutput == "summary") || ($sOutput == 'details'))
  526. {
  527. $oP->add_comment("Data Lines: ".$iLineCount);
  528. $oP->add_comment("Simulate: ".($bSimulate ? '1' : '0'));
  529. $oP->add_comment("Columns: ".implode(', ', $aFieldList));
  530. $aReconciliationReport = array();
  531. foreach($aReconcilKeysReport as $sKey => $aKeyDetails)
  532. {
  533. if (count($aKeyDetails) > 0)
  534. {
  535. $aReconciliationReport[] = $sKey.' ('.implode(',', $aKeyDetails).')';
  536. }
  537. else
  538. {
  539. $aReconciliationReport[] = $sKey;
  540. }
  541. }
  542. $oP->add_comment("Reconciliation Keys: ".implode(', ', $aReconciliationReport));
  543. }
  544. $oBulk = new BulkChange(
  545. $sClass,
  546. $aData,
  547. $aAttList,
  548. $aExtKeys,
  549. $aFinalReconcilKeys
  550. );
  551. if ($bSimulate)
  552. {
  553. $oMyChange = null;
  554. }
  555. else
  556. {
  557. $oMyChange = MetaModel::NewObject("CMDBChange");
  558. $oMyChange->Set("date", time());
  559. $sUserString = CMDBChange::GetCurrentUserName();
  560. if (strlen($sComment) > 0)
  561. {
  562. $sMoreInfo = 'Web Service (CSV) - '.$sComment;
  563. }
  564. else
  565. {
  566. $sMoreInfo = 'Web Service (CSV)';
  567. }
  568. $oMyChange->Set("userinfo", $sUserString.', '.$sMoreInfo);
  569. $iChangeId = $oMyChange->DBInsert();
  570. }
  571. $aRes = $oBulk->Process($oMyChange);
  572. //////////////////////////////////////////////////
  573. //
  574. // Compute statistics
  575. //
  576. $iCountErrors = 0;
  577. $iCountWarnings = 0;
  578. $iCountCreations = 0;
  579. $iCountUpdates = 0;
  580. $iCountUnchanged = 0;
  581. foreach($aRes as $iRow => $aRowData)
  582. {
  583. $bWritten = false;
  584. $oStatus = $aRowData["__STATUS__"];
  585. switch(get_class($oStatus))
  586. {
  587. case 'RowStatus_NoChange':
  588. $iCountUnchanged++;
  589. break;
  590. case 'RowStatus_Modify':
  591. $iCountUpdates++;
  592. $bWritten = true;
  593. break;
  594. case 'RowStatus_NewObj':
  595. $iCountCreations++;
  596. $bWritten = true;
  597. break;
  598. case 'RowStatus_Issue':
  599. $iCountErrors++;
  600. break;
  601. }
  602. if ($bWritten)
  603. {
  604. // Something has been done, still there may be some issues to report
  605. foreach($aRowData as $key => $value)
  606. {
  607. if (!is_object($value)) continue;
  608. switch (get_class($value))
  609. {
  610. case 'CellStatus_Void':
  611. case 'CellStatus_Modify':
  612. break;
  613. case 'CellStatus_Issue':
  614. case 'CellStatus_SearchIssue':
  615. case 'CellStatus_NullIssue':
  616. case 'CellStatus_Ambiguous':
  617. $iCountWarnings++;
  618. break;
  619. }
  620. }
  621. }
  622. }
  623. //////////////////////////////////////////////////
  624. //
  625. // Summary of settings and results
  626. //
  627. if ($sOutput == 'retcode')
  628. {
  629. $oP->add($iCountErrors);
  630. }
  631. if (($sOutput == "summary") || ($sOutput == 'details'))
  632. {
  633. // $oP->add_comment("Report level: ".$sReportLevel);
  634. $oP->add_comment("Change tracking comment: ".$sComment);
  635. $oP->add_comment("Issues: ".$iCountErrors);
  636. $oP->add_comment("Warnings: ".$iCountWarnings);
  637. $oP->add_comment("Created: ".$iCountCreations);
  638. $oP->add_comment("Updated: ".$iCountUpdates);
  639. $oP->add_comment("Unchanged: ".$iCountUnchanged);
  640. }
  641. if ($sOutput == 'details')
  642. {
  643. // Setup result presentation
  644. //
  645. $aDisplayConfig = array();
  646. $aDisplayConfig["__LINE__"] = array("label"=>"Line", "description"=>"");
  647. $aDisplayConfig["__STATUS__"] = array("label"=>"Status", "description"=>"");
  648. $aDisplayConfig["__OBJECT_CLASS__"] = array("label"=>"Object Class", "description"=>"");
  649. $aDisplayConfig["__OBJECT_ID__"] = array("label"=>"Object Id", "description"=>"");
  650. foreach($aExtKeys as $sExtKeyAttCode => $aRemoteAtt)
  651. {
  652. $sLabel = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode)->GetLabel();
  653. $aDisplayConfig["$sExtKeyAttCode"] = array("label"=>$sExtKeyAttCode, "description"=>$sLabel." - ext key");
  654. }
  655. foreach($aFinalReconcilKeys as $iCol => $sAttCode)
  656. {
  657. // $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  658. // $aDisplayConfig["$iCol"] = array("label"=>"$sLabel", "description"=>"");
  659. }
  660. foreach ($aAttList as $sAttCode => $iCol)
  661. {
  662. if ($sAttCode == 'id')
  663. {
  664. $sLabel = Dict::S('UI:CSVImport:idField');
  665. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  666. }
  667. else
  668. {
  669. $sLabel = MetaModel::GetAttributeDef($sClass, $sAttCode)->GetLabel();
  670. $aDisplayConfig["$iCol"] = array("label"=>$sAttCode, "description"=>$sLabel);
  671. }
  672. }
  673. $aResultDisp = array(); // to be displayed
  674. foreach($aRes as $iRow => $aRowData)
  675. {
  676. $aRowDisp = array();
  677. $aRowDisp["__LINE__"] = $iRow;
  678. if (is_object($aRowData["__STATUS__"]))
  679. {
  680. $aRowDisp["__STATUS__"] = $aRowData["__STATUS__"]->GetDescription();
  681. }
  682. else
  683. {
  684. $aRowDisp["__STATUS__"] = "*No status available*";
  685. }
  686. if (isset($aRowData["finalclass"]) && isset($aRowData["id"]))
  687. {
  688. $aRowDisp["__OBJECT_CLASS__"] = $aRowData["finalclass"];
  689. $aRowDisp["__OBJECT_ID__"] = $aRowData["id"]->GetDisplayableValue();
  690. }
  691. else
  692. {
  693. $aRowDisp["__OBJECT_CLASS__"] = "n/a";
  694. $aRowDisp["__OBJECT_ID__"] = "n/a";
  695. }
  696. foreach($aRowData as $key => $value)
  697. {
  698. $sKey = (string) $key;
  699. if ($sKey == '__STATUS__') continue;
  700. if ($sKey == 'finalclass') continue;
  701. if ($sKey == 'id') continue;
  702. if (is_object($value))
  703. {
  704. $aRowDisp["$sKey"] = $value->GetDisplayableValue().$value->GetDescription();
  705. }
  706. else
  707. {
  708. $aRowDisp["$sKey"] = $value;
  709. }
  710. }
  711. $aResultDisp[$iRow] = $aRowDisp;
  712. }
  713. $oP->table($aDisplayConfig, $aResultDisp);
  714. }
  715. }
  716. catch(BulkLoadException $e)
  717. {
  718. $oP->add_comment($e->getMessage());
  719. }
  720. catch(SecurityException $e)
  721. {
  722. $oP->add_comment($e->getMessage());
  723. }
  724. catch(Exception $e)
  725. {
  726. $oP->add_comment((string)$e);
  727. }
  728. $oP->output();
  729. ?>