civicrm.config.php.wordpress 13.4 KB
Newer Older
1 2 3
<?php

// WORD PRESS VARIANT of civicrm.config.php
4
// COPY OF Bootstrap.php from https://github.com/civicrm/cv
5

6
namespace Civi\Cv;
7
/**
8
 * Bootstrap the CiviCRM runtime.
9
 *
10 11 12 13
 * @code
 * // Use default bootstrap
 * require_once '/path/to/Civi/Bootstrap.php';
 * Civi\Bootstrap::singleton()->boot();
14
 *
15 16 17 18 19 20
 * // Use custom bootstrap
 * require_once '/path/to/Civi/Bootstrap.php';
 * Civi\Bootstrap::singleton()->boot(array(
 *   'settingsFile' => '/path/to/civicrm.settings.php',
 * ));
 * @endcode
21
 *
22 23
 * This class is intended to be run *before* the classloader is available. Therefore, it
 * must be self-sufficient.
24
 *
25 26 27
 * A key issue is locating the civicrm.settings.php file -- this is complicated because
 * each CMS has a different structure, because some CMS's have multisite features, and
 * because we don't know who's calling us.
28
 *
29 30 31 32 33 34 35
 * By default, bootstrap will search as follows:
 *   - Check ../settings_location.php for define(CIVICRM_CONFDIR)
 *   - Check ENV['CIVICRM_SETTINGS']
 *   - Check $options['settingsFile']
 *   - Scan PWD and every ancestor directory to see if it
 *     contains civicrm.settings.php in one of the
 *     standard subdirectories.
36
 *
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
 * Recommendations:
 *   - Administrators with an unusual directory structure should either:
 *     - Set env var CIVICRM_SETTINGS in their httpd vhost and bashrc, or
 *     - Create settings_location.php
 *   - Primary CMS-integration modules should preemptively configure the
 *     defaults so that other code may bootstrap without specifying options.
 *       require_once $cividir/Civi/Bootstrap.php
 *       Civi\Bootstrap::singleton()->setOptions(
 *         'settingsFile' => ...,
 *         'search' => FALSE,
 *       ));
 *   - External scripts should call:
 *       require_once $cividir/Civi/Bootstrap.php;
 *       Civi\Bootstrap::singleton()->boot();
 *   - Administrators who are concerned about bootstrap time for external
 *     scripts should use CIVICRM_SETTINGS or settings_location.php.
 *   - Pre-installation programs (code-generators, installers, etc) should not
 *     use Civi\Bootstrap. Instead, they should use CRM_Core_ClassLoader.
55
 *
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
 * The bootstrapper accepts a few options (either via setOptions() or boot()). They are:
 *   - dynamicSettingsFile: string|NULL. The location of a PHP file which dynamically
 *     determines the location of civicrm.settings.php. This is provided for backward
 *     compatibility.
 *     (Default: $civiRoot/settings_location.php)
 *   - cmsType: string|NULL. Give a hint to the search algorithm about which
 *     type of CMS is being used.
 *     (Default: NULL)
 *   - env: string|NULL. The environment variable which may contain the path to
 *     civicrm.settings.php. Set NULL to disable.
 *     (Default: CIVICRM_SETTINGS)
 *   - prefetch: bool. Whether to load various caches.
 *     (Default: TRUE)
 *   - settingsFile: string|NULL. The full path to the civicrm.settings.php
 *     (Default: NULL)
 *   - search: bool|string. Attempt to determine root+settings by searching
 *     the file system and checking against common Civi directory structures.
 *     Boolean TRUE means it should use a default (PWD).
 *     (Default: TRUE aka PWD)
 *
 * TODO: Consider adding flags for CMS bootstrap.
 *
 * @package Civi
79
 */
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
class Bootstrap {

  protected static $singleton = NULL;

  protected $options = array();

