[ Index ]

PHP Cross Reference of MyBB 1.8.19

title

Body

[close]

/ -> usercp.php (source)

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