csvimport.php 52 KB

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