csvimport.php 31 KB

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