csvimport.php 57 KB

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