provision.inc 11.2 KB
Newer Older
1
<?php
2
// $Id$
3

4 5 6 7 8 9 10 11 12
/**
 * @file
 * The provisioning framework API.
 *
 * API functions that are used by the provisioning framework to provide structure to the provisioning modules.
 *
 * @see errorhandling
 * @see logging
 * @see sitedata
13
 * @see provisionvalues
14 15
 */

16 17
drush_errors_on();

18 19 20 21 22 23 24 25 26 27
/**
 * @defgroup sitedata Site data management utility functions.
 * @{
 * The provision framework maintains a site.php file in the sites directory, to maintain additional
 * information from the front end, as well as providing a change history of setting changes. 
 *
 * 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.
 */

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
/**
 * Make a determination whether or not the given
 * host is local or not.
 *
 * 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'.
 * @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'.
46 47 48 49 50 51 52
  return ($host == 'localhost') || 
    ($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());
53 54 55 56 57 58 59 60 61 62 63 64
}

/**
 * return the FQDN of the machine or provided host
 *
 * this replicates hostname -f, which is not portable
 */
function provision_fqdn($host = null) {
  if (is_null($host)) {
    $host = php_uname('n');
  }
  return strtolower(gethostbyaddr(gethostbyname($host)));
65
}
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
/**
 * 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;

  $http_port = d()->web_server->http_port;
  if (!is_null($http_port) && ($http_port != 80)) {
    $base_url .= ':' . $http_port;
  }
  return $base_url;
}

82
/**
83
 * Save modified options to the drushrc.php file
84
 */
85
function provision_save_server_data() {
86
  if (!drush_get_error()) {
87
    $config = new provisionConfig_drushrc_server(d()->name);
88
    $config->write();
89
  }
90 91
}

92 93 94 95 96

function provision_save_site_data() {
  if (!drush_get_error()) {
    $config = new provisionConfig_drushrc_site(d()->name);
    $config->write();
97
    provision_drupal_sync_site();
98 99 100 101 102 103 104 105 106 107 108
  }
}


/**
 * Save modified options to the drushrc.php file
 */
function provision_save_platform_data() {
  if (!drush_get_error()) {
    $config = new provisionConfig_drushrc_platform(d()->name);
    $config->write();
109
    provision_drupal_sync_site();
110 111 112 113
  }
}


114 115 116 117
/**
 * @} End of "defgroup sitedata".
 */

118 119 120 121
/**
 * Remove files or directories, recursively
 *
 * This was taken from imagecache.module, with slight modifications:
122
 * - carry error codes along the way (returns TRUE only if all operations return TRUE)
123 124 125 126
 * - remove any type of files encountered (not just links, files and dirs)
 * - safety checking since we don't necessarly trust the removed files
 */
function _provision_recursive_delete($path) {
127
  $ret = 1;
128 129
  if (is_dir($path)) {
    $d = dir($path);
130
    while (($entry = $d->read()) !== FALSE) {
131 132
      if ($entry == '.' || $entry == '..') continue;
      $entry_path = $path .'/'. $entry;
133
      if (_provision_file_check_location($entry_path, $path)) {
134
        $ret = _provision_recursive_delete($entry_path);
135 136
      } 
      else {
137 138 139 140
        $ret = 0;
      }
    }

141
    $rm = provision_file()->rmdir($path)
142 143 144
      ->succeed('Deleting @path directory successful.')
      ->fail('Deleting @path directory failed.')
      ->status();
145 146 147 148

    $ret = $ret && $rm;
  }
  else {
149
    $rm = provision_file()->unlink($path)
150 151
      ->fail('Deleting @path file failed.')
      ->status();
152
    $ret = $ret && $rm;
153 154 155 156
  }
  return $ret;
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
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;
}

173

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
/**
 * 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());
}

191
/**
192
 * Check whether a user is a member of a group.
193
 *
194 195 196 197 198 199 200
 * @param user
 *   username or user id of user.
 * @param group
 *   groupname or group id of group.
 *
 * @return
 *   Boolean. True if user does belong to group, 
201
 *   and FALSE if the user does not belong to the group, or either the user or group do not exist.
202
 */
