PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/wpvb.lib.php

https://github.com/ambikuk/wordpress-vbulletin
PHP | 536 lines | 274 code | 56 blank | 206 comment | 45 complexity | 85ce31c271e4c7f2b4b12999b4baa59b MD5 | raw file
  1. <?php
  2. // $Id: wpvb.inc.php,v 1.34 2009/03/09 04:46:21 sun Exp $
  3. /**
  4. * @file
  5. * Drupal vB CRUD functions.
  6. */
  7. /**
  8. * Set the necessary cookies for the user to be logged into the forum.
  9. *
  10. * Frontend cookie names:
  11. * - lastvisit, lastactivity, sessionhash
  12. * Backend cookie names:
  13. * - cpsession, userid, password
  14. *
  15. * However, in all cases the cookiedomain is NOT prefixed with a dot unless
  16. * cookie domain has not been manually altered to either a suggested value or
  17. * custom value in vB's settings.
  18. */
  19. function wpvb_set_login_cookies($userid) {
  20. // Load required vB user data.
  21. global $wpdb;
  22. $vbdb = wpvb_db();
  23. $vbuser = $vbdb->get_row($vbdb->prepare("SELECT userid, password, salt FROM user WHERE userid = %d", $userid));
  24. if (!$vbuser) {
  25. return FALSE;
  26. }
  27. // var_dump($vbuser);exit;
  28. $vb_config = wpvb_get('config');
  29. $vb_options = wpvb_get('options');
  30. $cookie_prefix = (isset($vb_config['Misc']['cookieprefix']) ? $vb_config['Misc']['cookieprefix'] : 'bb');
  31. $cookie_path = $vb_options['cookiepath'];
  32. $now = time();
  33. $expire = $now + (@ini_get('session.cookie_lifetime') ? ini_get('session.cookie_lifetime') : 60 * 60 * 24 * 365);
  34. $vb_cookie_domain = (!empty($vb_options['cookiedomain']) ? $vb_options['cookiedomain'] : $GLOBALS['cookie_domain']);
  35. // Per RFC 2109, cookie domains must contain at least one dot other than the
  36. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  37. // @see conf_init()
  38. if (!(count(explode('.', $vb_cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $vb_cookie_domain)))) {
  39. $vb_cookie_domain = '';
  40. }
  41. // Clear out old session (if available).
  42. if (!empty($_COOKIE[$cookie_prefix .'sessionhash'])) {
  43. $vpdb->query($vpdb->prepare("DELETE FROM session WHERE sessionhash = '%s'", $_COOKIE[$cookie_prefix .'sessionhash']));
  44. }
  45. // Setup user session.
  46. $ip = implode('.', array_slice(explode('.', wpvb_get_ip()), 0, 4 - $vb_options['ipcheck']));
  47. $idhash = md5($_SERVER['HTTP_USER_AGENT'] . $ip);
  48. $sessionhash = md5($now . request_uri() . $idhash . $_SERVER['REMOTE_ADDR'] . user_password(6));
  49. // var_dump($now);exit;
  50. // $vpdb->query($vpdb->prepare("REPLACE INTO session (sessionhash, userid, host, idhash, lastactivity, location, useragent, loggedin) VALUES ('%s', %d, '%s', '%s', %d, '%s', '%s', %d)", $sessionhash, $vbuser->userid, substr($_SERVER['REMOTE_ADDR'], 0, 15), $idhash, $now, '/forum/', $_SERVER['HTTP_USER_AGENT'], 2));
  51. $wpdb->insert(
  52. 'session',
  53. array(
  54. 'sessionhash'=>$sessionhash,
  55. 'userid'=>$vbuser->userid,
  56. 'host'=>substr($_SERVER['REMOTE_ADDR'], 0, 15),
  57. 'idhash'=>$idhash,
  58. 'lastactivity'=>$now,
  59. 'location'=>'/forum/',
  60. 'useragent'=> $_SERVER['HTTP_USER_AGENT'],
  61. 'loggedin'=>2
  62. ),
  63. array(
  64. '%s', '%d', '%s', '%s', '%d', '%s', '%s', '%d'
  65. )
  66. );
  67. // Setup cookies.
  68. setcookie($cookie_prefix .'_sessionhash', $sessionhash, $expire, $cookie_path, $vb_cookie_domain);
  69. setcookie($cookie_prefix .'_lastvisit', $now, $expire, $cookie_path, $vb_cookie_domain);
  70. setcookie($cookie_prefix .'_lastactivity', $now, $expire, $cookie_path, $vb_cookie_domain);
  71. setcookie($cookie_prefix .'_userid', $vbuser->userid, $expire, $cookie_path, $vb_cookie_domain);
  72. setcookie($cookie_prefix .'_password', md5($vbuser->password . get_option('wpvb_license', '')), $expire, $cookie_path, $vb_cookie_domain);
  73. return TRUE;
  74. }
  75. /**
  76. * Clear all vB cookies for the current user.
  77. *
  78. * @see wpvb_logout(), wpvb_user_logout()
  79. */
  80. function wpvb_clear_cookies($userid = NULL) {
  81. $wpdb = wpvb_db();
  82. $vb_config = wpvb_get('config');
  83. $vb_options = wpvb_get('options');
  84. $cookie_prefix = (isset($vb_config['Misc']['cookieprefix']) ? $vb_config['Misc']['cookieprefix'] : 'bb');
  85. $cookie_path = $vb_options['cookiepath'];
  86. $expire = time() - 86400;
  87. $vb_cookie_domain = (!empty($vb_options['cookiedomain']) ? $vb_options['cookiedomain'] : $GLOBALS['cookie_domain']);
  88. // Per RFC 2109, cookie domains must contain at least one dot other than the
  89. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  90. // @see conf_init()
  91. if (!(count(explode('.', $vb_cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $vb_cookie_domain)))) {
  92. $vb_cookie_domain = '';
  93. }
  94. if (!empty($userid)) {
  95. $wpdb->query("DELETE FROM session WHERE userid = %d", $userid);
  96. $wpdb->query("UPDATE user SET lastvisit = %d WHERE userid = %d", time(), $userid);
  97. }
  98. // var_dump($expire);
  99. // var_dump($cookie_path);
  100. // var_dump($vb_cookie_domain);
  101. // var_dump($cookie_prefix);exit;
  102. setcookie($cookie_prefix .'_sessionhash', '', $expire, $cookie_path, $vb_cookie_domain);
  103. setcookie($cookie_prefix .'_lastvisit', '', $expire, $cookie_path, $vb_cookie_domain);
  104. setcookie($cookie_prefix .'_lastactivity', '', $expire, $cookie_path, $vb_cookie_domain);
  105. setcookie($cookie_prefix .'_userid', '', $expire, $cookie_path, $vb_cookie_domain);
  106. setcookie($cookie_prefix .'_password', '', $expire, $cookie_path, $vb_cookie_domain);
  107. }
  108. /**
  109. * Determines the IP address of current user.
  110. */
  111. function wpvb_get_ip() {
  112. $ip = $_SERVER['REMOTE_ADDR'];
  113. if (isset($_SERVER['HTTP_CLIENT_IP'])) {
  114. $ip = $_SERVER['HTTP_CLIENT_IP'];
  115. }
  116. else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
  117. // Make sure we don't pick up an internal IP defined by RFC1918.
  118. foreach ($matches[0] as $match) {
  119. if (!preg_match("#^(10|172\.16|192\.168)\.#", $match)) {
  120. $ip = $match;
  121. break;
  122. }
  123. }
  124. }
  125. else if (isset($_SERVER['HTTP_FROM'])) {
  126. $ip = $_SERVER['HTTP_FROM'];
  127. }
  128. return $ip;
  129. }
  130. /**
  131. * Create a user in vBulletin.
  132. *
  133. * @param object $account
  134. * A Drupal user account.
  135. * @param array $edit
  136. * Form values provided by hook_user().
  137. */
  138. //function wpvb_create_user($account, $edit) {
  139. // $wpdb = wpvb_db();
  140. // // Ensure we are not duplicating a user.
  141. // if ($wpdb->query($wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->users WHERE LOWER(username) = LOWER('%s')", wpvb_htmlspecialchars($edit['username']))) > 0) {
  142. // return FALSE;
  143. // }
  144. //
  145. // $salt = '';
  146. // for ($i = 0; $i < 3; $i++) {
  147. // $salt .= chr(rand(32, 126));
  148. // }
  149. // // Note: Password is already hashed during user export.
  150. // if (isset($edit['md5pass'])) {
  151. // $passhash = md5($edit['md5pass'] . $salt);
  152. // }
  153. // else {
  154. // $passhash = md5(md5($edit['pass']) . $salt);
  155. // }
  156. //
  157. //// $passdate = date('Y-m-d', $account->created);
  158. //// $joindate = $account->created;
  159. // $passdate = date('Y-m-d', time());
  160. // $joindate = $account->time();
  161. //
  162. // // Attempt to grab the user title from the database.
  163. //// $result = $wpdb->query("SELECT title FROM usertitle WHERE minposts = 0");
  164. //// if ($resarray = db_fetch_array($result)) {
  165. //// $usertitle = $resarray['title'];
  166. //// }
  167. //// else {
  168. //// $usertitle = 'Junior Member';
  169. //// }
  170. //
  171. // // Divide timezone by 3600, since vBulletin stores hours.
  172. // $timezone = get_option('timezone_string', 0);
  173. // $timezone = ($timezone != 0 ? $timezone / 3600 : 0);
  174. //
  175. // // Default new user options: I got these by setting up a new user how I
  176. // // wanted and looking in the database to see what options were set for him.
  177. //// $options = get_option('wpvb_default_options', '3415');
  178. // $options = '3415';
  179. //
  180. // // Default usergroup id.
  181. //// $usergroupid = get_option('wpvb_default_usergroup', '2');
  182. // $usergroupid = '2';
  183. // // Set up the insertion query.
  184. //
  185. // $result = $wpdb->insert('user', array(
  186. // 'username' => htmlspecialchars($edit['name']),
  187. // 'usergroupid' => $usergroupid,
  188. // 'password' => $passhash,
  189. // 'passworddate' => $passdate,
  190. // 'usertitle' => $usertitle,
  191. // 'email' => $edit['mail'],
  192. // 'salt' => $salt,
  193. // 'languageid' => wpvb_get('languageid'),
  194. // 'timezoneoffset' => $timezone,
  195. // 'joindate' => $joindate,
  196. // 'lastvisit' => time(),
  197. // 'lastactivity' => time(),
  198. // 'options' => $options
  199. // ), array(
  200. // '%s', '%s', '%s', '%s', '%s', '%s', '%s', '1', '%d', '%s', '0', '%s', '%s', '%s', '%s'
  201. // ));
  202. //
  203. // $userid = $wpdb->insert_id;
  204. //
  205. // $wpdb->query("INSERT INTO userfield (userid) VALUES (%d)", $userid);
  206. // $wpdb->query("INSERT INTO usertextfield (userid) VALUES (%d)", $userid);
  207. //
  208. // // Insert new user into mapping table.
  209. // wpvb_set_mapping($account->uid, $userid);
  210. //
  211. // // Return userid of newly created account.
  212. // return $userid;
  213. //}
  214. function wpvb_create_user($edit) {
  215. $wpdb = wpvb_db();
  216. // Ensure we are not duplicating a user.
  217. if ($wpdb->query($wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->users WHERE LOWER(username) = LOWER('%s')", wpvb_htmlspecialchars($edit['username']))) > 0) {
  218. return FALSE;
  219. }
  220. $salt = '';
  221. for ($i = 0; $i < 3; $i++) {
  222. $salt .= chr(rand(32, 126));
  223. }
  224. // Note: Password is already hashed during user export.
  225. // if (isset($edit['pass1'])) {
  226. // $passhash = md5($edit['pass1'] . $salt);
  227. // }
  228. // else {
  229. // $passhash = md5(md5($edit['pass1']) . $salt);
  230. // }
  231. // $passdate = date('Y-m-d', $account->created);
  232. // $joindate = $account->created;
  233. $passdate = date('Y-m-d', time());
  234. $joindate = date('Y-m-d', time());
  235. // Attempt to grab the user title from the database.
  236. // $result = $wpdb->query("SELECT title FROM usertitle WHERE minposts = 0");
  237. // if ($resarray = db_fetch_array($result)) {
  238. // $usertitle = $resarray['title'];
  239. // }
  240. // else {
  241. // $usertitle = 'Junior Member';
  242. // }
  243. // Divide timezone by 3600, since vBulletin stores hours.
  244. $timezone = get_option('timezone_string', 0);
  245. $timezone = ($timezone != 0 ? $timezone / 3600 : 0);
  246. // Default new user options: I got these by setting up a new user how I
  247. // wanted and looking in the database to see what options were set for him.
  248. // $options = get_option('wpvb_default_options', '3415');
  249. $options = '3415';
  250. // Default usergroup id.
  251. // $usergroupid = get_option('wpvb_default_usergroup', '2');
  252. $usergroupid = '2';
  253. // Set up the insertion query.
  254. // wpvb_get('languageid');
  255. $langId = 0;
  256. $result = $wpdb->insert('user', array(
  257. 'userid' => $edit[0],
  258. 'username' => htmlspecialchars($edit['user_login']),
  259. 'usergroupid' => $usergroupid,
  260. 'password' => $passhash,
  261. 'passworddate' => $passdate,
  262. 'usertitle' => $usertitle,
  263. 'email' => $edit['email'],
  264. 'salt' => $salt,
  265. 'languageid' => $langId,
  266. 'timezoneoffset' => $timezone,
  267. 'joindate' => $joindate,
  268. 'lastvisit' => time(),
  269. 'lastactivity' => time(),
  270. 'options' => $options,
  271. 'usertitle' => $edit['role']
  272. ), array(
  273. '%d','%s', '%s', '%s', '%s', '%s', '%s', '%s', '1', '%d', '%s', '0', '%s', '%s', '%s', '%s'
  274. ));
  275. // $userid = $wpdb->insert_id;
  276. //
  277. // $wpdb->query("INSERT INTO userfield (userid) VALUES (%d)", $userid);
  278. // $wpdb->query("INSERT INTO usertextfield (userid) VALUES (%d)", $userid);
  279. // Insert new user into mapping table.
  280. // wpvb_set_mapping($account->uid, $userid);
  281. // Return userid of newly created account.
  282. return true;
  283. }
  284. /**
  285. * Update a user in vBulletin.
  286. */
  287. function wpvb_update_user($account, $edit) {
  288. $wpdb = wpvb_db();
  289. $fields = $values = array();
  290. foreach ($edit as $field => $value) {
  291. if (empty($value)) {
  292. continue;
  293. }
  294. switch ($field) {
  295. case 'name':
  296. $fields[] = "username = '%s'";
  297. $values[] = wpvb_htmlspecialchars($value);
  298. break;
  299. case 'pass':
  300. $fields[] = "password = '%s'";
  301. // Note: Password is already hashed during user export.
  302. if (isset($edit['md5pass'])) {
  303. $values[] = md5($edit['md5pass'] . $edit['salt']);
  304. }
  305. else {
  306. $values[] = md5(md5($value) . $edit['salt']);
  307. }
  308. $fields[] = "salt = '%s'";
  309. $values[] = $edit['salt'];
  310. $fields[] = "passworddate = '%s'";
  311. $values[] = date('Y-m-d', time());
  312. break;
  313. case 'mail':
  314. $fields[] = "email = '%s'";
  315. $values[] = $value;
  316. break;
  317. case 'language':
  318. $fields[] = "languageid = %d";
  319. $values[] = wpvb_get('languageid', $value);
  320. break;
  321. }
  322. }
  323. $fields[] = 'lastactivity = %d';
  324. $values[] = time();
  325. // Use previous case insensitive username to update conflicting names.
  326. $values[] = wpvb_htmlspecialchars($account->name);
  327. $wpdb->query("UPDATE user SET ". implode(', ', $fields) ." WHERE LOWER(username) = LOWER('%s')", $values);
  328. // Ensure this user exists in the mapping table.
  329. // When integrating an existing installation, the mapping may not yet exist.
  330. $user = $wpdb->get_row("SELECT userid FROM user WHERE username = '%s'", wpvb_htmlspecialchars($account->name));
  331. wpvb_set_mapping($account->uid, $user->userid);
  332. }
  333. /**
  334. * Ensure that a mapping between two existing user accounts exists.
  335. *
  336. * @param $uid
  337. * A Drupal user id.
  338. * @param $userid
  339. * A vBulletin user id.
  340. */
  341. function wpvb_set_mapping($uid, $userid) {
  342. $wpdb = wpvb_db();
  343. $wpdb->query("INSERT IGNORE INTO wpvb_users (uid, userid) VALUES (%d, %d)", $uid, $userid);
  344. }
  345. /**
  346. * Export all drupal users to vBulletin.
  347. */
  348. function wpvb_export_drupal_users() {
  349. $wpdb = wpvb_db();
  350. module_load_include('inc', 'wpvb');
  351. $result = db_query("SELECT * FROM users ORDER BY uid");
  352. while ($user = db_fetch_object($result)) {
  353. if ($user->uid == 0) {
  354. continue;
  355. }
  356. // Let create/update functions know that passwords are hashed already.
  357. $user->md5pass = $user->pass;
  358. if (!wpvb_create_user($user, (array)$user)) {
  359. // Username already exists, update email and password only.
  360. // Case insensitive username is required to detect collisions.
  361. $vbuser = db_fetch_array($wpdb->query("SELECT salt FROM user WHERE LOWER(username) = LOWER('%s')", wpvb_htmlspecialchars($user->name)));
  362. wpvb_update_user($user, array_merge((array)$user, $vbuser));
  363. }
  364. }
  365. }
  366. /**
  367. * Get vBulletin configuration options.
  368. */
  369. function wpvb_get_options() {
  370. $wpdb = wpvb_db();
  371. static $options = array();
  372. if (empty($options)) {
  373. $result = $wpdb->get_results("SELECT varname, value FROM setting");
  374. foreach ($result as $var) {
  375. $options[$var->varname] = $var->value;
  376. }
  377. }
  378. // var_dump($options);exit;
  379. return $options;
  380. }
  381. /**
  382. * Get vBulletin configuration.
  383. */
  384. function wpvb_get_config() {
  385. static $config = array();
  386. // @todo Find & include vB's config automatically?
  387. // $files = file_scan_directory('.', '^config.php$', $nomask = array('.', '..', 'CVS', '.svn'));
  388. $config_file = ABSPATH .'forum/includes/config.php';
  389. if (empty($config) && file_exists($config_file)) {
  390. require_once $config_file;
  391. }
  392. // var_dump($config);exit;
  393. return $config;
  394. }
  395. /**
  396. * Get vB user roles.
  397. */
  398. function wpvb_get_roles() {
  399. $wpdb = wpvb_db();
  400. $result = $wpdb->query("SELECT usergroupid, title FROM usergroup");
  401. $roles = array();
  402. while ($data = db_fetch_object($result)) {
  403. $roles[$data->usergroupid] = $data->title;
  404. }
  405. if (!$roles) {
  406. $roles[] = t('No user roles could be found.');
  407. }
  408. return $roles;
  409. }
  410. /**
  411. * Get vB language id by given ISO language code.
  412. */
  413. function wpvb_get_languageid($language = NULL) {
  414. $wpdb = wpvb_db();
  415. static $vblanguages;
  416. if (!isset($vblanguages)) {
  417. $vblanguages = array();
  418. $result = $wpdb->query("SELECT languageid, title, languagecode FROM language");
  419. while ($lang = db_fetch_array($result)) {
  420. $vblanguages[$lang['languagecode']] = $lang['languageid'];
  421. }
  422. }
  423. $options = wpvb_get('options');
  424. return (!empty($language) && isset($vblanguages[$language]) ? $vblanguages[$language] : $vblanguages[$options['languageid']]);
  425. }
  426. /**
  427. * Get counts of guests and members currently online.
  428. */
  429. function wpvb_get_users_online() {
  430. $wpdb = wpvb_db();
  431. $vb_options = wpvb_get('options');
  432. $datecut = time() - $vb_options['cookietimeout'];
  433. $numbervisible = 0;
  434. $numberregistered = 0;
  435. $numberguest = 0;
  436. $result = $wpdb->query("SELECT user.username, user.usergroupid, session.userid, session.lastactivity FROM session AS session LEFT JOIN user AS user ON (user.userid = session.userid) WHERE session.lastactivity > %d", $datecut);
  437. $userinfos = array();
  438. while ($loggedin = db_fetch_array($result)) {
  439. $userid = $loggedin['userid'];
  440. if (!$userid) {
  441. $numberguest++;
  442. }
  443. else if (empty($userinfos[$userid]) || ($userinfos[$userid]['lastactivity'] < $loggedin['lastactivity'])) {
  444. $userinfos[$userid] = $loggedin;
  445. }
  446. }
  447. foreach ($userinfos as $userid => $loggedin) {
  448. $numberregistered++;
  449. }
  450. return array('guests' => $numberguest, 'members' => $numberregistered);
  451. }
  452. /**
  453. * Get counts of new or recent posts for the current user.
  454. */
  455. function wpvb_get_recent_posts($scope = 'last') {
  456. $wpdb = wpvb_db();
  457. global $user;
  458. // Queries the vB user database to find a matching set of user data.
  459. $result = $wpdb->query("SELECT userid, username, lastvisit FROM user WHERE username = '%s'", wpvb_htmlspecialchars($user->name));
  460. // Make sure a user is logged in to get their last visit and appropriate post
  461. // count.
  462. if ($vb_user = db_fetch_array($result)) {
  463. $wpdb = wpvb_db();
  464. if ($scope == 'last') {
  465. $datecut = $vb_user['lastvisit'];
  466. }
  467. else if ($scope == 'daily') {
  468. $datecut = time() - 86400;
  469. }
  470. $posts = $wpdb->get_results("SELECT COUNT(postid) FROM post WHERE dateline > %d", $datecut);
  471. }
  472. else {
  473. $posts = 0;
  474. }
  475. return $posts;
  476. }
  477. function wpvb_htmlspecialchars($text) {
  478. $text = preg_replace('/&(?!#[0-9]+|shy;)/si', '&amp;', $text);
  479. return str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $text);
  480. }