PageRenderTime 67ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/bontiv/insomnia
PHP | 1203 lines | 982 code | 86 blank | 135 comment | 315 complexity | f576a7fc92196470773450120a136f8c MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0, LGPL-2.1, GPL-3.0, BSD-3-Clause, GPL-2.0
  1. <?php
  2. /**
  3. * library with user functions
  4. *
  5. * this file is shared between the webbler and PHPlist via commonlib
  6. *
  7. * @package Common
  8. * @subpackage userlib
  9. */
  10. require_once dirname(__FILE__).'/accesscheck.php';
  11. function initialiseUserSession() {
  12. if (!is_array($_SESSION["userdata"])) {
  13. $_SESSION["userdata"] = array();
  14. }
  15. // $_SESSION["session"] = $GLOBALS["PHPSESSID"];
  16. // What should it be??
  17. $_SESSION["session"] = $_COOKIE["PHPSESSID"];
  18. }
  19. function getEveryoneGroupID() {
  20. $ev_req = Sql_Fetch_Row_Query("select id from groups where name = \"Everyone\"");
  21. $everyone_groupid = $ev_req[0];
  22. if (!$everyone_groupid) {
  23. Sql_Query("insert into groups (name) values(\"Everyone\")");
  24. $everyone_groupid = Sql_Insert_Id();
  25. }
  26. return $everyone_groupid;
  27. }
  28. function getUniqid($table = "") {
  29. global $tables;
  30. if (!$table) {
  31. if ($tables["user"])
  32. $table = $tables["user"];
  33. else
  34. $table = "user";
  35. }
  36. $id = md5(uniqid(mt_rand()));
  37. /* this doesn't scale very well, do this offline
  38. # make sure it is really unique
  39. $req = Sql_Query("select id from $table where uniqid = \"$id\"");
  40. while (Sql_Affected_rows()) {
  41. $id = md5(uniqid(mt_rand()));
  42. $req = Sql_Query("select id from $table where uniqid = \"$id\"");
  43. }
  44. */
  45. return $id;
  46. }
  47. function userSelect($fieldname,$current = '') {
  48. $html = sprintf('<select name="%s">',$fieldname);
  49. $req = Sql_Query(sprintf('select id,email from user order by email'));
  50. while ($row = Sql_Fetch_Array($req)) {
  51. $html .= sprintf('<option value="%d" %s>%s</option>',$row['id'],$current == $row['id']? 'selected="selected"':'',$row['email']);
  52. }
  53. $html .= '</select>';
  54. return $html;
  55. }
  56. function deleteUser($id) {
  57. global $tables;
  58. Sql_Query(sprintf('delete from %s where userid = %d',$tables["listuser"],$id));
  59. Sql_Query(sprintf('delete from %s where userid = %d',$tables["user_attribute"],$id));
  60. Sql_Query(sprintf('delete from %s where userid = %d',$tables["usermessage"],$id));
  61. Sql_Query(sprintf('delete from %s where user = %d',$tables["user_message_bounce"],$id));
  62. Sql_Query(sprintf('delete from %s where id = %d',$tables["user"],$id));
  63. Sql_Query(sprintf('delete from %s where userid = %d',$tables["user_history"],$id));
  64. if (Sql_table_exists('user_group')) {
  65. Sql_Query(sprintf('delete from user_group where userid = %d',$id));
  66. }
  67. ### allow plugins to delete their data
  68. if (is_array($GLOBALS['plugins'])) {
  69. foreach ($GLOBALS['plugins'] as $plugin) {
  70. //$plugin->deleteUser($id);
  71. if (method_exists($plugin, "deleteUser")) {
  72. $plugin->deleteUser($id);
  73. }
  74. }
  75. }
  76. }
  77. function addNewUser($email,$password = "") {
  78. if (empty($GLOBALS['tables']['user'])) {
  79. $GLOBALS['tables']['user'] = 'user';
  80. }
  81. /*
  82. "id" => array("integer not null primary key auto_increment","sys:ID"),
  83. "email" => array("varchar(255) not null","Email"),
  84. "confirmed" => array("tinyint default 0","sys:Is the email of this user confirmed"),
  85. "entered" => array("datetime","sys:Time Created"),
  86. "modified" => array("timestamp","sys:Time modified"),
  87. "uniqid" => array("varchar(255)","sys:Unique ID for User"),
  88. "unique" => array("(email)","sys:unique"),
  89. "htmlemail" => array("tinyint default 0","Send this user HTML emails"),
  90. "subscribepage" => array("integer","sys:Which page was used to subscribe"),
  91. "rssfrequency" => array("varchar(100)","rss Frequency"), // Leftover from the preplugin era
  92. "password" => array("varchar(255)","Password"),
  93. "passwordchanged" => array("datetime","sys:Last time password was changed"),
  94. "disabled" => array("tinyint default 0","Is this account disabled?"),
  95. "extradata" => array("text","Additional data"),
  96. */
  97. // insert into user db
  98. $exists = Sql_Fetch_Row_Query(sprintf('select id from %s where email = "%s"',
  99. $GLOBALS['tables']['user'],$email));
  100. if ($exists[0]) return $exists[0];
  101. Sql_Query(sprintf('insert into %s set email = "%s",
  102. entered = now(),modified = now(),password = "%s",
  103. passwordchanged = now(),disabled = 0,
  104. uniqid = "%s",htmlemail = 1
  105. ',$GLOBALS['tables']['user'],$email,$password,getUniqid()));
  106. $ar = Sql_Affected_Rows();
  107. if ($ar > 0) {
  108. $id = Sql_Insert_Id();
  109. } else {
  110. $id = 0;
  111. }
  112. return $id;
  113. }
  114. function getAttributeIDbyName ($sName) {
  115. # Looks for an attribute named sName.
  116. # Returns table ID or 0 if not found.
  117. # Can also be used as 'isAttribute'
  118. if(empty($sName)) return 0;
  119. global $usertable_prefix;
  120. # workaround for integration webbler/phplist
  121. if (!isset($usertable_prefix)) {
  122. $usertable_prefix = '';
  123. }
  124. if ($tables["attribute"]) {
  125. $att_table = $tables["attribute"];
  126. $user_att_table = $tables["user_attribute"];
  127. } else {
  128. $att_table = "attribute";
  129. $user_att_table = "user_attribute";
  130. }
  131. $res = Sql_Query(sprintf('SELECT id FROM %s%s WHERE name = "%s"',
  132. $usertable_prefix,$att_table,$sName));
  133. $row = Sql_Fetch_row($res);
  134. return $row[0];
  135. }
  136. function AttributeValue($table,$value) {
  137. global $table_prefix;
  138. # workaround for integration webbler/phplist
  139. if (!isset($table_prefix)) {
  140. $table_prefix = "phplist_";
  141. }
  142. if (ereg(",",$value)) {
  143. $result = "";
  144. $res = Sql_Query(sprintf('select name from %slistattr_%s where id in (%s)',
  145. $table_prefix,$table,$value));
  146. while ($row = Sql_Fetch_row($res)) {
  147. $result .= $row[0]."; ";
  148. }
  149. return substr($result,0,-2);
  150. } elseif ($value) {
  151. $res = Sql_Query(sprintf('select name from %slistattr_%s where id = %d',
  152. $table_prefix,$table,$value));
  153. $row = Sql_Fetch_row($res);
  154. } else {
  155. # return "Invalid Attribute Index";
  156. }
  157. return $row[0];
  158. }
  159. function existUserID($id = 0) {
  160. global $table_prefix,$tables;
  161. # workaround for integration webbler/phplist
  162. if (!isset($table_prefix))
  163. $table_prefix = "phplist_";
  164. if (isset($tables["attribute"])) {
  165. $usertable = $tables["user"];
  166. } else {
  167. $usertable = "user";
  168. }
  169. $userid = Sql_Fetch_Row_Query("select id from {$usertable} where id = \"$id\"");
  170. return $userid[0];
  171. }
  172. function getUserAttributeValues($email = '', $id = 0, $bIndexWithShortnames = false) {
  173. global $table_prefix,$tables;
  174. if (!$email && !$id) return;
  175. # workaround for integration webbler/phplist
  176. if (!isset($table_prefix))
  177. $table_prefix = "phplist_";
  178. if (isset($tables["attribute"])) {
  179. $att_table = $tables["attribute"];
  180. $user_att_table = $tables["user_attribute"];
  181. $usertable = $tables["user"];
  182. } else {
  183. $att_table = "attribute";
  184. $user_att_table = "user_attribute";
  185. $usertable = "user";
  186. }
  187. $result = array();
  188. if ($email && !$id) {
  189. $userid = Sql_Fetch_Row_Query("select id from {$usertable} where email = \"$email\"");
  190. $id = $userid[0];
  191. }
  192. if (!$id) return;
  193. $att_req = Sql_Query(sprintf('select
  194. %s.name,%s.id from %s,%s
  195. where %s.userid = %s and %s.id = %s.attributeid',
  196. $att_table,
  197. $att_table,
  198. $user_att_table,
  199. $att_table,
  200. $user_att_table,
  201. $id,
  202. $att_table,
  203. $user_att_table
  204. ));
  205. while ($att = Sql_fetch_array($att_req)) {
  206. if ( $bIndexWithShortnames ) {
  207. $result['attribute' . $att['id']] = UserAttributeValue($id,$att["id"]);
  208. } else {
  209. $result[$att['name']] = UserAttributeValue($id,$att["id"]);
  210. }
  211. }
  212. return $result;
  213. }
  214. function UserAttributeValue($user = 0,$attribute = 0) {
  215. # workaround for integration webbler/phplist
  216. global $table_prefix,$tables;
  217. if (!isset($table_prefix))
  218. $table_prefix = "phplist_";
  219. if (!$user || !$attribute) return;
  220. if (isset($tables["attribute"])) {
  221. $att_table = $tables["attribute"];
  222. $user_att_table = $tables["user_attribute"];
  223. } else {
  224. $att_table = "attribute";
  225. $user_att_table = "user_attribute";
  226. }
  227. $att = Sql_Fetch_array_Query("select * from $att_table where id = $attribute");
  228. switch ($att["type"]) {
  229. case "checkboxgroup":
  230. # print "select value from $user_att_table where userid = $user and attributeid = $attribute";
  231. $val_ids = Sql_Fetch_Row_Query("select value from $user_att_table where userid = $user and attributeid = $attribute");
  232. if ($val_ids[0]) {
  233. # print '<br/>1 <b>'.$val_ids[0].'</b>';
  234. if (function_exists('cleancommalist')) {
  235. $val_ids[0] = cleanCommaList($val_ids[0]);
  236. }
  237. ## make sure the val_ids as numbers
  238. $values = explode(',',$val_ids[0]);
  239. $ids = array();
  240. foreach ($values as $valueIndex) {
  241. $iValue = sprintf('%d',$valueIndex);
  242. if ($iValue) {
  243. $ids[] = $iValue;
  244. }
  245. }
  246. if (!sizeof($ids)) return '';
  247. $val_ids[0] = join(',',$ids);
  248. # print '<br/>2 <b>'.$val_ids[0].'</b>';
  249. $value = '';
  250. $res = Sql_Query("select $table_prefix"."listattr_".$att["tablename"].".name
  251. from $user_att_table,$table_prefix"."listattr_".$att["tablename"]."
  252. where $user_att_table".".userid = ".$user." and
  253. $table_prefix"."listattr_".$att["tablename"].".id in ($val_ids[0]) and
  254. $user_att_table".".attributeid = ".$attribute);
  255. while ($row = Sql_Fetch_row($res)) {
  256. $value .= $row[0]."; ";
  257. }
  258. $value = substr($value,0,-2);
  259. } else {
  260. $value = "";
  261. }
  262. break;
  263. case "select":
  264. case "radio":
  265. $res = Sql_Query("select $table_prefix"."listattr_".$att["tablename"].".name
  266. from $user_att_table,$table_prefix"."listattr_".$att["tablename"]."
  267. where $user_att_table".".userid = ".$user." and
  268. $table_prefix"."listattr_".$att["tablename"].".id = $user_att_table".".value and
  269. $user_att_table".".attributeid = ".$attribute);
  270. $row = Sql_Fetch_row($res);
  271. $value = $row[0];
  272. break;
  273. default:
  274. $res = Sql_Query(sprintf('select value from %s where
  275. userid = %d and attributeid = %d',$user_att_table,$user,$attribute));
  276. $row = Sql_Fetch_row($res);
  277. $value = $row[0];
  278. }
  279. return stripslashes($value);
  280. }
  281. function userName() {
  282. global $config;
  283. if (!is_array($config["nameattributes"])) return "";
  284. $res = "";
  285. foreach ($config["nameattributes"] as $att) {
  286. if (isset($_SESSION["userdata"][$att]["displayvalue"])) {
  287. $res .= $_SESSION["userdata"][$att]["displayvalue"].' ';
  288. }
  289. }
  290. return rtrim($res);
  291. }
  292. function isBlackListed($email = "") {
  293. if (!$email) return 0;
  294. if (!Sql_Table_exists($GLOBALS["tables"]["user_blacklist"])) return 0;
  295. $gracetime = sprintf('%d',$GLOBALS["blacklist_gracetime"]);
  296. if (!$gracetime || $gracetime > 15 || $gracetime < 0) {
  297. $gracetime = 5;
  298. }
  299. # allow 5 minutes to send the last message acknowledging unsubscription
  300. $req = Sql_Query(sprintf('select * from %s where email = "%s" and date_add(added,interval %d minute) < now()',
  301. $GLOBALS["tables"]["user_blacklist"],sql_escape($email),$gracetime));
  302. return Sql_Affected_Rows();
  303. }
  304. function isBlackListedID($userid = 0) {
  305. if (!$userid) return 0;
  306. $email = Sql_Fetch_Row_Query("select email from {$GLOBALS["tables"]["user"]} where id = $userid");
  307. return isBlackListed($email[0]);
  308. }
  309. function unBlackList($userid = 0) {
  310. if (!$userid) return;
  311. $email = Sql_Fetch_Row_Query("select email from {$GLOBALS["tables"]["user"]} where id = $userid");
  312. Sql_Query(sprintf('delete from %s where email = "%s"',
  313. $GLOBALS["tables"]["user_blacklist"],$email[0]));
  314. Sql_Query(sprintf('delete from %s where email = "%s"',
  315. $GLOBALS["tables"]["user_blacklist_data"],$email[0]));
  316. Sql_Query(sprintf('update %s set blacklisted = 0 where id = %d',$GLOBALS["tables"]["user"],$userid));
  317. if (isset($_SESSION["logindetails"]["adminname"])) {
  318. $msg = "Removed from blacklist by ".$_SESSION["logindetails"]["adminname"];
  319. addUserHistory($email[0],$msg,"");
  320. }
  321. }
  322. function addUserToBlackList($email,$reason = '') {
  323. Sql_Query(sprintf('update %s set blacklisted = 1 where email = "%s"',
  324. $GLOBALS['tables']["user"],addslashes($email)));
  325. #0012262: blacklist only email when email bounces. (not users): Function split so email can be blacklisted without blacklisting user
  326. addEmailToBlackList($email,$reason);
  327. }
  328. function addEmailToBlackList($email,$reason = '') {
  329. #0012262: blacklist only email when email bounces. (not users): Function split so email can be blacklisted without blacklisting user
  330. Sql_Query(sprintf('insert ignore into %s (email,added) values("%s",now())',
  331. $GLOBALS['tables']["user_blacklist"],addslashes($email)));
  332. # save the reason, and other data
  333. Sql_Query(sprintf('insert ignore into %s (email,name,data) values("%s","%s","%s")',
  334. $GLOBALS['tables']["user_blacklist_data"],addslashes($email),
  335. "reason",addslashes($reason)));
  336. foreach (array("REMOTE_ADDR") as $item ) { # @@@do we want to know more?
  337. if (isset($_SERVER[$item])) {
  338. Sql_Query(sprintf('insert ignore into %s (email,name,data) values("%s","%s","%s")',
  339. $GLOBALS['tables']["user_blacklist_data"],addslashes($email),
  340. $item,addslashes($_SERVER[$item])));
  341. }
  342. }
  343. ## call plugins to tell them
  344. if (isset($GLOBALS['plugins']) && is_array($GLOBALS['plugins'])) {
  345. foreach ($GLOBALS['plugins'] as $pluginname => $plugin) {
  346. if (method_exists($plugin, "blacklistEmail")) {
  347. $plugin->blacklistEmail($email);
  348. }
  349. }
  350. }
  351. }
  352. function UserAttributeValueSelect($user = 0,$attribute = 0) {
  353. # if (!$user || !$attribute) return;
  354. global $table_prefix,$tables;
  355. # workaround for integration webbler/phplist
  356. if (!isset($table_prefix))
  357. $table_prefix = "phplist_";
  358. if ($tables["attribute"]) {
  359. $att_table = $tables["attribute"];
  360. $user_att_table = $tables["user_attribute"];
  361. } else {
  362. $att_table = "attribute";
  363. $user_att_table = "user_attribute";
  364. }
  365. if (!Sql_Table_exists($att_table)) {
  366. return "broken attribute $attribute";
  367. }
  368. $att = Sql_Fetch_array_Query("select * from $att_table where id = $attribute");
  369. # $value = UserAttributeValue($att["tablename"],$attribute);
  370. $value = UserAttributeValue($user,$attribute);
  371. # $html = 'Value: '.$value;
  372. $html = sprintf('<select name="attribute[%d]" style="attributeinput" >',$attribute);
  373. $res = Sql_Query("select id,name from $table_prefix"."listattr_".$att["tablename"]." order by name");
  374. if (!Sql_Affected_Rows())
  375. return "(No values available)";
  376. $html .= '<option value="0">-- no value</option>';
  377. while ($row = Sql_Fetch_Row($res))
  378. if ($row[1] != '')
  379. $html .= sprintf('<option value="%d" %s>%s </option>',$row[0],$row[1] == $value?'selected="selected"':"",$row[1]);
  380. return $html . '</select>';
  381. }
  382. function UserAttributeValueCbGroup($user = 0,$attribute = 0) {
  383. # if (!$user || !$attribute) return;
  384. global $table_prefix,$tables;
  385. if ($tables["attribute"]) {
  386. $att_table = $tables["attribute"];
  387. $user_att_table = $tables["user_attribute"];
  388. } else {
  389. $att_table = "attribute";
  390. $user_att_table = "user_attribute";
  391. }
  392. # workaround for integration webbler/phplist
  393. if (!isset($table_prefix))
  394. $table_prefix = "phplist_";
  395. $att = Sql_Fetch_array_Query("select * from $att_table where id = $attribute");
  396. $values_req = Sql_Fetch_Row_Query("select value from $user_att_table where userid = $user and attributeid = $attribute");
  397. $values = explode(",",$values_req[0]);
  398. $html = sprintf('<input type="hidden" name="cbgroup[]" value="%d" /><table>',$attribute);
  399. # $html = sprintf('<select name="attribute[%d]" style="attributeinput" >',$attribute);
  400. $res = Sql_Query("select id,name from $table_prefix"."listattr_".$att["tablename"]." order by listorder,name");
  401. if (!Sql_Affected_Rows())
  402. return "(No values available)";
  403. while ($row = Sql_Fetch_Row($res))
  404. $html .= sprintf('<tr><td><input type="checkbox" name="cbgroup%d[]" value="%d" %s /></td><td>%s</td></tr>',
  405. $attribute,$row[0],in_array($row[0],$values)?"checked":"",$row[1]);
  406. return $html . '</table>';
  407. }
  408. function userGroups($loginname) {
  409. $result = array();
  410. if (Sql_Table_exists("user_group")) {
  411. $req = Sql_Query(sprintf('select groupid from user_group,user where user_group.userid = user.id and user.email = "%s"',addslashes($loginname)));
  412. while ($row = Sql_Fetch_Row($req)) {
  413. array_push($result,$row[0]);
  414. }
  415. $ev = getEveryoneGroupID();
  416. array_push($result,$ev);
  417. }
  418. return $result;
  419. }
  420. function is_email($email) {
  421. #@@ dont_require_validemail should be replaced by EMAIL_ADDRESS_VALIDATION_LEVEL
  422. if (isset($GLOBALS['config']) && isset($GLOBALS["config"]["dont_require_validemail"]) && $GLOBALS["config"]["dont_require_validemail"])
  423. return 1;
  424. $email = trim($email);
  425. switch (EMAIL_ADDRESS_VALIDATION_LEVEL) {
  426. case 0: # No email address validation.
  427. return 1;
  428. break;
  429. case 2: # RFC821 email validation without escaping and quoting of local part
  430. case 3: # RFC821 email validation.
  431. # $email is a valid address as defined by RFC821
  432. # Except:
  433. # Length of domainPart is not checked
  434. # Not accepted are CR and LF even if escaped by \
  435. # Not accepted is Folding
  436. # Not accepted is literal domain-part (eg. [1.0.0.127])
  437. # Not accepted is comments (eg. (this is a comment)@example.com)
  438. # Extra:
  439. # topLevelDomain can only be one of the defined ones
  440. $escapedChar = "\\\\[\\x01-\\x09\\x0B-\\x0C\\x0E-\\x7F]"; # CR and LF excluded for safety reasons
  441. $unescapedChar = "[a-zA-Z0-9!#$%&'*\+\-\/=?^_`{|}~]";
  442. if(EMAIL_ADDRESS_VALIDATION_LEVEL == 2) {
  443. $char = "$unescapedChar";
  444. } else {
  445. $char = "($unescapedChar|$escapedChar)";
  446. };
  447. $dotString = "$char((\.)?$char){0,63}";
  448. $qtext = "[\\x01-\\x09\\x0B-\\x0C\\x0E-\\x21\\x23-\\x5B\\x5D-\\x7F]"; # All but <LF> x0A, <CR> x0D, quote (") x22 and backslash (\) x5c
  449. $qchar = "$qtext|$escapedChar";
  450. $quotedString = "\"($qchar){1,62}\"";
  451. if(EMAIL_ADDRESS_VALIDATION_LEVEL == 2) {
  452. $localPart = "$dotString"; # without escaping and quoting of local part
  453. } else {
  454. $localPart = "($dotString|$quotedString)";
  455. };
  456. $topLevelDomain = "(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|asia|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|cat|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|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|home|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|jm|je|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|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|tel|tf|tg|th|tj|tk|tm|tn|to|tp|tr|travel|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)";
  457. $domainLiteral = "((([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]))";
  458. $domainPart = "([a-zA-Z0-9](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)*\.$topLevelDomain|$domainLiteral)";
  459. $validEmailPattern = "/^$localPart@$domainPart$/i"; # result: /^(([a-zA-Z0-9!#$%&'*\+\-\/=?^_`{|}~]|\\[\x01-\x09\x0B-\x0C\x0E-\x7F])((\.)?([a-zA-Z0-9!#$%&'*\+\-\/=?^_`{|}~]|\\[\x01-\x09\x0B-\x0C\x0E-\x7F])){0,63}|"([\x01-\x09\x0B-\x0C\x0E-\x21\x23-\x5B\x5D-\x7F]|\\[\x01-\x09\x0B-\x0C\x0E-\x7F]){1,62}")@([a-zA-Z0-9](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)*\.(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|cat|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|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|home|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|jm|je|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])))$/i
  460. if(preg_match($validEmailPattern, $email)) {
  461. return(1);
  462. } else {
  463. return(0);
  464. }
  465. break;
  466. default: # 10.4 style email validation
  467. # quite often emails have two @ signs
  468. $ats = substr_count($email,'@');
  469. if ($ats != 1) return 0;
  470. # hmm, it seems people are starting to have emails with & and ' or ` chars in the name
  471. #'
  472. $pattern =
  473. "/^[\&\'-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|asia|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|cat|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|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|home|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|jm|je|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|tel|tf|tg|th|tj|tk|tm|tn|to|tp|tr|travel|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]))$/i";
  474. if(preg_match($pattern, $email)) {
  475. return 1;
  476. } else {
  477. return 0;
  478. }
  479. break;
  480. }
  481. }
  482. function addUserHistory($email,$msg,$detail) {
  483. global $table_prefix,$tables;
  484. if (isset($tables["user"])) {
  485. $user_table = $tables["user"];
  486. } else {
  487. $user_table = "user";
  488. }
  489. if (isset($tables["user_history"])) {
  490. $user_his_table = $tables["user_history"];
  491. } else {
  492. $user_his_table = "user_history";
  493. }
  494. $sysinfo = "";
  495. $sysarrays = array_merge($_ENV,$_SERVER);
  496. if ( isset($GLOBALS["userhistory_systeminfo"]) && is_array($GLOBALS["userhistory_systeminfo"]) ) {
  497. foreach ($GLOBALS["userhistory_systeminfo"] as $key) {
  498. if (isset($sysarrays[$key])) {
  499. $sysinfo .= "\n$key = $sysarrays[$key]";
  500. }
  501. }
  502. } elseif ( isset($GLOBALS["config"]["userhistory_systeminfo"]) && is_array($GLOBALS["config"]["userhistory_systeminfo"])) {
  503. foreach ($GLOBALS["config"]["userhistory_systeminfo"] as $key) {
  504. if ($sysarrays[$key]) {
  505. $sysinfo .= "\n$key = $sysarrays[$key]";
  506. }
  507. }
  508. } else {
  509. $default = array('HTTP_USER_AGENT','HTTP_REFERER','REMOTE_ADDR','REQUEST_URI');
  510. foreach ($sysarrays as $key => $val) {
  511. if (in_array($key,$default))
  512. $sysinfo .= "\n".strip_tags($key) . ' = '.htmlspecialchars($val);
  513. }
  514. }
  515. $userid = Sql_Fetch_Row_Query("select id from $user_table where email = \"$email\"");
  516. if ($userid[0]) {
  517. if (isset($_SERVER["REMOTE_ADDR"])) {
  518. $ip = $_SERVER["REMOTE_ADDR"];
  519. } else {
  520. $ip = '';
  521. }
  522. Sql_Query(sprintf('insert into %s (ip,userid,date,summary,detail,systeminfo)
  523. values("%s",%d,now(),"%s","%s","%s")',$user_his_table,$ip,$userid[0],addslashes($msg),addslashes(htmlspecialchars($detail)),$sysinfo));
  524. }
  525. }
  526. function validateEmail($email) {
  527. if ( !empty($GLOBALS["config"]["dont_require_validemail"]) )
  528. return 1;
  529. if (!isset($GLOBALS["check_for_host"])) {
  530. $GLOBALS["check_for_host"] = 0;
  531. }
  532. if (!empty($email) && $GLOBALS["check_for_host"]) {
  533. list($username,$domaincheck) = explode('@',$email);
  534. # checking for an MX is not sufficient
  535. # $mxhosts = array();
  536. # $validhost = getmxrr ($domaincheck,$mxhosts);
  537. $validhost = checkdnsrr($domaincheck, "MX") || checkdnsrr($domaincheck, "A");
  538. } else {
  539. $validhost = 1;
  540. }
  541. return $validhost && is_email($email);
  542. }
  543. function validMod10($no) {
  544. $dups = array();
  545. $rev = strrev($no);
  546. for ($i=0;$i<strlen($rev);$i++) {
  547. if ($i % 2 == 1) {
  548. array_push($dups,substr($rev,$i,1) * 2);
  549. } else {
  550. array_push($dups,substr($rev,$i,1));
  551. }
  552. }
  553. $total = 0;
  554. foreach ($dups as $dig) {
  555. for ($i=0;$i<strlen($dig);$i++) {
  556. $total += substr($dig,$i,1);
  557. }
  558. # print "$dig - $total<br/>";
  559. }
  560. return ($total % 10 == 0);
  561. # print "$no";
  562. }
  563. function validateCC($ccno) {
  564. # credit card validation routines here
  565. # major credit cards that you might want to validate.
  566. #CARD TYPE Prefix Length Check digit algorithm
  567. #MASTERCARD 51-55 16 mod 10
  568. #VISA 4 13,16 mod 10
  569. #AMEX 34,37 15 mod 10
  570. #Diners Club/Carte Blanche 300-305,36,38 14 mod 10
  571. #Discover 6011 16 mod 10
  572. #enRoute 2014,2149 15 any
  573. #JCB 3 16 mod 10
  574. #JCB 2131,1800 15 mod 10
  575. $ccno = preg_replace("/\D/","",$ccno);
  576. $length = strlen($ccno);
  577. $firsttwo = substr($ccno,0,2);
  578. $firstthree = substr($ccno,0,3);
  579. $first = substr($ccno,0,1);
  580. $firstfour = substr($ccno,0,4);
  581. if ($firsttwo >= 51 && $firsttwo <= 55) # Mastercard
  582. return $length == 16 && validMod10($ccno);
  583. elseif ($first == 4) # visa
  584. return ($length == 13 || $length == 16) && validMod10($ccno);
  585. elseif ($firsttwo == 34 || $firsttwo == 37) # Amex
  586. return $length == 15 && validMod10($ccno);
  587. elseif (($firstthree >= 300 && $firstthree <= 305) # Diners1
  588. || ($firsttwo == 36 || $firsttwo == 38)) # Diners2
  589. return $length == 14 && validMod10($ccno);
  590. elseif ($firstfour == 6011) # discover
  591. return $length == 16 && validMod10($ccno);
  592. elseif ($firstfour == 2014 || $firstfour == 2149) # enRoute
  593. return $length == 15;
  594. else
  595. # if it is not any of the above, we do not know how to validate it
  596. # reject 4 and 15 1s anyway
  597. if ($ccno == "4111111111111111") {
  598. return 0;
  599. }
  600. return 1;
  601. }
  602. function loadCCvalidationFile($ccrangefile) {
  603. if (!is_file($ccrangefile))
  604. return array();
  605. $range = array();
  606. $fp = fopen($ccrangefile,"rb");
  607. $contents = fread($fp,filesize($ccrangefile));
  608. fclose($fp);
  609. $lines = explode("\n",$contents);
  610. foreach ($lines as $line) {
  611. if (!preg_match("/^\s*#/",$line) && !preg_match("/^\s+$/",$line)) {
  612. if (preg_match("#(\d+),(\d+),(\d+)#",$line,$regs)) {
  613. # print "RANGE".$line."<br/>";
  614. array_push($range,array(
  615. "start" => substr($regs[1],0,6),
  616. "end" => substr($regs[2],0,6),
  617. "company" => sprintf('%02d',$regs[3])
  618. ));
  619. # dbg($regs[1]. " ". $regs[2]. " -> ".$regs[3]);
  620. } elseif (preg_match("#\((\d+)\)\s*=\s*'(.*)'#",$line,$regs)) {
  621. # print "COMPANY".$line."<br/>";
  622. $company[sprintf('%02d',$regs[1])] = $regs[2];
  623. # dbg($regs[1]. " = " . $regs[2]);
  624. }
  625. }
  626. }
  627. return array($range,$company);
  628. }
  629. function ccCompany($ccno) {
  630. global $config;
  631. $ccrangefile = $config["code_root"]."/".$config["uploader_dir"]."/codelib/ccvalidation.txt";
  632. list($ranges,$companies) = loadCCvalidationFile($ccrangefile);
  633. $first6 = substr($ccno,0,6);
  634. if (is_array($ranges))
  635. foreach ($ranges as $range) {
  636. # dbg($range["start"]);
  637. # print "CHECKING ".$range["start"].' TO '.$range["end"].'<br/>';
  638. if ($range["start"] <= $first6 && $range["end"] >= $first6) {
  639. return array($range["company"],$companies[$range["company"]]);
  640. }
  641. }
  642. return -1;
  643. }
  644. function checkCCrange($ccno) {
  645. global $config;
  646. $ccrangefile = $config["code_root"]."/".$config["uploader_dir"]."/codelib/ccvalidation.txt";
  647. if (!is_file($ccrangefile) || !is_array($config["cc_accept_company"]))
  648. return 1;
  649. list($companyid,$companyname) = ccCompany($ccno);
  650. if ($companyid > 0 && in_array($companyid,$config["cc_accept_company"])) {
  651. # dbg($ccno . " is valid for company $companyid $companyname");
  652. return 1;
  653. } elseif ($companyid < 0) {
  654. return -1;
  655. } else {
  656. return 0;
  657. }
  658. }
  659. function validateCCExpiry($ccexpiry) {
  660. # expiry date validation here
  661. $mon = substr($ccexpiry,0,2);
  662. if (strlen($ccexpiry) == 5) {
  663. # I presume it is with a separator
  664. $year = substr($ccexpiry,3,2);
  665. } elseif (strlen($ccexpiry) == 4) {
  666. $year = substr($ccexpiry,2,2);
  667. } else {
  668. return 0;
  669. }
  670. $yeardiff = $year - date("y");
  671. return ($mon < 13 && $yeardiff < 9 && (($year > date("y")) || ($year == date("y") && $mon >= date("m"))));
  672. }
  673. function obscureCreditCard($cardno) {
  674. if (strlen($cardno) < 5)
  675. return $cardno;
  676. $res = substr($cardno,strlen($cardno)-4,4);
  677. for ($i=0;$i<strlen($cardno)-4;$i++) {
  678. $prefix .= '*';
  679. }
  680. $res = $prefix . $res;
  681. return $res;
  682. }
  683. function loadUser($loginname = "") {
  684. if (!Sql_Table_exists("user")) return;
  685. initialiseUserSession();
  686. if (!$loginname) {
  687. if ($_SESSION["userloggedin"] != "" && $_SESSION["username"] != "") {
  688. $loginname = $_SESSION["username"];
  689. } else {
  690. return "";
  691. }
  692. }
  693. $att_req = Sql_Query(sprintf('select attribute.id,
  694. %s.name,%s.type,
  695. %s.value,%s.tablename from %s,%s,%s
  696. where %s.userid = %s.id and %s.email = "%s" and %s.id = %s.attributeid',
  697. "attribute",
  698. "attribute",
  699. "user_attribute",
  700. "attribute",
  701. "user",
  702. "user_attribute",
  703. "attribute",
  704. "user_attribute",
  705. "user",
  706. "user",
  707. addslashes($loginname),
  708. "attribute",
  709. "user_attribute"
  710. ));
  711. while ($att = Sql_fetch_array($att_req)) {
  712. # if (!defined($_SESSION["userdata"]["attribute".$att["id"]])) {
  713. $_SESSION["userdata"]["attribute".$att["id"]] = array(
  714. "name" => $att["name"],
  715. "value" => $att["value"],
  716. "type" => $att["type"],
  717. "attid" => $att["id"],
  718. "displayvalue" => $att['value'],
  719. );
  720. switch ($att["type"]) {
  721. case "textline":
  722. case "hidden":
  723. $_SESSION["userdata"]["attribute".$att["id"]]["displayvalue"] =
  724. $att["value"];
  725. break;
  726. case "creditcardno":
  727. $_SESSION["userdata"]["attribute".$att["id"]]["displayvalue"] =
  728. obscureCreditCard($att["value"]);
  729. break;
  730. case "select":
  731. $_SESSION["userdata"]["attribute".$att["id"]]["displayvalue"] =
  732. AttributeValue($att["tablename"],$att["value"]);
  733. break;
  734. case "date":
  735. $_SESSION["userdata"]["attribute".$att["id"]]["displayvalue"] =
  736. formatDate($att["value"]);
  737. break;
  738. }
  739. # }
  740. }
  741. $d_req = Sql_Fetch_Array_Query("select * from user where email = \"$loginname\"");
  742. $_SESSION["userid"] = $d_req["id"];
  743. foreach (array("email","disabled","confirmed","htmlemail","uniqid",'password','foreignkey') as $field) {
  744. # if (!defined($_SESSION["userdata"][$field])) {
  745. $_SESSION["userdata"][$field] = array(
  746. "name" => $field,
  747. "value" => $d_req[$field],
  748. "type" => "static",
  749. "displayvalue" => $d_req[$field]
  750. );
  751. # }
  752. }
  753. $_SESSION["usergroups"] = userGroups($loginname);
  754. if (is_array($GLOBALS['config']['usergreeting'])) {
  755. $_SESSION['usergreeting'] = '';
  756. foreach ($GLOBALS['config']['usergreeting'] as $att) {
  757. $_SESSION['usergreeting'] .= $_SESSION["userdata"][$att]["displayvalue"].' ';
  758. }
  759. $_SESSION['usergreeting'] = rtrim($_SESSION['usergreeting']);
  760. }
  761. dbg("done loading user");
  762. return 1;
  763. }
  764. function addKeywordLibrary($name) {
  765. $req = Sql_Query(sprintf('select id from keywordlib where name = "%s"',$name));
  766. if (Sql_affected_Rows()) {
  767. $row = Sql_Fetch_Row($req);
  768. return $row[0];
  769. }
  770. Sql_Query(sprintf('insert into keywordlib (name) values("%s")',$name));
  771. return Sql_Insert_id();
  772. }
  773. function getNewAttributeTablename($name) {
  774. global $table_prefix,$tables;
  775. if ($tables["attribute"]) {
  776. $table = $tables["attribute"];
  777. } else {
  778. $table = "attribute";
  779. }
  780. $lc_name = substr(preg_replace("/\W/","", strtolower($name)),0,10);
  781. # if ($lc_name == "") Fatal_Error("Name cannot be empty: $lc_name");
  782. if (!$lc_name) $lc_name = "attribute";
  783. Sql_Query("select * from $table where tablename = \"$lc_name\"");
  784. # if (Sql_Affected_Rows()) Fatal_Error("Name is not unique enough");
  785. $c = 1;
  786. $basename = $lc_name;
  787. while (Sql_Affected_Rows() && $c < 100) {
  788. $lc_name = $basename.$c;
  789. Sql_Query("select * from $table where tablename = \"$lc_name\"");
  790. $c++;
  791. }
  792. return $lc_name;
  793. }
  794. function isGuestAccount() {
  795. if (!is_array($_SESSION["userdata"])) {
  796. return 1;
  797. }
  798. if ($GLOBALS["config"]["guestaccount_attribute"]) {
  799. return $_SESSION['userdata'][$GLOBALS["config"]["guestaccount_attribute"]]['value'];
  800. }
  801. if ($GLOBALS["config"]["guestaccount_email_match"]) {
  802. return preg_match($GLOBALS["config"]["guestaccount_email_match"],$_SESSION["userdata"]["email"]["value"]);
  803. }
  804. }
  805. function saveUserAttribute($userid,$attid,$data) {
  806. global $usertable_prefix, $table_prefix, $tables;
  807. # workaround for integration webbler/phplist
  808. if (!isset($usertable_prefix)) {
  809. $usertable_prefix = '';
  810. }
  811. if (!isset($table_prefix)) {
  812. $table_prefix = 'phplist_';
  813. }
  814. if (!empty($tables["attribute"])) {
  815. $att_table = $usertable_prefix .$tables["attribute"];
  816. $user_att_table = $usertable_prefix .$tables["user_attribute"];
  817. } else {
  818. $att_table = $usertable_prefix ."attribute";
  819. $user_att_table = $usertable_prefix . "user_attribute";
  820. }
  821. if (!is_array($data)) {
  822. $tmp = $data;
  823. $data = Sql_Fetch_Assoc_Query(sprintf('select * from %s where id = %d',$att_table,$attid));
  824. $data['value'] = $tmp;
  825. $data['displayvalue'] = $tmp;
  826. }
  827. # dbg($data,'$data to store for '.$userid.' '.$attid);
  828. if ($data["nodbsave"]) {
  829. # dbg($attid, "Not saving, nodbsave");
  830. return;
  831. }
  832. if ($attid == "emailcheck" || $attid == "passwordcheck") {
  833. # dbg($attid, "Not saving, emailcheck/passwordcheck");
  834. return;
  835. }
  836. if (!$data["type"])
  837. $data["type"] = "textline";
  838. if ($data["type"] == "static" || $data["type"] == "password" || $data['type'] == 'htmlpref') {
  839. Sql_Query(sprintf('update user set %s = "%s" where id = %d',
  840. $attid,$data["value"],$userid));
  841. dbg('Saving','',DBG_TRACE);
  842. if ($data["type"] == "password") {
  843. Sql_Query(sprintf('update user set passwordchanged = now(),password="%s" where id = %d',
  844. hash('sha256',$data['value']),$userid));
  845. }
  846. return 1;
  847. }
  848. $attributetype = $data['type'];
  849. $attid_req = Sql_Fetch_Row_Query(sprintf('
  850. select id,type,tablename from %s where id = %d', $att_table, $attid));
  851. if (!$attid_req[0]) {
  852. $attid_req = Sql_Fetch_Row_Query(sprintf('
  853. select id,type,tablename from %s where name = "%s"', $att_table, $data["name"]));
  854. if (!$attid_req[0]) {
  855. if (!empty($data["name"]) && $GLOBALS["config"]["autocreate_attributes"]) {
  856. # Dbg("Creating new Attribute: ".$data["name"]);
  857. sendError("creating new attribute ".$data["name"]);
  858. $atttable= getNewAttributeTablename($data["name"]);
  859. Sql_Query(sprintf('insert into %s (name,type,tablename) values("%s","%s","%s")', $att_table, $data["name"],$data["type"],$atttable));
  860. $attid = Sql_Insert_Id();
  861. } else {
  862. # dbg("Not creating new Attribute: ".$data["name"]);
  863. # sendError("Not creating new attribute ".$data["name"]);
  864. }
  865. } else {
  866. $attid = $attid_req[0];
  867. if (empty($attributetype)) {
  868. $attributetype = $attid_req[1];
  869. }
  870. $atttable = $attid_req[2];
  871. }
  872. } else {
  873. $attid = $attid_req[0];
  874. if (empty($attributetype)) {
  875. $attributetype = $attid_req[1];
  876. }
  877. $atttable = $attid_req[2];
  878. }
  879. if (!$atttable && !empty($data['name'])) {
  880. $atttable = getNewAttributeTablename($data["name"]);
  881. # fix attribute without tablename
  882. Sql_Query(sprintf('update %s set tablename ="%s" where id = %d',
  883. $att_table, $atttable,$attid));
  884. # sendError("Attribute without Tablename $attid");
  885. }
  886. switch ($attributetype) {
  887. case "static":
  888. case "password":
  889. # dbg('SAVING STATIC OR PASSWORD');
  890. if (!empty($GLOBALS['config']['dontsave_userpassword']) && $data['type'] == 'password') {
  891. $data["value"] = 'not authoritative';
  892. }
  893. Sql_Query(sprintf('update user set %s = "%s" where id = %d',
  894. $attid,$data["value"],$userid));
  895. break;
  896. case "select":
  897. $curval = Sql_Fetch_Row_Query(sprintf('select id from '.$table_prefix . 'listattr_%s
  898. where name = "%s"',$atttable,$data["displayvalue"]),1);
  899. if (!$curval[0] && $data['displayvalue'] && $data['displayvalue'] != '') {
  900. Sql_Query(sprintf('insert into '.$table_prefix . 'listattr_%s (name) values("%s")',$atttable,
  901. $data["displayvalue"]));
  902. sendError("Added ".$data["displayvalue"]." to $atttable");
  903. $valid = Sql_Insert_id();
  904. } else {
  905. $valid = $curval[0];
  906. }
  907. Sql_Query(sprintf('replace into %s (userid,attributeid,value)
  908. values(%d,%d,"%s")', $user_att_table, $userid,$attid,$valid));
  909. break;
  910. default:
  911. Sql_Query(sprintf('replace into %s (userid,attributeid,value)
  912. values(%d,%d,"%s")', $user_att_table, $userid,$attid,$data["value"]));
  913. break;
  914. }
  915. return 1;
  916. }
  917. function saveUserByID($userid,$data) {
  918. while (list($key,$val) = each($data)) {
  919. if (preg_match("/^attribute(\d+)/",$key,$regs)) {
  920. $attid = $regs[1];
  921. } else {
  922. $attid = $key;
  923. }
  924. dbg("Saving attribute $key, $attid, $val for $userid");
  925. if ($userid && $attid && $data[$key]["type"] != "userfield" && !$data[$key]["nodbsave"])
  926. saveUserAttribute($userid,$attid,$val);
  927. }
  928. }
  929. function saveUser($loginname,$data) {
  930. # saves user to database
  931. $id_req = Sql_Fetch_Row_Query("select id from user where email = \"$loginname\"");
  932. if ($id_req[0]) {
  933. $userid = $id_req[0];
  934. while (list($key,$val) = each($data)) {
  935. if (ereg("^attribute(\d+)",$key,$regs)) {
  936. $attid = $regs[1];
  937. }
  938. # dbg("Saving attribute $key, $attid, $val for $loginname, $userid");
  939. if ($userid && $attid)
  940. saveUserAttribute($userid,$key,$val);
  941. }
  942. }
  943. return 1;
  944. }
  945. function saveUserData($username,$fields) {
  946. # saves data in session, not in database
  947. if (!is_array($_SESSION["userdata"])) {
  948. initialiseUserSession();
  949. }
  950. if (!$username) {
  951. $username = 'Unknown User';
  952. }
  953. dbg("Saving user in session $username",'',DBG_TRACE);
  954. $res = "";
  955. $required_fields = explode(",",$_POST["required"]);
  956. if ($_POST["unrequire"]) {
  957. $unrequired_fields = explode(",",$_POST["unrequire"]);
  958. $required_fields = array_diff($required_fields,$unrequired_fields);
  959. } else {
  960. $unrequired_fields = array();
  961. }
  962. $required_formats = explode(",",$_POST["required_formats"]);
  963. $description_fields = explode(",",$_POST["required_description"]);
  964. reset($fields);
  965. # dbg("Checking fields");
  966. foreach ($fields as $fname => $fielddetails) {
  967. dbg('Saving user Saving '.$fname.' to session '.$_POST[$fname]);
  968. # dbg($fielddetails);
  969. $key = $fname;
  970. $val = $_POST[$fname];
  971. if (!ereg("required",$key) && $key != "unrequire" &&
  972. $fields[$key]["type"] != "separator" &&
  973. $fields[$key]["type"] != "emailcheck" &&
  974. $fields[$key]["type"] != "passwordcheck"
  975. ) {
  976. # dbg($fname ." of type ".$fields[$key]["type"]);
  977. if (!is_array($_SESSION["userdata"][$key]))
  978. $_SESSION["userdata"][$key] = array();
  979. $_SESSION["userdata"][$key]["name"] = $fields[$key]["name"];
  980. $_SESSION["userdata"][$key]["type"] = $fields[$key]["type"];
  981. if ($fields[$key]["type"] == "date") {
  982. $_SESSION["userdata"][$key]["value"] = sprintf('%04d-%02d-%02d',
  983. $_POST['year'][$key],$_POST['month'][$key],$_POST['day'][$key]);
  984. $_SESSION["userdata"][$key]["displayvalue"] = $_SESSION["userdata"][$key]["value"];
  985. } elseif ($fields[$key]["type"] == "creditcardno") {
  986. # dont overwrite known CC with ***
  987. if (!preg_match("#^\*+#",$val)) {
  988. $_SESSION["userdata"][$key]["value"] = ltrim($val);
  989. }
  990. } else {
  991. $_SESSION["userdata"][$key]["value"] = ltrim($val);
  992. }
  993. if ($fields[$key]["type"] == "select") {
  994. if (!empty($val) && is_array($fields[$key]["values"])) {
  995. $_SESSION["userdata"][$key]["displayvalue"] = $fields[$key]["values"][$val];
  996. }
  997. } elseif ($fields[$key]["type"] == "checkboxgroup") {
  998. if (is_array($val)) { // if val is empty join crashes
  999. $_SESSION["userdata"][$key]["value"] = join(",",$val);
  1000. }
  1001. } elseif ($fields[$key]["type"] == "creditcardno") {
  1002. # erase any non digits from the CC numbers
  1003. $_SESSION["userdata"][$key]["value"] = preg_replace("/\D/","",$_SESSION["userdata"][$key]["value"]);
  1004. $_SESSION["userdata"][$key]["displayvalue"] = obscureCreditCard($_SESSION["userdata"][$key]["value"]);
  1005. } elseif ($fields[$key]["name"] == "Card Number") {
  1006. $_SESSION["userdata"][$key]["value"] = preg_replace("/\D/","",$_SESSION["userdata"][$key]["value"]);
  1007. $_SESSION["userdata"][$key]["displayvalue"] = obscureCreditCard($_SESSION["userdata"][$key]["value"]);
  1008. /* $_SESSION["userdata"][$key]["displayvalue"] = substr($_SESSION["userdata"][$key]["displayvalue"],0,4);
  1009. for ($i=0;$i<strlen($_SESSION["userdata"][$key]["value"]-4);$i++) {
  1010. $_SESSION["userdata"][$key]["displayvalue"] .= '*';
  1011. }
  1012. */
  1013. } else {
  1014. $_SESSION["userdata"][$key]["displayvalue"] = $val;
  1015. }
  1016. foreach ($fielddetails as $field_attr => $field_attr_value) {
  1017. if (!isset($_SESSION["userdata"][$key][$field_attr]) && !preg_match("/^\d+$/",$key)
  1018. && !preg_match("/^\d+$/",$field_attr)
  1019. ) {
  1020. $_SESSION["userdata"][$key][$field_attr] = $field_attr_value;
  1021. }
  1022. }
  1023. # save it to the DB as well
  1024. } else {
  1025. # dbg("Not checking ".$fname ." of type ".$fields[$key]["type"]);
  1026. }
  1027. }
  1028. # fix UK postcodes to correct format
  1029. if ($_SESSION["userdata"][$GLOBALS["config"]["country_attribute"]]["displayvalue"] == "United Kingdom" && isset($_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"])) {
  1030. $postcode = $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"];
  1031. $postcode = strtoupper(str_replace(" ","",$postcode));
  1032. if (preg_match("/(.*)(\d\w\w)$/",$postcode,$regs)) {
  1033. $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"] = trim($regs[1])." ".$regs[2];
  1034. $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["displayvalue"] = trim($regs[1])." ".$regs[2];
  1035. }
  1036. }
  1037. dbg("Checking required fields");
  1038. reset($required_fields);
  1039. while (list($index,$field) = each ($required_fields)) {
  1040. $type = $fields[$field]["type"];
  1041. # dbg("$field of type $type");
  1042. if ($type != 'userfield' && $type != '') ### @@@ need to check why type is not set
  1043. if ($field && !$_SESSION["userdata"][$field]["value"]) {
  1044. $res = "Information missing: ".$description_fields[$index];
  1045. break;
  1046. } else if ($required_formats[$index] && !preg_match(stripslashes($required_formats[$index]),$_SESSION["userdata"][$field]["value"])) {
  1047. $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
  1048. break;
  1049. } else if ($field == "email" && !validateEmail($_SESSION["userdata"][$field]["value"])) {
  1050. $res = "Sorry, the following field cannot be validated: ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
  1051. break;
  1052. } elseif ($field == "emailcheck" && $_SESSION["userdata"]["email"]["value"] != $_SESSION["userdata"]["emailcheck"]["value"]) {
  1053. $res = "Emails entered are not the same";
  1054. break;
  1055. } else if ($field == "cardtype" && $_SESSION["userdata"][$field]["value"] == "WSWITCH" && !preg_match("/\d/",$_SESSION["userdata"]["attribute82"]["value"])) {
  1056. $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.";
  1057. break;
  1058. } else if ($field == "cardtype" && isset($_SESSION["userdata"][$field]["value"]) && $_SESSION["userdata"][$field]["value"] != "WSWITCH" && $_SESSION["userdata"]["attribute82"]["value"]) {
  1059. $res = "Sorry, an issue number is not valid when not using a Switch Card";
  1060. break;
  1061. } else if (($type == "creditcardno" || $field == "cardnumber") && isset($_SESSION["userdata"][$field]["value"]) && !checkCCrange($_SESSION["userdata"][$field]["value"])) {
  1062. list($cid,$cname) = ccCompany($_SESSION["userdata"][$field]["value"]);
  1063. if (!$cname)
  1064. $cname = '(Unknown Credit card)';
  1065. $res = "Sorry, we currently don't accept $cname cards";
  1066. break;
  1067. } else if (($type == "creditcardno" || $field == "cardnumber") && isset($_SESSION["userdata"][$field]["value"]) && !validateCC($_SESSION["userdata"][$field]["value"])) {
  1068. $res = "Sorry, you entered an invalid ".$description_fields[$index];#.": ".$_SESSION["userdata"][$field]["value"];
  1069. break;
  1070. } else if (($type == "creditcardexpiry" ||$field == "cardexpiry") && isset($_SESSION["userdata"][$field]["value"]) && !validateCCExpiry($_SESSION["userdata"][$field]["value"])) {
  1071. $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
  1072. break;
  1073. }
  1074. }
  1075. if (0 && isset($_SESSION["userdata"][$GLOBALS["config"]["country_attribute"]]["displayvalue"]) && $_SESSION["userdata"][$GLOBALS["config"]["country_attribute"]]["displayvalue"] == "United Kingdom" && isset($_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"])) {
  1076. $postcode = $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["displayvalue"];
  1077. if (!preg_match("/(.*)(\d\w\w)$/",$postcode,$regs)) {
  1078. $res = "That does not seem to be a valid UK postcode";
  1079. } elseif (!preg_match("/^[\s\w\d]+$/",$postcode,$regs)) {
  1080. $res = "That does not seem to be a valid UK postcode";
  1081. }
  1082. }
  1083. /* if (is_array($GLOBALS["config"]["bocs_dpa"])) {
  1084. if (!is_array($_SESSION["DPA"]))
  1085. $_SESSION["DPA"] = array();
  1086. foreach ($GLOBALS["config"]["bocs_dpa"] as $dpaatt => $val) {
  1087. if ($_SESSION["userdata"][$dpaatt]["displayvalue"]) {
  1088. $_SESSION["DPA"][$val] = "Y";
  1089. } else {
  1090. $_SESSION["DPA"][$val] = "N";
  1091. }
  1092. }
  1093. }*/
  1094. # if no error in form check for subscriptions
  1095. if (!$res && is_object($GLOBALS["config"]["plugins"]["phplist"])) {
  1096. $phplist = $GLOBALS["config"]["plugins"]["phplist"];
  1097. foreach ($_SESSION["userdata"] as $key => $field) {
  1098. if (($field["formtype"] == "List Subscription" || $field["type"] == "List Subscription") && $field["listid"]) {
  1099. $listid = $field["listid"];
  1100. if ($field["value"] && isset($_SESSION["userdata"]["email"])) {
  1101. if ($phplist->addEmailToList($_SESSION["userdata"]["email"]["value"],$listid)) {
  1102. $phplist->confirmEmail($_SESSION["userdata"]["email"]["value"]);
  1103. # sendError("User added to list: $listid");
  1104. } else {
  1105. # sendError("Error adding user to list: $listid");
  1106. }
  1107. } #else {
  1108. #$phplist->removeEmailFromList($_SESSION["userdata"]["email"]["value"],$listid);
  1109. #}
  1110. }
  1111. }
  1112. }
  1113. return $res;
  1114. }
  1115. ?>