203 204 205 206 207 208 209 210
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;
211 212
    }
  }
213
  return FALSE;
214 215 216 217 218 219
}

/**
 * Return the valid system username for $user.
 *
 * @return
220
 *   Returns the username if found, otherwise returns FALSE
221 222 223
 */
function provision_posix_username($user) {
  // TODO: make these singletons with static variables for caching.
224
  // we do this both ways, so that the function returns NULL if no such user was found.
225 226 227 228
  if (is_numeric($user)) {
    $info = posix_getpwuid($user);
    $user = $info['name'];
  }
229
  else {
230 231 232 233 234 235 236 237 238 239
    $info = posix_getpwnam($user);
    $user = $info['name'];
  }
  return $user;
}

/**
 * Return the valid system groupname for $group.
 *
 * @return
240
 *   Returns the groupname if found, otherwise returns FALSE
241 242 243
 */
function provision_posix_groupname($group) {
  // TODO: make these singletons with static variables for caching.
244
  // we do this both ways, so that the function returns NULL if no such user was found.
245
  if (is_numeric($group)) {
246 247 248 249 250 251
    $info = posix_getgrgid($group);
    $group = $info['name'];
  }
  else {
    $info = posix_getgrnam($group);
    $group = $info['name'];
252
  }
253
  return $group;
254
}
255

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
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;
}
279

280 281 282 283 284 285 286 287 288 289 290 291 292
/**
 * 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);
}
293 294 295 296 297 298 299

/**
 * Execute a command against a specific context object.
 */
function provision_backend_invoke($target, $command, $arguments = array(), $options = array(), $mode = 'GET') {
  return drush_backend_invoke_args('@' . ltrim($target, '@') . ' ' . $command, $arguments, $options + array('root' => null, 'uri' => null), $mode);
}
300 301 302


/**
drumm's avatar
drumm committed
303 304
 * A base class for the service and file handling classes that implements
 * chaining of methods.
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
 */
class provisionChainedState {
  protected $last_status;
  protected $tokens;

  /**
   * Clear internal state
   */
  protected function _clear_state() {
    $this->last_status = NULL;
    $this->tokens = NULL;
  }

  /**
   * Return the status of the last operation.
   *
   * @return
   *   TRUE or FALSE for success or failure; NULL if there was not a previous
   *   operation.
   */
  function status() {
    return $this->last_status;
  }

  /**
   * Log a notice into the logging system, if the last operation completed
   * succesfully.
   * 
   * @param $message
   *   The message to log, a string.
   */
  function succeed($message) {
    if ($this->last_status === TRUE) {
      drush_log(dt($message, $this->tokens), 'message');      
    }

    return $this;
  }

  /**
   * Log a notice into the logging system, if the last operation did not
   * complete succesfully.
   * 
   * @param $message
   *   Log this as a error to the logging system, if the $error_codes parameter
   *   has been set, otherwise, log this as a warning. If the operation
   *   specifies an additional reason for the operation failing, it will be
   *   appended to this message.
   *
   * @param error_codes
   *   Generate these system level errors using the provision error bitmasks.
   */
  function fail($message, $error_codes = NULL) {
    if (!empty($this->tokens['@reason'])) {
      $message .= ' (@reason)';
    }
    if ($this->last_status === FALSE) {
      if (is_null($error_codes)) {
        // Trigger a warning
        drush_log(dt($message, $this->tokens), 'warning');
      }
      else {
        // Trigger a sysem halting error
        drush_set_error($error_codes, dt($message, $this->tokens));
      }
    }

    return $this;
  }
}

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
// 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 {

}

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
/**
 * Provision class.
 *
 * This is just a container for some useful static methods.
 */
class provision {
  /**
   * The actual body of the method_invoke function.
   * 
   * 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);
    }
  }
}


413

414 415 416 417
include_once('provision.context.inc');
include_once('provision.context.server.inc');
include_once('provision.context.platform.inc');
include_once('provision.context.site.inc');
418 419 420 421 422
include_once('provision.service.inc');
include_once('provision.file.inc');
include_once('provision.config.inc');