csvimport.php 56 KB

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