csvimport.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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. $iChangeId = $oMyChange->DBInsert();
  279. }
  280. $oBulk = new BulkChange(
  281. $sClassName,
  282. $aData,
  283. $aAttributes,
  284. $aExtKeys,
  285. array_keys($aSearchKeys)
  286. );
  287. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated).'"/>');
  288. $aRes = $oBulk->Process($oMyChange);
  289. $sHtml = '<table id="bulk_preview">';
  290. $sHtml .= '<tr><th>Line</th>';
  291. $sHtml .= '<th>Status</th>';
  292. $sHtml .= '<th>Object</th>';
  293. foreach($aFieldsMapping as $iNumber => $sAttCode)
  294. {
  295. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  296. {
  297. $sHtml .= "<th>".GetFriendlyAttCodeName($sClassName, $sAttCode)."</th>";
  298. }
  299. }
  300. $sHtml .= '<th>Message</th>';
  301. $sHtml .= '</tr>';
  302. $iLine = 0;
  303. $iErrors = 0;
  304. $iCreated = 0;
  305. $iModified = 0;
  306. $iUnchanged = 0;
  307. foreach($aData as $aRow)
  308. {
  309. $oStatus = $aRes[$iLine]['__STATUS__'];
  310. $sUrl = '';
  311. $sMessage = '';
  312. $sCSSRowClass = '';
  313. $sCSSMessageClass = 'cell_ok';
  314. switch(get_class($oStatus))
  315. {
  316. case 'RowStatus_NoChange':
  317. $iUnchanged++;
  318. $sFinalClass = $aRes[$iLine]['finalclass'];
  319. $oObj = $oContext->GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  320. $sUrl = $oObj->GetHyperlink();
  321. $sStatus = '<img src="../images/unchanged.png" title="Unchanged">';
  322. $sCSSRowClass = 'row_unchanged';
  323. break;
  324. case 'RowStatus_Modify':
  325. $iModified++;
  326. $sFinalClass = $aRes[$iLine]['finalclass'];
  327. $oObj = $oContext->GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  328. $sUrl = $oObj->GetHyperlink();
  329. $sStatus = '<img src="../images/modified.png" title="Modified">';
  330. $sCSSRowClass = 'row_modified';
  331. break;
  332. case 'RowStatus_NewObj':
  333. $iCreated++;
  334. $sFinalClass = $aRes[$iLine]['finalclass'];
  335. $sStatus = '<img src="../images/added.png" title="Created">';
  336. $sCSSRowClass = 'row_added';
  337. if ($bSimulate)
  338. {
  339. $sMessage = 'Object will be created';
  340. }
  341. else
  342. {
  343. $sFinalClass = $aRes[$iLine]['finalclass'];
  344. $oObj = $oContext->GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  345. $sUrl = $oObj->GetHyperlink();
  346. $sMessage = 'Object created';
  347. }
  348. break;
  349. case 'RowStatus_Issue':
  350. $iErrors++;
  351. $sMessage .= $oPage->GetP($oStatus->GetDescription());
  352. $sStatus = '<img src="../images/error.png" title="Error">';
  353. $sCSSMessageClass = 'cell_error';
  354. $sCSSRowClass = 'row_error';
  355. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier,$aRow).$sTextQualifier; // Remove the first line and store it in case of error
  356. break;
  357. }
  358. $sHtml .= '<tr class="'.$sCSSRowClass.'">';
  359. $sHtml .= "<td>".sprintf("%0{$sMaxLen}d", 1+$iLine+$iRealSkippedLines)."</td>";
  360. $sHtml .= "<td>$sStatus</td>";
  361. $sHtml .= "<td>$sUrl</td>";
  362. foreach($aFieldsMapping as $iNumber => $sAttCode)
  363. {
  364. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  365. {
  366. $oCellStatus = $aRes[$iLine][$iNumber -1];
  367. $sCellMessage = '';
  368. if (isset($aExternalKeysByColumn[$iNumber -1]))
  369. {
  370. $sExtKeyName = $aExternalKeysByColumn[$iNumber -1];
  371. $oExtKeyCellStatus = $aRes[$iLine][$sExtKeyName];
  372. switch(get_class($oExtKeyCellStatus))
  373. {
  374. case 'CellStatus_Issue':
  375. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  376. break;
  377. case 'CellStatus_Ambiguous':
  378. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  379. break;
  380. default:
  381. // Do nothing
  382. }
  383. }
  384. switch(get_class($oCellStatus))
  385. {
  386. case 'CellStatus_Issue':
  387. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  388. $sHtml .= '<td class="cell_error">ERROR: '.htmlentities($aData[$iLine][$iNumber-1]).$sCellMessage.'</td>';
  389. break;
  390. case 'CellStatus_Ambiguous':
  391. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  392. $sHtml .= '<td class="cell_error">AMBIGUOUS: '.htmlentities($aData[$iLine][$iNumber-1]).$sCellMessage.'</td>';
  393. break;
  394. case 'CellStatus_Modify':
  395. $sHtml .= '<td class="cell_modified"><b>'.htmlentities($aData[$iLine][$iNumber-1]).'</b></td>';
  396. break;
  397. default:
  398. $sHtml .= '<td class="cell_ok">'.htmlentities($aData[$iLine][$iNumber-1]).$sCellMessage.'</td>';
  399. }
  400. }
  401. }
  402. $sHtml .= "<td class=\"$sCSSMessageClass\">$sMessage</td>";
  403. $iLine++;
  404. $sHtml .= '</tr>';
  405. }
  406. $sHtml .= '</table>';
  407. $oPage->add('<div class="wizContainer">');
  408. $oPage->add('<form id="wizForm" method="post" onSubmit="return CheckValues()">');
  409. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  410. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator).'"/>');
  411. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier).'"/>');
  412. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  413. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  414. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData).'"/>');
  415. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated).'"/>');
  416. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"r/>');
  417. foreach($aFieldsMapping as $iNumber => $sAttCode)
  418. {
  419. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  420. }
  421. foreach($aSearchFields as $index => $sDummy)
  422. {
  423. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  424. }
  425. $aFieldsMapping = utils::ReadParam('field', array());
  426. $aSearchFields = utils::ReadParam('search_field', array());
  427. $aDisplayFilters = array();
  428. if ($bSimulate)
  429. {
  430. $aDisplayFilters['unchanged'] = '%d objects(s) will stay unchanged.';
  431. $aDisplayFilters['modified'] = '%d objects(s) will stay be modified.';
  432. $aDisplayFilters['added'] = '%d objects(s) will be added.';
  433. $aDisplayFilters['errors'] = '%d objects(s) will have errors.';
  434. }
  435. else
  436. {
  437. $aDisplayFilters['unchanged'] = '%d objects(s) remained unchanged.';
  438. $aDisplayFilters['modified'] = '%d objects(s) were modified.';
  439. $aDisplayFilters['added'] = '%d objects(s) were added.';
  440. $aDisplayFilters['errors'] = '%d objects(s) had errors.';
  441. }
  442. $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;');
  443. $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;');
  444. $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;');
  445. $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>');
  446. $oPage->add('<div style="overflow-y:auto">');
  447. $oPage->add($sHtml);
  448. $oPage->add('</div> <!-- end of preview -->');
  449. $oPage->add('<p><input type="button" value=" << Back " onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  450. if ($bSimulate)
  451. {
  452. $oPage->add('<input type="submit" value=" Run the Import ! "/></p>');
  453. }
  454. else
  455. {
  456. $oPage->add('<input type="submit" value=" Done "/></p>');
  457. }
  458. $oPage->add('</form>');
  459. $oPage->add('</div> <!-- end of wizForm -->');
  460. $oPage->add_script(
  461. <<< EOF
  462. function CSVGoBack()
  463. {
  464. $('input[name=step]').val($iCurrentStep-1);
  465. $('#wizForm').submit();
  466. }
  467. function ToggleRows(sCSSClass)
  468. {
  469. $('.'+sCSSClass).toggle();
  470. }
  471. EOF
  472. );
  473. if ($iErrors > 0)
  474. {
  475. return $aResult;
  476. }
  477. else
  478. {
  479. return null;
  480. }
  481. }
  482. /**
  483. * Perform the actual load of the CSV data and display the results
  484. * @param WebPage $oPage The web page to display the wizard
  485. * @param UserContext $oContext Current user's context
  486. * @return void
  487. */
  488. function LoadData(WebPage $oPage, UserContext $oContext)
  489. {
  490. $oPage->add('<h2>Step 5 of 5: Import completed</h2>');
  491. $aResult = ProcessCSVData($oPage, $oContext, false /* simulate = false */);
  492. if (is_array($aResult))
  493. {
  494. $oPage->StartCollapsibleSection("Lines that could not be loaded:", false);
  495. $oPage->p('The following lines have not been imported because they contain errors');
  496. $oPage->add('<textarea rows="30" cols="100">');
  497. $oPage->add(htmlentities(implode("\n", $aResult)));
  498. $oPage->add('</textarea>');
  499. $oPage->EndCollapsibleSection();
  500. }
  501. }
  502. /**
  503. * Simulate the load of the CSV data and display the results
  504. * @param WebPage $oPage The web page to display the wizard
  505. * @param UserContext $oContext Current user's context
  506. * @return void
  507. */
  508. function Preview(WebPage $oPage, UserContext $oContext)
  509. {
  510. $oPage->add('<h2>Step 4 of 5: Import simulation</h2>');
  511. ProcessCSVData($oPage, $oContext, true /* simulate */);
  512. }
  513. /**
  514. * Select the mapping between the CSV column and the fields of the objects
  515. * @param WebPage $oPage The web page to display the wizard
  516. * @return void
  517. */
  518. function SelectMapping(WebPage $oPage)
  519. {
  520. $sCSVData = utils::ReadParam('csvdata', '');
  521. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');;
  522. $sSeparator = utils::ReadParam('separator', ',');
  523. if ($sSeparator == 'tab') $sSeparator = "\t";
  524. if ($sSeparator == 'other')
  525. {
  526. $sSeparator = utils::ReadParam('other_separator', ',');
  527. }
  528. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  529. if ($sTextQualifier == 'other')
  530. {
  531. $sTextQualifier = utils::ReadParam('other_qualifier', '"');
  532. }
  533. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  534. $iSkippedLines = 0;
  535. if (utils::ReadParam('box_skiplines', '0') == 1)
  536. {
  537. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  538. }
  539. $sClassName = utils::ReadParam('class_name', '');
  540. $oPage->add('<h2>Step 3 of 5: Data mapping</h2>');
  541. $oPage->add('<div class="wizContainer">');
  542. $oPage->add('<form id="wizForm" method="post" onSubmit="return CheckValues()"><p>Select the class to import: ');
  543. $oPage->add(GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY).'</p>');
  544. $oPage->add('<div id="mapping"><p><br/>Select a class to configure the mapping<br/></p></div>');
  545. $oPage->add('<input type="hidden" name="step" value="4"/>');
  546. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator).'"/>');
  547. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier).'"/>');
  548. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  549. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  550. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated).'"/>');
  551. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData).'"/>');
  552. $oPage->add('<p><input type="button" value=" << Back " onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  553. $oPage->add('<input type="submit" value=" Simulate Import >> "/></p>');
  554. $oPage->add('</form>');
  555. $oPage->add('</div>');
  556. $oPage->add_ready_script(
  557. <<<EOF
  558. $('#select_class_name').change( DoMapping );
  559. EOF
  560. );
  561. if ($sClassName != '')
  562. {
  563. $oPage->add_ready_script("DoMapping();"); // There is already a class selected, run the mapping
  564. }
  565. $oPage->add_script(
  566. <<<EOF
  567. function CSVGoBack()
  568. {
  569. $('input[name=step]').val(2);
  570. $('#wizForm').submit();
  571. }
  572. var ajax_request = null;
  573. function DoMapping()
  574. {
  575. var separator = $('input[name=separator]').val();
  576. var text_qualifier = $('input[name=text_qualifier]').val();
  577. var header_line = $('input[name=header_line]').val();
  578. var nb_lines_skipped = $('input[name=nb_skipped_lines]').val();
  579. var csv_data = $('input[name=csvdata]').val();
  580. var class_name = $('select[name=class_name]').val();
  581. $('#mapping').block();
  582. // Make sure that we cancel any pending request before issuing another
  583. // since responses may arrive in arbitrary order
  584. if (ajax_request != null)
  585. {
  586. ajax_request.abort();
  587. ajax_request = null;
  588. }
  589. ajax_request = $.post('ajax.csvimport.php',
  590. { 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 },
  591. function(data) {
  592. $('#mapping').empty();
  593. $('#mapping').append(data);
  594. $('#mapping').unblock();
  595. }
  596. );
  597. }
  598. function CheckValues()
  599. {
  600. bResult = true;
  601. bMappingOk = true;
  602. bSearchOk = false;
  603. $('select[name^=field]').each( function() {
  604. if ($(this).val() == '')
  605. {
  606. this.style.backgroundColor = '#fcc';
  607. bMappingOk = false;
  608. bResult = false;
  609. }
  610. else
  611. {
  612. this.style.backgroundColor = 'ThreeDFace';
  613. }
  614. });
  615. // At least one search field must be checked
  616. $('input[name^=search]:checked').each( function() {
  617. bSearchOk = true;
  618. });
  619. if (!bMappingOk)
  620. {
  621. alert("Please select a mapping for every field.");
  622. }
  623. if (!bSearchOk)
  624. {
  625. bResult = false;
  626. alert("Please select at least one search criteria.");
  627. }
  628. return bResult;
  629. }
  630. EOF
  631. );
  632. }
  633. /**
  634. * Select the options of the CSV load and check for CSV parsing errors
  635. * @param WebPage $oPage The current web page
  636. * @return void
  637. */
  638. function SelectOptions(WebPage $oPage)
  639. {
  640. $sOperation = utils::ReadParam('operation', 'csv_data', 'post');
  641. $sCSVData = '';
  642. switch($sOperation)
  643. {
  644. case 'file_upload':
  645. $oDocument = utils::ReadPostedDocument('csvdata');
  646. if (!$oDocument->IsEmpty())
  647. {
  648. $sCSVData = $oDocument->GetData();
  649. }
  650. break;
  651. default:
  652. $sCSVData = utils::ReadParam('csvdata', '', 'post');
  653. }
  654. $aGuesses = GuessParameters($sCSVData); // Try to predict the parameters, based on the input data
  655. $sSeparator = utils::ReadParam('separator', $aGuesses['separator']);
  656. if ($sSeparator == 'tab') $sSeparator = "\t";
  657. $sTextQualifier = utils::ReadParam('qualifier', $aGuesses['qualifier']);
  658. $bHeaderLine = utils::ReadParam('header_line', 0);
  659. // Create a truncated version of the data used for the fast preview
  660. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  661. $iMaxLines = 20;
  662. $iMaxLen = strlen($sCSVData);
  663. $iCurPos = true;
  664. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  665. {
  666. $pos = strpos($sCSVData, "\n", $iCurPos);
  667. if ($pos !== false)
  668. {
  669. $iCurPos = 1+$pos;
  670. }
  671. else
  672. {
  673. $iCurPos = strlen($sCSVData);
  674. $iMaxLines = 1;
  675. }
  676. $iMaxLines--;
  677. }
  678. $sCSVDataTruncated = substr($sCSVData, 0, $iCurPos);
  679. $oPage->add('<h2>Step 2 of 5: CSV data options</h2>');
  680. $oPage->add('<div class="wizContainer">');
  681. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;background:#E8F3CF">');
  682. $oPage->add('<form id="wizForm" method="post" id="csv_options">');
  683. $oPage->add('<h3>Separator character:</h3>');
  684. $oPage->add('<p><input type="radio" name="separator" value="," onChange="DoPreview()"'.IsChecked($sSeparator, ',').'/> , (comma)<br/>');
  685. $oPage->add('<input type="radio" name="separator" value=";" onChange="DoPreview()"'.IsChecked($sSeparator, ';').'/> ; (semicolon)<br/>');
  686. $oPage->add('<input type="radio" name="separator" value="tab" onChange="DoPreview()"'.IsChecked($sSeparator, "\t").'/> tab<br/>');
  687. $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()"/>');
  688. $oPage->add('</p>');
  689. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;background:#E8F3CF">');
  690. $oPage->add('<h3>Text qualifier character:</h3>');
  691. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onChange="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> " (double quote)<br/>');
  692. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onChange="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> \' (simple quote)<br/>');
  693. $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()"/>');
  694. $oPage->add('</p>');
  695. $oPage->add('</td><td style="vertical-align:top;background:#E8F3CF">');
  696. $oPage->add('<h3>Comments and header:</h3>');
  697. $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>');
  698. $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>');
  699. $oPage->add('</td></tr></table>');
  700. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated).'"/>');
  701. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sCSVData).'"/>');
  702. $oPage->add('<input type="hidden" name="step" value="3"/>');
  703. $oPage->add('<div id="preview">');
  704. $oPage->add('<p style="text-align:center">Data Preview</p>');
  705. $oPage->add('</div>');
  706. $oPage->add('<input type="button" value=" << Back " onClick="GoBack()"/>');
  707. $oPage->add('<input type="submit" value=" Next >> "/>');
  708. $oPage->add('</form>');
  709. $oPage->add('</div>');
  710. $oPage->add_script(
  711. <<<EOF
  712. function GoBack()
  713. {
  714. $('input[name=step]').val(1);
  715. $('#wizForm').submit();
  716. }
  717. var ajax_request = null;
  718. function DoPreview()
  719. {
  720. var separator = $('input[name=separator]:checked').val();
  721. if (separator == 'other')
  722. {
  723. separator = $('#other_separator').val();
  724. }
  725. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  726. if (text_qualifier == 'other')
  727. {
  728. text_qualifier = $('#other_qualifier').val();
  729. }
  730. var nb_lines_skipped = 0;
  731. if ($('#box_skiplines:checked').val() != null)
  732. {
  733. nb_lines_skipped = $('#nb_skipped_lines').val();
  734. }
  735. var header_line = 0;
  736. if ($('#box_header:checked').val() != null)
  737. {
  738. header_line = 1;
  739. }
  740. $('#preview').block();
  741. // Make sure that we cancel any pending request before issuing another
  742. // since responses may arrive in arbitrary order
  743. if (ajax_request != null)
  744. {
  745. ajax_request.abort();
  746. ajax_request = null;
  747. }
  748. ajax_request = $.post('ajax.csvimport.php',
  749. { operation: 'parser_preview', csvdata: $("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line },
  750. function(data) {
  751. $('#preview').empty();
  752. $('#preview').append(data);
  753. $('#preview').unblock();
  754. }
  755. );
  756. }
  757. EOF
  758. );
  759. $oPage->add_ready_script('DoPreview();');
  760. }
  761. /**
  762. * Prompt for the data to be loaded (either via a file or a copy/paste)
  763. * @param WebPage $oPage The current web page
  764. * @return void
  765. */
  766. function Welcome(iTopWebPage $oPage)
  767. {
  768. $oPage->add("<div><p><h1>CSV import wizard</h1></p></div>\n");
  769. $oPage->AddTabContainer('tabs1');
  770. $sFileLoadHtml = '<div><form method="post" enctype="multipart/form-data"><p>Select the file to import:</p>'.
  771. '<p><input type="file" name="csvdata"/></p>'.
  772. '<p><input type="submit" value=" Next >> "/></p>'.
  773. '<p><input type="hidden" name="step" value="2"/></p>'.
  774. '<p><input type="hidden" name="operation" value="file_upload"/></p>'.
  775. '</form></div>';
  776. $oPage->AddToTab('tabs1', "Load from a file", $sFileLoadHtml);
  777. $sCSVData = utils::ReadParam('csvdata', '');
  778. $sPasteDataHtml = '<div><form method="post"><p>Paste the data to import:</p>'.
  779. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData).'</textarea></p>'.
  780. '<p><input type="submit" value=" Next >> "/></p>'.
  781. '<p><input type="hidden" name="step" value="2"/></p>'.
  782. '<p><input type="hidden" name="operation" value="csv_data"/></p>'.
  783. '</form></div>';
  784. $oPage->AddToTab('tabs1', "Copy and paste data", $sPasteDataHtml);
  785. $sTemplateHtml = '<div><p>Pick the template do download: ';
  786. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  787. $sTemplateHtml .= '</div>';
  788. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  789. $sTemplateHtml .= '</div>';
  790. $oPage->AddToTab('tabs1', "Templates", $sTemplateHtml);
  791. $oPage->add_script(
  792. <<<EOF
  793. var ajax_request = null;
  794. function DisplayTemplate(sClassName) {
  795. $('#template').block();
  796. // Make sure that we cancel any pending request before issuing another
  797. // since responses may arrive in arbitrary order
  798. if (ajax_request != null)
  799. {
  800. ajax_request.abort();
  801. ajax_request = null;
  802. }
  803. ajax_request = $.get('ajax.csvimport.php',
  804. { operation: 'get_csv_template', class_name: sClassName },
  805. function(data) {
  806. $('#template').empty();
  807. $('#template').append(data);
  808. $('#template').unblock();
  809. }
  810. );
  811. }
  812. EOF
  813. );
  814. $oPage->add_ready_script(
  815. <<<EOF
  816. $('#select_template_class').change( function() {
  817. DisplayTemplate(this.value);
  818. });
  819. EOF
  820. );
  821. }
  822. switch($iStep)
  823. {
  824. case 5:
  825. LoadData($oPage, $oContext);
  826. break;
  827. case 4:
  828. Preview($oPage, $oContext);
  829. break;
  830. case 3:
  831. SelectMapping($oPage);
  832. break;
  833. case 2:
  834. SelectOptions($oPage);
  835. break;
  836. case 1:
  837. case 6: // Loop back here when we are done
  838. default:
  839. Welcome($oPage);
  840. }
  841. $oPage->output();
  842. ?>