[ Index ]

PHP Cross Reference of MyBB 1.8.26

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