[ Index ]

PHP Cross Reference of MyBB 1.8.28

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