summaryrefslogtreecommitdiffstats
path: root/modules/hosting/site/hosting_site.module
blob: 30574d17ce23e4ba009d8cd169a267744e917597 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
138
139
140
141
142
143
144
145
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
194
195
196
197
198
199
200
201
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
233
234
235
236
237
238
239
240
241
242
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
<?php

/**
 * This site is deleted from the backend.
 */
define('HOSTING_SITE_DELETED', -2);

/**
 * This site is disabled.
 */
define('HOSTING_SITE_DISABLED', -1);

/**
 * This site is queued for creation.
 */
define('HOSTING_SITE_QUEUED', 0);

/**
 * This site is created and enabled in the backend.
 */
define('HOSTING_SITE_ENABLED', 1);

include_once('hosting_site.nodeapi.inc');
include_once('hosting_site.form.inc');
include_once('hosting_site.backups.inc');

//Conditonally include site quotas
if (module_exists('hosting_quota')) {
  include_once('hosting_site.quota.inc');
}

/**
 * Implementation of hook_menu()
 */
function hosting_site_menu() {
  $items = array();

  $items['hosting/sites'] = array(
    'title' => 'Sites',
    'description' => 'Display a list of sites',
    'page callback' => 'hosting_sites',
    'access arguments' => array('view site'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['hosting/sites/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['hosting/sites/add'] = array(
    'title' => 'Add site',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_goto',
    'page arguments' => array('node/add/site'),
    'access callback' => 'node_access',
    'access arguments' => array('create', 'site'),
  );

  $items['hosting/hosting_site_form_check'] = array(
    'page callback' =>'_hosting_site_form_check',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
           

  $items['node/%hosting_site_node/goto_site'] = array(
    'page callback' => 'hosting_site_goto',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function _hosting_site_form_check() {
  drupal_json(
    hosting_site_available_options($_POST)
  );
  exit();
}

/**
 * Implementation of hook_load().
 *
 * @param arg
 *    Node's numeric nid
 */
function hosting_site_node_load($arg) {
 if (!is_numeric($arg)) {
    return FALSE;
  }
  if ($node = node_load($arg)) {
    if ($node->type == 'site') {
      return $node;
    }
  }
  return FALSE;
}

/**
 * Page handler for displaying list of hosted sites on front page
 */
function hosting_sites() {
  if ($list = drupal_get_form('hosting_site_list_form')) {
    return $list;
  }
  $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));
}

/**
 * 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) && (time() < $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) && (time() < $cache->data['expire'])) {
    $theurl = $cache->data['link'];
    cache_clear_all($cid, 'cache');
  }
  else {
    $theurl = _hosting_site_url($node);
  }

  drupal_goto($theurl);
  exit();
}

/**
 * Retrieve the port the site will be available on, so we can redirect.
 */
function hosting_site_get_port($node) {
  $platform = node_load($node->platform);
  $server = node_load($platform->web_server);
  return $server->services['http']->port;
}

/**
 * Get site's URL.
 */
function _hosting_site_url($node) {
  $schema = 'http';
  $port = null;

  $url = strtolower(trim($node->title));

  $platform = node_load($node->platform);
  $server = node_load($platform->web_server);


  if ($server->services['http']->has_port()) { 
    $port = $server->services['http']->port;
    if ($port == 80) {
      $port = null;
    }
  }

  /**
   * This is part of the ssl feature, but is better to implement here.
   */
  if (isset($node->ssl_enabled) && ($node->ssl_enabled == 2)) {
    // this is a bit of a magic number, because we cant rely on the constant being available yet.
    // 2 == Only SSL is enabled.
    $schema = 'https';

    if ($server->services['http']->has_port()) { 
      $port = $server->services['http']->ssl_port;
      if ($port == 443) {
        $port = null;
      }
    }
  }

  if (is_numeric($port)) {
    return "{$schema}://{$url}:{$port}";
  }

  return "{$schema}://{$url}";
}

/**
 * Implementation of hook_hosting_tasks
 */
function hosting_site_hosting_tasks() {
  $tasks = array();

  $tasks['site']['backup'] = array(
    'title' => t('Backup'),
    'description' => t('Generate a backup of this site that can be restored to at any time'),
     'dialog' => TRUE,
   );

  $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.'),
    'dialog' => TRUE,
  );

  $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.'),
    'provision_save' => TRUE,
  );

  $tasks['site']['disable'] = array(
    'title' =>  t('Disable'),
    'description' =>  t('Disabling this site will stop it from being accessible.
         It can be enabled again later.'),     
    'dialog' => TRUE,
  );     
  $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?'),
    'dialog' => TRUE,
  );

  $tasks['site']['login-reset'] = array(
     'title' => t('Reset password'),
     'description' => t('Generate a one-time login reset url for this site.'),
  );

  $tasks['site']['backup-delete'] = array(
     'title' => t('Delete backups'),
     'description' => t('Delete one or more backup files of a site.'),
     'dialog' => TRUE,
  );

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

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

  return $tasks;
}

/**
 * Implementation of hook_perm
 */
function hosting_site_perm() {
  return array('create site', 'view site', 'edit site', 'delete site', 'administer sites');
}

/**
 * Implementation of hook_access
 */
function hosting_site_access($op, $node, $account) {
  switch ($op) {
    case 'create':
      return user_access('create site', $account);
      break;
    case 'update':
      return user_access('edit site', $account);
      break;
    case 'delete':
      return user_access('delete site', $account);
      break;
    case 'view':
      return user_access('view site', $account);
      break;
  }
}

/**
 * Returns a count of sites.
 *
 * This is used by cron and statistics to batch the number of sites that are
 * processed with each call. It is also used to generate the 'site count' per
 * platform at /hosting/platforms
 *
 * By default it only counts enabled sites.
 *
 * Optionally can include an array of site statuses by which to consider in the
 * count.
 *
 * @param $platform
 *   (optional) A platform nid to only count sites on that specific platform.
 * @param $statuses
 *   (optional) An array of site statuses (defined by their constants) by which
 *   to include such sites in the site count.
 *
 * @return
 *   The number of sites matching the specified criteria.
 */
function hosting_site_count($platform = NULL, $statuses = NULL) {
  if (is_null($statuses)) {
    $statuses = array(HOSTING_SITE_ENABLED);
  }
  $args = array();
  $query = "SELECT count(nid) FROM {hosting_site}";
  $where = array();

  if (count($statuses)) {
    $where[] = '(status IN (' . db_placeholders($statuses) . '))';
    $args = array_merge($args, $statuses);
  }

  if (!is_null($platform)) {
    $where[] = "(platform = %d)";
    $args[] = $platform;
  }

  if (!empty($where)) {
    $query .= ' WHERE ' . implode(' AND ', $where);
  }

  return db_result(db_query($query, $args));
}

/**
 * Retrieve sites on a specific platform, with a specific status
 */
function hosting_get_sites_by_status($platform, $status) {
  $nodes = array();
  $result = db_query("SELECT nid FROM {hosting_site} WHERE platform=%d AND status = %d", $platform, $status);
  while ($nid = db_fetch_object($result)) {
    $nodes[$nid->nid] = node_load($nid->nid);
  }

  return $nodes;
}

/**
 * Retrieve a node based on the url
 */
function hosting_get_site_by_url($url) {
  // If the Aliases feature is enabled, try and get the site by its alias too
  if (hosting_feature('alias')) {
    $nid = db_result(db_query("SELECT n.nid FROM {node} n JOIN {hosting_site} h ON n.nid = h.nid LEFT JOIN {hosting_site_alias} ha ON h.vid = ha.vid WHERE (n.title = '%s' OR ha.alias = '%s') AND n.type = 'site' AND NOT (h.status = %d)", $url, $url, HOSTING_SITE_DELETED));
  }
  else {
    $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));
  }
  if ($nid) {
    return node_load($nid);
  }
  return false;
}