  /**
   * @return Bootstrap
   */
  public static function singleton() {
    if (self::$singleton === NULL) {
      self::$singleton = new Bootstrap(array(
        'dynamicSettingsFile' => dirname(__DIR__) . '/settings_location.php',
        'env' => 'CIVICRM_SETTINGS',
        'prefetch' => TRUE,
        'settingsFile' => NULL,
        'search' => TRUE,
        'cmsType' => NULL,
        'httpHost' => array_key_exists('HTTP_HOST', $_SERVER) ? $_SERVER['HTTP_HOST'] : '',
      ));
    }
    return self::$singleton;
  }

  /**
   * @param array $options
   *   See options in class doc.
   */
  public function __construct($options = array()) {
    $this->options = $options;
  }

  /**
   * Bootstrap the CiviCRM runtime.
   *
   * @param array $options
   *   See options in class doc.
   * @throws \Exception
   */
  public function boot($options = array()) {
    if (!defined('CIVICRM_SETTINGS_PATH')) {
      $this->options = $options = array_merge($this->options, $options);

      $settings = $this->getCivicrmSettingsPhp($options);
      if (empty($settings) || !file_exists($settings)) {
        throw new \Exception("Failed to locate civicrm.settings.php. Please boot with settingsFile, search, or CIVICRM_SETTINGS; or normalize your directory structure.");
      }

//      $reader = new SiteConfigReader($settings);
//      $GLOBALS['_CV'] = $reader->compile(array('buildkit', 'home'));

      define('CIVICRM_SETTINGS_PATH', $settings);
      $error = @include_once $settings;
      if ($error == FALSE) {
        throw new \Exception("Could not load the CiviCRM settings file: {$settings}");
      }

      list ($cmsType, $cmsBasePath) = $this->findCmsRoot($this->getSearchDir());
138 139 140 141 142 143 144 145
      if (PHP_SAPI === 'cli') {
        $_SERVER['SCRIPT_FILENAME'] = $cmsBasePath . '/index.php';
        $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
        $_SERVER['SERVER_SOFTWARE'] = NULL;
        $_SERVER['REQUEST_METHOD'] = 'GET';
        if (ord($_SERVER['SCRIPT_NAME']) != 47) {
          $_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
        }
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
      }
    }

    // Backward compatibility - New civicrm.settings.php files include
    // the classloader, but old ones don't.
    global $civicrm_root;
    require_once $civicrm_root . '/CRM/Core/ClassLoader.php';
    \CRM_Core_ClassLoader::singleton()->register();

    if (!empty($options['prefetch'])) {
      // I'm not sure why this is called explicitly during bootstrap
      // rather than lazily. However, it seems to be done by all
      // the existing bootstrap code. Perhaps initializing Config
      // has a side-effect of initializing other things?
      \CRM_Core_Config::singleton();
    }
  }

  /**
   * Generate bootstrap logic.
   *
   * NOTE: Assumes boot() has already run.
   *
   * @return string
   *   PHP code.
   */
  public function generate() {
    $code = array();

    $code[] = 'if (PHP_SAPI === "cli") {';
    $srvVars = array(
      'SCRIPT_FILENAME',
      'REMOTE_ADDR',
      'SERVER_SOFTWARE',
      'REQUEST_METHOD',
      'SCRIPT_NAME'
    );
    foreach ($srvVars as $srvVar) {
      $code [] = sprintf('$_SERVER["%s"] = %s;',
        $srvVar, var_export($_SERVER[$srvVar], 1));
    }
    foreach (array('CIVICRM_UF') as $envVar) {
      if (getenv($envVar)) {
        $code[] = sprintf('putenv("%s=" . %s);', $envVar, var_export(getenv($envVar), 1));
        $code[] = sprintf('$_ENV["%s"] = %s;', $envVar, var_export(getenv($envVar), 1));
      }
    }
    $code [] = '}';
194

195
    $code [] = sprintf('$GLOBALS[\'_CV\'] = %s;', var_export($GLOBALS['_CV'], 1));
196

197 198 199 200 201
    $code [] = sprintf('define("CIVICRM_SETTINGS_PATH", %s);', var_export(CIVICRM_SETTINGS_PATH, 1));
    $code [] = '$error = @include_once CIVICRM_SETTINGS_PATH;';
    $code [] = 'if ($error == FALSE) {';
    $code [] = '  throw new \Exception("Could not load the CiviCRM settings file: {$settings}");';
    $code [] = '}';
202

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    $code [] = 'require_once $GLOBALS["civicrm_root"] . "/CRM/Core/ClassLoader.php";';
    $code [] = '\CRM_Core_ClassLoader::singleton()->register();';

    return implode("\n", $code);
  }

