csvimport.php 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * CSV Import Page
  18. * Wizard to import CSV (or TSV) data into the database
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  24. */
  25. try
  26. {
  27. ini_set('memory_limit', '256M');
  28. require_once('../approot.inc.php');
  29. require_once(APPROOT.'/application/application.inc.php');
  30. require_once(APPROOT.'/application/itopwebpage.class.inc.php');
  31. require_once(APPROOT.'/application/startup.inc.php');
  32. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  33. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  34. $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', '');
  179. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');
  180. $sSeparator = utils::ReadParam('separator', ',');
  181. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  182. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  183. $iRealSkippedLines = $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  184. $sClassName = utils::ReadParam('class_name', '');
  185. $aFieldsMapping = utils::ReadParam('field', array());
  186. $aSearchFields = utils::ReadParam('search_field', array());
  187. $iCurrentStep = $bSimulate ? 4 : 5;
  188. $bAdvanced = utils::ReadParam('advanced', 0);
  189. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  190. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  191. if (!empty($sSynchroScope))
  192. {
  193. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  194. $sClassName = $oSearch->GetClass(); // If a synchronization scope is set, then the class is fixed !
  195. $oSet = new DBObjectSet($oSearch);
  196. $iCount = $oSet->Count();
  197. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  198. $sClassesSelect = "<select id=\"select_class_name\" name=\"class_name\"><option value=\"$sClassName\" selected>".MetaModel::GetName($sClassName)."</option>";
  199. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  200. }
  201. else
  202. {
  203. $sSynchroScope = '';
  204. $aSynchroUpdate = null;
  205. }
  206. // Parse the data set
  207. $oCSVParser = new CSVParser($sCSVData, $sSeparator, $sTextQualifier);
  208. $aData = $oCSVParser->ToArray($iSkippedLines);
  209. if ($bHeaderLine)
  210. {
  211. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier, array_shift($aData)).$sTextQualifier; // Remove the first line and store it in case of error
  212. $iRealSkippedLines++;
  213. }
  214. // Format for the line numbers
  215. $sMaxLen = (strlen(''.count($aData)) < 3) ? 3 : strlen(''.count($aData)); // Pad line numbers to the appropriate number of chars, but at least 3
  216. // Compute the list of search/reconciliation criteria
  217. $aSearchKeys = array();
  218. foreach($aSearchFields as $index => $sDummy)
  219. {
  220. $sSearchField = $aFieldsMapping[$index];
  221. $aMatches = array();
  222. if (preg_match('/(.+)->(.+)/', $sSearchField, $aMatches) > 0)
  223. {
  224. $sSearchField = $aMatches[1];
  225. $aSearchKeys[$aMatches[1]] = '';
  226. }
  227. else
  228. {
  229. $aSearchKeys[$sSearchField] = '';
  230. }
  231. if (!MetaModel::IsValidFilterCode($sClassName, $sSearchField))
  232. {
  233. // Remove invalid or unmapped search fields
  234. $aSearchFields[$index] = null;
  235. unset($aSearchKeys[$sSearchField]);
  236. }
  237. }
  238. // Compute the list of fields and external keys to process
  239. $aExtKeys = array();
  240. $aAttributes = array();
  241. $aExternalKeysByColumn = array();
  242. foreach($aFieldsMapping as $iNumber => $sAttCode)
  243. {
  244. $iIndex = $iNumber-1;
  245. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  246. {
  247. if (preg_match('/(.+)->(.+)/', $sAttCode, $aMatches) > 0)
  248. {
  249. $sAttribute = $aMatches[1];
  250. $sField = $aMatches[2];
  251. $aExtKeys[$sAttribute][$sField] = $iIndex;
  252. $aExternalKeysByColumn[$iIndex] = $sAttribute;
  253. }
  254. else
  255. {
  256. if ($sAttCode == 'id')
  257. {
  258. $aAttributes['id'] = $iIndex;
  259. }
  260. else
  261. {
  262. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  263. if ($oAttDef->IsExternalKey())
  264. {
  265. $aExtKeys[$sAttCode]['id'] = $iIndex;
  266. $aExternalKeysByColumn[$iIndex] = $sAttCode;
  267. }
  268. else
  269. {
  270. $aAttributes[$sAttCode] = $iIndex;
  271. }
  272. }
  273. }
  274. }
  275. }
  276. $oMyChange = null;
  277. if (!$bSimulate)
  278. {
  279. // We're doing it for real, let's create a change
  280. $oMyChange = MetaModel::NewObject("CMDBChange");
  281. $oMyChange->Set("date", time());
  282. $sUserString = CMDBChange::GetCurrentUserName();
  283. $sUserString .= ' (CSV)';
  284. $oMyChange->Set("userinfo", $sUserString);
  285. $iChangeId = $oMyChange->DBInsert();
  286. }
  287. $oBulk = new BulkChange(
  288. $sClassName,
  289. $aData,
  290. $aAttributes,
  291. $aExtKeys,
  292. array_keys($aSearchKeys),
  293. empty($sSynchroScope) ? null : $sSynchroScope,
  294. $aSynchroUpdate
  295. );
  296. $oBulk->SetReportHtml();
  297. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  298. $aRes = $oBulk->Process($oMyChange);
  299. $sHtml = '<table id="bulk_preview" style="border-collapse: collapse;">';
  300. $sHtml .= '<tr><th style="padding:2px;border-right: 2px #fff solid;">Line</th>';
  301. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Status</th>';
  302. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Object</th>';
  303. foreach($aFieldsMapping as $iNumber => $sAttCode)
  304. {
  305. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  306. {
  307. $sHtml .= "<th style=\"padding:2px;border-right: 2px #fff solid;\">".BulkChange::GetFriendlyAttCodeName($sClassName, $sAttCode)."</th>";
  308. }
  309. }
  310. $sHtml .= '<th>Message</th>';
  311. $sHtml .= '</tr>';
  312. $iErrors = 0;
  313. $iCreated = 0;
  314. $iModified = 0;
  315. $iUnchanged = 0;
  316. foreach($aRes as $iLine => $aResRow)
  317. {
  318. $oStatus = $aResRow['__STATUS__'];
  319. $sUrl = '';
  320. $sMessage = '';
  321. $sCSSRowClass = '';
  322. $sCSSMessageClass = 'cell_ok';
  323. switch(get_class($oStatus))
  324. {
  325. case 'RowStatus_NoChange':
  326. $iUnchanged++;
  327. $sFinalClass = $aResRow['finalclass'];
  328. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  329. $sUrl = $oObj->GetHyperlink();
  330. $sStatus = '<img src="../images/unchanged.png" title="Unchanged">';
  331. $sCSSRowClass = 'row_unchanged';
  332. break;
  333. case 'RowStatus_Modify':
  334. $iModified++;
  335. $sFinalClass = $aResRow['finalclass'];
  336. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  337. $sUrl = $oObj->GetHyperlink();
  338. $sStatus = '<img src="../images/modified.png" title="Modified">';
  339. $sCSSRowClass = 'row_modified';
  340. break;
  341. case 'RowStatus_Disappeared':
  342. $iModified++;
  343. $sFinalClass = $aResRow['finalclass'];
  344. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  345. $sUrl = $oObj->GetHyperlink();
  346. $sStatus = '<img src="../images/delete.png" title="Missing">';
  347. $sCSSRowClass = 'row_modified';
  348. if ($bSimulate)
  349. {
  350. $sMessage = 'Missing object: will be updated';
  351. }
  352. else
  353. {
  354. $sMessage = 'Missing object: updated';
  355. }
  356. break;
  357. case 'RowStatus_NewObj':
  358. $iCreated++;
  359. $sFinalClass = $aResRow['finalclass'];
  360. $sStatus = '<img src="../images/added.png" title="Created">';
  361. $sCSSRowClass = 'row_added';
  362. if ($bSimulate)
  363. {
  364. $sMessage = 'Object will be created';
  365. }
  366. else
  367. {
  368. $sFinalClass = $aResRow['finalclass'];
  369. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  370. $sUrl = $oObj->GetHyperlink();
  371. $sMessage = 'Object created';
  372. }
  373. break;
  374. case 'RowStatus_Issue':
  375. $iErrors++;
  376. $sMessage .= $oPage->GetP($oStatus->GetDescription());
  377. $sStatus = '<img src="../images/error.png" title="Error">';
  378. $sCSSMessageClass = 'cell_error';
  379. $sCSSRowClass = 'row_error';
  380. if (array_key_exists($iLine, $aData))
  381. {
  382. $aRow = $aData[$iLine];
  383. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier,$aRow).$sTextQualifier; // Remove the first line and store it in case of error
  384. }
  385. break;
  386. }
  387. $sHtml .= '<tr class="'.$sCSSRowClass.'">';
  388. $sHtml .= "<td style=\"background-color:#f1f1f1;border-right:2px #fff solid;\">".sprintf("%0{$sMaxLen}d", 1+$iLine+$iRealSkippedLines)."</td>";
  389. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;border-right:2px #fff solid;\">$sStatus</td>";
  390. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;\">$sUrl</td>";
  391. foreach($aFieldsMapping as $iNumber => $sAttCode)
  392. {
  393. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  394. {
  395. $oCellStatus = $aResRow[$iNumber -1];
  396. $sCellMessage = '';
  397. if (isset($aExternalKeysByColumn[$iNumber -1]))
  398. {
  399. $sExtKeyName = $aExternalKeysByColumn[$iNumber -1];
  400. $oExtKeyCellStatus = $aResRow[$sExtKeyName];
  401. switch(get_class($oExtKeyCellStatus))
  402. {
  403. case 'CellStatus_Issue':
  404. case 'CellStatus_SearchIssue':
  405. case 'CellStatus_NullIssue':
  406. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  407. break;
  408. case 'CellStatus_Ambiguous':
  409. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  410. break;
  411. default:
  412. // Do nothing
  413. }
  414. }
  415. $sHtmlValue = $oCellStatus->GetDisplayableValue();
  416. switch(get_class($oCellStatus))
  417. {
  418. case 'CellStatus_Issue':
  419. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  420. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">ERROR: '.$sHtmlValue.$sCellMessage.'</td>';
  421. break;
  422. case 'CellStatus_SearchIssue':
  423. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  424. $sHtml .= '<td class="cell_error">ERROR: '.$sHtmlValue.$sCellMessage.'</td>';
  425. break;
  426. case 'CellStatus_Ambiguous':
  427. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  428. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">AMBIGUOUS: '.$sHtmlValue.$sCellMessage.'</td>';
  429. break;
  430. case 'CellStatus_Modify':
  431. $sHtml .= '<td class="cell_modified" style="border-right:1px #eee solid;"><b>'.$sHtmlValue.'</b></td>';
  432. break;
  433. default:
  434. $sHtml .= '<td class="cell_ok" style="border-right:1px #eee solid;">'.$sHtmlValue.$sCellMessage.'</td>';
  435. }
  436. }
  437. }
  438. $sHtml .= "<td class=\"$sCSSMessageClass\" style=\"background-color:#f1f1f1;\">$sMessage</td>";
  439. $sHtml .= '</tr>';
  440. }
  441. $iUnchanged = count($aRes) - $iErrors - $iModified - $iCreated;
  442. $sHtml .= '</table>';
  443. $oPage->add('<div class="wizContainer" style="width:auto;display:inline-block;">');
  444. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post">');
  445. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  446. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  447. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  448. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  449. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  450. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  451. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  452. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  453. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  454. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  455. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'"/>');
  456. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  457. if (!empty($sSynchroScope))
  458. {
  459. foreach($aSynchroUpdate as $sKey => $value)
  460. {
  461. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  462. }
  463. }
  464. foreach($aFieldsMapping as $iNumber => $sAttCode)
  465. {
  466. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  467. }
  468. foreach($aSearchFields as $index => $sDummy)
  469. {
  470. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  471. }
  472. $aFieldsMapping = utils::ReadParam('field', array());
  473. $aSearchFields = utils::ReadParam('search_field', array());
  474. $aDisplayFilters = array();
  475. if ($bSimulate)
  476. {
  477. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsWillStayUnchanged');
  478. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWillBeModified');
  479. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWillBeAdded');
  480. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsWillHaveErrors');
  481. }
  482. else
  483. {
  484. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsRemainedUnchanged');
  485. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWereModified');
  486. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWereAdded');
  487. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsHadErrors');
  488. }
  489. $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;');
  490. $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;');
  491. $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;');
  492. $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>');
  493. $oPage->add('<div class="white" style="display:inline-block">');
  494. $oPage->add($sHtml);
  495. $oPage->add('</div> <!-- end of preview -->');
  496. $oPage->add('<p>');
  497. if($bSimulate)
  498. {
  499. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Restart').'" onClick="CSVRestart()"/>&nbsp;&nbsp;');
  500. }
  501. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  502. $bShouldConfirm = false;
  503. if ($bSimulate)
  504. {
  505. // if there are *too many* changes, we should ask the user for a confirmation
  506. if (count($aRes) >= MetaModel::GetConfig()->Get('csv_import_min_object_confirmation'))
  507. {
  508. $fErrorsPercentage = (100.0*$iErrors)/count($aRes);
  509. if ($fErrorsPercentage >= MetaModel::GetConfig()->Get('csv_import_errors_percentage'))
  510. {
  511. $sMessage = sprintf("%.0f %% of the loaded objects have errors and will be ignored.", $fErrorsPercentage);
  512. $bShouldConfirm = true;
  513. }
  514. $fCreatedPercentage = (100.0*$iCreated)/count($aRes);
  515. if ($fCreatedPercentage >= MetaModel::GetConfig()->Get('csv_import_creations_percentage'))
  516. {
  517. $sMessage = sprintf("%.0f %% of the loaded objects will be created.", $fCreatedPercentage);
  518. $bShouldConfirm = true;
  519. }
  520. $fModifiedPercentage = (100.0*$iModified)/count($aRes);
  521. if ($fModifiedPercentage >= MetaModel::GetConfig()->Get('csv_import_modifications_percentage'))
  522. {
  523. $sMessage = sprintf("%.0f %% of the loaded objects will be modified.", $fModifiedPercentage);
  524. $bShouldConfirm = true;
  525. }
  526. }
  527. $iCount = count($aRes);
  528. //$oPage->add('<input type="submit" value="'.Dict::S('UI:Button:DoImport').'" onClick="$(\'#wizForm\').block();"/></p>');
  529. $sConfirm = $bShouldConfirm ? 'true' : 'false';
  530. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:DoImport')."\" onClick=\"return DoSubmit($sConfirm);\"/></p>");
  531. }
  532. else
  533. {
  534. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Done').'"/></p>');
  535. }
  536. $oPage->add('</form>');
  537. $oPage->add('</div> <!-- end of wizForm -->');
  538. if ($bShouldConfirm)
  539. {
  540. $oPage->add('<div id="dlg_confirmation" title="Please confirm the operation">');
  541. $oPage->add('<p style="text-align:center"><b>'.$sMessage.'</b></p>');
  542. $oPage->add('<p style="text-align:center">Are you sure you want to do this ?</p>');
  543. $oPage->add('<div id="confirmation_chart"></div>');
  544. $oPage->add('</div> <!-- end of dlg_confirmation -->');
  545. $oPage->add_ready_script(
  546. <<<EOF
  547. $('#dlg_confirmation').dialog(
  548. {
  549. height: 'auto',
  550. width: 500,
  551. modal:true,
  552. autoOpen: false,
  553. buttons:
  554. {
  555. 'Yes': RunImport,
  556. 'No': CancelImport
  557. }
  558. });
  559. swfobject.embedSWF( "../images/open-flash-chart.swf",
  560. "confirmation_chart",
  561. "100%", "300","9.0.0",
  562. "expressInstall.swf",
  563. {},
  564. {'wmode': 'transparent'}
  565. );
  566. EOF
  567. );
  568. }
  569. $oPage->add_script(
  570. <<< EOF
  571. function CSVGoBack()
  572. {
  573. $('input[name=step]').val($iCurrentStep-1);
  574. $('#wizForm').submit();
  575. }
  576. function CSVRestart()
  577. {
  578. $('input[name=step]').val(1);
  579. $('#wizForm').submit();
  580. }
  581. function ToggleRows(sCSSClass)
  582. {
  583. $('.'+sCSSClass).toggle();
  584. }
  585. function DoSubmit(bConfirm)
  586. {
  587. if (bConfirm) //Ask for a confirmation
  588. {
  589. $('#dlg_confirmation').dialog('open');
  590. }
  591. else
  592. {
  593. // Submit the form
  594. $('#wizForm').block();
  595. $('#wizForm').submit();
  596. }
  597. return false;
  598. }
  599. function CancelImport()
  600. {
  601. $('#dlg_confirmation').dialog('close');
  602. }
  603. function RunImport()
  604. {
  605. $('#dlg_confirmation').dialog('close');
  606. // Submit the form
  607. $('#wizForm').block();
  608. $('#wizForm').submit();
  609. }
  610. function open_flash_chart_data()
  611. {
  612. var iErrors = $iErrors;
  613. var iModified = $iModified;
  614. var iCreated = $iCreated;
  615. var iUnchanged = $iUnchanged;
  616. var fAlpha = 0.9;
  617. var oResult = {
  618. "elements": [
  619. {
  620. "type": "pie",
  621. "tip": "#label# (#percent#)",
  622. "gradient-fill": true,
  623. "font-size": 14,
  624. "colours":[],
  625. "values": [],
  626. "animate":[
  627. {
  628. "type": "fade"
  629. }
  630. ]
  631. }
  632. ],
  633. "x_axis": null,
  634. "font-size": 14,
  635. "bg_colour": "#EEEEEE"
  636. };
  637. if (iErrors > 0)
  638. {
  639. var oErrors =
  640. {
  641. "value": iErrors,
  642. "label": "Errors: "+iErrors,
  643. "alpha": fAlpha,
  644. "label-colour": "#CC3333",
  645. };
  646. oResult.elements[0].values.push(oErrors);
  647. oResult.elements[0].colours.push('#FF6666');
  648. }
  649. if (iModified > 0)
  650. {
  651. var oModified =
  652. {
  653. "value": iModified,
  654. "label": "Modified: "+iModified,
  655. "alpha": fAlpha,
  656. "label-colour": "#3333CC",
  657. };
  658. oResult.elements[0].values.push(oModified);
  659. oResult.elements[0].colours.push('#6666FF');
  660. }
  661. if (iCreated > 0)
  662. {
  663. var oCreated =
  664. {
  665. "value": iCreated,
  666. "label": "Created: "+iCreated,
  667. "alpha": fAlpha,
  668. "label-colour": "#33CC33",
  669. };
  670. oResult.elements[0].values.push(oCreated);
  671. oResult.elements[0].colours.push('#66FF66');
  672. }
  673. if (iUnchanged > 0)
  674. {
  675. var oUnchanged =
  676. {
  677. "value": iUnchanged,
  678. "label": "Unchanged: "+iUnchanged,
  679. "alpha": fAlpha,
  680. "label-colour": "#333333",
  681. };
  682. oResult.elements[0].values.push(oUnchanged);
  683. oResult.elements[0].colours.push('#666666');
  684. }
  685. return JSON.stringify(oResult);
  686. }
  687. EOF
  688. );
  689. if ($iErrors > 0)
  690. {
  691. return $aResult;
  692. }
  693. else
  694. {
  695. return null;
  696. }
  697. }
  698. /**
  699. * Perform the actual load of the CSV data and display the results
  700. * @param WebPage $oPage The web page to display the wizard
  701. * @return void
  702. */
  703. function LoadData(WebPage $oPage)
  704. {
  705. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep5').'</h2>');
  706. $aResult = ProcessCSVData($oPage, false /* simulate = false */);
  707. if (is_array($aResult))
  708. {
  709. $oPage->StartCollapsibleSection(Dict::S('UI:CSVImport:LinesNotImported'), false);
  710. $oPage->p(Dict::S('UI:CSVImport:LinesNotImported+'));
  711. $oPage->add('<textarea rows="30" cols="100">');
  712. $oPage->add(htmlentities(implode("\n", $aResult), ENT_QUOTES, 'UTF-8'));
  713. $oPage->add('</textarea>');
  714. $oPage->EndCollapsibleSection();
  715. }
  716. }
  717. /**
  718. * Simulate the load of the CSV data and display the results
  719. * @param WebPage $oPage The web page to display the wizard
  720. * @return void
  721. */
  722. function Preview(WebPage $oPage)
  723. {
  724. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep4').'</h2>');
  725. ProcessCSVData($oPage, true /* simulate */);
  726. }
  727. /**
  728. * Select the mapping between the CSV column and the fields of the objects
  729. * @param WebPage $oPage The web page to display the wizard
  730. * @return void
  731. */
  732. function SelectMapping(WebPage $oPage)
  733. {
  734. $sCSVData = utils::ReadParam('csvdata', '');
  735. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');;
  736. $sSeparator = utils::ReadParam('separator', ',');
  737. if ($sSeparator == 'tab') $sSeparator = "\t";
  738. if ($sSeparator == 'other')
  739. {
  740. $sSeparator = utils::ReadParam('other_separator', ',');
  741. }
  742. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  743. if ($sTextQualifier == 'other')
  744. {
  745. $sTextQualifier = utils::ReadParam('other_qualifier', '"');
  746. }
  747. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  748. $iSkippedLines = 0;
  749. if (utils::ReadParam('box_skiplines', '0') == 1)
  750. {
  751. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  752. }
  753. $sClassName = utils::ReadParam('class_name', '');
  754. $bAdvanced = utils::ReadParam('advanced', 0);
  755. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  756. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  757. if (!empty($sSynchroScope))
  758. {
  759. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  760. $sClassName = $oSearch->GetClass(); // If a synchronization scope is set, then the class is fixed !
  761. $oSet = new DBObjectSet($oSearch);
  762. $iCount = $oSet->Count();
  763. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  764. $sClassesSelect = "<select id=\"select_class_name\" name=\"class_name\"><option value=\"$sClassName\" selected>".MetaModel::GetName($sClassName)."</option>";
  765. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  766. }
  767. else
  768. {
  769. $sClassesSelect = GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY);
  770. }
  771. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep3').'</h2>');
  772. $oPage->add('<div class="wizContainer">');
  773. $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').' ');
  774. $oPage->add($sClassesSelect);
  775. $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>');
  776. $oPage->add('<div style="padding:1em;display:none" id="advanced_help" style="display:none">'.Dict::S('UI:CSVImport:AdvancedMode+').'</div>');
  777. $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>');
  778. $oPage->add('<input type="hidden" name="step" value="4"/>');
  779. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  780. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  781. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  782. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  783. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  784. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  785. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  786. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'">');
  787. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'">');
  788. if (!empty($sSynchroScope))
  789. {
  790. foreach($aSynchroUpdate as $sKey => $value)
  791. {
  792. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  793. }
  794. }
  795. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Restart').'" onClick="CSVRestart()"/>&nbsp;&nbsp;');
  796. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  797. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:SimulateImport').'"/></p>');
  798. $oPage->add('</form>');
  799. $oPage->add('</div>');
  800. $sAlertIncompleteMapping = Dict::S('UI:CSVImport:AlertIncompleteMapping');
  801. $sAlertNoSearchCriteria = Dict::S('UI:CSVImport:AlertNoSearchCriteria');
  802. $oPage->add_ready_script(
  803. <<<EOF
  804. $('#select_class_name').change( DoMapping );
  805. EOF
  806. );
  807. if ($sClassName != '')
  808. {
  809. $oPage->add_ready_script("DoMapping();"); // There is already a class selected, run the mapping
  810. }
  811. $oPage->add_script(
  812. <<<EOF
  813. var aDefaultKeys = new Array();
  814. function CSVGoBack()
  815. {
  816. $('input[name=step]').val(2);
  817. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  818. $('#wizForm').submit();
  819. }
  820. function CSVRestart()
  821. {
  822. $('input[name=step]').val(1);
  823. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  824. $('#wizForm').submit();
  825. }
  826. var ajax_request = null;
  827. function DoMapping()
  828. {
  829. var class_name = $('select[name=class_name]').val();
  830. var advanced = $('input[name=advanced]:checked').val();
  831. if (advanced != 1)
  832. {
  833. $('#advanced_help').hide();
  834. }
  835. else
  836. {
  837. $('#advanced_help').show();
  838. }
  839. if (class_name != '')
  840. {
  841. var separator = $('input[name=separator]').val();
  842. var text_qualifier = $('input[name=text_qualifier]').val();
  843. var header_line = $('input[name=header_line]').val();
  844. var nb_lines_skipped = $('input[name=nb_skipped_lines]').val();
  845. var csv_data = $('input[name=csvdata]').val();
  846. var encoding = $('input[name=encoding]').val();
  847. if (advanced != 1)
  848. {
  849. advanced = 0;
  850. }
  851. $('#mapping').block();
  852. // Make sure that we cancel any pending request before issuing another
  853. // since responses may arrive in arbitrary order
  854. if (ajax_request != null)
  855. {
  856. ajax_request.abort();
  857. ajax_request = null;
  858. }
  859. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  860. { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator,
  861. qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, class_name: class_name,
  862. advanced: advanced, encoding: encoding },
  863. function(data) {
  864. $('#mapping').empty();
  865. $('#mapping').append(data);
  866. $('#mapping').unblock();
  867. }
  868. );
  869. }
  870. }
  871. function CheckValues()
  872. {
  873. bResult = true;
  874. bMappingOk = true;
  875. bSearchOk = false;
  876. $('select[name^=field]').each( function() {
  877. if ($(this).val() == '')
  878. {
  879. $(this).parent().css({'border': '2px #D81515 solid'});
  880. bMappingOk = false;
  881. bResult = false;
  882. }
  883. else
  884. {
  885. $(this).parent().css({'border': '0'});
  886. }
  887. });
  888. // At least one search field must be checked
  889. $('input[name^=search]:checked').each( function() {
  890. bSearchOk = true;
  891. });
  892. if (!bMappingOk)
  893. {
  894. alert("$sAlertIncompleteMapping");
  895. }
  896. if (!bSearchOk)
  897. {
  898. bResult = false;
  899. alert("$sAlertNoSearchCriteria");
  900. }
  901. if (bResult)
  902. {
  903. $('#mapping').block();
  904. // Re-enable all search_xxx checkboxes so that their value gets posted
  905. $('input[name^=search]').each(function() {
  906. $(this).attr('disabled', false);
  907. });
  908. }
  909. return bResult;
  910. }
  911. function DoCheckMapping()
  912. {
  913. // Check if there is a field mapped to 'id'
  914. // In which case, it's the only possible search key
  915. var idSelected = 0;
  916. var nbSearchKeys = $('input[name^=search]:checked').length;
  917. var nbMappings = $('select[name^=field]').length;
  918. for(index=1; index <= nbMappings; index++)
  919. {
  920. var selectedValue = $('#mapping_'+index).val();
  921. if (selectedValue == 'id')
  922. {
  923. idSelected = index;
  924. }
  925. }
  926. for (index=1; index <= nbMappings; index++)
  927. {
  928. sMappingValue = $('#mapping_'+index).val();
  929. if ((sMappingValue == '') || (sMappingValue == ':none:'))
  930. {
  931. // Non-mapped field, uncheck and disabled
  932. $('#search_'+index).attr('checked', false);
  933. $('#search_'+index).attr('disabled', true);
  934. }
  935. else if (index == idSelected)
  936. {
  937. // The 'id' field was mapped, it's the only possible reconciliation key
  938. $('#search_'+index).attr('checked', true);
  939. $('#search_'+index).attr('disabled', true);
  940. }
  941. else
  942. {
  943. if (idSelected > 0)
  944. {
  945. // The 'id' field was mapped, it's the only possible reconciliation key
  946. $('#search_'+index).attr('checked', false);
  947. $('#search_'+index).attr('disabled', true);
  948. }
  949. else
  950. {
  951. $('#search_'+index).attr('disabled', false);
  952. if (nbSearchKeys == 0)
  953. {
  954. // No search key was selected, select the default ones
  955. for(j =0; j < aDefaultKeys.length; j++)
  956. {
  957. if (sMappingValue == aDefaultKeys[j])
  958. {
  959. $('#search_'+index).attr('checked', true);
  960. }
  961. }
  962. }
  963. }
  964. }
  965. }
  966. }
  967. EOF
  968. );
  969. }
  970. /**
  971. * Select the options of the CSV load and check for CSV parsing errors
  972. * @param WebPage $oPage The current web page
  973. * @return void
  974. */
  975. function SelectOptions(WebPage $oPage)
  976. {
  977. $sOperation = utils::ReadParam('operation', 'csv_data');
  978. $sCSVData = '';
  979. switch($sOperation)
  980. {
  981. case 'file_upload':
  982. $oDocument = utils::ReadPostedDocument('csvdata');
  983. if (!$oDocument->IsEmpty())
  984. {
  985. $sCSVData = $oDocument->GetData();
  986. }
  987. break;
  988. default:
  989. $sCSVData = utils::ReadPostedParam('csvdata', '');
  990. }
  991. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  992. // Compute a subset of the data set, now that we know the charset
  993. if ($sEncoding == 'UTF-8')
  994. {
  995. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  996. }
  997. else
  998. {
  999. $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  1000. }
  1001. $aGuesses = GuessParameters($sUTF8Data); // Try to predict the parameters, based on the input data
  1002. $sSeparator = utils::ReadParam('separator', '');
  1003. if ($sSeparator == '') // May be set to an empty value by the previous page
  1004. {
  1005. $sSeparator = $aGuesses['separator'];
  1006. }
  1007. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  1008. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  1009. if ($sSeparator == 'tab') $sSeparator = "\t";
  1010. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  1011. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  1012. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  1013. {
  1014. $sTextQualifier = $aGuesses['qualifier'];
  1015. }
  1016. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  1017. $bHeaderLine = utils::ReadParam('header_line', 0);
  1018. $sClassName = utils::ReadParam('class_name', '');
  1019. $bAdvanced = utils::ReadParam('advanced', 0);
  1020. // Create a truncated version of the data used for the fast preview
  1021. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  1022. $iMaxLen = strlen($sUTF8Data);
  1023. if ($iMaxLen > 0)
  1024. {
  1025. $iMaxLines = 20;
  1026. $iCurPos = true;
  1027. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  1028. {
  1029. $pos = strpos($sUTF8Data, "\n", $iCurPos);
  1030. if ($pos !== false)
  1031. {
  1032. $iCurPos = 1+$pos;
  1033. }
  1034. else
  1035. {
  1036. $iCurPos = strlen($sUTF8Data);
  1037. $iMaxLines = 1;
  1038. }
  1039. $iMaxLines--;
  1040. }
  1041. $sCSVDataTruncated = substr($sUTF8Data, 0, $iCurPos);
  1042. }
  1043. else
  1044. {
  1045. $sCSVDataTruncated = '';
  1046. }
  1047. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  1048. if (!empty($sSynchroScope))
  1049. {
  1050. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1051. $sClassName = $oSearch->GetClass();
  1052. $oSet = new DBObjectSet($oSearch);
  1053. $iCount = $oSet->Count();
  1054. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1055. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1056. }
  1057. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep2').'</h2>');
  1058. $oPage->add('<div class="wizContainer">');
  1059. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;">');
  1060. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  1061. $oPage->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  1062. $oPage->add('<p><input type="radio" name="separator" value="," onClick="DoPreview()"'.IsChecked($sSeparator, ',').'/> '.Dict::S('UI:CSVImport:SeparatorComma+').'<br/>');
  1063. $oPage->add('<input type="radio" name="separator" value=";" onClick="DoPreview()"'.IsChecked($sSeparator, ';').'/> '.Dict::S('UI:CSVImport:SeparatorSemicolon+').'<br/>');
  1064. $oPage->add('<input type="radio" name="separator" value="tab" onClick="DoPreview()"'.IsChecked($sSeparator, "\t").'/> '.Dict::S('UI:CSVImport:SeparatorTab+').'<br/>');
  1065. $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()"/>');
  1066. $oPage->add('</p>');
  1067. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;">');
  1068. $oPage->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  1069. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onClick="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> '.Dict::S('UI:CSVImport:QualifierDoubleQuote+').'<br/>');
  1070. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onClick="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> '.Dict::S('UI:CSVImport:QualifierSimpleQuote+').'<br/>');
  1071. $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()"/>');
  1072. $oPage->add('</p>');
  1073. $oPage->add('</td><td style="vertical-align:top;">');
  1074. $oPage->add('<h3>'.Dict::S('UI:CSVImport:CommentsAndHeader').'</h3>');
  1075. $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>');
  1076. $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>');
  1077. $oPage->add('</td></tr></table>');
  1078. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  1079. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sUTF8Data, ENT_QUOTES, 'UTF-8').'"/>');
  1080. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  1081. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  1082. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  1083. $oPage->add('<input type="hidden" name="step" value="3"/>');
  1084. if (!empty($sSynchroScope))
  1085. {
  1086. foreach($aSynchroUpdate as $sKey => $value)
  1087. {
  1088. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  1089. }
  1090. }
  1091. $oPage->add('<div id="preview">');
  1092. $oPage->add('<p style="text-align:center">'.Dict::S('UI:CSVImport:CSVDataPreview').'</p>');
  1093. $oPage->add('</div>');
  1094. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="GoBack()"/>');
  1095. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Next').'"/>');
  1096. $oPage->add('</form>');
  1097. $oPage->add('</div>');
  1098. $oPage->add_script(
  1099. <<<EOF
  1100. function GoBack()
  1101. {
  1102. $('input[name=step]').val(1);
  1103. $('#wizForm').submit();
  1104. }
  1105. var ajax_request = null;
  1106. function DoPreview()
  1107. {
  1108. var separator = $('input[name=separator]:checked').val();
  1109. if (separator == 'other')
  1110. {
  1111. separator = $('#other_separator').val();
  1112. }
  1113. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  1114. if (text_qualifier == 'other')
  1115. {
  1116. text_qualifier = $('#other_qualifier').val();
  1117. }
  1118. var nb_lines_skipped = 0;
  1119. if ($('#box_skiplines:checked').val() != null)
  1120. {
  1121. nb_lines_skipped = $('#nb_skipped_lines').val();
  1122. }
  1123. var header_line = 0;
  1124. if ($('#box_header:checked').val() != null)
  1125. {
  1126. header_line = 1;
  1127. }
  1128. var encoding = $('input[name=encoding]').val();
  1129. $('#preview').block();
  1130. // Make sure that we cancel any pending request before issuing another
  1131. // since responses may arrive in arbitrary order
  1132. if (ajax_request != null)
  1133. {
  1134. ajax_request.abort();
  1135. ajax_request = null;
  1136. }
  1137. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  1138. { operation: 'parser_preview', enctype: 'multipart/form-data', csvdata: $("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, encoding: encoding },
  1139. function(data) {
  1140. $('#preview').empty();
  1141. $('#preview').append(data);
  1142. $('#preview').unblock();
  1143. }
  1144. );
  1145. }
  1146. EOF
  1147. );
  1148. $oPage->add_ready_script('DoPreview();');
  1149. }
  1150. /**
  1151. * Prompt for the data to be loaded (either via a file or a copy/paste)
  1152. * @param WebPage $oPage The current web page
  1153. * @return void
  1154. */
  1155. function Welcome(iTopWebPage $oPage)
  1156. {
  1157. // Encodings supported:
  1158. // ICONV_CODE => Display Name
  1159. // Each iconv installation supports different encodings
  1160. // Some reasonably common and useful encodnings are listed here
  1161. $aPossibleEncodings = array(
  1162. 'UTF-8' => 'Unicode (UTF-8)',
  1163. 'ISO-8859-1' => 'Western (ISO-8859-1)',
  1164. 'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
  1165. 'WINDOWS-1252' => 'Western (Windows 1252)',
  1166. 'ISO-8859-15' => 'Western (ISO-8859-15)',
  1167. );
  1168. // Some more encodings can be specified in the config file
  1169. $aExtraCharsets = MetaModel::GetConfig()->GetCSVImportCharsets();
  1170. $aPossibleEncodings = array_merge($aPossibleEncodings, $aExtraCharsets);
  1171. asort($aPossibleEncodings);
  1172. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  1173. if (!empty($sSynchroScope))
  1174. {
  1175. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1176. $sClassName = $oSearch->GetClass();
  1177. $oSet = new DBObjectSet($oSearch);
  1178. $iCount = $oSet->Count();
  1179. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1180. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1181. }
  1182. else
  1183. {
  1184. $aSynchroUpdate = null;
  1185. }
  1186. $oPage->add("<div><p><h1>".Dict::S('UI:Title:BulkImport+')."</h1></p></div>\n");
  1187. $oPage->AddTabContainer('tabs1');
  1188. $sSeparator = utils::ReadParam('separator', '');
  1189. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  1190. $bHeaderLine = utils::ReadParam('header_line', true);
  1191. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  1192. $sClassName = utils::ReadParam('class_name', '');
  1193. $bAdvanced = utils::ReadParam('advanced', 0);
  1194. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  1195. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:SelectFile').'</p>'.
  1196. '<p><input type="file" name="csvdata"/></p>';
  1197. $sFileLoadHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1198. $sFileLoadHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE 8 has some troubles if the font is different
  1199. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1200. {
  1201. $sSelected = '';
  1202. if ($sEncoding == $sIconvCode)
  1203. {
  1204. $sSelected = ' selected';
  1205. }
  1206. $sFileLoadHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1207. }
  1208. $sFileLoadHtml .= '</select></p>';
  1209. $sFileLoadHtml .= '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1210. '<input type="hidden" name="step" value="2"/>'.
  1211. '<input type="hidden" name="operation" value="file_upload"/>'.
  1212. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1213. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  1214. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1215. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1216. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1217. if (!empty($sSynchroScope))
  1218. {
  1219. foreach($aSynchroUpdate as $sKey => $value)
  1220. {
  1221. $sFileLoadHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1222. }
  1223. }
  1224. $sFileLoadHtml .= '</form></div>';
  1225. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:LoadFromFile'), $sFileLoadHtml);
  1226. $sCSVData = utils::ReadParam('csvdata', '');
  1227. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:PasteData').'</p>'.
  1228. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>';
  1229. $sPasteDataHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1230. $sPasteDataHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE8 has some troubles if the font is different
  1231. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1232. {
  1233. $sSelected = '';
  1234. if ($sEncoding == $sIconvCode)
  1235. {
  1236. $sSelected = ' selected';
  1237. }
  1238. $sPasteDataHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1239. }
  1240. $sPasteDataHtml .= '</select></p>'.
  1241. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1242. '<input type="hidden" name="step" value="2"/>'.
  1243. '<input type="hidden" name="operation" value="csv_data"/>'.
  1244. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  1245. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  1246. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1247. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  1248. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1249. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1250. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1251. if (!empty($sSynchroScope))
  1252. {
  1253. foreach($aSynchroUpdate as $sKey => $value)
  1254. {
  1255. $sPasteDataHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1256. }
  1257. }
  1258. $sPasteDataHtml .= '</form></div>';
  1259. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'), $sPasteDataHtml);
  1260. if (!empty($sCSVData))
  1261. {
  1262. // When there are some data, activate the 'copy & paste' tab by default
  1263. $oPage->SelectTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'));
  1264. }
  1265. $sTemplateHtml = '<div><p>'.Dict::S('UI:CSVImport:PickClassForTemplate').' ';
  1266. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  1267. $sTemplateHtml .= '</div>';
  1268. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  1269. $sTemplateHtml .= '</div>';
  1270. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:Templates'), $sTemplateHtml);
  1271. $oPage->add_script(
  1272. <<<EOF
  1273. var ajax_request = null;
  1274. function DisplayTemplate(sClassName) {
  1275. $('#template').block();
  1276. // Make sure that we cancel any pending request before issuing another
  1277. // since responses may arrive in arbitrary order
  1278. if (ajax_request != null)
  1279. {
  1280. ajax_request.abort();
  1281. ajax_request = null;
  1282. }
  1283. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  1284. { operation: 'get_csv_template', class_name: sClassName },
  1285. function(data) {
  1286. $('#template').empty();
  1287. $('#template').append(data);
  1288. $('#template').unblock();
  1289. }
  1290. );
  1291. }
  1292. EOF
  1293. );
  1294. $oPage->add_ready_script(
  1295. <<<EOF
  1296. $('#select_template_class').change( function() {
  1297. DisplayTemplate(this.value);
  1298. });
  1299. EOF
  1300. );
  1301. $oPage->SetCurrentTabContainer('tabs1');
  1302. $oPage->SetCurrentTab(Dict::S('UI:History:BulkImports'));
  1303. BulkChange::DisplayImportHistory($oPage);
  1304. }
  1305. switch($iStep)
  1306. {
  1307. case 10:
  1308. $iChange = (int)utils::ReadParam('changeid', 0);
  1309. BulkChange::DisplayImportHistoryDetails($oPage, $iChange);
  1310. break;
  1311. case 5:
  1312. LoadData($oPage);
  1313. break;
  1314. case 4:
  1315. Preview($oPage);
  1316. break;
  1317. case 3:
  1318. SelectMapping($oPage);
  1319. break;
  1320. case 2:
  1321. SelectOptions($oPage);
  1322. break;
  1323. case 1:
  1324. case 6: // Loop back here when we are done
  1325. default:
  1326. Welcome($oPage);
  1327. }
  1328. $oPage->output();
  1329. }
  1330. catch(xxxxxxxCoreException $e)
  1331. {
  1332. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1333. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1334. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1335. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1336. $oP->output();
  1337. if (MetaModel::IsLogEnabledIssue())
  1338. {
  1339. if (MetaModel::IsValidClass('EventIssue'))
  1340. {
  1341. $oLog = new EventIssue();
  1342. $oLog->Set('message', $e->getMessage());
  1343. $oLog->Set('userinfo', '');
  1344. $oLog->Set('issue', $e->GetIssue());
  1345. $oLog->Set('impact', 'Page could not be displayed');
  1346. $oLog->Set('callstack', $e->getTrace());
  1347. $oLog->Set('data', $e->getContextData());
  1348. $oLog->DBInsertNoReload();
  1349. }
  1350. IssueLog::Error($e->getMessage());
  1351. }
  1352. // For debugging only
  1353. //throw $e;
  1354. }
  1355. catch(xxxxxException $e)
  1356. {
  1357. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1358. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1359. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1360. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1361. $oP->output();
  1362. if (MetaModel::IsLogEnabledIssue())
  1363. {
  1364. if (MetaModel::IsValidClass('EventIssue'))
  1365. {
  1366. $oLog = new EventIssue();
  1367. $oLog->Set('message', $e->getMessage());
  1368. $oLog->Set('userinfo', '');
  1369. $oLog->Set('issue', 'PHP Exception');
  1370. $oLog->Set('impact', 'Page could not be displayed');
  1371. $oLog->Set('callstack', $e->getTrace());
  1372. $oLog->Set('data', array());
  1373. $oLog->DBInsertNoReload();
  1374. }
  1375. IssueLog::Error($e->getMessage());
  1376. }
  1377. }
  1378. ?>