provision.inc 14.3 KB
Newer Older
1 2 3 4 5
<?php
/**
 * @file
 * The provisioning framework API.
 *
6 7
 * API functions that are used by the provisioning framework to provide
 * structure to the provisioning modules.
8 9
 */

10 11
drush_errors_on();

12 13 14 15 16 17 18 19 20
/**
 * Return an instance of the provision autoloader.
 *
 * This will instiatate an instance if it needs to.
 */
function provision_autoload() {
  static $instance = NULL;

  if (is_null($instance)) {
helmo's avatar
helmo committed
21
    require_once dirname(__FILE__) . '/Symfony/Component/ClassLoader/UniversalClassLoader.php';
22
    $instance = new UniversalClassLoader();
23 24 25 26 27 28 29 30 31 32
    // Activate the autoloader.
    $instance->register();
  }

  return $instance;
}

/**
 * Register a PECL style prefix with the provision autoloader.
 *
helmo's avatar
helmo committed
33
 * @param string $prefix
34
 *   The class prefix to register.
helmo's avatar
helmo committed
35
 * @param string $dir
36
 *   The directory to search for the classes in.
helmo's avatar
helmo committed
37
 * @param bool $prepend
38 39
 *   If the directory should be searched first for the classes in the given
 *   prefix, set this to TRUE, otherwise, the default, FALSE, is fine.
40
 */
41
function provision_autoload_register_prefix($prefix, $dir, $prepend = FALSE) {
42

43 44 45 46 47 48 49 50
  // Get any current directories set for this prefix.
  $current_prefixes = provision_autoload()->getPrefixes();
  if (isset($current_prefixes[$prefix])) {
    $dirs = $current_prefixes[$prefix];
  }
  else {
    $dirs = array();
  }
51

52 53 54 55 56 57 58
  // Now add the new one.
  if ($prepend) {
    array_unshift($dirs, $dir);
  }
  else {
    array_push($dirs, $dir);
  }
59

60 61
  // Set the prefixes.
  provision_autoload()->registerPrefix($prefix, $dirs);
62 63 64
}

// Add our prefix to the autoloader.
65
provision_autoload_register_prefix('Provision_', dirname(__FILE__));
66

67 68 69
/**
 * Return the directory containing the file a class is defined in.
 *
helmo's avatar
helmo committed
70
 * @param string $class_name
71
 *   The class name to search for.
helmo's avatar
helmo committed
72 73
 *
 * @return string
74 75 76 77 78 79 80 81 82
 *   A directory if the class can be found or an empty string if not.
 */
function provision_class_directory($class_name) {
  return dirname(provision_class_file($class_name));
}

/**
 * Return the file a class is defined in.
 *
helmo's avatar
helmo committed
83
 * @param string $class_name
84
 *   The class name to search for.
helmo's avatar
helmo committed
85 86
 *
 * @return string
87 88 89 90 91 92 93 94 95
 *   A file if the class can be found or an empty string if not.
 */
function provision_class_file($class_name) {
  if (class_exists($class_name)) {
    $reflect = new reflectionClass($class_name);
    return $reflect->getFilename();
  }
  return '';
}
96

97 98 99 100
/**
 * @defgroup sitedata Site data management utility functions.
 * @{
 * The provision framework maintains a site.php file in the sites directory, to maintain additional
101
 * information from the front end, as well as providing a change history of setting changes.
102 103 104 105 106
 *
 * These functions load, save and manage changes made to the site data. This data has diagnostic and infrastructure
 * values, that allow sites to be more easily moved between different provisioned platforms.
 */

107
/**
helmo's avatar
helmo committed
108
 * Make a determination whether or not the given host is local or not.
109 110 111 112 113
 *
 * We needed to fork this from drush core to handle the case sensitivity in host names.
 *
 * @param host
 *   A hostname, 'localhost' or '127.0.0.1'.
helmo's avatar
helmo committed
114
 *
115 116 117 118 119 120 121 122 123 124
 * @return
 *   True if the host is local.
 */