  /**
   * @return array
   *   See options in class doc.
   */
  public function getOptions() {
    return $this->options;
  }

  /**
   * @param array $options
   *   See options in class doc.
   */
  public function setOptions($options) {
    $this->options = $options;
  }

  /**
   * @param array $options
   * @return string
   * @throws \Exception
   */
  public function getCivicrmSettingsPhp($options) {
    if (!empty($options['dynamicSettingsFile']) && file_exists($options['dynamicSettingsFile'])) {
      include $options['dynamicSettingsFile'];
233 234 235
    }

    /**
236 237
     * @var string
     *   Path to the settings file.
238
     */
239 240 241 242
    $settings = NULL;

    if (defined('CIVICRM_CONFDIR') && file_exists(CIVICRM_CONFDIR . '/civicrm.settings.php')) {
      $settings = CIVICRM_CONFDIR . '/civicrm.settings.php';
243
    }
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    elseif (!empty($options['env']) && getenv($options['env']) && file_exists(getenv($options['env']))) {
      $settings = getenv($options['env']);
    }
    elseif (!empty($options['settingsFile']) && file_exists($options['settingsFile'])) {
      $settings = $options['settingsFile'];
    }
    elseif (!empty($options['search'])) {
      list (, , $settings) = $this->findCivicrmSettingsPhp($this->getSearchDir());
    }

    return $settings;
  }

  /**
   * Locate a civicrm.settings.php using normal directory structures.
   *
   * @param string $searchDir
   *   The directory from which to begin the upward search.
   * @return array
   *   Array(string $cmsType, string $cmsRoot, string $settingsFile).
   */
  protected function findCivicrmSettingsPhp($searchDir) {
    list ($cmsType, $cmsRoot) = $this->findCmsRoot($searchDir);

    $settings = NULL;
    switch ($cmsType) {
270 271 272 273 274 275 276
      case 'backdrop':
        $settings = $this->findFirstFile(
           array_merge($this->findDrupalDirs($cmsRoot), array($cmsRoot)),
          'civicrm.settings.php'
        );
        break;

277 278 279
      case 'drupal':
        $settings = $this->findFirstFile($this->findDrupalDirs($cmsRoot), 'civicrm.settings.php');
        break;
280

281 282 283 284 285 286 287 288 289 290 291 292 293 294
      case 'joomla':
        // Note: Joomla technically has two copies of civicrm.settings.php with
        // slightly different values of CIVICRM_UF_BASEURL. It appears that Joomla
        // always used the admin copy for CLI/bin/extern scripts, so we do the
        // same. However, the arrangement seems gratuitous considering that WP
        // has the same frontend/backend split and does not need two copies of
        // civicrm.settings.php.

        $settings = $cmsRoot . 'administrator/components/com_civicrm/civicrm.settings.php';
        // $result =  $cmsRoot . 'components/com_civicrm/civicrm.settings.php';
        break;

      case 'wp':
        $wpDirs = array(
295 296
          $cmsRoot . '/*/uploads/civicrm',
          $cmsRoot . '/*/plugins/civicrm',
297 298
          $cmsRoot . '/*/uploads/sites/*/civicrm',
          $cmsRoot . '/*/blogs.dir/*/files/civicrm',
299 300 301
        );
        $settings = $this->findFirstFile($wpDirs, 'civicrm.settings.php');
        break;
302
    }
303 304
    return array($cmsType, $cmsRoot, $settings);
  }
305

306 307 308 309 310
  /**
   * Get an ordered list of multisite dirs that might apply to this request.
   *
   * @param string $cmsRoot
   *   The root of the Drupal installation.
311
   * @return array
312 313 314 315 316 317
   */
  protected function findDrupalDirs($cmsRoot) {
    $dirs = array();
    $server = explode('.', implode('.', array_reverse(explode(':', rtrim($this->options['httpHost'], '.')))));
    for ($j = count($server); $j > 0; $j--) {
      $dirs[] = "$cmsRoot/sites/" . implode('.', array_slice($server, -$j));
318
    }
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    $dirs[] = "$cmsRoot/sites/default";
    return $dirs;
  }

