[ Index ]

PHP Cross Reference of BuddyPress

title

Body

[close]

/src/bp-forums/ -> bp-forums-bbpress-sa.php (source)

   1  <?php
   2  /**
   3   * BuddyPress bbPress 1.x integration.
   4   *
   5   * @package BuddyPress
   6   * @subpackage ForumsbbPress
   7   * @since 1.5.0
   8   */
   9  
  10  // Exit if accessed directly.
  11  defined( 'ABSPATH' ) || exit;
  12  
  13  /**
  14   * Bootstrap bbPress 1.x, and manipulate globals to integrate with BuddyPress.
  15   *
  16   * @since 1.1.0
  17   *
  18   * @return bool|null Returns false on failure.
  19   */
  20  function bp_forums_load_bbpress() {
  21      global $wpdb, $wp_roles, $current_user, $wp_users_object;
  22      global $bb, $bbdb, $bb_table_prefix, $bb_current_user;
  23      global $bb_roles, $wp_taxonomy_object, $bb_queries;
  24  
  25      // Return if we've already run this function.
  26      if ( is_object( $bbdb ) )
  27          return;
  28  
  29      if ( !bp_forums_is_installed_correctly() )
  30          return false;
  31  
  32      $bp = buddypress();
  33  
  34      define( 'BB_PATH',        $bp->plugin_dir . '/bp-forums/bbpress/' );
  35      define( 'BACKPRESS_PATH', $bp->plugin_dir . '/bp-forums/bbpress/bb-includes/backpress/' );
  36      define( 'BB_URL',         $bp->plugin_url . 'bp-forums/bbpress/' );
  37      define( 'BB_INC', 'bb-includes/' );
  38  
  39      require( BB_PATH . BB_INC . 'class.bb-query.php' );
  40      require( BB_PATH . BB_INC . 'class.bb-walker.php' );
  41  
  42      require( BB_PATH . BB_INC . 'functions.bb-core.php' );
  43      require( BB_PATH . BB_INC . 'functions.bb-forums.php' );
  44      require( BB_PATH . BB_INC . 'functions.bb-topics.php' );
  45      require( BB_PATH . BB_INC . 'functions.bb-posts.php' );
  46      require( BB_PATH . BB_INC . 'functions.bb-topic-tags.php' );
  47      require( BB_PATH . BB_INC . 'functions.bb-capabilities.php' );
  48      require( BB_PATH . BB_INC . 'functions.bb-meta.php' );
  49      require( BB_PATH . BB_INC . 'functions.bb-pluggable.php' );
  50      require( BB_PATH . BB_INC . 'functions.bb-formatting.php' );
  51      require( BB_PATH . BB_INC . 'functions.bb-template.php' );
  52  
  53      require( BACKPRESS_PATH . 'class.wp-taxonomy.php' );
  54      require( BB_PATH . BB_INC . 'class.bb-taxonomy.php' );
  55  
  56      require ( BB_PATH . 'bb-admin/includes/functions.bb-admin.php' );
  57  
  58      $bb = new stdClass();
  59      require( bp_get_option(    'bb-config-location' ) );
  60  
  61      // Setup the global database connection.
  62      $bbdb = new BPDB ( BBDB_USER, BBDB_PASSWORD, BBDB_NAME, BBDB_HOST );
  63  
  64      // Set the table names.
  65      $bbdb->forums             = $bb_table_prefix . 'forums';
  66      $bbdb->meta               = $bb_table_prefix . 'meta';
  67      $bbdb->posts              = $bb_table_prefix . 'posts';
  68      $bbdb->terms              = $bb_table_prefix . 'terms';
  69      $bbdb->term_relationships = $bb_table_prefix . 'term_relationships';
  70      $bbdb->term_taxonomy      = $bb_table_prefix . 'term_taxonomy';
  71      $bbdb->topics             = $bb_table_prefix . 'topics';
  72  
  73      if ( isset( $bb->custom_user_table ) )
  74          $bbdb->users = $bb->custom_user_table;
  75      else
  76          $bbdb->users = $wpdb->users;
  77  
  78      if ( isset( $bb->custom_user_meta_table ) )
  79          $bbdb->usermeta = $bb->custom_user_meta_table;
  80      else
  81          $bbdb->usermeta = $wpdb->usermeta;
  82  
  83      $bbdb->prefix = $bb_table_prefix;
  84  
  85      define( 'BB_INSTALLING', false );
  86  
  87      if ( is_object( $wp_roles ) ) {
  88          $bb_roles = $wp_roles;
  89          bb_init_roles( $bb_roles );
  90      }
  91  
  92      /**
  93       * Fires during the bootstrap setup for bbPress 1.x.
  94       *
  95       * @since 1.1.0
  96       */
  97      do_action( 'bb_got_roles' );
  98  
  99      /**
 100       * Fires during the bootstrap setup for bbPress 1.x.
 101       *
 102       * @since 1.1.0
 103       */
 104      do_action( 'bb_init'      );
 105  
 106      /**
 107       * Fires during the bootstrap setup for bbPress 1.x.
 108       *
 109       * @since 1.1.0
 110       */
 111      do_action( 'init_roles'   );
 112  
 113      $bb_current_user = $current_user;
 114      $wp_users_object = new BP_Forums_BB_Auth;
 115  
 116      if ( !isset( $wp_taxonomy_object ) )
 117          $wp_taxonomy_object = new BB_Taxonomy( $bbdb );
 118  
 119      $wp_taxonomy_object->register_taxonomy( 'bb_topic_tag', 'bb_topic' );
 120  
 121      // Set a site id if there isn't one already.
 122      if ( !isset( $bb->site_id ) )
 123          $bb->site_id = bp_get_root_blog_id();
 124  
 125      // Check if the tables are installed, if not, install them.
 126      if ( !$tables_installed = (boolean) $bbdb->get_results( 'DESCRIBE `' . $bbdb->forums . '`;', ARRAY_A ) ) {
 127          require( BB_PATH . 'bb-admin/includes/defaults.bb-schema.php' );
 128  
 129          // Backticks and "IF NOT EXISTS" break the dbDelta function.
 130          bp_bb_dbDelta( str_replace( ' IF NOT EXISTS', '', str_replace( '`', '', $bb_queries ) ) );
 131  
 132          require( BB_PATH . 'bb-admin/includes/functions.bb-upgrade.php' );
 133          bb_update_db_version();
 134  
 135          // Set the site admins as the keymasters.
 136          $site_admins = get_site_option( 'site_admins', array('admin') );
 137          foreach ( (array) $site_admins as $site_admin )
 138              bp_update_user_meta( bp_core_get_userid( $site_admin ), $bb_table_prefix . 'capabilities', array( 'keymaster' => true ) );
 139  
 140          // Create the first forum.
 141          bb_new_forum( array( 'forum_name' => 'Default Forum' ) );
 142  
 143          // Set the site URI.
 144          bb_update_option( 'uri', BB_URL );
 145      }
 146  
 147      /**
 148       * Fires inside an anonymous function that is run on bbPress shutdown.
 149       *
 150       * @since 1.1.0
 151       */
 152      register_shutdown_function( function() { do_action( 'bb_shutdown' ); } );
 153  }
 154  add_action( 'bbpress_init', 'bp_forums_load_bbpress' );
 155  
 156  /** WP to bbPress wrapper functions ******************************************/
 157  
 158  /**
 159   * Get the current bbPress user.
 160   *
 161   * @since 1.1.0
 162   *
 163   * @return object $current_user Current user object from WordPress.
 164   */
 165  function bb_get_current_user() { global $current_user; return $current_user; }
 166  
 167  /**
 168   * Get userdata for a bbPress user.
 169   *
 170   * @since 1.1.0
 171   *
 172   * @param int $user_id User ID.
 173   * @return object User data from WordPress.
 174   */
 175  function bb_get_user( $user_id ) { return get_userdata( $user_id ); }
 176  
 177  /**
 178   * Cache users.
 179   *
 180   * Noop.
 181   *
 182   * @since 1.1.0
 183   *
 184   * @param array $users Array of users.
 185   */
 186  function bb_cache_users( $users ) {}
 187  
 188  /**
 189   * The bbPress plugin needs this class for its usermeta manipulation.
 190   *
 191   * @since 1.1.0
 192   */
 193  class BP_Forums_BB_Auth {
 194  
 195      /**
 196       * Update usermeta data.
 197       *
 198       * @since 1.1.0
 199       *
 200       * @param string $args Array of arguments.
 201       * @return bool
 202       */
 203  	function update_meta( $args = '' ) {
 204          $defaults = array( 'id' => 0, 'meta_key' => null, 'meta_value' => null, 'meta_table' => 'usermeta', 'meta_field' => 'user_id', 'cache_group' => 'users' );
 205          $args = wp_parse_args( $args, $defaults );
 206          extract( $args, EXTR_SKIP );
 207  
 208          return bp_update_user_meta( $id, $meta_key, $meta_value );
 209      }
 210  }
 211  
 212  /**
 213   * The bbPress plugin needs the DB class to be BPDB, but we want to use WPDB, so we can extend it and use this.
 214   *
 215   * The class is pluggable, so that plugins that swap out WPDB with a custom
 216   * database class (such as HyperDB and ShareDB) can provide their own versions
 217   * of BPDB which extend the appropriate base class.
 218   */
 219  if ( ! class_exists( 'BPDB' ) ) :
 220  
 221      /**
 222       * WPDB class extension.
 223       *
 224       * @since 1.1.0
 225       */
 226      class BPDB extends WPDB {
 227          var $db_servers = array();
 228  
 229          /**
 230           * Constructor.
 231           *
 232           * @since 1.1.0
 233           *
 234           * @see WPDB::__construct() for description of parameters.
 235           */
 236  		function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
 237              parent::__construct( $dbuser, $dbpassword, $dbname, $dbhost );
 238  
 239              $args = call_user_func_array( array( &$this, 'init' ), func_get_args() );
 240  
 241              if ( $args['host'] )
 242                  $this->db_servers['dbh_global'] = $args;
 243          }
 244  
 245          /**
 246           * Determine if a database supports a particular feature.
 247           *
 248           * Overridden here to work around differences between bbPress's
 249           * and WordPress's implementations. In particular, when
 250           * BuddyPress tries to run bbPress' SQL installation script,
 251           * the collation check always failed. The capability is long
 252           * supported by WordPress' minimum required MySQL version, so
 253           * this is safe.
 254           *
 255           * @since 1.1.0
 256           *
 257           * @see WPDB::has_cap() for a description of parameters and
 258           *      return values.
 259           *
 260           * @param string $db_cap See {@link WPDB::has_cap()}.
 261           * @param string $_table_name See {@link WPDB::has_cap()}.
 262           * @return bool See {@link WPDB::has_cap()}.
 263           */
 264  		function has_cap( $db_cap, $_table_name='' ) {
 265              if ( 'collation' == $db_cap )
 266                  return true;
 267  
 268              return parent::has_cap( $db_cap );
 269          }
 270  
 271          /**
 272           * Initialize the class variables based on provided arguments.
 273           *
 274           * Based on, and taken from, the BackPress class in turn taken
 275           * from the 1.0 branch of bbPress.
 276           *
 277           * @see BBDB::__construct() for a description of params.
 278           *
 279           * @param array $args Array of args to parse.
 280           * @return array $args.
 281           */
 282  		function init( $args ) {
 283              if ( 4 == func_num_args() ) {
 284                  $args = array(
 285                      'user'     => $args,
 286                      'password' => func_get_arg( 1 ),
 287                      'name'     => func_get_arg( 2 ),
 288                      'host'     => func_get_arg( 3 ),
 289                      'charset'  => defined( 'BBDB_CHARSET' ) ? BBDB_CHARSET : false,
 290                      'collate'  => defined( 'BBDB_COLLATE' ) ? BBDB_COLLATE : false,
 291                  );
 292              }
 293  
 294              $defaults = array(
 295                      'user'     => false,
 296                      'password' => false,
 297                      'name'     => false,
 298                      'host'     => 'localhost',
 299                      'charset'  => false,
 300                      'collate'  => false,
 301                      'errors'   => false
 302                      );
 303  
 304              return wp_parse_args( $args, $defaults );
 305          }
 306  
 307          /**
 308           * Stub for escape_deep() compatibility.
 309           *
 310           * @since 1.1.0
 311           *
 312           * @param mixed $data See {@link WPDB::escape_deep()}.
 313           * @return mixed $data See {@link WPDB::escape_deep()}.
 314           */
 315  		function escape_deep( $data ) {
 316              return esc_sql( $data );
 317          }
 318      }
 319  endif; // End class_exists( 'BPDB' ).
 320  
 321  /**
 322   * Convert object to given output format.
 323   *
 324   * The bbPress plugin needs this to convert vars.
 325   *
 326   * @since 1.1.0
 327   *
 328   * @param object $object Object to convert.
 329   * @param string $output Type of object to return. OBJECT, ARRAY_A, or ARRAY_N.
 330   */
 331  function backpress_convert_object( &$object, $output ) {
 332      if ( is_array( $object ) ) {
 333          foreach ( array_keys( $object ) as $key )
 334              backpress_convert_object( $object[$key], $output );
 335      } else {
 336          switch ( $output ) {
 337              case OBJECT  : break;
 338              case ARRAY_A : $object = get_object_vars($object); break;
 339              case ARRAY_N : $object = array_values(get_object_vars($object)); break;
 340          }
 341      }
 342  }
 343  
 344  /**
 345   * Parse and execute queries for updating a set of database tables.
 346   *
 347   * Copied from wp-admin/includes/upgrade.php, this will take care of creating
 348   * the bbPress stand-alone tables without loading a conflicting WP Admin.
 349   *
 350   * @since 1.5.0
 351   *
 352   * @see dbDelta() for a description of parameters and return value.
 353   *
 354   * @param array $queries See {@link dbDelta()}.
 355   * @param bool  $execute See {@link dbDelta()}.
 356   * @return array See {@link dbDelta()}.
 357   */
 358  function bp_bb_dbDelta($queries, $execute = true) {
 359      global $wpdb;
 360  
 361      // Separate individual queries into an array.
 362      if ( !is_array($queries) ) {
 363          $queries = explode( ';', $queries );
 364          if ('' == $queries[count($queries) - 1]) array_pop($queries);
 365      }
 366  
 367      $cqueries = array(); // Creation Queries.
 368      $iqueries = array(); // Insertion Queries.
 369      $for_update = array();
 370  
 371      // Create a tablename index for an array ($cqueries) of queries.
 372      foreach($queries as $qry) {
 373          if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
 374              $cqueries[trim( strtolower($matches[1]), '`' )] = $qry;
 375              $for_update[$matches[1]] = 'Created table '.$matches[1];
 376          } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
 377              array_unshift($cqueries, $qry);
 378          } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
 379              $iqueries[] = $qry;
 380          } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
 381              $iqueries[] = $qry;
 382          } else {
 383              // Unrecognized query type.
 384          }
 385      }
 386  
 387      // Check to see which tables and fields exist.
 388      if ($tables = $wpdb->get_col('SHOW TABLES;')) {
 389          // For every table in the database.
 390          foreach ($tables as $table) {
 391              // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
 392              if ( in_array($table, $wpdb->tables('global')) && ( !is_main_site() || defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) )
 393                  continue;
 394  
 395              // If a table query exists for the database table...
 396              if ( array_key_exists(strtolower($table), $cqueries) ) {
 397                  // Clear the field and index arrays.
 398                  $cfields = $indices = array();
 399                  // Get all of the field names in the query from between the parents.
 400                  preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
 401                  $qryline = trim($match2[1]);
 402  
 403                  // Separate field lines into an array.
 404                  $flds = explode("\n", $qryline);
 405  
 406                  //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
 407  
 408                  // For every field line specified in the query.
 409                  foreach ($flds as $fld) {
 410                      // Extract the field name.
 411                      preg_match("|^([^ ]*)|", trim($fld), $fvals);
 412                      $fieldname = trim( $fvals[1], '`' );
 413  
 414                      // Verify the found field name.
 415                      $validfield = true;
 416                      switch (strtolower($fieldname)) {
 417                      case '':
 418                      case 'primary':
 419                      case 'index':
 420                      case 'fulltext':
 421                      case 'unique':
 422                      case 'key':
 423                          $validfield = false;
 424                          $indices[] = trim(trim($fld), ", \n");
 425                          break;
 426                      }
 427                      $fld = trim($fld);
 428  
 429                      // If it's a valid field, add it to the field array.
 430                      if ($validfield) {
 431                          $cfields[strtolower($fieldname)] = trim($fld, ", \n");
 432                      }
 433                  }
 434  
 435                  // Fetch the table column structure from the database.
 436                  $tablefields = $wpdb->get_results("DESCRIBE {$table};");
 437  
 438                  // For every field in the table.
 439                  foreach ($tablefields as $tablefield) {
 440                      // If the table field exists in the field array...
 441                      if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
 442                          // Get the field type from the query.
 443                          preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
 444                          $fieldtype = $matches[1];
 445  
 446                          // Is actual field type different from the field type in query?
 447                          if ($tablefield->Type != $fieldtype) {
 448                              // Add a query to change the column type.
 449                              $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
 450                              $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
 451                          }
 452  
 453                          // Get the default value from the array.
 454                              //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
 455                          if (preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
 456                              $default_value = $matches[1];
 457                              if ($tablefield->Default != $default_value) {
 458                                  // Add a query to change the column's default value.
 459                                  $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
 460                                  $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
 461                              }
 462                          }
 463  
 464                          // Remove the field from the array (so it's not added).
 465                          unset($cfields[strtolower($tablefield->Field)]);
 466                      } else {
 467                          // This field exists in the table, but not in the creation queries?
 468                      }
 469                  }
 470  
 471                  // For every remaining field specified for the table.
 472                  foreach ($cfields as $fieldname => $fielddef) {
 473                      // Push a query line into $cqueries that adds the field to that table.
 474                      $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
 475                      $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
 476                  }
 477  
 478                  // Index stuff goes here
 479                  // Fetch the table index structure from the database.
 480                  $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
 481  
 482                  if ($tableindices) {
 483                      // Clear the index array.
 484                      unset($index_ary);
 485  
 486                      // For every index in the table.
 487                      foreach ($tableindices as $tableindex) {
 488                          // Add the index to the index data array.
 489                          $keyname = $tableindex->Key_name;
 490                          $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
 491                          $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
 492                      }
 493  
 494                      // For each actual index in the index array.
 495                      foreach ($index_ary as $index_name => $index_data) {
 496                          // Build a create string to compare to the query.
 497                          $index_string = '';
 498                          if ($index_name == 'PRIMARY') {
 499                              $index_string .= 'PRIMARY ';
 500                          } else if($index_data['unique']) {
 501                              $index_string .= 'UNIQUE ';
 502                          }
 503                          $index_string .= 'KEY ';
 504                          if ($index_name != 'PRIMARY') {
 505                              $index_string .= $index_name;
 506                          }
 507                          $index_columns = '';
 508                          // For each column in the index.
 509                          foreach ($index_data['columns'] as $column_data) {
 510                              if ($index_columns != '') $index_columns .= ',';
 511                              // Add the field to the column list string.
 512                              $index_columns .= $column_data['fieldname'];
 513                              if ($column_data['subpart'] != '') {
 514                                  $index_columns .= '('.$column_data['subpart'].')';
 515                              }
 516                          }
 517                          // Add the column list to the index create string.
 518                          $index_string .= ' ('.$index_columns.')';
 519                          if (!(($aindex = array_search($index_string, $indices)) === false)) {
 520                              unset($indices[$aindex]);
 521                              //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
 522                          }
 523                          //else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br /><b>Did not find index:</b>".$index_string."<br />".print_r($indices, true)."</pre>\n";
 524                      }
 525                  }
 526  
 527                  // For every remaining index specified for the table.
 528                  foreach ( (array) $indices as $index ) {
 529                      // Push a query line into $cqueries that adds the index to that table.
 530                      $cqueries[] = "ALTER TABLE {$table} ADD $index";
 531                      $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
 532                  }
 533  
 534                  // Remove the original table creation query from processing.
 535                  unset($cqueries[strtolower($table)]);
 536                  unset($for_update[strtolower($table)]);
 537              } else {
 538                  // This table exists in the database, but not in the creation queries?
 539              }
 540          }
 541      }
 542  
 543      $allqueries = array_merge($cqueries, $iqueries);
 544      if ($execute) {
 545          foreach ($allqueries as $query) {
 546              //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
 547              $wpdb->query($query);
 548          }
 549      }
 550  
 551      return $for_update;
 552  }


Generated: Thu Dec 7 01:01:35 2017 Cross-referenced by PHPXref 0.7.1