function provision_is_local_host($host) {
  $host = strtolower($host);
  // In order for this to work right, you must use 'localhost' or '127.0.0.1'
  // or the machine returned by 'uname -n' for your 'remote-host' entry in
  // your site alias.  Note that sometimes 'uname -n' does not return the
  // correct value.  To fix it, put the correct hostname in /etc/hostname
  // and then run 'hostname -F /etc/hostname'.
125
  return ($host == 'localhost') ||
126 127 128 129 130 131
    ($host == '127.0.0.1') ||
    (gethostbyname($host) == '127.0.0.1') ||
    (gethostbyname($host) == '127.0.1.1') || // common setting on
                                             // ubuntu and friends
    ($host == strtolower(php_uname('n'))) ||
    ($host == provision_fqdn());
132 133
}

134 135 136 137 138 139 140 141 142 143 144
/**
 * Determine if the currently acting context is the server's hostmaster site.
 *
 * @return
 *   Boolean TRUE if the current drush context is "@hostmaster".
 */
function provision_is_hostmaster_site() {
  // If the current root and URI matches "@hostmaster" root and URI, this is hostmaster.
  return d()->root == d('@hostmaster')->root && d()->uri == d('@hostmaster')->uri;
}

145 146 147 148 149
/**
 * return the FQDN of the machine or provided host
 *
 * this replicates hostname -f, which is not portable
 */
150
function provision_fqdn($host = NULL) {
151 152 153 154
  if (is_null($host)) {
    $host = php_uname('n');
  }
  return strtolower(gethostbyaddr(gethostbyname($host)));
155
}
156

157 158 159 160 161 162 163 164
/**
 * Retrieve a base_url for the currently active site.
 *
 * TODO: when we actually support HTTPS, do this correctly.
 */
function provision_get_base_url() {
  $base_url = 'http://' . d()->uri;

165
  $http_port = d()->server->http_port;
166 167 168 169 170 171
  if (!is_null($http_port) && ($http_port != 80)) {
    $base_url .= ':' . $http_port;
  }
  return $base_url;
}

172
/**
173
 * Save modified options to the drushrc.php file
174
 */
175
function provision_save_server_data() {
176
  if (!drush_get_error()) {
177
    $config = new Provision_Config_Drushrc_Server(d()->name);
178
    $config->write();
179
  }
180 181
}

182 183 184

function provision_save_site_data() {
  if (!drush_get_error()) {
185
    $config = new Provision_Config_Drushrc_Site(d()->name);
186
    $config->write();
187
    provision_drupal_push_site();
188 189 190 191 192 193 194 195 196
  }
}


/**
 * Save modified options to the drushrc.php file
 */
function provision_save_platform_data() {
  if (!drush_get_error()) {
197
    $config = new Provision_Config_Drushrc_Platform(d()->name);
198
    $config->write();
199
    provision_drupal_push_site();
200 201 202 203
  }
}


204 205 206 207
/**
 * @} End of "defgroup sitedata".
 */

208 209 210
/**
 * Remove files or directories, recursively
 *
211
 * This was taken from Drupal 7's file.inc, with slight modifications:
anarcat's avatar
anarcat committed
212 213 214
 *  * carry error codes along the way (returns TRUE only if all operations return TRUE)
 *  * remove any type of files encountered (not files and directories)
 *  * do not follow symlink directories
215 216
 *
 * @see file_unmanaged_delete_recursive()
217 218
 */
function _provision_recursive_delete($path) {
219
  $ret = 1;
220 221
  // is_dir() follows symlinks, so it can return true on a symlink
  if (is_dir($path) && !is_link($path)) {
222
    $d = dir($path);
223 224 225 226 227 228 229
    if (!empty($d)) {
      while (($entry = $d->read()) !== FALSE) {
        if ($entry == '.' || $entry == '..') {
          continue;
        }
        $entry_path = $path . '/' . $entry;
        $ret &= _provision_recursive_delete($entry_path);
230
      }
231
      $d->close();
232 233
    }

234
    $rm = provision_file()->rmdir($path)
235 236
      ->fail('Deleting @path directory failed.')
      ->status();
237 238 239 240

    $ret = $ret && $rm;
  }
  else {
241
    $rm = provision_file()->unlink($path)
242 243
      ->fail('Deleting @path file failed.')
      ->status();
244
    $ret = $ret && $rm;
245 246 247 248
  }
  return $ret;
}

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
/**
 * Convenience copy of Drupal 6's file_check_location()
 *
 * Check if a file is really located inside $directory. Should be used to make
 * sure a file specified is really located within the directory to prevent
 * exploits.
 *
 * @code
 *   // Returns FALSE:
 *   file_check_location('/www/example.com/files/../../../etc/passwd', '/www/example.com/files');
 * @endcode
 *
 * @param $source A string set to the file to check.
 * @param $directory A string where the file should be located.
 * @return 0 for invalid path or the real path of the source.
 *
 * @see file_check_location()
 */
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
function _provision_file_check_location($source, $directory = '') {
  $check = realpath($source);
  if ($check) {
    $source = $check;
  }
  else {
    // This file does not yet exist
    $source = realpath(dirname($source)) .'/'. basename($source);
  }
  $directory = realpath($directory);
  if ($directory && strpos($source, $directory) !== 0) {
    return 0;
  }
  return $source;
}

