hosting_site.module 32.7 KB
Newer Older
1 2
<?php

3 4 5 6
define('HOSTING_SITE_DELETED', -2);
define('HOSTING_SITE_DISABLED', -1);
define('HOSTING_SITE_QUEUED', 0);
define('HOSTING_SITE_ENABLED', 1);
7

8 9 10
/**
 * Implementation of hook_node_info
 */
11 12 13 14 15 16 17 18
function hosting_site_node_info() {
  $types["site"] =  array(
    "type" => 'site', "name" => 'Site',
    "module" => 'hosting_site',
    "has_title" => TRUE, "title_label" => 'Domain name', 
    "description" => hosting_node_help("site"),
    "has_body" => 0, "body_label" => '', "min_word_count" => 0);
  return $types;
19
}
20

21 22

/**
mig5's avatar
mig5 committed
23
 * Implementation of hook_hosting_tasks
24
 */
25 26
function hosting_site_hosting_tasks() {
  $tasks = array();
27

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  $tasks['site']['backup'] = array(
    'title' => t('Backup'),
    'description' => t('Generate a backup of this site that can be restored to at any time'),
   );

  $tasks['site']['restore'] = array(
    'title' => t('Restore'),
    'description' => t('Restore this site to a previous backup. A new backup will be created before this is attempted.'),
  );

  $tasks['site']['verify'] = array(
    'title' => t('Verify'),
    'description' => t('Confirm that the site has been correctly installed and regenerate all configuration files to match the hosting front end.'),
  );

  $tasks['site']['disable'] = array(
    'title' =>  t('Disable'),
    'description' =>  t('Disabling this site will stop it from being accessible.
         It can be enabled again later.'),     
  );     
  $tasks['site']['enable'] = array(
    'title' => t('Enable'),
    'description' => t('Enabling this site will allow it to be accesible again.
         It may be disabled again if needed.'),
  );
  $tasks['site']['delete'] = array(
    'title' => t('Delete'),
    'description' => t('Deleting this site will completely remove it from the hosting system,
        but will keep the last backup available. This process can not be undone.
        Are you really sure you want to delete this site?'),
  );

Adrian Rossouw's avatar
Adrian Rossouw committed
60 61 62 63 64
  $tasks['site']['login_reset'] = array(
     'title' => t('Reset password'),
     'description' => t('Generate a one-time login reset url for this site.'),
  );

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

  $tasks['site']['install'] = array(
    'title' => t('Install'), 
    'description' => t('Install a site'), 
    'hidden' => TRUE 
  );

  $tasks['site']['import'] = array(
    'title' => t('Import'), 
    'description' => t('Import an existing site into Aegir'), 
    'hidden' => TRUE
  );


  return $tasks;
80 81
}

82

83 84 85
/**
 * Implementation of hook_perm
 */
86
function hosting_site_perm() {
87
  return array('create site', 'view site', 'edit site', 'delete site', 'administer site', 'change site port');
88 89
}

90 91 92
/**
 * Implementation of hook_access
 */
93
function hosting_site_access($op, $node, $account) {
94 95
  switch ($op) {
    case 'create':
96
      return user_access('create site', $account);
97 98
      break;
    case 'update':
99
      return user_access('edit site', $account);
100 101
      break;
    case 'delete':
102
      return user_access('delete site', $account);
103 104 105 106
      break;
    default:
      break;
  }
107 108
}

Adrian Rossouw's avatar
 
Adrian Rossouw committed
109 110 111 112 113
/**
 * Return a count of enabled sites.
 *
 * This is used by cron and statistics to batch the number of sites that are processed with each call
 */
114 115 116 117 118 119 120 121
function hosting_site_count($platform = null) {
  $query = "SELECT count(nid) FROM {hosting_site} WHERE status = %d";
  $args = array(HOSTING_SITE_ENABLED);
  if (!is_null($platform)) {
    $query .= " AND platform = %d";
    $args[] = $platform;
  }
  return db_result(db_query($query, $args));
Adrian Rossouw's avatar
 
Adrian Rossouw committed
122
}
123

124 125 126 127 128
/**
 * Retrieve sites on a specific platform, with a specific status
 */
function hosting_get_sites_by_status($platform, $status) {
  $nodes = array();
129
  $result = db_query("SELECT nid FROM {hosting_site} WHERE platform=%d AND status = %d", $platform, $status);
130 131 132 133 134 135 136
  while ($nid = db_fetch_object($result)) {
    $nodes[$nid->nid] = node_load($nid->nid);
  }

  return $nodes;
}

137 138 139 140
/**
 * Retrieve a node based on the url
 */
function hosting_get_site_by_url($url) {
141
  $nid = db_result(db_query("SELECT n.nid FROM {node} n JOIN {hosting_site} h ON n.nid = h.nid WHERE n.title='%s' AND n.type = 'site' AND NOT (h.status=%d)", $url, HOSTING_SITE_DELETED));
142 143 144 145 146 147
  if ($nid) {
    return node_load($nid);
  }
  return false;
}

148
/**
149
 * Helper function to generate new site node during import
150
 */
151
function hosting_import_site($site_id, $data, $platform = HOSTING_DEFAULT_PLATFORM) {
152
  global $user;
153 154
  $client = node_load(HOSTING_DEFAULT_CLIENT);

155
  if ($data['client_email']) {
156
    $client = hosting_import_client($data['client_email'], $data['client_name'], $data['client_organization']);
157
  }
158

159 160
  $site = new stdClass();
  $site->nid = $site_id;
161 162
  $site->uid = $client->uid;
  $site->status = 1;
163
  $site->site_status = 1;
164
  $site->platform = $platform;
165 166
  $site->no_verify = TRUE;
  $site->verified = mktime();
167
  $site->client = $client->nid;
168 169
  $db_server = hosting_get_db_server($data['db_id']);
  $site->db_server = ($db_server) ? $db_server->nid : HOSTING_DEFAULT_DB_SERVER;
170
  $site->site_language = $data['language'] ? $data['language'] : 'en';
171 172 173 174 175
  // Try and find a default port from the web server and use that for the imported site.
  // Needs to be improved (one vhost > many ports, and a proper 'default port' feature
  $showports = _hosting_site_allowed_ports($platform);
  $defport = reset($showports);
  $site->port = $defport;
176 177 178

  // Drupal 6 introduced a language field on nodes
  unset($data['language']);
179

180
  // This should really be handled via a hook system, to allow hosting_alias to see these fields, but later.
181
  #$site->aliases = $data['aliases'] ? $data['aliases'] : array();
182

183 184 185 186
  $profile = hosting_package_instance_load(array(
    'rid' => $platform,
    'short_name' => $data['profile']
  ));
187
  if (!$profile) {
188 189 190
    $profile = hosting_package_instance_load(array(
       'rid' => $platform,
       'short_name' => 'default'));
191
  }
192
  $site->profile = $profile->package_id;
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

  // cast site object to array, will be using various array_* functions on the data.
  $site = (array) $site;

  // Protect the fields already in the site object.
  foreach (array_keys($site) as $key) {
    unset($data[$key]);
  }

  // Load all the original node fields.
  $site = array_merge( (array) node_load($site_id), $site);

  // Map the imported fields onto the node object.
  $site = array_merge($site, $data);

  // Cast back to object.
  $site = (object) $site;
210
  node_save($site);
211 212
}

213 214 215 216 217 218 219 220 221 222
/**
 * pre_render form callback
 *
 * Add the needed .js and .css files to render the form correctly before printing it
 */
function _hosting_site_form_pre_render($elements) {
  drupal_add_js(drupal_get_path('module', 'hosting_site') . '/hosting_site_form.js');
  drupal_add_css(drupal_get_path('module', 'hosting_site') . '/hosting_site_form.css');
  return $elements;
}
Adrian Rossouw's avatar
Adrian Rossouw committed
223

224 225 226 227 228
/**
 * Implementation of hook_form
 *
 * TODO: additional nested logic. Certain profiles are available only on certain platforms, and certain languages on certain profiles.
 */
229
function hosting_site_form($node) {
230
  $form['#pre_render'][] = '_hosting_site_form_pre_render';
231

232
  $type = node_get_types('type', $node);
233 234 235 236 237

  if ($node->nid) {
    $form['info']['#prefix'] = '<div class="clear-block" id="hosting-site-edit-info">';
    $form['info']['#suffix'] = '<br /></div>';
  }
238
  // We need to define form elements for the node's title and body.
239 240 241 242 243 244 245 246 247 248
  if (!$node->nid) {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Domain name'),
      '#required' => TRUE,
      '#default_value' => $node->title,
      '#weight' => -5
    );
  }
  else {
249 250 251 252 253 254 255
    $form['info']['title'] = array(
      '#type' => 'item',
      '#title' => t('Domain name'),
      '#value' => $node->title,
      '#weight' => -5
    );

256 257 258
    $form['title'] = array('#type' => 'hidden', '#value' => $node->title);
  }

259

anarcat's avatar
anarcat committed
260
  # find the right client
261
  global $user;
262 263
  $current_client_id = 0;

Adrian Rossouw's avatar
Adrian Rossouw committed
264 265 266 267 268 269 270 271 272 273
  if ($user->uid) {
    $client_ids = hosting_get_client_from_user($user->uid);
    $clients = array();
    foreach($client_ids as $client_id => $client_permissions) {
      $client_id = $client_id ? $client_id : HOSTING_DEFAULT_CLIENT;
      $client = node_load($client_id);
      $clients[$client->title] = $client->title;
      if ($node->client == $client_id || !$current_client_id) {
        $current_client_id = $client_id;
      }
anarcat's avatar
anarcat committed
274
    }
275
    if (!$current_client_id && !user_access('administer site')) {
276
      form_set_error('client', t('Your user is not associated with any clients so you are not allowed to create new sites'));
277
    }
anarcat's avatar
anarcat committed
278
  }
279 280

  if (!$current_client_id) {
Adrian Rossouw's avatar
Adrian Rossouw committed
281 282
    $current_client_id = HOSTING_DEFAULT_CLIENT;
  }
283

284 285
  // allow admins to override
  if ($node->client && user_access('administer site')) {
anarcat's avatar
anarcat committed
286
    $current_client_id = $node->client;
anarcat's avatar
anarcat committed
287
  }
Adrian Rossouw's avatar
Adrian Rossouw committed
288

anarcat's avatar
anarcat committed
289
  $client = node_load($current_client_id);
290 291 292 293 294 295 296
  if (!$client) {
    # we give up, couldn't find a client, we're probably in a preview so
    # just use the node client
    $client = new stdClass();
    $client->title = $node->client;
  }

297 298
  // If the user is an admin or if it's a new site, they can edit who the client of the site is
  if ((!$node->client || $node->nid) || user_access('administer site')) {
299 300 301 302 303 304 305 306
    $form['client'] = array(
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => t('Client'),
      '#default_value' => $client->title,
      '#description' => t('The client who this site belongs to.'),
      '#autocomplete_path' => 'hosting_client/autocomplete/client',
    );
307
  }
308 309
  // If the user is a client, they cannot choose who the client is
  else {
310
    $form['client'] = array('#type' => 'hidden', '#value' => $client->title);
311 312 313 314 315
    $form['info']['client'] = array(
      '#type' => 'item',
      '#title' => t('Client'),
      '#value' => $client->title,
    );
316
  }
317
  if (!$node->nid) {
318 319 320 321
    /* If Client module exists, non-admin user sees only accessible platforms
     * Otherwise, use enabled platforms
     * Admin user isn't restricted to only accessible platforms for the client
    */
322 323
    $platforms = _hosting_get_platforms();
    $user = user_load($GLOBALS['user']->uid);
mig5's avatar
mig5 committed
324
    if (sizeof($platforms)) {
325 326 327 328
      foreach ($platforms as $nid => $title) {
        $platform = node_load($nid);

        if ($platform->platform_status != HOSTING_PLATFORM_LOCKED) {
329
          if (!isset($platform->clients) || sizeof(array_intersect(array_keys($user->client_id), $platform->clients)) || $user->uid == 1) {
330 331 332 333 334 335
            $options[$nid] = $title;
          }
        }
      }

      if (sizeof($options) > 1) {
mig5's avatar
mig5 committed
336 337 338 339 340
        $form['platform'] = array(
          '#type' => 'radios',
          '#title' => t('Platform'),
          '#required' => TRUE,
          '#description' => t('The platform you want the site to be hosted on.'),
341
          '#options' => $options,
mig5's avatar
mig5 committed
342 343 344
          '#default_value' => HOSTING_DEFAULT_PLATFORM,
        );
      }
345 346 347 348 349
      elseif (sizeof($options) == 1) {
        $form['platform'] = array('#type' => 'hidden', '#value' => key($options));
      }
      else { 
        drupal_set_message(t('You have no enabled platforms! Please add or unlock a platform before attempting to create a site.'), 'error');
mig5's avatar
mig5 committed
350
      }
351

mig5's avatar
mig5 committed
352 353 354
      $form['port'] = _hosting_site_form_port();
      $form['profile'] = _hosting_site_form_profile();
      $form['site_language'] = _hosting_site_form_site_language();
355 356
    }
    else {
mig5's avatar
mig5 committed
357
      drupal_set_message(t('You have no enabled platforms! Please add or unlock a platform before attempting to create a site.'), 'error');
358
    }
359 360
  }
  else {
361 362 363 364 365
    $form['info']['platform'] = array(
      '#type' => 'item',
      '#title' => t('Platform'),
      '#value' => _hosting_node_link($node->platform),
     );
366
    $form['platform'] = array('#type' => 'hidden', '#value' => $node->platform);
367 368 369 370 371
    $form['info']['port'] = array(
      '#type' => 'item',
      '#title' => t('Port'),
      '#value' => $node->port,
     );
372
    $form['port'] = _hosting_site_form_port();
373 374 375 376 377
    $form['info']['profile'] = array(
       '#type' => 'item',
       '#title' => t('Install Profile'),
       '#value' => _hosting_node_link($node->profile),
    );
378
    $form['profile'] = array('#type' => 'hidden', '#value' => $node->profile);
379
    $form['info']['site_language'] = array(
380 381
      '#type' => 'item',
      '#title' => t('Language'),
382
      '#value' => _hosting_language_name($node->site_language),
383
    );
384
    $form['site_language'] = array('#type' => 'hidden', '#value' => $node->site_language);
385 386
  }

387
  if (!$node->nid) {
drumm's avatar
drumm committed
388
    $db_servers = hosting_get_servers('db');
389 390 391 392 393 394 395 396 397 398 399 400 401
    if (sizeof($db_servers) > 1) {
      $form['db_server'] = array(
        '#type' => 'radios',
        '#title' => t('Database server'),
        '#required' => TRUE,
        '#description' => t('The database server the site will use to host it\'s content.'),
        '#options' => $db_servers,
        '#default_value' => $node->db_server,
      );
    }
    else {
      $form['db_server'] = array('#type' => 'hidden', '#value' => key($db_servers));
    } 
402 403
  }
  else {
404 405 406 407 408 409 410
    $form['info']['db_server'] = array(
      '#type' => 'item',
      '#title' => t('Database Server'),
      '#value' => _hosting_node_link($node->db_server),
    );
    $form['db_server'] = array('#type' => 'hidden', '#value' => $node->db_server);
  }
drumm's avatar
drumm committed
411 412 413 414
  foreach(array('verified', 'last_cron', 'site_status') as $extra_attribute) {
    $form["$extra_attribute"] = array('#type' => 'value', '#value' => $node->$extra_attribute);
  }

415 416 417
  return $form;
}

mig5's avatar
mig5 committed
418 419 420
/**
 * Implementation of hook_validate().
 */
anarcat's avatar
anarcat committed
421 422
function hosting_site_validate($node, &$form) {
  global $user;
423
  $url = strtolower(trim($node->title)); // domain names are case-insensitive
424
  if (!_hosting_valid_fqdn($url)) {
425 426
    form_set_error('title', t("You have not specified a valid url for this site."));
  }
427
  
anarcat's avatar
anarcat committed
428
  if ($node->port < 1 || $node->port > 65536) {
429 430
    form_set_error('title', t("You have not specified a valid port for this site."));
  }
anarcat's avatar
anarcat committed
431 432 433
  if (!array_key_exists($node->port, _hosting_site_allowed_ports($node->platform))) {
    form_set_error('title', t("This port is forbidden by the administrators."));
  }
434
  
anarcat's avatar
anarcat committed
435 436 437 438 439
  if (!$node->new_client) {
    $client = hosting_get_client($node->client);
    if (!$node->client || !$client) {
      form_set_error('client', t('Please fill in a valid client'));
    }
anarcat's avatar
anarcat committed
440
    if (!user_access('administer clients') && !array_key_exists($client->nid, hosting_get_client_from_user($user->uid))) {
anarcat's avatar
anarcat committed
441 442
      form_set_error('client', t('Access denied to client @client', array('@client' => $client->title)));
    }
443
    $node->client = $client->nid;
444
  }
445 446 447 448 449
  # TODO: maybe we should allow creation of sites that conflict with HOSTING_SITE_DISABLED (which would then need to be renamed before being re-enabled)
  if (!hosting_domain_allowed($url, (array) $node)) {
    form_set_error('title', t("The domain name you have specified is already in use."));
  }

450 451 452
  if (!array_key_exists($node->profile, hosting_get_profiles($node->platform))) {
    form_set_error('profile', t('Please fill in a valid profile'));
  }
453 454
  if (!array_key_exists($node->site_language, hosting_get_profile_languages($node->profile, $node->platform))) {
    form_set_error('site_language', t('Please fill in a valid language'));
455 456
  }

457
}
458

459 460 461 462 463 464
/**
 * Implementation of hook_nodeapi().
 */
function hosting_site_nodeapi(&$node, $op, $teaser, $page) {
  switch($op) {
    case 'submit':
465
      $node->title = strtolower(trim($node->title)); // domain names are case-insensitive
466 467
      break;
  }
468 469
}

mig5's avatar
mig5 committed
470 471 472
/**
 * Implementation of hook_insert().
 */
473
function hosting_site_insert(&$node) {
474 475
  $client = hosting_get_client($node->client);
  $node->client = $client->nid;
476
  $node->site_language = ($node->site_language) ? $node->site_language : 'en';
477

478
  db_query("INSERT INTO {hosting_site} (vid, nid, client, db_server, platform, profile, language, last_cron, status, verified, port, `ssl`, ssl_redirect) VALUES (%d, %d, %d, %d, %d, %d, '%s', %d, %d, %d, %d, %d, %d)",
anarcat's avatar
anarcat committed
479
           $node->vid, $node->nid, $node->client, $node->db_server, $node->platform, $node->profile, $node->site_language, $node->last_cron, $node->site_status, $node->verified, $node->port, $node->ssl, $node->ssl_redirect);
480
  if ((!$node->old_vid)) {
481
    hosting_context_register($node->nid, ($node->hosting_name) ? $node->hosting_name : $node->title);
482
    if ($node->import) {
483 484 485 486 487
      hosting_add_task($node->nid, 'import');
    }
    else {
      hosting_add_task($node->nid, 'install');
    }
488
  }
489
}
mig5's avatar
mig5 committed
490 491 492 493

/**
 * Helper function to retrieve an array of allowed ports
 */
494 495 496 497 498 499 500 501 502 503 504 505 506
function _hosting_site_allowed_ports($platform) {
  $ports = db_result(db_query("SELECT ports FROM {hosting_platform} p JOIN {hosting_web_server} w ON p.web_server = w.nid WHERE p.nid = %d", $platform));
  $ports = explode(",", $ports);
  $ret = array();
  foreach($ports as $p) {
    $p = trim($p);
    if(is_numeric($p)) {
      $ret[$p] = $p;
    }
  }
  return $ret;
}

mig5's avatar
mig5 committed
507 508 509
/**
 * Implementation of hook_update().
 */
510
function hosting_site_update(&$node) {
511 512 513 514 515
  // if this is a new node or we're adding a new revision,
  if ($node->revision) {
    hosting_site_insert($node);
  }
  else {
516 517
    $client = hosting_get_client($node->client);
    $node->client = $client->nid;
518 519 520
    if ($node->site_status == HOSTING_SITE_DELETED) {
      $node->no_verify = TRUE;
    }
anarcat's avatar
anarcat committed
521 522
    db_query("UPDATE {hosting_site} SET client = %d, db_server = %d, platform = %d, last_cron = %d, status = %d, profile = %d, language = '%s', verified = %d, port = %d, `ssl` = %d, ssl_redirect = %d WHERE vid=%d",
             $node->client, $node->db_server, $node->platform, $node->last_cron, $node->site_status, $node->profile, $node->site_language, $node->verified, $node->port, $node->ssl, $node->ssl_redirect, $node->vid);
523
  }
Adrian Rossouw's avatar
Adrian Rossouw committed
524
  if (!$node->no_verify) {
drumm's avatar
drumm committed
525
    hosting_add_task($node->nid, 'verify');
Adrian Rossouw's avatar
 
Adrian Rossouw committed
526
  }
527 528
}

mig5's avatar
mig5 committed
529 530 531
/**
 * Implementation of hook_load().
 */
Adrian Rossouw's avatar
Adrian Rossouw committed
532
function hosting_site_load($node) {
anarcat's avatar
anarcat committed
533
  $additions = db_fetch_object(db_query('SELECT  client, db_server, platform, profile, language as site_language, last_cron, status AS site_status, verified, port, `ssl`, ssl_redirect FROM {hosting_site} WHERE vid = %d', $node->vid));
Adrian Rossouw's avatar
Adrian Rossouw committed
534 535 536
  return $additions;
}

mig5's avatar
mig5 committed
537 538 539
/**
 * Implementation of hook_nodeapi_delete_revision().
 */
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
function hosting_nodeapi_site_delete_revision(&$node) {
  db_query('DELETE FROM {hosting_site} WHERE vid = %d', $node->vid);
}

/**
 * Implementation of hook_delete().
 */
function hosting_site_delete($node) {
  db_query('DELETE FROM {hosting_site} WHERE nid = %d', $node->nid);
  db_query('DELETE FROM {hosting_package_instance} WHERE rid=%d', $node->nid);
  $result = db_query("SELECT distinct nid FROM {hosting_task} WHERE rid=%d", $node->nid);
  while ($nid = db_fetch_object($result)) {
    node_delete($nid->nid);
  }
}

mig5's avatar
mig5 committed
556 557 558
/**
 * Implementation of hook_view().
 */
559
function hosting_site_view(&$node, $teaser = false) {
560
  hosting_set_breadcrumb($node);
561
  modalframe_parent_js();
562
  $node->content['info']['#prefix'] = '<div id="hosting-site-info">';
563
  if ($node->site_status == HOSTING_SITE_ENABLED) {
564
    $node->content['info']['link'] = array(
565
      '#value' => _hosting_site_goto_link($node),
566 567
      '#weight' => -10
    );
Adrian Rossouw's avatar
Adrian Rossouw committed
568
  }
569

570
  if (is_numeric($node->client)) {
571 572 573 574 575 576 577 578
    $node->content['info']['client'] = array(
      '#type' => 'item',
      '#title' => t('Client'),
      '#value' => _hosting_node_link($node->client),
      '#weight' => 5
    );
  }

Adrian Rossouw's avatar
Adrian Rossouw committed
579 580 581 582 583
  $node->content['info']['verified'] = array(
    '#type' => 'item',
    '#title' => t('Verified'),
    '#value' => hosting_format_interval($node->verified),
  );
584 585 586 587 588 589
  
  $node->content['info']['port'] = array(
    '#type' => 'item',
    '#title' => t('Port'),
    '#value' => $node->port,
  );
Adrian Rossouw's avatar
Adrian Rossouw committed
590

591
  $node->content['info']['platform'] = array(
592 593 594 595
    '#type' => 'item',
    '#title' => t('Platform'),
    '#value' => _hosting_node_link($node->platform),
  );
596

597 598 599 600 601 602 603
  if ($node->profile) {
    $node->content['info']['profile'] = array(
      '#type' => 'item',
      '#title' => t('Install profile'),
      '#value' => _hosting_node_link($node->profile),
    );
  }
604 605
  if ($node->site_language) {
    $node->content['info']['site_language'] = array(
606 607
      '#type' => 'item',
      '#title' => t('Language'),
608
      '#value' => _hosting_language_name($node->site_language),
609 610 611 612 613 614 615 616 617
    );
  }
  if ($node->db_server) {
    $node->content['info']['db_server'] = array(
      '#type' => 'item',
      '#title' => t('Database server'),
      '#value' => _hosting_node_link($node->db_server),
    );
  }
618 619 620 621 622

  if ($node->nid) { 
    $node->content['info']['status'] = array(
      '#type' => 'item',
      '#title' => t('Status'),
623
      '#value' => _hosting_site_status($node),
624
    );
625
  }
626

627
  $node->content['info']['#suffix'] = '</div>';
628

629 630 631
  if ($node->nid) { 
    $node->content['tasks_view'] = array(
      '#type' => 'item',
632
      '#value' => hosting_task_table($node),
633 634
      '#prefix' => '<div id="hosting-task-list">',
      '#suffix' => '</div>', 
635 636
      '#weight' => 10
    );
637 638
    $settings['hostingTaskRefresh'] = array(
      'nid' => $node->nid,
639
      'changed' => $node->changed,
640 641 642 643
    );
    drupal_add_js($settings, 'setting');

    drupal_add_js(drupal_get_path('module','hosting_task') . '/hosting_task.js');
644
  }
Adrian Rossouw's avatar
Adrian Rossouw committed
645
  return $node;
646
}
647

mig5's avatar
mig5 committed
648 649 650
/**
 * Define the status types of a site
 */
651 652 653 654 655 656 657 658 659 660
function _hosting_site_status($node) {
  static $labels = array(
    HOSTING_SITE_QUEUED => "Queued",
    HOSTING_SITE_ENABLED => "Enabled",
    HOSTING_SITE_DELETED => "Deleted",
    HOSTING_SITE_DISABLED => "Disabled",
  );
  return $labels[$node->site_status];
}

661 662 663 664 665
/**
 * Add a site backup record.
 *
 * Builds a list of backups of the site that have been generated.
 */
666
function hosting_site_add_backup($site, $web_server, $filename, $description = '') {
667 668 669
  db_query("INSERT INTO {hosting_site_backups} (site, web_server, filename, description, timestamp) VALUES (%d, %d, '%s', '%s', %d)",
    $site, $web_server, $filename, $description, mktime());
  $bid = db_last_insert_id('hosting_site_backups', 'bid');
670 671 672 673 674 675 676 677 678 679 680 681 682 683
  return $bid;
}

/**
 * Delete a site backup record
 */
function hosting_site_delete_backup($bid) {
  db_query("DELETE FROM {hosting_site_backups} WHERE bid=%d", $bid);
}

/**
 * Get a site backup record
 */
function hosting_site_get_backup($bid) {
684
  return db_fetch_array(db_query("SELECT bid, site, web_server, filename, description, timestamp FROM {hosting_site_backups} WHERE bid = %d", $bid));
685 686 687 688 689 690 691 692 693 694 695
}

/**
 * Retrieve a list of backup generated for a site.
 *
 * @param site
 *   The node if of the site backups are being retrieved for
 * @return
 *   An associative array of backups existing for the site, indexed by bid and sorted reverse chronologically.
 */
function hosting_site_backup_list($site) {
696
  $result = db_query("SELECT bid, description, timestamp FROM {hosting_site_backups} WHERE site=%d ORDER BY timestamp DESC", $site);
697
  while ($object = db_fetch_object($result)) {
698 699
    #needs to be cleaned up. but i am NOT generating a theme func for this right now.
    $backups[$object->bid] = '<strong>' . format_date($object->timestamp) . '</strong> - ' . $object->description;
700 701 702 703
  }
  return $backups;
}

704

705
/**
mig5's avatar
mig5 committed
706
 * Implementation of hook_form_alter().
707 708
 * Hide the delete button on site nodes
 */
709
function hosting_site_form_alter(&$form, &$form_state, $form_id) {
710
  // Remove delete button from site edit form, unless the site's already been deleted via the Delete task
711
  if ($form_id == 'site_node_form') {
712 713 714 715
    $node = $form['#node'];
    if ($node->site_status !== '-2') {
      $form['buttons']['delete']['#type'] = 'hidden';
    }
716 717
  }
}
718

719
/**
720
 * Check if a site exists in a somehow wrong way
721
 *
722 723
 * @see hosting_domain_allowed()
 * @deprecated
724
 */
725
function hosting_site_exists($url, $port = null, $nid = null) {
726
  return !hosting_domain_allowed($url, array('port' => $port, 'nid' => $nid));
727 728
}

729 730 731 732
/**
 * Implementation of hook_allow_domain().
 *
 * @see hosting_domain_allowed()
733
 */
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
function hosting_site_allow_domain($url, $params = array()) {
  $query = "SELECT COUNT(n.nid) FROM {node} n 
    JOIN {hosting_site} h ON n.nid = h.nid
    WHERE type='site' AND title='%s' AND h.status <> %d ";
  $args[] = $url;
  $args[] = HOSTING_SITE_DELETED;
  
  if (isset($params['client'])) {
    if (isset($params['port'])) {
      $query .= ' AND ( h.client <> %d OR h.port = %d )';
      $args[] = $params['client'];
      $args[] = $params['port'];
    }
    else {
      $query .= ' AND h.client <> %d';
      $args[] = $params['client'];
    }
  }
  // check for ports only if we have no client provided
  else {
    if (isset($params['port'])) {
      $query .= ' AND h.port = %d';
      $args[] = $params['port'];
    }
  }

  if (isset($params['nid'])) {
    $query .= ' AND n.nid <> %d';
    $args[] = $params['nid'];
  }
  $result = !db_result(db_query($query, $args));
  return $result;
766 767 768 769 770
}

/**
 * Count the number of sites with a specific url, ignoring deleted sites
 */
771
function hosting_site_count_sites($url, $params = array()) {
772
  $query = "SELECT COUNT(n.nid) FROM 
773 774
    {node} n JOIN {hosting_site} h 
    ON n.nid = h.nid WHERE type='site'
775
    AND title='%s' AND h.status <> %d";
776
  $args[] = $url;
777
  $args[] = HOSTING_SITE_DELETED;
778
  
779
  if (isset($params['port'])) {
780
    $query .= ' AND h.port = %d';
781
    $args[] = $params['port'];
782
  }
783

784
  if (isset($params['nid'])) {
785
    $query .= ' AND n.nid <> %d';
786
    $args[] = $params['nid'];
787 788
  }
  return db_result(db_query($query, $args));
789
}
790

791 792 793 794
function hosting_site_task_status($nid) {
  return hosting_task_status_output('nid', $nid, 'install');
}

795 796 797 798 799 800 801 802 803 804
/**
 * Display a list of created sites on the front page
 * @TODO Add ability to filter by additional fields
 * @TODO Add paging.
 */
function hosting_site_list($filter_by = null, $filter_value = null) {
  $args[] = 'site';
  $cond = '';

  if ($filter_by && $filter_value) {
805 806 807 808 809
    if ($filter_by == 'status') {
      $cond = ' AND s.' . $filter_by . ' & %d';
    } else {
      $cond = ' AND s.' . $filter_by . ' = %d';
    }
810 811
    $args[] = $filter_value;
  }
812

813
  $header = array(
814
    array('data' => t('Site'), 'field' => 'title'),
815
    array('data' => t('Profile'), 'field' => 'profile'),
816
    array('data' => t('Language'), 'field' => 'site_language'),
817 818
    array('data' => t('Created'), 'field' => 'created', 'sort' => 'desc'),
  );
mig5's avatar
mig5 committed
819
  $platforms = _hosting_get_enabled_platforms();
820
  if (sizeof($platforms) > 1) {
821
    $header[] = array('data' => t('Platform'), 'field' => 'platform');
822
  }
823

824
  $sql = "SELECT n.nid, n.title, n.created, s.status as site_status, profile, s.language as site_language, platform, verified FROM {node} n left join {hosting_site} s ON n.vid=s.vid WHERE type='%s' AND s.status != -2 " . $cond;
825 826
  $sql .= tablesort_sql($header);

827
  // @TODO hide deleted sites
828
  $result = pager_query(db_rewrite_sql($sql), 25, 1, null, $args);
829

830
  if (!$result) {
831 832 833 834 835
    return null;
  }
  $rows = array();
  while ($node = db_fetch_object($result)) {
    $row = array();
836
    $row[] =  array('data' => l($node->title, 'node/' . $node->nid), 'class'=> 'hosting-status');
837
    $row[] = ($node->profile) ? _hosting_node_link($node->profile) : t('n/a');
838
    $row[] = ($node->site_language) ? _hosting_language_name($node->site_language) : t('n/a');
839
    $row[] = t("@interval ago", array('@interval' => format_interval(mktime() - $node->created, 1)));
840 841 842
    if (sizeof($platforms) > 1) {
      $row[] = ($node->platform) ? _hosting_node_link($node->platform) : t('n/a');
    }
843
    $rows[] = array('data' => $row, 'class' => _hosting_site_list_class($node));
844 845
  }
  
Adrian Rossouw's avatar
Adrian Rossouw committed
846
  return theme('table',  $header, $rows, array('class' => 'hosting-table')) . theme('pager', null, 25, 1);
847 848
}

mig5's avatar
mig5 committed
849 850 851 852
/**
 * Define the classes that correspond to the site status.
 * @see _hosting_site_status()
 */
853
function _hosting_site_list_class($node) {
854 855 856 857
  static $classes = array(
    HOSTING_SITE_QUEUED => "hosting-queue",
    HOSTING_SITE_ENABLED => "hosting-success",
    HOSTING_SITE_DELETED => "hosting-error",
858
    HOSTING_SITE_DISABLED => "hosting-error",
859
  );
Adrian Rossouw's avatar
Adrian Rossouw committed
860 861 862 863
  if (($node->site_status == HOSTING_SITE_ENABLED) && (!$node->verified)) {
    return 'hosting-warning';
  }

864
  return $classes[$node->site_status];
865 866 867 868 869 870
}

/**
 * Page handler for displaying list of hosted sites on front page
 */
function hosting_sites() {
871
  if ($list = hosting_site_list()) {
872 873
    return $list;
  }
874 875 876
  $create_site_link = l(t('Create a site now?'), 'node/add/site');
  return t("No sites have been created yet. !link", array(
    '!link' => $create_site_link));
877 878
}

mig5's avatar
mig5 committed
879 880 881
/**
 * Implementation of hook_menu()
 */
882 883 884 885
function hosting_site_menu() {
  $items = array();

  $items['hosting/sites'] = array(
886
    'title' => 'Sites',
887 888 889
    'description' => 'Display a list of sites',
    'page callback' => 'hosting_sites',
    'access arguments' => array('create site') 
890
  );
891

892 893
  $items['hosting/hosting_site_form_populate'] = array(
    'page callback' =>'_hosting_site_form_populate',
894
    'type' => MENU_CALLBACK,
895
    'access arguments' => array('access content'),
896 897
  );

898 899 900 901 902 903 904 905
  $items['node/%hosting_task_site/goto_site'] = array(
    'page callback' => 'hosting_site_goto',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'type' => MENU_CALLBACK,
  );

906 907
  return $items;
}
908 909

/**
mig5's avatar
mig5 committed
910
 * Generate hosting site node form element 'profile'
911 912 913
 */
function _hosting_site_form_profile($platform = NULL) {
  $profiles = hosting_get_profiles($platform);
914 915 916 917 918 919 920
  foreach($profiles as $id => $name) {
    // Don't allow a site to be provisioned with hostslave or hostmaster profile
    if (in_array($name, array('hostslave', 'hostmaster'))) {
      unset($profiles[$id]);
    }
  }
  reset($profiles);
drumm's avatar
drumm committed
921
  if (sizeof($profiles) >= 1) {
922 923 924 925 926
    $form['profile'] = array(
      '#type' => 'radios',
      '#title' => t('Install profile'),
      '#description' => t('The type of site to install.'),
      '#options' => $profiles,
927
      '#default_value' => key($profiles),
928
      '#required' => TRUE,
929 930 931 932
      '#attributes' => array('class' => "hosting-site-form-profile-options"),
    );
  }
  else {
933
    $form['profile'] = array('#type' => 'hidden', '#value' => key($profiles), '#attributes' => array('class' => "hosting-site-form-profile-options"));
934 935 936 937
  }
  return $form['profile'];
}

mig5's avatar
mig5 committed
938 939 940
/**
 * Generate hosting site node form element 'port'
 */
941 942 943 944 945 946 947 948 949 950
function _hosting_site_form_port($platform = HOSTING_DEFAULT_PLATFORM) {
  $showports = _hosting_site_allowed_ports($platform);
  $defport = reset($showports);
  if (sizeof($showports) > 1 && user_access('change site port')) {
    $form['port'] = array(
      '#type' => 'radios',
      '#title' => t('Port'),
      '#required' => TRUE,
      '#default_value' => $defport,
      '#options' => $showports,
951
      '#weight' => 5,
952 953 954 955 956 957 958 959
      '#attributes' => array('class' => "hosting-site-form-port-options"),
     );
  } else {
      $form['port'] = array('#type' => 'hidden', '#default_value' => $defport, '#attributes' => array('class' => "hosting-site-form-port-options"));
  }
  return $form['port'];
}

960
/**
mig5's avatar
mig5 committed
961
 * Generate hosting site node form element 'language'
962
 */
963
function _hosting_site_form_site_language($profile = NULL, $platform = null) {
964
  $languages = hosting_get_profile_languages($profile, $platform);
965
  if (sizeof($languages) > 1) {
966
    $form['site_language'] = array(
967 968 969 970
      '#type' => 'radios',
      '#title' => t('Language'),
      '#description' => t('The type of site to install.'),
      '#options' => $languages,
971
      '#required' => TRUE,
972
      '#default_value' => 'en',
973
      '#attributes' => array('class' => "hosting-site-form-site-language-options"),
974 975 976
    );
  }
  else {
977
    $form['site_language'] = array('#type' => 'hidden', '#default_value' => 'en', '#attributes' => array('class' => "hosting-site-form-site-language-options"));
978
  }
979
  return $form['site_language'];
980 981 982
}

/**
mig5's avatar
mig5 committed
983
 * Populate hosting site node form element with specified arguments
984
 */
985
function _hosting_site_form_populate($element, $value, $value2 = null) {
986
  $element = str_replace('-', '_', $element);
987
  $form[$element] = call_user_func('_hosting_site_form_'. $element, $value, $value2);
988

anarcat's avatar
anarcat committed
989
  $GLOBALS['devel_shutdown'] = FALSE;
990
  $form_state = array();
991
  $built = form_builder('hosting_site_form', $form, $form_state);
992
  drupal_json(
993 994
    array(
      'status' => 'TRUE',
995
      'type' => $form[$element]['#type'],
996
      'data' => drupal_render($built),
997 998 999 1000
    )
  );
  exit();
}
1001

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
/**
 * Generate a link allowing the user to log into their new site, or simply
 * go to the site front page if the link has expired.
 */
function _hosting_site_goto_link($node) {
  $cache = cache_get("hosting:site:" . $node->nid . ":login_link");
  if (!is_null($cache) && (mktime() < $cache->data['expire'])) {
    $title = t("Log in to !url" , array('!url' => $node->title));
  }
  else {
    $title = t("Go to !url" , array('!url' => $node->title));
  }
  $options['attributes']['class'] = 'hosting-goto-site-link';
  return l($title, "node/" . $node->nid . "/goto_site", $options); 
}

/**
 * Menu callback to go to your site.
 *
 * This needs to be a callback because the link is only going to work once, 
 * so this will remove the link from the cache and just redirect to the site
 * not the login page.
 */
function hosting_site_goto($node) {
  $cid = "hosting:site:" . $node->nid . ":login_link";
  $cache = cache_get($cid);
  if (!is_null($cache) && (mktime() < $cache->data['expire'])) {
    $theurl = $cache->data['link'];
    cache_clear_all($cid, 'cache');
  }
  else {
    $title = t("Go to !url" , array('!url' => $node->title));
    switch($node->port) {
      case 80:
      $theurl = 'http://' . $node->title;
      break;
      case 443:
      $theurl = 'https://' . $node->title;
      break;
      default:
      $theurl = 'http://' . $node->title . ':' . $node->port;
    }
  }

  drupal_goto($theurl);
  exit();
}
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

/**
 * Views integration
 */
function hosting_site_views_api() {
  return array(
    'api' => 2, 
    'path' => drupal_get_path('module', 'hosting_site'),
  );
}