csvimport.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * CSV Import Page
  20. * Wizard to import CSV (or TSV) data into the database
  21. *
  22. * @copyright Copyright (C) 2010-2016 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  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/ajaxwebpage.class.inc.php');
  32. require_once(APPROOT.'/application/startup.inc.php');
  33. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  34. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  35. $iStep = utils::ReadParam('step', 1);
  36. $oPage = new iTopWebPage(Dict::S('UI:Title:BulkImport'));
  37. $oPage->SetBreadCrumbEntry('ui-tool-bulkimport', Dict::S('Menu:CSVImportMenu'), Dict::S('UI:Title:BulkImport+'), '', utils::GetAbsoluteUrlAppRoot().'images/wrench.png');
  38. /**
  39. * Helper function to build a select from the list of valid classes for a given action
  40. * @param string $sName The name of the select in the HTML form
  41. * @param string $sDefaulfValue The defaut value (i.e the value selected by default)
  42. * @param integer $iWidthPx The width (in pixels) of the drop-down list
  43. * @param integer $iActionCode The ActionCode (from UserRights) to check for authorization for the classes
  44. * @return string The HTML fragment corresponding to the select tag
  45. */
  46. function GetClassesSelect($sName, $sDefaultValue, $iWidthPx, $iActionCode = null)
  47. {
  48. $sHtml = "<select id=\"select_$sName\" name=\"$sName\">";
  49. $sHtml .= "<option tyle=\"width: ".$iWidthPx."px;\" title=\"Select the class you want to load\" value=\"\">".Dict::S('UI:CSVImport:ClassesSelectOne')."</option>\n";
  50. $aValidClasses = array();
  51. $aClassCategories = array('bizmodel');
  52. if (UserRights::IsAdministrator())
  53. {
  54. $aClassCategories = array('bizmodel', 'application', 'addon/authentication');
  55. }
  56. foreach($aClassCategories as $sClassCategory)
  57. {
  58. foreach(MetaModel::GetClasses($sClassCategory) as $sClassName)
  59. {
  60. if ( (is_null($iActionCode) || UserRights::IsActionAllowed($sClassName, $iActionCode)) &&
  61. (!MetaModel::IsAbstract($sClassName)) )
  62. {
  63. $sSelected = ($sClassName == $sDefaultValue) ? " selected" : "";
  64. $sDescription = MetaModel::GetClassDescription($sClassName);
  65. $sDisplayName = MetaModel::GetName($sClassName);
  66. $aValidClasses[$sDisplayName] = "<option style=\"width: ".$iWidthPx."px;\" title=\"$sDescription\" value=\"$sClassName\"$sSelected>$sDisplayName</option>";
  67. }
  68. }
  69. }
  70. ksort($aValidClasses);
  71. $sHtml .= implode("\n", $aValidClasses);
  72. $sHtml .= "</select>";
  73. return $sHtml;
  74. }
  75. /**
  76. * Helper to 'check' an input in an HTML form if the current value equals the value given
  77. * @param mixed $sCurrentValue The current value to be chacked against the value of the input
  78. * @param mixed $sProposedValue The value of the input
  79. * @param bool $bInverseCondition Set to true to perform the reversed comparison
  80. * @return string Either ' checked' or an empty string
  81. */
  82. function IsChecked($sCurrentValue, $sProposedValue, $bInverseCondition = false)
  83. {
  84. $bCondition = ($sCurrentValue == $sProposedValue);
  85. return ($bCondition xor $bInverseCondition) ? ' checked' : '';
  86. }
  87. /**
  88. * Returns the number of occurences of each char from the set in the specified string
  89. * @param string $sString The input data
  90. * @param array $aSet The set of characters to count
  91. * @return hash 'char' => nb of occurences
  92. */
  93. function CountCharsFromSet($sString, $aSet)
  94. {
  95. $aResult = array();
  96. $aCount = count_chars($sString);
  97. foreach($aSet as $sChar)
  98. {
  99. $aResult[$sChar] = isset($aCount[ord($sChar)]) ? $aCount[ord($sChar)] : 0;
  100. }
  101. return $aResult;
  102. }
  103. /**
  104. * Return the most frequent (and regularly occuring) character among the given set, in the specified lines
  105. * @param array $aCSVData The input data, one entry per line
  106. * @param array $aPossibleSeparators The list of characters to count
  107. * @return string The most frequent character from the set
  108. */
  109. function GuessFromFrequency($aCSVData, $aPossibleSeparators)
  110. {
  111. $iLine = 0;
  112. $iMaxLine = 20; // Process max 20 lines to guess the parameters
  113. foreach($aPossibleSeparators as $sSep)
  114. {
  115. $aGuesses[$sSep]['total'] = $aGuesses[$sSep]['max'] = 0;
  116. $aGuesses[$sSep]['min'] = 999;
  117. }
  118. $aStats = array();
  119. while(($iLine < count($aCSVData)) && ($iLine < $iMaxLine) )
  120. {
  121. if (strlen($aCSVData[$iLine]) > 0)
  122. {
  123. $aStats[$iLine] = CountCharsFromSet($aCSVData[$iLine], $aPossibleSeparators);
  124. }
  125. $iLine++;
  126. }
  127. $iLine = 1;
  128. foreach($aStats as $aLineStats)
  129. {
  130. foreach($aPossibleSeparators as $sSep)
  131. {
  132. $aGuesses[$sSep]['total'] += $aLineStats[$sSep];
  133. if ($aLineStats[$sSep] > $aGuesses[$sSep]['max']) $aGuesses[$sSep]['max'] = $aLineStats[$sSep];
  134. if ($aLineStats[$sSep] < $aGuesses[$sSep]['min']) $aGuesses[$sSep]['min'] = $aLineStats[$sSep];
  135. }
  136. $iLine++;
  137. }
  138. $aScores = array();
  139. foreach($aGuesses as $sSep => $aData)
  140. {
  141. $aScores[$sSep] = $aData['total'] + $aData['max'] - $aData['min'];
  142. }
  143. arsort($aScores, SORT_NUMERIC); // Sort the array, higher scores first
  144. $aKeys = array_keys($aScores);
  145. $sSeparator = $aKeys[0]; // Take the first key, the one with the best score
  146. return $sSeparator;
  147. }
  148. /**
  149. * Try to predict the CSV parameters based on the input data
  150. * @param string $sCSVData The input data
  151. * @return hash 'separator' => the_guessed_separator, 'qualifier' => the_guessed_text_qualifier
  152. */
  153. function GuessParameters($sCSVData)
  154. {
  155. $aData = explode("\n", $sCSVData);
  156. $sSeparator = GuessFromFrequency($aData, array("\t", ',', ';', '|')); // Guess the most frequent (and regular) character on each line
  157. $sQualifier = GuessFromFrequency($aData, array('"', "'")); // Guess the most frequent (and regular) character on each line
  158. return array('separator' => $sSeparator, 'qualifier' => $sQualifier);
  159. }
  160. /**
  161. * Display a banner for the special "synchro" mode
  162. * @param WebPage $oP The Page for the output
  163. * @param string $sClass The class of objects to synchronize
  164. * @param integer $iCount The number of objects to synchronize
  165. * @return none
  166. */
  167. function DisplaySynchroBanner(WebPage $oP, $sClass, $iCount)
  168. {
  169. $oP->add("<div class=\"notification\"><p><h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Title:BulkSynchro_nbItem_ofClass_class', $iCount, MetaModel::GetName($sClass))."</h1></p></div>\n");
  170. }
  171. /**
  172. * Process the CSV data, for real or as a simulation
  173. * @param WebPage $oPage The page used to display the wizard
  174. * @param bool $bSimulate Whether or not to simulate the data load
  175. * @return array The CSV lines in error that were rejected from the load (with the header line - if any) or null
  176. */
  177. function ProcessCSVData(WebPage $oPage, $bSimulate = true)
  178. {
  179. $aResult = array();
  180. $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data');
  181. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '', false, 'raw_data');
  182. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  183. $sTextQualifier = utils::ReadParam('text_qualifier', '"', false, 'raw_data');
  184. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  185. $iSkippedLines = 0;
  186. if (utils::ReadParam('box_skiplines', '0') == 1)
  187. {
  188. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  189. }
  190. $sClassName = utils::ReadParam('class_name', '', false, 'class');
  191. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  192. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  193. $iCurrentStep = $bSimulate ? 4 : 5;
  194. $bAdvanced = utils::ReadParam('advanced', 0);
  195. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  196. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  197. $sDateTimeFormat = utils::ReadParam('date_time_format', 'default');
  198. $sCustomDateTimeFormat = utils::ReadParam('custom_date_time_format', (string)AttributeDateTime::GetFormat(), false, 'raw_data');
  199. $sChosenDateFormat = ($sDateTimeFormat == 'default') ? (string)AttributeDateTime::GetFormat() : $sCustomDateTimeFormat;
  200. if (!empty($sSynchroScope))
  201. {
  202. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  203. $sClassName = $oSearch->GetClass(); // If a synchronization scope is set, then the class is fixed !
  204. $oSet = new DBObjectSet($oSearch);
  205. $iCount = $oSet->Count();
  206. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  207. $sClassesSelect = "<select id=\"select_class_name\" name=\"class_name\"><option value=\"$sClassName\" selected>".MetaModel::GetName($sClassName)."</option>";
  208. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  209. }
  210. else
  211. {
  212. $sSynchroScope = '';
  213. $aSynchroUpdate = null;
  214. }
  215. // Parse the data set
  216. $oCSVParser = new CSVParser($sCSVData, $sSeparator, $sTextQualifier, MetaModel::GetConfig()->Get('max_execution_time_per_loop'));
  217. $aData = $oCSVParser->ToArray($iSkippedLines);
  218. $iRealSkippedLines = $iSkippedLines;
  219. if ($bHeaderLine)
  220. {
  221. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier, array_shift($aData)).$sTextQualifier; // Remove the first line and store it in case of error
  222. $iRealSkippedLines++;
  223. }
  224. // Format for the line numbers
  225. $sMaxLen = (strlen(''.count($aData)) < 3) ? 3 : strlen(''.count($aData)); // Pad line numbers to the appropriate number of chars, but at least 3
  226. // Compute the list of search/reconciliation criteria
  227. $aSearchKeys = array();
  228. foreach($aSearchFields as $index => $sDummy)
  229. {
  230. $sSearchField = $aFieldsMapping[$index];
  231. $aMatches = array();
  232. if (preg_match('/(.+)->(.+)/', $sSearchField, $aMatches) > 0)
  233. {
  234. $sSearchField = $aMatches[1];
  235. $aSearchKeys[$aMatches[1]] = '';
  236. }
  237. else
  238. {
  239. $aSearchKeys[$sSearchField] = '';
  240. }
  241. if (!MetaModel::IsValidFilterCode($sClassName, $sSearchField))
  242. {
  243. // Remove invalid or unmapped search fields
  244. $aSearchFields[$index] = null;
  245. unset($aSearchKeys[$sSearchField]);
  246. }
  247. }
  248. // Compute the list of fields and external keys to process
  249. $aExtKeys = array();
  250. $aAttributes = array();
  251. $aExternalKeysByColumn = array();
  252. foreach($aFieldsMapping as $iNumber => $sAttCode)
  253. {
  254. $iIndex = $iNumber-1;
  255. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  256. {
  257. if (preg_match('/(.+)->(.+)/', $sAttCode, $aMatches) > 0)
  258. {
  259. $sAttribute = $aMatches[1];
  260. $sField = $aMatches[2];
  261. $aExtKeys[$sAttribute][$sField] = $iIndex;
  262. $aExternalKeysByColumn[$iIndex] = $sAttribute;
  263. }
  264. else
  265. {
  266. if ($sAttCode == 'id')
  267. {
  268. $aAttributes['id'] = $iIndex;
  269. }
  270. else
  271. {
  272. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  273. if ($oAttDef->IsExternalKey())
  274. {
  275. $aExtKeys[$sAttCode]['id'] = $iIndex;
  276. $aExternalKeysByColumn[$iIndex] = $sAttCode;
  277. }
  278. else
  279. {
  280. $aAttributes[$sAttCode] = $iIndex;
  281. }
  282. }
  283. }
  284. }
  285. }
  286. $oMyChange = null;
  287. if (!$bSimulate)
  288. {
  289. // We're doing it for real, let's create a change
  290. $sUserString = CMDBChange::GetCurrentUserName().' (CSV)';
  291. CMDBObject::SetTrackInfo($sUserString);
  292. CMDBObject::SetTrackOrigin('csv-interactive');
  293. $oMyChange = CMDBObject::GetCurrentChange();
  294. }
  295. $oBulk = new BulkChange(
  296. $sClassName,
  297. $aData,
  298. $aAttributes,
  299. $aExtKeys,
  300. array_keys($aSearchKeys),
  301. empty($sSynchroScope) ? null : $sSynchroScope,
  302. $aSynchroUpdate,
  303. $sChosenDateFormat, // date format
  304. true // localize
  305. );
  306. $oBulk->SetReportHtml();
  307. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  308. $aRes = $oBulk->Process($oMyChange);
  309. $sHtml = '<table id="bulk_preview" style="border-collapse: collapse;">';
  310. $sHtml .= '<tr><th style="padding:2px;border-right: 2px #fff solid;">Line</th>';
  311. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Status</th>';
  312. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Object</th>';
  313. foreach($aFieldsMapping as $iNumber => $sAttCode)
  314. {
  315. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  316. {
  317. $sHtml .= "<th style=\"padding:2px;border-right: 2px #fff solid;\">".MetaModel::GetLabel($sClassName, $sAttCode)."</th>";
  318. }
  319. }
  320. $sHtml .= '<th>Message</th>';
  321. $sHtml .= '</tr>';
  322. $iErrors = 0;
  323. $iCreated = 0;
  324. $iModified = 0;
  325. $iUnchanged = 0;
  326. foreach($aRes as $iLine => $aResRow)
  327. {
  328. $oStatus = $aResRow['__STATUS__'];
  329. $sUrl = '';
  330. $sMessage = '';
  331. $sCSSRowClass = '';
  332. $sCSSMessageClass = 'cell_ok';
  333. switch(get_class($oStatus))
  334. {
  335. case 'RowStatus_NoChange':
  336. $iUnchanged++;
  337. $sFinalClass = $aResRow['finalclass'];
  338. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  339. $sUrl = $oObj->GetHyperlink();
  340. $sStatus = '<img src="../images/unchanged.png" title="'.Dict::S('UI:CSVReport-Icon-Unchanged').'">';
  341. $sCSSRowClass = 'row_unchanged';
  342. break;
  343. case 'RowStatus_Modify':
  344. $iModified++;
  345. $sFinalClass = $aResRow['finalclass'];
  346. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  347. $sUrl = $oObj->GetHyperlink();
  348. $sStatus = '<img src="../images/modified.png" title="'.Dict::S('UI:CSVReport-Icon-Modified').'">';
  349. $sCSSRowClass = 'row_modified';
  350. break;
  351. case 'RowStatus_Disappeared':
  352. $iModified++;
  353. $sFinalClass = $aResRow['finalclass'];
  354. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  355. $sUrl = $oObj->GetHyperlink();
  356. $sStatus = '<img src="../images/delete.png" title="'.Dict::S('UI:CSVReport-Icon-Missing').'">';
  357. $sCSSRowClass = 'row_modified';
  358. if ($bSimulate)
  359. {
  360. $sMessage = Dict::S('UI:CSVReport-Object-MissingToUpdate');
  361. }
  362. else
  363. {
  364. $sMessage = Dict::S('UI:CSVReport-Object-MissingUpdated');
  365. }
  366. break;
  367. case 'RowStatus_NewObj':
  368. $iCreated++;
  369. $sFinalClass = $aResRow['finalclass'];
  370. $sStatus = '<img src="../images/added.png" title="'.Dict::S('UI:CSVReport-Icon-Created').'">';
  371. $sCSSRowClass = 'row_added';
  372. if ($bSimulate)
  373. {
  374. $sMessage = Dict::S('UI:CSVReport-Object-ToCreate');
  375. }
  376. else
  377. {
  378. $sFinalClass = $aResRow['finalclass'];
  379. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  380. $sUrl = $oObj->GetHyperlink();
  381. $sMessage = Dict::S('UI:CSVReport-Object-Created');
  382. }
  383. break;
  384. case 'RowStatus_Issue':
  385. $iErrors++;
  386. $sMessage .= $oPage->GetP($oStatus->GetDescription());
  387. $sStatus = '<img src="../images/error.png" title="'.Dict::S('UI:CSVReport-Icon-Error').'">';//translate
  388. $sCSSMessageClass = 'cell_error';
  389. $sCSSRowClass = 'row_error';
  390. if (array_key_exists($iLine, $aData))
  391. {
  392. $aRow = $aData[$iLine];
  393. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier,$aRow).$sTextQualifier; // Remove the first line and store it in case of error
  394. }
  395. break;
  396. }
  397. $sHtml .= '<tr class="'.$sCSSRowClass.'">';
  398. $sHtml .= "<td style=\"background-color:#f1f1f1;border-right:2px #fff solid;\">".sprintf("%0{$sMaxLen}d", 1+$iLine+$iRealSkippedLines)."</td>";
  399. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;border-right:2px #fff solid;\">$sStatus</td>";
  400. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;\">$sUrl</td>";
  401. foreach($aFieldsMapping as $iNumber => $sAttCode)
  402. {
  403. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  404. {
  405. $oCellStatus = $aResRow[$iNumber -1];
  406. $sCellMessage = '';
  407. if (isset($aExternalKeysByColumn[$iNumber -1]))
  408. {
  409. $sExtKeyName = $aExternalKeysByColumn[$iNumber -1];
  410. $oExtKeyCellStatus = $aResRow[$sExtKeyName];
  411. switch(get_class($oExtKeyCellStatus))
  412. {
  413. case 'CellStatus_Issue':
  414. case 'CellStatus_SearchIssue':
  415. case 'CellStatus_NullIssue':
  416. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  417. break;
  418. case 'CellStatus_Ambiguous':
  419. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  420. break;
  421. default:
  422. // Do nothing
  423. }
  424. }
  425. $sHtmlValue = $oCellStatus->GetDisplayableValue();
  426. switch(get_class($oCellStatus))
  427. {
  428. case 'CellStatus_Issue':
  429. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  430. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">'.Dict::Format('UI:CSVReport-Object-Error', $sHtmlValue).$sCellMessage.'</td>';
  431. break;
  432. case 'CellStatus_SearchIssue':
  433. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  434. $sHtml .= '<td class="cell_error">ERROR: '.$sHtmlValue.$sCellMessage.'</td>';
  435. break;
  436. case 'CellStatus_Ambiguous':
  437. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  438. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">'.Dict::Format('UI:CSVReport-Object-Ambiguous', $sHtmlValue).$sCellMessage.'</td>';
  439. break;
  440. case 'CellStatus_Modify':
  441. $sHtml .= '<td class="cell_modified" style="border-right:1px #eee solid;"><b>'.$sHtmlValue.'</b></td>';
  442. break;
  443. default:
  444. $sHtml .= '<td class="cell_ok" style="border-right:1px #eee solid;">'.$sHtmlValue.$sCellMessage.'</td>';
  445. }
  446. }
  447. }
  448. $sHtml .= "<td class=\"$sCSSMessageClass\" style=\"background-color:#f1f1f1;\">$sMessage</td>";
  449. $sHtml .= '</tr>';
  450. }
  451. $iUnchanged = count($aRes) - $iErrors - $iModified - $iCreated;
  452. $sHtml .= '</table>';
  453. $oPage->add('<div class="wizContainer" style="width:auto;display:inline-block;">');
  454. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post">');
  455. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  456. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  457. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  458. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  459. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>');
  460. $oPage->add('<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>');
  461. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  462. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  463. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  464. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  465. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'"/>');
  466. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  467. $oPage->add('<input type="hidden" name="date_time_format" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>');
  468. $oPage->add('<input type="hidden" name="custom_date_time_format" value="'.htmlentities($sCustomDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>');
  469. if (!empty($sSynchroScope))
  470. {
  471. foreach($aSynchroUpdate as $sKey => $value)
  472. {
  473. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  474. }
  475. }
  476. foreach($aFieldsMapping as $iNumber => $sAttCode)
  477. {
  478. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  479. }
  480. foreach($aSearchFields as $index => $sDummy)
  481. {
  482. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  483. }
  484. $aDisplayFilters = array();
  485. if ($bSimulate)
  486. {
  487. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsWillStayUnchanged');
  488. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWillBeModified');
  489. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWillBeAdded');
  490. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsWillHaveErrors');
  491. }
  492. else
  493. {
  494. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsRemainedUnchanged');
  495. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWereModified');
  496. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWereAdded');
  497. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsHadErrors');
  498. }
  499. $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;');
  500. $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;');
  501. $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;');
  502. $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>');
  503. $oPage->add('<div class="white" style="display:inline-block">');
  504. $oPage->add($sHtml);
  505. $oPage->add('</div> <!-- end of preview -->');
  506. $oPage->add('<p>');
  507. if($bSimulate)
  508. {
  509. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Restart').'" onClick="CSVRestart()"/>&nbsp;&nbsp;');
  510. }
  511. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  512. $bShouldConfirm = false;
  513. if ($bSimulate)
  514. {
  515. // if there are *too many* changes, we should ask the user for a confirmation
  516. if (count($aRes) >= MetaModel::GetConfig()->Get('csv_import_min_object_confirmation'))
  517. {
  518. $fErrorsPercentage = (100.0*$iErrors)/count($aRes);
  519. if ($fErrorsPercentage >= MetaModel::GetConfig()->Get('csv_import_errors_percentage'))
  520. {
  521. $sMessage = Dict::Format('UI:CSVReport-Stats-Errors', $fErrorsPercentage);
  522. $bShouldConfirm = true;
  523. }
  524. $fCreatedPercentage = (100.0*$iCreated)/count($aRes);
  525. if ($fCreatedPercentage >= MetaModel::GetConfig()->Get('csv_import_creations_percentage'))
  526. {
  527. $sMessage = Dict::Format('UI:CSVReport-Stats-Created', $fCreatedPercentage);
  528. $bShouldConfirm = true;
  529. }
  530. $fModifiedPercentage = (100.0*$iModified)/count($aRes);
  531. if ($fModifiedPercentage >= MetaModel::GetConfig()->Get('csv_import_modifications_percentage'))
  532. {
  533. $sMessage = Dict::Format('UI:CSVReport-Stats-Modified', $fModifiedPercentage);
  534. $bShouldConfirm = true;
  535. }
  536. }
  537. $iCount = count($aRes);
  538. //$oPage->add('<input type="submit" value="'.Dict::S('UI:Button:DoImport').'" onClick="$(\'#wizForm\').block();"/></p>');
  539. $sConfirm = $bShouldConfirm ? 'true' : 'false';
  540. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:DoImport')."\" onClick=\"return DoSubmit($sConfirm);\"/></p>");
  541. }
  542. else
  543. {
  544. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Done').'"/></p>');
  545. }
  546. $oPage->add('</form>');
  547. $oPage->add('</div> <!-- end of wizForm -->');
  548. if ($bShouldConfirm)
  549. {
  550. $sYesButton = Dict::S('UI:Button:Ok');
  551. $sNoButton = Dict::S('UI:Button:Cancel');
  552. $oPage->add('<div id="dlg_confirmation" title="'.htmlentities(Dict::S('UI:CSVImportConfirmTitle'), ENT_QUOTES, 'UTF-8').'">');
  553. $oPage->add('<p style="text-align:center"><b>'.$sMessage.'</b></p>');
  554. $oPage->add('<p style="text-align:center">'.htmlentities(Dict::S('UI:CSVImportConfirmMessage'), ENT_QUOTES, 'UTF-8').'</p>');
  555. $oPage->add('<div id="confirmation_chart" style="width:100%;height:300px;overflow:hidden"></div>');
  556. $oPage->add('</div> <!-- end of dlg_confirmation -->');
  557. $oPage->add_ready_script(
  558. <<<EOF
  559. $('#dlg_confirmation').dialog(
  560. {
  561. height: 'auto',
  562. width: 500,
  563. modal:true,
  564. autoOpen: false,
  565. buttons:
  566. {
  567. '$sYesButton': RunImport,
  568. '$sNoButton': CancelImport
  569. }
  570. });
  571. EOF
  572. );
  573. }
  574. $sErrors = json_encode(Dict::Format('UI:CSVImportError_items', $iErrors));
  575. $sCreated = json_encode(Dict::Format('UI:CSVImportCreated_items', $iCreated));
  576. $sModified = json_encode(Dict::Format('UI:CSVImportModified_items', $iModified));
  577. $sUnchanged = json_encode(Dict::Format('UI:CSVImportUnchanged_items', $iUnchanged));
  578. $oPage->add_script(
  579. <<< EOF
  580. function CSVGoBack()
  581. {
  582. $('input[name=step]').val($iCurrentStep-1);
  583. $('#wizForm').submit();
  584. }
  585. function CSVRestart()
  586. {
  587. $('input[name=step]').val(1);
  588. $('#wizForm').submit();
  589. }
  590. function ToggleRows(sCSSClass)
  591. {
  592. $('.'+sCSSClass).toggle();
  593. }
  594. function DoSubmit(bConfirm)
  595. {
  596. if (bConfirm) //Ask for a confirmation
  597. {
  598. $('#dlg_confirmation').dialog('open');
  599. var chart = c3.generate({
  600. bindto: '#confirmation_chart',
  601. data: {
  602. columns: [
  603. ['errors', $iErrors],
  604. ['created', $iCreated],
  605. ['modified', $iModified],
  606. ['unchanged', $iUnchanged]
  607. ],
  608. colors: {
  609. errors: '#FF6666',
  610. created: '#66FF66',
  611. modified: '#6666FF',
  612. unchanged: '#666666'
  613. },
  614. names: {
  615. errors: $sErrors,
  616. created: $sCreated,
  617. modified: $sModified,
  618. unchanged: $sUnchanged
  619. },
  620. type: 'donut'
  621. },
  622. legend: {
  623. show: true,
  624. }
  625. });
  626. }
  627. else
  628. {
  629. // Submit the form
  630. $('#wizForm').block();
  631. $('#wizForm').submit();
  632. }
  633. return false;
  634. }
  635. function CancelImport()
  636. {
  637. $('#dlg_confirmation').dialog('close');
  638. }
  639. function RunImport()
  640. {
  641. $('#dlg_confirmation').dialog('close');
  642. // Submit the form
  643. $('#wizForm').block();
  644. $('#wizForm').submit();
  645. }
  646. EOF
  647. );
  648. if ($iErrors > 0)
  649. {
  650. return $aResult;
  651. }
  652. else
  653. {
  654. return null;
  655. }
  656. }
  657. /**
  658. * Perform the actual load of the CSV data and display the results
  659. * @param WebPage $oPage The web page to display the wizard
  660. * @return void
  661. */
  662. function LoadData(WebPage $oPage)
  663. {
  664. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep5').'</h2>');
  665. $aResult = ProcessCSVData($oPage, false /* simulate = false */);
  666. if (is_array($aResult))
  667. {
  668. $oPage->StartCollapsibleSection(Dict::S('UI:CSVImport:LinesNotImported'), false);
  669. $oPage->p(Dict::S('UI:CSVImport:LinesNotImported+'));
  670. $oPage->add('<textarea rows="30" cols="100">');
  671. $oPage->add(htmlentities(implode("\n", $aResult), ENT_QUOTES, 'UTF-8'));
  672. $oPage->add('</textarea>');
  673. $oPage->EndCollapsibleSection();
  674. }
  675. }
  676. /**
  677. * Simulate the load of the CSV data and display the results
  678. * @param WebPage $oPage The web page to display the wizard
  679. * @return void
  680. */
  681. function Preview(WebPage $oPage)
  682. {
  683. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep4').'</h2>');
  684. ProcessCSVData($oPage, true /* simulate */);
  685. }
  686. /**
  687. * Select the mapping between the CSV column and the fields of the objects
  688. * @param WebPage $oPage The web page to display the wizard
  689. * @return void
  690. */
  691. function SelectMapping(WebPage $oPage)
  692. {
  693. $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data');
  694. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '', false, 'raw_data');
  695. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  696. if ($sSeparator == 'tab') $sSeparator = "\t";
  697. if ($sSeparator == 'other')
  698. {
  699. $sSeparator = utils::ReadParam('other_separator', ',', false, 'raw_data');
  700. }
  701. $sTextQualifier = utils::ReadParam('text_qualifier', '"', false, 'raw_data');
  702. if ($sTextQualifier == 'other')
  703. {
  704. $sTextQualifier = utils::ReadParam('other_qualifier', '"', false, 'raw_data');
  705. }
  706. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  707. $sClassName = utils::ReadParam('class_name', '', false, 'class');
  708. $bAdvanced = utils::ReadParam('advanced', 0);
  709. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  710. $sDateTimeFormat = utils::ReadParam('date_time_format', 'default');
  711. $sCustomDateTimeFormat = utils::ReadParam('custom_date_time_format', (string)AttributeDateTime::GetFormat(), false, 'raw_data');
  712. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  713. if (!empty($sSynchroScope))
  714. {
  715. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  716. $sClassName = $oSearch->GetClass(); // If a synchronization scope is set, then the class is fixed !
  717. $oSet = new DBObjectSet($oSearch);
  718. $iCount = $oSet->Count();
  719. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  720. $sClassesSelect = "<select id=\"select_class_name\" name=\"class_name\"><option value=\"$sClassName\" selected>".MetaModel::GetName($sClassName)."</option>";
  721. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  722. }
  723. else
  724. {
  725. $sClassesSelect = GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY);
  726. }
  727. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep3').'</h2>');
  728. $oPage->add('<div class="wizContainer">');
  729. $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').' ');
  730. $oPage->add($sClassesSelect);
  731. $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>');
  732. $oPage->add('<div style="padding:1em;display:none" id="advanced_help" style="display:none">'.Dict::S('UI:CSVImport:AdvancedMode+').'</div>');
  733. $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>');
  734. $oPage->add('<input type="hidden" name="step" value="4"/>');
  735. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  736. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  737. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  738. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>');
  739. $oPage->add('<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>');
  740. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  741. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  742. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'">');
  743. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'">');
  744. $oPage->add('<input type="hidden" name="date_time_format" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>');
  745. $oPage->add('<input type="hidden" name="custom_date_time_format" value="'.htmlentities($sCustomDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>');
  746. if (!empty($sSynchroScope))
  747. {
  748. foreach($aSynchroUpdate as $sKey => $value)
  749. {
  750. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  751. }
  752. }
  753. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Restart').'" onClick="CSVRestart()"/>&nbsp;&nbsp;');
  754. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  755. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:SimulateImport').'"/></p>');
  756. $oPage->add('</form>');
  757. $oPage->add('</div>');
  758. $sAlertIncompleteMapping = addslashes(Dict::S('UI:CSVImport:AlertIncompleteMapping'));
  759. $sAlertMultipleMapping = addslashes(Dict::S('UI:CSVImport:AlertMultipleMapping'));
  760. $sAlertNoSearchCriteria = addslashes(Dict::S('UI:CSVImport:AlertNoSearchCriteria'));
  761. $oPage->add_ready_script(
  762. <<<EOF
  763. $('#select_class_name').change( function(ev) { DoMapping(); } );
  764. EOF
  765. );
  766. if ($sClassName != '')
  767. {
  768. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  769. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  770. $sFieldsMapping = addslashes(json_encode($aFieldsMapping));
  771. $sSearchFields = addslashes(json_encode($aSearchFields));
  772. $oPage->add_ready_script("DoMapping('$sFieldsMapping', '$sSearchFields');"); // There is already a class selected, run the mapping
  773. }
  774. $oPage->add_script(
  775. <<<EOF
  776. var aDefaultKeys = new Array();
  777. var aReadOnlyKeys = new Array();
  778. function CSVGoBack()
  779. {
  780. $('input[name=step]').val(2);
  781. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  782. $('#wizForm').submit();
  783. }
  784. function CSVRestart()
  785. {
  786. $('input[name=step]').val(1);
  787. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  788. $('#wizForm').submit();
  789. }
  790. var ajax_request = null;
  791. function DoMapping(sInitFieldsMapping, sInitSearchFields)
  792. {
  793. var class_name = $('select[name=class_name]').val();
  794. var advanced = $('input[name=advanced]:checked').val();
  795. if (advanced != 1)
  796. {
  797. $('#advanced_help').hide();
  798. }
  799. else
  800. {
  801. $('#advanced_help').show();
  802. }
  803. if (class_name != '')
  804. {
  805. var separator = $('input[name=separator]').val();
  806. var text_qualifier = $('input[name=text_qualifier]').val();
  807. var header_line = $('input[name=header_line]').val();
  808. var do_skip_lines = 0;
  809. if ($('input[name=box_skiplines]').val() == '1')
  810. {
  811. do_skip_lines = $('input[name=nb_skipped_lines]').val();
  812. }
  813. var csv_data = $('input[name=csvdata]').val();
  814. var encoding = $('input[name=encoding]').val();
  815. if (advanced != 1)
  816. {
  817. advanced = 0;
  818. }
  819. $('#mapping').block();
  820. // Make sure that we cancel any pending request before issuing another
  821. // since responses may arrive in arbitrary order
  822. if (ajax_request != null)
  823. {
  824. ajax_request.abort();
  825. ajax_request = null;
  826. }
  827. var aParams = { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator,
  828. qualifier: text_qualifier, do_skip_lines: do_skip_lines, header_line: header_line, class_name: class_name,
  829. advanced: advanced, encoding: encoding };
  830. if (sInitFieldsMapping != undefined)
  831. {
  832. aParams.init_field_mapping = sInitFieldsMapping;
  833. aParams.init_search_field = sInitSearchFields;
  834. }
  835. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  836. aParams,
  837. function(data) {
  838. $('#mapping').empty();
  839. $('#mapping').append(data);
  840. $('#mapping').unblock();
  841. }
  842. );
  843. }
  844. }
  845. function CheckValues()
  846. {
  847. // Reset the highlight in case the check has already been executed with failure
  848. $('select[name^=field]').each( function() {
  849. $(this).parent().css({'border': '0'});
  850. });
  851. bResult = true;
  852. bMappingOk = true;
  853. bMultipleMapping = false;
  854. bSearchOk = false;
  855. $('select[name^=field]').each( function() {
  856. $(this).parent().css({'border': '0'});
  857. if ($(this).val() == '')
  858. {
  859. $(this).parent().css({'border': '2px #D81515 solid'});
  860. bMappingOk = false;
  861. bResult = false;
  862. }
  863. else
  864. {
  865. iOccurences = 0;
  866. sRefValue = $(this).val();
  867. $('select[name^=field]').each( function() {
  868. if ($(this).val() == sRefValue)
  869. {
  870. iOccurences++;
  871. }
  872. });
  873. if ((iOccurences > 1) && (sRefValue != ':none:'))
  874. {
  875. $(this).parent().css({'border': '2px #D81515 solid'});
  876. bResult = false;
  877. bMultipleMapping = true;
  878. }
  879. }
  880. });
  881. // At least one search field must be checked
  882. $('input[name^=search]:checked').each( function() {
  883. bSearchOk = true;
  884. });
  885. if (!bMappingOk)
  886. {
  887. alert("$sAlertIncompleteMapping");
  888. }
  889. if (bMultipleMapping)
  890. {
  891. alert("$sAlertMultipleMapping");
  892. }
  893. if (!bSearchOk)
  894. {
  895. bResult = false;
  896. alert("$sAlertNoSearchCriteria");
  897. }
  898. if (bResult)
  899. {
  900. $('#mapping').block();
  901. // Re-enable all search_xxx checkboxes so that their value gets posted
  902. $('input[name^=search]').each(function() {
  903. $(this).attr('disabled', false);
  904. });
  905. }
  906. return bResult;
  907. }
  908. function DoCheckMapping()
  909. {
  910. // Check if there is a field mapped to 'id'
  911. // In which case, it's the only possible search key
  912. var idSelected = 0;
  913. var nbSearchKeys = $('input[name^=search]:checked').length;
  914. var nbMappings = $('select[name^=field]').length;
  915. for(index=1; index <= nbMappings; index++)
  916. {
  917. var selectedValue = $('#mapping_'+index).val();
  918. if (selectedValue == 'id')
  919. {
  920. idSelected = index;
  921. }
  922. }
  923. for (index=1; index <= nbMappings; index++)
  924. {
  925. sMappingValue = $('#mapping_'+index).val();
  926. if ((sMappingValue == '') || (sMappingValue == ':none:'))
  927. {
  928. // Non-mapped field, uncheck and disabled
  929. $('#search_'+index).attr('checked', false);
  930. $('#search_'+index).attr('disabled', true);
  931. }
  932. else if (aReadOnlyKeys.indexOf(sMappingValue) >= 0)
  933. {
  934. // Read-only attribute forced to reconciliation key
  935. $('#search_'+index).attr('checked', true);
  936. $('#search_'+index).attr('disabled', true);
  937. }
  938. else if (index == idSelected)
  939. {
  940. // The 'id' field was mapped, it's the only possible reconciliation key
  941. $('#search_'+index).attr('checked', true);
  942. $('#search_'+index).attr('disabled', true);
  943. }
  944. else
  945. {
  946. if (idSelected > 0)
  947. {
  948. // The 'id' field was mapped, it's the only possible reconciliation key
  949. $('#search_'+index).attr('checked', false);
  950. $('#search_'+index).attr('disabled', true);
  951. }
  952. else
  953. {
  954. $('#search_'+index).attr('disabled', false);
  955. if (nbSearchKeys == 0)
  956. {
  957. // No search key was selected, select the default ones
  958. for(j =0; j < aDefaultKeys.length; j++)
  959. {
  960. if (sMappingValue == aDefaultKeys[j])
  961. {
  962. $('#search_'+index).attr('checked', true);
  963. }
  964. }
  965. }
  966. }
  967. }
  968. }
  969. }
  970. EOF
  971. );
  972. }
  973. /**
  974. * Select the options of the CSV load and check for CSV parsing errors
  975. * @param WebPage $oPage The current web page
  976. * @return void
  977. */
  978. function SelectOptions(WebPage $oPage)
  979. {
  980. $sOperation = utils::ReadParam('operation', 'csv_data');
  981. $sCSVData = '';
  982. switch($sOperation)
  983. {
  984. case 'file_upload':
  985. $oDocument = utils::ReadPostedDocument('csvdata');
  986. if (!$oDocument->IsEmpty())
  987. {
  988. $sCSVData = $oDocument->GetData();
  989. }
  990. break;
  991. default:
  992. $sCSVData = utils::ReadPostedParam('csvdata', '', 'raw_data');
  993. }
  994. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  995. // Compute a subset of the data set, now that we know the charset
  996. if ($sEncoding == 'UTF-8')
  997. {
  998. // Remove the BOM if any
  999. if (substr($sCSVData, 0, 3) == UTF8_BOM)
  1000. {
  1001. $sCSVData = substr($sCSVData, 3);
  1002. }
  1003. // Clean the input
  1004. // Todo: warn the user if some characters are lost/substituted
  1005. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  1006. }
  1007. else
  1008. {
  1009. $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  1010. }
  1011. $aGuesses = GuessParameters($sUTF8Data); // Try to predict the parameters, based on the input data
  1012. $sSeparator = utils::ReadParam('separator', '', false, 'raw_data');
  1013. if ($sSeparator == '') // May be set to an empty value by the previous page
  1014. {
  1015. $sSeparator = $aGuesses['separator'];
  1016. }
  1017. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  1018. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  1019. if ($sSeparator == 'tab') $sSeparator = "\t";
  1020. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  1021. $sTextQualifier = utils::ReadParam('text_qualifier', '', false, 'raw_data');
  1022. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  1023. {
  1024. $sTextQualifier = $aGuesses['qualifier'];
  1025. }
  1026. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  1027. $bHeaderLine = utils::ReadParam('header_line', 0);
  1028. $sClassName = utils::ReadParam('class_name', '', false, 'class');
  1029. $bAdvanced = utils::ReadParam('advanced', 0);
  1030. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  1031. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  1032. $sDateTimeFormat = utils::ReadParam('date_time_format', 'default');
  1033. $sCustomDateTimeFormat = utils::ReadParam('custom_date_time_format', (string)AttributeDateTime::GetFormat(), false, 'raw_data');
  1034. // Create a truncated version of the data used for the fast preview
  1035. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  1036. $iMaxLen = strlen($sUTF8Data);
  1037. if ($iMaxLen > 0)
  1038. {
  1039. $iMaxLines = 20;
  1040. $iCurPos = true;
  1041. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  1042. {
  1043. $pos = strpos($sUTF8Data, "\n", $iCurPos);
  1044. if ($pos !== false)
  1045. {
  1046. $iCurPos = 1+$pos;
  1047. }
  1048. else
  1049. {
  1050. $iCurPos = strlen($sUTF8Data);
  1051. $iMaxLines = 1;
  1052. }
  1053. $iMaxLines--;
  1054. }
  1055. $sCSVDataTruncated = substr($sUTF8Data, 0, $iCurPos);
  1056. }
  1057. else
  1058. {
  1059. $sCSVDataTruncated = '';
  1060. }
  1061. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  1062. if (!empty($sSynchroScope))
  1063. {
  1064. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1065. $sClassName = $oSearch->GetClass();
  1066. $oSet = new DBObjectSet($oSearch);
  1067. $iCount = $oSet->Count();
  1068. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1069. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1070. }
  1071. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep2').'</h2>');
  1072. $oPage->add('<div class="wizContainer">');
  1073. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:30px;">');
  1074. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  1075. $oPage->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  1076. $oPage->add('<p><input type="radio" name="separator" value="," onClick="DoPreview()"'.IsChecked($sSeparator, ',').'/> '.Dict::S('UI:CSVImport:SeparatorComma+').'<br/>');
  1077. $oPage->add('<input type="radio" name="separator" value=";" onClick="DoPreview()"'.IsChecked($sSeparator, ';').'/> '.Dict::S('UI:CSVImport:SeparatorSemicolon+').'<br/>');
  1078. $oPage->add('<input type="radio" name="separator" value="tab" onClick="DoPreview()"'.IsChecked($sSeparator, "\t").'/> '.Dict::S('UI:CSVImport:SeparatorTab+').'<br/>');
  1079. $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()"/>');
  1080. $oPage->add('</p>');
  1081. $oPage->add('</td><td style="vertical-align:top;padding-right:30px;">');
  1082. $oPage->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  1083. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onClick="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> '.Dict::S('UI:CSVImport:QualifierDoubleQuote+').'<br/>');
  1084. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onClick="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> '.Dict::S('UI:CSVImport:QualifierSimpleQuote+').'<br/>');
  1085. $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()"/>');
  1086. $oPage->add('</p>');
  1087. $oPage->add('</td><td style="vertical-align:top;padding-right:30px;">');
  1088. $oPage->add('<h3>'.Dict::S('UI:CSVImport:CommentsAndHeader').'</h3>');
  1089. $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>');
  1090. $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>');
  1091. $oPage->add('</td><td style="vertical-align:top;">');
  1092. $oPage->add('<h3>'.Dict::S('UI:CSVImport:DateAndTimeFormats').'</h3>');
  1093. $oPage->add('<p><input type="radio" name="date_time_format" id="radio_date_time_std" value="default"'.IsChecked($sDateTimeFormat, 'default').'/><label for="radio_date_time_std"> '.Dict::Format('UI:CSVImport:DefaultDateTimeFormat_Format_Example', htmlentities((string)AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8'), date((string)AttributeDateTime::GetFormat())).'</label><p>');
  1094. $oPage->add('<p><input type="radio" name="date_time_format" id="radio_date_time_custom" value="custom"'.IsChecked($sDateTimeFormat, 'custom').'/><label for="radio_date_time_custom"> '.Dict::Format('UI:CSVImport:CustomDateTimeFormat', '<input type="text" size="15" name="custom_date_time_format" id="custom_date_time_format" title="" value="'.htmlentities($sCustomDateTimeFormat, ENT_QUOTES, 'UTF-8').'">').'</label><p>');
  1095. $oPage->add('</td></tr></table>');
  1096. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  1097. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sUTF8Data, ENT_QUOTES, 'UTF-8').'"/>');
  1098. // The encoding has changed, keep that information within the wizard
  1099. $oPage->add('<input type="hidden" name="encoding" value="UTF-8">');
  1100. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  1101. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  1102. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  1103. foreach($aFieldsMapping as $iNumber => $sAttCode)
  1104. {
  1105. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  1106. }
  1107. foreach($aSearchFields as $index => $sDummy)
  1108. {
  1109. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  1110. }
  1111. $oPage->add('<input type="hidden" name="step" value="3"/>');
  1112. if (!empty($sSynchroScope))
  1113. {
  1114. foreach($aSynchroUpdate as $sKey => $value)
  1115. {
  1116. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  1117. }
  1118. }
  1119. $oPage->add('<div id="preview">');
  1120. $oPage->add('<p style="text-align:center">'.Dict::S('UI:CSVImport:CSVDataPreview').'</p>');
  1121. $oPage->add('</div>');
  1122. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="GoBack()"/>');
  1123. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Next').'"/>');
  1124. $oPage->add('</form>');
  1125. $oPage->add('</div>');
  1126. $oPage->add_script(
  1127. <<<EOF
  1128. function GoBack()
  1129. {
  1130. $('input[name=step]').val(1);
  1131. $('#wizForm').submit();
  1132. }
  1133. var ajax_request = null;
  1134. function DoPreview()
  1135. {
  1136. var separator = $('input[name=separator]:checked').val();
  1137. if (separator == 'other')
  1138. {
  1139. separator = $('#other_separator').val();
  1140. }
  1141. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  1142. if (text_qualifier == 'other')
  1143. {
  1144. text_qualifier = $('#other_qualifier').val();
  1145. }
  1146. var do_skip_lines = 0;
  1147. if ($('#box_skiplines:checked').val() != null)
  1148. {
  1149. do_skip_lines = $('#nb_skipped_lines').val();
  1150. }
  1151. var header_line = 0;
  1152. if ($('#box_header:checked').val() != null)
  1153. {
  1154. header_line = 1;
  1155. }
  1156. var encoding = $('input[name=encoding]').val();
  1157. $('#preview').block();
  1158. // Make sure that we cancel any pending request before issuing another
  1159. // since responses may arrive in arbitrary order
  1160. if (ajax_request != null)
  1161. {
  1162. ajax_request.abort();
  1163. ajax_request = null;
  1164. }
  1165. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  1166. { operation: 'parser_preview', enctype: 'multipart/form-data', csvdata: $("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, do_skip_lines: do_skip_lines, header_line: header_line, encoding: encoding },
  1167. function(data) {
  1168. $('#preview').empty();
  1169. $('#preview').append(data);
  1170. $('#preview').unblock();
  1171. }
  1172. );
  1173. }
  1174. EOF
  1175. );
  1176. $sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
  1177. $oPage->add_ready_script(
  1178. <<<EOF
  1179. DoPreview();
  1180. $('#custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
  1181. $('#custom_date_time_format').on('click', function() { $('#radio_date_time_custom').prop('checked', true); });
  1182. EOF
  1183. );
  1184. }
  1185. /**
  1186. * Prompt for the data to be loaded (either via a file or a copy/paste)
  1187. * @param WebPage $oPage The current web page
  1188. * @return void
  1189. */
  1190. function Welcome(iTopWebPage $oPage)
  1191. {
  1192. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  1193. if (!empty($sSynchroScope))
  1194. {
  1195. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1196. $sClassName = $oSearch->GetClass();
  1197. $oSet = new DBObjectSet($oSearch);
  1198. $iCount = $oSet->Count();
  1199. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1200. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1201. }
  1202. else
  1203. {
  1204. $aSynchroUpdate = null;
  1205. }
  1206. $oPage->add("<div><p><h1>".Dict::S('UI:Title:BulkImport+')."</h1></p></div>\n");
  1207. $oPage->AddTabContainer('tabs1');
  1208. $sSeparator = utils::ReadParam('separator', '', false, 'raw_data');
  1209. $sTextQualifier = utils::ReadParam('text_qualifier', '', false, 'raw_data');
  1210. $bHeaderLine = utils::ReadParam('header_line', true);
  1211. $sClassName = utils::ReadParam('class_name', '');
  1212. $bAdvanced = utils::ReadParam('advanced', 0);
  1213. $sEncoding = utils::ReadParam('encoding', '');
  1214. $sDateTimeFormat = utils::ReadParam('date_time_format', 'default');
  1215. $sCustomDateTimeFormat = utils::ReadParam('custom_date_time_format', (string)AttributeDateTime::GetFormat(), false, 'raw_data');
  1216. if ($sEncoding == '')
  1217. {
  1218. $sEncoding = MetaModel::GetConfig()->Get('csv_file_default_charset');
  1219. }
  1220. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  1221. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  1222. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:SelectFile').'</p>'.
  1223. '<p><input type="file" name="csvdata"/></p>';
  1224. $sFileLoadHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1225. $sFileLoadHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif">'; // IE 8 has some troubles if the font is different
  1226. $aPossibleEncodings = utils::GetPossibleEncodings(MetaModel::GetConfig()->GetCSVImportCharsets());
  1227. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1228. {
  1229. $sSelected = '';
  1230. if ($sEncoding == $sIconvCode)
  1231. {
  1232. $sSelected = ' selected';
  1233. }
  1234. $sFileLoadHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1235. }
  1236. $sFileLoadHtml .= '</select></p>';
  1237. $sFileLoadHtml .= '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1238. '<input type="hidden" name="step" value="2"/>'.
  1239. '<input type="hidden" name="operation" value="file_upload"/>'.
  1240. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1241. '<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>'.
  1242. '<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>'.
  1243. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1244. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1245. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1246. if (!empty($sSynchroScope))
  1247. {
  1248. foreach($aSynchroUpdate as $sKey => $value)
  1249. {
  1250. $sFileLoadHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1251. }
  1252. }
  1253. foreach($aFieldsMapping as $iNumber => $sAttCode)
  1254. {
  1255. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  1256. }
  1257. foreach($aSearchFields as $index => $sDummy)
  1258. {
  1259. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  1260. }
  1261. $sFileLoadHtml .= '</form></div>';
  1262. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:LoadFromFile'), $sFileLoadHtml);
  1263. $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data');
  1264. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:PasteData').'</p>'.
  1265. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>';
  1266. $sPasteDataHtml .= '<hidden name="encoding" value="UTF-8">';
  1267. $sPasteDataHtml .=
  1268. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1269. '<input type="hidden" name="step" value="2"/>'.
  1270. '<input type="hidden" name="operation" value="csv_data"/>'.
  1271. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  1272. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  1273. '<input type="hidden" name="date_time_format" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>'.
  1274. '<input type="hidden" name="custom_date_time_format" value="'.htmlentities($sCustomDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>'.
  1275. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1276. '<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>'.
  1277. '<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>'.
  1278. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1279. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1280. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1281. if (!empty($sSynchroScope))
  1282. {
  1283. foreach($aSynchroUpdate as $sKey => $value)
  1284. {
  1285. $sPasteDataHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1286. }
  1287. }
  1288. foreach($aFieldsMapping as $iNumber => $sAttCode)
  1289. {
  1290. $sPasteDataHtml .= '<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>';
  1291. }
  1292. foreach($aSearchFields as $index => $sDummy)
  1293. {
  1294. $sPasteDataHtml .= '<input type="hidden" name="search_field['.$index.']" value="1"/>';
  1295. }
  1296. $sPasteDataHtml .= '</form></div>';
  1297. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'), $sPasteDataHtml);
  1298. if (!empty($sCSVData))
  1299. {
  1300. // When there are some data, activate the 'copy & paste' tab by default
  1301. $oPage->SelectTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'));
  1302. }
  1303. $sTemplateHtml = '<div><p>'.Dict::S('UI:CSVImport:PickClassForTemplate').' ';
  1304. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  1305. $sTemplateHtml .= '</div>';
  1306. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  1307. $sTemplateHtml .= '</div>';
  1308. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:Templates'), $sTemplateHtml);
  1309. $oPage->add_script(
  1310. <<<EOF
  1311. var ajax_request = null;
  1312. function DisplayTemplate(sClassName) {
  1313. $('#template').block();
  1314. // Make sure that we cancel any pending request before issuing another
  1315. // since responses may arrive in arbitrary order
  1316. if (ajax_request != null)
  1317. {
  1318. ajax_request.abort();
  1319. ajax_request = null;
  1320. }
  1321. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  1322. { operation: 'get_csv_template', class_name: sClassName },
  1323. function(data) {
  1324. $('#template').empty();
  1325. $('#template').append(data);
  1326. $('#template').unblock();
  1327. }
  1328. );
  1329. }
  1330. EOF
  1331. );
  1332. $oPage->add_ready_script(
  1333. <<<EOF
  1334. $('#select_template_class').change( function() {
  1335. DisplayTemplate(this.value);
  1336. });
  1337. EOF
  1338. );
  1339. if (Utils::GetConfig()->Get('csv_import_history_display'))
  1340. {
  1341. $oPage->SetCurrentTabContainer('tabs1');
  1342. $oPage->AddAjaxTab(Dict::S('UI:History:BulkImports'), utils::GetAbsoluteUrlAppRoot().'pages/csvimport.php?step=11', true /* bCache */);
  1343. }
  1344. }
  1345. switch($iStep)
  1346. {
  1347. case 11:
  1348. // Asynchronous tab
  1349. $oPage = new ajax_page('');
  1350. BulkChange::DisplayImportHistory($oPage);
  1351. $oPage->add_ready_script('$("#CSVImportHistory table.listResults").tableHover();');
  1352. $oPage->add_ready_script('$("#CSVImportHistory table.listResults").tablesorter( { widgets: ["myZebra", "truncatedList"]} );');
  1353. break;
  1354. case 10:
  1355. // Case generated by BulkChange::DisplayImportHistory
  1356. $iChange = (int)utils::ReadParam('changeid', 0);
  1357. BulkChange::DisplayImportHistoryDetails($oPage, $iChange);
  1358. break;
  1359. case 5:
  1360. LoadData($oPage);
  1361. break;
  1362. case 4:
  1363. Preview($oPage);
  1364. break;
  1365. case 3:
  1366. SelectMapping($oPage);
  1367. break;
  1368. case 2:
  1369. SelectOptions($oPage);
  1370. break;
  1371. case 1:
  1372. case 6: // Loop back here when we are done
  1373. default:
  1374. Welcome($oPage);
  1375. }
  1376. $oPage->output();
  1377. }
  1378. catch(CoreException $e)
  1379. {
  1380. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1381. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1382. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1383. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1384. $oP->output();
  1385. if (MetaModel::IsLogEnabledIssue())
  1386. {
  1387. if (MetaModel::IsValidClass('EventIssue'))
  1388. {
  1389. $oLog = new EventIssue();
  1390. $oLog->Set('message', $e->getMessage());
  1391. $oLog->Set('userinfo', '');
  1392. $oLog->Set('issue', $e->GetIssue());
  1393. $oLog->Set('impact', 'Page could not be displayed');
  1394. $oLog->Set('callstack', $e->getTrace());
  1395. $oLog->Set('data', $e->getContextData());
  1396. $oLog->DBInsertNoReload();
  1397. }
  1398. IssueLog::Error($e->getMessage());
  1399. }
  1400. // For debugging only
  1401. //throw $e;
  1402. }
  1403. catch(Exception $e)
  1404. {
  1405. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1406. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1407. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1408. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1409. $oP->output();
  1410. if (MetaModel::IsLogEnabledIssue())
  1411. {
  1412. if (MetaModel::IsValidClass('EventIssue'))
  1413. {
  1414. $oLog = new EventIssue();
  1415. $oLog->Set('message', $e->getMessage());
  1416. $oLog->Set('userinfo', '');
  1417. $oLog->Set('issue', 'PHP Exception');
  1418. $oLog->Set('impact', 'Page could not be displayed');
  1419. $oLog->Set('callstack', $e->getTrace());
  1420. $oLog->Set('data', array());
  1421. $oLog->DBInsertNoReload();
  1422. }
  1423. IssueLog::Error($e->getMessage());
  1424. }
  1425. }
  1426. ?>