PageRenderTime 52ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/phplist/admin/commonlib/pages/importcsv.php

https://github.com/radicaldesigns/amp
PHP | 729 lines | 616 code | 51 blank | 62 comment | 189 complexity | e4650a51556df5696db983d0bbf7d32f MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, BSD-3-Clause, LGPL-2.0, CC-BY-SA-3.0, AGPL-1.0
  1. <?php
  2. print '<script language="Javascript" src="js/progressbar.js" type="text/javascript"></script>';
  3. ignore_user_abort();
  4. set_time_limit(500);
  5. $illegal_cha = array(",", ";", ":", "#","\t");
  6. $system_tmpdir = ini_get("upload_tmp_dir");
  7. if (!isset($GLOBALS["tmpdir"]) && !empty($system_tmpdir)) {
  8. $GLOBALS["tmpdir"] = $system_tmpdir;
  9. }
  10. if (!is_dir($GLOBALS["tmpdir"]) || !is_writable($GLOBALS["tmpdir"]) && !empty($system_tmpdir)) {
  11. $GLOBALS["tmpdir"] = $system_tmpdir;
  12. }
  13. #if (ini_get("open_basedir")) {
  14. if (!is_dir($GLOBALS["tmpdir"]) || !is_writable($GLOBALS["tmpdir"])) {
  15. Warn(sprintf($GLOBALS['I18N']->get('The temporary directory for uploading (%s) is not writable, so import will fail'),$GLOBALS["tmpdir"]));
  16. }
  17. if (!isset($GLOBALS["assign_invalid_default"]))
  18. $GLOBALS["assign_invalid_default"] = $GLOBALS['I18N']->get('Invalid Email').' [number]';
  19. function my_shutdown () {
  20. # print "Shutting down";
  21. # print connection_status(); # with PHP 4.2.1 buggy. http://bugs.php.net/bug.php?id=17774
  22. }
  23. function parsePlaceHolders($templ,$data) {
  24. $retval = $templ;
  25. foreach ($data as $key => $val) {
  26. if (!is_array($val)) {
  27. $retval = preg_replace('/\['.preg_quote($key).'\]/i',$val,$retval);
  28. }
  29. }
  30. return $retval;
  31. }
  32. function clearImport() {
  33. if (is_file($_SESSION["import_file"])) {
  34. unlink($_SESSION["import_file"]);
  35. }
  36. $_SESSION["import_file"] = "";
  37. $_SESSION["systemindex"] = "";
  38. $_SESSION["import_attribute"] = "";
  39. $_SESSION["test_import"] = "";
  40. $_SESSION["assign_invalid"] = "";
  41. $_SESSION["overwrite"] = "";
  42. }
  43. register_shutdown_function("my_shutdown");
  44. require_once $GLOBALS["coderoot"] . "structure.php";
  45. # identify system values from the database structure
  46. $system_attributes = array();
  47. reset($DBstruct["user"]);
  48. while (list ($key,$val) = each ($DBstruct["user"])) {
  49. if (!ereg("^sys",$val[1])) {
  50. $system_attributes[strtolower($val[1])] = $key;
  51. } #elseif (ereg("sysexp:(.*)",$val[1],$regs)) {
  52. #$system_attributes[strtolower($regs[1])] = $key;
  53. #}
  54. }
  55. ob_end_flush();
  56. if ($_GET["reset"] == "yes") {
  57. clearImport();
  58. print '<h1>'.$GLOBALS['I18N']->get('Import cleared').'</h1>';
  59. print PageLink2($_GET["page"],$GLOBALS['I18N']->get('Continue'));
  60. return;
  61. } else {
  62. # if ($_SESSION["test_import"])
  63. print '<p>'.PageLink2($_GET["page"]."&amp;reset=yes",$GLOBALS['I18N']->get('Reset Import session')).'</p>';
  64. }
  65. if(isset($_POST["import"])) {
  66. $test_import = (isset($_POST["import_test"]) && $_POST["import_test"] == "yes");
  67. $_SESSION["test_import"] = $test_import;
  68. if(!$_FILES["import_file"]) {
  69. Fatal_Error($GLOBALS['I18N']->get('File is either too large or does not exist.'));
  70. return;
  71. }
  72. if(empty($_FILES["import_file"])) {
  73. Fatal_Error($GLOBALS['I18N']->get('No file was specified. Maybe the file is too big? '));
  74. return;
  75. }
  76. if (filesize($_FILES["import_file"]['tmp_name']) > 1000000) {
  77. # if we allow more, we will certainly run out of memory
  78. Fatal_Error($GLOBALS['I18N']->get('File too big, please split it up into smaller ones'));
  79. return;
  80. }
  81. if( !preg_match("/^[0-9A-Za-z_\.\-\/\s \(\)]+$/", $_FILES["import_file"]["name"]) ) {
  82. Fatal_Error($GLOBALS['I18N']->get('Use of wrong characters in filename: ').$_FILES["import_file"]["name"]);
  83. return;
  84. }
  85. if (!$_POST["notify"] && !$test_import) {
  86. Fatal_Error($GLOBALS['I18N']->get('Please choose whether to sign up immediately or to send a notification'));
  87. return;
  88. } else {
  89. $_SESSION["notify"] = $_POST["notify"];
  90. }
  91. if ($_FILES["import_file"] && $_FILES["import_file"]['size'] > 10) {
  92. $newfile = $GLOBALS['tmpdir'].'/'. $_FILES['import_file']['name'].time();
  93. move_uploaded_file($_FILES['import_file']['tmp_name'], $newfile);
  94. $_SESSION["import_file"] = $newfile;
  95. if( !($fp = fopen ($newfile, "r"))) {
  96. Fatal_Error(sprintf($GLOBALS['I18N']->get('Cannot read %s. file is not readable !'),$newfile));
  97. return;
  98. }
  99. fclose($fp);
  100. } elseif ($_FILES["import_file"]) {
  101. Fatal_Error($GLOBALS['I18N']->get('Something went wrong while uploading the file. Empty file received. Maybe the file is too big, or you have no permissions to read it.'));
  102. return;
  103. }
  104. if(isset($_POST["import_record_delimiter"]) && $_POST["import_record_delimiter"] != "") {
  105. $_SESSION["import_record_delimiter"] = $_POST["import_record_delimiter"];
  106. } else {
  107. $_SESSION["import_record_delimiter"] = "\n";
  108. }
  109. if (!isset($_POST["import_field_delimiter"]) || $_POST["import_field_delimiter"] == "" || $_POST["import_field_delimiter"] == "TAB") {
  110. $_SESSION["import_field_delimiter"] = "\t";
  111. } else {
  112. $_SESSION["import_field_delimiter"] = $_POST["import_field_delimiter"];
  113. }
  114. $_SESSION["show_warnings"] = $_POST["show_warnings"];
  115. $_SESSION["assign_invalid"] = $_POST["assign_invalid"];
  116. $_SESSION["omit_invalid"] = $_POST["omit_invalid"];
  117. $_SESSION["lists"] = $_POST["lists"];
  118. $_SESSION["groups"] = $_POST["groups"];
  119. $_SESSION["overwrite"] = $_POST["overwrite"];
  120. $_SESSION["notify"] = $_POST["notify"];
  121. $_SESSION["listname"] = $_POST["listname"];
  122. $_SESSION["retainold"] = $_POST["retainold"];
  123. }
  124. if ($_GET["confirm"]) {
  125. $_SESSION["test_import"] = '';
  126. }
  127. if ($_SESSION["import_file"]) {
  128. # output some stuff to make sure it's not buffered in the browser
  129. for ($i=0;$i<10000; $i++) {
  130. print ' '."\n";
  131. }
  132. print "<p>".$GLOBALS['I18N']->get('Reading emails from file ... ');
  133. flush();
  134. $fp = fopen ($_SESSION["import_file"], "r");
  135. $email_list = fread($fp, filesize ($_SESSION["import_file"]));
  136. fclose($fp);
  137. flush();
  138. // Clean up email file
  139. $email_list = trim($email_list);
  140. $email_list = str_replace("\r","\n",$email_list);
  141. $email_list = str_replace("\n\r","\n",$email_list);
  142. $email_list = str_replace("\n\n","\n",$email_list);
  143. if ($_SESSION["import_record_delimiter"] != "\n") {
  144. $email_list = str_replace($_SESSION["import_record_delimiter"],"\n",$email_list);
  145. };
  146. # not sure if we need to check on errors
  147. /*
  148. for($i=0; $i<count($illegal_cha); $i++) {
  149. if( ($illegal_cha[$i] != $import_field_delimiter) && ($illegal_cha[$i] != $import_record_delimiter) && (strpos($header, $illegal_cha[$i]) != false) ) {
  150. $errpos = strpos($email_list, $illegal_cha[$i]);
  151. $startpos = ( $errpos > 20 ) ? $errpos - 20 : 0;
  152. print '<h1>';
  153. printf($GLOBALS['I18N']->get('Error was around here &quot;%s&quot;'),substr( $email_list, $startpos, 40 ));
  154. print '</h1>';
  155. printf('<h1>',$GLOBALS['I18N']->get('Illegal character was %s').'</h1>',$illegal_cha[$i]);
  156. Fatal_Error($GLOBALS['I18N']->get('A character has been found in the import which is not the delimiter indicated, but is likely to be confused for one. Please clean up your import file and try again')." $import_field_delimiter, $import_record_delimiter");
  157. return;
  158. }
  159. };
  160. */
  161. # error_reporting(E_ALL);
  162. // Split file/emails into array
  163. $email_list = explode("\n",$email_list);
  164. printf('..'.$GLOBALS['I18N']->get('ok, %d lines').'</p>',sizeof($email_list));
  165. $header = array_shift($email_list);
  166. $header = str_replace('"','',$header);
  167. $total = sizeof($email_list);
  168. $headers = explode($_SESSION["import_field_delimiter"],$header);
  169. $headers = array_unique($headers);
  170. $req = Sql_Query(sprintf('select * from %s order by listorder,name',$tables["attribute"]));
  171. while ($row = Sql_Fetch_Array($req)) {
  172. $attributes[$row["id"]] = $row["name"];
  173. }
  174. $used_systemattr = array();
  175. $used_attributes = array();
  176. for ($i=0;$i<sizeof($headers);$i++) {
  177. $column = clean($headers[$i]);
  178. # print $i."<h1>$column</h1>".$_POST['column'.$i].'<br/>';
  179. $column = preg_replace('#/#','',$column);
  180. if (in_array(strtolower($column),array_keys($system_attributes))) {
  181. # print "System $column => $i<br/>";
  182. $_SESSION["systemindex"][strtolower($column)] = $i;
  183. array_push($used_systemattr,strtolower($column));
  184. } elseif (strtolower($column) == "list membership" || $_POST['column'.$i] == 'skip') {
  185. # skip this one
  186. $_SESSION["import_attribute"][$column] = array("index"=>$i,"record"=>'skip',"column" => "$column");
  187. array_push($used_systemattr,strtolower($column));
  188. } else {
  189. if (isset($_SESSION["import_attribute"][$column]["record"]) && $_SESSION["import_attribute"][$column]["record"]) {
  190. # mapping has been defined
  191. } elseif (isset($_POST["column$i"])) {
  192. $_SESSION["import_attribute"][$column] = array("index"=>$i,"record"=>$_POST["column$i"],"column" => "$column");
  193. } else {
  194. $existing = Sql_Fetch_Row_Query("select id from ".$tables["attribute"]." where name = \"$column\"");
  195. $_SESSION["import_attribute"][$column] = array("index"=>$i,"record"=>$existing[0],"column" => $column);
  196. array_push($used_attributes,$existing[0]);
  197. }
  198. }
  199. }
  200. if (!isset($_SESSION["systemindex"]["email"])) {
  201. Fatal_Error($GLOBALS['I18N']->get('Cannot find column with email, please make sure the column is called &quot;email&quot; and not eg e-mail'));
  202. return;
  203. }
  204. $unused_systemattr = array_diff(array_keys($system_attributes),$used_systemattr);
  205. $unused_attributes = array_diff(array_keys($attributes),$used_attributes);
  206. $options = '<option value="new">-- '.$GLOBALS['I18N']->get('Create new one').'</option>';
  207. $options .= '<option value="skip">-- '.$GLOBALS['I18N']->get('Skip Column').'</option>';
  208. foreach ($unused_systemattr as $sysindex) {
  209. $options .= sprintf('<option value="%s">%s</option>',$sysindex,substr($system_attributes[$sysindex],0,25));
  210. }
  211. foreach ($unused_attributes as $attindex) {
  212. $options .= sprintf('<option value="%s">%s</option>',$attindex,substr(stripslashes($attributes[$attindex]),0,25));
  213. }
  214. $ls = new WebblerListing($GLOBALS['I18N']->get('Import Attributes'));
  215. $request_mapping = 0;
  216. foreach ($_SESSION["import_attribute"] as $column => $rec) {
  217. if (trim($column) != '' && !$rec["record"]) {
  218. $request_mapping = 1;
  219. $ls->addElement($column);
  220. $ls->addColumn($column,$GLOBALS['I18N']->get('select'),'<select name="column'.$rec["index"].'">'.$options.'</select>');
  221. }
  222. }
  223. if ($request_mapping) {
  224. $ls->addButton($GLOBALS['I18N']->get('Continue'),'javascript:document.importform.submit()');
  225. print '<p>'.$GLOBALS['I18N']->get('Please identify the target of the following unknown columns').'</p>';
  226. print '<form name="importform" method="post">';
  227. print $ls->display();
  228. print '</form>';
  229. return;
  230. }
  231. }
  232. if ($_SESSION["test_import"]) {
  233. $ls = new WebblerListing($GLOBALS['I18N']->get('Summary'));
  234. foreach ($_SESSION["import_attribute"] as $column => $rec) {
  235. if (trim($column) != '') {
  236. $ls->addElement($column);
  237. if ($rec["record"] == "new") {
  238. $ls->addColumn($column,$GLOBALS['I18N']->get('maps to'),$GLOBALS['I18N']->get('Create new Attribute'));
  239. } elseif ($rec["record"] == "skip") {
  240. $ls->addColumn($column,$GLOBALS['I18N']->get('maps to'),$GLOBALS['I18N']->get('Skip Column'));
  241. } else {
  242. $ls->addColumn($column,$GLOBALS['I18N']->get('maps to'),$attributes[$rec["record"]]);
  243. }
  244. }
  245. }
  246. print $ls->display();
  247. print '<h3>';
  248. printf($GLOBALS['I18N']->get('%d lines will be imported'),$total);
  249. print '</h3>';
  250. print '<p>'.PageLink2($_GET["page"]."&amp;confirm=yes",$GLOBALS['I18N']->get('Confirm Import')).'</p>';
  251. print '<p><h1>'.$GLOBALS['I18N']->get('Test Output').'</h1></p>';
  252. }
  253. if (sizeof($email_list)) {
  254. $import_field_delimiter = $_SESSION["import_field_delimiter"];
  255. if (sizeof($email_list) > 300 && !$_SESSION["test_import"]) {
  256. # this is a possibly a time consuming process, so show a progress bar
  257. print '<script language="Javascript" type="text/javascript"> document.write(progressmeter); start();</script>';
  258. flush();
  259. # increase the memory to make sure we are not running out
  260. ini_set("memory_limit","16M");
  261. }
  262. # print "A: ".sizeof($import_attribute);
  263. reset($system_attributes);
  264. foreach ($system_attributes as $key => $val) {
  265. # print "<br/>$key => $val ".$_SESSION["systemindex"][$key];
  266. if (isset($_SESSION["systemindex"][$key]))
  267. $system_attribute_mapping[$key] = $_SESSION["systemindex"][$key];
  268. }
  269. // Parse the lines into records
  270. # print "<br/>Loading emails .. ";
  271. flush();
  272. $count = array();
  273. $count["email_add"] = 0;
  274. $count["exist"] = 0;
  275. $count["list_add"] = 0;
  276. $count["group_add"] = 0;
  277. $c = 1;
  278. $count["invalid_email"] = 0;
  279. $num_lists = sizeof($_SESSION["lists"]);
  280. $total = sizeof($email_list);
  281. $cnt = 0;
  282. $count["emailmatch"] = 0;
  283. $count["fkeymatch"] = 0;
  284. $count["dataupdate"] = 0;
  285. $additional_emails = 0;
  286. foreach ($email_list as $line) {
  287. # print $line.'<br/>';
  288. $user = array();
  289. # get rid of text delimiters generally added by spreadsheet apps
  290. $line = str_replace('"','',$line);
  291. $values = explode($_SESSION["import_field_delimiter"],$line);
  292. reset($system_attribute_mapping);
  293. $system_values = array();
  294. foreach ($system_attribute_mapping as $column => $index) {
  295. #print "$column = ".$values[$index]."<br/>";
  296. $system_values[$column] = $values[$index];
  297. }
  298. $index = clean($system_values["email"]);
  299. $invalid = 0;
  300. if (!$index) {
  301. if ($_SESSION["show_warnings"])
  302. Warn($GLOBALS['I18N']->get('Record has no email').": $c -> $line");
  303. $index = $GLOBALS['I18N']->get('Invalid Email')." $c";
  304. $system_values["email"] = $_SESSION["assign_invalid"];
  305. $invalid = 1;
  306. $count["invalid_email"]++;
  307. }
  308. if (sizeof($values) != (sizeof($_SESSION["import_attribute"]) + sizeof($_SESSION["system_attributes"]))
  309. && $test_import && $_POST["show_warnings"])
  310. Warn("Record has more values than header indicated (".
  311. sizeof($values). "!=".
  312. (sizeof($_SESSION["import_attribute"]) + sizeof($_SESSION["system_attributes"]))
  313. ."), this may cause trouble: $index");
  314. if (!$invalid || ($invalid && $_SESSION["omit_invalid"] != "yes")) {
  315. $user["systemvalues"] = $system_values;
  316. reset($_SESSION["import_attribute"]);
  317. $replace = array();
  318. while (list($key,$val) = each ($_SESSION["import_attribute"])) {
  319. $user[$val["index"]] = addslashes($values[$val["index"]]);
  320. $replace[$key] = addslashes($values[$val["index"]]);
  321. }
  322. } else {
  323. # Warn("Omitting invalid one: $email");
  324. }
  325. $user["systemvalues"]["email"] = parsePlaceHolders($system_values["email"],array_merge($replace,$system_values,array("number" => $c)));
  326. $user["systemvalues"]["email"] = clean($user["systemvalues"]["email"]);
  327. $c++;
  328. if ($_SESSION["test_import"]) {
  329. # print "<br/><b>$index</b><br/>";
  330. $html = '';
  331. foreach ($user["systemvalues"] as $column => $value) {
  332. if ($value) {
  333. $html .= "$column -> $value<br/>\n";
  334. } else {
  335. $html .= "$column -> ".$GLOBALS['I18N']->get('clear value')."<br/>\n";
  336. }
  337. }
  338. reset($_SESSION["import_attribute"]);
  339. foreach ($_SESSION["import_attribute"] as $column => $item) {
  340. if ($user[$item["index"]]) {
  341. if ($item["record"] == "new") {
  342. $html .= ' '.$GLOBALS['I18N']->get('New Attribute').': '.$item["column"];
  343. } elseif ($item["record"] == "skip") {
  344. # forget about it
  345. $html .= ' '.$GLOBALS['I18N']->get('Skip value').': ';
  346. } else {
  347. $html .= $attributes[$item["record"]];
  348. }
  349. $html .= " -> ".$user[$item["index"]]."<br>";
  350. }
  351. }
  352. if ($html) print '<blockquote>'.$html.'</blockquote>';
  353. } else {
  354. # do import
  355. # create new attributes
  356. foreach ($_SESSION["import_attribute"] as $column => $item) {
  357. if ($item["record"] == "new") {
  358. Sql_Query(sprintf('insert into %s (name,type) values("%s","textline")',
  359. $tables["attribute"],addslashes($column)));
  360. $attid = Sql_Insert_id();
  361. Sql_Query(sprintf('update %s set tablename = "attr%d" where id = %d',
  362. $tables["attribute"],$attid,$attid));
  363. Sql_Query("create table ".$GLOBALS["table_prefix"]."listattr_attr".$attid."
  364. (id integer not null primary key auto_increment, name varchar(255) unique,
  365. listorder integer default 0)");
  366. $_SESSION["import_attribute"][$column]["record"] = $attid;
  367. }
  368. }
  369. $new = 0;
  370. $cnt++;
  371. if ($cnt % 25 == 0) {
  372. print "<br/>\n$cnt/$total";
  373. flush();
  374. }
  375. if ($user["systemvalues"]["foreign key"]) {
  376. $result = Sql_query(sprintf('select id,uniqid from %s where foreignkey = "%s"',
  377. $tables["user"],$user["systemvalues"]["foreign key"]));
  378. # print "<br/>Using foreign key for matching: ".$user["systemvalues"]["foreign key"];
  379. $count["fkeymatch"]++;
  380. $exists = Sql_Affected_Rows();
  381. $existing_user = Sql_fetch_array($result);
  382. # check whether the email will clash
  383. $clashcheck = Sql_Fetch_Row_Query(sprintf('select id from %s
  384. where email = "%s"',$tables["user"],$user["systemvalues"]["email"]));
  385. if ($clashcheck[0] != $existing_user["id"]) {
  386. $duplicatecount++;
  387. $notduplicate = 0;
  388. $c=0;
  389. while (!$notduplicate) {
  390. $c++;
  391. $req = Sql_Query(sprintf('select id from %s where email = "%s"',
  392. $tables["user"],$GLOBALS['I18N']->get('duplicate')."$c ".$user["systemvalues"]["email"]));
  393. $notduplicate = !Sql_Affected_Rows();
  394. }
  395. if (!$_SESSION["retainold"]) {
  396. Sql_Query(sprintf('update %s set email = "%s" where email = "%s"',
  397. $tables["user"],"duplicate$c ".$user["systemvalues"]["email"],$user["systemvalues"]["email"]));
  398. addUserHistory("duplicate$c ".$user["systemvalues"]["email"],"Duplication clash ",' User marked duplicate email after clash with imported record');
  399. } else {
  400. if ($_SESSION["show_warnings"]) print Warn($GLOBALS['I18N']->get('Duplicate Email').' '.$user["systemvalues"]["email"]. $GLOBALS['I18N']->get(' user imported as ').'&quot;'.$GLOBALS['I18N']->get('duplicate')."$c ".$user["systemvalues"]["email"]."&quot;");
  401. $user["systemvalues"]["email"] = $GLOBALS['I18N']->get('duplicate')."$c ".$user["systemvalues"]["email"];
  402. }
  403. }
  404. } else {
  405. $result = Sql_query(sprintf('select id,uniqid from %s where email = "%s"',$tables["user"],$user["systemvalues"]["email"]));
  406. # print "<br/>Using email for matching: ".$user["systemvalues"]["email"];
  407. $count["emailmatch"]++;
  408. $exists = Sql_Affected_Rows();
  409. $existing_user = Sql_fetch_array($result);
  410. }
  411. if ($exists) {
  412. // User exist, remember some values to add them to the lists
  413. $count["exist"]++;
  414. $userid = $existing_user["id"];
  415. $uniqid = $existing_user["uniqid"];
  416. } else {
  417. // user does not exist
  418. $new = 1;
  419. // Create unique number
  420. mt_srand((double)microtime()*1000000);
  421. $randval = mt_rand();
  422. # this is very time consuming when importing loads of users as it does a lookup
  423. # needs speeding up if possible
  424. $uniqid = getUniqid();
  425. $confirmed = $_SESSION["notify"] != "yes" && !preg_match("/Invalid Email/i",$index);
  426. $query = sprintf('INSERT INTO %s (email,entered,confirmed,uniqid)
  427. values("%s",now(),%d,"%s")',
  428. $tables["user"],$user["systemvalues"]["email"],$confirmed,$uniqid);
  429. $result = Sql_query($query,1);
  430. $userid = Sql_insert_id();
  431. if (!$userid) {
  432. # no id returned, so it must have been a duplicate entry
  433. if ($_SESSION["show_warnings"]) print Warn($GLOBALS['I18N']->get('Duplicate Email').' '.$user["systemvalues"]["email"]);
  434. $c = 0;
  435. while (!$userid) {
  436. $c++;
  437. $query = sprintf('INSERT INTO %s (email,entered,confirmed,uniqid)
  438. values("%s",now(),%d,"%s")',
  439. $tables["user"],$user["systemvalues"]["email"]." ($c)",0,$uniqid);
  440. $result = Sql_query($query,1);
  441. $userid = Sql_insert_id();
  442. }
  443. $user["systemvalues"]["email"] = $user["systemvalues"]["email"]." ($c)";
  444. }
  445. $count["email_add"]++;
  446. $some = 1;
  447. }
  448. reset($_SESSION["import_attribute"]);
  449. if ($new || (!$new && $_SESSION["overwrite"] == "yes")) {
  450. $query = "";
  451. $count["dataupdate"]++;
  452. $old_data = Sql_Fetch_Array_Query(sprintf('select * from %s where id = %d',$tables["user"],$userid));
  453. $old_data = array_merge($old_data,getUserAttributeValues('',$userid));
  454. $history_entry = 'http://'.getConfig("website").$GLOBALS["adminpages"].'/?page=user&id='.$userid."\n\n";
  455. foreach ($user["systemvalues"] as $column => $value) {
  456. $query .= sprintf('%s = "%s",',$system_attributes[$column],$value);
  457. }
  458. if ($query) {
  459. $query = substr($query,0,-1);
  460. # this may cause a duplicate error on email, so add ignore
  461. Sql_Query("update ignore {$tables["user"]} set $query where id = $userid");
  462. }
  463. foreach ($_SESSION["import_attribute"] as $item) {
  464. if ($user[$item["index"]] && $item['record'] != 'skip') {
  465. $attribute_index = $item["record"];
  466. $uservalue = $user[$item["index"]];
  467. # check whether this is a textline or a selectable item
  468. $att = Sql_Fetch_Row_Query("select type,tablename,name from ".$tables["attribute"]." where id = $attribute_index");
  469. switch ($att[0]) {
  470. case "select":
  471. case "radio":
  472. $val = Sql_Query("select id from $table_prefix"."listattr_$att[1] where name = \"$uservalue\"");
  473. # if we do not have this value add it
  474. if (!Sql_Affected_Rows()) {
  475. Sql_Query("insert into $table_prefix"."listattr_$att[1] (name) values(\"$uservalue\")");
  476. Warn("Value $uservalue added to attribute $att[2]");
  477. $user_att_value = Sql_Insert_Id();
  478. } else {
  479. $d = Sql_Fetch_Row($val);
  480. $user_att_value = $d[0];
  481. }
  482. break;
  483. case "checkbox":
  484. if ($uservalue && $uservalue != "off")
  485. $user_att_value = "on";
  486. else
  487. $user_att_value = "off";
  488. break;
  489. case "date":
  490. $user_att_value = parseDate($uservalue);
  491. break;
  492. default:
  493. $user_att_value = $uservalue;
  494. break;
  495. }
  496. Sql_query(sprintf('replace into %s (attributeid,userid,value) values(%d,%d,"%s")',
  497. $tables["user_attribute"],$attribute_index,$userid,$user_att_value));
  498. } else {
  499. if ($item["record"] != "skip") {
  500. # add an empty entry if none existed
  501. Sql_Query(sprintf('insert ignore into %s (attributeid,userid,value) values(%d,%d,"")',
  502. $tables["user_attribute"],$item["record"],$userid));
  503. }
  504. }
  505. }
  506. $current_data = Sql_Fetch_Array_Query(sprintf('select * from %s where id = %d',$tables["user"],$userid));
  507. $current_data = array_merge($current_data,getUserAttributeValues('',$userid));
  508. foreach ($current_data as $key => $val) {
  509. if (!is_numeric($key))
  510. if ($old_data[$key] != $val && $old_data[$key] && $key != "password" && $key != "modified") {
  511. $information_changed = 1;
  512. $history_entry .= "$key = $val\n*changed* from $old_data[$key]\n";
  513. }
  514. }
  515. if (!$information_changed) {
  516. $history_entry .= "\nNo user details changed";
  517. }
  518. addUserHistory($user["systemvalues"]["email"],"Import by ".adminName(),$history_entry);
  519. }
  520. #add this user to the lists identified
  521. if (is_array($_SESSION["lists"])) {
  522. reset($_SESSION["lists"]);
  523. $addition = 0;
  524. $listoflists = "";
  525. while (list($key,$listid) = each($_SESSION["lists"])) {
  526. $query = "replace INTO ".$tables["listuser"]." (userid,listid,entered) values($userid,$listid,now())";
  527. $result = Sql_query($query,1);
  528. # if the affected rows is 2, the user was already subscribed
  529. $addition = $addition || Sql_Affected_Rows() == 1;
  530. $listoflists .= " * ".$_SESSION["listname"][$key]."\n";
  531. }
  532. if ($addition)
  533. $count["list_add"]++;
  534. if (!TEST && $_SESSION["notify"] == "yes" && $addition) {
  535. $subscribemessage = ereg_replace('\[LISTS\]', $listoflists, getUserConfig("subscribemessage",$userid));
  536. sendMail($user["systemvalues"]["email"], getConfig("subscribesubject"), $subscribemessage,system_messageheaders(),$envelope);
  537. }
  538. }
  539. if (!is_array($_SESSION["groups"])) {
  540. $groups = array();
  541. } else {
  542. $groups = $_SESSION["groups"];
  543. }
  544. if (isset($everyone_groupid) && !in_array($everyone_groupid,$groups)) {
  545. array_push($groups,$everyone_groupid);
  546. }
  547. if (is_array($groups)) {
  548. #add this user to the groups identified
  549. reset($groups);
  550. $groupaddition = 0;
  551. while (list($key,$groupid) = each($groups)) {
  552. if ($groupid) {
  553. $query = "replace INTO user_group (userid,groupid) values($userid,$groupid)";
  554. $result = Sql_query($query);
  555. # if the affected rows is 2, the user was already subscribed
  556. $groupaddition = $groupaddition || Sql_Affected_Rows() == 1;
  557. }
  558. }
  559. if ($groupaddition)
  560. $count["group_add"]++;
  561. }
  562. } // end else
  563. if ($_SESSION["test_import"] && $c > 50) break;
  564. }
  565. if (!$_SESSION["test_import"]) {
  566. print '<script language="Javascript" type="text/javascript"> finish(); </script>';
  567. $report = "";
  568. if(!$some && !$count["list_add"]) {
  569. $report .= '<br/>'.$GLOBALS['I18N']->get('All the emails already exist in the database and are member of the lists');
  570. } else {
  571. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('%s emails succesfully imported to the database and added to %d lists.'),$count["email_add"],$num_lists);
  572. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('%d emails subscribed to the lists'),$count["list_add"]);
  573. if ($count["exist"]) {
  574. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('%s emails already existed in the database'),$count["exist"]);
  575. }
  576. }
  577. if ($count["invalid_email"]) {
  578. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('%d Invalid Emails found.'),$count["invalid_email"]);
  579. if (!$_SESSION["omit_invalid"]) {
  580. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('These records were added, but the email has been made up from ').$_SESSION["assign_invalid"]);
  581. } else {
  582. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('These records were deleted. Check your source and reimport the data. Duplicates will be identified.'));
  583. }
  584. }
  585. if ($_SESSION["overwrite"] == "yes") {
  586. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('User data was updated for %d users'),$count["dataupdate"]);
  587. }
  588. $report .= sprintf('<br/>'.$GLOBALS['I18N']->get('%d users were matched by foreign key, %d by email'),$count["fkeymatch"],$count["emailmatch"]);
  589. print $report;
  590. if (function_exists('sendmail')) {
  591. sendMail (getConfig("admin_address"),$GLOBALS['I18N']->get('phplist Import Results'),$report);
  592. }
  593. clearImport();
  594. } else {
  595. printf($GLOBALS['I18N']->get('Test output<br/>If the output looks ok, click %s to submit for real').'<br/><br/>',PageLink2($_GET["page"]."&amp;confirm=yes",$GLOBALS['I18N']->get('Confirm Import')));
  596. }
  597. print '<p>'.PageLink2($_GET["page"],$GLOBALS['I18N']->get('Import some more emails'));
  598. return;
  599. }
  600. ?>
  601. <ul>
  602. <?php print formStart('enctype="multipart/form-data" name="import"');?>
  603. <?php
  604. if ($GLOBALS["require_login"] && !isSuperUser()) {
  605. $access = accessLevel("import2");
  606. if ($access == "owner")
  607. $subselect = " where owner = ".$_SESSION["logindetails"]["id"];
  608. elseif ($access == "all")
  609. $subselect = "";
  610. elseif ($access == "none")
  611. $subselect = " where id = 0";
  612. }
  613. if (Sql_Table_Exists($tables["list"])) {
  614. $result = Sql_query("SELECT id,name FROM ".$tables["list"]." $subselect ORDER BY listorder");
  615. $c=0;
  616. if (Sql_Affected_Rows() == 1) {
  617. $row = Sql_fetch_array($result);
  618. printf('<input type=hidden name="listname[%d]" value="%s"><input type=hidden name="lists[%d]" value="%d">%s <b>%s</b>',$c,stripslashes($row["name"]),$c,$row["id"],$GLOBALS['I18N']->get('Adding users to list'),stripslashes($row["name"]));
  619. } else {
  620. print '<p>'.$GLOBALS['I18N']->get('Select the lists to add the emails to').'</p>';
  621. while ($row = Sql_fetch_array($result)) {
  622. printf('<li><input type=hidden name="listname[%d]" value="%s"><input type=checkbox name="lists[%d]" value="%d">%s',$c,stripslashes($row["name"]),$c,$row["id"],stripslashes($row["name"]));
  623. $some = 1;$c++;
  624. }
  625. if (!$some) {
  626. echo $GLOBALS['I18N']->get('No lists available').' '.PageLink2("editlist",$GLOBALS['I18N']->get('Add a list'));
  627. }
  628. }
  629. }
  630. if (Sql_Table_Exists("groups")) {
  631. $result = Sql_query("SELECT id,name FROM groups ORDER BY listorder");
  632. $c=0;
  633. if (Sql_Affected_Rows() == 1) {
  634. $row = Sql_fetch_array($result);
  635. printf('<p><input type=hidden name="groupname[%d]" value="%s"><input type=hidden name="groups[%d]" value="%d">Adding users to group <b>%s</b></p>',$c,$row["name"],$c,$row["id"],$row["name"]);;
  636. } else {
  637. print '<p>'.$GLOBALS['I18N']->get('Select the groups to add the users to').'</p>';
  638. while ($row = Sql_fetch_array($result)) {
  639. if ($row["id"] == $everyone_groupid) {
  640. printf('<li><input type=hidden name="groupname[%d]" value="%s"><input type=hidden name="groups[%d]" value="%d"><b>%s</b> - '.$GLOBALS['I18N']->get('automatically added'),$c,$row["name"],$c,$row["id"],$row["name"]);
  641. } else {
  642. printf('<li><input type=hidden name="groupname[%d]" value="%s"><input type=checkbox name="groups[%d]" value="%d">%s',$c,$row["name"],$c,$row["id"],$row["name"]);;
  643. }
  644. $some = 1;$c++;
  645. }
  646. }
  647. }
  648. ?>
  649. </ul>
  650. <table border="1">
  651. <tr><td colspan=2>
  652. <?php echo $GLOBALS['I18N']->get('importintro')?>
  653. </td></tr>
  654. <tr><td><?php echo $GLOBALS['I18N']->get('File containing emails')?>:<br/>
  655. </td><td><input type="file" name="import_file">
  656. <br/><?php printf($GLOBALS['I18N']->get('uploadlimits'),ini_get("post_max_size"),ini_get("upload_max_filesize"));?>
  657. </td></tr>
  658. <tr><td><?php echo $GLOBALS['I18N']->get('Field Delimiter')?>:</td><td><input type="text" name="import_field_delimiter" size=5> <?php echo $GLOBALS['I18N']->get('(default is TAB)')?></td></tr>
  659. <tr><td><?php echo $GLOBALS['I18N']->get('Record Delimiter')?>:</td><td><input type="text" name="import_record_delimiter" size=5> <?php echo $GLOBALS['I18N']->get('(default is line break)')?></td></tr>
  660. <tr><td colspan=2><?php echo $GLOBALS['I18N']->get('testoutput_blurb')?></td></tr>
  661. <tr><td><?php echo $GLOBALS['I18N']->get('Test output')?>:</td><td><input type="checkbox" name="import_test" value="yes"></td></tr>
  662. <tr><td colspan=2><?php echo $GLOBALS['I18N']->get('warnings_blurb')?></td></tr>
  663. <tr><td><?php echo $GLOBALS['I18N']->get('Show Warnings')?>:</td><td><input type="checkbox" name="show_warnings" value="yes"></td></tr>
  664. <tr><td colspan=2><?php echo $GLOBALS['I18N']->get('omitinvalid_blurb')?></td></tr>
  665. <tr><td><?php echo $GLOBALS['I18N']->get('Omit Invalid')?>:</td><td><input type="checkbox" name="omit_invalid" value="yes"></td></tr>
  666. <tr><td colspan=2><?php echo $GLOBALS['I18N']->get('assigninvalid_blurb')?>
  667. </td></tr>
  668. <tr><td><?php echo $GLOBALS['I18N']->get('Assign Invalid')?>:</td><td><input type="text" name="assign_invalid" value="<?=$GLOBALS["assign_invalid_default"]?>"></td></tr>
  669. <tr><td colspan=2><?php echo $GLOBALS['I18N']->get('overwriteexisting_blurb')?></td></tr>
  670. <tr><td><?php echo $GLOBALS['I18N']->get('Overwrite Existing')?>:</td><td><input type="checkbox" name="overwrite" value="yes"></td></tr>
  671. <tr><td colspan=2><?php echo $GLOBALS['I18N']->get('retainold_blurb')?></td></tr>
  672. <tr><td><?php echo $GLOBALS['I18N']->get('Retain Old User Email')?>:</td><td><input type="checkbox" name="retainold" value="yes"></td></tr>
  673. <tr><td colspan=2><?php echo $GLOBALS['I18N']->get('sendnotification_blurb')?></td></tr>
  674. <tr><td><?php echo $GLOBALS['I18N']->get('Send&nbsp;Notification&nbsp;email')?>&nbsp;<input type="radio" name="notify" value="yes"></td><td><?php echo $GLOBALS['I18N']->get('Make confirmed immediately')?>&nbsp;<input type="radio" name="notify" value="no"></td></tr>
  675. <tr><td><input type="submit" name="import" value="<?php echo $GLOBALS['I18N']->get('Import')?>"></td><td>&nbsp;</td></tr>
  676. </table>
  677. </p>
  678. </form>