/**
 * Helper function to generate update a site node during import.
 *
 * @param $site_id
 *   The node ID of the existing site node to update.
 * @param $data
 *  An associative array of data to add to the site node. Keys should correspond
 *  to properties on the node object to overwrite.
 * @param $platform
 *   The node ID of the platform that the site is deployed on.
 */
function hosting_import_site($site_id, $data, $platform) {
  global $user;
  $client = node_load(HOSTING_DEFAULT_CLIENT);

  if ($data['client_name']) {
    $client = hosting_import_client($data['client_name']);
  } 

  $site = node_load($site_id);
  $site->nid = $site_id;
  $site->uid = $client->uid;
  $site->status = 1;
  $site->site_status = 1;
  $site->platform = $platform;
  $site->no_verify = TRUE;
  $site->verified = time();
  $site->client = $client->nid ? $client->nid : HOSTING_DEFAULT_CLIENT;
  $site->ip_addresses = array_values($data['site_ip_addresses']);
  $site->cron_key = ($data['cron_key']) ? $data['cron_key'] : '';

  $site->aliases = ($data['aliases']) ? $data['aliases'] : array();
  $site->db_server = ($site->db_server) ? $site->db_server : HOSTING_DEFAULT_DB_SERVER;
  $site->site_language = $data['language'] ? $data['language'] : 'en';

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


  $profile = hosting_package_instance_load(array(
    'i.rid' => $platform,
    'p.short_name' => $data['profile']
  ));
  if (!$profile) {
    $profile = hosting_package_instance_load(array(
       'i.rid' => $platform,
       'p.short_name' => 'default'));
  }
  $site->profile = $profile->package_id;

  // 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;
  node_save($site);
}

