cleaner version of planetlab vicci toggling
[plewww.git] / modules / planetlab.module
1 <?php // -*-php-*-
2   //
3   // PlanetLab authentication and integration with Drupal
4   //
5   // Mark Huang <mlhuang@cs.princeton.edu>
6   // Copyright (C) 2006 The Trustees of Princeton University
7   //
8   // $Id$
9   //
10
11 require_once 'plc_config.php';
12 require_once 'plc_session.php';
13 require_once 'plc_functions.php';
14
15 drupal_set_html_head('<link href="/planetlab/css/plc_style.css" rel="stylesheet" type="text/css"/>');
16
17 function planetlab_help($section) {
18   switch ($section) {
19   case 'admin/modules#description':
20     return t('Enables authenticated login via a PlanetLab API server.');
21   }
22 }
23
24 function planetlab_info($field = 0) {
25   $info['name'] = 'PlanetLab';
26
27   if ($field) {
28     return $info[$field];
29   } else {
30     return $info;
31   }
32 }
33
34 function planetlab_menu($may_cache) {
35   $items = array();
36
37   if ($may_cache) {
38     $items[] = array(
39                      'path' => 'planetlab/common/logout',
40                      'title' => t('Logout of %s', array('%s' => variable_get('site_name', 'local'))),
41                      'callback' => 'planetlab_logout',
42                      'access' => TRUE,
43                      'type' => MENU_CALLBACK
44                      );
45     $items[] = array(
46                      'path' => 'db',
47                      'title' => variable_get('site_name', 'local'),
48                      'callback' => 'planetlab_page',
49                      'access' => TRUE,
50                      'type' => MENU_CALLBACK
51                      );
52   }
53
54   return $items;
55 }
56
57 //////////////////// formatting helpers - specific to module presentation
58 function ul_start () { return '<ul class="menu">'; }
59 function ul_end () { return '</ul>'; }
60 function leaf($text) { return '<li class="leaf">' . $text . '</li>'; }
61 function expanded($text) { return '<li class="expanded">' . $text . '</li>'; }
62 function p($text) { return '<p>' . $text . '</p>'; }
63
64 # this should get embedded into a ul_start()/ul_end() pair
65 function plc_my_site_links() {
66   $html = '';
67   $sites = plc_my_sites();
68   if (count($sites)>1) foreach ($sites as $site) {
69       $html .= leaf( href(l_site($site['site_id']),$site['abbreviated_name']));
70     } else {
71     $html .= leaf( href(l_site(plc_my_site_id()),"My Site"));
72   }
73   return $html;
74 }
75
76 // ditto
77 function plc_my_node_links () {
78   $html = '';
79   if (count (plc_my_site_ids()) == 1) {
80     $html .= leaf( href (l_nodes_my_site() ,"My Site Nodes"));
81   } else {
82     $html .= leaf( href (l_nodes_all_my_site(),"All My Sites Nodes"));
83   }
84   return $html;
85 }
86
87 // fake theme to look like menu
88 function menu_theme ($menu) {
89   $result = '';
90   $result .= ul_start();
91   foreach ($menu as $item) $result .= $item;
92   $result .= ul_end();
93   return $result;
94 }
95
96 function planetlab_block($op = 'list', $delta = 0, $edit = array()) {
97   global $user, $plc;
98
99   if ($op == 'list') {
100     $blocks[0]['info'] = t('PlanetLab login');
101
102     return $blocks;
103
104   } else if ($op == 'view') {
105     $block = array();
106
107     if ($plc->hide_planetlab_block) {
108       // do nothing
109       // this is a private hook from the Vicci module to hide the planetlab module
110     } else if (!$plc->person) {
111       // Force login via HTTPS
112       unset($_GET['time']);
113       $form['#action'] = "https://" . $_SERVER['HTTP_HOST'] . url($_GET['q'], drupal_get_destination());
114       $form['#id'] = 'planetlab-login-form';
115       $form['name'] = array('#type' => 'textfield',
116                             '#title' => t('E-mail'),
117                             '#maxlength' => 60,
118                             '#size' => 25,
119                             '#required' => TRUE,
120                             );
121       $form['pass'] = array('#type' => 'password',
122                             '#title' => t('Password'),
123                             '#size' => 25,
124                             '#required' => TRUE,
125                             );
126       $form['submit'] = array('#type' => 'submit',
127                               '#value' => t('Log in'),
128                               );
129
130       $block['subject'] = t('%s login', array('%s' => variable_get('site_name', 'local')));
131       $block['content'] = drupal_get_form('planetlab_login_block', $form, 'planetlab_login');
132       $block['content'] .= p('');
133       $block['content'] .= p( href (l_reset_password(),"Forgot your password?") );
134       $block['content'] .= p( href(l_person_register(),"Create an account") );
135       $block['content'] .= p( href(l_site_register(),"File a site registration") );
136     } else {
137       $block['subject'] = truncate($plc->person['email'],30);
138
139       //////////////////// Logout 
140       $bullet_item = '';
141       if ($user->uid) {
142         // Drupal logout (destroys the session and cleans up $user)
143         // Thierry unclear when this triggers, I suspect this is obsolete
144         $bullet_item .= l(t('Logout of %s', 
145                           array('%s' => variable_get('site_name', 'local'))), 'logout');
146       } else {
147         // PlanetLab logout (just destroy the session)
148         $bullet_item .= href (l_logout(),'Logout');
149       }
150       $bullet_item .= ul_start();
151       // logout 
152       if ( $plc->alt_person && $plc->alt_auth) {
153         $email = truncate($plc->person['email'],20); 
154         $bullet_item .= leaf( href( l_sulogout(),"Un-become $email"));
155       } 
156       $bullet_item .= ul_end();
157       $items []= expanded ($bullet_item);
158
159       //////////////////// accounts
160       $bullet_item = '';
161       $bullet_item .=  l_person_t(plc_my_person_id(),"My Account");
162       $bullet_item .= ul_start();
163       if (plc_is_admin() || plc_is_pi()) 
164         $bullet_item .= leaf( href( l_persons_site(plc_my_site_id()), "My Site Accounts"));
165       if (plc_is_admin()) {
166         $bullet_item .= leaf(href(l_persons_peer('local'),'Local Accounts (slow)'));
167         $bullet_item .= leaf(href(l_persons(),'All Accounts (slow)'));
168       }
169         
170       $bullet_item .= ul_end();
171       $items [] = expanded($bullet_item);
172
173       //////////////////// Sites
174       $bullet_item = '';
175       $bullet_item .= href(l_sites(),"Sites");
176       $bullet_item .= ul_start();
177       $bullet_item .= plc_my_site_links();
178       if ( plc_is_admin() ) 
179         $bullet_item .= leaf( href(l_sites_pending(),"Pending Requests"));
180       $bullet_item .= ul_end();
181       $items[] = expanded($bullet_item);
182
183       //////////////////// Nodes
184       $bullet_item = '';
185       $bullet_item .= href(l_nodes(),"Nodes");
186       $bullet_item .= ul_start();
187       $bullet_item .= plc_my_node_links();
188       if (plc_is_admin() || plc_is_pi() || plc_is_tech()) 
189         $bullet_item .= leaf( href (l_register_node(),"Register Node"));
190       $bullet_item .= ul_end();
191       $items [] = expanded($bullet_item);
192
193       //////////////////// Slices
194       $bullet_item = '';
195       //if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) ) 
196       if (plc_is_admin()) {
197         $bullet_item .= href(l_slices(),"Slices");
198       } else {
199         $bullet_item .= href(l_slices(),"My Slices");
200       }
201       $bullet_item .= ul_start();
202       if (plc_is_admin()) 
203         $bullet_item .= leaf ( href(l_slices_my_site(), 'My Site Slices'));
204       if( plc_is_admin() || plc_is_pi() ) {
205         $bullet_item .= leaf(href(l_slice_add(),"Create Slice"));
206       }
207       if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) ) 
208         $bullet_item .= leaf(href(l_sirius(),"Sirius"));
209       $bullet_item .= ul_end();
210       $items [] = expanded($bullet_item);
211
212       //////////////////// Admin
213       if( plc_is_admin() || plc_is_pi() ) {
214         $bullet_item = '';
215         $bullet_item .= href(l_admin(),"Admin search");
216         $bullet_item .= ul_start();
217         if ( plc_is_admin() )
218           $bullet_item .= leaf( href (l_node_add(),"Add Node"));
219         $bullet_item .= leaf( href( l_tags(),"Tags"));
220         $bullet_item .= leaf( href( l_nodegroups(),"Node groups"));
221         $bullet_item .= leaf (href(l_peers(),'Peers'));
222         if ( plc_is_admin() )
223           $bullet_item .= leaf (href(l_events(),'Events'));
224         $bullet_item .= ul_end();
225         $items [] = expanded($bullet_item);
226       }
227
228       $bullet_item = '';
229       $bullet_item .= href(l_about(),'About MyPLC');
230       $bullet_item .= ul_start();
231       $bullet_item .= leaf ( href (l_doc_plcapi(),"PLCAPI doc"));
232       $bullet_item .= leaf ( href (l_doc_nmapi(),"NMAPI doc"));
233       $bullet_item .= ul_end();
234       $items[] = expanded($bullet_item);
235
236       //$block['content'] = theme('list_item', $items);
237       $block['content'] = menu_theme($items);
238     }
239
240     /*
241      ob_start();
242      print '<pre>';
243      print_r($_SESSION);
244      print '</pre>';
245      $block['content'] .= ob_get_contents();
246      ob_end_clean();
247     */
248
249     return $block;
250   }
251 }
252
253 function planetlab_login_validate($form_id, $form_values) {
254   global $user, $plc;
255
256   if ($form_values['name'] && $form_values['pass']) {
257     // Drupal login succeeded
258     if (($user = user_authenticate($form_values['name'], trim($form_values['pass']))) &&
259         $user->uid) {
260       return;
261     }
262
263     $plc = new PLCSession($form_values['name'], $form_values['pass']);
264
265     // PlanetLab login failed
266     if (!$plc->person) {
267       form_set_error('login', t('Sorry. Unrecognized username or password.'));
268       watchdog('planetlab', t('Login attempt failed for %user.', array('%user' => theme('placeholder', $form_values['name']))));
269     }
270
271     // PlanetLab login succeeded
272     else {
273       // Login admins to Drupal as the superuser
274       if (in_array('admin', $plc->person['roles'])) {
275         $user = user_load(array('uid' => 1));
276       }
277     }
278   }
279 }
280
281 function planetlab_login_submit($form_id, $form_values) {
282   global $plc;
283
284   // Our referring page is encased in a query string of the form
285   // "destination=referrer".
286   parse_str(drupal_get_destination()); // => $destination
287
288   // The referrer itself is a URL path with the original query string,
289   // e.g. "referer.php?query".
290   extract(parse_url($destination)); // => $query
291
292   // Which we then have to parse again as a query string.
293   parse_str($query); // => $url
294
295   if ($plc->person) {
296     // To handle the edge case where this function is called during a
297     // bootstrap, check for the existence of t().
298     if (function_exists('t')) {
299       $message = t('Session opened for %name.', array('%name' => theme('placeholder', $plc->person['email'])));
300     }
301     else {
302       $message = "Session opened for ". check_plain($person['email']);
303     }
304     watchdog('planetlab', $message);
305
306     if (empty($url)) {
307       // Create a timestamped final URL so that browsers don't return the user to
308       // a cached page (where it would appear as if they never logged in or out).
309       return array('time='. time());
310     } else {
311       // Make sure that redirections are always local
312       $url = urldecode($url);
313       if ($url[0] != "/") {
314         $url = "/$url";
315       }
316       header("Location: $url");
317       exit();
318     }
319   }
320 }
321
322 function planetlab_logout() {
323   global $plc;
324
325   if ($plc->person) {
326     // Invalidate PlanetLab session
327     $plc->logout();
328     watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
329   }
330
331   // Destroy the current session:
332   session_destroy();
333
334   // The time prevents caching.
335   drupal_goto(NULL, 'time='. time());
336 }
337
338 function planetlab_user($type, &$edit, &$user, $category = NULL) {
339   switch ($type) {
340   case 'logout':
341     if ($plc->person) {
342       $plc->logout();
343       watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
344     }
345     break;
346   }
347 }
348
349 function planetlab_page() {
350   $path = $_SERVER['DOCUMENT_ROOT'] . preg_replace('/^db\//', '/planetlab/', $_GET['q']);
351
352   // error_log("Requested " . $_GET['q'] . " -> $path");
353
354   if (is_dir($path)) {
355     foreach (array('index.php', 'index.html', 'index.htm') as $index) {
356       if (is_file($path . "/$index")) {
357         $path .= "/$index";
358         break;
359       }
360     }
361   }
362
363   if (is_file($path)) {
364     if (preg_match('/.php$/', $path)) {
365       ob_start();
366       include $path;
367       $output = ob_get_contents();
368       ob_end_clean();
369     } else {
370       $output = file_get_contents($path);
371     }
372     return $output;
373   }
374             
375   drupal_not_found();
376 }
377
378 function theme_planetlab($content) {
379   return $content;
380 }
381
382 ?>