PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lists/admin/commonlib/lib/userlib.php

https://github.com/radicaldesigns/amp
PHP | 814 lines | 672 code | 58 blank | 84 comment | 209 complexity | ebb52348b4ebfc82521551d8bf76c858 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. <?
  2. # library with user functions
  3. # this file is shared between the webbler and PHPlist via commonlib
  4. function initialiseUserSession() {
  5. if (!is_array($_SESSION["userdata"])) {
  6. $_SESSION["userdata"] = array();
  7. }
  8. $_SESSION["session"] = $GLOBALS["PHPSESSID"];
  9. }
  10. function getEveryoneGroupID() {
  11. $ev_req = Sql_Fetch_Row_Query("select id from groups where name = \"Everyone\"");
  12. $everyone_groupid = $ev_req[0];
  13. if (!$everyone_groupid) {
  14. Sql_Query("insert into groups (name) values(\"Everyone\")");
  15. $everyone_groupid = Sql_Insert_Id();
  16. }
  17. return $everyone_groupid;
  18. }
  19. function getUniqid($table = "") {
  20. global $tables;
  21. if (!$table) {
  22. if ($tables["user"])
  23. $table = $tables["user"];
  24. else
  25. $table = "user";
  26. }
  27. # make sure it is really unique
  28. $id = md5(uniqid(mt_rand()));
  29. $req = Sql_Query("select id from $table where uniqid = \"$id\"");
  30. while (Sql_Affected_rows()) {
  31. $id = md5(uniqid(mt_rand()));
  32. $req = Sql_Query("select id from $table where uniqid = \"$id\"");
  33. }
  34. return $id;
  35. }
  36. function deleteUser($id) {
  37. global $tables;
  38. Sql_Query(sprintf('delete from %s where userid = %d',$tables["listuser"],$id));
  39. Sql_Query(sprintf('delete from %s where userid = %d',$tables["user_attribute"],$id));
  40. Sql_Query(sprintf('delete from %s where userid = %d',$tables["usermessage"],$id));
  41. Sql_Query(sprintf('delete from %s where user = %d',$tables["user_message_bounce"],$id));
  42. Sql_Query(sprintf('delete from %s where id = %d',$tables["user"],$id));
  43. }
  44. function addNewUser($email,$password = "") {
  45. /*
  46. "id" => array("integer not null primary key auto_increment","sys:ID"),
  47. "email" => array("varchar(255) not null","Email"),
  48. "confirmed" => array("tinyint default 0","sys:Is the email of this user confirmed"),
  49. "entered" => array("datetime","sys:Time Created"),
  50. "modified" => array("timestamp","sys:Time modified"),
  51. "uniqid" => array("varchar(255)","sys:Unique ID for User"),
  52. "unique" => array("(email)","sys:unique"),
  53. "htmlemail" => array("tinyint default 0","Send this user HTML emails"),
  54. "subscribepage" => array("integer","sys:Which page was used to subscribe"),
  55. "rssfrequency" => array("varchar(100)","RSS Frequency"),
  56. "password" => array("varchar(255)","Password"),
  57. "passwordchanged" => array("datetime","sys:Last time password was changed"),
  58. "disabled" => array("tinyint default 0","Is this account disabled?"),
  59. "extradata" => array("text","Additional data"),
  60. */
  61. // insert into user db
  62. Sql_Query(sprintf('insert into user set email = "%s",
  63. entered = now(),modified = now(),password = "%s",
  64. passwordchanged = now(),disabled = 0,
  65. uniqid = "%s",htmlemail = 1
  66. ', $email,$password,getUniqid()));
  67. $id = Sql_Insert_Id();
  68. return $id;
  69. }
  70. function AttributeValue($table,$value) {
  71. global $table_prefix;
  72. # workaround for integration webbler/phplist
  73. if (!isset($table_prefix))
  74. $table_prefix = "phplist_";
  75. if (ereg(",",$value)) {
  76. $result = "";
  77. $res = Sql_Query(sprintf('select name from %slistattr_%s where id in (%s)',
  78. $table_prefix,$table,$value));
  79. while ($row = Sql_Fetch_row($res)) {
  80. $result .= $row[0]."; ";
  81. }
  82. return substr($result,0,-2);
  83. } elseif ($value) {
  84. $res = Sql_Query(sprintf('select name from %slistattr_%s where id = %d',
  85. $table_prefix,$table,$value));
  86. $row = Sql_Fetch_row($res);
  87. } else {
  88. return "Invalid Attribute Index";
  89. }
  90. return $row[0];
  91. }
  92. function getUserAttributeValues($email) {
  93. global $table_prefix,$tables;
  94. # workaround for integration webbler/phplist
  95. if (!isset($table_prefix))
  96. $table_prefix = "phplist_";
  97. if (!$email) return;
  98. if (isset($tables["attribute"])) {
  99. $att_table = $tables["attribute"];
  100. $user_att_table = $tables["user_attribute"];
  101. $usertable = $tables["user"];
  102. } else {
  103. $att_table = "attribute";
  104. $user_att_table = "user_attribute";
  105. $usertable = "user";
  106. }
  107. $result = array();
  108. $userid = Sql_Fetch_Row_Query("select id from {$usertable} where email = \"$email\"");
  109. $att_req = Sql_Query(sprintf('select
  110. %s.name,%s.id from %s,%s
  111. where %s.userid = %s and %s.id = %s.attributeid',
  112. $att_table,
  113. $att_table,
  114. $user_att_table,
  115. $att_table,
  116. $user_att_table,
  117. $userid[0],
  118. $att_table,
  119. $user_att_table
  120. ));
  121. while ($att = Sql_fetch_array($att_req)) {
  122. $result[$att["name"]] = UserAttributeValue($userid[0],$att["id"]);
  123. }
  124. return $result;
  125. }
  126. function UserAttributeValue($user = 0,$attribute = 0) {
  127. # workaround for integration webbler/phplist
  128. global $table_prefix,$tables;
  129. if (!isset($table_prefix))
  130. $table_prefix = "phplist_";
  131. if (!$user || !$attribute) return;
  132. if (isset($tables["attribute"])) {
  133. $att_table = $tables["attribute"];
  134. $user_att_table = $tables["user_attribute"];
  135. } else {
  136. $att_table = "attribute";
  137. $user_att_table = "user_attribute";
  138. }
  139. $att = Sql_Fetch_array_Query("select * from $att_table where id = $attribute");
  140. switch ($att["type"]) {
  141. case "checkboxgroup":
  142. $val_ids = Sql_Fetch_Row_Query("select value from $user_att_table where userid = $user and attributeid = $attribute");
  143. if ($val_ids[0]) {
  144. $res = Sql_Query("select $table_prefix"."listattr_".$att["tablename"].".name
  145. from $user_att_table,$table_prefix"."listattr_".$att["tablename"]."
  146. where $user_att_table".".userid = ".$user." and
  147. $table_prefix"."listattr_".$att["tablename"].".id in ($val_ids[0]) and
  148. $user_att_table".".attributeid = ".$attribute);
  149. while ($row = Sql_Fetch_row($res))
  150. $value .= $row[0]."; ";
  151. $value = substr($value,0,-2);
  152. } else {
  153. $value = "";
  154. }
  155. break;
  156. case "select":
  157. case "radio":
  158. $res = Sql_Query("select $table_prefix"."listattr_".$att["tablename"].".name
  159. from $user_att_table,$table_prefix"."listattr_".$att["tablename"]."
  160. where $user_att_table".".userid = ".$user." and
  161. $table_prefix"."listattr_".$att["tablename"].".id = $user_att_table".".value and
  162. $user_att_table".".attributeid = ".$attribute);
  163. $row = Sql_Fetch_row($res);
  164. $value = $row[0];
  165. break;
  166. default:
  167. $res = Sql_Query("select value from $user_att_table where
  168. $user_att_table".".userid = ".$user." and attributeid =
  169. ".$attribute);
  170. $row = Sql_Fetch_row($res);
  171. $value = $row[0];
  172. }
  173. return $value;
  174. }
  175. function userName() {
  176. global $config;
  177. if (!is_array($config["nameattributes"])) return "";
  178. $res = "";
  179. foreach ($config["nameattributes"] as $att) {
  180. $res .= $_SESSION["userdata"][$att]["displayvalue"].' ';
  181. }
  182. return rtrim($res);
  183. }
  184. function UserAttributeValueSelect($user,$attribute) {
  185. if (!$user || !$attribute) return;
  186. global $table_prefix,$tables;
  187. # workaround for integration webbler/phplist
  188. if (!isset($table_prefix))
  189. $table_prefix = "phplist_";
  190. if ($tables["attribute"]) {
  191. $att_table = $tables["attribute"];
  192. $user_att_table = $tables["user_attribute"];
  193. } else {
  194. $att_table = "attribute";
  195. $user_att_table = "user_attribute";
  196. }
  197. if (!Sql_Table_exists($att_table)) {
  198. return "broken attribute $attribute";
  199. }
  200. $att = Sql_Fetch_array_Query("select * from $att_table where id = $attribute");
  201. # $value = UserAttributeValue($att["tablename"],$attribute);
  202. $value = UserAttributeValue($user,$attribute);
  203. $html .= 'Value: '.$value;
  204. $html = sprintf('<select name="attribute[%d]" style="attributeinput" >',$attribute);
  205. $res = Sql_Query("select id,name from $table_prefix"."listattr_".$att["tablename"]." order by name");
  206. if (!Sql_Affected_Rows())
  207. return "(No values available)";
  208. $html .= '<option value="0">-- no value</option>';
  209. while ($row = Sql_Fetch_Row($res))
  210. $html .= sprintf('<option value="%d" %s>%s',$row[0],$row[1] == $value?"selected":"",$row[1]);
  211. return $html . '</select>';
  212. }
  213. function UserAttributeValueCbGroup($user,$attribute) {
  214. if (!$user || !$attribute) return;
  215. global $table_prefix,$tables;
  216. if ($tables["attribute"]) {
  217. $att_table = $tables["attribute"];
  218. $user_att_table = $tables["user_attribute"];
  219. } else {
  220. $att_table = "attribute";
  221. $user_att_table = "user_attribute";
  222. }
  223. # workaround for integration webbler/phplist
  224. if (!isset($table_prefix))
  225. $table_prefix = "phplist_";
  226. $att = Sql_Fetch_array_Query("select * from $att_table where id = $attribute");
  227. $values_req = Sql_Fetch_Row_Query("select value from $user_att_table where userid = $user and attributeid = $attribute");
  228. $values = split(",",$values_req[0]);
  229. $html = sprintf('<input type="hidden" name="cbgroup[]" value="%d"><table>',$attribute);
  230. # $html = sprintf('<select name="attribute[%d]" style="attributeinput" >',$attribute);
  231. $res = Sql_Query("select id,name from $table_prefix"."listattr_".$att["tablename"]." order by listorder,name");
  232. if (!Sql_Affected_Rows())
  233. return "(No values available)";
  234. while ($row = Sql_Fetch_Row($res))
  235. $html .= sprintf('<tr><td><input type="checkbox" name="cbgroup%d[]" value="%d" %s></td><td>%s</td></tr>',
  236. $attribute,$row[0],in_array($row[0],$values)?"checked":"",$row[1]);
  237. return $html . '</table>';
  238. }
  239. function userGroups($loginname) {
  240. $result = array();
  241. if (Sql_Table_exists("user_group")) {
  242. $req = Sql_Query("select groupid from user_group,user where user_group.userid = user.id and user.email = \"$loginname\"");
  243. while ($row = Sql_Fetch_Row($req))
  244. array_push($result,$row[0]);
  245. }
  246. return $result;
  247. }
  248. function UserAttributeValue1($kwlib,$value) {
  249. if ($value) {
  250. $res = Sql_Query("select value from keywordlibvalue where id = $value");
  251. $row = Sql_Fetch_row($res);
  252. } else {
  253. return "Invalid Attribute Index";
  254. }
  255. return $row[0];
  256. }
  257. function is_email($email) {
  258. $email = trim($email);
  259. # hmm, it seems people are starting to have emails with & and ' or ` chars in the name
  260. #'
  261. $pattern =
  262. "^[\&\'-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dev|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|home|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|loc|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|quipu|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$";
  263. if(eregi($pattern, $email))
  264. return(1);
  265. else
  266. return(0);
  267. }
  268. function validateEmail($email) {
  269. if ($GLOBALS["config"]["dont_require_validemail"])
  270. return 1;
  271. if (isset($email) && (!isset($GLOBALS["check_for_host"]) || $GLOBALS["check_for_host"])) {
  272. list($username,$domaincheck) = split('@',$email);
  273. $mxhosts = array();
  274. $validhost = getmxrr ($domaincheck,$mxhosts);
  275. } else {
  276. $validhost = 0;
  277. }
  278. return $validhost && is_email($email);
  279. }
  280. function validMod10($no) {
  281. $dups = array();
  282. $rev = strrev($no);
  283. for ($i=0;$i<strlen($rev);$i++) {
  284. if ($i % 2 == 1) {
  285. array_push($dups,substr($rev,$i,1) * 2);
  286. } else {
  287. array_push($dups,substr($rev,$i,1));
  288. }
  289. }
  290. $total = 0;
  291. foreach ($dups as $dig) {
  292. for ($i=0;$i<strlen($dig);$i++) {
  293. $total += substr($dig,$i,1);
  294. }
  295. # print "$dig - $total<br/>";
  296. }
  297. return ($total % 10 == 0);
  298. # print "$no";
  299. }
  300. function validateCC($ccno) {
  301. # credit card validation routines here
  302. # major credit cards that you might want to validate.
  303. #CARD TYPE Prefix Length Check digit algorithm
  304. #MASTERCARD 51-55 16 mod 10
  305. #VISA 4 13,16 mod 10
  306. #AMEX 34,37 15 mod 10
  307. #Diners Club/Carte Blanche 300-305,36,38 14 mod 10
  308. #Discover 6011 16 mod 10
  309. #enRoute 2014,2149 15 any
  310. #JCB 3 16 mod 10
  311. #JCB 2131,1800 15 mod 10
  312. $ccno = preg_replace("/\D/","",$ccno);
  313. $length = strlen($ccno);
  314. $firsttwo = substr($ccno,0,2);
  315. $firstthree = substr($ccno,0,3);
  316. $first = substr($ccno,0,1);
  317. $firstfour = substr($ccno,0,4);
  318. if ($firsttwo >= 51 && $firsttwo <= 55) # Mastercard
  319. return $length == 16 && validMod10($ccno);
  320. elseif ($first == 4) # visa
  321. return ($length == 13 || $length == 16) && validMod10($ccno);
  322. elseif ($firsttwo == 34 || $firsttwo == 37) # Amex
  323. return $length == 15 && validMod10($ccno);
  324. elseif (($firstthree >= 300 && $firstthree <= 305) # Diners1
  325. || ($firsttwo == 36 || $firsttwo == 38)) # Diners2
  326. return $length == 14 && validMod10($ccno);
  327. elseif ($firstfour == 6011) # discover
  328. return $length == 16 && validMod10($ccno);
  329. elseif ($firstfour == 2014 || $firstfour == 2149) # enRoute
  330. return $length == 15;
  331. else
  332. # if it is not any of the above, we do not know how to validate it
  333. # reject 4 and 15 1s anyway apart when request is from tincan offices
  334. if ($ccno == "4111111111111111" && getenv("REMOTE_ADDR") != '213.253.144.33') {
  335. return 0;
  336. }
  337. return 1;
  338. }
  339. function loadCCvalidationFile($ccrangefile) {
  340. if (!is_file($ccrangefile))
  341. return array();
  342. $range = array();
  343. $fp = fopen($ccrangefile,"rb");
  344. $contents = fread($fp,filesize($ccrangefile));
  345. fclose($fp);
  346. $lines = explode("\n",$contents);
  347. foreach ($lines as $line) {
  348. if (!preg_match("/^\s*#/",$line) && !preg_match("/^\s+$/",$line)) {
  349. if (preg_match("#(\d+),(\d+),(\d+)#",$line,$regs)) {
  350. array_push($range,array(
  351. "start" => $regs[1],
  352. "end" => $regs[2],
  353. "company" => sprintf('%02d',$regs[3])
  354. ));
  355. # dbg($regs[1]. " ". $regs[2]. " -> ".$regs[3]);
  356. } elseif (preg_match("#\((\d+)\)\s*=\s*'(.*)'#",$line,$regs)) {
  357. $company[sprintf('%02d',$regs[1])] = $regs[2];
  358. # dbg($regs[1]. " = " . $regs[2]);
  359. }
  360. }
  361. }
  362. return array($range,$company);
  363. }
  364. function ccCompany($ccno) {
  365. global $config;
  366. $ccrangefile = $config["code_root"]."/".$config["uploader_dir"]."/codelib/ccvalidation.txt";
  367. list($ranges,$companies) = loadCCvalidationFile($ccrangefile);
  368. $first6 = substr($ccno,0,6);
  369. if (is_array($ranges))
  370. foreach ($ranges as $range) {
  371. # dbg($range["start"]);
  372. if ($range["start"] <= $first6 && $range["end"] >= $first6) {
  373. return array($range["company"],$companies[$range["company"]]);
  374. }
  375. }
  376. return -1;
  377. }
  378. function checkCCrange($ccno) {
  379. global $config;
  380. $ccrangefile = $config["code_root"]."/".$config["uploader_dir"]."/codelib/ccvalidation.txt";
  381. if (!is_file($ccrangefile) || !is_array($config["cc_accept_company"]))
  382. return 1;
  383. list($companyid,$companyname) = ccCompany($ccno);
  384. if ($companyid > 0 && in_array($companyid,$config["cc_accept_company"])) {
  385. # dbg($ccno . " is valid for company $companyid $companyname");
  386. return 1;
  387. } elseif ($companyid < 0) {
  388. return -1;
  389. } else {
  390. return 0;
  391. }
  392. }
  393. function validateCCExpiry($ccexpiry) {
  394. # expiry date validation here
  395. $mon = substr($ccexpiry,0,2);
  396. if (strlen($ccexpiry) == 5) {
  397. # I presume it is with a separator
  398. $year = substr($ccexpiry,3,2);
  399. } elseif (strlen($ccexpiry) == 4) {
  400. $year = substr($ccexpiry,2,2);
  401. } else {
  402. return 0;
  403. }
  404. $yeardiff = $year - date("y");
  405. return ($mon < 13 && $yeardiff < 9 && (($year > date("y")) || ($year == date("y") && $mon >= date("m"))));
  406. }
  407. function obscureCreditCard($cardno) {
  408. if (strlen($cardno) < 5)
  409. return $cardno;
  410. $res = substr($cardno,strlen($cardno)-4,4);
  411. for ($i=0;$i<strlen($cardno)-4;$i++) {
  412. $prefix .= '*';
  413. }
  414. $res = $prefix . $res;
  415. return $res;
  416. }
  417. function loadUser($loginname = "") {
  418. dbg("Loading User");
  419. if (!Sql_Table_exists("user")) return;
  420. initialiseUserSession();
  421. if (!$loginname) {
  422. if ($_SESSION["userloggedin"] != "" && $_SESSION["username"] != "") {
  423. $loginname = $_SESSION["username"];
  424. } else {
  425. return "";
  426. }
  427. }
  428. $att_req = Sql_Query(sprintf('select attribute.id,
  429. %s.name,%s.type,
  430. %s.value,%s.tablename from %s,%s,%s
  431. where %s.userid = %s.id and %s.email = "%s" and %s.id = %s.attributeid',
  432. "attribute",
  433. "attribute",
  434. "user_attribute",
  435. "attribute",
  436. "user",
  437. "user_attribute",
  438. "attribute",
  439. "user_attribute",
  440. "user",
  441. "user",
  442. $loginname,
  443. "attribute",
  444. "user_attribute"
  445. ));
  446. while ($att = Sql_fetch_array($att_req)) {
  447. # if (!defined($_SESSION["userdata"]["attribute".$att["id"]])) {
  448. $_SESSION["userdata"]["attribute".$att["id"]] = array(
  449. "name" => $att["name"],
  450. "value" => $att["value"],
  451. "type" => $att["type"],
  452. "attid" => $att["id"]
  453. );
  454. switch ($att["type"]) {
  455. case "textline":
  456. case "hidden":
  457. $_SESSION["userdata"]["attribute".$att["id"]]["displayvalue"] =
  458. $att["value"];
  459. break;
  460. case "creditcardno":
  461. $_SESSION["userdata"]["attribute".$att["id"]]["displayvalue"] =
  462. obscureCreditCard($att["value"]);
  463. break;
  464. case "select":
  465. $_SESSION["userdata"]["attribute".$att["id"]]["displayvalue"] =
  466. AttributeValue($att["tablename"],$att["value"]);
  467. break;
  468. }
  469. # }
  470. }
  471. $d_req = Sql_Fetch_Array_Query("select * from user where email = \"$loginname\"");
  472. $_SESSION["userid"] = $d_req["id"];
  473. foreach (array("email","disabled","confirmed","htmlemail","uniqid") as $field) {
  474. # if (!defined($_SESSION["userdata"][$field])) {
  475. $_SESSION["userdata"][$field] = array(
  476. "name" => $field,
  477. "value" => $d_req[$field],
  478. "type" => "static",
  479. "displayvalue" => $d_req[$field]
  480. );
  481. # }
  482. }
  483. dbg("done loading user");
  484. $_SESSION["groups"] = userGroups($loginname);
  485. return 1;
  486. }
  487. function addKeywordLibrary($name) {
  488. $req = Sql_Query(sprintf('select id from keywordlib where name = "%s"',$name));
  489. if (Sql_affected_Rows()) {
  490. $row = Sql_Fetch_Row($req);
  491. return $row[0];
  492. }
  493. Sql_Query(sprintf('insert into keywordlib (name) values("%s")',$name));
  494. return Sql_Insert_id();
  495. }
  496. function getNewAttributeTablename($name) {
  497. $lc_name = substr(preg_replace("/\W/","", strtolower($name)),0,10);
  498. # if ($lc_name == "") Fatal_Error("Name cannot be empty: $lc_name");
  499. if (!$lc_name) $lc_name = "attribute";
  500. Sql_Query("select * from attribute where tablename = \"$lc_name\"");
  501. # if (Sql_Affected_Rows()) Fatal_Error("Name is not unique enough");
  502. $c = 1;
  503. $basename = $lc_name;
  504. while (Sql_Affected_Rows() && $c < 100) {
  505. $lc_name = $basename.$c;
  506. Sql_Query("select * from attribute where tablename = \"$lc_name\"");
  507. $c++;
  508. }
  509. return $lc_name;
  510. }
  511. function isGuestAccount() {
  512. if (!is_array($_SESSION["userdata"])) {
  513. return 1;
  514. }
  515. if ($GLOBALS["config"]["guestaccount_email_match"]) {
  516. return preg_match($GLOBALS["config"]["guestaccount_email_match"],$_SESSION["userdata"]["email"]["value"]);
  517. }
  518. }
  519. function saveUserAttribute($userid,$attid,$data) {
  520. if ($data["nodbsave"]) {
  521. dbg("Not saving $attid");
  522. return;
  523. }
  524. if ($attid == "emailcheck" || $attid == "passwordcheck") {
  525. dbg("Not saving $attid");
  526. return;
  527. }
  528. if (!$data["type"])
  529. $data["type"] = "textline";
  530. if ($data["type"] == "static" || $data["type"] == "password") {
  531. Sql_Query(sprintf('update user set %s = "%s" where id = %d',
  532. $attid,$data["value"],$userid));
  533. return 1;
  534. }
  535. $attid_req = Sql_Fetch_Row_Query(sprintf('
  536. select id,type,tablename from attribute where id = %d',$attid));
  537. if (!$attid_req[0]) {
  538. $attid_req = Sql_Fetch_Row_Query(sprintf('
  539. select id,type,tablename from attribute where name = "%s"',$data["name"]));
  540. if (!$attid_req[0]) {
  541. if ($GLOBALS["config"]["autocreate_attributes"]) {
  542. Dbg("Creating new Attribute: ".$data["name"]);
  543. sendError("creating new attribute ".$data["name"]);
  544. $atttable= getNewAttributeTablename($data["name"]);
  545. Sql_Query(sprintf('insert into attribute (name,type,tablename) values("%s","%s","%s")',$data["name"],$data["type"],$atttable));
  546. $attid = Sql_Insert_Id();
  547. } else {
  548. dbg("Not creating new Attribute: ".$data["name"]);
  549. # sendError("Not creating new attribute ".$data["name"]);
  550. }
  551. } else {
  552. $attid = $attid_req[0];
  553. $atttable = $attid_req[2];
  554. }
  555. } else {
  556. $attid = $attid_req[0];
  557. $atttable = $attid_req[2];
  558. }
  559. if (!$atttable) {
  560. $atttable = getNewAttributeTablename($data["name"]);
  561. # fix attribute without tablename
  562. Sql_Query(sprintf('update attribute set tablename ="%s" where id = %d',
  563. $atttable,$attid));
  564. # sendError("Attribute without Tablename $attid");
  565. }
  566. switch ($data["type"]) {
  567. case "static":
  568. case "password":
  569. Sql_Query(sprintf('update user set %s = "%s" where id = %d',
  570. $attid,$data["value"],$userid));
  571. break;
  572. case "select":
  573. $curval = Sql_Fetch_Row_Query(sprintf('select id from phplist_listattr_%s
  574. where name = "%s"',$atttable,$data["displayvalue"]),1);
  575. if (!$curval[0]) {
  576. Sql_Query(sprintf('insert into phplist_listattr_%s (name) values("%s")',$atttable,
  577. $data["displayvalue"]));
  578. sendError("Added ".$data["displayvalue"]." to $atttable");
  579. $valid = Sql_Insert_id();
  580. } else {
  581. $valid = $curval[0];
  582. }
  583. Sql_Query(sprintf('replace into user_attribute (userid,attributeid,value)
  584. values(%d,%d,"%s")',$userid,$attid,$valid));
  585. break;
  586. default:
  587. Sql_Query(sprintf('replace into user_attribute (userid,attributeid,value)
  588. values(%d,%d,"%s")',$userid,$attid,$data["value"]));
  589. break;
  590. }
  591. return 1;
  592. }
  593. function saveUserByID($userid,$data) {
  594. while (list($key,$val) = each($data)) {
  595. if (preg_match("/^attribute(\d+)/",$key,$regs)) {
  596. $attid = $regs[1];
  597. } else {
  598. $attid = $key;
  599. }
  600. dbg("Saving attribute $key, $attid, $val for $userid");
  601. if ($userid && $attid)
  602. saveUserAttribute($userid,$attid,$val);
  603. }
  604. }
  605. function saveUser($loginname,$data) {
  606. # saves user to database
  607. $id_req = Sql_Fetch_Row_Query("select id from user where email = \"$loginname\"");
  608. if ($id_req[0]) {
  609. $userid = $id_req[0];
  610. while (list($key,$val) = each($data)) {
  611. if (ereg("^attribute(\d+)",$key,$regs)) {
  612. $attid = $regs[1];
  613. }
  614. dbg("Saving attribute $key, $attid, $val for $loginname, $userid");
  615. if ($userid && $attid)
  616. saveUserAttribute($userid,$key,$val);
  617. }
  618. }
  619. return 1;
  620. }
  621. function saveUserData($username,$fields) {
  622. # saves data in session, not in database
  623. dbg("Saving user $username");
  624. if (!is_array($_SESSION["userdata"])) {
  625. dbg("Nothing to save");
  626. return;
  627. }
  628. if (!$username) {
  629. $username = 'Unknown User';
  630. }
  631. $res = "";
  632. $required_fields = explode(",",$_POST["required"]);
  633. $required_formats = explode(",",$_POST["required_formats"]);
  634. $description_fields = explode(",",$_POST["required_description"]);
  635. reset($fields);
  636. dbg("Checking fields");
  637. while (list($fname,$fval) = each ($fields)) {
  638. # dbg($fname);
  639. $key = $fname;
  640. $val = $_POST[$fname];
  641. if (!ereg("required",$key) &&
  642. $fields[$key]["type"] != "separator" &&
  643. $fields[$key]["type"] != "emailcheck" &&
  644. $fields[$key]["type"] != "passwordcheck"
  645. ) {
  646. # dbg($fname ." of type ".$fields[$key]["type"]);
  647. if (!is_array($_SESSION["userdata"][$key]))
  648. $_SESSION["userdata"][$key] = array();
  649. $_SESSION["userdata"][$key]["name"] = $fields[$key]["name"];
  650. $_SESSION["userdata"][$key]["type"] = $fields[$key]["type"];
  651. if ($fields[$key]["type"] == "creditcardno") {
  652. # dont overwrite known CC with ***
  653. if (!preg_match("#^\*+#",$val)) {
  654. $_SESSION["userdata"][$key]["value"] = ltrim($val);
  655. }
  656. } else {
  657. $_SESSION["userdata"][$key]["value"] = ltrim($val);
  658. }
  659. if ($fields[$key]["type"] == "select") {
  660. $_SESSION["userdata"][$key]["displayvalue"] = $fields[$key]["values"][$val];
  661. } elseif ($fields[$key]["type"] == "checkboxgroup") {
  662. $_SESSION["userdata"][$key]["value"] = join(",",$val);
  663. } elseif ($fields[$key]["type"] == "creditcardno") {
  664. # erase any non digits from the CC numbers
  665. $_SESSION["userdata"][$key]["value"] = preg_replace("/\D/","",$_SESSION["userdata"][$key]["value"]);
  666. $_SESSION["userdata"][$key]["displayvalue"] = obscureCreditCard($_SESSION["userdata"][$key]["value"]);
  667. } elseif ($fields[$key]["name"] == "Card Number") {
  668. $_SESSION["userdata"][$key]["value"] = preg_replace("/\D/","",$_SESSION["userdata"][$key]["value"]);
  669. $_SESSION["userdata"][$key]["displayvalue"] = obscureCreditCard($_SESSION["userdata"][$key]["value"]);
  670. /* $_SESSION["userdata"][$key]["displayvalue"] = substr($_SESSION["userdata"][$key]["displayvalue"],0,4);
  671. for ($i=0;$i<strlen($_SESSION["userdata"][$key]["value"]-4);$i++) {
  672. $_SESSION["userdata"][$key]["displayvalue"] .= '*';
  673. }
  674. */
  675. } else {
  676. $_SESSION["userdata"][$key]["displayvalue"] = $val;
  677. }
  678. /* # remember other aspects of the fields
  679. foreach ($fields as $key => $val) {
  680. foreach ($val as $field_attr => $value) {
  681. if (!isset($_SESSION["userdata"][$key][$field_attr]) && !preg_match("/^\d+$/",$key)
  682. && !preg_match("/^\d+$/",$field_attr)
  683. ) {
  684. $_SESSION["userdata"][$key][$field_attr] = $value;
  685. }
  686. }
  687. }
  688. */
  689. # save it to the DB as well
  690. } else {
  691. # dbg("Not checking ".$fname ." of type ".$fields[$key]["type"]);
  692. }
  693. }
  694. # fix UK postcodes to correct format
  695. if ($_SESSION["userdata"][$GLOBALS["config"]["country_attribute"]]["displayvalue"] == "United Kingdom") {
  696. $postcode = $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"];
  697. $postcode = strtoupper(str_replace(" ","",$postcode));
  698. if (preg_match("/(.*)(\d\w\w)$/",$postcode,$regs)) {
  699. $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"] = trim($regs[1])." ".$regs[2];
  700. $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["displayvalue"] = trim($regs[1])." ".$regs[2];
  701. }
  702. }
  703. while (list($index,$field) = each ($required_fields)) {
  704. $type = $fields[$field]["type"];
  705. if ($field && !$_SESSION["userdata"][$field]["value"]) {
  706. $res = "Information missing: ".$description_fields[$index];
  707. break;
  708. } else if ($required_formats[$index] && !preg_match(stripslashes($required_formats[$index]),$_SESSION["userdata"][$field]["value"])) {
  709. $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
  710. break;
  711. } else if ($field == "email" && !validateEmail($_SESSION["userdata"][$field]["value"])) {
  712. $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
  713. break;
  714. } else if ($field == "cardtype" && $_SESSION["userdata"][$field]["value"] == "WSWITCH" && !preg_match("/\d/",$_SESSION["userdata"]["attribute82"]["value"])) {
  715. $res = "Sorry, a Switch Card requires a valid issue number. If you have a new Switch card without an issue number, please use 0 as the issue number.";
  716. break;
  717. } else if ($field == "cardtype" && $_SESSION["userdata"][$field]["value"] != "WSWITCH" && $_SESSION["userdata"]["attribute82"]["value"]) {
  718. $res = "Sorry, an issue number is not valid when not using a Switch Card";
  719. break;
  720. } else if (($type == "creditcardno" || $field == "cardnumber") && !checkCCrange($_SESSION["userdata"][$field]["value"])) {
  721. list($cid,$cname) = ccCompany($_SESSION["userdata"][$field]["value"]);
  722. if (!$cname)
  723. $cname = '(Unknown Credit card)';
  724. $res = "Sorry, we currently don't accept $cname cards";
  725. break;
  726. } else if (($type == "creditcardno" || $field == "cardnumber") && !validateCC($_SESSION["userdata"][$field]["value"])) {
  727. $res = "Sorry, you entered an invalid ".$description_fields[$index];#.": ".$_SESSION["userdata"][$field]["value"];
  728. break;
  729. } else if (($type == "creditcardexpiry" ||$field == "cardexpiry") && !validateCCExpiry($_SESSION["userdata"][$field]["value"])) {
  730. $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
  731. break;
  732. }
  733. }
  734. if ($_SESSION["userdata"][$GLOBALS["config"]["country_attribute"]]["displayvalue"] == "United Kingdom") {
  735. $postcode = $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["displayvalue"];
  736. if (!preg_match("/(.*)(\d\w\w)$/",$postcode,$regs)) {
  737. $res = "That does not seem to be a valid UK postcode";
  738. } elseif (!preg_match("/^[\s\w\d]+$/",$postcode,$regs)) {
  739. $res = "That does not seem to be a valid UK postcode";
  740. }
  741. }
  742. if (is_array($GLOBALS["config"]["bocs_dpa"])) {
  743. if (!is_array($_SESSION["DPA"]))
  744. $_SESSION["DPA"] = array();
  745. foreach ($GLOBALS["config"]["bocs_dpa"] as $dpaatt => $val) {
  746. if ($_SESSION["userdata"][$dpaatt]["displayvalue"]) {
  747. $_SESSION["DPA"][$val] = "Y";
  748. } else {
  749. $_SESSION["DPA"][$val] = "N";
  750. }
  751. }
  752. }
  753. return $res;
  754. }
  755. ?>