/**
 * Define the status types of a site
 */
function _hosting_site_status($node) {
  $status = (is_numeric($node)) ? $node : $node->site_status;
  static $labels = array(
    HOSTING_SITE_QUEUED => "Queued",
    HOSTING_SITE_ENABLED => "Enabled",
    HOSTING_SITE_DELETED => "Deleted",
    HOSTING_SITE_DISABLED => "Disabled",
  );
  return $labels[$status];
}

/**
 * Implementation of hook_allow_domain().
 *
 * @see hosting_domain_allowed()
 */
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['nid'])) {
    $query .= ' AND n.nid <> %d';
    $args[] = $params['nid'];
  }
  $result = !db_result(db_query($query, $args));
  return $result;
}

function hosting_site_task_status($nid) {
  return hosting_task_status_output('nid', $nid, 'install');
}

/**
 * Create a form for building a list of sites.
 * @TODO Add ability to filter by additional fields
 */
function hosting_site_list_form($form_state, $filter_by = NULL, $filter_value = NULL) {
  $step = isset($form_state['storage']['step']) ? $form_state['storage']['step'] : 1;

  // Step 1 - select sites
  if ($step == 1) {
    $args[] = 'site';
    $cond = '';

    if ($filter_by && $filter_value) {
      if ($filter_by == 'status') {
        $cond = ' AND s.' . $filter_by . ' & %d';
      } else {
        $cond = ' AND s.' . $filter_by . ' = %d';
      }
      $args[] = $filter_value;
    }

    $header = array(
      array('data' => t('Site'), 'field' => 'title'),
      array('data' => t('Profile'), 'field' => 'profile'),
      array('data' => t('Language'), 'field' => 'site_language'),
      array('data' => t('Created'), 'field' => 'created', 'sort' => 'desc'),
    );
    $platforms = _hosting_get_platforms();
    if (sizeof($platforms) > 1) {
      $header[] = array('data' => t('Platform'), 'field' => 'platform');
    }

    $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;
    $sql .= tablesort_sql($header);

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

    $form['options'] = array(
      '#type' => 'fieldset',
      '#title' => t('Site tasks'),
      '#prefix' => '<div class="container-inline">',
      '#suffix' => '</div>',
    );
    $options = array();

    foreach (hosting_available_tasks('site') as $task => $array) {
      // At this stage we only want to handle simple tasks, the presense of a
      // specific task form means there are other options for this tasks.
      $func = 'hosting_task_' . $task . '_form';
      if (!function_exists($func) && user_access('create '. $task .' task')) {
        $options[$task] = $array['title'];
      }
    }
    $form['options']['task'] = array(
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => 'backup',
    );
    $form['options']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Add to queue'),
      '#submit' => array('hosting_site_list_form_submit'),
    );

    $sites = array();
    while ($node = db_fetch_object($result)) {
      $sites[$node->nid] = '';
      $form['site'][$node->nid] = array('#value' => l($node->title, 'node/' . $node->nid));
      $form['profile'][$node->nid] =  array('#value' => ($node->profile) ? _hosting_node_link($node->profile) : t('n/a'));
      $form['language'][$node->nid] = array('#value' => ($node->site_language) ? _hosting_language_name($node->site_language) : t('n/a'));
      $form['created'][$node->nid] =  array('#value' => t("@interval ago", array('@interval' => format_interval(time() - $node->created, 1))));
      if (sizeof($platforms) > 1) {
        $form['platform'][$node->nid] = array('#value' => ($node->platform) ? _hosting_node_link($node->platform) : t('n/a'));
      }
      $form['site_class'][$node->nid] = array('#value' => _hosting_site_list_class($node, $node->verified));
    }
    $form['sites'] = array('#type' => 'checkboxes', '#options' => $sites);
    $form['pager'] = array('#value' => theme('pager', NULL, 25, 1));
    $form['#theme'] = 'hosting_site_list';
    $form['#action'] = url('hosting/sites');
    return $form;
  }
  elseif ($step == 2) {
    $task = $form_state['values']['task'];
    $tasks = hosting_available_tasks('site');

    $title = array(
      'passed' => t("The following sites will be processed"),
      'failed' => t("The following sites failed validation checks and will not be processed")
    );
    foreach (array('passed', 'failed') as $type) {
      if (sizeof($form_state['storage'][$type])) {
        foreach ($form_state['storage'][$type] as $site_id => $url) {
          $row = array(
            'data' => array(
              array('data' => l($url, 'node/'.$site_id), 'class' => 'hosting-status'),
            ),
            'class' => ($type == 'passed' ? 'hosting-success' : 'hosting-error'),
          );
          $rows[] = $row;
        }
      }
    }

    $header = array(t('Site'));
    $form['sites_test'] = array(
      '#value' => theme('table', $header, $rows)
    );

    if (sizeof($form_state['storage']['failed']) && sizeof($form_state['storage']['passed'])) {
      drupal_set_message(t('The task @task is not able to be performed on all the sites selected, the sites below that failed will not be added to the queue.', array('@task' => $task)), 'warning');
    }
    elseif (sizeof($form_state['storage']['failed'])) {
      drupal_set_message(t('The task @task is not able to be performed on any of the selected sites.', array('@task' => $task)), 'error');
      $form['return_link'] = array('#value' => l('Return to site listing', 'hosting/sites'));
      return $form;
    }

    $form['help'] = array('#value' => $tasks[$task]['description']);

    $question = t('Are you sure you want to perform the "@task" task on each of the following sites?', array('@task' => $tasks[$task]['title']));
    return confirm_form($form, $question, 'hosting/sites', '', $tasks[$task]['title']);
  }
}
/**
 * Validate hosting_site_list form submissions.
 */