  /**
   * @param string $searchDir
   *   The directory from which to begin the upward search.
   * @return array
   *   Array(string $cmsType, string $cmsRoot, string $civiRoot)
   */
  protected function findCmsRoot($searchDir) {
    // A list of file patterns; if one of the patterns matches a give
    // directory, then we can assume that this directory is the
    // CMS root.
    $cmsPatterns = array(
      'wp' => array(
335
        'wp-includes/version.php',
336 337 338 339 340 341 342
        // Future? 'vendor/civicrm/wordpress/civicrm.php' => 'wp',
      ),
      'joomla' => array(
        'administrator/components/com_civicrm/civicrm/civicrm-version.php',
        // Future? 'vendor/civicrm/joomla/civicrm.php' => 'joomla',
      ),
      'drupal' => array(
343 344 345 346 347
        'modules/system/system.module', // D7
        'core/core.services.yml', // D8
      ),
      'backdrop' => array(
        'core/modules/layout/layout.module',
348 349
      ),
    );
350

351 352 353
    $parts = explode('/', str_replace('\\', '/', $searchDir));
    while (!empty($parts)) {
      $basePath = implode('/', $parts);
354

355 356 357
      foreach ($cmsPatterns as $cmsType => $relPaths) {
        if (!empty($this->options['cmsType']) && $this->options['cmsType'] != $cmsType) {
          continue;
358
        }
359 360 361 362 363 364 365 366 367
        foreach ($relPaths as $relPath) {
          $matches = glob("$basePath/$relPath");
          if (!empty($matches)) {
            return array($cmsType, $basePath);
          }
        }
      }

      array_pop($parts);
368 369
    }

370 371
    return array(NULL, NULL);
  }
372

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
  /**
   * @param string|array $dirs
   *   List of directories to check.
   * @param string|array $items
   *   List of globs to check in each directory.
   * @return null|string
   */
  protected function findFirstFile($dirs, $items) {
    $dirs = (array) $dirs;
    $items = (array) $items;
    foreach ($dirs as $dir) {
      foreach ($items as $item) {
        $matches = (array) glob("$dir/$item");
        if (isset($matches[0])) {
          return $matches[0];
        }
      }
    }
    return NULL;
  }

  /**
   * @return string
   */
  protected function getSearchDir() {
    if ($this->options['search'] === TRUE) {
399 400 401 402 403 404
      if ($_SERVER['SCRIPT_FILENAME']) {
        return dirname($_SERVER['SCRIPT_FILENAME']);
      }
      // getenv('PWD') works better with symlinked source trees, but it's
      // not portable to Windows.
      elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
405 406 407
        return getcwd();
      }
      else {
408
        return getenv('PWD');
409 410 411 412 413 414
      }
    }
    else {
      return $this->options['search'];
    }
  }
415

416 417
}

418
\Civi\Cv\Bootstrap::singleton()->boot();