[ Index ]

PHP Cross Reference of MyBB 1.8.27

title

Body

[close]

/ -> usercp.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('THIS_SCRIPT', 'usercp.php');
  13  define("ALLOWABLE_PAGE", "removesubscription,removesubscriptions");
  14  
  15  $templatelist = "usercp,usercp_nav,usercp_profile,usercp_changename,usercp_password,usercp_subscriptions_thread,forumbit_depth2_forum_lastpost,usercp_forumsubscriptions_forum,postbit_reputation_formatted,usercp_subscriptions_thread_icon";
  16  $templatelist .= ",usercp_usergroups_memberof_usergroup,usercp_usergroups_memberof,usercp_usergroups_joinable_usergroup,usercp_usergroups_joinable,usercp_usergroups,usercp_nav_attachments,usercp_options_style,usercp_warnings_warning_post";
  17  $templatelist .= ",usercp_nav_messenger,usercp_nav_changename,usercp_nav_profile,usercp_nav_misc,usercp_usergroups_leader_usergroup,usercp_usergroups_leader,usercp_currentavatar,usercp_reputation,usercp_avatar_remove,usercp_resendactivation";
  18  $templatelist .= ",usercp_attachments_attachment,usercp_attachments,usercp_profile_away,usercp_profile_customfield,usercp_profile_profilefields,usercp_profile_customtitle,usercp_forumsubscriptions_none,usercp_profile_customtitle_currentcustom";
  19  $templatelist .= ",usercp_forumsubscriptions,usercp_subscriptions_none,usercp_subscriptions,usercp_options_pms_from_buddys,usercp_options_tppselect,usercp_options_pppselect,usercp_themeselector,usercp_profile_customtitle_reverttitle";
  20  $templatelist .= ",usercp_nav_editsignature,usercp_referrals,usercp_notepad,usercp_latest_threads_threads,forumdisplay_thread_gotounread,usercp_latest_threads,usercp_subscriptions_remove,usercp_nav_messenger_folder,usercp_profile_profilefields_text";
  21  $templatelist .= ",usercp_editsig_suspended,usercp_editsig,usercp_avatar_current,usercp_options_timezone_option,usercp_drafts,usercp_options_language,usercp_options_date_format,usercp_profile_website,usercp_latest_subscribed,usercp_warnings";
  22  $templatelist .= ",usercp_avatar,usercp_editlists_userusercp_editlists,usercp_drafts_draft,usercp_usergroups_joingroup,usercp_attachments_none,usercp_avatar_upload,usercp_options_timezone,usercp_usergroups_joinable_usergroup_join";
  23  $templatelist .= ",usercp_warnings_warning,usercp_nav_messenger_tracking,multipage,multipage_end,multipage_jump_page,multipage_nextpage,multipage_page,multipage_page_current,multipage_page_link_current,multipage_prevpage,multipage_start";
  24  $templatelist .= ",codebuttons,usercp_nav_messenger_compose,usercp_options_language_option,usercp_editlists,usercp_profile_contact_fields_field,usercp_latest_subscribed_threads,usercp_profile_contact_fields,usercp_profile_day,usercp_nav_home";
  25  $templatelist .= ",usercp_profile_profilefields_select_option,usercp_profile_profilefields_multiselect,usercp_profile_profilefields_select,usercp_profile_profilefields_textarea,usercp_profile_profilefields_radio,usercp_profile_profilefields_checkbox";
  26  $templatelist .= ",usercp_options_tppselect_option,usercp_options_pppselect_option,forumbit_depth2_forum_lastpost_never,forumbit_depth2_forum_lastpost_hidden,usercp_avatar_auto_resize_auto,usercp_avatar_auto_resize_user,usercp_options";
  27  $templatelist .= ",usercp_editlists_no_buddies,usercp_editlists_no_ignored,usercp_editlists_no_requests,usercp_editlists_received_requests,usercp_editlists_sent_requests,usercp_drafts_draft_thread,usercp_drafts_draft_forum,usercp_editlists_user";
  28  $templatelist .= ",usercp_usergroups_leader_usergroup_memberlist,usercp_usergroups_leader_usergroup_moderaterequests,usercp_usergroups_memberof_usergroup_leaveprimary,usercp_usergroups_memberof_usergroup_display,usercp_email,usercp_options_pms";
  29  $templatelist .= ",usercp_usergroups_memberof_usergroup_leaveleader,usercp_usergroups_memberof_usergroup_leaveother,usercp_usergroups_memberof_usergroup_leave,usercp_usergroups_joinable_usergroup_description,usercp_options_time_format";
  30  $templatelist .= ",usercp_editlists_sent_request,usercp_editlists_received_request,usercp_drafts_none,usercp_usergroups_memberof_usergroup_setdisplay,usercp_usergroups_memberof_usergroup_description,usercp_options_quick_reply";
  31  $templatelist .= ",usercp_addsubscription_thread,forumdisplay_password,forumdisplay_password_wrongpass,";
  32  
  33  require_once  "./global.php";
  34  require_once  MYBB_ROOT."inc/functions_post.php";
  35  require_once  MYBB_ROOT."inc/functions_search.php";
  36  require_once  MYBB_ROOT."inc/functions_user.php";
  37  require_once  MYBB_ROOT."inc/class_parser.php";
  38  $parser = new postParser;
  39  
  40  // Load global language phrases
  41  $lang->load("usercp");
  42  
  43  if($mybb->user['uid'] == 0 || $mybb->usergroup['canusercp'] == 0)
  44  {
  45      error_no_permission();
  46  }
  47  
  48  $errors = '';
  49  
  50  $mybb->input['action'] = $mybb->get_input('action');
  51  
  52  usercp_menu();
  53  
  54  $server_http_referer = htmlentities($_SERVER['HTTP_REFERER']);
  55  
  56  if(my_strpos($server_http_referer, $mybb->settings['bburl'].'/') !== 0)
  57  {
  58      if(my_strpos($server_http_referer, '/') === 0)
  59      {
  60          $server_http_referer = my_substr($server_http_referer, 1);
  61      }
  62      $url_segments = explode('/', $server_http_referer);
  63      $server_http_referer = $mybb->settings['bburl'].'/'.end($url_segments);
  64  }
  65  
  66  $plugins->run_hooks("usercp_start");
  67  if($mybb->input['action'] == "do_editsig" && $mybb->request_method == "post")
  68  {
  69      require_once  MYBB_ROOT."inc/datahandlers/user.php";
  70      $userhandler = new UserDataHandler();
  71  
  72      $data = array(
  73          'uid' => $mybb->user['uid'],
  74          'signature' => $mybb->get_input('signature'),
  75      );
  76  
  77      $userhandler->set_data($data);
  78  
  79      if(!$userhandler->verify_signature())
  80      {
  81          $error = inline_error($userhandler->get_friendly_errors());
  82      }
  83  
  84      if(isset($error) || !empty($mybb->input['preview']))
  85      {
  86          $mybb->input['action'] = "editsig";
  87      }
  88  }
  89  
  90  // Make navigation
  91  add_breadcrumb($lang->nav_usercp, "usercp.php");
  92  
  93  switch($mybb->input['action'])
  94  {
  95      case "profile":
  96      case "do_profile":
  97          add_breadcrumb($lang->ucp_nav_profile);
  98          break;
  99      case "options":
 100      case "do_options":
 101          add_breadcrumb($lang->nav_options);
 102          break;
 103      case "email":
 104      case "do_email":
 105          add_breadcrumb($lang->nav_email);
 106          break;
 107      case "password":
 108      case "do_password":
 109          add_breadcrumb($lang->nav_password);
 110          break;
 111      case "changename":
 112      case "do_changename":
 113          add_breadcrumb($lang->nav_changename);
 114          break;
 115      case "subscriptions":
 116          add_breadcrumb($lang->ucp_nav_subscribed_threads);
 117          break;
 118      case "forumsubscriptions":
 119          add_breadcrumb($lang->ucp_nav_forum_subscriptions);
 120          break;
 121      case "editsig":
 122      case "do_editsig":
 123          add_breadcrumb($lang->nav_editsig);
 124          break;
 125      case "avatar":
 126      case "do_avatar":
 127          add_breadcrumb($lang->nav_avatar);
 128          break;
 129      case "notepad":
 130      case "do_notepad":
 131          add_breadcrumb($lang->ucp_nav_notepad);
 132          break;
 133      case "editlists":
 134      case "do_editlists":
 135          add_breadcrumb($lang->ucp_nav_editlists);
 136          break;
 137      case "drafts":
 138          add_breadcrumb($lang->ucp_nav_drafts);
 139          break;
 140      case "usergroups":
 141          add_breadcrumb($lang->ucp_nav_usergroups);
 142          break;
 143      case "attachments":
 144          add_breadcrumb($lang->ucp_nav_attachments);
 145          break;
 146  }
 147  
 148  if($mybb->input['action'] == "do_profile" && $mybb->request_method == "post")
 149  {
 150      // Verify incoming POST request
 151      verify_post_check($mybb->get_input('my_post_key'));
 152  
 153      $user = array();
 154  
 155      $plugins->run_hooks("usercp_do_profile_start");
 156  
 157      if($mybb->get_input('away', MyBB::INPUT_INT) == 1 && $mybb->settings['allowaway'] != 0)
 158      {
 159          $awaydate = TIME_NOW;
 160          if(!empty($mybb->input['awayday']))
 161          {
 162              // If the user has indicated that they will return on a specific day, but not month or year, assume it is current month and year
 163              if(!$mybb->get_input('awaymonth', MyBB::INPUT_INT))
 164              {
 165                  $mybb->input['awaymonth'] = my_date('n', $awaydate);
 166              }
 167              if(!$mybb->get_input('awayyear', MyBB::INPUT_INT))
 168              {
 169                  $mybb->input['awayyear'] = my_date('Y', $awaydate);
 170              }
 171  
 172              $return_month = (int)substr($mybb->get_input('awaymonth'), 0, 2);
 173              $return_day = (int)substr($mybb->get_input('awayday'), 0, 2);
 174              $return_year = min((int)$mybb->get_input('awayyear'), 9999);
 175  
 176              // Check if return date is after the away date.
 177              $returntimestamp = gmmktime(0, 0, 0, $return_month, $return_day, $return_year);
 178              $awaytimestamp = gmmktime(0, 0, 0, my_date('n', $awaydate), my_date('j', $awaydate), my_date('Y', $awaydate));
 179              if($return_year < my_date('Y', $awaydate) || ($returntimestamp < $awaytimestamp && $return_year == my_date('Y', $awaydate)))
 180              {
 181                  error($lang->error_usercp_return_date_past);
 182              }
 183  
 184              $returndate = "{$return_day}-{$return_month}-{$return_year}";
 185          }
 186          else
 187          {
 188              $returndate = "";
 189          }
 190          $away = array(
 191              "away" => 1,
 192              "date" => $awaydate,
 193              "returndate" => $returndate,
 194              "awayreason" => $mybb->get_input('awayreason')
 195          );
 196      }
 197      else
 198      {
 199          $away = array(
 200              "away" => 0,
 201              "date" => '',
 202              "returndate" => '',
 203              "awayreason" => ''
 204          );
 205      }
 206  
 207      $bday = array(
 208          "day" => $mybb->get_input('bday1', MyBB::INPUT_INT),
 209          "month" => $mybb->get_input('bday2', MyBB::INPUT_INT),
 210          "year" => $mybb->get_input('bday3', MyBB::INPUT_INT)
 211      );
 212  
 213      // Set up user handler.
 214      require_once  MYBB_ROOT."inc/datahandlers/user.php";
 215      $userhandler = new UserDataHandler("update");
 216  
 217      $user = array_merge($user, array(
 218          "uid" => $mybb->user['uid'],
 219          "postnum" => $mybb->user['postnum'],
 220          "usergroup" => $mybb->user['usergroup'],
 221          "additionalgroups" => $mybb->user['additionalgroups'],
 222          "birthday" => $bday,
 223          "birthdayprivacy" => $mybb->get_input('birthdayprivacy'),
 224          "away" => $away,
 225          "profile_fields" => $mybb->get_input('profile_fields', MyBB::INPUT_ARRAY)
 226      ));
 227      foreach(array('icq', 'skype', 'google') as $cfield)
 228      {
 229          $csetting = 'allow'.$cfield.'field';
 230          if($mybb->settings[$csetting] == '')
 231          {
 232              continue;
 233          }
 234  
 235          if(!is_member($mybb->settings[$csetting]))
 236          {
 237              continue;
 238          }
 239  
 240          if($cfield == 'icq')
 241          {
 242              $user[$cfield] = $mybb->get_input($cfield, 1);
 243  
 244              if(my_strlen($user[$cfield]) > 10)
 245              {
 246                  error($lang->contact_field_icqerror);
 247              }
 248          }
 249          else
 250          {
 251              $user[$cfield] = $mybb->get_input($cfield);
 252  
 253              if(my_strlen($user[$cfield]) > 75)
 254              {
 255                  error($lang->contact_field_error);
 256              }
 257          }
 258      }
 259  
 260      if($mybb->usergroup['canchangewebsite'] == 1)
 261      {
 262          $user['website'] = $mybb->get_input('website');
 263      }
 264  
 265      if($mybb->usergroup['cancustomtitle'] == 1)
 266      {
 267          if($mybb->get_input('usertitle') != '')
 268          {
 269              $user['usertitle'] = $mybb->get_input('usertitle');
 270          }
 271          elseif(!empty($mybb->input['reverttitle']))
 272          {
 273              $user['usertitle'] = '';
 274          }
 275      }
 276      $userhandler->set_data($user);
 277  
 278      if(!$userhandler->validate_user())
 279      {
 280          $errors = $userhandler->get_friendly_errors();
 281          $raw_errors = $userhandler->get_errors();
 282  
 283          // Set to stored value if invalid
 284          if(array_key_exists("invalid_birthday_privacy", $raw_errors) || array_key_exists("conflicted_birthday_privacy", $raw_errors))
 285          {
 286              $mybb->input['birthdayprivacy'] = $mybb->user['birthdayprivacy'];
 287              $bday = explode("-", $mybb->user['birthday']);
 288  
 289              if(isset($bday[2]))
 290              {
 291                  $mybb->input['bday3'] = $bday[2];
 292              }
 293          }
 294  
 295          $errors = inline_error($errors);
 296          $mybb->input['action'] = "profile";
 297      }
 298      else
 299      {
 300          $userhandler->update_user();
 301  
 302          $plugins->run_hooks("usercp_do_profile_end");
 303          redirect("usercp.php?action=profile", $lang->redirect_profileupdated);
 304      }
 305  }
 306  
 307  if($mybb->input['action'] == "profile")
 308  {
 309      if($errors)
 310      {
 311          $user = $mybb->input;
 312          $bday = array();
 313          $bday[0] = $mybb->get_input('bday1', MyBB::INPUT_INT);
 314          $bday[1] = $mybb->get_input('bday2', MyBB::INPUT_INT);
 315          $bday[2] = $mybb->get_input('bday3', MyBB::INPUT_INT);
 316      }
 317      else
 318      {
 319          $user = $mybb->user;
 320          $bday = explode("-", $user['birthday']);
 321          if(!isset($bday[1]))
 322          {
 323              $bday[1] = 0;
 324          }
 325      }
 326      if(!isset($bday[2]) || $bday[2] == 0)
 327      {
 328          $bday[2] = '';
 329      }
 330  
 331      $plugins->run_hooks("usercp_profile_start");
 332  
 333      $bdaydaysel = '';
 334      for($day = 1; $day <= 31; ++$day)
 335      {
 336          if($bday[0] == $day)
 337          {
 338              $selected = "selected=\"selected\"";
 339          }
 340          else
 341          {
 342              $selected = '';
 343          }
 344  
 345          eval("\$bdaydaysel .= \"".$templates->get("usercp_profile_day")."\";");
 346      }
 347  
 348      $bdaymonthsel = array();
 349      foreach(range(1, 12) as $month)
 350      {
 351          $bdaymonthsel[$month] = '';
 352      }
 353      $bdaymonthsel[$bday[1]] = 'selected="selected"';
 354  
 355      $allselected = $noneselected = $ageselected = '';
 356      if($user['birthdayprivacy'] == 'all' || !$user['birthdayprivacy'])
 357      {
 358          $allselected = " selected=\"selected\"";
 359      }
 360      elseif($user['birthdayprivacy'] == 'none')
 361      {
 362          $noneselected = " selected=\"selected\"";
 363      }
 364      elseif($user['birthdayprivacy'] == 'age')
 365      {
 366          $ageselected = " selected=\"selected\"";
 367      }
 368  
 369      if(!my_validate_url($user['website']))
 370      {
 371          $user['website'] = '';
 372      }
 373      else
 374      {
 375          $user['website'] = htmlspecialchars_uni($user['website']);
 376      }
 377  
 378      if($user['icq'] != "0")
 379      {
 380          $user['icq'] = (int)$user['icq'];
 381      }
 382  
 383      if($user['icq'] == 0)
 384      {
 385          $user['icq'] = '';
 386      }
 387  
 388      if($errors)
 389      {
 390          $user['skype'] = htmlspecialchars_uni($user['skype']);
 391          $user['google'] = htmlspecialchars_uni($user['google']);
 392      }
 393  
 394      $contact_fields = array();
 395      $contactfields = '';
 396      $cfieldsshow = false;
 397  
 398      foreach(array('icq', 'skype', 'google') as $cfield)
 399      {
 400          $contact_fields[$cfield] = '';
 401          $csetting = 'allow'.$cfield.'field';
 402          if($mybb->settings[$csetting] == '')
 403          {
 404              continue;
 405          }
 406  
 407          if(!is_member($mybb->settings[$csetting]))
 408          {
 409              continue;
 410          }
 411  
 412          $cfieldsshow = true;
 413  
 414          $lang_string = 'contact_field_'.$cfield;
 415          $lang_string = $lang->{$lang_string};
 416          $cfvalue = htmlspecialchars_uni($user[$cfield]);
 417  
 418          eval('$contact_fields[$cfield] = "'.$templates->get('usercp_profile_contact_fields_field').'";');
 419      }
 420  
 421      if($cfieldsshow)
 422      {
 423          eval('$contactfields = "'.$templates->get('usercp_profile_contact_fields').'";');
 424      }
 425  
 426      if($mybb->settings['allowaway'] != 0)
 427      {
 428          $awaycheck = array('', '');
 429          if($errors)
 430          {
 431              if($user['away'] == 1)
 432              {
 433                  $awaycheck[1] = "checked=\"checked\"";
 434              }
 435              else
 436              {
 437                  $awaycheck[0] = "checked=\"checked\"";
 438              }
 439              $returndate = array();
 440              $returndate[0] = $mybb->get_input('awayday', MyBB::INPUT_INT);
 441              $returndate[1] = $mybb->get_input('awaymonth', MyBB::INPUT_INT);
 442              $returndate[2] = $mybb->get_input('awayyear', MyBB::INPUT_INT);
 443              $user['awayreason'] = htmlspecialchars_uni($mybb->get_input('awayreason'));
 444          }
 445          else
 446          {
 447              $user['awayreason'] = htmlspecialchars_uni($user['awayreason']);
 448              if($mybb->user['away'] == 1)
 449              {
 450                  $awaydate = my_date($mybb->settings['dateformat'], $mybb->user['awaydate']);
 451                  $awaycheck[1] = "checked=\"checked\"";
 452                  $awaynotice = $lang->sprintf($lang->away_notice_away, $awaydate);
 453              }
 454              else
 455              {
 456                  $awaynotice = $lang->away_notice;
 457                  $awaycheck[0] = "checked=\"checked\"";
 458              }
 459              $returndate = explode("-", $mybb->user['returndate']);
 460              if(!isset($returndate[1]))
 461              {
 462                  $returndate[1] = 0;
 463              }
 464              if(!isset($returndate[2]))
 465              {
 466                  $returndate[2] = '';
 467              }
 468          }
 469  
 470          $returndatesel = '';
 471          for($day = 1; $day <= 31; ++$day)
 472          {
 473              if($returndate[0] == $day)
 474              {
 475                  $selected = "selected=\"selected\"";
 476              }
 477              else
 478              {
 479                  $selected = '';
 480              }
 481  
 482              eval("\$returndatesel .= \"".$templates->get("usercp_profile_day")."\";");
 483          }
 484  
 485          $returndatemonthsel = array();
 486          foreach(range(1, 12) as $month)
 487          {
 488              $returndatemonthsel[$month] = '';
 489          }
 490          $returndatemonthsel[$returndate[1]] = "selected";
 491  
 492          eval("\$awaysection = \"".$templates->get("usercp_profile_away")."\";");
 493      }
 494  
 495      // Custom profile fields baby!
 496      $altbg = "trow1";
 497      $requiredfields = $customfields = '';
 498      $mybb->input['profile_fields'] = $mybb->get_input('profile_fields', MyBB::INPUT_ARRAY);
 499  
 500      $pfcache = $cache->read('profilefields');
 501  
 502      if(is_array($pfcache))
 503      {
 504          foreach($pfcache as $profilefield)
 505          {
 506              if(!is_member($profilefield['editableby']) || ($profilefield['postnum'] && $profilefield['postnum'] > $mybb->user['postnum']))
 507              {
 508                  continue;
 509              }
 510  
 511              $profilefield['type'] = htmlspecialchars_uni($profilefield['type']);
 512              $profilefield['name'] = htmlspecialchars_uni($profilefield['name']);
 513              $profilefield['description'] = htmlspecialchars_uni($profilefield['description']);
 514              $thing = explode("\n", $profilefield['type'], "2");
 515              $type = $thing[0];
 516              if(isset($thing[1]))
 517              {
 518                  $options = $thing[1];
 519              }
 520              else
 521              {
 522                  $options = array();
 523              }
 524              $field = "fid{$profilefield['fid']}";
 525              $select = '';
 526              if($errors)
 527              {
 528                  if(!isset($mybb->input['profile_fields'][$field]))
 529                  {
 530                      $mybb->input['profile_fields'][$field] = '';
 531                  }
 532                  $userfield = $mybb->input['profile_fields'][$field];
 533              }
 534              else
 535              {
 536                  $userfield = $user[$field];
 537              }
 538              if($type == "multiselect")
 539              {
 540                  if($errors)
 541                  {
 542                      $useropts = $userfield;
 543                  }
 544                  else
 545                  {
 546                      $useropts = explode("\n", $userfield);
 547                  }
 548                  if(is_array($useropts))
 549                  {
 550                      foreach($useropts as $key => $val)
 551                      {
 552                          $val = htmlspecialchars_uni($val);
 553                          $seloptions[$val] = $val;
 554                      }
 555                  }
 556                  $expoptions = explode("\n", $options);
 557                  if(is_array($expoptions))
 558                  {
 559                      foreach($expoptions as $key => $val)
 560                      {
 561                          $val = trim($val);
 562                          $val = str_replace("\n", "\\n", $val);
 563  
 564                          $sel = "";
 565                          if(isset($seloptions[$val]) && $val == $seloptions[$val])
 566                          {
 567                              $sel = " selected=\"selected\"";
 568                          }
 569  
 570                          eval("\$select .= \"".$templates->get("usercp_profile_profilefields_select_option")."\";");
 571                      }
 572                      if(!$profilefield['length'])
 573                      {
 574                          $profilefield['length'] = 3;
 575                      }
 576  
 577                      eval("\$code = \"".$templates->get("usercp_profile_profilefields_multiselect")."\";");
 578                  }
 579              }
 580              elseif($type == "select")
 581              {
 582                  $expoptions = explode("\n", $options);
 583                  if(is_array($expoptions))
 584                  {
 585                      foreach($expoptions as $key => $val)
 586                      {
 587                          $val = trim($val);
 588                          $val = str_replace("\n", "\\n", $val);
 589                          $sel = "";
 590                          if($val == htmlspecialchars_uni($userfield))
 591                          {
 592                              $sel = " selected=\"selected\"";
 593                          }
 594  
 595                          eval("\$select .= \"".$templates->get("usercp_profile_profilefields_select_option")."\";");
 596                      }
 597                      if(!$profilefield['length'])
 598                      {
 599                          $profilefield['length'] = 1;
 600                      }
 601  
 602                      eval("\$code = \"".$templates->get("usercp_profile_profilefields_select")."\";");
 603                  }
 604              }
 605              elseif($type == "radio")
 606              {
 607                  $userfield = htmlspecialchars_uni($userfield);
 608                  $expoptions = explode("\n", $options);
 609                  if(is_array($expoptions))
 610                  {
 611                      foreach($expoptions as $key => $val)
 612                      {
 613                          $checked = "";
 614                          if($val == $userfield)
 615                          {
 616                              $checked = " checked=\"checked\"";
 617                          }
 618  
 619                          eval("\$code .= \"".$templates->get("usercp_profile_profilefields_radio")."\";");
 620                      }
 621                  }
 622              }
 623              elseif($type == "checkbox")
 624              {
 625                  $userfield = htmlspecialchars_uni($userfield);
 626                  if($errors)
 627                  {
 628                      $useropts = $userfield;
 629                  }
 630                  else
 631                  {
 632                      $useropts = explode("\n", $userfield);
 633                  }
 634                  if(is_array($useropts))
 635                  {
 636                      foreach($useropts as $key => $val)
 637                      {
 638                          $seloptions[$val] = $val;
 639                      }
 640                  }
 641                  $expoptions = explode("\n", $options);
 642                  if(is_array($expoptions))
 643                  {
 644                      foreach($expoptions as $key => $val)
 645                      {
 646                          $checked = "";
 647                          if(isset($seloptions[$val]) && $val == $seloptions[$val])
 648                          {
 649                              $checked = " checked=\"checked\"";
 650                          }
 651  
 652                          eval("\$code .= \"".$templates->get("usercp_profile_profilefields_checkbox")."\";");
 653                      }
 654                  }
 655              }
 656              elseif($type == "textarea")
 657              {
 658                  $value = htmlspecialchars_uni($userfield);
 659                  eval("\$code = \"".$templates->get("usercp_profile_profilefields_textarea")."\";");
 660              }
 661              else
 662              {
 663                  $value = htmlspecialchars_uni($userfield);
 664                  $maxlength = "";
 665                  if($profilefield['maxlength'] > 0)
 666                  {
 667                      $maxlength = " maxlength=\"{$profilefield['maxlength']}\"";
 668                  }
 669  
 670                  eval("\$code = \"".$templates->get("usercp_profile_profilefields_text")."\";");
 671              }
 672  
 673              if($profilefield['required'] == 1)
 674              {
 675                  eval("\$requiredfields .= \"".$templates->get("usercp_profile_customfield")."\";");
 676              }
 677              else
 678              {
 679                  eval("\$customfields .= \"".$templates->get("usercp_profile_customfield")."\";");
 680              }
 681              $altbg = alt_trow();
 682              $code = "";
 683              $select = "";
 684              $val = "";
 685              $options = "";
 686              $expoptions = "";
 687              $useropts = "";
 688              $seloptions = array();
 689          }
 690      }
 691      if($customfields)
 692      {
 693          eval("\$customfields = \"".$templates->get("usercp_profile_profilefields")."\";");
 694      }
 695  
 696      if($mybb->usergroup['cancustomtitle'] == 1)
 697      {
 698          if($mybb->usergroup['usertitle'] == "")
 699          {
 700              $defaulttitle = '';
 701              $usertitles = $cache->read('usertitles');
 702  
 703              foreach($usertitles as $title)
 704              {
 705                  if($title['posts'] <= $mybb->user['postnum'])
 706                  {
 707                      $defaulttitle = htmlspecialchars_uni($title['title']);
 708                      break;
 709                  }
 710              }
 711          }
 712          else
 713          {
 714              $defaulttitle = htmlspecialchars_uni($mybb->usergroup['usertitle']);
 715          }
 716  
 717          $newtitle = '';
 718          if(trim($user['usertitle']) == '')
 719          {
 720              $lang->current_custom_usertitle = '';
 721          }
 722          else
 723          {
 724              if($errors)
 725              {
 726                  $newtitle = htmlspecialchars_uni($user['usertitle']);
 727                  $user['usertitle'] = $mybb->user['usertitle'];
 728              }
 729          }
 730  
 731          $user['usertitle'] = htmlspecialchars_uni($user['usertitle']);
 732  
 733          $currentcustom = $reverttitle = '';
 734          if(!empty($mybb->user['usertitle']))
 735          {
 736              eval("\$currentcustom = \"".$templates->get("usercp_profile_customtitle_currentcustom")."\";");
 737  
 738              if($mybb->user['usertitle'] != $mybb->usergroup['usertitle'])
 739              {
 740                  eval("\$reverttitle = \"".$templates->get("usercp_profile_customtitle_reverttitle")."\";");
 741              }
 742          }
 743  
 744          eval("\$customtitle = \"".$templates->get("usercp_profile_customtitle")."\";");
 745      }
 746      else
 747      {
 748          $customtitle = "";
 749      }
 750  
 751      if($mybb->usergroup['canchangewebsite'] == 1)
 752      {
 753          eval("\$website = \"".$templates->get("usercp_profile_website")."\";");
 754      }
 755  
 756      $plugins->run_hooks("usercp_profile_end");
 757  
 758      eval("\$editprofile = \"".$templates->get("usercp_profile")."\";");
 759      output_page($editprofile);
 760  }
 761  
 762  if($mybb->input['action'] == "do_options" && $mybb->request_method == "post")
 763  {
 764      // Verify incoming POST request
 765      verify_post_check($mybb->get_input('my_post_key'));
 766  
 767      $user = array();
 768  
 769      $plugins->run_hooks("usercp_do_options_start");
 770  
 771      // Set up user handler.
 772      require_once  MYBB_ROOT."inc/datahandlers/user.php";
 773      $userhandler = new UserDataHandler("update");
 774  
 775      $user = array_merge($user, array(
 776          "uid" => $mybb->user['uid'],
 777          "style" => $mybb->get_input('style', MyBB::INPUT_INT),
 778          "dateformat" => $mybb->get_input('dateformat', MyBB::INPUT_INT),
 779          "timeformat" => $mybb->get_input('timeformat', MyBB::INPUT_INT),
 780          "timezone" => $db->escape_string($mybb->get_input('timezoneoffset')),
 781          "language" => $mybb->get_input('language'),
 782          'usergroup'    => $mybb->user['usergroup'],
 783          'additionalgroups'    => $mybb->user['additionalgroups']
 784      ));
 785  
 786      $user['options'] = array(
 787          "allownotices" => $mybb->get_input('allownotices', MyBB::INPUT_INT),
 788          "hideemail" => $mybb->get_input('hideemail', MyBB::INPUT_INT),
 789          "subscriptionmethod" => $mybb->get_input('subscriptionmethod', MyBB::INPUT_INT),
 790          "invisible" => $mybb->get_input('invisible', MyBB::INPUT_INT),
 791          "dstcorrection" => $mybb->get_input('dstcorrection', MyBB::INPUT_INT),
 792          "threadmode" => $mybb->get_input('threadmode'),
 793          "showimages" => $mybb->get_input('showimages', MyBB::INPUT_INT),
 794          "showvideos" => $mybb->get_input('showvideos', MyBB::INPUT_INT),
 795          "showsigs" => $mybb->get_input('showsigs', MyBB::INPUT_INT),
 796          "showavatars" => $mybb->get_input('showavatars', MyBB::INPUT_INT),
 797          "showquickreply" => $mybb->get_input('showquickreply', MyBB::INPUT_INT),
 798          "receivepms" => $mybb->get_input('receivepms', MyBB::INPUT_INT),
 799          "pmnotice" => $mybb->get_input('pmnotice', MyBB::INPUT_INT),
 800          "receivefrombuddy" => $mybb->get_input('receivefrombuddy', MyBB::INPUT_INT),
 801          "daysprune" => $mybb->get_input('daysprune', MyBB::INPUT_INT),
 802          "showcodebuttons" => $mybb->get_input('showcodebuttons', MyBB::INPUT_INT),
 803          "sourceeditor" => $mybb->get_input('sourceeditor', MyBB::INPUT_INT),
 804          "pmnotify" => $mybb->get_input('pmnotify', MyBB::INPUT_INT),
 805          "buddyrequestspm" => $mybb->get_input('buddyrequestspm', MyBB::INPUT_INT),
 806          "buddyrequestsauto" => $mybb->get_input('buddyrequestsauto', MyBB::INPUT_INT),
 807          "showredirect" => $mybb->get_input('showredirect', MyBB::INPUT_INT),
 808          "classicpostbit" => $mybb->get_input('classicpostbit', MyBB::INPUT_INT)
 809      );
 810  
 811      if($mybb->settings['usertppoptions'])
 812      {
 813          $user['options']['tpp'] = $mybb->get_input('tpp', MyBB::INPUT_INT);
 814      }
 815  
 816      if($mybb->settings['userpppoptions'])
 817      {
 818          $user['options']['ppp'] = $mybb->get_input('ppp', MyBB::INPUT_INT);
 819      }
 820  
 821      $userhandler->set_data($user);
 822  
 823      if(!$userhandler->validate_user())
 824      {
 825          $errors = $userhandler->get_friendly_errors();
 826          $errors = inline_error($errors);
 827          $mybb->input['action'] = "options";
 828      }
 829      else
 830      {
 831          $userhandler->update_user();
 832  
 833          $plugins->run_hooks("usercp_do_options_end");
 834  
 835          redirect("usercp.php?action=options", $lang->redirect_optionsupdated);
 836      }
 837  }
 838  
 839  if($mybb->input['action'] == "options")
 840  {
 841      if($errors != '')
 842      {
 843          $user = $mybb->input;
 844      }
 845      else
 846      {
 847          $user = $mybb->user;
 848      }
 849  
 850      $plugins->run_hooks("usercp_options_start");
 851  
 852      $languages = $lang->get_languages();
 853      $board_language = $langoptions = '';
 854      if(count($languages) > 1)
 855      {
 856          foreach($languages as $name => $language)
 857          {
 858              $language = htmlspecialchars_uni($language);
 859  
 860              $sel = '';
 861              if(isset($user['language']) && $user['language'] == $name)
 862              {
 863                  $sel = " selected=\"selected\"";
 864              }
 865  
 866              eval('$langoptions .= "'.$templates->get('usercp_options_language_option').'";');
 867          }
 868  
 869          eval('$board_language = "'.$templates->get('usercp_options_language').'";');
 870      }
 871  
 872      // Lets work out which options the user has selected and check the boxes
 873      if(isset($user['allownotices']) && $user['allownotices'] == 1)
 874      {
 875          $allownoticescheck = "checked=\"checked\"";
 876      }
 877      else
 878      {
 879          $allownoticescheck = "";
 880      }
 881  
 882      $canbeinvisible = '';
 883  
 884      // Check usergroup permission before showing invisible check box
 885      if($mybb->usergroup['canbeinvisible'] == 1)
 886      {
 887          if(isset($user['invisible']) && $user['invisible'] == 1)
 888          {
 889              $invisiblecheck = "checked=\"checked\"";
 890          }
 891          else
 892          {
 893              $invisiblecheck = "";
 894          }
 895          eval('$canbeinvisible = "'.$templates->get("usercp_options_invisible")."\";");
 896      }
 897  
 898      if(isset($user['hideemail']) && $user['hideemail'] == 1)
 899      {
 900          $hideemailcheck = "checked=\"checked\"";
 901      }
 902      else
 903      {
 904          $hideemailcheck = "";
 905      }
 906  
 907      $no_auto_subscribe_selected = $instant_email_subscribe_selected = $instant_pm_subscribe_selected = $no_subscribe_selected = '';
 908      if(isset($user['subscriptionmethod']) && $user['subscriptionmethod'] == 1)
 909      {
 910          $no_subscribe_selected = "selected=\"selected\"";
 911      }
 912      elseif(isset($user['subscriptionmethod']) && $user['subscriptionmethod'] == 2)
 913      {
 914          $instant_email_subscribe_selected = "selected=\"selected\"";
 915      }
 916      elseif(isset($user['subscriptionmethod']) && $user['subscriptionmethod'] == 3)
 917      {
 918          $instant_pm_subscribe_selected = "selected=\"selected\"";
 919      }
 920      else
 921      {
 922          $no_auto_subscribe_selected = "selected=\"selected\"";
 923      }
 924  
 925      if(isset($user['showimages']) && $user['showimages'] == 1)
 926      {
 927          $showimagescheck = "checked=\"checked\"";
 928      }
 929      else
 930      {
 931          $showimagescheck = "";
 932      }
 933  
 934      if(isset($user['showvideos']) && $user['showvideos'] == 1)
 935      {
 936          $showvideoscheck = "checked=\"checked\"";
 937      }
 938      else
 939      {
 940          $showvideoscheck = "";
 941      }
 942  
 943      if(isset($user['showsigs']) && $user['showsigs'] == 1)
 944      {
 945          $showsigscheck = "checked=\"checked\"";
 946      }
 947      else
 948      {
 949          $showsigscheck = "";
 950      }
 951  
 952      if(isset($user['showavatars']) && $user['showavatars'] == 1)
 953      {
 954          $showavatarscheck = "checked=\"checked\"";
 955      }
 956      else
 957      {
 958          $showavatarscheck = "";
 959      }
 960  
 961      if(isset($user['showquickreply']) && $user['showquickreply'] == 1)
 962      {
 963          $showquickreplycheck = "checked=\"checked\"";
 964      }
 965      else
 966      {
 967          $showquickreplycheck = "";
 968      }
 969  
 970      if(isset($user['receivepms']) && $user['receivepms'] == 1)
 971      {
 972          $receivepmscheck = "checked=\"checked\"";
 973      }
 974      else
 975      {
 976          $receivepmscheck = "";
 977      }
 978  
 979      if(isset($user['receivefrombuddy']) && $user['receivefrombuddy'] == 1)
 980      {
 981          $receivefrombuddycheck = "checked=\"checked\"";
 982      }
 983      else
 984      {
 985          $receivefrombuddycheck = "";
 986      }
 987  
 988      if(isset($user['pmnotice']) && $user['pmnotice'] >= 1)
 989      {
 990          $pmnoticecheck = " checked=\"checked\"";
 991      }
 992      else
 993      {
 994          $pmnoticecheck = "";
 995      }
 996  
 997      $dst_auto_selected = $dst_enabled_selected = $dst_disabled_selected = '';
 998      if(isset($user['dstcorrection']) && $user['dstcorrection'] == 2)
 999      {
1000          $dst_auto_selected = "selected=\"selected\"";
1001      }
1002      elseif(isset($user['dstcorrection']) && $user['dstcorrection'] == 1)
1003      {
1004          $dst_enabled_selected = "selected=\"selected\"";
1005      }
1006      else
1007      {
1008          $dst_disabled_selected = "selected=\"selected\"";
1009      }
1010  
1011      if(isset($user['showcodebuttons']) && $user['showcodebuttons'] == 1)
1012      {
1013          $showcodebuttonscheck = "checked=\"checked\"";
1014      }
1015      else
1016      {
1017          $showcodebuttonscheck = "";
1018      }
1019  
1020      if(isset($user['sourceeditor']) && $user['sourceeditor'] == 1)
1021      {
1022          $sourcemodecheck = "checked=\"checked\"";
1023      }
1024      else
1025      {
1026          $sourcemodecheck = "";
1027      }
1028  
1029      if(isset($user['showredirect']) && $user['showredirect'] != 0)
1030      {
1031          $showredirectcheck = "checked=\"checked\"";
1032      }
1033      else
1034      {
1035          $showredirectcheck = "";
1036      }
1037  
1038      if(isset($user['pmnotify']) && $user['pmnotify'] != 0)
1039      {
1040          $pmnotifycheck = "checked=\"checked\"";
1041      }
1042      else
1043      {
1044          $pmnotifycheck = '';
1045      }
1046  
1047      if(isset($user['buddyrequestspm']) && $user['buddyrequestspm'] != 0)
1048      {
1049          $buddyrequestspmcheck = "checked=\"checked\"";
1050      }
1051      else
1052      {
1053          $buddyrequestspmcheck = '';
1054      }
1055  
1056      if(isset($user['buddyrequestsauto']) && $user['buddyrequestsauto'] != 0)
1057      {
1058          $buddyrequestsautocheck = "checked=\"checked\"";
1059      }
1060      else
1061      {
1062          $buddyrequestsautocheck = '';
1063      }
1064  
1065      if(!isset($user['threadmode']) || ($user['threadmode'] != "threaded" && $user['threadmode'] != "linear"))
1066      {
1067          $user['threadmode'] = ''; // Leave blank to show default
1068      }
1069  
1070      if(isset($user['classicpostbit']) && $user['classicpostbit'] != 0)
1071      {
1072          $classicpostbitcheck = "checked=\"checked\"";
1073      }
1074      else
1075      {
1076          $classicpostbitcheck = '';
1077      }
1078  
1079      $date_format_options = $dateformat = '';
1080      foreach($date_formats as $key => $format)
1081      {
1082          $selected = '';
1083          if(isset($user['dateformat']) && $user['dateformat'] == $key)
1084          {
1085              $selected = " selected=\"selected\"";
1086          }
1087  
1088          $dateformat = my_date($format, TIME_NOW, "", 0);
1089          eval("\$date_format_options .= \"".$templates->get("usercp_options_date_format")."\";");
1090      }
1091  
1092      $time_format_options = $timeformat = '';
1093      foreach($time_formats as $key => $format)
1094      {
1095          $selected = '';
1096          if(isset($user['timeformat']) && $user['timeformat'] == $key)
1097          {
1098              $selected = " selected=\"selected\"";
1099          }
1100  
1101          $timeformat = my_date($format, TIME_NOW, "", 0);
1102          eval("\$time_format_options .= \"".$templates->get("usercp_options_time_format")."\";");
1103      }
1104  
1105      $tzselect = build_timezone_select("timezoneoffset", $mybb->user['timezone'], true);
1106  
1107      $pms_from_buddys = '';
1108      if($mybb->settings['allowbuddyonly'] == 1)
1109      {
1110          eval("\$pms_from_buddys = \"".$templates->get("usercp_options_pms_from_buddys")."\";");
1111      }
1112  
1113      $pms = '';
1114      if($mybb->settings['enablepms'] != 0 && $mybb->usergroup['canusepms'] == 1)
1115      {
1116          eval("\$pms = \"".$templates->get("usercp_options_pms")."\";");
1117      }
1118  
1119      $quick_reply = '';
1120      if($mybb->settings['quickreply'] == 1)
1121      {
1122          eval("\$quick_reply = \"".$templates->get("usercp_options_quick_reply")."\";");
1123      }
1124  
1125      $threadview = array('linear' => '', 'threaded' => '');
1126      if(isset($user['threadmode']) && is_scalar($user['threadmode']))
1127      {
1128          $threadview[$user['threadmode']] = 'selected="selected"';
1129      }
1130      $daysprunesel = array(1 => '', 5 => '', 10 => '', 20 => '', 50 => '', 75 => '', 100 => '', 365 => '', 9999 => '');
1131      if(isset($user['daysprune']) && is_numeric($user['daysprune']))
1132      {
1133          $daysprunesel[$user['daysprune']] = 'selected="selected"';
1134      }
1135      if(!isset($user['style']))
1136      {
1137          $user['style'] = '';
1138      }
1139  
1140      $board_style = $stylelist = '';
1141      $stylelist = build_theme_select("style", $user['style']);
1142  
1143      if(!empty($stylelist))
1144      {
1145          eval('$board_style = "'.$templates->get('usercp_options_style').'";');
1146      }
1147  
1148      $tppselect = $pppselect = '';
1149      if($mybb->settings['usertppoptions'])
1150      {
1151          $explodedtpp = explode(",", $mybb->settings['usertppoptions']);
1152          $tppoptions = $tpp_option = '';
1153          if(is_array($explodedtpp))
1154          {
1155              foreach($explodedtpp as $key => $val)
1156              {
1157                  $val = trim($val);
1158                  $selected = "";
1159                  if(isset($user['tpp']) && $user['tpp'] == $val)
1160                  {
1161                      $selected = " selected=\"selected\"";
1162                  }
1163  
1164                  $tpp_option = $lang->sprintf($lang->tpp_option, $val);
1165                  eval("\$tppoptions .= \"".$templates->get("usercp_options_tppselect_option")."\";");
1166              }
1167          }
1168          eval("\$tppselect = \"".$templates->get("usercp_options_tppselect")."\";");
1169      }
1170  
1171      if($mybb->settings['userpppoptions'])
1172      {
1173          $explodedppp = explode(",", $mybb->settings['userpppoptions']);
1174          $pppoptions = $ppp_option = '';
1175          if(is_array($explodedppp))
1176          {
1177              foreach($explodedppp as $key => $val)
1178              {
1179                  $val = trim($val);
1180                  $selected = "";
1181                  if(isset($user['ppp']) && $user['ppp'] == $val)
1182                  {
1183                      $selected = " selected=\"selected\"";
1184                  }
1185  
1186                  $ppp_option = $lang->sprintf($lang->ppp_option, $val);
1187                  eval("\$pppoptions .= \"".$templates->get("usercp_options_pppselect_option")."\";");
1188              }
1189          }
1190          eval("\$pppselect = \"".$templates->get("usercp_options_pppselect")."\";");
1191      }
1192  
1193      $plugins->run_hooks("usercp_options_end");
1194  
1195      eval("\$editprofile = \"".$templates->get("usercp_options")."\";");
1196      output_page($editprofile);
1197  }
1198  
1199  if($mybb->input['action'] == "do_email" && $mybb->request_method == "post")
1200  {
1201      // Verify incoming POST request
1202      verify_post_check($mybb->get_input('my_post_key'));
1203  
1204      $errors = array();
1205  
1206      $plugins->run_hooks("usercp_do_email_start");
1207      if(validate_password_from_uid($mybb->user['uid'], $mybb->get_input('password')) == false)
1208      {
1209          $errors[] = $lang->error_invalidpassword;
1210      }
1211      else
1212      {
1213          // Set up user handler.
1214          require_once  MYBB_ROOT."inc/datahandlers/user.php";
1215          $userhandler = new UserDataHandler("update");
1216  
1217          $user = array(
1218              "uid" => $mybb->user['uid'],
1219              "email" => $mybb->get_input('email'),
1220              "email2" => $mybb->get_input('email2')
1221          );
1222  
1223          $userhandler->set_data($user);
1224  
1225          if(!$userhandler->validate_user())
1226          {
1227              $errors = $userhandler->get_friendly_errors();
1228          }
1229          else
1230          {
1231              $activation = false;
1232              // Checking for pending activations for non-activated accounts
1233              if($mybb->user['usergroup'] == 5 && ($mybb->settings['regtype'] == "verify" || $mybb->settings['regtype'] == "both"))
1234              {
1235                  $query = $db->simple_select("awaitingactivation", "*", "uid='".$mybb->user['uid']."' AND (type='r' OR type='b')");
1236                  $activation = $db->fetch_array($query);
1237              }
1238              if($activation)
1239              {
1240                  $userhandler->update_user();
1241  
1242                  $db->delete_query("awaitingactivation", "uid='".$mybb->user['uid']."'");
1243  
1244                  // Send new activation mail for non-activated accounts
1245                  $activationcode = random_str();
1246                  $activationarray = array(
1247                      "uid" => $mybb->user['uid'],
1248                      "dateline" => TIME_NOW,
1249                      "code" => $activationcode,
1250                      "type" => $activation['type']
1251                  );
1252                  $db->insert_query("awaitingactivation", $activationarray);
1253                  $emailsubject = $lang->sprintf($lang->emailsubject_activateaccount, $mybb->settings['bbname']);
1254                  switch($mybb->settings['username_method'])
1255                  {
1256                      case 0:
1257                          $emailmessage = $lang->sprintf($lang->email_activateaccount, $mybb->user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $mybb->user['uid'], $activationcode);
1258                          break;
1259                      case 1:
1260                          $emailmessage = $lang->sprintf($lang->email_activateaccount1, $mybb->user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $mybb->user['uid'], $activationcode);
1261                          break;
1262                      case 2:
1263                          $emailmessage = $lang->sprintf($lang->email_activateaccount2, $mybb->user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $mybb->user['uid'], $activationcode);
1264                          break;
1265                      default:
1266                          $emailmessage = $lang->sprintf($lang->email_activateaccount, $mybb->user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $mybb->user['uid'], $activationcode);
1267                          break;
1268                  }
1269                  my_mail($mybb->user['email'], $emailsubject, $emailmessage);
1270  
1271                  $plugins->run_hooks("usercp_do_email_changed");
1272                  redirect("usercp.php?action=email", $lang->redirect_emailupdated);
1273              }
1274              elseif($mybb->usergroup['cancp'] != 1 && ($mybb->settings['regtype'] == "verify" || $mybb->settings['regtype'] == "both"))
1275              {
1276                  $uid = $mybb->user['uid'];
1277                  $username = $mybb->user['username'];
1278  
1279                  // Emails require verification
1280                  $activationcode = random_str();
1281                  $db->delete_query("awaitingactivation", "uid='".$mybb->user['uid']."'");
1282  
1283                  $newactivation = array(
1284                      "uid" => $mybb->user['uid'],
1285                      "dateline" => TIME_NOW,
1286                      "code" => $activationcode,
1287                      "type" => "e",
1288                      "misc" => $db->escape_string($mybb->get_input('email'))
1289                  );
1290  
1291                  $db->insert_query("awaitingactivation", $newactivation);
1292  
1293                  $mail_message = $lang->sprintf($lang->email_changeemail, $mybb->user['username'], $mybb->settings['bbname'], $mybb->user['email'], $mybb->get_input('email'), $mybb->settings['bburl'], $activationcode, $mybb->user['username'], $mybb->user['uid']);
1294  
1295                  $lang->emailsubject_changeemail = $lang->sprintf($lang->emailsubject_changeemail, $mybb->settings['bbname']);
1296                  my_mail($mybb->get_input('email'), $lang->emailsubject_changeemail, $mail_message);
1297  
1298                  $plugins->run_hooks("usercp_do_email_verify");
1299                  error($lang->redirect_changeemail_activation);
1300              }
1301              else
1302              {
1303                  $userhandler->update_user();
1304                  // Email requires no activation
1305                  $mail_message = $lang->sprintf($lang->email_changeemail_noactivation, $mybb->user['username'], $mybb->settings['bbname'], $mybb->user['email'], $mybb->get_input('email'), $mybb->settings['bburl']);
1306                  my_mail($mybb->get_input('email'), $lang->sprintf($lang->emailsubject_changeemail, $mybb->settings['bbname']), $mail_message);
1307                  $plugins->run_hooks("usercp_do_email_changed");
1308                  redirect("usercp.php?action=email", $lang->redirect_emailupdated);
1309              }
1310          }
1311      }
1312      if(count($errors) > 0)
1313      {
1314          $mybb->input['action'] = "email";
1315          $errors = inline_error($errors);
1316      }
1317  }
1318  
1319  if($mybb->input['action'] == "email")
1320  {
1321      // Coming back to this page after one or more errors were experienced, show fields the user previously entered (with the exception of the password)
1322      if($errors)
1323      {
1324          $email = htmlspecialchars_uni($mybb->get_input('email'));
1325          $email2 = htmlspecialchars_uni($mybb->get_input('email2'));
1326      }
1327      else
1328      {
1329          $email = $email2 = '';
1330      }
1331  
1332      $plugins->run_hooks("usercp_email");
1333  
1334      eval("\$changemail = \"".$templates->get("usercp_email")."\";");
1335      output_page($changemail);
1336  }
1337  
1338  if($mybb->input['action'] == "do_password" && $mybb->request_method == "post")
1339  {
1340      // Verify incoming POST request
1341      verify_post_check($mybb->get_input('my_post_key'));
1342  
1343      $user = array();
1344      $errors = array();
1345  
1346      $plugins->run_hooks("usercp_do_password_start");
1347      if(validate_password_from_uid($mybb->user['uid'], $mybb->get_input('oldpassword')) == false)
1348      {
1349          $errors[] = $lang->error_invalidpassword;
1350      }
1351      else
1352      {
1353          // Set up user handler.
1354          require_once  MYBB_ROOT."inc/datahandlers/user.php";
1355          $userhandler = new UserDataHandler("update");
1356  
1357          $user = array_merge($user, array(
1358              "uid" => $mybb->user['uid'],
1359              "password" => $mybb->get_input('password'),
1360              "password2" => $mybb->get_input('password2')
1361          ));
1362  
1363          $userhandler->set_data($user);
1364  
1365          if(!$userhandler->validate_user())
1366          {
1367              $errors = $userhandler->get_friendly_errors();
1368          }
1369          else
1370          {
1371              $userhandler->update_user();
1372              my_setcookie("mybbuser", $mybb->user['uid']."_".$userhandler->data['loginkey'], null, true, "lax");
1373  
1374              // Notify the user by email that their password has been changed
1375              $mail_message = $lang->sprintf($lang->email_changepassword, $mybb->user['username'], $mybb->user['email'], $mybb->settings['bbname'], $mybb->settings['bburl']);
1376              $lang->emailsubject_changepassword = $lang->sprintf($lang->emailsubject_changepassword, $mybb->settings['bbname']);
1377              my_mail($mybb->user['email'], $lang->emailsubject_changepassword, $mail_message);
1378  
1379              $plugins->run_hooks("usercp_do_password_end");
1380              redirect("usercp.php?action=password", $lang->redirect_passwordupdated);
1381          }
1382      }
1383      if(count($errors) > 0)
1384      {
1385              $mybb->input['action'] = "password";
1386              $errors = inline_error($errors);
1387      }
1388  }
1389  
1390  if($mybb->input['action'] == "password")
1391  {
1392      $plugins->run_hooks("usercp_password");
1393  
1394      eval("\$editpassword = \"".$templates->get("usercp_password")."\";");
1395      output_page($editpassword);
1396  }
1397  
1398  if($mybb->input['action'] == "do_changename" && $mybb->request_method == "post")
1399  {
1400      // Verify incoming POST request
1401      verify_post_check($mybb->get_input('my_post_key'));
1402  
1403      $errors = array();
1404  
1405      if($mybb->usergroup['canchangename'] != 1)
1406      {
1407          error_no_permission();
1408      }
1409  
1410      $user = array();
1411  
1412      $plugins->run_hooks("usercp_do_changename_start");
1413  
1414      if(validate_password_from_uid($mybb->user['uid'], $mybb->get_input('password')) == false)
1415      {
1416          $errors[] = $lang->error_invalidpassword;
1417      }
1418      else
1419      {
1420          // Set up user handler.
1421          require_once  MYBB_ROOT."inc/datahandlers/user.php";
1422          $userhandler = new UserDataHandler("update");
1423  
1424          $user = array_merge($user, array(
1425              "uid" => $mybb->user['uid'],
1426              "username" => $mybb->get_input('username')
1427          ));
1428  
1429          $userhandler->set_data($user);
1430  
1431          if(!$userhandler->validate_user())
1432          {
1433              $errors = $userhandler->get_friendly_errors();
1434          }
1435          else
1436          {
1437              $userhandler->update_user();
1438              $plugins->run_hooks("usercp_do_changename_end");
1439              redirect("usercp.php?action=changename", $lang->redirect_namechanged);
1440          }
1441      }
1442      if(count($errors) > 0)
1443      {
1444          $errors = inline_error($errors);
1445          $mybb->input['action'] = "changename";
1446      }
1447  }
1448  
1449  if($mybb->input['action'] == "changename")
1450  {
1451      $plugins->run_hooks("usercp_changename_start");
1452      if($mybb->usergroup['canchangename'] != 1)
1453      {
1454          error_no_permission();
1455      }
1456  
1457      // Coming back to this page after one or more errors were experienced, show field the user previously entered (with the exception of the password)
1458      if($errors)
1459      {
1460          $username = htmlspecialchars_uni($mybb->get_input('username'));
1461      }
1462      else
1463      {
1464          $username = '';
1465      }
1466  
1467      $plugins->run_hooks("usercp_changename_end");
1468  
1469      eval("\$changename = \"".$templates->get("usercp_changename")."\";");
1470      output_page($changename);
1471  }
1472  
1473  if($mybb->input['action'] == "do_subscriptions")
1474  {
1475      // Verify incoming POST request
1476      verify_post_check($mybb->get_input('my_post_key'));
1477  
1478      if(!isset($mybb->input['check']) || !is_array($mybb->input['check']))
1479      {
1480          error($lang->no_subscriptions_selected);
1481      }
1482  
1483      $plugins->run_hooks("usercp_do_subscriptions_start");
1484  
1485      // Clean input - only accept integers thanks!
1486      $mybb->input['check'] = array_map('intval', $mybb->get_input('check', MyBB::INPUT_ARRAY));
1487      $tids = implode(",", $mybb->input['check']);
1488  
1489      // Deleting these subscriptions?
1490      if($mybb->get_input('do') == "delete")
1491      {
1492          $db->delete_query("threadsubscriptions", "tid IN ($tids) AND uid='{$mybb->user['uid']}'");
1493      }
1494      // Changing subscription type
1495      else
1496      {
1497          if($mybb->get_input('do') == "no_notification")
1498          {
1499              $new_notification = 0;
1500          }
1501          elseif($mybb->get_input('do') == "email_notification")
1502          {
1503              $new_notification = 1;
1504          }
1505          elseif($mybb->get_input('do') == "pm_notification")
1506          {
1507              $new_notification = 2;
1508          }
1509  
1510          // Update
1511          $update_array = array("notification" => $new_notification);
1512          $db->update_query("threadsubscriptions", $update_array, "tid IN ($tids) AND uid='{$mybb->user['uid']}'");
1513      }
1514  
1515      // Done, redirect
1516      redirect("usercp.php?action=subscriptions", $lang->redirect_subscriptions_updated);
1517  }
1518  
1519  if($mybb->input['action'] == "subscriptions")
1520  {
1521      $plugins->run_hooks("usercp_subscriptions_start");
1522  
1523      // Thread visiblity
1524      $where = array(
1525          "s.uid={$mybb->user['uid']}",
1526          get_visible_where('t')
1527      );
1528  
1529      if($unviewable_forums = get_unviewable_forums(true))
1530      {
1531          $where[] = "t.fid NOT IN ({$unviewable_forums})";
1532      }
1533  
1534      if($inactive_forums = get_inactive_forums())
1535      {
1536          $where[] = "t.fid NOT IN ({$inactive_forums})";
1537      }
1538  
1539      $where = implode(' AND ', $where);
1540  
1541      // Do Multi Pages
1542      $query = $db->query("
1543          SELECT COUNT(s.tid) as threads
1544          FROM ".TABLE_PREFIX."threadsubscriptions s
1545          LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid = s.tid)
1546          WHERE {$where}
1547      ");
1548      $threadcount = $db->fetch_field($query, "threads");
1549  
1550      if(!$mybb->settings['threadsperpage'] || (int)$mybb->settings['threadsperpage'] < 1)
1551      {
1552          $mybb->settings['threadsperpage'] = 20;
1553      }
1554  
1555      $perpage = $mybb->settings['threadsperpage'];
1556      $page = $mybb->get_input('page', MyBB::INPUT_INT);
1557      if($page > 0)
1558      {
1559          $start = ($page-1) * $perpage;
1560          $pages = $threadcount / $perpage;
1561          $pages = ceil($pages);
1562          if($page > $pages || $page <= 0)
1563          {
1564              $start = 0;
1565              $page = 1;
1566          }
1567      }
1568      else
1569      {
1570          $start = 0;
1571          $page = 1;
1572      }
1573      $end = $start + $perpage;
1574      $lower = $start+1;
1575      $upper = $end;
1576      if($upper > $threadcount)
1577      {
1578          $upper = $threadcount;
1579      }
1580      $multipage = multipage($threadcount, $perpage, $page, "usercp.php?action=subscriptions");
1581      $fpermissions = forum_permissions();
1582      $del_subscriptions = $subscriptions = array();
1583  
1584      // Fetch subscriptions
1585      $query = $db->query("
1586          SELECT s.*, t.*, t.username AS threadusername, u.username
1587          FROM ".TABLE_PREFIX."threadsubscriptions s
1588          LEFT JOIN ".TABLE_PREFIX."threads t ON (s.tid=t.tid)
1589          LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid = t.uid)
1590          WHERE {$where}
1591          ORDER BY t.lastpost DESC
1592          LIMIT $start, $perpage
1593      ");
1594      while($subscription = $db->fetch_array($query))
1595      {
1596          $forumpermissions = $fpermissions[$subscription['fid']];
1597  
1598          if(isset($forumpermissions['canonlyviewownthreads']) && $forumpermissions['canonlyviewownthreads'] != 0 && $subscription['uid'] != $mybb->user['uid'])
1599          {
1600              // Hmm, you don't have permission to view this thread - unsubscribe!
1601              $del_subscriptions[] = $subscription['sid'];
1602          }
1603          elseif($subscription['tid'])
1604          {
1605              $subscriptions[$subscription['tid']] = $subscription;
1606          }
1607      }
1608  
1609      if(!empty($del_subscriptions))
1610      {
1611          $sids = implode(',', $del_subscriptions);
1612  
1613          if($sids)
1614          {
1615              $db->delete_query("threadsubscriptions", "sid IN ({$sids}) AND uid='{$mybb->user['uid']}'");
1616          }
1617  
1618          $threadcount = $threadcount - count($del_subscriptions);
1619  
1620          if($threadcount < 0)
1621          {
1622              $threadcount = 0;
1623          }
1624      }
1625  
1626      if(!empty($subscriptions))
1627      {
1628          $tids = implode(",", array_keys($subscriptions));
1629          $readforums = array();
1630  
1631          // Build a forum cache.
1632          $query = $db->query("
1633              SELECT f.fid, fr.dateline AS lastread
1634              FROM ".TABLE_PREFIX."forums f
1635              LEFT JOIN ".TABLE_PREFIX."forumsread fr ON (fr.fid=f.fid AND fr.uid='{$mybb->user['uid']}')
1636              WHERE f.active != 0
1637              ORDER BY pid, disporder
1638          ");
1639  
1640          while($forum = $db->fetch_array($query))
1641          {
1642              $readforums[$forum['fid']] = $forum['lastread'];
1643          }
1644  
1645          // Check participation by the current user in any of these threads - for 'dot' folder icons
1646          if($mybb->settings['dotfolders'] != 0)
1647          {
1648              $query = $db->simple_select("posts", "tid,uid", "uid='{$mybb->user['uid']}' AND tid IN ({$tids})");
1649              while($post = $db->fetch_array($query))
1650              {
1651                  $subscriptions[$post['tid']]['doticon'] = 1;
1652              }
1653          }
1654  
1655          // Read threads
1656          if($mybb->settings['threadreadcut'] > 0)
1657          {
1658              $query = $db->simple_select("threadsread", "*", "uid='{$mybb->user['uid']}' AND tid IN ({$tids})");
1659              while($readthread = $db->fetch_array($query))
1660              {
1661                  $subscriptions[$readthread['tid']]['lastread'] = $readthread['dateline'];
1662              }
1663          }
1664  
1665          $icon_cache = $cache->read("posticons");
1666          $threadprefixes = build_prefixes();
1667  
1668          $threads = '';
1669  
1670          // Now we can build our subscription list
1671          foreach($subscriptions as $thread)
1672          {
1673              $bgcolor = alt_trow();
1674  
1675              $folder = '';
1676              $prefix = '';
1677              $thread['threadprefix'] = '';
1678  
1679              // If this thread has a prefix, insert a space between prefix and subject
1680              if($thread['prefix'] != 0 && !empty($threadprefixes[$thread['prefix']]))
1681              {
1682                  $thread['threadprefix'] = $threadprefixes[$thread['prefix']]['displaystyle'].'&nbsp;';
1683              }
1684  
1685              // Sanitize
1686              $thread['subject'] = $parser->parse_badwords($thread['subject']);
1687              $thread['subject'] = htmlspecialchars_uni($thread['subject']);
1688  
1689              // Build our links
1690              $thread['threadlink'] = get_thread_link($thread['tid']);
1691              $thread['lastpostlink'] = get_thread_link($thread['tid'], 0, "lastpost");
1692  
1693              // Fetch the thread icon if we have one
1694              if($thread['icon'] > 0 && $icon_cache[$thread['icon']])
1695              {
1696                  $icon = $icon_cache[$thread['icon']];
1697                  $icon['path'] = str_replace("{theme}", $theme['imgdir'], $icon['path']);
1698                  $icon['path'] = htmlspecialchars_uni($icon['path']);
1699                  $icon['name'] = htmlspecialchars_uni($icon['name']);
1700                  eval("\$icon = \"".$templates->get("usercp_subscriptions_thread_icon")."\";");
1701              }
1702              else
1703              {
1704                  $icon = "&nbsp;";
1705              }
1706  
1707              // Determine the folder
1708              $folder = '';
1709              $folder_label = '';
1710  
1711              if(isset($thread['doticon']))
1712              {
1713                  $folder = "dot_";
1714                  $folder_label .= $lang->icon_dot;
1715              }
1716  
1717              $gotounread = '';
1718              $isnew = 0;
1719              $donenew = 0;
1720              $lastread = 0;
1721  
1722              if($mybb->settings['threadreadcut'] > 0)
1723              {
1724                  $read_cutoff = TIME_NOW-$mybb->settings['threadreadcut']*60*60*24;
1725                  if(empty($readforums[$thread['fid']]) || $readforums[$thread['fid']] < $read_cutoff)
1726                  {
1727                      $forum_read = $read_cutoff;
1728                  }
1729                  else
1730                  {
1731                      $forum_read = $readforums[$thread['fid']];
1732                  }
1733              }
1734  
1735              $cutoff = 0;
1736              if($mybb->settings['threadreadcut'] > 0 && $thread['lastpost'] > $forum_read)
1737              {
1738                  $cutoff = TIME_NOW-$mybb->settings['threadreadcut']*60*60*24;
1739              }
1740  
1741              if($thread['lastpost'] > $cutoff)
1742              {
1743                  if(!empty($thread['lastread']))
1744                  {
1745                      $lastread = $thread['lastread'];
1746                  }
1747                  else
1748                  {
1749                      $lastread = 1;
1750                  }
1751              }
1752  
1753              if(!$lastread)
1754              {
1755                  $readcookie = $threadread = my_get_array_cookie("threadread", $thread['tid']);
1756                  if($readcookie > $forum_read)
1757                  {
1758                      $lastread = $readcookie;
1759                  }
1760                  else
1761                  {
1762                      $lastread = $forum_read;
1763                  }
1764              }
1765  
1766              if($lastread && $lastread < $thread['lastpost'])
1767              {
1768                  $folder .= "new";
1769                  $folder_label .= $lang->icon_new;
1770                  $new_class = "subject_new";
1771                  $thread['newpostlink'] = get_thread_link($thread['tid'], 0, "newpost");
1772                  eval("\$gotounread = \"".$templates->get("forumdisplay_thread_gotounread")."\";");
1773                  $unreadpost = 1;
1774              }
1775              else
1776              {
1777                  $folder_label .= $lang->icon_no_new;
1778                  $new_class = "subject_old";
1779              }
1780  
1781              if($thread['replies'] >= $mybb->settings['hottopic'] || $thread['views'] >= $mybb->settings['hottopicviews'])
1782              {
1783                  $folder .= "hot";
1784                  $folder_label .= $lang->icon_hot;
1785              }
1786  
1787              if($thread['closed'] == 1)
1788              {
1789                  $folder .= "close";
1790                  $folder_label .= $lang->icon_close;
1791              }
1792  
1793              $folder .= "folder";
1794  
1795              if($thread['visible'] == 0)
1796              {
1797                  $bgcolor = "trow_shaded";
1798              }
1799  
1800              // Build last post info
1801              $lastpostdate = my_date('relative', $thread['lastpost']);
1802              $lastposteruid = $thread['lastposteruid'];
1803              if(!$lastposteruid && !$thread['lastposter'])
1804              {
1805                  $lastposter = htmlspecialchars_uni($lang->guest);
1806              }
1807              else
1808              {
1809                  $lastposter = htmlspecialchars_uni($thread['lastposter']);
1810              }
1811  
1812              // Don't link to guest's profiles (they have no profile).
1813              if($lastposteruid == 0)
1814              {
1815                  $lastposterlink = $lastposter;
1816              }
1817              else
1818              {
1819                  $lastposterlink = build_profile_link($lastposter, $lastposteruid);
1820              }
1821  
1822              $thread['replies'] = my_number_format($thread['replies']);
1823              $thread['views'] = my_number_format($thread['views']);
1824  
1825              // What kind of notification type do we have here?
1826              switch($thread['notification'])
1827              {
1828                  case "2": // PM
1829                      $notification_type = $lang->pm_notification;
1830                      break;
1831                  case "1": // Email
1832                      $notification_type = $lang->email_notification;
1833                      break;
1834                  default: // No notification
1835                      $notification_type = $lang->no_notification;
1836              }
1837  
1838              eval("\$threads .= \"".$templates->get("usercp_subscriptions_thread")."\";");
1839          }
1840  
1841          // Provide remove options
1842          eval("\$remove_options = \"".$templates->get("usercp_subscriptions_remove")."\";");
1843      }
1844      else
1845      {
1846          $remove_options = '';
1847          eval("\$threads = \"".$templates->get("usercp_subscriptions_none")."\";");
1848      }
1849  
1850      $plugins->run_hooks("usercp_subscriptions_end");
1851  
1852      eval("\$subscriptions = \"".$templates->get("usercp_subscriptions")."\";");
1853      output_page($subscriptions);
1854  }
1855  
1856  if($mybb->input['action'] == "forumsubscriptions")
1857  {
1858      $plugins->run_hooks("usercp_forumsubscriptions_start");
1859  
1860      // Build a forum cache.
1861      $query = $db->query("
1862          SELECT f.fid, fr.dateline AS lastread
1863          FROM ".TABLE_PREFIX."forums f
1864          LEFT JOIN ".TABLE_PREFIX."forumsread fr ON (fr.fid=f.fid AND fr.uid='{$mybb->user['uid']}')
1865          WHERE f.active != 0
1866          ORDER BY pid, disporder
1867      ");
1868      $readforums = array();
1869      while($forum = $db->fetch_array($query))
1870      {
1871          $readforums[$forum['fid']] = $forum['lastread'];
1872      }
1873  
1874      $fpermissions = forum_permissions();
1875      require_once  MYBB_ROOT."inc/functions_forumlist.php";
1876  
1877      $query = $db->query("
1878          SELECT fs.*, f.*, t.subject AS lastpostsubject, fr.dateline AS lastread
1879          FROM ".TABLE_PREFIX."forumsubscriptions fs
1880          LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid = fs.fid)
1881          LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid = f.lastposttid)
1882          LEFT JOIN ".TABLE_PREFIX."forumsread fr ON (fr.fid=f.fid AND fr.uid='{$mybb->user['uid']}')
1883          WHERE f.type='f' AND fs.uid='".$mybb->user['uid']."'
1884          ORDER BY f.name ASC
1885      ");
1886  
1887      $forums = '';
1888      while($forum = $db->fetch_array($query))
1889      {
1890          $forum_url = get_forum_link($forum['fid']);
1891          $forumpermissions = $fpermissions[$forum['fid']];
1892  
1893          if($forumpermissions['canview'] == 0 || $forumpermissions['canviewthreads'] == 0)
1894          {
1895              continue;
1896          }
1897  
1898          $lightbulb = get_forum_lightbulb(array('open' => $forum['open'], 'lastread' => $forum['lastread']), array('lastpost' => $forum['lastpost']));
1899          $folder = $lightbulb['folder'];
1900  
1901          if(isset($forumpermissions['canonlyviewownthreads']) && $forumpermissions['canonlyviewownthreads'] != 0)
1902          {
1903              $posts = '-';
1904              $threads = '-';
1905          }
1906          else
1907          {
1908              $posts = my_number_format($forum['posts']);
1909              $threads = my_number_format($forum['threads']);
1910          }
1911  
1912          if($forum['lastpost'] == 0)
1913          {
1914              eval("\$lastpost = \"".$templates->get("forumbit_depth2_forum_lastpost_never")."\";");
1915          }
1916          // Hide last post
1917          elseif(isset($forumpermissions['canonlyviewownthreads']) && $forumpermissions['canonlyviewownthreads'] != 0 && $forum['lastposteruid'] != $mybb->user['uid'])
1918          {
1919              eval("\$lastpost = \"".$templates->get("forumbit_depth2_forum_lastpost_hidden")."\";");
1920          }
1921          else
1922          {
1923              $forum['lastpostsubject'] = $parser->parse_badwords($forum['lastpostsubject']);
1924              $lastpost_date = my_date('relative', $forum['lastpost']);
1925              $lastposttid = $forum['lastposttid'];
1926              if(!$forum['lastposteruid'] && !$forum['lastposter'])
1927              {
1928                  $lastposter = htmlspecialchars_uni($lang->guest);
1929              }
1930              else
1931              {
1932                  $lastposter = htmlspecialchars_uni($forum['lastposter']);
1933              }
1934              if($forum['lastposteruid'] == 0)
1935              {
1936                  $lastpost_profilelink = $lastposter;
1937              }
1938              else
1939              {
1940                  $lastpost_profilelink = build_profile_link($lastposter, $forum['lastposteruid']);
1941              }
1942              $full_lastpost_subject = $lastpost_subject = htmlspecialchars_uni($forum['lastpostsubject']);
1943              if(my_strlen($lastpost_subject) > 25)
1944              {
1945                  $lastpost_subject = my_substr($lastpost_subject, 0, 25) . "...";
1946              }
1947              $lastpost_link = get_thread_link($forum['lastposttid'], 0, "lastpost");
1948              eval("\$lastpost = \"".$templates->get("forumbit_depth2_forum_lastpost")."\";");
1949          }
1950  
1951          if($mybb->settings['showdescriptions'] == 0)
1952          {
1953              $forum['description'] = "";
1954          }
1955  
1956          eval("\$forums .= \"".$templates->get("usercp_forumsubscriptions_forum")."\";");
1957      }
1958  
1959      if(!$forums)
1960      {
1961          eval("\$forums = \"".$templates->get("usercp_forumsubscriptions_none")."\";");
1962      }
1963  
1964      $plugins->run_hooks("usercp_forumsubscriptions_end");
1965  
1966      eval("\$forumsubscriptions = \"".$templates->get("usercp_forumsubscriptions")."\";");
1967      output_page($forumsubscriptions);
1968  }
1969  
1970  if($mybb->input['action'] == "do_addsubscription" && $mybb->get_input('type') != "forum")
1971  {
1972      // Verify incoming POST request
1973      verify_post_check($mybb->get_input('my_post_key'));
1974  
1975      $thread = get_thread($mybb->get_input('tid'));
1976      if(!$thread || $thread['visible'] == -1)
1977      {
1978          error($lang->error_invalidthread);
1979      }
1980  
1981      // Is the currently logged in user a moderator of this forum?
1982      $ismod = is_moderator($thread['fid']);
1983  
1984      // Make sure we are looking at a real thread here.
1985      if(($thread['visible'] != 1 && $ismod == false) || ($thread['visible'] > 1 && $ismod == true))
1986      {
1987          error($lang->error_invalidthread);
1988      }
1989  
1990      $forumpermissions = forum_permissions($thread['fid']);
1991      if($forumpermissions['canview'] == 0 || $forumpermissions['canviewthreads'] == 0 || (isset($forumpermissions['canonlyviewownthreads']) && $forumpermissions['canonlyviewownthreads'] != 0 && $thread['uid'] != $mybb->user['uid']))
1992      {
1993          error_no_permission();
1994      }
1995  
1996      // check if the forum requires a password to view. If so, we need to show a form to the user
1997      check_forum_password($thread['fid']);
1998  
1999      // Naming of the hook retained for backward compatibility while dropping usercp2.php
2000      $plugins->run_hooks("usercp2_do_addsubscription");
2001  
2002      add_subscribed_thread($thread['tid'], $mybb->get_input('notification', MyBB::INPUT_INT));
2003  
2004      if($mybb->get_input('referrer'))
2005      {
2006          $mybb->input['referrer'] = $mybb->get_input('referrer');
2007  
2008          if(my_strpos($mybb->input['referrer'], $mybb->settings['bburl'].'/') !== 0)
2009          {
2010              if(my_strpos($mybb->input['referrer'], '/') === 0)
2011              {
2012                  $mybb->input['referrer'] = my_substr($mybb->input['url'], 1);
2013              }
2014              $url_segments = explode('/', $mybb->input['referrer']);
2015              $mybb->input['referrer'] = $mybb->settings['bburl'].'/'.end($url_segments);
2016          }
2017  
2018          $url = htmlspecialchars_uni($mybb->input['referrer']);
2019      }
2020      else
2021      {
2022          $url = get_thread_link($thread['tid']);
2023      }
2024      redirect($url, $lang->redirect_subscriptionadded);
2025  }
2026  
2027  if($mybb->input['action'] == "addsubscription")
2028  {
2029      // Verify incoming POST request
2030      verify_post_check($mybb->get_input('my_post_key'));
2031  
2032      if($mybb->get_input('type') == "forum")
2033      {
2034          $forum = get_forum($mybb->get_input('fid', MyBB::INPUT_INT));
2035          if(!$forum)
2036          {
2037              error($lang->error_invalidforum);
2038          }
2039          $forumpermissions = forum_permissions($forum['fid']);
2040          if($forumpermissions['canview'] == 0 || $forumpermissions['canviewthreads'] == 0)
2041          {
2042              error_no_permission();
2043          }
2044  
2045          // check if the forum requires a password to view. If so, we need to show a form to the user
2046          check_forum_password($forum['fid']);
2047  
2048          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2049          $plugins->run_hooks("usercp2_addsubscription_forum");
2050  
2051          add_subscribed_forum($forum['fid']);
2052          if($server_http_referer && $mybb->request_method != 'post')
2053          {
2054              $url = $server_http_referer;
2055          }
2056          else
2057          {
2058              $url = "index.php";
2059          }
2060          redirect($url, $lang->redirect_forumsubscriptionadded);
2061      }
2062      else
2063      {
2064          $thread  = get_thread($mybb->get_input('tid', MyBB::INPUT_INT));
2065          if(!$thread || $thread['visible'] == -1)
2066          {
2067              error($lang->error_invalidthread);
2068          }
2069  
2070          // Is the currently logged in user a moderator of this forum?
2071          $ismod = is_moderator($thread['fid']);
2072  
2073          // Make sure we are looking at a real thread here.
2074          if(($thread['visible'] != 1 && $ismod == false) || ($thread['visible'] > 1 && $ismod == true))
2075          {
2076              error($lang->error_invalidthread);
2077          }
2078  
2079          add_breadcrumb($lang->nav_subthreads, "usercp.php?action=subscriptions");
2080          add_breadcrumb($lang->nav_addsubscription);
2081  
2082          $forumpermissions = forum_permissions($thread['fid']);
2083          if($forumpermissions['canview'] == 0 || $forumpermissions['canviewthreads'] == 0 || (isset($forumpermissions['canonlyviewownthreads']) && $forumpermissions['canonlyviewownthreads'] != 0 && $thread['uid'] != $mybb->user['uid']))
2084          {
2085              error_no_permission();
2086          }
2087  
2088          // check if the forum requires a password to view. If so, we need to show a form to the user
2089          check_forum_password($thread['fid']);
2090  
2091          $referrer = '';
2092          if($server_http_referer)
2093          {
2094              $referrer = $server_http_referer;
2095          }
2096  
2097          require_once  MYBB_ROOT."inc/class_parser.php";
2098          $parser = new postParser;
2099          $thread['subject'] = $parser->parse_badwords($thread['subject']);
2100          $thread['subject'] = htmlspecialchars_uni($thread['subject']);
2101          $lang->subscribe_to_thread = $lang->sprintf($lang->subscribe_to_thread, $thread['subject']);
2102  
2103          $notification_none_checked = $notification_email_checked = $notification_pm_checked = '';
2104          if($mybb->user['subscriptionmethod'] == 1 || $mybb->user['subscriptionmethod'] == 0)
2105          {
2106              $notification_none_checked = "checked=\"checked\"";
2107          }
2108          elseif($mybb->user['subscriptionmethod'] == 2)
2109          {
2110              $notification_email_checked = "checked=\"checked\"";
2111          }
2112          elseif($mybb->user['subscriptionmethod'] == 3)
2113          {
2114              $notification_pm_checked = "checked=\"checked\"";
2115          }
2116  
2117          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2118          $plugins->run_hooks("usercp2_addsubscription_thread");
2119  
2120          eval("\$add_subscription = \"".$templates->get("usercp_addsubscription_thread")."\";");
2121          output_page($add_subscription);
2122          exit;
2123      }
2124  }
2125  
2126  if($mybb->input['action'] == "removesubscription" && ($mybb->request_method == "post" || verify_post_check($mybb->get_input('my_post_key'), true)))
2127  {
2128      // Verify incoming POST request
2129      verify_post_check($mybb->get_input('my_post_key'));
2130  
2131      if($mybb->get_input('type') == "forum")
2132      {
2133          $forum = get_forum($mybb->get_input('fid', MyBB::INPUT_INT));
2134          if(!$forum)
2135          {
2136              error($lang->error_invalidforum);
2137          }
2138  
2139          // check if the forum requires a password to view. If so, we need to show a form to the user
2140          check_forum_password($forum['fid']);
2141  
2142          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2143          $plugins->run_hooks("usercp2_removesubscription_forum");
2144  
2145          remove_subscribed_forum($forum['fid']);
2146          if($server_http_referer && $mybb->request_method != 'post')
2147          {
2148              $url = $server_http_referer;
2149          }
2150          else
2151          {
2152              $url = "usercp.php?action=forumsubscriptions";
2153          }
2154          redirect($url, $lang->redirect_forumsubscriptionremoved);
2155      }
2156      else
2157      {
2158          $thread = get_thread($mybb->get_input('tid', MyBB::INPUT_INT));
2159          if(!$thread)
2160          {
2161              error($lang->error_invalidthread);
2162          }
2163  
2164          // Is the currently logged in user a moderator of this forum?
2165          $ismod = is_moderator($thread['fid']);
2166  
2167          // Make sure we are looking at a real thread here.
2168          if(($thread['visible'] != 1 && $ismod == false) || ($thread['visible'] > 1 && $ismod == true))
2169          {
2170              error($lang->error_invalidthread);
2171          }
2172  
2173          // check if the forum requires a password to view. If so, we need to show a form to the user
2174          check_forum_password($thread['fid']);
2175  
2176          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2177          $plugins->run_hooks("usercp2_removesubscription_thread");
2178  
2179          remove_subscribed_thread($thread['tid']);
2180          if($server_http_referer && $mybb->request_method != 'post')
2181          {
2182              $url = $server_http_referer;
2183          }
2184          else
2185          {
2186              $url = "usercp.php?action=subscriptions";
2187          }
2188          redirect($url, $lang->redirect_subscriptionremoved);
2189      }
2190  }
2191  
2192  // Show remove subscription form when GET method and without valid my_post_key
2193  if($mybb->input['action'] == "removesubscription")
2194  {
2195      $referrer = '';
2196      if($mybb->get_input('type') == "forum")
2197      {
2198          $forum = get_forum($mybb->get_input('fid', MyBB::INPUT_INT));
2199          if(!$forum)
2200          {
2201              error($lang->error_invalidforum);
2202          }
2203  
2204          add_breadcrumb($lang->nav_forumsubscriptions, "usercp.php?action=forumsubscriptions");
2205          add_breadcrumb($lang->nav_removesubscription);
2206  
2207          $forumpermissions = forum_permissions($forum['fid']);
2208          if($forumpermissions['canview'] == 0 || $forumpermissions['canviewthreads'] == 0)
2209          {
2210              error_no_permission();
2211          }
2212  
2213          // check if the forum requires a password to view. If so, we need to show a form to the user
2214          check_forum_password($forum['fid']);
2215  
2216          $lang->unsubscribe_from_forum = $lang->sprintf($lang->unsubscribe_from_forum, $forum['name']);
2217  
2218          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2219          $plugins->run_hooks("usercp2_removesubscription_display_forum");
2220  
2221          eval("\$remove_forum_subscription = \"".$templates->get("usercp_removesubscription_forum")."\";");
2222          output_page($remove_forum_subscription);
2223          exit;
2224      }
2225      else
2226      {
2227          $thread  = get_thread($mybb->get_input('tid', MyBB::INPUT_INT));
2228          if(!$thread || $thread['visible'] == -1)
2229          {
2230              error($lang->error_invalidthread);
2231          }
2232  
2233          // Is the currently logged in user a moderator of this forum?
2234          $ismod = is_moderator($thread['fid']);
2235  
2236          // Make sure we are looking at a real thread here.
2237          if(($thread['visible'] != 1 && $ismod == false) || ($thread['visible'] > 1 && $ismod == true))
2238          {
2239              error($lang->error_invalidthread);
2240          }
2241  
2242          add_breadcrumb($lang->nav_subthreads, "usercp.php?action=subscriptions");
2243          add_breadcrumb($lang->nav_removesubscription);
2244  
2245          $forumpermissions = forum_permissions($thread['fid']);
2246          if($forumpermissions['canview'] == 0 || $forumpermissions['canviewthreads'] == 0 || (isset($forumpermissions['canonlyviewownthreads']) && $forumpermissions['canonlyviewownthreads'] != 0 && $thread['uid'] != $mybb->user['uid']))
2247          {
2248              error_no_permission();
2249          }
2250  
2251          // check if the forum requires a password to view. If so, we need to show a form to the user
2252          check_forum_password($thread['fid']);
2253  
2254          require_once  MYBB_ROOT."inc/class_parser.php";
2255          $parser = new postParser;
2256          $thread['subject'] = $parser->parse_badwords($thread['subject']);
2257          $thread['subject'] = htmlspecialchars_uni($thread['subject']);
2258          $lang->unsubscribe_from_thread = $lang->sprintf($lang->unsubscribe_from_thread, $thread['subject']);
2259  
2260          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2261          $plugins->run_hooks("usercp2_removesubscription_display_thread");
2262  
2263          eval("\$remove_thread_subscription = \"".$templates->get("usercp_removesubscription_thread")."\";");
2264          output_page($remove_thread_subscription);
2265          exit;
2266      }
2267  }
2268  
2269  if($mybb->input['action'] == "removesubscriptions")
2270  {
2271      // Verify incoming POST request
2272      verify_post_check($mybb->get_input('my_post_key'));
2273  
2274      if($mybb->get_input('type') == "forum")
2275      {
2276          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2277          $plugins->run_hooks("usercp2_removesubscriptions_forum");
2278  
2279          $db->delete_query("forumsubscriptions", "uid='".$mybb->user['uid']."'");
2280          if($server_http_referer)
2281          {
2282              $url = $server_http_referer;
2283          }
2284          else
2285          {
2286              $url = "usercp.php?action=forumsubscriptions";
2287          }
2288          redirect($url, $lang->redirect_forumsubscriptionsremoved);
2289      }
2290      else
2291      {
2292          // Naming of the hook retained for backward compatibility while dropping usercp2.php
2293          $plugins->run_hooks("usercp2_removesubscriptions_thread");
2294  
2295          $db->delete_query("threadsubscriptions", "uid='".$mybb->user['uid']."'");
2296          if($server_http_referer)
2297          {
2298              $url = $server_http_referer;
2299          }
2300          else
2301          {
2302              $url = "usercp.php?action=subscriptions";
2303          }
2304          redirect($url, $lang->redirect_subscriptionsremoved);
2305      }
2306  }
2307  
2308  if($mybb->input['action'] == "do_editsig" && $mybb->request_method == "post")
2309  {
2310      // Verify incoming POST request
2311      verify_post_check($mybb->get_input('my_post_key'));
2312  
2313      // User currently has a suspended signature
2314      if($mybb->user['suspendsignature'] == 1 && $mybb->user['suspendsigtime'] > TIME_NOW)
2315      {
2316          error_no_permission();
2317      }
2318  
2319      $plugins->run_hooks("usercp_do_editsig_start");
2320  
2321      if($mybb->get_input('updateposts') == "enable")
2322      {
2323          $update_signature = array(
2324              "includesig" => 1
2325          );
2326          $db->update_query("posts", $update_signature, "uid='".$mybb->user['uid']."'");
2327      }
2328      elseif($mybb->get_input('updateposts') == "disable")
2329      {
2330          $update_signature = array(
2331              "includesig" => 0
2332          );
2333          $db->update_query("posts", $update_signature, "uid='".$mybb->user['uid']."'");
2334      }
2335      $new_signature = array(
2336          "signature" => $db->escape_string($mybb->get_input('signature'))
2337      );
2338      $plugins->run_hooks("usercp_do_editsig_process");
2339      $db->update_query("users", $new_signature, "uid='".$mybb->user['uid']."'");
2340      $plugins->run_hooks("usercp_do_editsig_end");
2341      redirect("usercp.php?action=editsig", $lang->redirect_sigupdated);
2342  }
2343  
2344  if($mybb->input['action'] == "editsig")
2345  {
2346      $plugins->run_hooks("usercp_editsig_start");
2347      if(!empty($mybb->input['preview']) && empty($error))
2348      {
2349          $sig = $mybb->get_input('signature');
2350          $template = "usercp_editsig_preview";
2351      }
2352      elseif(empty($error))
2353      {
2354          $sig = $mybb->user['signature'];
2355          $template = "usercp_editsig_current";
2356      }
2357      else
2358      {
2359          $sig = $mybb->get_input('signature');
2360          $template = false;
2361      }
2362  
2363      if(!isset($error))
2364      {
2365          $error = '';
2366      }
2367  
2368      if($mybb->user['suspendsignature'] && ($mybb->user['suspendsigtime'] == 0 || $mybb->user['suspendsigtime'] > 0 && $mybb->user['suspendsigtime'] > TIME_NOW))
2369      {
2370          // User currently has no signature and they're suspended
2371          error($lang->sig_suspended);
2372      }
2373  
2374      if($mybb->usergroup['canusesig'] != 1)
2375      {
2376          // Usergroup has no permission to use this facility
2377          error_no_permission();
2378      }
2379      elseif($mybb->usergroup['canusesig'] == 1 && $mybb->usergroup['canusesigxposts'] > 0 && $mybb->user['postnum'] < $mybb->usergroup['canusesigxposts'])
2380      {
2381          // Usergroup can use this facility, but only after x posts
2382          error($lang->sprintf($lang->sig_suspended_posts, $mybb->usergroup['canusesigxposts']));
2383      }
2384  
2385      $signature = '';
2386      if($sig && $template)
2387      {
2388          $sig_parser = array(
2389              "allow_html" => $mybb->settings['sightml'],
2390              "allow_mycode" => $mybb->settings['sigmycode'],
2391              "allow_smilies" => $mybb->settings['sigsmilies'],
2392              "allow_imgcode" => $mybb->settings['sigimgcode'],
2393              "me_username" => $mybb->user['username'],
2394              "filter_badwords" => 1
2395          );
2396  
2397          if($mybb->user['showimages'] != 1)
2398          {
2399              $sig_parser['allow_imgcode'] = 0;
2400          }
2401  
2402          $sigpreview = $parser->parse_message($sig, $sig_parser);
2403          eval("\$signature = \"".$templates->get($template)."\";");
2404      }
2405  
2406      // User has a current signature, so let's display it (but show an error message)
2407      if($mybb->user['suspendsignature'] && $mybb->user['suspendsigtime'] > TIME_NOW)
2408      {
2409          $plugins->run_hooks("usercp_editsig_end");
2410  
2411          // User either doesn't have permission, or has their signature suspended
2412          eval("\$editsig = \"".$templates->get("usercp_editsig_suspended")."\";");
2413      }
2414      else
2415      {
2416          // User is allowed to edit their signature
2417          if($mybb->settings['sigsmilies'] == 1)
2418          {
2419              $sigsmilies = $lang->on;
2420              $smilieinserter = build_clickable_smilies();
2421          }
2422          else
2423          {
2424              $sigsmilies = $lang->off;
2425          }
2426          if($mybb->settings['sigmycode'] == 1)
2427          {
2428              $sigmycode = $lang->on;
2429          }
2430          else
2431          {
2432              $sigmycode = $lang->off;
2433          }
2434          if($mybb->settings['sightml'] == 1)
2435          {
2436              $sightml = $lang->on;
2437          }
2438          else
2439          {
2440              $sightml = $lang->off;
2441          }
2442          if($mybb->settings['sigimgcode'] == 1)
2443          {
2444              $sigimgcode = $lang->on;
2445          }
2446          else
2447          {
2448              $sigimgcode = $lang->off;
2449          }
2450  
2451          if($mybb->settings['siglength'] == 0)
2452          {
2453              $siglength = $lang->unlimited;
2454          }
2455          else
2456          {
2457              $siglength = $mybb->settings['siglength'];
2458          }
2459  
2460          $sig = htmlspecialchars_uni($sig);
2461          $lang->edit_sig_note2 = $lang->sprintf($lang->edit_sig_note2, $sigsmilies, $sigmycode, $sigimgcode, $sightml, $siglength);
2462  
2463          if($mybb->settings['sigmycode'] != 0 && $mybb->settings['bbcodeinserter'] != 0 && $mybb->user['showcodebuttons'] != 0)
2464          {
2465              $codebuttons = build_mycode_inserter("signature");
2466          }
2467  
2468          $plugins->run_hooks("usercp_editsig_end");
2469  
2470          eval("\$editsig = \"".$templates->get("usercp_editsig")."\";");
2471      }
2472  
2473      output_page($editsig);
2474  }
2475  
2476  if($mybb->input['action'] == "do_avatar" && $mybb->request_method == "post")
2477  {
2478      // Verify incoming POST request
2479      verify_post_check($mybb->get_input('my_post_key'));
2480  
2481      $plugins->run_hooks("usercp_do_avatar_start");
2482      require_once  MYBB_ROOT."inc/functions_upload.php";
2483  
2484      $avatar_error = "";
2485  
2486      if(!empty($mybb->input['remove'])) // remove avatar
2487      {
2488          $updated_avatar = array(
2489              "avatar" => "",
2490              "avatardimensions" => "",
2491              "avatartype" => ""
2492          );
2493          $db->update_query("users", $updated_avatar, "uid='".$mybb->user['uid']."'");
2494          remove_avatars($mybb->user['uid']);
2495      }
2496      elseif($_FILES['avatarupload']['name']) // upload avatar
2497      {
2498          if($mybb->usergroup['canuploadavatars'] == 0)
2499          {
2500              error_no_permission();
2501          }
2502          $avatar = upload_avatar();
2503          if(!empty($avatar['error']))
2504          {
2505              $avatar_error = $avatar['error'];
2506          }
2507          else
2508          {
2509              if($avatar['width'] > 0 && $avatar['height'] > 0)
2510              {
2511                  $avatar_dimensions = $avatar['width']."|".$avatar['height'];
2512              }
2513              $updated_avatar = array(
2514                  "avatar" => $avatar['avatar'].'?dateline='.TIME_NOW,
2515                  "avatardimensions" => $avatar_dimensions,
2516                  "avatartype" => "upload"
2517              );
2518              $db->update_query("users", $updated_avatar, "uid='".$mybb->user['uid']."'");
2519          }
2520      }
2521      elseif(!$mybb->settings['allowremoteavatars'] && !$_FILES['avatarupload']['name']) // missing avatar image
2522      {
2523          $avatar_error = $lang->error_avatarimagemissing;
2524      }
2525      elseif($mybb->settings['allowremoteavatars']) // remote avatar
2526      {
2527          $mybb->input['avatarurl'] = trim($mybb->get_input('avatarurl'));
2528          if(validate_email_format($mybb->input['avatarurl']) != false)
2529          {
2530              // Gravatar
2531              $mybb->input['avatarurl'] = my_strtolower($mybb->input['avatarurl']);
2532  
2533              // If user image does not exist, or is a higher rating, use the mystery man
2534              $email = md5($mybb->input['avatarurl']);
2535  
2536              $s = '';
2537              if(!$mybb->settings['maxavatardims'])
2538              {
2539                  $mybb->settings['maxavatardims'] = '100x100'; // Hard limit of 100 if there are no limits
2540              }
2541  
2542              // Because Gravatars are square, hijack the width
2543              list($maxwidth, $maxheight) = preg_split('/[|x]/', my_strtolower($mybb->settings['maxavatardims']));
2544              $maxheight = (int)$maxwidth;
2545  
2546              // Rating?
2547              $types = array('g', 'pg', 'r', 'x');
2548              $rating = $mybb->settings['useravatarrating'];
2549  
2550              if(!in_array($rating, $types))
2551              {
2552                  $rating = 'g';
2553              }
2554  
2555              $s = "?s={$maxheight}&r={$rating}&d=mm";
2556  
2557              $updated_avatar = array(
2558                  "avatar" => "https://www.gravatar.com/avatar/{$email}{$s}",
2559                  "avatardimensions" => "{$maxheight}|{$maxheight}",
2560                  "avatartype" => "gravatar"
2561              );
2562  
2563              $db->update_query("users", $updated_avatar, "uid = '{$mybb->user['uid']}'");
2564          }
2565          else
2566          {
2567              $mybb->input['avatarurl'] = preg_replace("#script:#i", "", $mybb->get_input('avatarurl'));
2568              $ext = get_extension($mybb->input['avatarurl']);
2569  
2570              // Copy the avatar to the local server (work around remote URL access disabled for getimagesize)
2571              $file = fetch_remote_file($mybb->input['avatarurl']);
2572              if(!$file)
2573              {
2574                  $avatar_error = $lang->error_invalidavatarurl;
2575              }
2576              else
2577              {
2578                  $tmp_name = $mybb->settings['avataruploadpath']."/remote_".md5(random_str());
2579                  $fp = @fopen($tmp_name, "wb");
2580                  if(!$fp)
2581                  {
2582                      $avatar_error = $lang->error_invalidavatarurl;
2583                  }
2584                  else
2585                  {
2586                      fwrite($fp, $file);
2587                      fclose($fp);
2588                      list($width, $height, $type) = @getimagesize($tmp_name);
2589                      @unlink($tmp_name);
2590                      if(!$type)
2591                      {
2592                          $avatar_error = $lang->error_invalidavatarurl;
2593                      }
2594                  }
2595              }
2596  
2597              if(empty($avatar_error))
2598              {
2599                  if($width && $height && $mybb->settings['maxavatardims'] != "")
2600                  {
2601                      list($maxwidth, $maxheight) = preg_split('/[|x]/', my_strtolower($mybb->settings['maxavatardims']));
2602                      if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight))
2603                      {
2604                          $lang->error_avatartoobig = $lang->sprintf($lang->error_avatartoobig, $maxwidth, $maxheight);
2605                          $avatar_error = $lang->error_avatartoobig;
2606                      }
2607                  }
2608              }
2609  
2610              // Limiting URL string to stay within database limit
2611              if(strlen($mybb->input['avatarurl']) > 200)
2612              {
2613                  $avatar_error = $lang->error_avatarurltoolong;
2614              }
2615  
2616              if(empty($avatar_error))
2617              {
2618                  if($width > 0 && $height > 0)
2619                  {
2620                      $avatar_dimensions = (int)$width."|".(int)$height;
2621                  }
2622                  $updated_avatar = array(
2623                      "avatar" => $db->escape_string($mybb->input['avatarurl'].'?dateline='.TIME_NOW),
2624                      "avatardimensions" => $avatar_dimensions,
2625                      "avatartype" => "remote"
2626                  );
2627                  $db->update_query("users", $updated_avatar, "uid='".$mybb->user['uid']."'");
2628                  remove_avatars($mybb->user['uid']);
2629              }
2630          }
2631      }
2632      else // remote avatar, but remote avatars are not allowed
2633      {
2634          $avatar_error = $lang->error_remote_avatar_not_allowed;
2635      }
2636  
2637      if(empty($avatar_error))
2638      {
2639          $plugins->run_hooks("usercp_do_avatar_end");
2640          redirect("usercp.php?action=avatar", $lang->redirect_avatarupdated);
2641      }
2642      else
2643      {
2644          $mybb->input['action'] = "avatar";
2645          $avatar_error = inline_error($avatar_error);
2646      }
2647  }
2648  
2649  if($mybb->input['action'] == "avatar")
2650  {
2651      $plugins->run_hooks("usercp_avatar_start");
2652  
2653      $avatarmsg = $avatarurl = '';
2654  
2655      if($mybb->user['avatartype'] == "upload" || stristr($mybb->user['avatar'], $mybb->settings['avataruploadpath']))
2656      {
2657          $avatarmsg = "<br /><strong>".$lang->already_uploaded_avatar."</strong>";
2658      }
2659      elseif($mybb->user['avatartype'] == "remote" || my_validate_url($mybb->user['avatar']))
2660      {
2661          $avatarmsg = "<br /><strong>".$lang->using_remote_avatar."</strong>";
2662          $avatarurl = htmlspecialchars_uni($mybb->user['avatar']);
2663      }
2664  
2665      $useravatar = format_avatar($mybb->user['avatar'], $mybb->user['avatardimensions'], '100x100');
2666      eval("\$currentavatar = \"".$templates->get("usercp_avatar_current")."\";");
2667  
2668      if($mybb->settings['maxavatardims'] != "")
2669      {
2670          list($maxwidth, $maxheight) = preg_split('/[|x]/', my_strtolower($mybb->settings['maxavatardims']));
2671          $lang->avatar_note .= "<br />".$lang->sprintf($lang->avatar_note_dimensions, $maxwidth, $maxheight);
2672      }
2673  
2674      if($mybb->settings['avatarsize'])
2675      {
2676          $maxsize = get_friendly_size($mybb->settings['avatarsize']*1024);
2677          $lang->avatar_note .= "<br />".$lang->sprintf($lang->avatar_note_size, $maxsize);
2678      }
2679  
2680      $plugins->run_hooks("usercp_avatar_intermediate");
2681  
2682      $auto_resize = '';
2683      if($mybb->settings['avatarresizing'] == "auto")
2684      {
2685          eval("\$auto_resize = \"".$templates->get("usercp_avatar_auto_resize_auto")."\";");
2686      }
2687      elseif($mybb->settings['avatarresizing'] == "user")
2688      {
2689          eval("\$auto_resize = \"".$templates->get("usercp_avatar_auto_resize_user")."\";");
2690      }
2691  
2692      $avatarupload = '';
2693      if($mybb->usergroup['canuploadavatars'] == 1)
2694      {
2695          eval("\$avatarupload = \"".$templates->get("usercp_avatar_upload")."\";");
2696      }
2697  
2698      $avatar_remote = '';
2699      if($mybb->settings['allowremoteavatars'] == 1)
2700      {
2701          eval("\$avatar_remote = \"".$templates->get("usercp_avatar_remote")."\";");
2702      }
2703  
2704      $removeavatar = '';
2705      if(!empty($mybb->user['avatar']))
2706      {
2707          eval("\$removeavatar = \"".$templates->get("usercp_avatar_remove")."\";");
2708      }
2709  
2710      $plugins->run_hooks("usercp_avatar_end");
2711  
2712      if(!isset($avatar_error))
2713      {
2714          $avatar_error = '';
2715      }
2716  
2717      eval("\$avatar = \"".$templates->get("usercp_avatar")."\";");
2718      output_page($avatar);
2719  }
2720  
2721  if($mybb->input['action'] == "acceptrequest")
2722  {
2723      // Verify incoming POST request
2724      verify_post_check($mybb->get_input('my_post_key'));
2725  
2726      // Validate request
2727      $query = $db->simple_select('buddyrequests', '*', 'id='.$mybb->get_input('id', MyBB::INPUT_INT).' AND touid='.(int)$mybb->user['uid']);
2728      $request = $db->fetch_array($query);
2729      if(empty($request))
2730      {
2731          error($lang->invalid_request);
2732      }
2733  
2734      $plugins->run_hooks("usercp_acceptrequest_start");
2735  
2736      $user = get_user($request['uid']);
2737      if(!empty($user))
2738      {
2739          // We want to add us to this user's buddy list
2740          if($user['buddylist'] != '')
2741          {
2742              $user['buddylist'] = explode(',', $user['buddylist']);
2743          }
2744          else
2745          {
2746              $user['buddylist'] = array();
2747          }
2748  
2749          $user['buddylist'][] = (int)$mybb->user['uid'];
2750  
2751          // Now we have the new list, so throw it all back together
2752          $new_list = implode(",", $user['buddylist']);
2753  
2754          // And clean it up a little to ensure there is no possibility of bad values
2755          $new_list = preg_replace("#,{2,}#", ",", $new_list);
2756          $new_list = preg_replace("#[^0-9,]#", "", $new_list);
2757  
2758          if(my_substr($new_list, 0, 1) == ",")
2759          {
2760              $new_list = my_substr($new_list, 1);
2761          }
2762          if(my_substr($new_list, -1) == ",")
2763          {
2764              $new_list = my_substr($new_list, 0, my_strlen($new_list)-2);
2765          }
2766  
2767          $user['buddylist'] = $db->escape_string($new_list);
2768  
2769          $db->update_query("users", array('buddylist' => $user['buddylist']), "uid='".(int)$user['uid']."'");
2770  
2771  
2772          // We want to add the user to our buddy list
2773          if($mybb->user['buddylist'] != '')
2774          {
2775              $mybb->user['buddylist'] = explode(',', $mybb->user['buddylist']);
2776          }
2777          else
2778          {
2779              $mybb->user['buddylist'] = array();
2780          }
2781  
2782          $mybb->user['buddylist'][] = (int)$request['uid'];
2783  
2784          // Now we have the new list, so throw it all back together
2785          $new_list = implode(",", $mybb->user['buddylist']);
2786  
2787          // And clean it up a little to ensure there is no possibility of bad values
2788          $new_list = preg_replace("#,{2,}#", ",", $new_list);
2789          $new_list = preg_replace("#[^0-9,]#", "", $new_list);
2790  
2791          if(my_substr($new_list, 0, 1) == ",")
2792          {
2793              $new_list = my_substr($new_list, 1);
2794          }
2795          if(my_substr($new_list, -1) == ",")
2796          {
2797              $new_list = my_substr($new_list, 0, my_strlen($new_list)-2);
2798          }
2799  
2800          $mybb->user['buddylist'] = $db->escape_string($new_list);
2801  
2802          $db->update_query("users", array('buddylist' => $mybb->user['buddylist']), "uid='".(int)$mybb->user['uid']."'");
2803  
2804          $pm = array(
2805              'subject' => 'buddyrequest_accepted_request',
2806              'message' => 'buddyrequest_accepted_request_message',
2807              'touid' => $user['uid'],
2808              'language' => $user['language'],
2809              'language_file' => 'usercp'
2810          );
2811  
2812          send_pm($pm, $mybb->user['uid'], true);
2813  
2814          $db->delete_query('buddyrequests', 'id='.(int)$request['id']);
2815      }
2816      else
2817      {
2818          error($lang->user_doesnt_exist);
2819      }
2820  
2821      $plugins->run_hooks("usercp_acceptrequest_end");
2822  
2823      redirect("usercp.php?action=editlists", $lang->buddyrequest_accepted);
2824  }
2825  
2826  elseif($mybb->input['action'] == "declinerequest")
2827  {
2828      // Verify incoming POST request
2829      verify_post_check($mybb->get_input('my_post_key'));
2830  
2831      // Validate request
2832      $query = $db->simple_select('buddyrequests', '*', 'id='.$mybb->get_input('id', MyBB::INPUT_INT).' AND touid='.(int)$mybb->user['uid']);
2833      $request = $db->fetch_array($query);
2834      if(empty($request))
2835      {
2836          error($lang->invalid_request);
2837      }
2838  
2839      $plugins->run_hooks("usercp_declinerequest_start");
2840  
2841      $user = get_user($request['uid']);
2842      if(!empty($user))
2843      {
2844          $db->delete_query('buddyrequests', 'id='.(int)$request['id']);
2845      }
2846      else
2847      {
2848          error($lang->user_doesnt_exist);
2849      }
2850  
2851      $plugins->run_hooks("usercp_declinerequest_end");
2852  
2853      redirect("usercp.php?action=editlists", $lang->buddyrequest_declined);
2854  }
2855  
2856  elseif($mybb->input['action'] == "cancelrequest")
2857  {
2858      // Verify incoming POST request
2859      verify_post_check($mybb->get_input('my_post_key'));
2860  
2861      // Validate request
2862      $query = $db->simple_select('buddyrequests', '*', 'id='.$mybb->get_input('id', MyBB::INPUT_INT).' AND uid='.(int)$mybb->user['uid']);
2863      $request = $db->fetch_array($query);
2864      if(empty($request))
2865      {
2866          error($lang->invalid_request);
2867      }
2868  
2869      $plugins->run_hooks("usercp_cancelrequest_start");
2870  
2871      $db->delete_query('buddyrequests', 'id='.(int)$request['id']);
2872  
2873      $plugins->run_hooks("usercp_cancelrequest_end");
2874  
2875      redirect("usercp.php?action=editlists", $lang->buddyrequest_cancelled);
2876  }
2877  
2878  if($mybb->input['action'] == "do_editlists")
2879  {
2880      // Verify incoming POST request
2881      verify_post_check($mybb->get_input('my_post_key'));
2882  
2883      $plugins->run_hooks("usercp_do_editlists_start");
2884  
2885      $existing_users = array();
2886      $selected_list = array();
2887      if($mybb->get_input('manage') == "ignored")
2888      {
2889          if($mybb->user['ignorelist'])
2890          {
2891              $existing_users = explode(",", $mybb->user['ignorelist']);
2892          }
2893  
2894          if($mybb->user['buddylist'])
2895          {
2896              // Create a list of buddies...
2897              $selected_list = explode(",", $mybb->user['buddylist']);
2898          }
2899      }
2900      else
2901      {
2902          if($mybb->user['buddylist'])
2903          {
2904              $existing_users = explode(",", $mybb->user['buddylist']);
2905          }
2906  
2907          if($mybb->user['ignorelist'])
2908          {
2909              // Create a list of ignored users
2910              $selected_list = explode(",", $mybb->user['ignorelist']);
2911          }
2912      }
2913  
2914      $error_message = "";
2915      $message = "";
2916  
2917      // Adding one or more users to this list
2918      if($mybb->get_input('add_username'))
2919      {
2920          // Split up any usernames we have
2921          $found_users = 0;
2922          $adding_self = false;
2923          $users = explode(",", $mybb->get_input('add_username'));
2924          $users = array_map("trim", $users);
2925          $users = array_unique($users);
2926          foreach($users as $key => $username)
2927          {
2928              if(empty($username))
2929              {
2930                  unset($users[$key]);
2931                  continue;
2932              }
2933  
2934              if(my_strtoupper($mybb->user['username']) == my_strtoupper($username))
2935              {
2936                  $adding_self = true;
2937                  unset($users[$key]);
2938                  continue;
2939              }
2940              $users[$key] = $db->escape_string($username);
2941          }
2942  
2943          // Get the requests we have sent that are still pending
2944          $query = $db->simple_select('buddyrequests', 'touid', 'uid='.(int)$mybb->user['uid']);
2945          $requests = array();
2946          while($req = $db->fetch_array($query))
2947          {
2948              $requests[$req['touid']] = true;
2949          }
2950  
2951          // Get the requests we have received that are still pending
2952          $query = $db->simple_select('buddyrequests', 'uid', 'touid='.(int)$mybb->user['uid']);
2953          $requests_rec = array();
2954          while($req = $db->fetch_array($query))
2955          {
2956              $requests_rec[$req['uid']] = true;
2957          }
2958  
2959          $sent = false;
2960  
2961          // Fetch out new users
2962          if(count($users) > 0)
2963          {
2964              switch($db->type)
2965              {
2966                  case 'mysql':
2967                  case 'mysqli':
2968                      $field = 'username';
2969                      break;
2970                  default:
2971                      $field = 'LOWER(username)';
2972                      break;
2973              }
2974              $query = $db->simple_select("users", "uid,buddyrequestsauto,buddyrequestspm,language", "{$field} IN ('".my_strtolower(implode("','", $users))."')");
2975              while($user = $db->fetch_array($query))
2976              {
2977                  ++$found_users;
2978  
2979                  // Make sure we're not adding a duplicate
2980                  if(in_array($user['uid'], $existing_users) || in_array($user['uid'], $selected_list))
2981                  {
2982                      if($mybb->get_input('manage') == "ignored")
2983                      {
2984                          $error_message = "ignore";
2985                      }
2986                      else
2987                      {
2988                          $error_message = "buddy";
2989                      }
2990  
2991                      // On another list?
2992                      $string = "users_already_on_".$error_message."_list";
2993                      if(in_array($user['uid'], $selected_list))
2994                      {
2995                          $string .= "_alt";
2996                      }
2997  
2998                      $error_message = $lang->$string;
2999                      array_pop($users); // To maintain a proper count when we call count($users)
3000                      continue;
3001                  }
3002  
3003                  if(isset($requests[$user['uid']]))
3004                  {
3005                      if($mybb->get_input('manage') != "ignored")
3006                      {
3007                          $error_message = $lang->users_already_sent_request;
3008                      }
3009                      elseif($mybb->get_input('manage') == "ignored")
3010                      {
3011                          $error_message = $lang->users_already_sent_request_alt;
3012                      }
3013  
3014                      array_pop($users); // To maintain a proper count when we call count($users)
3015                      continue;
3016                  }
3017  
3018                  if(isset($requests_rec[$user['uid']]))
3019                  {
3020                      if($mybb->get_input('manage') != "ignored")
3021                      {
3022                          $error_message = $lang->users_already_rec_request;
3023                      }
3024                      elseif($mybb->get_input('manage') == "ignored")
3025                      {
3026                          $error_message = $lang->users_already_rec_request_alt;
3027                      }
3028  
3029                      array_pop($users); // To maintain a proper count when we call count($users)
3030                      continue;
3031                  }
3032  
3033                  // Do we have auto approval set to On?
3034                  if($user['buddyrequestsauto'] == 1 && $mybb->get_input('manage') != "ignored")
3035                  {
3036                      $existing_users[] = $user['uid'];
3037  
3038                      $pm = array(
3039                          'subject' => 'buddyrequest_new_buddy',
3040                          'message' => 'buddyrequest_new_buddy_message',
3041                          'touid' => $user['uid'],
3042                          'receivepms' => (int)$user['buddyrequestspm'],
3043                          'language' => $user['language'],
3044                          'language_file' => 'usercp'
3045                      );
3046  
3047                      send_pm($pm);
3048                  }
3049                  elseif($user['buddyrequestsauto'] != 1 && $mybb->get_input('manage') != "ignored")
3050                  {
3051                      // Send request
3052                      $id = $db->insert_query('buddyrequests', array('uid' => (int)$mybb->user['uid'], 'touid' => (int)$user['uid'], 'date' => TIME_NOW));
3053  
3054                      $pm = array(
3055                          'subject' => 'buddyrequest_received',
3056                          'message' => 'buddyrequest_received_message',
3057                          'touid' => $user['uid'],
3058                          'receivepms' => (int)$user['buddyrequestspm'],
3059                          'language' => $user['language'],
3060                          'language_file' => 'usercp'
3061                      );
3062  
3063                      send_pm($pm);
3064  
3065                      $sent = true;
3066                  }
3067                  elseif($mybb->get_input('manage') == "ignored")
3068                  {
3069                      $existing_users[] = $user['uid'];
3070                  }
3071              }
3072          }
3073  
3074          if($found_users < count($users))
3075          {
3076              if($error_message)
3077              {
3078                  $error_message .= "<br />";
3079              }
3080  
3081              $error_message .= $lang->invalid_user_selected;
3082          }
3083  
3084          if(($adding_self != true || ($adding_self == true && count($users) > 0)) && ($error_message == "" || count($users) > 1))
3085          {
3086              if($mybb->get_input('manage') == "ignored")
3087              {
3088                  $message = $lang->users_added_to_ignore_list;
3089              }
3090              else
3091              {
3092                  $message = $lang->users_added_to_buddy_list;
3093              }
3094          }
3095  
3096          if($adding_self == true)
3097          {
3098              if($mybb->get_input('manage') == "ignored")
3099              {
3100                  $error_message = $lang->cant_add_self_to_ignore_list;
3101              }
3102              else
3103              {
3104                  $error_message = $lang->cant_add_self_to_buddy_list;
3105              }
3106          }
3107  
3108          if(count($existing_users) == 0)
3109          {
3110              $message = "";
3111  
3112              if($sent === true)
3113              {
3114                  $message = $lang->buddyrequests_sent_success;
3115              }
3116          }
3117      }
3118  
3119      // Removing a user from this list
3120      elseif($mybb->get_input('delete', MyBB::INPUT_INT))
3121      {
3122          // Check if user exists on the list
3123          $key = array_search($mybb->get_input('delete', MyBB::INPUT_INT), $existing_users);
3124          if($key !== false)
3125          {
3126              unset($existing_users[$key]);
3127              $user = get_user($mybb->get_input('delete', MyBB::INPUT_INT));
3128              if(!empty($user))
3129              {
3130                  // We want to remove us from this user's buddy list
3131                  if($user['buddylist'] != '')
3132                  {
3133                      $user['buddylist'] = explode(',', $user['buddylist']);
3134                  }
3135                  else
3136                  {
3137                      $user['buddylist'] = array();
3138                  }
3139  
3140                  $key = array_search($mybb->get_input('delete', MyBB::INPUT_INT), $user['buddylist']);
3141                  unset($user['buddylist'][$key]);
3142  
3143                  // Now we have the new list, so throw it all back together
3144                  $new_list = implode(",", $user['buddylist']);
3145  
3146                  // And clean it up a little to ensure there is no possibility of bad values
3147                  $new_list = preg_replace("#,{2,}#", ",", $new_list);
3148                  $new_list = preg_replace("#[^0-9,]#", "", $new_list);
3149  
3150                  if(my_substr($new_list, 0, 1) == ",")
3151                  {
3152                      $new_list = my_substr($new_list, 1);
3153                  }
3154                  if(my_substr($new_list, -1) == ",")
3155                  {
3156                      $new_list = my_substr($new_list, 0, my_strlen($new_list)-2);
3157                  }
3158  
3159                  $user['buddylist'] = $db->escape_string($new_list);
3160  
3161                  $db->update_query("users", array('buddylist' => $user['buddylist']), "uid='".(int)$user['uid']."'");
3162              }
3163  
3164              if($mybb->get_input('manage') == "ignored")
3165              {
3166                  $message = $lang->removed_from_ignore_list;
3167              }
3168              else
3169              {
3170                  $message = $lang->removed_from_buddy_list;
3171              }
3172              $user['username'] = htmlspecialchars_uni($user['username']);
3173              $message = $lang->sprintf($message, $user['username']);
3174          }
3175      }
3176  
3177      // Now we have the new list, so throw it all back together
3178      $new_list = implode(",", $existing_users);
3179  
3180      // And clean it up a little to ensure there is no possibility of bad values
3181      $new_list = preg_replace("#,{2,}#", ",", $new_list);
3182      $new_list = preg_replace("#[^0-9,]#", "", $new_list);
3183  
3184      if(my_substr($new_list, 0, 1) == ",")
3185      {
3186          $new_list = my_substr($new_list, 1);
3187      }
3188      if(my_substr($new_list, -1) == ",")
3189      {
3190          $new_list = my_substr($new_list, 0, my_strlen($new_list)-2);
3191      }
3192  
3193      // And update
3194      $user = array();
3195      if($mybb->get_input('manage') == "ignored")
3196      {
3197          $user['ignorelist'] = $db->escape_string($new_list);
3198          $mybb->user['ignorelist'] = $user['ignorelist'];
3199      }
3200      else
3201      {
3202          $user['buddylist'] = $db->escape_string($new_list);
3203          $mybb->user['buddylist'] = $user['buddylist'];
3204      }
3205  
3206      $db->update_query("users", $user, "uid='".$mybb->user['uid']."'");
3207  
3208      $plugins->run_hooks("usercp_do_editlists_end");
3209  
3210      // Ajax based request, throw new list to browser
3211      if(!empty($mybb->input['ajax']))
3212      {
3213          if($mybb->get_input('manage') == "ignored")
3214          {
3215              $list = "ignore";
3216          }
3217          else
3218          {
3219              $list = "buddy";
3220          }
3221  
3222          $message_js = '';
3223          if($message)
3224          {
3225              $message_js = "$.jGrowl('{$message}', {theme:'jgrowl_success'});";
3226          }
3227  
3228          if($error_message)
3229          {
3230              $message_js .= " $.jGrowl('{$error_message}', {theme:'jgrowl_error'});";
3231          }
3232  
3233          if($mybb->get_input('delete', MyBB::INPUT_INT))
3234          {
3235              header("Content-type: text/javascript");
3236              echo "$(\"#".$mybb->get_input('manage')."_".$mybb->get_input('delete', MyBB::INPUT_INT)."\").remove();\n";
3237              if($new_list == "")
3238              {
3239                  echo "\$(\"#".$mybb->get_input('manage')."_count\").html(\"0\");\n";
3240                  echo "\$(\"#buddylink\").remove();\n";
3241  
3242                  if($mybb->get_input('manage') == "ignored")
3243                  {
3244                      echo "\$(\"#ignore_list\").html(\"<li>{$lang->ignore_list_empty}</li>\");\n";
3245                  }
3246                  else
3247                  {
3248                      echo "\$(\"#buddy_list\").html(\"<li>{$lang->buddy_list_empty}</li>\");\n";
3249                  }
3250              }
3251              else
3252              {
3253                  echo "\$(\"#".$mybb->get_input('manage')."_count\").html(\"".count(explode(",", $new_list))."\");\n";
3254              }
3255              echo $message_js;
3256              exit;
3257          }
3258          $mybb->input['action'] = "editlists";
3259      }
3260      else
3261      {
3262          if($error_message)
3263          {
3264              $message .= "<br />".$error_message;
3265          }
3266          redirect("usercp.php?action=editlists#".$mybb->get_input('manage'), $message);
3267      }
3268  }
3269  
3270  if($mybb->input['action'] == "editlists")
3271  {
3272      $plugins->run_hooks("usercp_editlists_start");
3273  
3274      $timecut = TIME_NOW - $mybb->settings['wolcutoff'];
3275  
3276      // Fetch out buddies
3277      $buddy_count = 0;
3278      $buddy_list = '';
3279      if($mybb->user['buddylist'])
3280      {
3281          $type = "buddy";
3282          $query = $db->simple_select("users", "*", "uid IN ({$mybb->user['buddylist']})", array("order_by" => "username"));
3283          while($user = $db->fetch_array($query))
3284          {
3285              $user['username'] = htmlspecialchars_uni($user['username']);
3286              $profile_link = build_profile_link(format_name($user['username'], $user['usergroup'], $user['displaygroup']), $user['uid']);
3287              if($user['lastactive'] > $timecut && ($user['invisible'] == 0 || $mybb->usergroup['canviewwolinvis'] == 1) && $user['lastvisit'] != $user['lastactive'])
3288              {
3289                  $status = "online";
3290              }
3291              else
3292              {
3293                  $status = "offline";
3294              }
3295              eval("\$buddy_list .= \"".$templates->get("usercp_editlists_user")."\";");
3296              ++$buddy_count;
3297          }
3298      }
3299  
3300      $lang->current_buddies = $lang->sprintf($lang->current_buddies, $buddy_count);
3301      if(!$buddy_list)
3302      {
3303          eval("\$buddy_list = \"".$templates->get("usercp_editlists_no_buddies")."\";");
3304      }
3305  
3306      // Fetch out ignore list users
3307      $ignore_count = 0;
3308      $ignore_list = '';
3309      if($mybb->user['ignorelist'])
3310      {
3311          $type = "ignored";
3312          $query = $db->simple_select("users", "*", "uid IN ({$mybb->user['ignorelist']})", array("order_by" => "username"));
3313          while($user = $db->fetch_array($query))
3314          {
3315              $user['username'] = htmlspecialchars_uni($user['username']);
3316              $profile_link = build_profile_link(format_name($user['username'], $user['usergroup'], $user['displaygroup']), $user['uid']);
3317              if($user['lastactive'] > $timecut && ($user['invisible'] == 0 || $mybb->usergroup['canviewwolinvis'] == 1) && $user['lastvisit'] != $user['lastactive'])
3318              {
3319                  $status = "online";
3320              }
3321              else
3322              {
3323                  $status = "offline";
3324              }
3325              eval("\$ignore_list .= \"".$templates->get("usercp_editlists_user")."\";");
3326              ++$ignore_count;
3327          }
3328      }
3329  
3330      $lang->current_ignored_users = $lang->sprintf($lang->current_ignored_users, $ignore_count);
3331      if(!$ignore_list)
3332      {
3333          eval("\$ignore_list = \"".$templates->get("usercp_editlists_no_ignored")."\";");
3334      }
3335  
3336      // If an AJAX request from buddy management, echo out whatever the new list is.
3337      if($mybb->request_method == "post" && $mybb->input['ajax'] == 1)
3338      {
3339          if($mybb->input['manage'] == "ignored")
3340          {
3341              echo $ignore_list;
3342              echo "<script type=\"text/javascript\"> $(\"#ignored_count\").html(\"{$ignore_count}\"); {$message_js}</script>";
3343          }
3344          else
3345          {
3346              if(isset($sent) && $sent === true)
3347              {
3348                  $sent_rows = '';
3349                  $query = $db->query("
3350                      SELECT r.*, u.username
3351                      FROM ".TABLE_PREFIX."buddyrequests r
3352                      LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=r.touid)
3353                      WHERE r.uid=".(int)$mybb->user['uid']);
3354  
3355                  while($request = $db->fetch_array($query))
3356                  {
3357                      $bgcolor = alt_trow();
3358                      $request['username'] = build_profile_link(htmlspecialchars_uni($request['username']), (int)$request['touid']);
3359                      $request['date'] = my_date('relative', $request['date']);
3360                      eval("\$sent_rows .= \"".$templates->get("usercp_editlists_sent_request", 1, 0)."\";");
3361                  }
3362  
3363                  if($sent_rows == '')
3364                  {
3365                      eval("\$sent_rows = \"".$templates->get("usercp_editlists_no_requests", 1, 0)."\";");
3366                  }
3367  
3368                  eval("\$sent_requests = \"".$templates->get("usercp_editlists_sent_requests", 1, 0)."\";");
3369  
3370                  echo $sent_requests."<script type=\"text/javascript\">{$message_js}</script>";
3371              }
3372              else
3373              {
3374                  echo $buddy_list;
3375                  echo "<script type=\"text/javascript\"> $(\"#buddy_count\").html(\"{$buddy_count}\"); {$message_js}</script>";
3376              }
3377          }
3378          exit;
3379      }
3380  
3381      $received_rows = $bgcolor = '';
3382      $query = $db->query("
3383          SELECT r.*, u.username
3384          FROM ".TABLE_PREFIX."buddyrequests r
3385          LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=r.uid)
3386          WHERE r.touid=".(int)$mybb->user['uid']);
3387  
3388      while($request = $db->fetch_array($query))
3389      {
3390          $bgcolor = alt_trow();
3391          $request['username'] = build_profile_link(htmlspecialchars_uni($request['username']), (int)$request['uid']);
3392          $request['date'] = my_date('relative', $request['date']);
3393          eval("\$received_rows .= \"".$templates->get("usercp_editlists_received_request")."\";");
3394      }
3395  
3396      if($received_rows == '')
3397      {
3398          eval("\$received_rows = \"".$templates->get("usercp_editlists_no_requests")."\";");
3399      }
3400  
3401      eval("\$received_requests = \"".$templates->get("usercp_editlists_received_requests")."\";");
3402  
3403      $sent_rows = $bgcolor = '';
3404      $query = $db->query("
3405          SELECT r.*, u.username
3406          FROM ".TABLE_PREFIX."buddyrequests r
3407          LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=r.touid)
3408          WHERE r.uid=".(int)$mybb->user['uid']);
3409  
3410      while($request = $db->fetch_array($query))
3411      {
3412          $bgcolor = alt_trow();
3413          $request['username'] = build_profile_link(htmlspecialchars_uni($request['username']), (int)$request['touid']);
3414          $request['date'] = my_date('relative', $request['date']);
3415          eval("\$sent_rows .= \"".$templates->get("usercp_editlists_sent_request")."\";");
3416      }
3417  
3418      if($sent_rows == '')
3419      {
3420          eval("\$sent_rows = \"".$templates->get("usercp_editlists_no_requests")."\";");
3421      }
3422  
3423      eval("\$sent_requests = \"".$templates->get("usercp_editlists_sent_requests")."\";");
3424  
3425      $plugins->run_hooks("usercp_editlists_end");
3426  
3427      eval("\$listpage = \"".$templates->get("usercp_editlists")."\";");
3428      output_page($listpage);
3429  }
3430  
3431  if($mybb->input['action'] == "drafts")
3432  {
3433      $plugins->run_hooks("usercp_drafts_start");
3434  
3435      $query = $db->simple_select("posts", "COUNT(pid) AS draftcount", "visible='-2' AND uid='{$mybb->user['uid']}'");
3436      $draftcount = $db->fetch_field($query, 'draftcount');
3437  
3438      $drafts = $disable_delete_drafts = '';
3439      $lang->drafts_count = $lang->sprintf($lang->drafts_count, my_number_format($draftcount));
3440  
3441      // Show a listing of all of the current 'draft' posts or threads the user has.
3442      if($draftcount)
3443      {
3444          $query = $db->query("
3445              SELECT p.subject, p.pid, t.tid, t.subject AS threadsubject, t.fid, f.name AS forumname, p.dateline, t.visible AS threadvisible, p.visible AS postvisible
3446              FROM ".TABLE_PREFIX."posts p
3447              LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
3448              LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=t.fid)
3449              WHERE p.uid = '{$mybb->user['uid']}' AND p.visible = '-2'
3450              ORDER BY p.dateline DESC, p.pid DESC
3451          ");
3452  
3453          while($draft = $db->fetch_array($query))
3454          {
3455              $detail = '';
3456              $trow = alt_trow();
3457              if($draft['threadvisible'] == 1) // We're looking at a draft post
3458              {
3459                  $draft['threadlink'] = get_thread_link($draft['tid']);
3460                  $draft['threadsubject'] = htmlspecialchars_uni($draft['threadsubject']);
3461                  eval("\$detail = \"".$templates->get("usercp_drafts_draft_thread")."\";");
3462                  $editurl = "newreply.php?action=editdraft&amp;pid={$draft['pid']}";
3463                  $id = $draft['pid'];
3464                  $type = "post";
3465              }
3466              elseif($draft['threadvisible'] == -2) // We're looking at a draft thread
3467              {
3468                  $draft['forumlink'] = get_forum_link($draft['fid']);
3469                  $draft['forumname'] = htmlspecialchars_uni($draft['forumname']);
3470                  eval("\$detail = \"".$templates->get("usercp_drafts_draft_forum")."\";");
3471                  $editurl = "newthread.php?action=editdraft&amp;tid={$draft['tid']}";
3472                  $id = $draft['tid'];
3473                  $type = "thread";
3474              }
3475  
3476              $draft['subject'] = htmlspecialchars_uni($draft['subject']);
3477              $savedate = my_date('relative', $draft['dateline']);
3478              eval("\$drafts .= \"".$templates->get("usercp_drafts_draft")."\";");
3479          }
3480      }
3481      else
3482      {
3483          $disable_delete_drafts = 'disabled="disabled"';
3484          eval("\$drafts = \"".$templates->get("usercp_drafts_none")."\";");
3485      }
3486  
3487      $plugins->run_hooks("usercp_drafts_end");
3488  
3489      eval("\$draftlist = \"".$templates->get("usercp_drafts")."\";");
3490      output_page($draftlist);
3491  }
3492  
3493  if($mybb->input['action'] == "do_drafts" && $mybb->request_method == "post")
3494  {
3495      // Verify incoming POST request
3496      verify_post_check($mybb->get_input('my_post_key'));
3497  
3498      $mybb->input['deletedraft'] = $mybb->get_input('deletedraft', MyBB::INPUT_ARRAY);
3499      if(empty($mybb->input['deletedraft']))
3500      {
3501          error($lang->no_drafts_selected);
3502      }
3503  
3504      $plugins->run_hooks("usercp_do_drafts_start");
3505  
3506      $pidin = array();
3507      $tidin = array();
3508  
3509      foreach($mybb->input['deletedraft'] as $id => $val)
3510      {
3511          if($val == "post")
3512          {
3513              $pidin[] = "'".(int)$id."'";
3514          }
3515          elseif($val == "thread")
3516          {
3517              $tidin[] = "'".(int)$id."'";
3518          }
3519      }
3520      if($tidin)
3521      {
3522          $tidin = implode(",", $tidin);
3523          $db->delete_query("threads", "tid IN ($tidin) AND visible='-2' AND uid='".$mybb->user['uid']."'");
3524          $tidinp = "OR tid IN ($tidin)";
3525      }
3526      else
3527      {
3528          $tidinp = '';
3529      }
3530      if($pidin || $tidinp)
3531      {
3532          $pidinq = $tidin = '';
3533          if($pidin)
3534          {
3535              $pidin = implode(",", $pidin);
3536              $pidinq = "pid IN ($pidin)";
3537          }
3538          else
3539          {
3540              $pidinq = "1=0";
3541          }
3542          $db->delete_query("posts", "($pidinq $tidinp) AND visible='-2' AND uid='".$mybb->user['uid']."'");
3543      }
3544      $plugins->run_hooks("usercp_do_drafts_end");
3545      redirect("usercp.php?action=drafts", $lang->selected_drafts_deleted);
3546  }
3547  
3548  if($mybb->input['action'] == "usergroups")
3549  {
3550      $ingroups = ",".$mybb->user['usergroup'].",".$mybb->user['additionalgroups'].",".$mybb->user['displaygroup'].",";
3551  
3552      $usergroups = $mybb->cache->read('usergroups');
3553  
3554      $plugins->run_hooks("usercp_usergroups_start");
3555  
3556      // Changing our display group
3557      if($mybb->get_input('displaygroup', MyBB::INPUT_INT))
3558      {
3559          // Verify incoming POST request
3560          verify_post_check($mybb->get_input('my_post_key'));
3561  
3562          if(my_strpos($ingroups, ",".$mybb->input['displaygroup'].",") === false)
3563          {
3564              error($lang->not_member_of_group);
3565          }
3566  
3567          $dispgroup = $usergroups[$mybb->get_input('displaygroup', MyBB::INPUT_INT)];
3568          if($dispgroup['candisplaygroup'] != 1)
3569          {
3570              error($lang->cannot_set_displaygroup);
3571          }
3572          $db->update_query("users", array('displaygroup' => $mybb->get_input('displaygroup', MyBB::INPUT_INT)), "uid='".$mybb->user['uid']."'");
3573          $cache->update_moderators();
3574          $plugins->run_hooks("usercp_usergroups_change_displaygroup");
3575          redirect("usercp.php?action=usergroups", $lang->display_group_changed);
3576          exit;
3577      }
3578  
3579      // Leaving a group
3580      if($mybb->get_input('leavegroup', MyBB::INPUT_INT))
3581      {
3582          // Verify incoming POST request
3583          verify_post_check($mybb->input['my_post_key']);
3584  
3585          if(my_strpos($ingroups, ",".$mybb->get_input('leavegroup', MyBB::INPUT_INT).",") === false)
3586          {
3587              error($lang->not_member_of_group);
3588          }
3589          if($mybb->user['usergroup'] == $mybb->get_input('leavegroup', MyBB::INPUT_INT))
3590          {
3591              error($lang->cannot_leave_primary_group);
3592          }
3593  
3594          $usergroup = $usergroups[$mybb->get_input('leavegroup', MyBB::INPUT_INT)];
3595          if($usergroup['type'] != 4 && $usergroup['type'] != 3 && $usergroup['type'] != 5)
3596          {
3597              error($lang->cannot_leave_group);
3598          }
3599          leave_usergroup($mybb->user['uid'], $mybb->get_input('leavegroup', MyBB::INPUT_INT));
3600          $plugins->run_hooks("usercp_usergroups_leave_group");
3601          redirect("usercp.php?action=usergroups", $lang->left_group);
3602          exit;
3603      }
3604  
3605      $groupleaders = array();
3606  
3607      // List of usergroup leaders
3608      $query = $db->query("
3609          SELECT g.*, u.username, u.displaygroup, u.usergroup, u.email, u.language
3610          FROM ".TABLE_PREFIX."groupleaders g
3611          LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=g.uid)
3612          ORDER BY u.username ASC
3613      ");
3614      while($leader = $db->fetch_array($query))
3615      {
3616          $groupleaders[$leader['gid']][$leader['uid']] = $leader;
3617      }
3618  
3619      // Joining a group
3620      if($mybb->get_input('joingroup', MyBB::INPUT_INT))
3621      {
3622          // Verify incoming POST request
3623          verify_post_check($mybb->get_input('my_post_key'));
3624  
3625          $usergroup = $usergroups[$mybb->get_input('joingroup', MyBB::INPUT_INT)];
3626  
3627          if($usergroup['type'] == 5)
3628          {
3629              error($lang->cannot_join_invite_group);
3630          }
3631  
3632          if(($usergroup['type'] != 4 && $usergroup['type'] != 3) || !$usergroup['gid'])
3633          {
3634              error($lang->cannot_join_group);
3635          }
3636  
3637          if(my_strpos($ingroups, ",".$mybb->get_input('joingroup', MyBB::INPUT_INT).",") !== false)
3638          {
3639              error($lang->already_member_of_group);
3640          }
3641  
3642          $query = $db->simple_select("joinrequests", "*", "uid='".$mybb->user['uid']."' AND gid='".$mybb->get_input('joingroup', MyBB::INPUT_INT)."'");
3643          $joinrequest = $db->fetch_array($query);
3644  
3645          if($joinrequest['rid'])
3646          {
3647              error($lang->already_sent_join_request);
3648          }
3649  
3650          if($mybb->get_input('do') == "joingroup" && $usergroup['type'] == 4)
3651          {
3652              $reasonlength = my_strlen($mybb->get_input('reason'));
3653  
3654              if($reasonlength > 250) // Reason field is varchar(250) in database
3655              {
3656                  error($lang->sprintf($lang->joinreason_too_long, ($reasonlength - 250)));
3657              }
3658  
3659              $now = TIME_NOW;
3660              $joinrequest = array(
3661                  "uid" => $mybb->user['uid'],
3662                  "gid" => $mybb->get_input('joingroup', MyBB::INPUT_INT),
3663                  "reason" => $db->escape_string($mybb->get_input('reason')),
3664                  "dateline" => TIME_NOW
3665              );
3666  
3667              $db->insert_query("joinrequests", $joinrequest);
3668  
3669              if(array_key_exists($usergroup['gid'], $groupleaders))
3670              {
3671                  foreach($groupleaders[$usergroup['gid']] as $leader)
3672                  {
3673                      // Load language
3674                      $lang->set_language($leader['language']);
3675                      $lang->load("messages");
3676  
3677                      $subject = $lang->sprintf($lang->emailsubject_newjoinrequest, $mybb->settings['bbname']);
3678                      $message = $lang->sprintf($lang->email_groupleader_joinrequest, $leader['username'], $mybb->user['username'], $usergroup['title'], $mybb->settings['bbname'], $mybb->get_input('reason'), $mybb->settings['bburl'], $leader['gid']);
3679                      my_mail($leader['email'], $subject, $message);
3680                  }
3681              }
3682  
3683              // Load language
3684              $lang->set_language($mybb->user['language']);
3685              $lang->load("messages");
3686  
3687              $plugins->run_hooks("usercp_usergroups_join_group_request");
3688              redirect("usercp.php?action=usergroups", $lang->group_join_requestsent);
3689              exit;
3690          }
3691          elseif($usergroup['type'] == 4)
3692          {
3693              $joingroup = $mybb->get_input('joingroup', MyBB::INPUT_INT);
3694              eval("\$joinpage = \"".$templates->get("usercp_usergroups_joingroup")."\";");
3695              output_page($joinpage);
3696              exit;
3697          }
3698          else
3699          {
3700              join_usergroup($mybb->user['uid'], $mybb->get_input('joingroup', MyBB::INPUT_INT));
3701              $plugins->run_hooks("usercp_usergroups_join_group");
3702              redirect("usercp.php?action=usergroups", $lang->joined_group);
3703          }
3704      }
3705  
3706      // Accepting invitation
3707      if($mybb->get_input('acceptinvite', MyBB::INPUT_INT))
3708      {
3709          // Verify incoming POST request
3710          verify_post_check($mybb->get_input('my_post_key'));
3711  
3712          $usergroup = $usergroups[$mybb->get_input('acceptinvite', MyBB::INPUT_INT)];
3713  
3714          if(my_strpos($ingroups, ",".$mybb->get_input('acceptinvite', MyBB::INPUT_INT).",") !== false)
3715          {
3716              error($lang->already_accepted_invite);
3717          }
3718  
3719          $query = $db->simple_select("joinrequests", "*", "uid='".$mybb->user['uid']."' AND gid='".$mybb->get_input('acceptinvite', MyBB::INPUT_INT)."' AND invite='1'");
3720          $joinrequest = $db->fetch_array($query);
3721          if($joinrequest['rid'])
3722          {
3723              join_usergroup($mybb->user['uid'], $mybb->get_input('acceptinvite', MyBB::INPUT_INT));
3724              $db->delete_query("joinrequests", "uid='{$mybb->user['uid']}' AND gid='".$mybb->get_input('acceptinvite', MyBB::INPUT_INT)."'");
3725              $plugins->run_hooks("usercp_usergroups_accept_invite");
3726              redirect("usercp.php?action=usergroups", $lang->joined_group);
3727          }
3728          else
3729          {
3730              error($lang->no_pending_invitation);
3731          }
3732      }
3733      // Show listing of various group related things
3734  
3735      // List of groups this user is a leader of
3736      $groupsledlist = '';
3737  
3738      switch($db->type)
3739      {
3740          case "pgsql":
3741          case "sqlite":
3742              $query = $db->query("
3743                  SELECT g.title, g.gid, g.type, COUNT(DISTINCT u.uid) AS users, COUNT(DISTINCT j.rid) AS joinrequests, l.canmanagerequests, l.canmanagemembers, l.caninvitemembers
3744                  FROM ".TABLE_PREFIX."groupleaders l
3745                  LEFT JOIN ".TABLE_PREFIX."usergroups g ON(g.gid=l.gid)
3746                  LEFT JOIN ".TABLE_PREFIX."users u ON(((','|| u.additionalgroups|| ',' LIKE '%,'|| g.gid|| ',%') OR u.usergroup = g.gid))
3747                  LEFT JOIN ".TABLE_PREFIX."joinrequests j ON(j.gid=g.gid AND j.uid != 0)
3748                  WHERE l.uid='".$mybb->user['uid']."'
3749                  GROUP BY g.gid, g.title, g.type, l.canmanagerequests, l.canmanagemembers, l.caninvitemembers
3750              ");
3751              break;
3752          default:
3753              $query = $db->query("
3754                  SELECT g.title, g.gid, g.type, COUNT(DISTINCT u.uid) AS users, COUNT(DISTINCT j.rid) AS joinrequests, l.canmanagerequests, l.canmanagemembers, l.caninvitemembers
3755                  FROM ".TABLE_PREFIX."groupleaders l
3756                  LEFT JOIN ".TABLE_PREFIX."usergroups g ON(g.gid=l.gid)
3757                  LEFT JOIN ".TABLE_PREFIX."users u ON(((CONCAT(',', u.additionalgroups, ',') LIKE CONCAT('%,', g.gid, ',%')) OR u.usergroup = g.gid))
3758                  LEFT JOIN ".TABLE_PREFIX."joinrequests j ON(j.gid=g.gid AND j.uid != 0)
3759                  WHERE l.uid='".$mybb->user['uid']."'
3760                  GROUP BY g.gid, g.title, g.type, l.canmanagerequests, l.canmanagemembers, l.caninvitemembers
3761              ");
3762      }
3763  
3764      while($usergroup = $db->fetch_array($query))
3765      {
3766          $memberlistlink = $moderaterequestslink = '';
3767          eval("\$memberlistlink = \"".$templates->get("usercp_usergroups_leader_usergroup_memberlist")."\";");
3768          $usergroup['title'] = htmlspecialchars_uni($usergroup['title']);
3769          if($usergroup['type'] != 4)
3770          {
3771              $usergroup['joinrequests'] = '--';
3772          }
3773          if($usergroup['joinrequests'] > 0 && $usergroup['canmanagerequests'] == 1)
3774          {
3775              eval("\$moderaterequestslink = \"".$templates->get("usercp_usergroups_leader_usergroup_moderaterequests")."\";");
3776          }
3777          $groupleader[$usergroup['gid']] = 1;
3778          $trow = alt_trow();
3779          eval("\$groupsledlist .= \"".$templates->get("usercp_usergroups_leader_usergroup")."\";");
3780      }
3781      $leadinggroups = '';
3782      if($groupsledlist)
3783      {
3784          eval("\$leadinggroups = \"".$templates->get("usercp_usergroups_leader")."\";");
3785      }
3786  
3787      // Fetch the list of groups the member is in
3788      // Do the primary group first
3789      $usergroup = $usergroups[$mybb->user['usergroup']];
3790      $usergroup['title'] = htmlspecialchars_uni($usergroup['title']);
3791      $usergroup['usertitle'] = htmlspecialchars_uni($usergroup['usertitle']);
3792      if($usergroup['description'])
3793      {
3794          $usergroup['description'] = htmlspecialchars_uni($usergroup['description']);
3795          eval("\$description = \"".$templates->get("usercp_usergroups_memberof_usergroup_description")."\";");
3796      }
3797      eval("\$leavelink = \"".$templates->get("usercp_usergroups_memberof_usergroup_leaveprimary")."\";");
3798      $trow = alt_trow();
3799      if($usergroup['candisplaygroup'] == 1 && $usergroup['gid'] == $mybb->user['displaygroup'])
3800      {
3801          eval("\$displaycode = \"".$templates->get("usercp_usergroups_memberof_usergroup_display")."\";");
3802      }
3803      elseif($usergroup['candisplaygroup'] == 1)
3804      {
3805          eval("\$displaycode = \"".$templates->get("usercp_usergroups_memberof_usergroup_setdisplay")."\";");
3806      }
3807      else
3808      {
3809          $displaycode = '';
3810      }
3811  
3812      eval("\$memberoflist = \"".$templates->get("usercp_usergroups_memberof_usergroup")."\";");
3813      $showmemberof = false;
3814      if($mybb->user['additionalgroups'])
3815      {
3816          $additionalgroups = implode(
3817              ',',
3818              array_map(
3819                  'intval',
3820                  explode(',', $mybb->user['additionalgroups'])
3821              )
3822          );
3823          $query = $db->simple_select("usergroups", "*", "gid IN (".$additionalgroups.") AND gid !='".$mybb->user['usergroup']."'", array('order_by' => 'title'));
3824          while($usergroup = $db->fetch_array($query))
3825          {
3826              $showmemberof = true;
3827  
3828              if(isset($groupleader[$usergroup['gid']]))
3829              {
3830                  eval("\$leavelink = \"".$templates->get("usercp_usergroups_memberof_usergroup_leaveleader")."\";");
3831              }
3832              elseif($usergroup['type'] != 4 && $usergroup['type'] != 3 && $usergroup['type'] != 5)
3833              {
3834                  eval("\$leavelink = \"".$templates->get("usercp_usergroups_memberof_usergroup_leaveother")."\";");
3835              }
3836              else
3837              {
3838                  eval("\$leavelink = \"".$templates->get("usercp_usergroups_memberof_usergroup_leave")."\";");
3839              }
3840  
3841              $description = '';
3842              $usergroup['title'] = htmlspecialchars_uni($usergroup['title']);
3843              $usergroup['usertitle'] = htmlspecialchars_uni($usergroup['usertitle']);
3844              if($usergroup['description'])
3845              {
3846                  $usergroup['description'] = htmlspecialchars_uni($usergroup['description']);
3847                  eval("\$description = \"".$templates->get("usercp_usergroups_memberof_usergroup_description")."\";");
3848              }
3849              $trow = alt_trow();
3850              if($usergroup['candisplaygroup'] == 1 && $usergroup['gid'] == $mybb->user['displaygroup'])
3851              {
3852                  eval("\$displaycode = \"".$templates->get("usercp_usergroups_memberof_usergroup_display")."\";");
3853              }
3854              elseif($usergroup['candisplaygroup'] == 1)
3855              {
3856                  eval("\$displaycode = \"".$templates->get("usercp_usergroups_memberof_usergroup_setdisplay")."\";");
3857              }
3858              else
3859              {
3860                  $displaycode = '';
3861              }
3862              eval("\$memberoflist .= \"".$templates->get("usercp_usergroups_memberof_usergroup")."\";");
3863          }
3864      }
3865      eval("\$membergroups = \"".$templates->get("usercp_usergroups_memberof")."\";");
3866  
3867      // List of groups this user has applied for but has not been accepted in to
3868      $query = $db->simple_select("joinrequests", "*", "uid='".$mybb->user['uid']."'");
3869      while($request = $db->fetch_array($query))
3870      {
3871          $appliedjoin[$request['gid']] = $request['dateline'];
3872      }
3873  
3874      // Fetch list of groups the member can join
3875      $existinggroups = $mybb->user['usergroup'];
3876      if($mybb->user['additionalgroups'])
3877      {
3878          $additionalgroups = implode(
3879              ',',
3880              array_map(
3881                  'intval',
3882                  explode(',', $mybb->user['additionalgroups'])
3883              )
3884          );
3885          $existinggroups .= ",".$additionalgroups;
3886      }
3887  
3888      $joinablegroups = $joinablegrouplist = '';
3889      $query = $db->simple_select("usergroups", "*", "(type='3' OR type='4' OR type='5') AND gid NOT IN ($existinggroups)", array('order_by' => 'title'));