function hosting_site_list_form_validate($form, &$form_state) {
  if (isset($form_state['values']['sites'])) {
    $sites = array_filter($form_state['values']['sites']);
    if (count($sites) == 0) {
      form_set_error('', t('No sites selected.'));
    }
  }
}

/**
 * Process hosting_site_list form submissions.
 */
function hosting_site_list_form_submit($form, &$form_state) {
  $step = isset($form_state['storage']['step']) ? $form_state['storage']['step'] : 1;

  $task = $form_state['values']['task'];
  switch ($step) {
    case 1:
      $form_state['storage']['task'] = $task;
      // Verify tasks can be performed on each site.
      $tasks = hosting_available_tasks('site');

      // Filter out unchecked sites
      $sites = array_filter($form_state['values']['sites']);

      $operations = array();
      foreach ($sites as $site) {
        $operations[] = array('hosting_sites_batch_process',
          array($site, $task));
      }
      if (sizeof($operations)) {
        $batch = array(
          'operations' => $operations,
          'title' => t('Processing'),
          'progress_message' => t('Evaluated @current out of @total sites.'),
          'error_message' => t('The update has encountered an error.'),
        );
        batch_set($batch);
      }
      break;
    case 2:
      $values = $form_state['values'];
      foreach ($form_state['storage']['passed'] as $site_id => $url) {
        hosting_add_task($site_id, $form_state['storage']['task'], $values['parameters']);
      }
      unset($form_state['storage']);
      $step = 0;
      drupal_set_message(t('The task @task will be applied to the selected sites and have been added to the task queue.', array('@task' => $form_state['storage']['task'])));
      break;
  }
  $form_state['storage']['step'] = $step + 1;
}

