csvimport.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * CSV Import Page
  18. * Wizard to import CSV (or TSV) data into the database
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  24. */
  25. try
  26. {
  27. ini_set('memory_limit', '256M');
  28. require_once('../approot.inc.php');
  29. require_once(APPROOT.'/application/application.inc.php');
  30. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  31. require_once(APPROOT.'/application/startup.inc.php');
  32. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  33. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  34. $oAppContext = new ApplicationContext();
  35. $iStep = utils::ReadParam('step', 1);
  36. $oPage = new iTopWebPage(Dict::S('UI:Title:BulkImport'));
  37. /**
  38. * Helper function to build a select from the list of valid classes for a given action
  39. * @param string $sName The name of the select in the HTML form
  40. * @param string $sDefaulfValue The defaut value (i.e the value selected by default)
  41. * @param integer $iWidthPx The width (in pixels) of the drop-down list
  42. * @param integer $iActionCode The ActionCode (from UserRights) to check for authorization for the classes
  43. * @return string The HTML fragment corresponding to the select tag
  44. */
  45. function GetClassesSelect($sName, $sDefaultValue, $iWidthPx, $iActionCode = null)
  46. {
  47. $sHtml = "<select id=\"select_$sName\" name=\"$sName\">";
  48. $sHtml .= "<option tyle=\"width: ".$iWidthPx."px;\" title=\"Select the class you want to load\" value=\"\">".Dict::S('UI:CSVImport:ClassesSelectOne')."</option>\n";
  49. $aValidClasses = array();
  50. $aClassCategories = array('bizmodel');
  51. if (UserRights::IsAdministrator())
  52. {
  53. $aClassCategories = array('bizmodel', 'application', 'addon/authentication');
  54. }
  55. foreach($aClassCategories as $sClassCategory)
  56. {
  57. foreach(MetaModel::GetClasses($sClassCategory) as $sClassName)
  58. {
  59. if ( (is_null($iActionCode) || UserRights::IsActionAllowed($sClassName, $iActionCode)) &&
  60. (!MetaModel::IsAbstract($sClassName)) )
  61. {
  62. $sSelected = ($sClassName == $sDefaultValue) ? " selected" : "";
  63. $sDescription = MetaModel::GetClassDescription($sClassName);
  64. $sDisplayName = MetaModel::GetName($sClassName);
  65. $aValidClasses[$sDisplayName] = "<option style=\"width: ".$iWidthPx."px;\" title=\"$sDescription\" value=\"$sClassName\"$sSelected>$sDisplayName</option>";
  66. }
  67. }
  68. }
  69. ksort($aValidClasses);
  70. $sHtml .= implode("\n", $aValidClasses);
  71. $sHtml .= "</select>";
  72. return $sHtml;
  73. }
  74. /**
  75. * Helper to 'check' an input in an HTML form if the current value equals the value given
  76. * @param mixed $sCurrentValue The current value to be chacked against the value of the input
  77. * @param mixed $sProposedValue The value of the input
  78. * @param bool $bInverseCondition Set to true to perform the reversed comparison
  79. * @return string Either ' checked' or an empty string
  80. */
  81. function IsChecked($sCurrentValue, $sProposedValue, $bInverseCondition = false)
  82. {
  83. $bCondition = ($sCurrentValue == $sProposedValue);
  84. return ($bCondition xor $bInverseCondition) ? ' checked' : '';
  85. }
  86. /**
  87. * Get the user friendly name for an 'extended' attribute code i.e 'name', becomes 'Name' and 'org_id->name' becomes 'Organization->Name'
  88. * @param string $sClassName The name of the class
  89. * @param string $sAttCodeEx Either an attribute code of ext_key_name->att_code
  90. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  91. */
  92. function GetFriendlyAttCodeName($sClassName, $sAttCodeEx)
  93. {
  94. $sFriendlyName = '';
  95. if (preg_match('/(.+)->(.+)/', $sAttCodeEx, $aMatches) > 0)
  96. {
  97. $sAttribute = $aMatches[1];
  98. $sField = $aMatches[2];
  99. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttribute);
  100. if ($oAttDef->IsExternalKey())
  101. {
  102. $sTargetClass = $oAttDef->GetTargetClass();
  103. $oTargetAttDef = MetaModel::GetAttributeDef($sTargetClass, $sField);
  104. $sFriendlyName = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  105. }
  106. else
  107. {
  108. // hum, hum... should never happen, we'd better raise an exception
  109. throw(new Exception(Dict::Format('UI:CSVImport:ErrorExtendedAttCode', $sAttCodeEx, $sAttribute, $sClassName)));
  110. }
  111. }
  112. else
  113. {
  114. if ($sAttCodeEx == 'id')
  115. {
  116. $sFriendlyName = Dict::S('UI:CSVImport:idField');
  117. }
  118. else
  119. {
  120. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCodeEx);
  121. $sFriendlyName = $oAttDef->GetLabel();
  122. }
  123. }
  124. return $sFriendlyName;
  125. }
  126. /**
  127. * Returns the number of occurences of each char from the set in the specified string
  128. * @param string $sString The input data
  129. * @param array $aSet The set of characters to count
  130. * @return hash 'char' => nb of occurences
  131. */
  132. function CountCharsFromSet($sString, $aSet)
  133. {
  134. $aResult = array();
  135. $aCount = count_chars($sString);
  136. foreach($aSet as $sChar)
  137. {
  138. $aResult[$sChar] = isset($aCount[ord($sChar)]) ? $aCount[ord($sChar)] : 0;
  139. }
  140. return $aResult;
  141. }
  142. /**
  143. * Return the most frequent (and regularly occuring) character among the given set, in the specified lines
  144. * @param array $aCSVData The input data, one entry per line
  145. * @param array $aPossibleSeparators The list of characters to count
  146. * @return string The most frequent character from the set
  147. */
  148. function GuessFromFrequency($aCSVData, $aPossibleSeparators)
  149. {
  150. $iLine = 0;
  151. $iMaxLine = 20; // Process max 20 lines to guess the parameters
  152. foreach($aPossibleSeparators as $sSep)
  153. {
  154. $aGuesses[$sSep]['total'] = $aGuesses[$sSep]['max'] = 0;
  155. $aGuesses[$sSep]['min'] = 999;
  156. }
  157. $aStats = array();
  158. while(($iLine < count($aCSVData)) && ($iLine < $iMaxLine) )
  159. {
  160. if (strlen($aCSVData[$iLine]) > 0)
  161. {
  162. $aStats[$iLine] = CountCharsFromSet($aCSVData[$iLine], $aPossibleSeparators);
  163. }
  164. $iLine++;
  165. }
  166. $iLine = 1;
  167. foreach($aStats as $aLineStats)
  168. {
  169. foreach($aPossibleSeparators as $sSep)
  170. {
  171. $aGuesses[$sSep]['total'] += $aLineStats[$sSep];
  172. if ($aLineStats[$sSep] > $aGuesses[$sSep]['max']) $aGuesses[$sSep]['max'] = $aLineStats[$sSep];
  173. if ($aLineStats[$sSep] < $aGuesses[$sSep]['min']) $aGuesses[$sSep]['min'] = $aLineStats[$sSep];
  174. }
  175. $iLine++;
  176. }
  177. $aScores = array();
  178. foreach($aGuesses as $sSep => $aData)
  179. {
  180. $aScores[$sSep] = $aData['total'] + $aData['max'] - $aData['min'];
  181. }
  182. arsort($aScores, SORT_NUMERIC); // Sort the array, higher scores first
  183. $aKeys = array_keys($aScores);
  184. $sSeparator = $aKeys[0]; // Take the first key, the one with the best score
  185. return $sSeparator;
  186. }
  187. /**
  188. * Try to predict the CSV parameters based on the input data
  189. * @param string $sCSVData The input data
  190. * @return hash 'separator' => the_guessed_separator, 'qualifier' => the_guessed_text_qualifier
  191. */
  192. function GuessParameters($sCSVData)
  193. {
  194. $aData = explode("\n", $sCSVData);
  195. $sSeparator = GuessFromFrequency($aData, array("\t", ',', ';', '|')); // Guess the most frequent (and regular) character on each line
  196. $sQualifier = GuessFromFrequency($aData, array('"', "'")); // Guess the most frequent (and regular) character on each line
  197. return array('separator' => $sSeparator, 'qualifier' => $sQualifier);
  198. }
  199. /**
  200. * Process the CSV data, for real or as a simulation
  201. * @param WebPage $oPage The page used to display the wizard
  202. * @param bool $bSimulate Whether or not to simulate the data load
  203. * @return array The CSV lines in error that were rejected from the load (with the header line - if any) or null
  204. */
  205. function ProcessCSVData(WebPage $oPage, $bSimulate = true)
  206. {
  207. $aResult = array();
  208. $sCSVData = utils::ReadParam('csvdata', '');
  209. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');
  210. $sSeparator = utils::ReadParam('separator', ',');
  211. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  212. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  213. $iRealSkippedLines = $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  214. $sClassName = utils::ReadParam('class_name', '');
  215. $aFieldsMapping = utils::ReadParam('field', array());
  216. $aSearchFields = utils::ReadParam('search_field', array());
  217. $iCurrentStep = $bSimulate ? 4 : 5;
  218. $bAdvanced = utils::ReadParam('advanced', 0);
  219. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  220. // Parse the data set
  221. $oCSVParser = new CSVParser($sCSVData, $sSeparator, $sTextQualifier);
  222. $aData = $oCSVParser->ToArray($iSkippedLines);
  223. if ($bHeaderLine)
  224. {
  225. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier, array_shift($aData)).$sTextQualifier; // Remove the first line and store it in case of error
  226. $iRealSkippedLines++;
  227. }
  228. // Format for the line numbers
  229. $sMaxLen = (strlen(''.count($aData)) < 3) ? 3 : strlen(''.count($aData)); // Pad line numbers to the appropriate number of chars, but at least 3
  230. // Compute the list of search/reconciliation criteria
  231. $aSearchKeys = array();
  232. foreach($aSearchFields as $index => $sDummy)
  233. {
  234. $sSearchField = $aFieldsMapping[$index];
  235. $aMatches = array();
  236. if (preg_match('/(.+)->(.+)/', $sSearchField, $aMatches) > 0)
  237. {
  238. $sSearchField = $aMatches[1];
  239. $aSearchKeys[$aMatches[1]] = '';
  240. }
  241. else
  242. {
  243. $aSearchKeys[$sSearchField] = '';
  244. }
  245. if (!MetaModel::IsValidFilterCode($sClassName, $sSearchField))
  246. {
  247. // Remove invalid or unmapped search fields
  248. $aSearchFields[$index] = null;
  249. unset($aSearchKeys[$sSearchField]);
  250. }
  251. }
  252. // Compute the list of fields and external keys to process
  253. $aExtKeys = array();
  254. $aAttributes = array();
  255. $aExternalKeysByColumn = array();
  256. foreach($aFieldsMapping as $iNumber => $sAttCode)
  257. {
  258. $iIndex = $iNumber-1;
  259. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  260. {
  261. if (preg_match('/(.+)->(.+)/', $sAttCode, $aMatches) > 0)
  262. {
  263. $sAttribute = $aMatches[1];
  264. $sField = $aMatches[2];
  265. $aExtKeys[$sAttribute][$sField] = $iIndex;
  266. $aExternalKeysByColumn[$iIndex] = $sAttribute;
  267. }
  268. else
  269. {
  270. if ($sAttCode == 'id')
  271. {
  272. $aAttributes['id'] = $iIndex;
  273. }
  274. else
  275. {
  276. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  277. if ($oAttDef->IsExternalKey())
  278. {
  279. $aExtKeys[$sAttCode]['id'] = $iIndex;
  280. $aExternalKeysByColumn[$iIndex] = $sAttCode;
  281. }
  282. else
  283. {
  284. $aAttributes[$sAttCode] = $iIndex;
  285. }
  286. }
  287. }
  288. }
  289. }
  290. $oMyChange = null;
  291. if (!$bSimulate)
  292. {
  293. // We're doing it for real, let's create a change
  294. $oMyChange = MetaModel::NewObject("CMDBChange");
  295. $oMyChange->Set("date", time());
  296. if (UserRights::IsImpersonated())
  297. {
  298. $sUserString = Dict::Format('UI:Archive_User_OnBehalfOf_User', UserRights::GetRealUser(), UserRights::GetUser());
  299. }
  300. else
  301. {
  302. $sUserString = UserRights::GetUser();
  303. }
  304. $sUserString .= ' (CSV)';
  305. $oMyChange->Set("userinfo", $sUserString);
  306. $iChangeId = $oMyChange->DBInsert();
  307. }
  308. $sSynchroScope = null; // e.g. "SELECT Server";
  309. $aSynchroUpdate = null; // e.g. array('status' => 'obsolete')
  310. $oBulk = new BulkChange(
  311. $sClassName,
  312. $aData,
  313. $aAttributes,
  314. $aExtKeys,
  315. array_keys($aSearchKeys),
  316. $sSynchroScope,
  317. $aSynchroUpdate
  318. );
  319. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  320. $aRes = $oBulk->Process($oMyChange);
  321. $sHtml = '<table id="bulk_preview" style="border-collapse: collapse;">';
  322. $sHtml .= '<tr><th style="padding:2px;border-right: 2px #fff solid;">Line</th>';
  323. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Status</th>';
  324. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Object</th>';
  325. foreach($aFieldsMapping as $iNumber => $sAttCode)
  326. {
  327. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  328. {
  329. $sHtml .= "<th style=\"padding:2px;border-right: 2px #fff solid;\">".GetFriendlyAttCodeName($sClassName, $sAttCode)."</th>";
  330. }
  331. }
  332. $sHtml .= '<th>Message</th>';
  333. $sHtml .= '</tr>';
  334. $iErrors = 0;
  335. $iCreated = 0;
  336. $iModified = 0;
  337. $iUnchanged = 0;
  338. foreach($aRes as $iLine => $aResRow)
  339. {
  340. $oStatus = $aResRow['__STATUS__'];
  341. $sUrl = '';
  342. $sMessage = '';
  343. $sCSSRowClass = '';
  344. $sCSSMessageClass = 'cell_ok';
  345. switch(get_class($oStatus))
  346. {
  347. case 'RowStatus_NoChange':
  348. $iUnchanged++;
  349. $sFinalClass = $aResRow['finalclass'];
  350. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetValue());
  351. $sUrl = $oObj->GetHyperlink();
  352. $sStatus = '<img src="../images/unchanged.png" title="Unchanged">';
  353. $sCSSRowClass = 'row_unchanged';
  354. break;
  355. case 'RowStatus_Modify':
  356. $iModified++;
  357. $sFinalClass = $aResRow['finalclass'];
  358. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetValue());
  359. $sUrl = $oObj->GetHyperlink();
  360. $sStatus = '<img src="../images/modified.png" title="Modified">';
  361. $sCSSRowClass = 'row_modified';
  362. break;
  363. case 'RowStatus_Disappeared':
  364. $iModified++;
  365. $sFinalClass = $aResRow['finalclass'];
  366. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetValue());
  367. $sUrl = $oObj->GetHyperlink();
  368. $sStatus = '<img src="../images/delete.png" title="Missing">';
  369. $sCSSRowClass = 'row_modified';
  370. if ($bSimulate)
  371. {
  372. $sMessage = 'Missing object: will be updated';
  373. }
  374. else
  375. {
  376. $sMessage = 'Missing object: updated';
  377. }
  378. break;
  379. case 'RowStatus_NewObj':
  380. $iCreated++;
  381. $sFinalClass = $aResRow['finalclass'];
  382. $sStatus = '<img src="../images/added.png" title="Created">';
  383. $sCSSRowClass = 'row_added';
  384. if ($bSimulate)
  385. {
  386. $sMessage = 'Object will be created';
  387. }
  388. else
  389. {
  390. $sFinalClass = $aResRow['finalclass'];
  391. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetValue());
  392. $sUrl = $oObj->GetHyperlink();
  393. $sMessage = 'Object created';
  394. }
  395. break;
  396. case 'RowStatus_Issue':
  397. $iErrors++;
  398. $sMessage .= $oPage->GetP($oStatus->GetDescription());
  399. $sStatus = '<img src="../images/error.png" title="Error">';
  400. $sCSSMessageClass = 'cell_error';
  401. $sCSSRowClass = 'row_error';
  402. if (array_key_exists($iLine, $aData))
  403. {
  404. $aRow = $aData[$iLine];
  405. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier,$aRow).$sTextQualifier; // Remove the first line and store it in case of error
  406. }
  407. break;
  408. }
  409. $sHtml .= '<tr class="'.$sCSSRowClass.'">';
  410. $sHtml .= "<td style=\"background-color:#f1f1f1;border-right:2px #fff solid;\">".sprintf("%0{$sMaxLen}d", 1+$iLine+$iRealSkippedLines)."</td>";
  411. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;border-right:2px #fff solid;\">$sStatus</td>";
  412. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;\">$sUrl</td>";
  413. foreach($aFieldsMapping as $iNumber => $sAttCode)
  414. {
  415. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  416. {
  417. $oCellStatus = $aResRow[$iNumber -1];
  418. $sCellMessage = '';
  419. if (isset($aExternalKeysByColumn[$iNumber -1]))
  420. {
  421. $sExtKeyName = $aExternalKeysByColumn[$iNumber -1];
  422. $oExtKeyCellStatus = $aResRow[$sExtKeyName];
  423. switch(get_class($oExtKeyCellStatus))
  424. {
  425. case 'CellStatus_Issue':
  426. case 'CellStatus_SearchIssue':
  427. case 'CellStatus_NullIssue':
  428. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  429. break;
  430. case 'CellStatus_Ambiguous':
  431. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  432. break;
  433. default:
  434. // Do nothing
  435. }
  436. }
  437. $sHtmlValue = htmlentities($oCellStatus->GetValue(), ENT_QUOTES, 'UTF-8');
  438. switch(get_class($oCellStatus))
  439. {
  440. case 'CellStatus_Issue':
  441. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  442. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">ERROR: '.$sHtmlValue.$sCellMessage.'</td>';
  443. break;
  444. case 'CellStatus_SearchIssue':
  445. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  446. $sHtml .= '<td class="cell_error">ERROR: '.$sHtmlValue.$sCellMessage.'</td>';
  447. break;
  448. case 'CellStatus_Ambiguous':
  449. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  450. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">AMBIGUOUS: '.$sHtmlValue.$sCellMessage.'</td>';
  451. break;
  452. case 'CellStatus_Modify':
  453. $sHtml .= '<td class="cell_modified" style="border-right:1px #eee solid;"><b>'.$sHtmlValue.'</b></td>';
  454. break;
  455. default:
  456. $sHtml .= '<td class="cell_ok" style="border-right:1px #eee solid;">'.$sHtmlValue.$sCellMessage.'</td>';
  457. }
  458. }
  459. }
  460. $sHtml .= "<td class=\"$sCSSMessageClass\" style=\"background-color:#f1f1f1;\">$sMessage</td>";
  461. $sHtml .= '</tr>';
  462. }
  463. $sHtml .= '</table>';
  464. $oPage->add('<div class="wizContainer">');
  465. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post">');
  466. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  467. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  468. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  469. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  470. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  471. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  472. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  473. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  474. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  475. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  476. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'"/>');
  477. foreach($aFieldsMapping as $iNumber => $sAttCode)
  478. {
  479. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  480. }
  481. foreach($aSearchFields as $index => $sDummy)
  482. {
  483. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  484. }
  485. $aFieldsMapping = utils::ReadParam('field', array());
  486. $aSearchFields = utils::ReadParam('search_field', array());
  487. $aDisplayFilters = array();
  488. if ($bSimulate)
  489. {
  490. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsWillStayUnchanged');
  491. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWillBeModified');
  492. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWillBeAdded');
  493. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsWillHaveErrors');
  494. }
  495. else
  496. {
  497. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsRemainedUnchanged');
  498. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWereModified');
  499. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWereAdded');
  500. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsHadErrors');
  501. }
  502. $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;');
  503. $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;');
  504. $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;');
  505. $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>');
  506. $oPage->add('<div style="overflow-y:auto" class="white">');
  507. $oPage->add($sHtml);
  508. $oPage->add('</div> <!-- end of preview -->');
  509. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  510. if ($bSimulate)
  511. {
  512. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:DoImport').'" onClick="$(\'#wizForm\').block();"/></p>');
  513. }
  514. else
  515. {
  516. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Done').'"/></p>');
  517. }
  518. $oPage->add('</form>');
  519. $oPage->add('</div> <!-- end of wizForm -->');
  520. $oPage->add_script(
  521. <<< EOF
  522. function CSVGoBack()
  523. {
  524. $('input[name=step]').val($iCurrentStep-1);
  525. $('#wizForm').submit();
  526. }
  527. function ToggleRows(sCSSClass)
  528. {
  529. $('.'+sCSSClass).toggle();
  530. }
  531. EOF
  532. );
  533. if ($iErrors > 0)
  534. {
  535. return $aResult;
  536. }
  537. else
  538. {
  539. return null;
  540. }
  541. }
  542. /**
  543. * Perform the actual load of the CSV data and display the results
  544. * @param WebPage $oPage The web page to display the wizard
  545. * @return void
  546. */
  547. function LoadData(WebPage $oPage)
  548. {
  549. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep5').'</h2>');
  550. $aResult = ProcessCSVData($oPage, false /* simulate = false */);
  551. if (is_array($aResult))
  552. {
  553. $oPage->StartCollapsibleSection(Dict::S('UI:CSVImport:LinesNotImported'), false);
  554. $oPage->p(Dict::S('UI:CSVImport:LinesNotImported+'));
  555. $oPage->add('<textarea rows="30" cols="100">');
  556. $oPage->add(htmlentities(implode("\n", $aResult), ENT_QUOTES, 'UTF-8'));
  557. $oPage->add('</textarea>');
  558. $oPage->EndCollapsibleSection();
  559. }
  560. }
  561. /**
  562. * Simulate the load of the CSV data and display the results
  563. * @param WebPage $oPage The web page to display the wizard
  564. * @return void
  565. */
  566. function Preview(WebPage $oPage)
  567. {
  568. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep4').'</h2>');
  569. ProcessCSVData($oPage, true /* simulate */);
  570. }
  571. /**
  572. * Select the mapping between the CSV column and the fields of the objects
  573. * @param WebPage $oPage The web page to display the wizard
  574. * @return void
  575. */
  576. function SelectMapping(WebPage $oPage)
  577. {
  578. $sCSVData = utils::ReadParam('csvdata', '');
  579. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');;
  580. $sSeparator = utils::ReadParam('separator', ',');
  581. if ($sSeparator == 'tab') $sSeparator = "\t";
  582. if ($sSeparator == 'other')
  583. {
  584. $sSeparator = utils::ReadParam('other_separator', ',');
  585. }
  586. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  587. if ($sTextQualifier == 'other')
  588. {
  589. $sTextQualifier = utils::ReadParam('other_qualifier', '"');
  590. }
  591. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  592. $iSkippedLines = 0;
  593. if (utils::ReadParam('box_skiplines', '0') == 1)
  594. {
  595. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  596. }
  597. $sClassName = utils::ReadParam('class_name', '');
  598. $bAdvanced = utils::ReadParam('advanced', 0);
  599. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  600. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep3').'</h2>');
  601. $oPage->add('<div class="wizContainer">');
  602. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" onSubmit="return CheckValues()"><table style="width:100%" class="transparent"><tr><td>'.Dict::S('UI:CSVImport:SelectClass').' ');
  603. $oPage->add(GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY));
  604. $oPage->add('</td><td style="text-align:right"><input type="checkbox" name="advanced" value="1" '.IsChecked($bAdvanced, 1).' onClick="DoMapping()">&nbsp;'.Dict::S('UI:CSVImport:AdvancedMode').'</td></tr></table>');
  605. $oPage->add('<div style="padding:1em;display:none" id="advanced_help" style="display:none">'.Dict::S('UI:CSVImport:AdvancedMode+').'</div>');
  606. $oPage->add('<div id="mapping" class="white"><p style="text-align:center;width:100%;font-size:1.5em;padding:1em;">'.Dict::S('UI:CSVImport:SelectAClassFirst').'<br/></p></div>');
  607. $oPage->add('<input type="hidden" name="step" value="4"/>');
  608. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  609. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  610. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  611. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  612. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  613. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  614. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  615. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'">');
  616. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  617. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:SimulateImport').'"/></p>');
  618. $oPage->add('</form>');
  619. $oPage->add('</div>');
  620. $sAlertIncompleteMapping = Dict::S('UI:CSVImport:AlertIncompleteMapping');
  621. $sAlertNoSearchCriteria = Dict::S('UI:CSVImport:AlertNoSearchCriteria');
  622. $oPage->add_ready_script(
  623. <<<EOF
  624. $('#select_class_name').change( DoMapping );
  625. EOF
  626. );
  627. if ($sClassName != '')
  628. {
  629. $oPage->add_ready_script("DoMapping();"); // There is already a class selected, run the mapping
  630. }
  631. $oPage->add_script(
  632. <<<EOF
  633. var aDefaultKeys = new Array();
  634. function CSVGoBack()
  635. {
  636. $('input[name=step]').val(2);
  637. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  638. $('#wizForm').submit();
  639. }
  640. var ajax_request = null;
  641. function DoMapping()
  642. {
  643. var class_name = $('select[name=class_name]').val();
  644. var advanced = $('input[name=advanced]:checked').val();
  645. if (advanced != 1)
  646. {
  647. $('#advanced_help').hide();
  648. }
  649. else
  650. {
  651. $('#advanced_help').show();
  652. }
  653. if (class_name != '')
  654. {
  655. var separator = $('input[name=separator]').val();
  656. var text_qualifier = $('input[name=text_qualifier]').val();
  657. var header_line = $('input[name=header_line]').val();
  658. var nb_lines_skipped = $('input[name=nb_skipped_lines]').val();
  659. var csv_data = $('input[name=csvdata]').val();
  660. var encoding = $('input[name=encoding]').val();
  661. if (advanced != 1)
  662. {
  663. advanced = 0;
  664. }
  665. $('#mapping').block();
  666. // Make sure that we cancel any pending request before issuing another
  667. // since responses may arrive in arbitrary order
  668. if (ajax_request != null)
  669. {
  670. ajax_request.abort();
  671. ajax_request = null;
  672. }
  673. ajax_request = $.post('ajax.csvimport.php',
  674. { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator,
  675. qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, class_name: class_name,
  676. advanced: advanced, encoding: encoding },
  677. function(data) {
  678. $('#mapping').empty();
  679. $('#mapping').append(data);
  680. $('#mapping').unblock();
  681. }
  682. );
  683. }
  684. }
  685. function CheckValues()
  686. {
  687. bResult = true;
  688. bMappingOk = true;
  689. bSearchOk = false;
  690. $('select[name^=field]').each( function() {
  691. if ($(this).val() == '')
  692. {
  693. $(this).parent().css({'border': '2px #D81515 solid'});
  694. bMappingOk = false;
  695. bResult = false;
  696. }
  697. else
  698. {
  699. $(this).parent().css({'border': '0'});
  700. }
  701. });
  702. // At least one search field must be checked
  703. $('input[name^=search]:checked').each( function() {
  704. bSearchOk = true;
  705. });
  706. if (!bMappingOk)
  707. {
  708. alert("$sAlertIncompleteMapping");
  709. }
  710. if (!bSearchOk)
  711. {
  712. bResult = false;
  713. alert("$sAlertNoSearchCriteria");
  714. }
  715. if (bResult)
  716. {
  717. $('#mapping').block();
  718. // Re-enable all search_xxx checkboxes so that their value gets posted
  719. $('input[name^=search]').each(function() {
  720. $(this).attr('disabled', false);
  721. });
  722. }
  723. return bResult;
  724. }
  725. function DoCheckMapping()
  726. {
  727. // Check if there is a field mapped to 'id'
  728. // In which case, it's the only possible search key
  729. var idSelected = 0;
  730. var nbSearchKeys = $('input[name^=search]:checked').length;
  731. var nbMappings = $('select[name^=field]').length;
  732. for(index=1; index <= nbMappings; index++)
  733. {
  734. var selectedValue = $('#mapping_'+index).val();
  735. if (selectedValue == 'id')
  736. {
  737. idSelected = index;
  738. }
  739. }
  740. for (index=1; index <= nbMappings; index++)
  741. {
  742. sMappingValue = $('#mapping_'+index).val();
  743. if ((sMappingValue == '') || (sMappingValue == ':none:'))
  744. {
  745. // Non-mapped field, uncheck and disabled
  746. $('#search_'+index).attr('checked', false);
  747. $('#search_'+index).attr('disabled', true);
  748. }
  749. else if (index == idSelected)
  750. {
  751. // The 'id' field was mapped, it's the only possible reconciliation key
  752. $('#search_'+index).attr('checked', true);
  753. $('#search_'+index).attr('disabled', true);
  754. }
  755. else
  756. {
  757. if (idSelected > 0)
  758. {
  759. // The 'id' field was mapped, it's the only possible reconciliation key
  760. $('#search_'+index).attr('checked', false);
  761. $('#search_'+index).attr('disabled', true);
  762. }
  763. else
  764. {
  765. $('#search_'+index).attr('disabled', false);
  766. if (nbSearchKeys == 0)
  767. {
  768. // No search key was selected, select the default ones
  769. for(j =0; j < aDefaultKeys.length; j++)
  770. {
  771. if (sMappingValue == aDefaultKeys[j])
  772. {
  773. $('#search_'+index).attr('checked', true);
  774. }
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. EOF
  782. );
  783. }
  784. /**
  785. * Select the options of the CSV load and check for CSV parsing errors
  786. * @param WebPage $oPage The current web page
  787. * @return void
  788. */
  789. function SelectOptions(WebPage $oPage)
  790. {
  791. $sOperation = utils::ReadParam('operation', 'csv_data');
  792. $sCSVData = '';
  793. switch($sOperation)
  794. {
  795. case 'file_upload':
  796. $oDocument = utils::ReadPostedDocument('csvdata');
  797. if (!$oDocument->IsEmpty())
  798. {
  799. $sCSVData = $oDocument->GetData();
  800. }
  801. break;
  802. default:
  803. $sCSVData = utils::ReadPostedParam('csvdata', '');
  804. }
  805. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  806. // Compute a subset of the data set, now that we know the charset
  807. if ($sEncoding == 'UTF-8')
  808. {
  809. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  810. }
  811. else
  812. {
  813. $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  814. }
  815. $aGuesses = GuessParameters($sUTF8Data); // Try to predict the parameters, based on the input data
  816. $sSeparator = utils::ReadParam('separator', '');
  817. if ($sSeparator == '') // May be set to an empty value by the previous page
  818. {
  819. $sSeparator = $aGuesses['separator'];
  820. }
  821. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  822. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  823. if ($sSeparator == 'tab') $sSeparator = "\t";
  824. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  825. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  826. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  827. {
  828. $sTextQualifier = $aGuesses['qualifier'];
  829. }
  830. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  831. $bHeaderLine = utils::ReadParam('header_line', 0);
  832. $sClassName = utils::ReadParam('class_name', '');
  833. $bAdvanced = utils::ReadParam('advanced', 0);
  834. // Create a truncated version of the data used for the fast preview
  835. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  836. $iMaxLines = 20;
  837. $iMaxLen = strlen($sUTF8Data);
  838. $iCurPos = true;
  839. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  840. {
  841. $pos = strpos($sUTF8Data, "\n", $iCurPos);
  842. if ($pos !== false)
  843. {
  844. $iCurPos = 1+$pos;
  845. }
  846. else
  847. {
  848. $iCurPos = strlen($sUTF8Data);
  849. $iMaxLines = 1;
  850. }
  851. $iMaxLines--;
  852. }
  853. $sCSVDataTruncated = substr($sUTF8Data, 0, $iCurPos);
  854. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep2').'</h2>');
  855. $oPage->add('<div class="wizContainer">');
  856. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;">');
  857. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  858. $oPage->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  859. $oPage->add('<p><input type="radio" name="separator" value="," onClick="DoPreview()"'.IsChecked($sSeparator, ',').'/> '.Dict::S('UI:CSVImport:SeparatorComma+').'<br/>');
  860. $oPage->add('<input type="radio" name="separator" value=";" onClick="DoPreview()"'.IsChecked($sSeparator, ';').'/> '.Dict::S('UI:CSVImport:SeparatorSemicolon+').'<br/>');
  861. $oPage->add('<input type="radio" name="separator" value="tab" onClick="DoPreview()"'.IsChecked($sSeparator, "\t").'/> '.Dict::S('UI:CSVImport:SeparatorTab+').'<br/>');
  862. $oPage->add('<input type="radio" name="separator" value="other" onClick="DoPreview()"'.IsChecked($sOtherSeparator, '', true).'/> '.Dict::S('UI:CSVImport:SeparatorOther').' <input type="text" size="3" maxlength="1" name="other_separator" id="other_separator" value="'.$sOtherSeparator.'" onClick="DoPreview()"/>');
  863. $oPage->add('</p>');
  864. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;">');
  865. $oPage->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  866. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onClick="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> '.Dict::S('UI:CSVImport:QualifierDoubleQuote+').'<br/>');
  867. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onClick="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> '.Dict::S('UI:CSVImport:QualifierSimpleQuote+').'<br/>');
  868. $oPage->add('<input type="radio" name="text_qualifier" value="other" onClick="DoPreview()"'.IsChecked($sOtherTextQualifier, '', true).'/> '.Dict::S('UI:CSVImport:QualifierOther').' <input type="text" size="3" maxlength="1" name="other_qualifier" value="'.htmlentities($sOtherTextQualifier, ENT_QUOTES, 'UTF-8').'" onChange="DoPreview()"/>');
  869. $oPage->add('</p>');
  870. $oPage->add('</td><td style="vertical-align:top;">');
  871. $oPage->add('<h3>'.Dict::S('UI:CSVImport:CommentsAndHeader').'</h3>');
  872. $oPage->add('<p><input type="checkbox" name="header_line" id="box_header" value="1" onClick="DoPreview()"'.IsChecked($bHeaderLine, 1).'/> '.Dict::S('UI:CSVImport:TreatFirstLineAsHeader').'<p>');
  873. $oPage->add('<p><input type="checkbox" name="box_skiplines" value="1" id="box_skiplines" onClick="DoPreview()"'.IsChecked($bBoxSkipLines, 1).'/> '.Dict::Format('UI:CSVImport:Skip_N_LinesAtTheBeginning', '<input type="text" size=2 name="nb_skipped_lines" id="nb_skipped_lines" onChange="DoPreview()" value="'.$iSkippedLines.'">').'<p>');
  874. $oPage->add('</td></tr></table>');
  875. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  876. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sUTF8Data, ENT_QUOTES, 'UTF-8').'"/>');
  877. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  878. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  879. $oPage->add('<input type="hidden" name="step" value="3"/>');
  880. $oPage->add('<div id="preview">');
  881. $oPage->add('<p style="text-align:center">'.Dict::S('UI:CSVImport:CSVDataPreview').'</p>');
  882. $oPage->add('</div>');
  883. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="GoBack()"/>');
  884. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Next').'"/>');
  885. $oPage->add('</form>');
  886. $oPage->add('</div>');
  887. $oPage->add_script(
  888. <<<EOF
  889. function GoBack()
  890. {
  891. $('input[name=step]').val(1);
  892. $('#wizForm').submit();
  893. }
  894. var ajax_request = null;
  895. function DoPreview()
  896. {
  897. var separator = $('input[name=separator]:checked').val();
  898. if (separator == 'other')
  899. {
  900. separator = $('#other_separator').val();
  901. }
  902. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  903. if (text_qualifier == 'other')
  904. {
  905. text_qualifier = $('#other_qualifier').val();
  906. }
  907. var nb_lines_skipped = 0;
  908. if ($('#box_skiplines:checked').val() != null)
  909. {
  910. nb_lines_skipped = $('#nb_skipped_lines').val();
  911. }
  912. var header_line = 0;
  913. if ($('#box_header:checked').val() != null)
  914. {
  915. header_line = 1;
  916. }
  917. var encoding = $('input[name=encoding]').val();
  918. $('#preview').block();
  919. // Make sure that we cancel any pending request before issuing another
  920. // since responses may arrive in arbitrary order
  921. if (ajax_request != null)
  922. {
  923. ajax_request.abort();
  924. ajax_request = null;
  925. }
  926. ajax_request = $.post('ajax.csvimport.php',
  927. { operation: 'parser_preview', enctype: 'multipart/form-data', csvdata: $("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, encoding: encoding },
  928. function(data) {
  929. $('#preview').empty();
  930. $('#preview').append(data);
  931. $('#preview').unblock();
  932. }
  933. );
  934. }
  935. EOF
  936. );
  937. $oPage->add_ready_script('DoPreview();');
  938. }
  939. /**
  940. * Prompt for the data to be loaded (either via a file or a copy/paste)
  941. * @param WebPage $oPage The current web page
  942. * @return void
  943. */
  944. function Welcome(iTopWebPage $oPage)
  945. {
  946. // Encodings supported:
  947. // ICONV_CODE => Display Name
  948. // Each iconv installation supports different encodings
  949. // Some reasonably common and useful encodnings are listed here
  950. $aPossibleEncodings = array(
  951. 'UTF-8' => 'Unicode (UTF-8)',
  952. 'ISO-8859-1' => 'Western (ISO-8859-1)',
  953. 'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
  954. 'WINDOWS-1252' => 'Western (Windows 1252)',
  955. 'ISO-8859-15' => 'Western (ISO-8859-15)',
  956. );
  957. // Some more encodings can be specified in the config file
  958. $aExtraCharsets = utils::GetConfig()->GetCSVImportCharsets();
  959. $aPossibleEncodings = array_merge($aPossibleEncodings, $aExtraCharsets);
  960. asort($aPossibleEncodings);
  961. $oPage->add("<div><p><h1>".Dict::S('UI:Title:BulkImport+')."</h1></p></div>\n");
  962. $oPage->AddTabContainer('tabs1');
  963. $sSeparator = utils::ReadParam('separator', '');
  964. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  965. $bHeaderLine = utils::ReadParam('header_line', true);
  966. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  967. $sClassName = utils::ReadParam('class_name', '');
  968. $bAdvanced = utils::ReadParam('advanced', 0);
  969. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  970. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:SelectFile').'</p>'.
  971. '<p><input type="file" name="csvdata"/></p>';
  972. $sFileLoadHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  973. $sFileLoadHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE 8 has some troubles if the font is different
  974. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  975. {
  976. $sSelected = '';
  977. if ($sEncoding == $sIconvCode)
  978. {
  979. $sSelected = ' selected';
  980. }
  981. $sFileLoadHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  982. }
  983. $sFileLoadHtml .= '</select></p>';
  984. $sFileLoadHtml .= '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  985. '<input type="hidden" name="step" value="2"/>'.
  986. '<input type="hidden" name="operation" value="file_upload"/>'.
  987. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  988. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  989. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  990. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  991. '</form></div>';
  992. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:LoadFromFile'), $sFileLoadHtml);
  993. $sCSVData = utils::ReadParam('csvdata', '');
  994. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:PasteData').'</p>'.
  995. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>';
  996. $sPasteDataHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  997. $sPasteDataHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE8 has some troubles if the font is different
  998. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  999. {
  1000. $sSelected = '';
  1001. if ($sEncoding == $sIconvCode)
  1002. {
  1003. $sSelected = ' selected';
  1004. }
  1005. $sPasteDataHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1006. }
  1007. $sPasteDataHtml .= '</select></p>'.
  1008. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1009. '<input type="hidden" name="step" value="2"/>'.
  1010. '<input type="hidden" name="operation" value="csv_data"/>'.
  1011. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  1012. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  1013. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1014. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  1015. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1016. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1017. '</form></div>';
  1018. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'), $sPasteDataHtml);
  1019. if (!empty($sCSVData))
  1020. {
  1021. // When there are some data, activate the 'copy & paste' tab by default
  1022. $oPage->SelectTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'));
  1023. }
  1024. $sTemplateHtml = '<div><p>'.Dict::S('UI:CSVImport:PickClassForTemplate').' ';
  1025. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  1026. $sTemplateHtml .= '</div>';
  1027. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  1028. $sTemplateHtml .= '</div>';
  1029. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:Templates'), $sTemplateHtml);
  1030. $oPage->add_script(
  1031. <<<EOF
  1032. var ajax_request = null;
  1033. function DisplayTemplate(sClassName) {
  1034. $('#template').block();
  1035. // Make sure that we cancel any pending request before issuing another
  1036. // since responses may arrive in arbitrary order
  1037. if (ajax_request != null)
  1038. {
  1039. ajax_request.abort();
  1040. ajax_request = null;
  1041. }
  1042. ajax_request = $.post('ajax.csvimport.php',
  1043. { operation: 'get_csv_template', class_name: sClassName },
  1044. function(data) {
  1045. $('#template').empty();
  1046. $('#template').append(data);
  1047. $('#template').unblock();
  1048. }
  1049. );
  1050. }
  1051. EOF
  1052. );
  1053. $oPage->add_ready_script(
  1054. <<<EOF
  1055. $('#select_template_class').change( function() {
  1056. DisplayTemplate(this.value);
  1057. });
  1058. EOF
  1059. );
  1060. }
  1061. switch($iStep)
  1062. {
  1063. case 5:
  1064. LoadData($oPage);
  1065. break;
  1066. case 4:
  1067. Preview($oPage);
  1068. break;
  1069. case 3:
  1070. SelectMapping($oPage);
  1071. break;
  1072. case 2:
  1073. SelectOptions($oPage);
  1074. break;
  1075. case 1:
  1076. case 6: // Loop back here when we are done
  1077. default:
  1078. Welcome($oPage);
  1079. }
  1080. $oPage->output();
  1081. }
  1082. catch(CoreException $e)
  1083. {
  1084. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1085. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1086. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1087. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1088. $oP->output();
  1089. if (MetaModel::IsLogEnabledIssue())
  1090. {
  1091. if (MetaModel::IsValidClass('EventIssue'))
  1092. {
  1093. $oLog = new EventIssue();
  1094. $oLog->Set('message', $e->getMessage());
  1095. $oLog->Set('userinfo', '');
  1096. $oLog->Set('issue', $e->GetIssue());
  1097. $oLog->Set('impact', 'Page could not be displayed');
  1098. $oLog->Set('callstack', $e->getTrace());
  1099. $oLog->Set('data', $e->getContextData());
  1100. $oLog->DBInsertNoReload();
  1101. }
  1102. IssueLog::Error($e->getMessage());
  1103. }
  1104. // For debugging only
  1105. //throw $e;
  1106. }
  1107. catch(Exception $e)
  1108. {
  1109. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1110. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1111. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1112. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1113. $oP->output();
  1114. if (MetaModel::IsLogEnabledIssue())
  1115. {
  1116. if (MetaModel::IsValidClass('EventIssue'))
  1117. {
  1118. $oLog = new EventIssue();
  1119. $oLog->Set('message', $e->getMessage());
  1120. $oLog->Set('userinfo', '');
  1121. $oLog->Set('issue', 'PHP Exception');
  1122. $oLog->Set('impact', 'Page could not be displayed');
  1123. $oLog->Set('callstack', $e->getTrace());
  1124. $oLog->Set('data', array());
  1125. $oLog->DBInsertNoReload();
  1126. }
  1127. IssueLog::Error($e->getMessage());
  1128. }
  1129. }
  1130. ?>