csvimport.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. <?php
  2. /**
  3. * CSV Import Page
  4. * Wizard to import CSV (or TSV) data into the database
  5. *
  6. * @package iTopAppplication
  7. * @author Romain Quetiez <romain.quetiez@combodo.com>
  8. * @author Denis Flaven <denis.flaven@combodo.com>
  9. * @license http://www.opensource.org/licenses/lgpl-3.0.html LGPL
  10. * @link http://www.combodo.com/itop iTop
  11. */
  12. ini_set('memory_limit', '256M');
  13. require_once('../application/application.inc.php');
  14. require_once('../application/itopwebpage.class.inc.php');
  15. require_once('../application/startup.inc.php');
  16. require_once('../application/loginwebpage.class.inc.php');
  17. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  18. $oContext = new UserContext();
  19. $oAppContext = new ApplicationContext();
  20. $currentOrganization = utils::ReadParam('org_id', 1);
  21. $iStep = utils::ReadParam('step', 1);
  22. $oPage = new iTopWebPage("iTop - Bulk import", $currentOrganization);
  23. /**
  24. * Helper function to build a select from the list of valid classes for a given action
  25. * @param string $sName The name of the select in the HTML form
  26. * @param string $sDefaulfValue The defaut value (i.e the value selected by default)
  27. * @param integer $iWidthPx The width (in pixels) of the drop-down list
  28. * @param integer $iActionCode The ActionCode (from UserRights) to check for authorization for the classes
  29. * @return string The HTML fragment corresponding to the select tag
  30. */
  31. function GetClassesSelect($sName, $sDefaultValue, $iWidthPx, $iActionCode = null)
  32. {
  33. $sHtml = "<select id=\"select_$sName\" name=\"$sName\">";
  34. $sHtml .= "<option tyle=\"width: ".$iWidthPx."px;\" title=\"Select the class you want to load\" value=\"\">--- select one ---</option>\n";
  35. $aValidClasses = array();
  36. foreach(MetaModel::GetClasses('bizmodel') as $sClassName)
  37. {
  38. if (is_null($iActionCode) || UserRights::IsActionAllowed($sClassName, $iActionCode))
  39. {
  40. $sSelected = ($sClassName == $sDefaultValue) ? " SELECTED" : "";
  41. $sDescription = MetaModel::GetClassDescription($sClassName);
  42. $sDisplayName = MetaModel::GetName($sClassName);
  43. $aValidClasses[$sDisplayName] = "<option style=\"width: ".$iWidthPx."px;\" title=\"$sDescription\" value=\"$sClassName\"$sSelected>$sDisplayName</option>";
  44. }
  45. }
  46. ksort($aValidClasses);
  47. $sHtml .= implode("\n", $aValidClasses);
  48. $sHtml .= "</select>";
  49. return $sHtml;
  50. }
  51. /**
  52. * Helper to 'check' an input in an HTML form if the current value equals the value given
  53. * @param mixed $sCurrentValue The current value to be chacked against the value of the input
  54. * @param mixed $sProposedValue The value of the input
  55. * @param bool $bInverseCondition Set to true to perform the reversed comparison
  56. * @return string Either ' checked' or an empty string
  57. */
  58. function IsChecked($sCurrentValue, $sProposedValue, $bInverseCondition = false)
  59. {
  60. $bCondition = ($sCurrentValue == $sProposedValue);
  61. return ($bCondition xor $bInverseCondition) ? ' checked' : '';
  62. }
  63. /**
  64. * Get the user friendly name for an 'extended' attribute code i.e 'name', becomes 'Name' and 'org_id->name' becomes 'Organization->Name'
  65. * @param string $sClassName The name of the class
  66. * @param string $sAttCodeEx Either an attribute code of ext_key_name->att_code
  67. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  68. */
  69. function GetFriendlyAttCodeName($sClassName, $sAttCodeEx)
  70. {
  71. $sFriendlyName = '';
  72. if (preg_match('/(.+)->(.+)/', $sAttCodeEx, $aMatches) > 0)
  73. {
  74. $Attribute = $aMatches[1];
  75. $sField = $aMatches[2];
  76. $oAttDef = MetaModel::GetAttributeDef($sClassName, $Attribute);
  77. if ($oAttDef->IsExternalKey())
  78. {
  79. $sTargetClass = $oAttDef->GetTargetClass();
  80. $oTargetAttDef = MetaModel::GetAttributeDef($sTargetClass, $sField);
  81. $sFriendlyName = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  82. }
  83. else
  84. {
  85. // hum, hum... should never happen, we'd better raise an exception
  86. throw(new Exception("Internal error: '$sAttCodeEx' is an incorrect code because '$sAttribute' is NOT an external key of the class '$sClassName'."));
  87. }
  88. }
  89. else
  90. {
  91. if ($sAttCodeEx == 'id')
  92. {
  93. $sFriendlyName = 'id (Primary Key)';
  94. }
  95. else
  96. {
  97. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCodeEx);
  98. $sFriendlyName = $oAttDef->GetLabel();
  99. }
  100. }
  101. return $sFriendlyName;
  102. }
  103. /**
  104. * Returns the number of occurences of each char from the set in the specified string
  105. * @param string $sString The input data
  106. * @param array $aSet The set of characters to count
  107. * @return hash 'char' => nb of occurences
  108. */
  109. function CountCharsFromSet($sString, $aSet)
  110. {
  111. $aResult = array();
  112. $aCount = count_chars($sString);
  113. foreach($aSet as $sChar)
  114. {
  115. $aResult[$sChar] = isset($aCount[ord($sChar)]) ? $aCount[ord($sChar)] : 0;
  116. }
  117. return $aResult;
  118. }
  119. /**
  120. * Return the most frequent (and regularly occuring) character among the given set, in the specified lines
  121. * @param array $aCSVData The input data, one entry per line
  122. * @param array $aPossibleSeparators The list of characters to count
  123. * @return string The most frequent character from the set
  124. */
  125. function GuessFromFrequency($aCSVData, $aPossibleSeparators)
  126. {
  127. $iLine = 0;
  128. $iMaxLine = 20; // Process max 20 lines to guess the parameters
  129. foreach($aPossibleSeparators as $sSep)
  130. {
  131. $aGuesses[$sSep]['total'] = $aGuesses[$sSep]['max'] = 0;
  132. $aGuesses[$sSep]['min'] = 999;
  133. }
  134. $aStats = array();
  135. while(($iLine < count($aCSVData)) && ($iLine < $iMaxLine) )
  136. {
  137. if (strlen($aCSVData[$iLine]) > 0)
  138. {
  139. $aStats[$iLine] = CountCharsFromSet($aCSVData[$iLine], $aPossibleSeparators);
  140. }
  141. $iLine++;
  142. }
  143. $iLine = 1;
  144. foreach($aStats as $aLineStats)
  145. {
  146. foreach($aPossibleSeparators as $sSep)
  147. {
  148. $aGuesses[$sSep]['total'] += $aLineStats[$sSep];
  149. if ($aLineStats[$sSep] > $aGuesses[$sSep]['max']) $aGuesses[$sSep]['max'] = $aLineStats[$sSep];
  150. if ($aLineStats[$sSep] < $aGuesses[$sSep]['min']) $aGuesses[$sSep]['min'] = $aLineStats[$sSep];
  151. }
  152. $iLine++;
  153. }
  154. $aScores = array();
  155. foreach($aGuesses as $sSep => $aData)
  156. {
  157. $aScores[$sSep] = $aData['total'] + $aData['max'] - $aData['min'];
  158. }
  159. arsort($aScores, SORT_NUMERIC); // Sort the array, higher scores first
  160. $aKeys = array_keys($aScores);
  161. $sSeparator = $aKeys[0]; // Take the first key, the one with the best score
  162. return $sSeparator;
  163. }
  164. /**
  165. * Try to predict the CSV parameters based on the input data
  166. * @param string $sCSVData The input data
  167. * @return hash 'separator' => the_guessed_separator, 'qualifier' => the_guessed_text_qualifier
  168. */
  169. function GuessParameters($sCSVData)
  170. {
  171. $aData = explode("\n", $sCSVData);
  172. $sSeparator = GuessFromFrequency($aData, array("\t", ',', ';', '|')); // Guess the most frequent (and regular) character on each line
  173. $sQualifier = GuessFromFrequency($aData, array('"', "'")); // Guess the most frequent (and regular) character on each line
  174. return array('separator' => $sSeparator, 'qualifier' => $sQualifier);
  175. }
  176. /**
  177. * Process the CSV data, for real or as a simulation
  178. * @param WebPage $oPage The page used to display the wizard
  179. * @param UserContext $oContext The current user context
  180. * @param bool $bSimulate Whether or not to simulate the data load
  181. * @return array The CSV lines in error that were rejected from the load (with the header line - if any) or null
  182. */
  183. function ProcessCSVData(WebPage $oPage, UserContext $oContext, $bSimulate = true)
  184. {
  185. $aResult = array();
  186. $sCSVData = utils::ReadParam('csvdata', '');
  187. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');
  188. $sSeparator = utils::ReadParam('separator', ',');
  189. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  190. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  191. $iRealSkippedLines = $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  192. $sClassName = utils::ReadParam('class_name', '');
  193. $aFieldsMapping = utils::ReadParam('field', array());
  194. $aSearchFields = utils::ReadParam('search_field', array());
  195. $iCurrentStep = $bSimulate ? 4 : 5;
  196. // Parse the data set
  197. $oCSVParser = new CSVParser($sCSVData, $sSeparator, $sTextQualifier);
  198. $aData = $oCSVParser->ToArray($iSkippedLines);
  199. if ($bHeaderLine)
  200. {
  201. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier, array_shift($aData)).$sTextQualifier; // Remove the first line and store it in case of error
  202. $iRealSkippedLines++;
  203. }
  204. // Format for the line numbers
  205. $sMaxLen = (strlen(''.count($aData)) < 3) ? 3 : strlen(''.count($aData)); // Pad line numbers to the appropriate number of chars, but at least 3
  206. // Compute the list of search/reconciliation criteria
  207. $aSearchKeys = array();
  208. foreach($aSearchFields as $index => $sDummy)
  209. {
  210. $sSearchField = $aFieldsMapping[$index];
  211. $aMatches = array();
  212. if (preg_match('/(.+)->(.+)/', $sSearchField, $aMatches) > 0)
  213. {
  214. $sSearchField = $aMatches[1];
  215. $aSearchKeys[$aMatches[1]] = '';
  216. }
  217. else
  218. {
  219. $aSearchKeys[$sSearchField] = '';
  220. }
  221. if (!MetaModel::IsValidFilterCode($sClassName, $sSearchField))
  222. {
  223. // Remove invalid or unmapped search fields
  224. $aSearchFields[$index] = null;
  225. unset($aSearchKeys[$sSearchField]);
  226. }
  227. }
  228. // Compute the list of fields and external keys to process
  229. $aExtKeys = array();
  230. $aAttributes = array();
  231. $aExternalKeysByColumn = array();
  232. foreach($aFieldsMapping as $iNumber => $sAttCode)
  233. {
  234. $iIndex = $iNumber-1;
  235. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  236. {
  237. if (preg_match('/(.+)->(.+)/', $sAttCode, $aMatches) > 0)
  238. {
  239. $sAttribute = $aMatches[1];
  240. $sField = $aMatches[2];
  241. $aExtKeys[$sAttribute][$sField] = $iIndex;
  242. $aExternalKeysByColumn[$iIndex] = $sAttribute;
  243. }
  244. else
  245. {
  246. if ($sAttCode == 'id')
  247. {
  248. $aAttributes['id'] = $iIndex;
  249. }
  250. else
  251. {
  252. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  253. if ($oAttDef->IsExternalKey())
  254. {
  255. $aExtKeys[$sAttCode]['id'] = $iIndex;
  256. $aExternalKeysByColumn[$iIndex] = $sAttCode;
  257. }
  258. else
  259. {
  260. $aAttributes[$sAttCode] = $iIndex;
  261. }
  262. }
  263. }
  264. }
  265. }
  266. $oMyChange = null;
  267. if (!$bSimulate)
  268. {
  269. // We're doing it for real, let's create a change
  270. $oMyChange = MetaModel::NewObject("CMDBChange");
  271. $oMyChange->Set("date", time());
  272. if (UserRights::GetUser() != UserRights::GetRealUser())
  273. {
  274. $sUserString = UserRights::GetRealUser()." on behalf of ".UserRights::GetUser();
  275. }
  276. else
  277. {
  278. $sUserString = UserRights::GetUser();
  279. }
  280. $oMyChange->Set("userinfo", $sUserString);
  281. $iChangeId = $oMyChange->DBInsert();
  282. }
  283. $oBulk = new BulkChange(
  284. $sClassName,
  285. $aData,
  286. $aAttributes,
  287. $aExtKeys,
  288. array_keys($aSearchKeys)
  289. );
  290. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  291. $aRes = $oBulk->Process($oMyChange);
  292. $sHtml = '<table id="bulk_preview">';
  293. $sHtml .= '<tr><th>Line</th>';
  294. $sHtml .= '<th>Status</th>';
  295. $sHtml .= '<th>Object</th>';
  296. foreach($aFieldsMapping as $iNumber => $sAttCode)
  297. {
  298. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  299. {
  300. $sHtml .= "<th>".GetFriendlyAttCodeName($sClassName, $sAttCode)."</th>";
  301. }
  302. }
  303. $sHtml .= '<th>Message</th>';
  304. $sHtml .= '</tr>';
  305. $iLine = 0;
  306. $iErrors = 0;
  307. $iCreated = 0;
  308. $iModified = 0;
  309. $iUnchanged = 0;
  310. foreach($aData as $aRow)
  311. {
  312. $oStatus = $aRes[$iLine]['__STATUS__'];
  313. $sUrl = '';
  314. $sMessage = '';
  315. $sCSSRowClass = '';
  316. $sCSSMessageClass = 'cell_ok';
  317. switch(get_class($oStatus))
  318. {
  319. case 'RowStatus_NoChange':
  320. $iUnchanged++;
  321. $sFinalClass = $aRes[$iLine]['finalclass'];
  322. $oObj = $oContext->GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  323. $sUrl = $oObj->GetHyperlink();
  324. $sStatus = '<img src="../images/unchanged.png" title="Unchanged">';
  325. $sCSSRowClass = 'row_unchanged';
  326. break;
  327. case 'RowStatus_Modify':
  328. $iModified++;
  329. $sFinalClass = $aRes[$iLine]['finalclass'];
  330. $oObj = $oContext->GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  331. $sUrl = $oObj->GetHyperlink();
  332. $sStatus = '<img src="../images/modified.png" title="Modified">';
  333. $sCSSRowClass = 'row_modified';
  334. break;
  335. case 'RowStatus_NewObj':
  336. $iCreated++;
  337. $sFinalClass = $aRes[$iLine]['finalclass'];
  338. $sStatus = '<img src="../images/added.png" title="Created">';
  339. $sCSSRowClass = 'row_added';
  340. if ($bSimulate)
  341. {
  342. $sMessage = 'Object will be created';
  343. }
  344. else
  345. {
  346. $sFinalClass = $aRes[$iLine]['finalclass'];
  347. $oObj = $oContext->GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  348. $sUrl = $oObj->GetHyperlink();
  349. $sMessage = 'Object created';
  350. }
  351. break;
  352. case 'RowStatus_Issue':
  353. $iErrors++;
  354. $sMessage .= $oPage->GetP($oStatus->GetDescription());
  355. $sStatus = '<img src="../images/error.png" title="Error">';
  356. $sCSSMessageClass = 'cell_error';
  357. $sCSSRowClass = 'row_error';
  358. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier,$aRow).$sTextQualifier; // Remove the first line and store it in case of error
  359. break;
  360. }
  361. $sHtml .= '<tr class="'.$sCSSRowClass.'">';
  362. $sHtml .= "<td>".sprintf("%0{$sMaxLen}d", 1+$iLine+$iRealSkippedLines)."</td>";
  363. $sHtml .= "<td>$sStatus</td>";
  364. $sHtml .= "<td>$sUrl</td>";
  365. foreach($aFieldsMapping as $iNumber => $sAttCode)
  366. {
  367. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  368. {
  369. $oCellStatus = $aRes[$iLine][$iNumber -1];
  370. $sCellMessage = '';
  371. if (isset($aExternalKeysByColumn[$iNumber -1]))
  372. {
  373. $sExtKeyName = $aExternalKeysByColumn[$iNumber -1];
  374. $oExtKeyCellStatus = $aRes[$iLine][$sExtKeyName];
  375. switch(get_class($oExtKeyCellStatus))
  376. {
  377. case 'CellStatus_Issue':
  378. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  379. break;
  380. case 'CellStatus_Ambiguous':
  381. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  382. break;
  383. default:
  384. // Do nothing
  385. }
  386. }
  387. switch(get_class($oCellStatus))
  388. {
  389. case 'CellStatus_Issue':
  390. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  391. $sHtml .= '<td class="cell_error">ERROR: '.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').$sCellMessage.'</td>';
  392. break;
  393. case 'CellStatus_Ambiguous':
  394. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  395. $sHtml .= '<td class="cell_error">AMBIGUOUS: '.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').$sCellMessage.'</td>';
  396. break;
  397. case 'CellStatus_Modify':
  398. $sHtml .= '<td class="cell_modified"><b>'.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').'</b></td>';
  399. break;
  400. default:
  401. $sHtml .= '<td class="cell_ok">'.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').$sCellMessage.'</td>';
  402. }
  403. }
  404. }
  405. $sHtml .= "<td class=\"$sCSSMessageClass\">$sMessage</td>";
  406. $iLine++;
  407. $sHtml .= '</tr>';
  408. }
  409. $sHtml .= '</table>';
  410. $oPage->add('<div class="wizContainer">');
  411. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" onSubmit="return CheckValues()">');
  412. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  413. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  414. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  415. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  416. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  417. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  418. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  419. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  420. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  421. $oPage->add('<input type="hidden" name="_charset_"/>');
  422. foreach($aFieldsMapping as $iNumber => $sAttCode)
  423. {
  424. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  425. }
  426. foreach($aSearchFields as $index => $sDummy)
  427. {
  428. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  429. }
  430. $aFieldsMapping = utils::ReadParam('field', array());
  431. $aSearchFields = utils::ReadParam('search_field', array());
  432. $aDisplayFilters = array();
  433. if ($bSimulate)
  434. {
  435. $aDisplayFilters['unchanged'] = '%d objects(s) will stay unchanged.';
  436. $aDisplayFilters['modified'] = '%d objects(s) will stay be modified.';
  437. $aDisplayFilters['added'] = '%d objects(s) will be added.';
  438. $aDisplayFilters['errors'] = '%d objects(s) will have errors.';
  439. }
  440. else
  441. {
  442. $aDisplayFilters['unchanged'] = '%d objects(s) remained unchanged.';
  443. $aDisplayFilters['modified'] = '%d objects(s) were modified.';
  444. $aDisplayFilters['added'] = '%d objects(s) were added.';
  445. $aDisplayFilters['errors'] = '%d objects(s) had errors.';
  446. }
  447. $oPage->add('<p><input type="checkbox" checked id="show_unchanged" onClick="ToggleRows(\'row_unchanged\')"/>&nbsp;<img src="../images/unchanged.png">&nbsp;'.sprintf($aDisplayFilters['unchanged'], $iUnchanged).'&nbsp&nbsp;');
  448. $oPage->add('<input type="checkbox" checked id="show_modified" onClick="ToggleRows(\'row_modified\')"/>&nbsp;<img src="../images/modified.png">&nbsp;'.sprintf($aDisplayFilters['modified'], $iModified).'&nbsp&nbsp;');
  449. $oPage->add('<input type="checkbox" checked id="show_created" onClick="ToggleRows(\'row_added\')"/>&nbsp;<img src="../images/added.png">&nbsp;'.sprintf($aDisplayFilters['added'], $iCreated).'&nbsp&nbsp;');
  450. $oPage->add('<input type="checkbox" checked id="show_errors" onClick="ToggleRows(\'row_error\')"/>&nbsp;<img src="../images/error.png">&nbsp;'.sprintf($aDisplayFilters['errors'], $iErrors).'</p>');
  451. $oPage->add('<div style="overflow-y:auto">');
  452. $oPage->add($sHtml);
  453. $oPage->add('</div> <!-- end of preview -->');
  454. $oPage->add('<p><input type="button" value=" << Back " onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  455. if ($bSimulate)
  456. {
  457. $oPage->add('<input type="submit" value=" Run the Import ! "/></p>');
  458. }
  459. else
  460. {
  461. $oPage->add('<input type="submit" value=" Done "/></p>');
  462. }
  463. $oPage->add('</form>');
  464. $oPage->add('</div> <!-- end of wizForm -->');
  465. $oPage->add_script(
  466. <<< EOF
  467. function CSVGoBack()
  468. {
  469. $('input[name=step]').val($iCurrentStep-1);
  470. $('#wizForm').submit();
  471. }
  472. function ToggleRows(sCSSClass)
  473. {
  474. $('.'+sCSSClass).toggle();
  475. }
  476. EOF
  477. );
  478. if ($iErrors > 0)
  479. {
  480. return $aResult;
  481. }
  482. else
  483. {
  484. return null;
  485. }
  486. }
  487. /**
  488. * Perform the actual load of the CSV data and display the results
  489. * @param WebPage $oPage The web page to display the wizard
  490. * @param UserContext $oContext Current user's context
  491. * @return void
  492. */
  493. function LoadData(WebPage $oPage, UserContext $oContext)
  494. {
  495. $oPage->add('<h2>Step 5 of 5: Import completed</h2>');
  496. $aResult = ProcessCSVData($oPage, $oContext, false /* simulate = false */);
  497. if (is_array($aResult))
  498. {
  499. $oPage->StartCollapsibleSection("Lines that could not be loaded:", false);
  500. $oPage->p('The following lines have not been imported because they contain errors');
  501. $oPage->add('<textarea rows="30" cols="100">');
  502. $oPage->add(htmlentities(implode("\n", $aResult), ENT_QUOTES, 'UTF-8'));
  503. $oPage->add('</textarea>');
  504. $oPage->EndCollapsibleSection();
  505. }
  506. }
  507. /**
  508. * Simulate the load of the CSV data and display the results
  509. * @param WebPage $oPage The web page to display the wizard
  510. * @param UserContext $oContext Current user's context
  511. * @return void
  512. */
  513. function Preview(WebPage $oPage, UserContext $oContext)
  514. {
  515. $oPage->add('<h2>Step 4 of 5: Import simulation</h2>');
  516. ProcessCSVData($oPage, $oContext, true /* simulate */);
  517. }
  518. /**
  519. * Select the mapping between the CSV column and the fields of the objects
  520. * @param WebPage $oPage The web page to display the wizard
  521. * @return void
  522. */
  523. function SelectMapping(WebPage $oPage)
  524. {
  525. $sCSVData = utils::ReadParam('csvdata', '');
  526. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');;
  527. $sSeparator = utils::ReadParam('separator', ',');
  528. if ($sSeparator == 'tab') $sSeparator = "\t";
  529. if ($sSeparator == 'other')
  530. {
  531. $sSeparator = utils::ReadParam('other_separator', ',');
  532. }
  533. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  534. if ($sTextQualifier == 'other')
  535. {
  536. $sTextQualifier = utils::ReadParam('other_qualifier', '"');
  537. }
  538. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  539. $iSkippedLines = 0;
  540. if (utils::ReadParam('box_skiplines', '0') == 1)
  541. {
  542. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  543. }
  544. $sClassName = utils::ReadParam('class_name', '');
  545. $oPage->add('<h2>Step 3 of 5: Data mapping</h2>');
  546. $oPage->add('<div class="wizContainer">');
  547. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" onSubmit="return CheckValues()"><p>Select the class to import: ');
  548. $oPage->add(GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY).'</p>');
  549. $oPage->add('<div id="mapping"><p><br/>Select a class to configure the mapping<br/></p></div>');
  550. $oPage->add('<input type="hidden" name="step" value="4"/>');
  551. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  552. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  553. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  554. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  555. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  556. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  557. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  558. $oPage->add('<input type="hidden" name="_charset_"/>');
  559. $oPage->add('<p><input type="button" value=" << Back " onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  560. $oPage->add('<input type="submit" value=" Simulate Import >> "/></p>');
  561. $oPage->add('</form>');
  562. $oPage->add('</div>');
  563. $oPage->add_ready_script(
  564. <<<EOF
  565. $('#select_class_name').change( DoMapping );
  566. EOF
  567. );
  568. if ($sClassName != '')
  569. {
  570. $oPage->add_ready_script("DoMapping();"); // There is already a class selected, run the mapping
  571. }
  572. $oPage->add_script(
  573. <<<EOF
  574. function CSVGoBack()
  575. {
  576. $('input[name=step]').val(2);
  577. $('#wizForm').submit();
  578. }
  579. var ajax_request = null;
  580. function DoMapping()
  581. {
  582. var separator = $('input[name=separator]').val();
  583. var text_qualifier = $('input[name=text_qualifier]').val();
  584. var header_line = $('input[name=header_line]').val();
  585. var nb_lines_skipped = $('input[name=nb_skipped_lines]').val();
  586. var csv_data = $('input[name=csvdata]').val();
  587. var class_name = $('select[name=class_name]').val();
  588. $('#mapping').block();
  589. // Make sure that we cancel any pending request before issuing another
  590. // since responses may arrive in arbitrary order
  591. if (ajax_request != null)
  592. {
  593. ajax_request.abort();
  594. ajax_request = null;
  595. }
  596. ajax_request = $.post('ajax.csvimport.php',
  597. { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator, qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, class_name: class_name },
  598. function(data) {
  599. $('#mapping').empty();
  600. $('#mapping').append(data);
  601. $('#mapping').unblock();
  602. }
  603. );
  604. }
  605. function CheckValues()
  606. {
  607. bResult = true;
  608. bMappingOk = true;
  609. bSearchOk = false;
  610. $('select[name^=field]').each( function() {
  611. if ($(this).val() == '')
  612. {
  613. this.style.backgroundColor = '#fcc';
  614. bMappingOk = false;
  615. bResult = false;
  616. }
  617. else
  618. {
  619. this.style.backgroundColor = 'ThreeDFace';
  620. }
  621. });
  622. // At least one search field must be checked
  623. $('input[name^=search]:checked').each( function() {
  624. bSearchOk = true;
  625. });
  626. if (!bMappingOk)
  627. {
  628. alert("Please select a mapping for every field.");
  629. }
  630. if (!bSearchOk)
  631. {
  632. bResult = false;
  633. alert("Please select at least one search criteria.");
  634. }
  635. return bResult;
  636. }
  637. EOF
  638. );
  639. }
  640. /**
  641. * Select the options of the CSV load and check for CSV parsing errors
  642. * @param WebPage $oPage The current web page
  643. * @return void
  644. */
  645. function SelectOptions(WebPage $oPage)
  646. {
  647. $sOperation = utils::ReadParam('operation', 'csv_data', 'post');
  648. $sCSVData = '';
  649. switch($sOperation)
  650. {
  651. case 'file_upload':
  652. $oDocument = utils::ReadPostedDocument('csvdata');
  653. if (!$oDocument->IsEmpty())
  654. {
  655. $sCSVData = $oDocument->GetData();
  656. }
  657. break;
  658. default:
  659. $sCSVData = utils::ReadParam('csvdata', '', 'post');
  660. }
  661. $aGuesses = GuessParameters($sCSVData); // Try to predict the parameters, based on the input data
  662. $sSeparator = utils::ReadParam('separator', '');
  663. if ($sSeparator == '') // May be set to an empty value by the previous page
  664. {
  665. $sSeparator = $aGuesses['separator'];
  666. }
  667. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  668. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  669. if ($sSeparator == 'tab') $sSeparator = "\t";
  670. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  671. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  672. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  673. {
  674. $sTextQualifier = $aGuesses['qualifier'];
  675. }
  676. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  677. $bHeaderLine = utils::ReadParam('header_line', 0);
  678. $sClassName = utils::ReadParam('class_name', '');
  679. // Create a truncated version of the data used for the fast preview
  680. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  681. $iMaxLines = 20;
  682. $iMaxLen = strlen($sCSVData);
  683. $iCurPos = true;
  684. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  685. {
  686. $pos = strpos($sCSVData, "\n", $iCurPos);
  687. if ($pos !== false)
  688. {
  689. $iCurPos = 1+$pos;
  690. }
  691. else
  692. {
  693. $iCurPos = strlen($sCSVData);
  694. $iMaxLines = 1;
  695. }
  696. $iMaxLines--;
  697. }
  698. $sCSVDataTruncated = substr($sCSVData, 0, $iCurPos);
  699. $oPage->add('<h2>Step 2 of 5: CSV data options</h2>');
  700. $oPage->add('<div class="wizContainer">');
  701. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;background:#E8F3CF">');
  702. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  703. $oPage->add('<h3>Separator character:</h3>');
  704. $oPage->add('<p><input type="radio" name="separator" value="," onChange="DoPreview()"'.IsChecked($sSeparator, ',').'/> , (comma)<br/>');
  705. $oPage->add('<input type="radio" name="separator" value=";" onChange="DoPreview()"'.IsChecked($sSeparator, ';').'/> ; (semicolon)<br/>');
  706. $oPage->add('<input type="radio" name="separator" value="tab" onChange="DoPreview()"'.IsChecked($sSeparator, "\t").'/> tab<br/>');
  707. $oPage->add('<input type="radio" name="separator" value="other" onChange="DoPreview()"'.IsChecked($sOtherSeparator, '', true).'/> other: <input type="text" size="3" maxlength="1" name="other_separator" id="other_separator" value="'.$sOtherSeparator.'" onChange="DoPreview()"/>');
  708. $oPage->add('</p>');
  709. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;background:#E8F3CF">');
  710. $oPage->add('<h3>Text qualifier character:</h3>');
  711. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onChange="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> " (double quote)<br/>');
  712. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onChange="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> \' (simple quote)<br/>');
  713. $oPage->add('<input type="radio" name="text_qualifier" value="other" onChange="DoPreview()"'.IsChecked($sOtherTextQualifier, '', true).'/> other: <input type="text" size="3" maxlength="1" name="other_qualifier" value="'.htmlentities($sOtherTextQualifier, ENT_QUOTES, 'UTF-8').'" onChange="DoPreview()"/>');
  714. $oPage->add('</p>');
  715. $oPage->add('</td><td style="vertical-align:top;background:#E8F3CF">');
  716. $oPage->add('<h3>Comments and header:</h3>');
  717. $oPage->add('<p><input type="checkbox" name="header_line" id="box_header" value="1" onChange="DoPreview()"'.IsChecked($bHeaderLine, 1).'/> Treat the first line as a header (column names)<p>');
  718. $oPage->add('<p><input type="checkbox" name="box_skiplines" value="1" id="box_skiplines" onChange="DoPreview()"'.IsChecked($bBoxSkipLines, 1).'/> Skip <input type="text" size=2 name="nb_skipped_lines" id="nb_skipped_lines" onChange="DoPreview()" value="'.$iSkippedLines.'"> line(s) at the beginning of the file<p>');
  719. $oPage->add('</td></tr></table>');
  720. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  721. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  722. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  723. $oPage->add('<input type="hidden" name="step" value="3"/>');
  724. $oPage->add('<div id="preview">');
  725. $oPage->add('<p style="text-align:center">Data Preview</p>');
  726. $oPage->add('</div>');
  727. $oPage->add('<input type="button" value=" << Back " onClick="GoBack()"/>');
  728. $oPage->add('<input type="submit" value=" Next >> "/>');
  729. $oPage->add('</form>');
  730. $oPage->add('</div>');
  731. $oPage->add_script(
  732. <<<EOF
  733. function GoBack()
  734. {
  735. $('input[name=step]').val(1);
  736. $('#wizForm').submit();
  737. }
  738. var ajax_request = null;
  739. function DoPreview()
  740. {
  741. var separator = $('input[name=separator]:checked').val();
  742. if (separator == 'other')
  743. {
  744. separator = $('#other_separator').val();
  745. }
  746. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  747. if (text_qualifier == 'other')
  748. {
  749. text_qualifier = $('#other_qualifier').val();
  750. }
  751. var nb_lines_skipped = 0;
  752. if ($('#box_skiplines:checked').val() != null)
  753. {
  754. nb_lines_skipped = $('#nb_skipped_lines').val();
  755. }
  756. var header_line = 0;
  757. if ($('#box_header:checked').val() != null)
  758. {
  759. header_line = 1;
  760. }
  761. $('#preview').block();
  762. // Make sure that we cancel any pending request before issuing another
  763. // since responses may arrive in arbitrary order
  764. if (ajax_request != null)
  765. {
  766. ajax_request.abort();
  767. ajax_request = null;
  768. }
  769. ajax_request = $.post('ajax.csvimport.php',
  770. { operation: 'parser_preview', enctype: 'multipart/form-data', csvdata: $("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line },
  771. function(data) {
  772. $('#preview').empty();
  773. $('#preview').append(data);
  774. $('#preview').unblock();
  775. }
  776. );
  777. }
  778. EOF
  779. );
  780. $oPage->add_ready_script('DoPreview();');
  781. }
  782. /**
  783. * Prompt for the data to be loaded (either via a file or a copy/paste)
  784. * @param WebPage $oPage The current web page
  785. * @return void
  786. */
  787. function Welcome(iTopWebPage $oPage)
  788. {
  789. $oPage->add("<div><p><h1>CSV import wizard</h1></p></div>\n");
  790. $oPage->AddTabContainer('tabs1');
  791. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>Select the file to import:</p>'.
  792. '<p><input type="file" name="csvdata"/></p>'.
  793. '<p><input type="submit" value=" Next >> "/></p>'.
  794. '<p><input type="hidden" name="step" value="2"/></p>'.
  795. '<p><input type="hidden" name="operation" value="file_upload"/></p>'.
  796. '</form></div>';
  797. $oPage->AddToTab('tabs1', "Load from a file", $sFileLoadHtml);
  798. $sCSVData = utils::ReadParam('csvdata', '');
  799. $sSeparator = utils::ReadParam('separator', '');
  800. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  801. $bHeaderLine = utils::ReadParam('header_line', true);
  802. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  803. $sClassName = utils::ReadParam('class_name', '');
  804. $sCSVData = utils::ReadParam('csvdata', '');
  805. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>Paste the data to import:</p>'.
  806. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>'.
  807. '<p><input type="submit" value=" Next >> "/></p>'.
  808. '<input type="hidden" name="step" value="2"/>'.
  809. '<input type="hidden" name="operation" value="csv_data"/>'.
  810. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  811. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  812. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  813. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  814. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  815. '</form></div>';
  816. $oPage->AddToTab('tabs1', "Copy and paste data", $sPasteDataHtml);
  817. $sTemplateHtml = '<div><p>Pick the template do download: ';
  818. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  819. $sTemplateHtml .= '</div>';
  820. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  821. $sTemplateHtml .= '</div>';
  822. $oPage->AddToTab('tabs1', "Templates", $sTemplateHtml);
  823. $oPage->add_script(
  824. <<<EOF
  825. var ajax_request = null;
  826. function DisplayTemplate(sClassName) {
  827. $('#template').block();
  828. // Make sure that we cancel any pending request before issuing another
  829. // since responses may arrive in arbitrary order
  830. if (ajax_request != null)
  831. {
  832. ajax_request.abort();
  833. ajax_request = null;
  834. }
  835. ajax_request = $.get('ajax.csvimport.php',
  836. { operation: 'get_csv_template', class_name: sClassName },
  837. function(data) {
  838. $('#template').empty();
  839. $('#template').append(data);
  840. $('#template').unblock();
  841. }
  842. );
  843. }
  844. EOF
  845. );
  846. $oPage->add_ready_script(
  847. <<<EOF
  848. $('#select_template_class').change( function() {
  849. DisplayTemplate(this.value);
  850. });
  851. EOF
  852. );
  853. }
  854. switch($iStep)
  855. {
  856. case 5:
  857. LoadData($oPage, $oContext);
  858. break;
  859. case 4:
  860. Preview($oPage, $oContext);
  861. break;
  862. case 3:
  863. SelectMapping($oPage);
  864. break;
  865. case 2:
  866. SelectOptions($oPage);
  867. break;
  868. case 1:
  869. case 6: // Loop back here when we are done
  870. default:
  871. Welcome($oPage);
  872. }
  873. $oPage->output();
  874. ?>