[ Index ]

PHP Cross Reference of MyBB 1.8.15

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