283

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
/**
 * Find the username of the current running procses
 *
 * This will return the username of the current running user (as seen
 * from posix_geteuid()) and should be used instead of
 * get_current_user() (which looks at the file owner instead).
 *
 * @see get_current_user()
 * @see posix_geteuid()
 *
 * @return
 *   String. The username.
 */
function provision_current_user() {
  return provision_posix_username(posix_geteuid());
}

301
/**
302
 * Check whether a user is a member of a group.
303
 *
304 305 306 307 308 309
 * @param user
 *   username or user id of user.
 * @param group
 *   groupname or group id of group.
 *
 * @return
310
 *   Boolean. True if user does belong to group,
311
 *   and FALSE if the user does not belong to the group, or either the user or group do not exist.
312
 */
313 314 315 316 317 318 319 320
function provision_user_in_group($user, $group) {
  // TODO: make these singletons with static variables for caching.
  $user = provision_posix_username($user);
  $group = provision_posix_groupname($group);
  if ($user && $group) {
    $info = posix_getgrnam($group);
    if (in_array($user, $info['members'])) {
      return TRUE;
321 322
    }
  }
323
  return FALSE;
324 325 326 327 328 329
}

/**
 * Return the valid system username for $user.
 *
 * @return
330
 *   Returns the username if found, otherwise returns FALSE
331 332 333
 */
function provision_posix_username($user) {
  // TODO: make these singletons with static variables for caching.
334
  // we do this both ways, so that the function returns NULL if no such user was found.
335 336 337 338
  if (is_numeric($user)) {
    $info = posix_getpwuid($user);
    $user = $info['name'];
  }
339
  else {
340 341 342 343 344 345 346 347 348 349
    $info = posix_getpwnam($user);
    $user = $info['name'];
  }
  return $user;
}

/**
 * Return the valid system groupname for $group.
 *
 * @return
350
 *   Returns the groupname if found, otherwise returns FALSE
351 352 353
 */
function provision_posix_groupname($group) {
  // TODO: make these singletons with static variables for caching.
354
  // we do this both ways, so that the function returns NULL if no such user was found.
355
  if (is_numeric($group)) {
356 357 358 359 360 361
    $info = posix_getgrgid($group);
    $group = $info['name'];
  }
  else {
    $info = posix_getgrnam($group);
    $group = $info['name'];
362
  }
363
  return $group;
364
}
365

anarcat's avatar
anarcat committed
366 367 368 369 370 371 372 373 374
/**
 * Generate a random alphanumeric password.
 *
 * This is a copy of Drupal core's user_password() function. We keep it
 * here in case we need this and don't have a bootstrapped Drupal
 * around.
 *
 * @see user_password()
 */
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
function provision_password($length = 10) {
  // This variable contains the list of allowable characters for the
  // password. Note that the number 0 and the letter 'O' have been
  // removed to avoid confusion between the two. The same is true
  // of 'I', 1, and 'l'.
  $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';

  // Zero-based count of characters in the allowable list:
  $len = strlen($allowable_characters) - 1;

  // Declare the password as a blank string.
  $pass = '';

  // Loop the number of times specified by $length.
  for ($i = 0; $i < $length; $i++) {

    // Each iteration, pick a random character from the
    // allowable string and append it to the password:
    $pass .= $allowable_characters[mt_rand(0, $len)];
  }

  return $pass;
}
398

