[ Index ]

PHP Cross Reference of MyBB 1.8.38

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