[ Index ]

PHP Cross Reference of MyBB 1.8.17

title

Body

[close]

/ -> member.php (source)

   1  <?php
   2  /**
   3   * MyBB 1.8
   4   * Copyright 2014 MyBB Group, All Rights Reserved
   5   *
   6   * Website: http://www.mybb.com
   7   * License: http://www.mybb.com/about/license
   8   *
   9   */
  10  
  11  define("IN_MYBB", 1);
  12  define("IGNORE_CLEAN_VARS", "sid");
  13  define('THIS_SCRIPT', 'member.php');
  14  define("ALLOWABLE_PAGE", "register,do_register,login,do_login,logout,lostpw,do_lostpw,activate,resendactivation,do_resendactivation,resetpassword,viewnotes");
  15  
  16  $nosession['avatar'] = 1;
  17  
  18  $templatelist = "member_register,member_register_hiddencaptcha,member_register_coppa,member_register_agreement_coppa,member_register_agreement,member_register_customfield,member_register_requiredfields,member_profile_findthreads";
  19  $templatelist .= ",member_loggedin_notice,member_profile_away,member_register_regimage,member_register_regimage_recaptcha_invisible,member_register_regimage_nocaptcha,post_captcha_hidden,post_captcha,member_register_referrer";
  20  $templatelist .= ",member_profile_email,member_profile_offline,member_profile_reputation,member_profile_warn,member_profile_warninglevel,member_profile_customfields_field,member_profile_customfields,member_profile_adminoptions,member_profile";
  21  $templatelist .= ",member_profile_signature,member_profile_avatar,member_profile_groupimage,member_profile_referrals,member_profile_website,member_profile_reputation_vote,member_activate,member_lostpw,member_register_additionalfields";
  22  $templatelist .= ",member_profile_modoptions_manageuser,member_profile_modoptions_editprofile,member_profile_modoptions_banuser,member_profile_modoptions_viewnotes,member_profile_modoptions_editnotes,member_profile_modoptions_purgespammer";
  23  $templatelist .= ",usercp_profile_profilefields_select_option,usercp_profile_profilefields_multiselect,usercp_profile_profilefields_select,usercp_profile_profilefields_textarea,usercp_profile_profilefields_radio,member_viewnotes";
  24  $templatelist .= ",member_register_question,member_register_question_refresh,usercp_options_timezone,usercp_options_timezone_option,usercp_options_language_option,member_profile_customfields_field_multi_item,member_profile_customfields_field_multi";
  25  $templatelist .= ",member_profile_contact_fields_google,member_profile_contact_fields_icq,member_profile_contact_fields_skype,member_profile_contact_fields_yahoo,member_profile_pm,member_profile_contact_details";
  26  $templatelist .= ",member_profile_banned_remaining,member_profile_addremove,member_emailuser_guest,member_register_day,usercp_options_tppselect_option,postbit_warninglevel_formatted,member_profile_userstar,member_profile_findposts";
  27  $templatelist .= ",usercp_options_tppselect,usercp_options_pppselect,member_resetpassword,member_login,member_profile_online,usercp_options_pppselect_option,postbit_reputation_formatted,member_emailuser,usercp_profile_profilefields_text";
  28  $templatelist .= ",member_profile_modoptions_ipaddress,member_profile_modoptions,member_profile_banned,member_register_language,member_resendactivation,usercp_profile_profilefields_checkbox,member_register_password,member_coppa_form";
  29  
  30  require_once  "./global.php";
  31  require_once  MYBB_ROOT."inc/functions_post.php";
  32  require_once  MYBB_ROOT."inc/functions_user.php";
  33  require_once  MYBB_ROOT."inc/class_parser.php";
  34  $parser = new postParser;
  35  
  36  // Load global language phrases
  37  $lang->load("member");
  38  
  39  $mybb->input['action'] = $mybb->get_input('action');
  40  
  41  // Make navigation
  42  switch($mybb->input['action'])
  43  {
  44      case "register":
  45      case "do_register":
  46          add_breadcrumb($lang->nav_register);
  47          break;
  48      case "activate":
  49          add_breadcrumb($lang->nav_activate);
  50          break;
  51      case "resendactivation":
  52          add_breadcrumb($lang->nav_resendactivation);
  53          break;
  54      case "lostpw":
  55          add_breadcrumb($lang->nav_lostpw);
  56          break;
  57      case "resetpassword":
  58          add_breadcrumb($lang->nav_resetpassword);
  59          break;
  60      case "login":
  61          add_breadcrumb($lang->nav_login);
  62          break;
  63      case "emailuser":
  64          add_breadcrumb($lang->nav_emailuser);
  65          break;
  66  }
  67  
  68  if(($mybb->input['action'] == "register" || $mybb->input['action'] == "do_register") && $mybb->usergroup['cancp'] != 1)
  69  {
  70      if($mybb->settings['disableregs'] == 1)
  71      {
  72          error($lang->registrations_disabled);
  73      }
  74      if($mybb->user['uid'] != 0)
  75      {
  76          error($lang->error_alreadyregistered);
  77      }
  78      if($mybb->settings['betweenregstime'] && $mybb->settings['maxregsbetweentime'])
  79      {
  80          $time = TIME_NOW;
  81          $datecut = $time-(60*60*$mybb->settings['betweenregstime']);
  82          $query = $db->simple_select("users", "*", "regip=".$db->escape_binary($session->packedip)." AND regdate > '$datecut'");
  83          $regcount = $db->num_rows($query);
  84          if($regcount >= $mybb->settings['maxregsbetweentime'])
  85          {
  86              $lang->error_alreadyregisteredtime = $lang->sprintf($lang->error_alreadyregisteredtime, $regcount, $mybb->settings['betweenregstime']);
  87              error($lang->error_alreadyregisteredtime);
  88          }
  89      }
  90  }
  91  
  92  if($mybb->input['action'] == "do_register" && $mybb->request_method == "post")
  93  {
  94      $plugins->run_hooks("member_do_register_start");
  95  
  96      // Are checking how long it takes for users to register?
  97      if($mybb->settings['regtime'] > 0)
  98      {
  99          // Is the field actually set?
 100          if(isset($mybb->input['regtime']))
 101          {
 102              // Check how long it took for this person to register
 103              $timetook = TIME_NOW - $mybb->get_input('regtime', MyBB::INPUT_INT);
 104  
 105              // See if they registered faster than normal
 106              if($timetook < $mybb->settings['regtime'])
 107              {
 108                  // This user registered pretty quickly, bot detected!
 109                  $lang->error_spam_deny_time = $lang->sprintf($lang->error_spam_deny_time, $mybb->settings['regtime'], $timetook);
 110                  error($lang->error_spam_deny_time);
 111              }
 112          }
 113          else
 114          {
 115              error($lang->error_spam_deny);
 116          }
 117      }
 118  
 119      // If we have hidden CATPCHA enabled and it's filled, deny registration
 120      if($mybb->settings['hiddencaptchaimage'])
 121      {
 122          $string = $mybb->settings['hiddencaptchaimagefield'];
 123  
 124          if(!empty($mybb->input[$string]))
 125          {
 126              error($lang->error_spam_deny);
 127          }
 128      }
 129  
 130      if($mybb->settings['regtype'] == "randompass")
 131      {
 132  
 133          $password_length = (int)$mybb->settings['minpasswordlength'];
 134          if($password_length < 8)
 135          {
 136              $password_length = min(8, (int)$mybb->settings['maxpasswordlength']);
 137          }
 138  
 139          $mybb->input['password'] = random_str($password_length, $mybb->settings['requirecomplexpasswords']);
 140          $mybb->input['password2'] = $mybb->input['password'];
 141      }
 142  
 143      if($mybb->settings['regtype'] == "verify" || $mybb->settings['regtype'] == "admin" || $mybb->settings['regtype'] == "both" || $mybb->get_input('coppa', MyBB::INPUT_INT) == 1)
 144      {
 145          $usergroup = 5;
 146      }
 147      else
 148      {
 149          $usergroup = 2;
 150      }
 151  
 152      // Set up user handler.
 153      require_once  MYBB_ROOT."inc/datahandlers/user.php";
 154      $userhandler = new UserDataHandler("insert");
 155  
 156      $coppauser = 0;
 157      if(isset($mybb->cookies['coppauser']))
 158      {
 159          $coppauser = (int)$mybb->cookies['coppauser'];
 160      }
 161  
 162      // Set the data for the new user.
 163      $user = array(
 164          "username" => $mybb->get_input('username'),
 165          "password" => $mybb->get_input('password'),
 166          "password2" => $mybb->get_input('password2'),
 167          "email" => $mybb->get_input('email'),
 168          "email2" => $mybb->get_input('email2'),
 169          "usergroup" => $usergroup,
 170          "referrer" => $mybb->get_input('referrername'),
 171          "timezone" => $mybb->get_input('timezoneoffset'),
 172          "language" => $mybb->get_input('language'),
 173          "profile_fields" => $mybb->get_input('profile_fields', MyBB::INPUT_ARRAY),
 174          "regip" => $session->packedip,
 175          "coppa_user" => $coppauser,
 176          "regcheck1" => $mybb->get_input('regcheck1'),
 177          "regcheck2" => $mybb->get_input('regcheck2'),
 178          "registration" => true
 179      );
 180  
 181      // Do we have a saved COPPA DOB?
 182      if(isset($mybb->cookies['coppadob']))
 183      {
 184          list($dob_day, $dob_month, $dob_year) = explode("-", $mybb->cookies['coppadob']);
 185          $user['birthday'] = array(
 186              "day" => $dob_day,
 187              "month" => $dob_month,
 188              "year" => $dob_year
 189          );
 190      }
 191  
 192      $user['options'] = array(
 193          "allownotices" => $mybb->get_input('allownotices', MyBB::INPUT_INT),
 194          "hideemail" => $mybb->get_input('hideemail', MyBB::INPUT_INT),
 195          "subscriptionmethod" => $mybb->get_input('subscriptionmethod', MyBB::INPUT_INT),
 196          "receivepms" => $mybb->get_input('receivepms', MyBB::INPUT_INT),
 197          "pmnotice" => $mybb->get_input('pmnotice', MyBB::INPUT_INT),
 198          "pmnotify" => $mybb->get_input('pmnotify', MyBB::INPUT_INT),
 199          "invisible" => $mybb->get_input('invisible', MyBB::INPUT_INT),
 200          "dstcorrection" => $mybb->get_input('dstcorrection')
 201      );
 202  
 203      $userhandler->set_data($user);
 204  
 205      $errors = array();
 206  
 207      if(!$userhandler->validate_user())
 208      {
 209          $errors = $userhandler->get_friendly_errors();
 210      }
 211  
 212      if($mybb->settings['enablestopforumspam_on_register'])
 213      {
 214          require_once  MYBB_ROOT . '/inc/class_stopforumspamchecker.php';
 215  
 216          $stop_forum_spam_checker = new StopForumSpamChecker(
 217              $plugins,
 218              $mybb->settings['stopforumspam_min_weighting_before_spam'],
 219              $mybb->settings['stopforumspam_check_usernames'],
 220              $mybb->settings['stopforumspam_check_emails'],
 221              $mybb->settings['stopforumspam_check_ips'],
 222              $mybb->settings['stopforumspam_log_blocks']
 223          );
 224  
 225          try {
 226              if($stop_forum_spam_checker->is_user_a_spammer($user['username'], $user['email'], get_ip()))
 227              {
 228                  error($lang->sprintf($lang->error_stop_forum_spam_spammer,
 229                          $stop_forum_spam_checker->getErrorText(array(
 230                              'stopforumspam_check_usernames',
 231                              'stopforumspam_check_emails',
 232                              'stopforumspam_check_ips'
 233                              ))));
 234              }
 235          }
 236          catch (Exception $e)
 237          {
 238              if($mybb->settings['stopforumspam_block_on_error'])
 239              {
 240                  error($lang->error_stop_forum_spam_fetching);
 241              }
 242          }
 243      }
 244  
 245      if($mybb->settings['captchaimage'])
 246      {
 247          require_once  MYBB_ROOT.'inc/class_captcha.php';
 248          $captcha = new captcha;
 249  
 250          if($captcha->validate_captcha() == false)
 251          {
 252              // CAPTCHA validation failed
 253              foreach($captcha->get_errors() as $error)
 254              {
 255                  $errors[] = $error;
 256              }
 257          }
 258      }
 259  
 260      // If we have a security question, check to see if answer is correct
 261      if($mybb->settings['securityquestion'])
 262      {
 263          $question_id = $db->escape_string($mybb->get_input('question_id'));
 264          $answer = $db->escape_string($mybb->get_input('answer'));
 265  
 266          $query = $db->query("
 267              SELECT q.*, s.sid
 268              FROM ".TABLE_PREFIX."questionsessions s
 269              LEFT JOIN ".TABLE_PREFIX."questions q ON (q.qid=s.qid)
 270              WHERE q.active='1' AND s.sid='{$question_id}'
 271          ");
 272          if($db->num_rows($query) > 0)
 273          {
 274              $question = $db->fetch_array($query);
 275              $valid_answers = explode("\n", $question['answer']);
 276              $validated = 0;
 277  
 278              foreach($valid_answers as $answers)
 279              {
 280                  if(my_strtolower($answers) == my_strtolower($answer))
 281                  {
 282                      $validated = 1;
 283                  }
 284              }
 285  
 286              if($validated != 1)
 287              {
 288                  $update_question = array(
 289                      "incorrect" => $question['incorrect'] + 1
 290                  );
 291                  $db->update_query("questions", $update_question, "qid='{$question['qid']}'");
 292  
 293                  $errors[] = $lang->error_question_wrong;
 294              }
 295              else
 296              {
 297                  $update_question = array(
 298                      "correct" => $question['correct'] + 1
 299                  );
 300                  $db->update_query("questions", $update_question, "qid='{$question['qid']}'");
 301              }
 302  
 303              $db->delete_query("questionsessions", "sid='{$sid}'");
 304          }
 305      }
 306  
 307      if(!empty($errors))
 308      {
 309          $username = htmlspecialchars_uni($mybb->get_input('username'));
 310          $email = htmlspecialchars_uni($mybb->get_input('email'));
 311          $email2 = htmlspecialchars_uni($mybb->get_input('email2'));
 312          $referrername = htmlspecialchars_uni($mybb->get_input('referrername'));
 313  
 314          $allownoticescheck = $hideemailcheck = $no_auto_subscribe_selected = $instant_email_subscribe_selected = $instant_pm_subscribe_selected = $no_subscribe_selected = '';
 315          $receivepmscheck = $pmnoticecheck = $pmnotifycheck = $invisiblecheck = $dst_auto_selected = $dst_enabled_selected = $dst_disabled_selected = '';
 316  
 317          if($mybb->get_input('allownotices', MyBB::INPUT_INT) == 1)
 318          {
 319              $allownoticescheck = "checked=\"checked\"";
 320          }
 321  
 322          if($mybb->get_input('hideemail', MyBB::INPUT_INT) == 1)
 323          {
 324              $hideemailcheck = "checked=\"checked\"";
 325          }
 326  
 327          if($mybb->get_input('subscriptionmethod', MyBB::INPUT_INT) == 1)
 328          {
 329              $no_subscribe_selected = "selected=\"selected\"";
 330          }
 331          else if($mybb->get_input('subscriptionmethod', MyBB::INPUT_INT) == 2)
 332          {
 333              $instant_email_subscribe_selected = "selected=\"selected\"";
 334          }
 335          else if($mybb->get_input('subscriptionmethod', MyBB::INPUT_INT) == 3)
 336          {
 337              $instant_pm_subscribe_selected = "selected=\"selected\"";
 338          }
 339          else
 340          {
 341              $no_auto_subscribe_selected = "selected=\"selected\"";
 342          }
 343  
 344          if($mybb->get_input('receivepms', MyBB::INPUT_INT) == 1)
 345          {
 346              $receivepmscheck = "checked=\"checked\"";
 347          }
 348  
 349          if($mybb->get_input('pmnotice', MyBB::INPUT_INT) == 1)
 350          {
 351              $pmnoticecheck = " checked=\"checked\"";
 352          }
 353  
 354          if($mybb->get_input('pmnotify', MyBB::INPUT_INT) == 1)
 355          {
 356              $pmnotifycheck = "checked=\"checked\"";
 357          }
 358  
 359          if($mybb->get_input('invisible', MyBB::INPUT_INT) == 1)
 360          {
 361              $invisiblecheck = "checked=\"checked\"";
 362          }
 363  
 364          if($mybb->get_input('dstcorrection', MyBB::INPUT_INT) == 2)
 365          {
 366              $dst_auto_selected = "selected=\"selected\"";
 367          }
 368          else if($mybb->get_input('dstcorrection', MyBB::INPUT_INT) == 1)
 369          {
 370              $dst_enabled_selected = "selected=\"selected\"";
 371          }
 372          else
 373          {
 374              $dst_disabled_selected = "selected=\"selected\"";
 375          }
 376  
 377          $regerrors = inline_error($errors);
 378          $mybb->input['action'] = "register";
 379          $fromreg = 1;
 380      }
 381      else
 382      {
 383          $user_info = $userhandler->insert_user();
 384  
 385          // Invalidate solved captcha
 386          if($mybb->settings['captchaimage'])
 387          {
 388              $captcha->invalidate_captcha();
 389          }
 390  
 391          if($mybb->settings['regtype'] != "randompass" && !isset($mybb->cookies['coppauser']))
 392          {
 393              // Log them in
 394              my_setcookie("mybbuser", $user_info['uid']."_".$user_info['loginkey'], null, true, "lax");
 395          }
 396  
 397          if(isset($mybb->cookies['coppauser']))
 398          {
 399              $lang->redirect_registered_coppa_activate = $lang->sprintf($lang->redirect_registered_coppa_activate, $mybb->settings['bbname'], htmlspecialchars_uni($user_info['username']));
 400              my_unsetcookie("coppauser");
 401              my_unsetcookie("coppadob");
 402              $plugins->run_hooks("member_do_register_end");
 403              error($lang->redirect_registered_coppa_activate);
 404          }
 405          else if($mybb->settings['regtype'] == "verify")
 406          {
 407              $activationcode = random_str();
 408              $now = TIME_NOW;
 409              $activationarray = array(
 410                  "uid" => $user_info['uid'],
 411                  "dateline" => TIME_NOW,
 412                  "code" => $activationcode,
 413                  "type" => "r"
 414              );
 415              $db->insert_query("awaitingactivation", $activationarray);
 416              $emailsubject = $lang->sprintf($lang->emailsubject_activateaccount, $mybb->settings['bbname']);
 417              switch($mybb->settings['username_method'])
 418              {
 419                  case 0:
 420                      $emailmessage = $lang->sprintf($lang->email_activateaccount, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 421                      break;
 422                  case 1:
 423                      $emailmessage = $lang->sprintf($lang->email_activateaccount1, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 424                      break;
 425                  case 2:
 426                      $emailmessage = $lang->sprintf($lang->email_activateaccount2, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 427                      break;
 428                  default:
 429                      $emailmessage = $lang->sprintf($lang->email_activateaccount, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 430                      break;
 431              }
 432              my_mail($user_info['email'], $emailsubject, $emailmessage);
 433  
 434              $lang->redirect_registered_activation = $lang->sprintf($lang->redirect_registered_activation, $mybb->settings['bbname'], htmlspecialchars_uni($user_info['username']));
 435  
 436              $plugins->run_hooks("member_do_register_end");
 437  
 438              error($lang->redirect_registered_activation);
 439          }
 440          else if($mybb->settings['regtype'] == "randompass")
 441          {
 442              $emailsubject = $lang->sprintf($lang->emailsubject_randompassword, $mybb->settings['bbname']);
 443              switch($mybb->settings['username_method'])
 444              {
 445                  case 0:
 446                      $emailmessage = $lang->sprintf($lang->email_randompassword, $user['username'], $mybb->settings['bbname'], $user_info['username'], $mybb->get_input('password'));
 447                      break;
 448                  case 1:
 449                      $emailmessage = $lang->sprintf($lang->email_randompassword1, $user['username'], $mybb->settings['bbname'], $user_info['username'], $mybb->get_input('password'));
 450                      break;
 451                  case 2:
 452                      $emailmessage = $lang->sprintf($lang->email_randompassword2, $user['username'], $mybb->settings['bbname'], $user_info['username'], $mybb->get_input('password'));
 453                      break;
 454                  default:
 455                      $emailmessage = $lang->sprintf($lang->email_randompassword, $user['username'], $mybb->settings['bbname'], $user_info['username'], $mybb->get_input('password'));
 456                      break;
 457              }
 458              my_mail($user_info['email'], $emailsubject, $emailmessage);
 459  
 460              $plugins->run_hooks("member_do_register_end");
 461  
 462              error($lang->redirect_registered_passwordsent);
 463          }
 464          else if($mybb->settings['regtype'] == "admin")
 465          {
 466              $groups = $cache->read("usergroups");
 467              $admingroups = array();
 468              if(!empty($groups)) // Shouldn't be...
 469              {
 470                  foreach($groups as $group)
 471                  {
 472                      if($group['cancp'] == 1)
 473                      {
 474                          $admingroups[] = (int)$group['gid'];
 475                      }
 476                  }
 477              }
 478  
 479              if(!empty($admingroups))
 480              {
 481                  $sqlwhere = 'usergroup IN ('.implode(',', $admingroups).')';
 482                  foreach($admingroups as $admingroup)
 483                  {
 484                      switch($db->type)
 485                      {
 486                          case 'pgsql':
 487                          case 'sqlite':
 488                              $sqlwhere .= " OR ','||additionalgroups||',' LIKE '%,{$admingroup},%'";
 489                              break;
 490                          default:
 491                              $sqlwhere .= " OR CONCAT(',',additionalgroups,',') LIKE '%,{$admingroup},%'";
 492                              break;
 493                      }
 494                  }
 495                  $q = $db->simple_select('users', 'uid,username,email,language', $sqlwhere);
 496                  while($recipient = $db->fetch_array($q))
 497                  {
 498                      // First we check if the user's a super admin: if yes, we don't care about permissions
 499                      $is_super_admin = is_super_admin($recipient['uid']);
 500                      if(!$is_super_admin)
 501                      {
 502                          // Include admin functions
 503                          if(!file_exists(MYBB_ROOT.$mybb->config['admin_dir']."/inc/functions.php"))
 504                          {
 505                              continue;
 506                          }
 507  
 508                          require_once MYBB_ROOT.$mybb->config['admin_dir']."/inc/functions.php";
 509  
 510                          // Verify if we have permissions to access user-users
 511                          require_once MYBB_ROOT.$mybb->config['admin_dir']."/modules/user/module_meta.php";
 512                          if(function_exists("user_admin_permissions"))
 513                          {
 514                              // Get admin permissions
 515                              $adminperms = get_admin_permissions($recipient['uid']);
 516  
 517                              $permissions = user_admin_permissions();
 518                              if(array_key_exists('users', $permissions['permissions']) && $adminperms['user']['users'] != 1)
 519                              {
 520                                  continue; // No permissions
 521                              }
 522                          }
 523                      }
 524  
 525                      // Load language
 526                      if($recipient['language'] != $lang->language && $lang->language_exists($recipient['language']))
 527                      {
 528                          $reset_lang = true;
 529                          $lang->set_language($recipient['language']);
 530                          $lang->load("member");
 531                      }
 532  
 533                      $subject = $lang->sprintf($lang->newregistration_subject, $mybb->settings['bbname']);
 534                      $message = $lang->sprintf($lang->newregistration_message, $recipient['username'], $mybb->settings['bbname'], $user['username']);
 535                      my_mail($recipient['email'], $subject, $message);
 536                  }
 537  
 538                  // Reset language
 539                  if(isset($reset_lang))
 540                  {
 541                      $lang->set_language($mybb->settings['bblanguage']);
 542                      $lang->load("member");
 543                  }
 544              }
 545  
 546              $lang->redirect_registered_admin_activate = $lang->sprintf($lang->redirect_registered_admin_activate, $mybb->settings['bbname'], htmlspecialchars_uni($user_info['username']));
 547  
 548              $plugins->run_hooks("member_do_register_end");
 549  
 550              error($lang->redirect_registered_admin_activate);
 551          }
 552          else if($mybb->settings['regtype'] == "both")
 553          {
 554              $groups = $cache->read("usergroups");
 555              $admingroups = array();
 556              if(!empty($groups)) // Shouldn't be...
 557              {
 558                  foreach($groups as $group)
 559                  {
 560                      if($group['cancp'] == 1)
 561                      {
 562                          $admingroups[] = (int)$group['gid'];
 563                      }
 564                  }
 565              }
 566  
 567              if(!empty($admingroups))
 568              {
 569                  $sqlwhere = 'usergroup IN ('.implode(',', $admingroups).')';
 570                  foreach($admingroups as $admingroup)
 571                  {
 572                      switch($db->type)
 573                      {
 574                          case 'pgsql':
 575                          case 'sqlite':
 576                              $sqlwhere .= " OR ','||additionalgroups||',' LIKE '%,{$admingroup},%'";
 577                              break;
 578                          default:
 579                              $sqlwhere .= " OR CONCAT(',',additionalgroups,',') LIKE '%,{$admingroup},%'";
 580                              break;
 581                      }
 582                  }
 583                  $q = $db->simple_select('users', 'uid,username,email,language', $sqlwhere);
 584                  while($recipient = $db->fetch_array($q))
 585                  {
 586                      // First we check if the user's a super admin: if yes, we don't care about permissions
 587                      $is_super_admin = is_super_admin($recipient['uid']);
 588                      if(!$is_super_admin)
 589                      {
 590                          // Include admin functions
 591                          if(!file_exists(MYBB_ROOT.$mybb->config['admin_dir']."/inc/functions.php"))
 592                          {
 593                              continue;
 594                          }
 595  
 596                          require_once MYBB_ROOT.$mybb->config['admin_dir']."/inc/functions.php";
 597  
 598                          // Verify if we have permissions to access user-users
 599                          require_once MYBB_ROOT.$mybb->config['admin_dir']."/modules/user/module_meta.php";
 600                          if(function_exists("user_admin_permissions"))
 601                          {
 602                              // Get admin permissions
 603                              $adminperms = get_admin_permissions($recipient['uid']);
 604  
 605                              $permissions = user_admin_permissions();
 606                              if(array_key_exists('users', $permissions['permissions']) && $adminperms['user']['users'] != 1)
 607                              {
 608                                  continue; // No permissions
 609                              }
 610                          }
 611                      }
 612  
 613                      // Load language
 614                      if($recipient['language'] != $lang->language && $lang->language_exists($recipient['language']))
 615                      {
 616                          $reset_lang = true;
 617                          $lang->set_language($recipient['language']);
 618                          $lang->load("member");
 619                      }
 620  
 621                      $subject = $lang->sprintf($lang->newregistration_subject, $mybb->settings['bbname']);
 622                      $message = $lang->sprintf($lang->newregistration_message, $recipient['username'], $mybb->settings['bbname'], $user['username']);
 623                      my_mail($recipient['email'], $subject, $message);
 624                  }
 625  
 626                  // Reset language
 627                  if(isset($reset_lang))
 628                  {
 629                      $lang->set_language($mybb->settings['bblanguage']);
 630                      $lang->load("member");
 631                  }
 632              }
 633  
 634              $activationcode = random_str();
 635              $activationarray = array(
 636                  "uid" => $user_info['uid'],
 637                  "dateline" => TIME_NOW,
 638                  "code" => $activationcode,
 639                  "type" => "b"
 640              );
 641              $db->insert_query("awaitingactivation", $activationarray);
 642              $emailsubject = $lang->sprintf($lang->emailsubject_activateaccount, $mybb->settings['bbname']);
 643              switch($mybb->settings['username_method'])
 644              {
 645                  case 0:
 646                      $emailmessage = $lang->sprintf($lang->email_activateaccount, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 647                      break;
 648                  case 1:
 649                      $emailmessage = $lang->sprintf($lang->email_activateaccount1, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 650                      break;
 651                  case 2:
 652                      $emailmessage = $lang->sprintf($lang->email_activateaccount2, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 653                      break;
 654                  default:
 655                      $emailmessage = $lang->sprintf($lang->email_activateaccount, $user_info['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user_info['uid'], $activationcode);
 656                      break;
 657              }
 658              my_mail($user_info['email'], $emailsubject, $emailmessage);
 659  
 660              $lang->redirect_registered_activation = $lang->sprintf($lang->redirect_registered_activation, $mybb->settings['bbname'], htmlspecialchars_uni($user_info['username']));
 661  
 662              $plugins->run_hooks("member_do_register_end");
 663  
 664              error($lang->redirect_registered_activation);
 665          }
 666          else
 667          {
 668              $lang->redirect_registered = $lang->sprintf($lang->redirect_registered, $mybb->settings['bbname'], htmlspecialchars_uni($user_info['username']));
 669  
 670              $plugins->run_hooks("member_do_register_end");
 671  
 672              redirect("index.php", $lang->redirect_registered);
 673          }
 674      }
 675  }
 676  
 677  if($mybb->input['action'] == "coppa_form")
 678  {
 679      if(!$mybb->settings['faxno'])
 680      {
 681          $mybb->settings['faxno'] = "&nbsp;";
 682      }
 683  
 684      $plugins->run_hooks("member_coppa_form");
 685  
 686      eval("\$coppa_form = \"".$templates->get("member_coppa_form")."\";");
 687      output_page($coppa_form);
 688  }
 689  
 690  if($mybb->input['action'] == "register")
 691  {
 692      $bdaysel = '';
 693      if($mybb->settings['coppa'] == "disabled")
 694      {
 695          $bdaysel = $bday2blank = '';
 696      }
 697      $mybb->input['bday1'] = $mybb->get_input('bday1', MyBB::INPUT_INT);
 698      for($day = 1; $day <= 31; ++$day)
 699      {
 700          $selected = '';
 701          if($mybb->input['bday1'] == $day)
 702          {
 703              $selected = " selected=\"selected\"";
 704          }
 705  
 706          eval("\$bdaysel .= \"".$templates->get("member_register_day")."\";");
 707      }
 708  
 709      $mybb->input['bday2'] = $mybb->get_input('bday2', MyBB::INPUT_INT);
 710      $bdaymonthsel = array();
 711      foreach(range(1, 12) as $number)
 712      {
 713          $bdaymonthsel[$number] = '';
 714      }
 715      $bdaymonthsel[$mybb->input['bday2']] = "selected=\"selected\"";
 716      $birthday_year = $mybb->get_input('bday3', MyBB::INPUT_INT);
 717  
 718      if($birthday_year == 0)
 719      {
 720          $birthday_year = '';
 721      }
 722  
 723      // Is COPPA checking enabled?
 724      if($mybb->settings['coppa'] != "disabled" && !isset($mybb->input['step']))
 725      {
 726          // Just selected DOB, we check
 727          if($mybb->input['bday1'] && $mybb->input['bday2'] && $birthday_year)
 728          {
 729              my_unsetcookie("coppauser");
 730  
 731              $months = get_bdays($birthday_year);
 732              if($mybb->input['bday2'] < 1 || $mybb->input['bday2'] > 12 || $birthday_year < (date("Y")-100) || $birthday_year > date("Y") || $mybb->input['bday1'] > $months[$mybb->input['bday2']-1])
 733              {
 734                  error($lang->error_invalid_birthday);
 735              }
 736  
 737              $bdaytime = @mktime(0, 0, 0, $mybb->input['bday2'], $mybb->input['bday1'], $birthday_year);
 738  
 739              // Store DOB in cookie so we can save it with the registration
 740              my_setcookie("coppadob", "{$mybb->input['bday1']}-{$mybb->input['bday2']}-{$birthday_year}", -1);
 741  
 742              // User is <= 13, we mark as a coppa user
 743              if($bdaytime >= mktime(0, 0, 0, my_date('n'), my_date('d'), my_date('Y')-13))
 744              {
 745                  my_setcookie("coppauser", 1, -0);
 746                  $under_thirteen = true;
 747              }
 748              $mybb->request_method = "";
 749          }
 750          // Show DOB select form
 751          else
 752          {
 753              $plugins->run_hooks("member_register_coppa");
 754  
 755              my_unsetcookie("coppauser");
 756  
 757              $coppa_desc = $mybb->settings['coppa'] == 'deny' ? $lang->coppa_desc_for_deny : $lang->coppa_desc;
 758              eval("\$coppa = \"".$templates->get("member_register_coppa")."\";");
 759              output_page($coppa);
 760              exit;
 761          }
 762      }
 763  
 764      if((!isset($mybb->input['agree']) && !isset($mybb->input['regsubmit'])) && $fromreg == 0 || $mybb->request_method != "post")
 765      {
 766          $coppa_agreement = '';
 767          // Is this user a COPPA user? We need to show the COPPA agreement too
 768          if($mybb->settings['coppa'] != "disabled" && ($mybb->cookies['coppauser'] == 1 || $under_thirteen))
 769          {
 770              if($mybb->settings['coppa'] == "deny")
 771              {
 772                  error($lang->error_need_to_be_thirteen);
 773              }
 774              $lang->coppa_agreement_1 = $lang->sprintf($lang->coppa_agreement_1, $mybb->settings['bbname']);
 775              eval("\$coppa_agreement = \"".$templates->get("member_register_agreement_coppa")."\";");
 776          }
 777  
 778          $plugins->run_hooks("member_register_agreement");
 779  
 780          eval("\$agreement = \"".$templates->get("member_register_agreement")."\";");
 781          output_page($agreement);
 782      }
 783      else
 784      {
 785          $plugins->run_hooks("member_register_start");
 786  
 787          // JS validator extra
 788          if($mybb->settings['maxnamelength'] > 0 && $mybb->settings['minnamelength'] > 0)
 789          {
 790              $lang->js_validator_username_length = $lang->sprintf($lang->js_validator_username_length, $mybb->settings['minnamelength'], $mybb->settings['maxnamelength']);
 791          }
 792  
 793          $validator_javascript = "<script type=\"text/javascript\">
 794  $(document).ready(function() {
 795      $('#registration_form').validate({
 796          rules: {
 797              username: {
 798                  required: true,
 799                  minlength: {$mybb->settings['minnamelength']},
 800                  maxlength: {$mybb->settings['maxnamelength']},
 801                  remote: {
 802                      url: 'xmlhttp.php?action=username_availability',
 803                      type: 'post',
 804                      dataType: 'json',
 805                      data:
 806                      {
 807                          my_post_key: my_post_key
 808                      },
 809                  },
 810              },
 811              email: {
 812                  required: true,
 813                  email: true,
 814                  remote: {
 815                      url: 'xmlhttp.php?action=email_availability',
 816                      type: 'post',
 817                      dataType: 'json',
 818                      data:
 819                      {
 820                          my_post_key: my_post_key
 821                      },
 822                  },
 823              },
 824              email2: {
 825                  required: true,
 826                  email: true,
 827                  equalTo: '#email'
 828              },
 829          },
 830          messages: {
 831              username: {
 832                  minlength: '{$lang->js_validator_username_length}',
 833                  maxlength: '{$lang->js_validator_username_length}',
 834              },
 835              email: '{$lang->js_validator_invalid_email}',
 836              email2: '{$lang->js_validator_email_match}',
 837          },
 838          errorPlacement: function(error, element) {
 839              if(element.is(':checkbox') || element.is(':radio'))
 840                  error.insertAfter($('input[name=\"' + element.attr('name') + '\"]').last().next('span'));
 841              else
 842                  error.insertAfter(element);
 843          }
 844      });\n";
 845  
 846          if(isset($mybb->input['timezoneoffset']))
 847          {
 848              $timezoneoffset = $mybb->get_input('timezoneoffset');
 849          }
 850          else
 851          {
 852              $timezoneoffset = $mybb->settings['timezoneoffset'];
 853          }
 854          $tzselect = build_timezone_select("timezoneoffset", $timezoneoffset, true);
 855  
 856          $stylelist = build_theme_select("style");
 857  
 858          if($mybb->settings['usertppoptions'])
 859          {
 860              $tppoptions = '';
 861              $explodedtpp = explode(",", $mybb->settings['usertppoptions']);
 862              if(is_array($explodedtpp))
 863              {
 864                  foreach($explodedtpp as $val)
 865                  {
 866                      $val = trim($val);
 867                      $tpp_option = $lang->sprintf($lang->tpp_option, $val);
 868                      eval("\$tppoptions .= \"".$templates->get("usercp_options_tppselect_option")."\";");
 869                  }
 870              }
 871              eval("\$tppselect = \"".$templates->get("usercp_options_tppselect")."\";");
 872          }
 873          if($mybb->settings['userpppoptions'])
 874          {
 875              $pppoptions = '';
 876              $explodedppp = explode(",", $mybb->settings['userpppoptions']);
 877              if(is_array($explodedppp))
 878              {
 879                  foreach($explodedppp as $val)
 880                  {
 881                      $val = trim($val);
 882                      $ppp_option = $lang->sprintf($lang->ppp_option, $val);
 883                      eval("\$pppoptions .= \"".$templates->get("usercp_options_pppselect_option")."\";");
 884                  }
 885              }
 886              eval("\$pppselect = \"".$templates->get("usercp_options_pppselect")."\";");
 887          }
 888          if($mybb->settings['usereferrals'] == 1 && !$mybb->user['uid'])
 889          {
 890              if(isset($mybb->cookies['mybb']['referrer']))
 891              {
 892                  $query = $db->simple_select("users", "uid,username", "uid='".(int)$mybb->cookies['mybb']['referrer']."'");
 893                  $ref = $db->fetch_array($query);
 894                  $ref['username'] = htmlspecialchars_uni($ref['username']);
 895                  $referrername = $ref['username'];
 896              }
 897              elseif(isset($referrer))
 898              {
 899                  $query = $db->simple_select("users", "username", "uid='".(int)$referrer['uid']."'");
 900                  $ref = $db->fetch_array($query);
 901                  $ref['username'] = htmlspecialchars_uni($ref['username']);
 902                  $referrername = $ref['username'];
 903              }
 904              elseif(!empty($referrername))
 905              {
 906                  $ref = get_user_by_username($referrername);
 907                  if(!$ref['uid'])
 908                  {
 909                      $errors[] = $lang->error_badreferrer;
 910                  }
 911              }
 912              else
 913              {
 914                  $referrername = '';
 915              }
 916              if(isset($quickreg))
 917              {
 918                  $refbg = "trow1";
 919              }
 920              else
 921              {
 922                  $refbg = "trow2";
 923              }
 924              eval("\$referrer = \"".$templates->get("member_register_referrer")."\";");
 925          }
 926          else
 927          {
 928              $referrer = '';
 929          }
 930          $mybb->input['profile_fields'] = $mybb->get_input('profile_fields', MyBB::INPUT_ARRAY);
 931          // Custom profile fields baby!
 932          $altbg = "trow1";
 933          $requiredfields = $customfields = '';
 934  
 935          if($mybb->settings['regtype'] == "verify" || $mybb->settings['regtype'] == "admin" || $mybb->settings['regtype'] == "both" || $mybb->get_input('coppa', MyBB::INPUT_INT) == 1)
 936          {
 937              $usergroup = 5;
 938          }
 939          else
 940          {
 941              $usergroup = 2;
 942          }
 943  
 944          $pfcache = $cache->read('profilefields');
 945  
 946          if(is_array($pfcache))
 947          {
 948              foreach($pfcache as $profilefield)
 949              {
 950                  if($profilefield['required'] != 1 && $profilefield['registration'] != 1 || !is_member($profilefield['editableby'], array('usergroup' => $mybb->user['usergroup'], 'additionalgroups' => $usergroup)))
 951                  {
 952                      continue;
 953                  }
 954  
 955                  $code = $select = $val = $options = $expoptions = $useropts = '';
 956                  $seloptions = array();
 957                  $profilefield['type'] = htmlspecialchars_uni($profilefield['type']);
 958                  $thing = explode("\n", $profilefield['type'], "2");
 959                  $type = trim($thing[0]);
 960                  $options = $thing[1];
 961                  $select = '';
 962                  $field = "fid{$profilefield['fid']}";
 963                  $profilefield['description'] = htmlspecialchars_uni($profilefield['description']);
 964                  $profilefield['name'] = htmlspecialchars_uni($profilefield['name']);
 965                  if($errors && isset($mybb->input['profile_fields'][$field]))
 966                  {
 967                      $userfield = $mybb->input['profile_fields'][$field];
 968                  }
 969                  else
 970                  {
 971                      $userfield = '';
 972                  }
 973                  if($type == "multiselect")
 974                  {
 975                      if($errors)
 976                      {
 977                          $useropts = $userfield;
 978                      }
 979                      else
 980                      {
 981                          $useropts = explode("\n", $userfield);
 982                      }
 983                      if(is_array($useropts))
 984                      {
 985                          foreach($useropts as $key => $val)
 986                          {
 987                              $seloptions[$val] = $val;
 988                          }
 989                      }
 990                      $expoptions = explode("\n", $options);
 991                      if(is_array($expoptions))
 992                      {
 993                          foreach($expoptions as $key => $val)
 994                          {
 995                              $val = trim($val);
 996                              $val = str_replace("\n", "\\n", $val);
 997  
 998                              $sel = "";
 999                              if(isset($seloptions[$val]) && $val == $seloptions[$val])
1000                              {
1001                                  $sel = ' selected="selected"';
1002                              }
1003  
1004                              eval("\$select .= \"".$templates->get("usercp_profile_profilefields_select_option")."\";");
1005                          }
1006                          if(!$profilefield['length'])
1007                          {
1008                              $profilefield['length'] = 3;
1009                          }
1010  
1011                          eval("\$code = \"".$templates->get("usercp_profile_profilefields_multiselect")."\";");
1012                      }
1013                  }
1014                  elseif($type == "select")
1015                  {
1016                      $expoptions = explode("\n", $options);
1017                      if(is_array($expoptions))
1018                      {
1019                          foreach($expoptions as $key => $val)
1020                          {
1021                              $val = trim($val);
1022                              $val = str_replace("\n", "\\n", $val);
1023                              $sel = "";
1024                              if($val == $userfield)
1025                              {
1026                                  $sel = ' selected="selected"';
1027                              }
1028  
1029                              eval("\$select .= \"".$templates->get("usercp_profile_profilefields_select_option")."\";");
1030                          }
1031                          if(!$profilefield['length'])
1032                          {
1033                              $profilefield['length'] = 1;
1034                          }
1035  
1036                          eval("\$code = \"".$templates->get("usercp_profile_profilefields_select")."\";");
1037                      }
1038                  }
1039                  elseif($type == "radio")
1040                  {
1041                      $expoptions = explode("\n", $options);
1042                      if(is_array($expoptions))
1043                      {
1044                          foreach($expoptions as $key => $val)
1045                          {
1046                              $checked = "";
1047                              if($val == $userfield)
1048                              {
1049                                  $checked = 'checked="checked"';
1050                              }
1051  
1052                              eval("\$code .= \"".$templates->get("usercp_profile_profilefields_radio")."\";");
1053                          }
1054                      }
1055                  }
1056                  elseif($type == "checkbox")
1057                  {
1058                      if($errors)
1059                      {
1060                          $useropts = $userfield;
1061                      }
1062                      else
1063                      {
1064                          $useropts = explode("\n", $userfield);
1065                      }
1066                      if(is_array($useropts))
1067                      {
1068                          foreach($useropts as $key => $val)
1069                          {
1070                              $seloptions[$val] = $val;
1071                          }
1072                      }
1073                      $expoptions = explode("\n", $options);
1074                      if(is_array($expoptions))
1075                      {
1076                          foreach($expoptions as $key => $val)
1077                          {
1078                              $checked = "";
1079                              if(isset($seloptions[$val]) && $val == $seloptions[$val])
1080                              {
1081                                  $checked = 'checked="checked"';
1082                              }
1083  
1084                              eval("\$code .= \"".$templates->get("usercp_profile_profilefields_checkbox")."\";");
1085                          }
1086                      }
1087                  }
1088                  elseif($type == "textarea")
1089                  {
1090                      $value = htmlspecialchars_uni($userfield);
1091                      eval("\$code = \"".$templates->get("usercp_profile_profilefields_textarea")."\";");
1092                  }
1093                  else
1094                  {
1095                      $value = htmlspecialchars_uni($userfield);
1096                      $maxlength = "";
1097                      if($profilefield['maxlength'] > 0)
1098                      {
1099                          $maxlength = " maxlength=\"{$profilefield['maxlength']}\"";
1100                      }
1101  
1102                      eval("\$code = \"".$templates->get("usercp_profile_profilefields_text")."\";");
1103                  }
1104  
1105                  if($profilefield['required'] == 1)
1106                  {
1107                      // JS validator extra, choose correct selectors for everything except single select which always has value
1108                      if($type != 'select')
1109                      {
1110                          if($type == "textarea")
1111                          {
1112                              $inp_selector = "$('textarea[name=\"profile_fields[{$field}]\"]')";
1113                          }
1114                          elseif($type == "multiselect")
1115                          {
1116                              $inp_selector = "$('select[name=\"profile_fields[{$field}][]\"]')";
1117                          }
1118                          elseif($type == "checkbox")
1119                          {
1120                              $inp_selector = "$('input[name=\"profile_fields[{$field}][]\"]')";
1121                          }
1122                          else
1123                          {
1124                              $inp_selector = "$('input[name=\"profile_fields[{$field}]\"]')";
1125                          }
1126  
1127                          $validator_javascript .= "
1128      {$inp_selector}.rules('add', {
1129          required: true,
1130          messages: {
1131              required: '{$lang->js_validator_not_empty}'
1132          }
1133      });\n";
1134                      }
1135  
1136                      eval("\$requiredfields .= \"".$templates->get("member_register_customfield")."\";");
1137                  }
1138                  else
1139                  {
1140                      eval("\$customfields .= \"".$templates->get("member_register_customfield")."\";");
1141                  }
1142              }
1143  
1144              if($requiredfields)
1145              {
1146                  eval("\$requiredfields = \"".$templates->get("member_register_requiredfields")."\";");
1147              }
1148  
1149              if($customfields)
1150              {
1151                  eval("\$customfields = \"".$templates->get("member_register_additionalfields")."\";");
1152              }
1153          }
1154  
1155          if(!isset($fromreg))
1156          {
1157              $allownoticescheck = "checked=\"checked\"";
1158              $hideemailcheck = '';
1159              $receivepmscheck = "checked=\"checked\"";
1160              $pmnoticecheck = " checked=\"checked\"";
1161              $pmnotifycheck = '';
1162              $invisiblecheck = '';
1163              if($mybb->settings['dstcorrection'] == 1)
1164              {
1165                  $enabledstcheck = "checked=\"checked\"";
1166              }
1167              $no_auto_subscribe_selected = $instant_email_subscribe_selected = $instant_pm_subscribe_selected = $no_subscribe_selected = '';
1168              $dst_auto_selected = $dst_enabled_selected = $dst_disabled_selected = '';
1169              $username = $email = $email2 = '';
1170              $regerrors = '';
1171          }
1172          // Spambot registration image thingy
1173          if($mybb->settings['captchaimage'])
1174          {
1175              require_once  MYBB_ROOT.'inc/class_captcha.php';
1176              $captcha = new captcha(true, "member_register_regimage");
1177  
1178              if($captcha->html)
1179              {
1180                  $regimage = $captcha->html;
1181  
1182                  if($mybb->settings['captchaimage'] == 1)
1183                  {
1184                      // JS validator extra for our default CAPTCHA
1185                      $validator_javascript .= "
1186      $('#imagestring').rules('add', {
1187          required: true,
1188          remote:{
1189              url: 'xmlhttp.php?action=validate_captcha',
1190              type: 'post',
1191              dataType: 'json',
1192              data:
1193              {
1194                  imagehash: function () {
1195                      return $('#imagehash').val();
1196                  },
1197                  my_post_key: my_post_key
1198              },
1199          },
1200          messages: {
1201              remote: '{$lang->js_validator_no_image_text}'
1202          }
1203      });\n";
1204                  }
1205              }
1206          }
1207  
1208          // Security Question
1209          $questionbox = '';
1210          if($mybb->settings['securityquestion'])
1211          {
1212              $sid = generate_question();
1213              $query = $db->query("
1214                  SELECT q.question, s.sid
1215                  FROM ".TABLE_PREFIX."questionsessions s
1216                  LEFT JOIN ".TABLE_PREFIX."questions q ON (q.qid=s.qid)
1217                  WHERE q.active='1' AND s.sid='{$sid}'
1218              ");
1219              if($db->num_rows($query) > 0)
1220              {
1221                  $question = $db->fetch_array($query);
1222  
1223                  $question['question'] = htmlspecialchars_uni($question['question']);
1224                  $question['sid'] = htmlspecialchars_uni($question['sid']);
1225  
1226                  $refresh = '';
1227                  // Total questions
1228                  $q = $db->simple_select('questions', 'COUNT(qid) as num', 'active=1');
1229                  $num = $db->fetch_field($q, 'num');
1230                  if($num > 1)
1231                  {
1232                      eval("\$refresh = \"".$templates->get("member_register_question_refresh")."\";");
1233                  }
1234  
1235                  eval("\$questionbox = \"".$templates->get("member_register_question")."\";");
1236  
1237                  $validator_javascript .= "
1238      $('#answer').rules('add', {
1239          required: true,
1240          remote:{
1241              url: 'xmlhttp.php?action=validate_question',
1242              type: 'post',
1243              dataType: 'json',
1244              data:
1245              {
1246                  question: function () {
1247                      return $('#question_id').val();
1248                  },
1249                  my_post_key: my_post_key
1250              },
1251          },
1252          messages: {
1253              remote: '{$lang->js_validator_no_security_question}'
1254          }
1255      });\n";
1256              }
1257          }
1258  
1259          $hiddencaptcha = '';
1260          // Hidden CAPTCHA for Spambots
1261          if($mybb->settings['hiddencaptchaimage'])
1262          {
1263              $captcha_field = $mybb->settings['hiddencaptchaimagefield'];
1264  
1265              eval("\$hiddencaptcha = \"".$templates->get("member_register_hiddencaptcha")."\";");
1266          }
1267          if($mybb->settings['regtype'] != "randompass")
1268          {
1269              // JS validator extra
1270              $lang->js_validator_password_length = $lang->sprintf($lang->js_validator_password_length, $mybb->settings['minpasswordlength']);
1271  
1272              $validator_javascript .= "
1273      $.validator.addMethod('passwordSecurity', function(value, element, param) {
1274          return !(
1275                  ($('#email').val() != '' && value == $('#email').val()) ||
1276                  ($('#username').val() != '' && value == $('#username').val()) ||
1277                  ($('#email').val() != '' && value.indexOf($('#email').val()) > -1) ||
1278                  ($('#username').val() != '' && value.indexOf($('#username').val()) > -1) ||
1279                  ($('#email').val() != '' && $('#email').val().indexOf(value) > -1) ||
1280                  ($('#username').val() != '' && $('#username').val().indexOf(value) > -1)
1281          );
1282      }, '{$lang->js_validator_bad_password_security}');\n";
1283  
1284              // See if the board has "require complex passwords" enabled.
1285              if($mybb->settings['requirecomplexpasswords'] == 1)
1286              {
1287                  $lang->password = $lang->complex_password = $lang->sprintf($lang->complex_password, $mybb->settings['minpasswordlength']);
1288  
1289                  $validator_javascript .= "
1290      $('#password').rules('add', {
1291          required: true,
1292          minlength: {$mybb->settings['minpasswordlength']},
1293          remote:{
1294              url: 'xmlhttp.php?action=complex_password',
1295              type: 'post',
1296              dataType: 'json',
1297              data:
1298              {
1299                  my_post_key: my_post_key
1300              },
1301          },
1302          passwordSecurity: '',
1303          messages: {
1304              minlength: '{$lang->js_validator_password_length}',
1305              required: '{$lang->js_validator_password_length}',
1306              remote: '{$lang->js_validator_no_image_text}'
1307          }
1308      });\n";
1309              }
1310              else
1311              {
1312                  $validator_javascript .= "
1313      $('#password').rules('add', {
1314          required: true,
1315          minlength: {$mybb->settings['minpasswordlength']},
1316          passwordSecurity: '',
1317          messages: {
1318              minlength: '{$lang->js_validator_password_length}',
1319              required: '{$lang->js_validator_password_length}'
1320          }
1321      });\n";
1322              }
1323  
1324              $validator_javascript .= "
1325      $('#password2').rules('add', {
1326          required: true,
1327          minlength: {$mybb->settings['minpasswordlength']},
1328          equalTo: '#password',
1329          messages: {
1330              minlength: '{$lang->js_validator_password_length}',
1331              required: '{$lang->js_validator_password_length}',
1332              equalTo: '{$lang->js_validator_password_matches}'
1333          }
1334      });\n";
1335  
1336              eval("\$passboxes = \"".$templates->get("member_register_password")."\";");
1337          }
1338  
1339          $languages = $lang->get_languages();
1340          $langoptions = $boardlanguage = '';
1341          if(count($languages) > 1)
1342          {
1343              foreach($languages as $name => $language)
1344              {
1345                  $language = htmlspecialchars_uni($language);
1346  
1347                  $sel = '';
1348                  if($mybb->get_input('language') == $name)
1349                  {
1350                      $sel = " selected=\"selected\"";
1351                  }
1352  
1353                  eval('$langoptions .= "'.$templates->get('usercp_options_language_option').'";');
1354              }
1355  
1356              eval('$boardlanguage = "'.$templates->get('member_register_language').'";');
1357          }
1358  
1359          // Set the time so we can find automated signups
1360          $time = TIME_NOW;
1361  
1362          $plugins->run_hooks("member_register_end");
1363  
1364          $validator_javascript .= "
1365  });
1366  </script>\n";
1367  
1368          eval("\$registration = \"".$templates->get("member_register")."\";");
1369          output_page($registration);
1370      }
1371  }
1372  
1373  if($mybb->input['action'] == "activate")
1374  {
1375      $plugins->run_hooks("member_activate_start");
1376  
1377      if(isset($mybb->input['username']))
1378      {
1379          $mybb->input['username'] = $mybb->get_input('username');
1380          $options = array(
1381              'username_method' => $mybb->settings['username_method'],
1382              'fields' => '*',
1383          );
1384          $user = get_user_by_username($mybb->input['username'], $options);
1385          if(!$user)
1386          {
1387              switch($mybb->settings['username_method'])
1388              {
1389                  case 0:
1390                      error($lang->error_invalidpworusername);
1391                      break;
1392                  case 1:
1393                      error($lang->error_invalidpworusername1);
1394                      break;
1395                  case 2:
1396                      error($lang->error_invalidpworusername2);
1397                      break;
1398                  default:
1399                      error($lang->error_invalidpworusername);
1400                      break;
1401              }
1402          }
1403          $uid = $user['uid'];
1404      }
1405      else
1406      {
1407          $user = get_user($mybb->get_input('uid', MyBB::INPUT_INT));
1408      }
1409      if(isset($mybb->input['code']) && $user)
1410      {
1411          $query = $db->simple_select("awaitingactivation", "*", "uid='".$user['uid']."' AND (type='r' OR type='e' OR type='b')");
1412          $activation = $db->fetch_array($query);
1413          if(!$activation['uid'])
1414          {
1415              error($lang->error_alreadyactivated);
1416          }
1417          if($activation['code'] !== $mybb->get_input('code'))
1418          {
1419              error($lang->error_badactivationcode);
1420          }
1421  
1422          if($activation['type'] == "b" && $activation['validated'] == 1)
1423          {
1424              error($lang->error_alreadyvalidated);
1425          }
1426  
1427          $db->delete_query("awaitingactivation", "uid='".$user['uid']."' AND (type='r' OR type='e')");
1428  
1429          if($user['usergroup'] == 5 && $activation['type'] != "e" && $activation['type'] != "b")
1430          {
1431              $db->update_query("users", array("usergroup" => 2), "uid='".$user['uid']."'");
1432  
1433              $cache->update_awaitingactivation();
1434          }
1435          if($activation['type'] == "e")
1436          {
1437              $newemail = array(
1438                  "email" => $db->escape_string($activation['misc']),
1439              );
1440              $db->update_query("users", $newemail, "uid='".$user['uid']."'");
1441              $plugins->run_hooks("member_activate_emailupdated");
1442  
1443              redirect("usercp.php", $lang->redirect_emailupdated);
1444          }
1445          elseif($activation['type'] == "b")
1446          {
1447              $update = array(
1448                  "validated" => 1,
1449              );
1450              $db->update_query("awaitingactivation", $update, "uid='".$user['uid']."' AND type='b'");
1451              $plugins->run_hooks("member_activate_emailactivated");
1452  
1453              redirect("index.php", $lang->redirect_accountactivated_admin, "", true);
1454          }
1455          else
1456          {
1457              $plugins->run_hooks("member_activate_accountactivated");
1458  
1459              redirect("index.php", $lang->redirect_accountactivated);
1460          }
1461      }
1462      else
1463      {
1464          $plugins->run_hooks("member_activate_form");
1465  
1466          $code = htmlspecialchars_uni($mybb->get_input('code'));
1467  
1468          if(!isset($user['username']))
1469          {
1470              $user['username'] = '';
1471          }
1472          $user['username'] = htmlspecialchars_uni($user['username']);
1473  
1474          eval("\$activate = \"".$templates->get("member_activate")."\";");
1475          output_page($activate);
1476      }
1477  }
1478  
1479  if($mybb->input['action'] == "resendactivation")
1480  {
1481      $plugins->run_hooks("member_resendactivation");
1482  
1483      if($mybb->settings['regtype'] == "admin")
1484      {
1485          error($lang->error_activated_by_admin);
1486      }
1487      if($mybb->user['uid'] && $mybb->user['usergroup'] != 5)
1488      {
1489          error($lang->error_alreadyactivated);
1490      }
1491  
1492      $query = $db->simple_select("awaitingactivation", "*", "uid='".$mybb->user['uid']."' AND type='b'");
1493      $activation = $db->fetch_array($query);
1494  
1495      if($activation['validated'] == 1)
1496      {
1497          error($lang->error_activated_by_admin);
1498      }
1499  
1500      $plugins->run_hooks("member_resendactivation_end");
1501  
1502      eval("\$activate = \"".$templates->get("member_resendactivation")."\";");
1503      output_page($activate);
1504  }
1505  
1506  if($mybb->input['action'] == "do_resendactivation" && $mybb->request_method == "post")
1507  {
1508      $plugins->run_hooks("member_do_resendactivation_start");
1509  
1510      if($mybb->settings['regtype'] == "admin")
1511      {
1512          error($lang->error_activated_by_admin);
1513      }
1514  
1515      $query = $db->query("
1516          SELECT u.uid, u.username, u.usergroup, u.email, a.code, a.type, a.validated
1517          FROM ".TABLE_PREFIX."users u
1518          LEFT JOIN ".TABLE_PREFIX."awaitingactivation a ON (a.uid=u.uid AND a.type='r' OR a.type='b')
1519          WHERE u.email='".$db->escape_string($mybb->get_input('email'))."'
1520      ");
1521      $numusers = $db->num_rows($query);
1522      if($numusers < 1)
1523      {
1524          error($lang->error_invalidemail);
1525      }
1526      else
1527      {
1528          while($user = $db->fetch_array($query))
1529          {
1530              if($user['type'] == "b" && $user['validated'] == 1)
1531              {
1532                  error($lang->error_activated_by_admin);
1533              }
1534  
1535              if($user['usergroup'] == 5)
1536              {
1537                  if(!$user['code'])
1538                  {
1539                      $user['code'] = random_str();
1540                      $uid = $user['uid'];
1541                      $awaitingarray = array(
1542                          "uid" => $uid,
1543                          "dateline" => TIME_NOW,
1544                          "code" => $user['code'],
1545                          "type" => $user['type']
1546                      );
1547                      $db->insert_query("awaitingactivation", $awaitingarray);
1548                  }
1549                  $username = $user['username'];
1550                  $email = $user['email'];
1551                  $activationcode = $user['code'];
1552                  $emailsubject = $lang->sprintf($lang->emailsubject_activateaccount, $mybb->settings['bbname']);
1553                  switch($mybb->settings['username_method'])
1554                  {
1555                      case 0:
1556                          $emailmessage = $lang->sprintf($lang->email_activateaccount, $user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user['uid'], $activationcode);
1557                          break;
1558                      case 1:
1559                          $emailmessage = $lang->sprintf($lang->email_activateaccount1, $user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user['uid'], $activationcode);
1560                          break;
1561                      case 2:
1562                          $emailmessage = $lang->sprintf($lang->email_activateaccount2, $user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user['uid'], $activationcode);
1563                          break;
1564                      default:
1565                          $emailmessage = $lang->sprintf($lang->email_activateaccount, $user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $user['uid'], $activationcode);
1566                          break;
1567                  }
1568                  my_mail($email, $emailsubject, $emailmessage);
1569              }
1570          }
1571          $plugins->run_hooks("member_do_resendactivation_end");
1572  
1573          redirect("index.php", $lang->redirect_activationresent);
1574      }
1575  }
1576  
1577  if($mybb->input['action'] == "lostpw")
1578  {
1579      $plugins->run_hooks("member_lostpw");
1580  
1581      eval("\$lostpw = \"".$templates->get("member_lostpw")."\";");
1582      output_page($lostpw);
1583  }
1584  
1585  if($mybb->input['action'] == "do_lostpw" && $mybb->request_method == "post")
1586  {
1587      $plugins->run_hooks("member_do_lostpw_start");
1588  
1589      $email = $db->escape_string($email);
1590      $query = $db->simple_select("users", "*", "email='".$db->escape_string($mybb->get_input('email'))."'");
1591      $numusers = $db->num_rows($query);
1592      if($numusers < 1)
1593      {
1594          error($lang->error_invalidemail);
1595      }
1596      else
1597      {
1598          while($user = $db->fetch_array($query))
1599          {
1600              $db->delete_query("awaitingactivation", "uid='{$user['uid']}' AND type='p'");
1601              $user['activationcode'] = random_str(30);
1602              $now = TIME_NOW;
1603              $uid = $user['uid'];
1604              $awaitingarray = array(
1605                  "uid" => $user['uid'],
1606                  "dateline" => TIME_NOW,
1607                  "code" => $user['activationcode'],
1608                  "type" => "p"
1609              );
1610              $db->insert_query("awaitingactivation", $awaitingarray);
1611              $username = $user['username'];
1612              $email = $user['email'];
1613              $activationcode = $user['activationcode'];
1614              $emailsubject = $lang->sprintf($lang->emailsubject_lostpw, $mybb->settings['bbname']);
1615              switch($mybb->settings['username_method'])
1616              {
1617                  case 0:
1618                      $emailmessage = $lang->sprintf($lang->email_lostpw, $username, $mybb->settings['bbname'], $mybb->settings['bburl'], $uid, $activationcode);
1619                      break;
1620                  case 1:
1621                      $emailmessage = $lang->sprintf($lang->email_lostpw1, $username, $mybb->settings['bbname'], $mybb->settings['bburl'], $uid, $activationcode);
1622                      break;
1623                  case 2:
1624                      $emailmessage = $lang->sprintf($lang->email_lostpw2, $username, $mybb->settings['bbname'], $mybb->settings['bburl'], $uid, $activationcode);
1625                      break;
1626                  default:
1627                      $emailmessage = $lang->sprintf($lang->email_lostpw, $username, $mybb->settings['bbname'], $mybb->settings['bburl'], $uid, $activationcode);
1628                      break;
1629              }
1630              my_mail($email, $emailsubject, $emailmessage);
1631          }
1632      }
1633      $plugins->run_hooks("member_do_lostpw_end");
1634  
1635      redirect("index.php", $lang->redirect_lostpwsent, "", true);
1636  }
1637  
1638  if($mybb->input['action'] == "resetpassword")
1639  {
1640      $plugins->run_hooks("member_resetpassword_start");
1641  
1642      if(isset($mybb->input['username']))
1643      {
1644          $mybb->input['username'] = $mybb->get_input('username');
1645          $options = array(
1646              'username_method' => $mybb->settings['username_method'],
1647              'fields' => '*',
1648          );
1649          $user = get_user_by_username($mybb->input['username'], $options);
1650          if(!$user)
1651          {
1652              switch($mybb->settings['username_method'])
1653              {
1654                  case 0:
1655                      error($lang->error_invalidpworusername);
1656                      break;
1657                  case 1:
1658                      error($lang->error_invalidpworusername1);
1659                      break;
1660                  case 2:
1661                      error($lang->error_invalidpworusername2);
1662                      break;
1663                  default:
1664                      error($lang->error_invalidpworusername);
1665                      break;
1666              }
1667          }
1668      }
1669      else
1670      {
1671          $user = get_user($mybb->get_input('uid', MyBB::INPUT_INT));
1672      }
1673  
1674      if(isset($mybb->input['code']) && $user)
1675      {
1676          $query = $db->simple_select("awaitingactivation", "code", "uid='".$user['uid']."' AND type='p'");
1677          $activationcode = $db->fetch_field($query, 'code');
1678          $now = TIME_NOW;
1679          if(!$activationcode || $activationcode !== $mybb->get_input('code'))
1680          {
1681              error($lang->error_badlostpwcode);
1682          }
1683          $db->delete_query("awaitingactivation", "uid='".$user['uid']."' AND type='p'");
1684          $username = $user['username'];
1685  
1686          // Generate a new password, then update it
1687          $password_length = (int)$mybb->settings['minpasswordlength'];
1688  
1689          if($password_length < 8)
1690          {
1691              $password_length = min(8, (int)$mybb->settings['maxpasswordlength']);
1692          }
1693  
1694          // Set up user handler.
1695          require_once  MYBB_ROOT.'inc/datahandlers/user.php';
1696          $userhandler = new UserDataHandler('update');
1697  
1698          while(!$userhandler->verify_password())
1699          {
1700              $password = random_str($password_length, $mybb->settings['requirecomplexpasswords']);
1701  
1702              $userhandler->set_data(array(
1703                  'uid'        => $user['uid'],
1704                  'username'    => $user['username'],
1705                  'email'        => $user['email'],
1706                  'password'    => $password
1707              ));
1708  
1709              $userhandler->set_validated(true);
1710              $userhandler->errors = array();
1711          }
1712  
1713          $userhandler->update_user();
1714  
1715          $logindetails = array(
1716              'salt'        => $userhandler->data['salt'],
1717              'password'    => $userhandler->data['saltedpw'],
1718              'loginkey'    => $userhandler->data['loginkey'],
1719          );
1720  
1721          $email = $user['email'];
1722  
1723          $plugins->run_hooks("member_resetpassword_process");
1724  
1725          $emailsubject = $lang->sprintf($lang->emailsubject_passwordreset, $mybb->settings['bbname']);
1726          $emailmessage = $lang->sprintf($lang->email_passwordreset, $username, $mybb->settings['bbname'], $password);
1727          my_mail($email, $emailsubject, $emailmessage);
1728  
1729          $plugins->run_hooks("member_resetpassword_reset");
1730  
1731          error($lang->redirect_passwordreset);
1732      }
1733      else
1734      {
1735          $plugins->run_hooks("member_resetpassword_form");
1736  
1737          switch($mybb->settings['username_method'])
1738          {
1739              case 0:
1740                  $lang_username = $lang->username;
1741                  break;
1742              case 1:
1743                  $lang_username = $lang->username1;
1744                  break;
1745              case 2:
1746                  $lang_username = $lang->username2;
1747                  break;
1748              default:
1749                  $lang_username = $lang->username;
1750                  break;
1751          }
1752  
1753          $code = $mybb->get_input('code');
1754  
1755          if(!isset($user['username']))
1756          {
1757              $user['username'] = '';
1758          }
1759          $user['username'] = htmlspecialchars_uni($user['username']);
1760  
1761          eval("\$activate = \"".$templates->get("member_resetpassword")."\";");
1762          output_page($activate);
1763      }
1764  }
1765  
1766  $do_captcha = $correct = false;
1767  $inline_errors = "";
1768  if($mybb->input['action'] == "do_login" && $mybb->request_method == "post")
1769  {
1770      verify_post_check($mybb->get_input('my_post_key'));
1771  
1772      $errors = array();
1773  
1774      $plugins->run_hooks("member_do_login_start");
1775  
1776      require_once  MYBB_ROOT."inc/datahandlers/login.php";
1777      $loginhandler = new LoginDataHandler("get");
1778  
1779      if($mybb->get_input('quick_password') && $mybb->get_input('quick_username'))
1780      {
1781          $mybb->input['password'] = $mybb->get_input('quick_password');
1782          $mybb->input['username'] = $mybb->get_input('quick_username');
1783          $mybb->input['remember'] = $mybb->get_input('quick_remember');
1784      }
1785  
1786      $user = array(
1787          'username' => $mybb->get_input('username'),
1788          'password' => $mybb->get_input('password'),
1789          'remember' => $mybb->get_input('remember'),
1790          'imagestring' => $mybb->get_input('imagestring')
1791      );
1792  
1793      $options = array(
1794          'fields' => 'loginattempts',
1795          'username_method' => (int)$mybb->settings['username_method'],
1796      );
1797  
1798      $user_loginattempts = get_user_by_username($user['username'], $options);
1799      $user['loginattempts'] = (int)$user_loginattempts['loginattempts'];
1800  
1801      $loginhandler->set_data($user);
1802      $validated = $loginhandler->validate_login();
1803  
1804      if(!$validated)
1805      {
1806          $mybb->input['action'] = "login";
1807          $mybb->request_method = "get";
1808  
1809          $login_user = get_user_by_username($user['username'], array('fields' => 'uid'));
1810  
1811          // Is a fatal call if user has had too many tries
1812          $logins = login_attempt_check($login_user['uid']);
1813  
1814          $db->update_query("users", array('loginattempts' => 'loginattempts+1'), "uid='".(int)$loginhandler->login_data['uid']."'", 1, true);
1815  
1816          $errors = $loginhandler->get_friendly_errors();
1817  
1818          $user['loginattempts'] = (int)$loginhandler->login_data['loginattempts'];
1819  
1820          // If we need a captcha set it here
1821          if($mybb->settings['failedcaptchalogincount'] > 0 && ($user['loginattempts'] > $mybb->settings['failedcaptchalogincount'] || (int)$mybb->cookies['loginattempts'] > $mybb->settings['failedcaptchalogincount']))
1822          {
1823              $do_captcha = true;
1824              $correct = $loginhandler->captcha_verified;
1825          }
1826      }
1827      else if($validated && $loginhandler->captcha_verified == true)
1828      {
1829          // Successful login
1830          if($loginhandler->login_data['coppauser'])
1831          {
1832              error($lang->error_awaitingcoppa);
1833          }
1834  
1835          $loginhandler->complete_login();
1836  
1837          $plugins->run_hooks("member_do_login_end");
1838  
1839          $mybb->input['url'] = $mybb->get_input('url');
1840  
1841          if(!empty($mybb->input['url']) && my_strpos(basename($mybb->input['url']), 'member.php') === false && !preg_match('#^javascript:#i', $mybb->input['url']))
1842          {
1843              if((my_strpos(basename($mybb->input['url']), 'newthread.php') !== false || my_strpos(basename($mybb->input['url']), 'newreply.php') !== false) && my_strpos($mybb->input['url'], '&processed=1') !== false)
1844              {
1845                  $mybb->input['url'] = str_replace('&processed=1', '', $mybb->input['url']);
1846              }
1847  
1848              $mybb->input['url'] = str_replace('&amp;', '&', $mybb->input['url']);
1849  
1850              // Redirect to the URL if it is not member.php
1851              redirect($mybb->input['url'], $lang->redirect_loggedin);
1852          }
1853          else
1854          {
1855  
1856              redirect("index.php", $lang->redirect_loggedin);
1857          }
1858      }
1859  
1860      $plugins->run_hooks("member_do_login_end");
1861  }
1862  
1863  if($mybb->input['action'] == "login")
1864  {
1865      $plugins->run_hooks("member_login");
1866  
1867      $member_loggedin_notice = "";
1868      if($mybb->user['uid'] != 0)
1869      {
1870          $mybb->user['username'] = htmlspecialchars_uni($mybb->user['username']);
1871          $lang->already_logged_in = $lang->sprintf($lang->already_logged_in, build_profile_link($mybb->user['username'], $mybb->user['uid']));
1872          eval("\$member_loggedin_notice = \"".$templates->get("member_loggedin_notice")."\";");
1873      }
1874  
1875      // Checks to make sure the user can login; they haven't had too many tries at logging in.
1876      // Is a fatal call if user has had too many tries. This particular check uses cookies, as a uid is not set yet
1877      // and we can't check loginattempts in the db
1878      login_attempt_check();
1879  
1880      // Redirect to the page where the user came from, but not if that was the login page.
1881      if(isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], "action=login") === false)
1882      {
1883          $redirect_url = htmlentities($_SERVER['HTTP_REFERER']);
1884      }
1885      else
1886      {
1887          $redirect_url = '';
1888      }
1889  
1890      $captcha = '';
1891      // Show captcha image for guests if enabled and only if we have to do
1892      if($mybb->settings['captchaimage'] && $do_captcha == true)
1893      {
1894          require_once  MYBB_ROOT.'inc/class_captcha.php';
1895          $login_captcha = new captcha(false, "post_captcha");
1896  
1897          if($login_captcha->type == 1)
1898          {
1899              if(!$correct)
1900              {
1901                  $login_captcha->build_captcha();
1902              }
1903              else
1904              {
1905                  $captcha = $login_captcha->build_hidden_captcha();
1906              }
1907          }
1908          elseif(in_array($login_captcha->type, array(2, 4, 5)))
1909          {
1910              $login_captcha->build_recaptcha();
1911          }
1912  
1913          if($login_captcha->html)
1914          {
1915              $captcha = $login_captcha->html;
1916          }
1917      }
1918  
1919      $username = "";
1920      $password = "";
1921      if(isset($mybb->input['username']) && $mybb->request_method == "post")
1922      {
1923          $username = htmlspecialchars_uni($mybb->get_input('username'));
1924      }
1925  
1926      if(isset($mybb->input['password']) && $mybb->request_method == "post")
1927      {
1928          $password = htmlspecialchars_uni($mybb->get_input('password'));
1929      }
1930  
1931      if(!empty($errors))
1932      {
1933          $mybb->input['action'] = "login";
1934          $mybb->request_method = "get";
1935  
1936          $inline_errors = inline_error($errors);
1937      }
1938  
1939      switch($mybb->settings['username_method'])
1940      {
1941          case 1:
1942              $lang->username = $lang->username1;
1943              break;
1944          case 2:
1945              $lang->username = $lang->username2;
1946              break;
1947          default:
1948              break;
1949      }
1950  
1951      $plugins->run_hooks("member_login_end");
1952  
1953      eval("\$login = \"".$templates->get("member_login")."\";");
1954      output_page($login);
1955  }
1956  
1957  if($mybb->input['action'] == "logout")
1958  {
1959      $plugins->run_hooks("member_logout_start");
1960  
1961      if(!$mybb->user['uid'])
1962      {
1963          redirect("index.php", $lang->redirect_alreadyloggedout);
1964      }
1965  
1966      // Check session ID if we have one
1967      if(isset($mybb->input['sid']) && $mybb->get_input('sid') !== $session->sid)
1968      {
1969          error($lang->error_notloggedout);
1970      }
1971      // Otherwise, check logoutkey
1972      else if(!isset($mybb->input['sid']) && $mybb->get_input('logoutkey') !== $mybb->user['logoutkey'])
1973      {
1974          error($lang->error_notloggedout);
1975      }
1976  
1977      my_unsetcookie("mybbuser");
1978      my_unsetcookie("sid");
1979  
1980      if($mybb->user['uid'])
1981      {
1982          $time = TIME_NOW;
1983          // Run this after the shutdown query from session system
1984          $db->shutdown_query("UPDATE ".TABLE_PREFIX."users SET lastvisit='{$time}', lastactive='{$time}' WHERE uid='{$mybb->user['uid']}'");
1985          $db->delete_query("sessions", "sid = '{$session->sid}'");
1986      }
1987  
1988      $plugins->run_hooks("member_logout_end");
1989  
1990      redirect("index.php", $lang->redirect_loggedout);
1991  }
1992  
1993  if($mybb->input['action'] == "viewnotes")
1994  {
1995      $uid = $mybb->get_input('uid', MyBB::INPUT_INT);
1996      $user = get_user($uid);
1997  
1998      // Make sure we are looking at a real user here.
1999      if(!$user)
2000      {
2001          error($lang->error_nomember);
2002      }
2003  
2004      if($mybb->user['uid'] == 0 || $mybb->usergroup['canmodcp'] != 1)
2005      {
2006          error_no_permission();
2007      }
2008  
2009      $user['username'] = htmlspecialchars_uni($user['username']);
2010      $lang->view_notes_for = $lang->sprintf($lang->view_notes_for, $user['username']);
2011  
2012      $user['usernotes'] = nl2br(htmlspecialchars_uni($user['usernotes']));
2013  
2014      $plugins->run_hooks('member_viewnotes');
2015  
2016      eval("\$viewnotes = \"".$templates->get("member_viewnotes", 1, 0)."\";");
2017      echo $viewnotes;
2018      exit;
2019  }
2020  
2021  if($mybb->input['action'] == "profile")
2022  {
2023      $plugins->run_hooks("member_profile_start");
2024  
2025      if($mybb->usergroup['canviewprofiles'] == 0)
2026      {
2027          error_no_permission();
2028      }
2029  
2030      $uid = $mybb->get_input('uid', MyBB::INPUT_INT);
2031      if($uid)
2032      {
2033          $memprofile = get_user($uid);
2034      }
2035      elseif($mybb->user['uid'])
2036      {
2037          $memprofile = $mybb->user;
2038      }
2039      else
2040      {
2041          $memprofile = false;
2042      }
2043  
2044      if(!$memprofile)
2045      {
2046          error($lang->error_nomember);
2047      }
2048  
2049      $uid = $memprofile['uid'];
2050  
2051      $me_username = $memprofile['username'];
2052      $memprofile['username'] = htmlspecialchars_uni($memprofile['username']);
2053      $lang->profile = $lang->sprintf($lang->profile, $memprofile['username']);
2054  
2055      // Get member's permissions
2056      $memperms = user_permissions($memprofile['uid']);
2057  
2058      // Set display group
2059      $displaygroupfields = array("title", "description", "namestyle", "usertitle", "stars", "starimage", "image");
2060  
2061      if(!$memprofile['displaygroup'])
2062      {
2063          $memprofile['displaygroup'] = $memprofile['usergroup'];
2064      }
2065  
2066      $displaygroup = usergroup_displaygroup($memprofile['displaygroup']);
2067      if(is_array($displaygroup))
2068      {
2069          $memperms = array_merge($memperms, $displaygroup);
2070      }
2071  
2072      $lang->nav_profile = $lang->sprintf($lang->nav_profile, $memprofile['username']);
2073      add_breadcrumb($lang->nav_profile);
2074  
2075      $lang->users_forum_info = $lang->sprintf($lang->users_forum_info, $memprofile['username']);
2076      $lang->users_contact_details = $lang->sprintf($lang->users_contact_details, $memprofile['username']);
2077      $lang->send_pm = $lang->sprintf($lang->send_pm, $memprofile['username']);
2078      $lang->away_note = $lang->sprintf($lang->away_note, $memprofile['username']);
2079      $lang->users_additional_info = $lang->sprintf($lang->users_additional_info, $memprofile['username']);
2080      $lang->users_signature = $lang->sprintf($lang->users_signature, $memprofile['username']);
2081      $lang->send_user_email = $lang->sprintf($lang->send_user_email, $memprofile['username']);
2082  
2083      $useravatar = format_avatar($memprofile['avatar'], $memprofile['avatardimensions']);
2084      eval("\$avatar = \"".$templates->get("member_profile_avatar")."\";");
2085  
2086      $website = $sendemail = $sendpm = $contact_details = '';
2087  
2088      if(my_validate_url($memprofile['website']) && !is_member($mybb->settings['hidewebsite']) && $memperms['canchangewebsite'] == 1)
2089      {
2090          $memprofile['website'] = htmlspecialchars_uni($memprofile['website']);
2091          $bgcolor = alt_trow();
2092          eval("\$website = \"".$templates->get("member_profile_website")."\";");
2093      }
2094  
2095      if($memprofile['hideemail'] != 1 && (my_strpos(",".$memprofile['ignorelist'].",", ",".$mybb->user['uid'].",") === false || $mybb->usergroup['cansendemailoverride'] != 0))
2096      {
2097          $bgcolor = alt_trow();
2098          eval("\$sendemail = \"".$templates->get("member_profile_email")."\";");
2099      }
2100  
2101      if($mybb->settings['enablepms'] != 0 && (($memprofile['receivepms'] != 0 && $memperms['canusepms'] != 0 && my_strpos(",".$memprofile['ignorelist'].",", ",".$mybb->user['uid'].",") === false) || $mybb->usergroup['canoverridepm'] == 1))
2102      {
2103          $bgcolor = alt_trow();
2104          eval('$sendpm = "'.$templates->get("member_profile_pm").'";');
2105      }
2106  
2107      $contact_fields = array();
2108      $any_contact_field = false;
2109      foreach(array('icq', 'yahoo', 'skype', 'google') as $field)
2110      {
2111          $contact_fields[$field] = '';
2112          $settingkey = 'allow'.$field.'field';
2113  
2114          if(!empty($memprofile[$field]) && is_member($mybb->settings[$settingkey], array('usergroup' => $memprofile['usergroup'], 'additionalgroups' => $memprofile['additionalgroups'])))
2115          {
2116              $any_contact_field = true;
2117  
2118              if($field == 'icq')
2119              {
2120                  $memprofile[$field] = (int)$memprofile[$field];
2121              }
2122              else
2123              {
2124                  $memprofile[$field] = htmlspecialchars_uni($memprofile[$field]);
2125              }
2126              $tmpl = 'member_profile_contact_fields_'.$field;
2127  
2128              $bgcolors[$field] = alt_trow();
2129              eval('$contact_fields[\''.$field.'\'] = "'.$templates->get($tmpl).'";');
2130          }
2131      }
2132  
2133      if($any_contact_field || $sendemail || $sendpm || $website)
2134      {
2135          eval('$contact_details = "'.$templates->get("member_profile_contact_details").'";');
2136      }
2137  
2138      $signature = '';
2139      if($memprofile['signature'] && ($memprofile['suspendsignature'] == 0 || $memprofile['suspendsigtime'] < TIME_NOW) && !is_member($mybb->settings['hidesignatures']) && $memperms['canusesig'] && $memperms['canusesigxposts'] <= $memprofile['postnum'])
2140      {
2141          $sig_parser = array(
2142              "allow_html" => $mybb->settings['sightml'],
2143              "allow_mycode" => $mybb->settings['sigmycode'],
2144              "allow_smilies" => $mybb->settings['sigsmilies'],
2145              "allow_imgcode" => $mybb->settings['sigimgcode'],
2146              "me_username" => $me_username,
2147              "filter_badwords" => 1
2148          );
2149  
2150          if($memperms['signofollow'])
2151          {
2152              $sig_parser['nofollow_on'] = 1;
2153          }
2154  
2155          if($mybb->user['showimages'] != 1 && $mybb->user['uid'] != 0 || $mybb->settings['guestimages'] != 1 && $mybb->user['uid'] == 0)
2156          {
2157              $sig_parser['allow_imgcode'] = 0;
2158          }
2159  
2160          $memprofile['signature'] = $parser->parse_message($memprofile['signature'], $sig_parser);
2161          eval("\$signature = \"".$templates->get("member_profile_signature")."\";");
2162      }
2163  
2164      $daysreg = (TIME_NOW - $memprofile['regdate']) / (24*3600);
2165  
2166      if($daysreg < 1)
2167      {
2168          $daysreg = 1;
2169      }
2170  
2171      $stats = $cache->read("stats");
2172  
2173      // Format post count, per day count and percent of total
2174      $ppd = $memprofile['postnum'] / $daysreg;
2175      $ppd = round($ppd, 2);
2176      if($ppd > $memprofile['postnum'])
2177      {
2178          $ppd = $memprofile['postnum'];
2179      }
2180  
2181      $numposts = $stats['numposts'];
2182      if($numposts == 0)
2183      {
2184          $post_percent = "0";
2185      }
2186      else
2187      {
2188          $post_percent = $memprofile['postnum']*100/$numposts;
2189          $post_percent = round($post_percent, 2);
2190      }
2191  
2192      if($post_percent > 100)
2193      {
2194          $post_percent = 100;
2195      }
2196  
2197      // Format thread count, per day count and percent of total
2198      $tpd = $memprofile['threadnum'] / $daysreg;
2199      $tpd = round($tpd, 2);
2200      if($tpd > $memprofile['threadnum'])
2201      {
2202          $tpd = $memprofile['threadnum'];
2203      }
2204  
2205      $numthreads = $stats['numthreads'];
2206      if($numthreads == 0)
2207      {
2208          $thread_percent = "0";
2209      }
2210      else
2211      {
2212          $thread_percent = $memprofile['threadnum']*100/$numthreads;
2213          $thread_percent = round($thread_percent, 2);
2214      }
2215  
2216      if($thread_percent > 100)
2217      {
2218          $thread_percent = 100;
2219      }
2220  
2221      $findposts = $findthreads = '';
2222      if($mybb->usergroup['cansearch'] == 1)
2223      {
2224          eval("\$findposts = \"".$templates->get("member_profile_findposts")."\";");
2225          eval("\$findthreads = \"".$templates->get("member_profile_findthreads")."\";");
2226      }
2227  
2228      $awaybit = '';
2229      if($memprofile['away'] == 1 && $mybb->settings['allowaway'] != 0)
2230      {
2231          $lang->away_note = $lang->sprintf($lang->away_note, $memprofile['username']);
2232          $awaydate = my_date($mybb->settings['dateformat'], $memprofile['awaydate']);
2233          if(!empty($memprofile['awayreason']))
2234          {
2235              $reason = $parser->parse_badwords($memprofile['awayreason']);
2236              $awayreason = htmlspecialchars_uni($reason);
2237          }
2238          else
2239          {
2240              $awayreason = $lang->away_no_reason;
2241          }
2242          if($memprofile['returndate'] == '')
2243          {
2244              $returndate = "$lang->unknown";
2245          }
2246          else
2247          {
2248              $returnhome = explode("-", $memprofile['returndate']);
2249  
2250              // PHP native date functions use integers so timestamps for years after 2038 will not work
2251              // Thus we use adodb_mktime
2252              if($returnhome[2] >= 2038)
2253              {
2254                  require_once  MYBB_ROOT."inc/functions_time.php";
2255                  $returnmkdate = adodb_mktime(0, 0, 0, $returnhome[1], $returnhome[0], $returnhome[2]);
2256                  $returndate = my_date($mybb->settings['dateformat'], $returnmkdate, "", 1, true);
2257              }
2258              else
2259              {
2260                  $returnmkdate = mktime(0, 0, 0, $returnhome[1], $returnhome[0], $returnhome[2]);
2261                  $returndate = my_date($mybb->settings['dateformat'], $returnmkdate);
2262              }
2263  
2264              // If our away time has expired already, we should be back, right?
2265              if($returnmkdate < TIME_NOW)
2266              {
2267                  $db->update_query('users', array('away' => '0', 'awaydate' => '0', 'returndate' => '', 'awayreason' => ''), 'uid=\''.(int)$memprofile['uid'].'\'');
2268  
2269                  // Update our status to "not away"
2270                  $memprofile['away'] = 0;
2271              }
2272          }
2273  
2274          // Check if our away status is set to 1, it may have been updated already (see a few lines above)
2275          if($memprofile['away'] == 1)
2276          {
2277              eval("\$awaybit = \"".$templates->get("member_profile_away")."\";");
2278          }
2279      }
2280  
2281      $memprofile['timezone'] = (float)$memprofile['timezone'];
2282  
2283      if($memprofile['dst'] == 1)
2284      {
2285          $memprofile['timezone']++;
2286          if(my_substr($memprofile['timezone'], 0, 1) != "-")
2287          {
2288              $memprofile['timezone'] = "+{$memprofile['timezone']}";
2289          }
2290      }
2291  
2292      $memregdate = my_date($mybb->settings['dateformat'], $memprofile['regdate']);
2293      $memlocaldate = gmdate($mybb->settings['dateformat'], TIME_NOW + ($memprofile['timezone'] * 3600));
2294      $memlocaltime = gmdate($mybb->settings['timeformat'], TIME_NOW + ($memprofile['timezone'] * 3600));
2295  
2296      $localtime = $lang->sprintf($lang->local_time_format, $memlocaldate, $memlocaltime);
2297  
2298      if($memprofile['lastactive'])
2299      {
2300          $memlastvisitdate = my_date($mybb->settings['dateformat'], $memprofile['lastactive']);
2301          $memlastvisitsep = $lang->comma;
2302          $memlastvisittime = my_date($mybb->settings['timeformat'], $memprofile['lastactive']);
2303      }
2304      else
2305      {
2306          $memlastvisitdate = $lang->lastvisit_never;
2307          $memlastvisitsep = '';
2308          $memlastvisittime = '';
2309      }
2310  
2311      if($memprofile['birthday'])
2312      {
2313          $membday = explode("-", $memprofile['birthday']);
2314  
2315          if($memprofile['birthdayprivacy'] != 'none')
2316          {
2317              if($membday[0] && $membday[1] && $membday[2])
2318              {
2319                  $lang->membdayage = $lang->sprintf($lang->membdayage, get_age($memprofile['birthday']));
2320  
2321                  $bdayformat = fix_mktime($mybb->settings['dateformat'], $membday[2]);
2322                  $membday = mktime(0, 0, 0, $membday[1], $membday[0], $membday[2]);
2323                  $membday = date($bdayformat, $membday);
2324  
2325                  $membdayage = $lang->membdayage;
2326              }
2327              elseif($membday[2])
2328              {
2329                  $membday = mktime(0, 0, 0, 1, 1, $membday[2]);
2330                  $membday = date("Y", $membday);
2331                  $membdayage = '';
2332              }
2333              else
2334              {
2335                  $membday = mktime(0, 0, 0, $membday[1], $membday[0], 0);
2336                  $membday = date("F j", $membday);
2337                  $membdayage = '';
2338              }
2339          }
2340  
2341          if($memprofile['birthdayprivacy'] == 'age')
2342          {
2343              $membday = $lang->birthdayhidden;
2344          }
2345          else if($memprofile['birthdayprivacy'] == 'none')
2346          {
2347              $membday = $lang->birthdayhidden;
2348              $membdayage = '';
2349          }
2350      }
2351      else
2352      {
2353          $membday = $lang->not_specified;
2354          $membdayage = '';
2355      }
2356  
2357      // Get the user title for this user
2358      unset($usertitle);
2359      unset($stars);
2360      $starimage = '';
2361      if(trim($memprofile['usertitle']) != '')
2362      {
2363          // User has custom user title
2364          $usertitle = $memprofile['usertitle'];
2365      }
2366      elseif(trim($memperms['usertitle']) != '')
2367      {
2368          // User has group title
2369          $usertitle = $memperms['usertitle'];
2370      }
2371      else
2372      {
2373          // No usergroup title so get a default one
2374          $usertitles = $cache->read('usertitles');
2375  
2376          if(is_array($usertitles))
2377          {
2378              foreach($usertitles as $title)
2379              {
2380                  if($memprofile['postnum'] >= $title['posts'])
2381                  {
2382                      $usertitle = $title['title'];
2383                      $stars = $title['stars'];
2384                      $starimage = $title['starimage'];
2385  
2386                      break;
2387                  }
2388              }
2389          }
2390      }
2391  
2392      $usertitle = htmlspecialchars_uni($usertitle);
2393  
2394      if($memperms['stars'] || $memperms['usertitle'])
2395      {
2396          // Set the number of stars if display group has constant number of stars
2397          $stars = $memperms['stars'];
2398      }
2399      elseif(!$stars)
2400      {
2401          if(!is_array($usertitles))
2402          {
2403              $usertitles = $cache->read('usertitles');
2404          }
2405  
2406          // This is for cases where the user has a title, but the group has no defined number of stars (use number of stars as per default usergroups)
2407          if(is_array($usertitles))
2408          {
2409              foreach($usertitles as $title)
2410              {
2411                  if($memprofile['postnum'] >= $title['posts'])
2412                  {
2413                      $stars = $title['stars'];
2414                      $starimage = $title['starimage'];
2415                      break;
2416                  }
2417              }
2418          }
2419      }
2420  
2421      $groupimage = '';
2422      if(!empty($memperms['image']))
2423      {
2424          if(!empty($mybb->user['language']))
2425          {
2426              $language = $mybb->user['language'];
2427          }
2428          else
2429          {
2430              $language = $mybb->settings['bblanguage'];
2431          }
2432          $memperms['image'] = str_replace("{lang}", $language, $memperms['image']);
2433          $memperms['image'] = str_replace("{theme}", $theme['imgdir'], $memperms['image']);
2434          eval("\$groupimage = \"".$templates->get("member_profile_groupimage")."\";");
2435      }
2436  
2437      if(empty($starimage))
2438      {
2439          $starimage = $memperms['starimage'];
2440      }
2441  
2442      if(!empty($starimage))
2443      {
2444          // Only display stars if we have an image to use...
2445          $starimage = str_replace("{theme}", $theme['imgdir'], $starimage);
2446          $userstars = '';
2447          for($i = 0; $i < $stars; ++$i)
2448          {
2449              eval("\$userstars .= \"".$templates->get("member_profile_userstar", 1, 0)."\";");
2450          }
2451      }
2452  
2453      // User is currently online and this user has permissions to view the user on the WOL
2454      $timesearch = TIME_NOW - $mybb->settings['wolcutoffmins']*60;
2455      $query = $db->simple_select("sessions", "location,nopermission", "uid='$uid' AND time>'{$timesearch}'", array('order_by' => 'time', 'order_dir' => 'DESC', 'limit' => 1));
2456      $session = $db->fetch_array($query);
2457  
2458      $online_status = '';
2459      if($memprofile['invisible'] != 1 || $mybb->usergroup['canviewwolinvis'] == 1 || $memprofile['uid'] == $mybb->user['uid'])
2460      {
2461          // Lastvisit
2462          if($memprofile['lastactive'])
2463          {
2464              $memlastvisitsep = $lang->comma;
2465              $memlastvisitdate = my_date('relative', $memprofile['lastactive']);
2466          }
2467  
2468          // Time Online
2469          $timeonline = $lang->none_registered;
2470          if($memprofile['timeonline'] > 0)
2471          {
2472              $timeonline = nice_time($memprofile['timeonline']);
2473          }
2474  
2475          // Online?
2476          if(!empty($session))
2477          {
2478              // Fetch their current location
2479              $lang->load("online");
2480              require_once  MYBB_ROOT."inc/functions_online.php";
2481              $activity = fetch_wol_activity($session['location'], $session['nopermission']);
2482              $location = build_friendly_wol_location($activity);
2483              $location_time = my_date($mybb->settings['timeformat'], $memprofile['lastactive']);
2484  
2485              eval("\$online_status = \"".$templates->get("member_profile_online")."\";");
2486          }
2487          // User is offline
2488          else
2489          {
2490              eval("\$online_status = \"".$templates->get("member_profile_offline")."\";");
2491          }
2492      }
2493  
2494      if($memprofile['invisible'] == 1 && $mybb->usergroup['canviewwolinvis'] != 1 && $memprofile['uid'] != $mybb->user['uid'])
2495      {
2496          $memlastvisitsep = '';
2497          $memlastvisittime = '';
2498          $memlastvisitdate = $lang->lastvisit_never;
2499  
2500          if($memprofile['lastactive'])
2501          {
2502              // We have had at least some active time, hide it instead
2503              $memlastvisitdate = $lang->lastvisit_hidden;
2504          }
2505  
2506          $timeonline = $lang->timeonline_hidden;
2507      }
2508  
2509      // Reset the background colours to keep it inline
2510      $alttrow = 'trow1';
2511  
2512      // Build Referral
2513      $referrals = '';
2514      if($mybb->settings['usereferrals'] == 1)
2515      {
2516          $bg_color = alt_trow();
2517  
2518          eval("\$referrals = \"".$templates->get("member_profile_referrals")."\";");
2519      }
2520  
2521      // Fetch the reputation for this user
2522      $reputation = '';
2523      if($memperms['usereputationsystem'] == 1 && $mybb->settings['enablereputation'] == 1)
2524      {
2525          $bg_color = alt_trow();
2526          $reputation = get_reputation($memprofile['reputation']);
2527  
2528          // If this user has permission to give reputations show the vote link
2529          $vote_link = '';
2530          if($mybb->usergroup['cangivereputations'] == 1 && $memprofile['uid'] != $mybb->user['uid'] && ($mybb->settings['posrep'] || $mybb->settings['neurep'] || $mybb->settings['negrep']))
2531          {
2532              eval("\$vote_link = \"".$templates->get("member_profile_reputation_vote")."\";");
2533          }
2534  
2535          eval("\$reputation = \"".$templates->get("member_profile_reputation")."\";");
2536      }
2537  
2538      $warning_level = '';
2539      if($mybb->settings['enablewarningsystem'] != 0 && $memperms['canreceivewarnings'] != 0 && ($mybb->usergroup['canwarnusers'] != 0 || ($mybb->user['uid'] == $memprofile['uid'] && $mybb->settings['canviewownwarning'] != 0)))
2540      {
2541          $bg_color = alt_trow();
2542  
2543          if($mybb->settings['maxwarningpoints'] < 1)
2544          {
2545              $mybb->settings['maxwarningpoints'] = 10;
2546          }
2547  
2548          $warning_level = round($memprofile['warningpoints']/$mybb->settings['maxwarningpoints']*100);
2549  
2550          if($warning_level > 100)
2551          {
2552              $warning_level = 100;
2553          }
2554  
2555          $warn_user = '';
2556          $warning_link = 'usercp.php';
2557          $warning_level = get_colored_warning_level($warning_level);
2558          if($mybb->usergroup['canwarnusers'] != 0 && $memprofile['uid'] != $mybb->user['uid'])
2559          {
2560              eval("\$warn_user = \"".$templates->get("member_profile_warn")."\";");
2561              $warning_link = "warnings.php?uid={$memprofile['uid']}";
2562          }
2563  
2564          eval("\$warning_level = \"".$templates->get("member_profile_warninglevel")."\";");
2565      }
2566  
2567      $bgcolor = $alttrow = 'trow1';
2568      $customfields = $profilefields = '';
2569  
2570      $query = $db->simple_select("userfields", "*", "ufid = '{$uid}'");
2571      $userfields = $db->fetch_array($query);
2572  
2573      // If this user is an Administrator or a Moderator then we wish to show all profile fields
2574      $pfcache = $cache->read('profilefields');
2575  
2576      if(is_array($pfcache))
2577      {
2578          foreach($pfcache as $customfield)
2579          {
2580              if($mybb->usergroup['cancp'] != 1 && $mybb->usergroup['issupermod'] != 1 && $mybb->usergroup['canmodcp'] != 1 && (!is_member($customfield['viewableby']) || !$customfield['profile']))
2581              {
2582                  continue;
2583              }
2584  
2585              $thing = explode("\n", $customfield['type'], "2");
2586              $type = trim($thing[0]);
2587  
2588              $customfieldval = $customfield_val = '';
2589              $field = "fid{$customfield['fid']}";
2590  
2591              if(isset($userfields[$field]))
2592              {
2593                  $useropts = explode("\n", $userfields[$field]);
2594                  $customfieldval = $comma = '';
2595                  if(is_array($useropts) && ($type == "multiselect" || $type == "checkbox"))
2596                  {
2597                      foreach($useropts as $val)
2598                      {
2599                          if($val != '')
2600                          {
2601                              eval("\$customfield_val .= \"".$templates->get("member_profile_customfields_field_multi_item")."\";");
2602                          }
2603                      }
2604                      if($customfield_val != '')
2605                      {
2606                          eval("\$customfieldval = \"".$templates->get("member_profile_customfields_field_multi")."\";");
2607                      }
2608                  }
2609                  else
2610                  {
2611                      $parser_options = array(
2612                          "allow_html" => $customfield['allowhtml'],
2613                          "allow_mycode" => $customfield['allowmycode'],
2614                          "allow_smilies" => $customfield['allowsmilies'],
2615                          "allow_imgcode" => $customfield['allowimgcode'],
2616                          "allow_videocode" => $customfield['allowvideocode'],
2617                          #"nofollow_on" => 1,
2618                          "filter_badwords" => 1
2619                      );
2620  
2621                      if($customfield['type'] == "textarea")
2622                      {
2623                          $parser_options['me_username'] = $memprofile['username'];
2624                      }
2625                      else
2626                      {
2627                          $parser_options['nl2br'] = 0;
2628                      }
2629  
2630                      if($mybb->user['showimages'] != 1 && $mybb->user['uid'] != 0 || $mybb->settings['guestimages'] != 1 && $mybb->user['uid'] == 0)
2631                      {
2632                          $parser_options['allow_imgcode'] = 0;
2633                      }
2634  
2635                      $customfieldval = $parser->parse_message($userfields[$field], $parser_options);
2636                  }
2637              }
2638  
2639              if($customfieldval)
2640              {
2641                  $customfield['name'] = htmlspecialchars_uni($customfield['name']);
2642                  eval("\$customfields .= \"".$templates->get("member_profile_customfields_field")."\";");
2643                  $bgcolor = alt_trow();
2644              }
2645          }
2646      }
2647  
2648      if($customfields)
2649      {
2650          eval("\$profilefields = \"".$templates->get("member_profile_customfields")."\";");
2651      }
2652  
2653      $memprofile['postnum'] = my_number_format($memprofile['postnum']);
2654      $lang->ppd_percent_total = $lang->sprintf($lang->ppd_percent_total, my_number_format($ppd), $post_percent);
2655  
2656      $memprofile['threadnum'] = my_number_format($memprofile['threadnum']);
2657      $lang->tpd_percent_total = $lang->sprintf($lang->tpd_percent_total, my_number_format($tpd), $thread_percent);
2658  
2659      $formattedname = format_name($memprofile['username'], $memprofile['usergroup'], $memprofile['displaygroup']);
2660  
2661      $bannedbit = '';
2662      if($memperms['isbannedgroup'] == 1 && $mybb->usergroup['canbanusers'] == 1)
2663      {
2664          // Fetch details on their ban
2665          $query = $db->simple_select('banned b LEFT JOIN '.TABLE_PREFIX.'users a ON (b.admin=a.uid)', 'b.*, a.username AS adminuser', "b.uid='{$uid}'", array('limit' => 1));
2666          $memban = $db->fetch_array($query);
2667  
2668          if($memban['reason'])
2669          {
2670              $memban['reason'] = htmlspecialchars_uni($parser->parse_badwords($memban['reason']));
2671          }
2672          else
2673          {
2674              $memban['reason'] = $lang->na;
2675          }
2676  
2677          if($memban['lifted'] == 'perm' || $memban['lifted'] == '' || $memban['bantime'] == 'perm' || $memban['bantime'] == '---')
2678          {
2679              $banlength = $lang->permanent;
2680              $timeremaining = $lang->na;
2681          }
2682          else
2683          {
2684              // Set up the array of ban times.
2685              $bantimes = fetch_ban_times();
2686  
2687              $banlength = $bantimes[$memban['bantime']];
2688              $remaining = $memban['lifted']-TIME_NOW;
2689  
2690              $timeremaining = nice_time($remaining, array('short' => 1, 'seconds' => false))."";
2691  
2692              $banned_class = '';
2693              if($remaining < 3600)
2694              {
2695                  $banned_class = "high_banned";
2696              }
2697              else if($remaining < 86400)
2698              {
2699                  $banned_class = "moderate_banned";
2700              }
2701              else if($remaining < 604800)
2702              {
2703                  $banned_class = "low_banned";
2704              }
2705              else
2706              {
2707                  $banned_class = "normal_banned";
2708              }
2709  
2710              eval('$timeremaining = "'.$templates->get('member_profile_banned_remaining').'";');
2711          }
2712  
2713          $memban['adminuser'] = build_profile_link(htmlspecialchars_uni($memban['adminuser']), $memban['admin']);
2714  
2715          // Display a nice warning to the user
2716          eval('$bannedbit = "'.$templates->get('member_profile_banned').'";');
2717      }
2718  
2719      $adminoptions = '';
2720      if($mybb->usergroup['cancp'] == 1 && $mybb->config['hide_admin_links'] != 1)
2721      {
2722          eval("\$adminoptions = \"".$templates->get("member_profile_adminoptions")."\";");
2723      }
2724  
2725      $modoptions = $viewnotes = $editnotes = $editprofile = $banuser = $manageuser = '';
2726      $can_purge_spammer = purgespammer_show($memprofile['postnum'], $memprofile['usergroup'], $memprofile['uid']);
2727      if($mybb->usergroup['canmodcp'] == 1 || $can_purge_spammer)
2728      {
2729          if($mybb->usergroup['canuseipsearch'] == 1)
2730          {
2731              $memprofile['regip'] = my_inet_ntop($db->unescape_binary($memprofile['regip']));
2732              $memprofile['lastip'] = my_inet_ntop($db->unescape_binary($memprofile['lastip']));
2733  
2734              eval("\$ipaddress = \"".$templates->get("member_profile_modoptions_ipaddress")."\";");
2735          }
2736  
2737          $memprofile['usernotes'] = nl2br(htmlspecialchars_uni($memprofile['usernotes']));
2738  
2739          if(!empty($memprofile['usernotes']))
2740          {
2741              if(strlen($memprofile['usernotes']) > 100)
2742              {
2743                  eval("\$viewnotes = \"".$templates->get("member_profile_modoptions_viewnotes")."\";");
2744                  $memprofile['usernotes'] = my_substr($memprofile['usernotes'], 0, 100)."... {$viewnotes}";
2745              }
2746          }
2747          else
2748          {
2749              $memprofile['usernotes'] = $lang->no_usernotes;
2750          }
2751  
2752          if($mybb->usergroup['caneditprofiles'] == 1)
2753          {
2754              eval("\$editprofile = \"".$templates->get("member_profile_modoptions_editprofile")."\";");
2755              eval("\$editnotes = \"".$templates->get("member_profile_modoptions_editnotes")."\";");
2756          }
2757  
2758          if($mybb->usergroup['canbanusers'] == 1 && (!$memban['uid'] || $memban['uid'] && ($mybb->user['uid'] == $memban['admin']) || $mybb->usergroup['issupermod'] == 1 || $mybb->usergroup['cancp'] == 1))
2759          {
2760              eval("\$banuser = \"".$templates->get("member_profile_modoptions_banuser")."\";");
2761          }
2762  
2763          if($can_purge_spammer)
2764          {
2765              eval("\$purgespammer = \"".$templates->get('member_profile_modoptions_purgespammer')."\";");
2766          }
2767  
2768          if(!empty($editprofile) || !empty($banuser) || !empty($purgespammer))
2769          {
2770              eval("\$manageuser = \"".$templates->get("member_profile_modoptions_manageuser")."\";");
2771          }
2772  
2773          eval("\$modoptions = \"".$templates->get("member_profile_modoptions")."\";");
2774      }
2775  
2776      $add_remove_options = array();
2777      $buddy_options = $ignore_options = $report_options = '';
2778      if($mybb->user['uid'] != $memprofile['uid'] && $mybb->user['uid'] != 0)
2779      {
2780          $buddy_list = explode(',', $mybb->user['buddylist']);
2781          $ignore_list = explode(',', $mybb->user['ignorelist']);
2782  
2783          if(in_array($uid, $buddy_list))
2784          {
2785              $add_remove_options = array('url' => "usercp.php?action=do_editlists&amp;delete={$uid}&amp;my_post_key={$mybb->post_code}", 'class' => 'remove_buddy_button', 'lang' => $lang->remove_from_buddy_list);
2786          }
2787          else
2788          {
2789              $add_remove_options = array('url' => "usercp.php?action=do_editlists&amp;add_username=".urlencode($memprofile['username'])."&amp;my_post_key={$mybb->post_code}", 'class' => 'add_buddy_button', 'lang' => $lang->add_to_buddy_list);
2790          }
2791  
2792          if(!in_array($uid, $ignore_list))
2793          {
2794              eval("\$buddy_options = \"".$templates->get("member_profile_addremove")."\";"); // Add/Remove Buddy
2795          }
2796  
2797          if(in_array($uid, $ignore_list))
2798          {
2799              $add_remove_options = array('url' => "usercp.php?action=do_editlists&amp;manage=ignored&amp;delete={$uid}&amp;my_post_key={$mybb->post_code}", 'class' => 'remove_ignore_button', 'lang' => $lang->remove_from_ignore_list);
2800          }
2801          else
2802          {
2803              $add_remove_options = array('url' => "usercp.php?action=do_editlists&amp;manage=ignored&amp;add_username=".urlencode($memprofile['username'])."&amp;my_post_key={$mybb->post_code}", 'class' => 'add_ignore_button', 'lang' => $lang->add_to_ignore_list);
2804          }
2805  
2806          if(!in_array($uid, $buddy_list))
2807          {
2808              eval("\$ignore_options = \"".$templates->get("member_profile_addremove")."\";"); // Add/Remove Ignore
2809          }
2810  
2811          if(isset($memperms['canbereported']) && $memperms['canbereported'] == 1)
2812          {
2813              $add_remove_options = array('url' => "javascript:Report.reportUser({$memprofile['uid']});", 'class' => 'report_user_button', 'lang' => $lang->report_user);
2814              eval("\$report_options = \"".$templates->get("member_profile_addremove")."\";"); // Report User
2815          }
2816      }
2817  
2818      $plugins->run_hooks("member_profile_end");
2819  
2820      eval("\$profile = \"".$templates->get("member_profile")."\";");
2821      output_page($profile);
2822  }
2823  
2824  if($mybb->input['action'] == "do_emailuser" && $mybb->request_method == "post")
2825  {
2826      // Verify incoming POST request
2827      verify_post_check($mybb->get_input('my_post_key'));
2828  
2829      $plugins->run_hooks("member_do_emailuser_start");
2830  
2831      // Guests or those without permission can't email other users
2832      if($mybb->usergroup['cansendemail'] == 0)
2833      {
2834          error_no_permission();
2835      }
2836  
2837      // Check group limits
2838      if($mybb->usergroup['maxemails'] > 0)
2839      {
2840          if($mybb->user['uid'] > 0)
2841          {
2842              $user_check = "fromuid='{$mybb->user['uid']}'";
2843          }
2844          else
2845          {
2846              $user_check = "ipaddress=".$db->escape_binary($session->packedip);
2847          }
2848  
2849          $query = $db->simple_select("maillogs", "COUNT(*) AS sent_count", "{$user_check} AND dateline >= '".(TIME_NOW - (60*60*24))."'");
2850          $sent_count = $db->fetch_field($query, "sent_count");
2851          if($sent_count >= $mybb->usergroup['maxemails'])
2852          {
2853              $lang->error_max_emails_day = $lang->sprintf($lang->error_max_emails_day, $mybb->usergroup['maxemails']);
2854              error($lang->error_max_emails_day);
2855          }
2856      }
2857  
2858      // Check email flood control
2859      if($mybb->usergroup['emailfloodtime'] > 0)
2860      {
2861          if($mybb->user['uid'] > 0)
2862          {
2863              $user_check = "fromuid='{$mybb->user['uid']}'";
2864          }
2865          else
2866          {
2867              $user_check = "ipaddress=".$db->escape_binary($session->packedip);
2868          }
2869  
2870          $timecut = TIME_NOW-$mybb->usergroup['emailfloodtime']*60;
2871  
2872          $query = $db->simple_select("maillogs", "mid, dateline", "{$user_check} AND dateline > '{$timecut}'", array('order_by' => "dateline", 'order_dir' => "DESC"));
2873          $last_email = $db->fetch_array($query);
2874  
2875          // Users last email was within the flood time, show the error
2876          if($last_email['mid'])
2877          {
2878              $remaining_time = ($mybb->usergroup['emailfloodtime']*60)-(TIME_NOW-$last_email['dateline']);
2879  
2880              if($remaining_time == 1)
2881              {
2882                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_1_second, $mybb->usergroup['emailfloodtime']);
2883              }
2884              elseif($remaining_time < 60)
2885              {
2886                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_seconds, $mybb->usergroup['emailfloodtime'], $remaining_time);
2887              }
2888              elseif($remaining_time > 60 && $remaining_time < 120)
2889              {
2890                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_1_minute, $mybb->usergroup['emailfloodtime']);
2891              }
2892              else
2893              {
2894                  $remaining_time_minutes = ceil($remaining_time/60);
2895                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_minutes, $mybb->usergroup['emailfloodtime'], $remaining_time_minutes);
2896              }
2897  
2898              error($lang->error_emailflooding);
2899          }
2900      }
2901  
2902      $query = $db->simple_select("users", "uid, username, email, hideemail", "uid='".$mybb->get_input('uid', MyBB::INPUT_INT)."'");
2903      $to_user = $db->fetch_array($query);
2904  
2905      if(!$to_user['username'])
2906      {
2907          error($lang->error_invalidusername);
2908      }
2909  
2910      if($to_user['hideemail'] != 0)
2911      {
2912          error($lang->error_hideemail);
2913      }
2914  
2915      $errors = array();
2916  
2917      if($mybb->user['uid'])
2918      {
2919          $mybb->input['fromemail'] = $mybb->user['email'];
2920          $mybb->input['fromname'] = $mybb->user['username'];
2921      }
2922  
2923      if(!validate_email_format($mybb->input['fromemail']))
2924      {
2925          $errors[] = $lang->error_invalidfromemail;
2926      }
2927  
2928      if(empty($mybb->input['fromname']))
2929      {
2930          $errors[] = $lang->error_noname;
2931      }
2932  
2933      if(empty($mybb->input['subject']))
2934      {
2935          $errors[] = $lang->error_no_email_subject;
2936      }
2937  
2938      if(empty($mybb->input['message']))
2939      {
2940          $errors[] = $lang->error_no_email_message;
2941      }
2942  
2943      if($mybb->settings['captchaimage'] && $mybb->user['uid'] == 0)
2944      {
2945          require_once  MYBB_ROOT.'inc/class_captcha.php';
2946          $captcha = new captcha;
2947  
2948          if($captcha->validate_captcha() == false)
2949          {
2950              // CAPTCHA validation failed
2951              foreach($captcha->get_errors() as $error)
2952              {
2953                  $errors[] = $error;
2954              }
2955          }
2956      }
2957  
2958      if(count($errors) == 0)
2959      {
2960          if($mybb->settings['mail_handler'] == 'smtp')
2961          {
2962              $from = $mybb->input['fromemail'];
2963          }
2964          else
2965          {
2966              $from = "{$mybb->input['fromname']} <{$mybb->input['fromemail']}>";
2967          }
2968  
2969          $message = $lang->sprintf($lang->email_emailuser, $to_user['username'], $mybb->input['fromname'], $mybb->settings['bbname'], $mybb->settings['bburl'], $mybb->get_input('message'));
2970          my_mail($to_user['email'], $mybb->get_input('subject'), $message, '', '', '', false, 'text', '', $from);
2971  
2972          if($mybb->settings['mail_logging'] > 0)
2973          {
2974              // Log the message
2975              $log_entry = array(
2976                  "subject" => $db->escape_string($mybb->get_input('subject')),
2977                  "message" => $db->escape_string($mybb->get_input('message')),
2978                  "dateline" => TIME_NOW,
2979                  "fromuid" => $mybb->user['uid'],
2980                  "fromemail" => $db->escape_string($mybb->input['fromemail']),
2981                  "touid" => $to_user['uid'],
2982                  "toemail" => $db->escape_string($to_user['email']),
2983                  "tid" => 0,
2984                  "ipaddress" => $db->escape_binary($session->packedip),
2985                  "type" => 1
2986              );
2987              $db->insert_query("maillogs", $log_entry);
2988          }
2989  
2990          $plugins->run_hooks("member_do_emailuser_end");
2991  
2992          redirect(get_profile_link($to_user['uid']), $lang->redirect_emailsent);
2993      }
2994      else
2995      {
2996          $mybb->input['action'] = "emailuser";
2997      }
2998  }
2999  
3000  if($mybb->input['action'] == "emailuser")
3001  {
3002      $plugins->run_hooks("member_emailuser_start");
3003  
3004      // Guests or those without permission can't email other users
3005      if($mybb->usergroup['cansendemail'] == 0)
3006      {
3007          error_no_permission();
3008      }
3009  
3010      // Check group limits
3011      if($mybb->usergroup['maxemails'] > 0)
3012      {
3013          if($mybb->user['uid'] > 0)
3014          {
3015              $user_check = "fromuid='{$mybb->user['uid']}'";
3016          }
3017          else
3018          {
3019              $user_check = "ipaddress=".$db->escape_binary($session->packedip);
3020          }
3021  
3022          $query = $db->simple_select("maillogs", "COUNT(*) AS sent_count", "{$user_check} AND dateline >= '".(TIME_NOW - (60*60*24))."'");
3023          $sent_count = $db->fetch_field($query, "sent_count");
3024          if($sent_count >= $mybb->usergroup['maxemails'])
3025          {
3026              $lang->error_max_emails_day = $lang->sprintf($lang->error_max_emails_day, $mybb->usergroup['maxemails']);
3027              error($lang->error_max_emails_day);
3028          }
3029      }
3030  
3031      // Check email flood control
3032      if($mybb->usergroup['emailfloodtime'] > 0)
3033      {
3034          if($mybb->user['uid'] > 0)
3035          {
3036              $user_check = "fromuid='{$mybb->user['uid']}'";
3037          }
3038          else
3039          {
3040              $user_check = "ipaddress=".$db->escape_binary($session->packedip);
3041          }
3042  
3043          $timecut = TIME_NOW-$mybb->usergroup['emailfloodtime']*60;
3044  
3045          $query = $db->simple_select("maillogs", "mid, dateline", "{$user_check} AND dateline > '{$timecut}'", array('order_by' => "dateline", 'order_dir' => "DESC"));
3046          $last_email = $db->fetch_array($query);
3047  
3048          // Users last email was within the flood time, show the error
3049          if($last_email['mid'])
3050          {
3051              $remaining_time = ($mybb->usergroup['emailfloodtime']*60)-(TIME_NOW-$last_email['dateline']);
3052  
3053              if($remaining_time == 1)
3054              {
3055                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_1_second, $mybb->usergroup['emailfloodtime']);
3056              }
3057              elseif($remaining_time < 60)
3058              {
3059                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_seconds, $mybb->usergroup['emailfloodtime'], $remaining_time);
3060              }
3061              elseif($remaining_time > 60 && $remaining_time < 120)
3062              {
3063                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_1_minute, $mybb->usergroup['emailfloodtime']);
3064              }
3065              else
3066              {
3067                  $remaining_time_minutes = ceil($remaining_time/60);
3068                  $lang->error_emailflooding = $lang->sprintf($lang->error_emailflooding_minutes, $mybb->usergroup['emailfloodtime'], $remaining_time_minutes);
3069              }
3070  
3071              error($lang->error_emailflooding);
3072          }
3073      }
3074  
3075      $query = $db->simple_select("users", "uid, username, email, hideemail, ignorelist", "uid='".$mybb->get_input('uid', MyBB::INPUT_INT)."'");
3076      $to_user = $db->fetch_array($query);
3077  
3078      $to_user['username'] = htmlspecialchars_uni($to_user['username']);
3079      $lang->email_user = $lang->sprintf($lang->email_user, $to_user['username']);
3080  
3081      if(!$to_user['uid'])
3082      {
3083          error($lang->error_invaliduser);
3084      }
3085  
3086      if($to_user['hideemail'] != 0)
3087      {
3088          error($lang->error_hideemail);
3089      }
3090  
3091      if($to_user['ignorelist'] && (my_strpos(",".$to_user['ignorelist'].",", ",".$mybb->user['uid'].",") !== false && $mybb->usergroup['cansendemailoverride'] != 1))
3092      {
3093          error_no_permission();
3094      }
3095  
3096      if(isset($errors) && count($errors) > 0)
3097      {
3098          $errors = inline_error($errors);
3099          $fromname = htmlspecialchars_uni($mybb->get_input('fromname'));
3100          $fromemail = htmlspecialchars_uni($mybb->get_input('fromemail'));
3101          $subject = htmlspecialchars_uni($mybb->get_input('subject'));
3102          $message = htmlspecialchars_uni($mybb->get_input('message'));
3103      }
3104      else
3105      {
3106          $errors = '';
3107          $fromname = '';
3108          $fromemail = '';
3109          $subject = '';
3110          $message = '';
3111      }
3112  
3113      // Generate CAPTCHA?
3114      if($mybb->settings['captchaimage'] && $mybb->user['uid'] == 0)
3115      {
3116          require_once  MYBB_ROOT.'inc/class_captcha.php';
3117          $post_captcha = new captcha(true, "post_captcha");
3118  
3119          if($post_captcha->html)
3120          {
3121              $captcha = $post_captcha->html;
3122          }
3123      }
3124      else
3125      {
3126          $captcha = '';
3127      }
3128  
3129      $from_email = '';
3130      if($mybb->user['uid'] == 0)
3131      {
3132          eval("\$from_email = \"".$templates->get("member_emailuser_guest")."\";");
3133      }
3134  
3135      $plugins->run_hooks("member_emailuser_end");
3136  
3137      eval("\$emailuser = \"".$templates->get("member_emailuser")."\";");
3138      output_page($emailuser);
3139  }
3140  
3141  if(!$mybb->input['action'])
3142  {
3143      header("Location: index.php");
3144  }


2005 - 2018 © MyBB.de | Alle Rechte vorbehalten! | Sponsor: netcup Cross-referenced by PHPXref 0.7.1