399 400 401 402 403 404 405 406 407 408 409 410 411
/**
 * This is a helper function which changes deeply nested objects into arrays
 *
 * This helps get past the face that objects are not simple to work with, or
 * save in context files.
 *
 * This function 'misuses' a side effect of the json_decode function's second
 * parameter. As this is done in C, and the structures we are manipulating
 * aren't that large, it should be performant enough.
 */
function _scrub_object($input) {
  return json_decode(json_encode($input), TRUE);
}
412 413 414

/**
 * Execute a command against a specific context object.
415
 *
416 417 418 419 420 421 422 423 424 425
 * @param $target
 *   the context to operate on, @ prefix is optional.
 * @param $command
 *   drush command passed to drush_invoke_process().
 * @param $arguments
 *   drush arguments passed to drush_invoke_process().
 * @param $data
 *   drush data passed to drush_invoke_process().
 * @param $mode
 *   drush IPC mode (GET/POST) passed to drush_invoke_process().
426
 *
427
 * @see drush_invoke_process()
428
 */
429
function provision_backend_invoke($target, $command, $arguments = array(), $data = array(), $mode = 'GET') {
430
  $context = '@' . ltrim($target, '@');
431
  return drush_invoke_process($context, $command, $arguments, $data, array('method' => $mode, 'integrate' => TRUE, 'dispatch-using-alias' => TRUE));
432
}
Steven Jones's avatar
Steven Jones committed
433

434
/**
435 436 437 438 439 440 441 442
 * the aegir version of the backend
 *
 * @return string
 *  the aegir version as stored in the .info file, potentially
 *  including the 6.x- prefix. to get a cleaned up version, use
 *  provision_version_parts()
 *
 * @see provision_version_parts()
443 444 445 446 447
 */
function provision_version() {
  $ini = parse_ini_file(dirname(__FILE__) . '/provision.info');
  return $ini['version'];
}
448

449 450 451 452 453 454
/**
 * Aegir API implemented by this backend
 *
 * This is the major release number, the first part of the version
 * stored in the info file
 *
455
 * @return int
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
 *   a number greater than zero, 1 for 1.0 or 1.0-rc2, 2 for 2.0, etc.
 *
 * @see provision_version_parts()
 */
function provision_api_version() {
  $parts = provision_version_parts();
  return $parts[0];
}

/**
 * The different parts of the version number
 *
 * This cleans up the version number by removing the Drupal version
 * (6.x-...) and splits the remaining version on dots.
 *
471
 * @return array
472 473 474 475 476 477 478 479
 *   the major and minor version numbers, e.g. array(1, 0-rc3) for
 *   1.0-rc3 or array(1, 2) for 1.2
 */
function provision_version_parts() {
  $version = preg_replace('/^[^-]*-/', '', provision_version()); // remove "6.x-"
  return explode('.', $version);
}

480 481 482 483 484 485 486 487 488 489 490 491 492
/**
 * Normalise a context name, ensuring that it starts with one '@'.
 *
 * @param $name
 *   The context name to normalise.
 *
 * @return
 *   The normalised context name.
 */
function provision_normalise_context_name($name) {
  return '@' . ltrim($name, '@');
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
// Base class for provision exceptions.
class provisionException extends Exception {

}

/**
 * Signal for parent to continue processing.
 *
 * The primary use for this class is for the config
 * classes to be able to signal to it's caller, that
 * the configuration file was not needed, and to
 * continue on.
 */
class provisionException_continue extends provisionException {

}

510 511 512 513 514 515 516 517
/**
 * Provision class.
 *
 * This is just a container for some useful static methods.
 */
class provision {
  /**
   * The actual body of the method_invoke function.
518
   *
519 520 521 522 523 524 525 526 527 528
   * This is a static method so it can be re-used by some other classes
   * that aren't contexts. (notably services and configs).
   */
  static function method_invoke($object, $func, $args = array()) {
    if (method_exists($object, $func)) {
      return call_user_func_array(array($object, $func), $args);
    }
  }
}

529
include_once('provision.context.inc');
530 531
include_once('provision.service.inc');
include_once('provision.file.inc');