csvimport.php 32 KB

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