function hosting_sites_batch_process($site_id, $task, &$context) {
  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
  }

  $site = node_load($site_id);
  $batch =& batch_get();

  if (hosting_task_menu_access($site, $task)) {
    $batch['form_state']['storage']['passed'][$site->nid] = $site->title;
  }
  else {
    $batch['form_state']['storage']['failed'][$site->nid] = $site->title;
  }
}

/**
 * Implementation of hook_theme().
 */
function hosting_site_theme() {
  return array(
    'hosting_site_list' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

/**
 * Build the site list form.
 */
function theme_hosting_site_list($form) {
  // If there are rows in this form, then $form['site'] contains a list of
  // the title form elements.
  $has_posts = isset($form['site']) && is_array($form['site']);
  $select_header = $has_posts ? theme('table_select_header_cell') : '';
  $header = array(
    $select_header,
    array('data' => t('Site'), 'field' => 'title'),
    array('data' => t('Profile'), 'field' => 'profile'),
    array('data' => t('Language'), 'field' => 'site_language'),
    array('data' => t('Created'), 'field' => 'created', 'sort' => 'desc'),
  );
  if (isset($form['platform'])) {
    $header[] = array('data' => t('Platform'), 'field' => 'platform');
  }
  $output = '';

  $output .= drupal_render($form['options']);
  if ($has_posts) {
    foreach (element_children($form['site']) as $key) {
      $row = array();
      $row[] = drupal_render($form['sites'][$key]);
      $row[] = array('data' => drupal_render($form['site'][$key]), 'class'=> 'hosting-status');
      $row[] = drupal_render($form['profile'][$key]);
      $row[] = drupal_render($form['language'][$key]);
      $row[] = drupal_render($form['created'][$key]);
      if (isset($form['platform'])) {
        $row[] = drupal_render($form['platform'][$key]);
      }
      $rows[] = array('data' => $row, 'class' => drupal_render($form['site_class'][$key]));
    }

  }
  else {
    $rows[] = array(array('data' => t('No sites available.'), 'colspan' => sizeof($header)));
  }

  $output .= theme('table',  $header, $rows, array('class' => 'hosting-table'));
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}


/**
 * Define the classes that correspond to the site status.
 * @see _hosting_site_status()
 */
function _hosting_site_list_class($node, $verified = null) {
  $status = (is_numeric($node)) ? $node : $node->site_status;
  static $classes = array(
    HOSTING_SITE_QUEUED => "hosting-queue",
    HOSTING_SITE_ENABLED => "hosting-success",
    HOSTING_SITE_DELETED => "hosting-error",
    HOSTING_SITE_DISABLED => "hosting-error",
  );
  if (($status == HOSTING_SITE_ENABLED) && (!$verified)) {
    return 'hosting-warning';
  }

  return $classes[$status];
}

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


function hosting_site_preprocess_views_view_table(&$variables) {
  $view = $variables['view'];
  if ($view->plugin_name == 'hosting_site_list') {
    foreach ($view->result as $num => $result) {
      if (isset($result->hosting_site_status) && isset($result->hosting_site_verified)) {
        $variables['row_classes'][$num][] = _hosting_site_list_class($result->hosting_site_status, $result->hosting_site_verified);
      }
    }
  }
  $variables['class'] .= " hosting-table";
}