478c5c00348ed7a9e949f3b29f12641e858901b0
[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->person) {
108       // Force login via HTTPS
109       unset($_GET['time']);
110       $form['#action'] = "https://" . $_SERVER['HTTP_HOST'] . url($_GET['q'], drupal_get_destination());
111       $form['#id'] = 'planetlab-login-form';
112       $form['name'] = array('#type' => 'textfield',
113                             '#title' => t('E-mail'),
114                             '#maxlength' => 60,
115                             '#size' => 25,
116                             '#required' => TRUE,
117                             );
118       $form['pass'] = array('#type' => 'password',
119                             '#title' => t('Password'),
120                             '#size' => 25,
121                             '#required' => TRUE,
122                             );
123       $form['submit'] = array('#type' => 'submit',
124                               '#value' => t('Log in'),
125                               );
126
127       $block['subject'] = t('%s login', array('%s' => variable_get('site_name', 'local')));
128       $block['content'] = drupal_get_form('planetlab_login_block', $form, 'planetlab_login');
129       $block['content'] .= p('');
130       $block['content'] .= p( href (l_reset_password(),"Forgot your password?") );
131       $block['content'] .= p( href(l_person_register(),"Create an account") );
132       $block['content'] .= p( href(l_site_register(),"File a site registration") );
133     } else if ((PLC_SHORTNAME!="VICCI") || (plc_advanced())) {
134       // for now, only pay attention to plc_advanced() on vicci
135
136       $block['subject'] = truncate($plc->person['email'],30);
137
138       //////////////////// Logout 
139       $bullet_item = '';
140       if ($user->uid) {
141         // Drupal logout (destroys the session and cleans up $user)
142         // Thierry unclear when this triggers, I suspect this is obsolete
143         $bullet_item .= l(t('Logout of %s', 
144                           array('%s' => variable_get('site_name', 'local'))), 'logout');
145       } else {
146         // PlanetLab logout (just destroy the session)
147         $bullet_item .= href (l_logout(),'Logout');
148       }
149       $bullet_item .= ul_start();
150       // logout 
151       if ( $plc->alt_person && $plc->alt_auth) {
152         $email = truncate($plc->person['email'],20); 
153         $bullet_item .= leaf( href( l_sulogout(),"Un-become $email"));
154       } 
155       $bullet_item .= ul_end();
156       $items []= expanded ($bullet_item);
157
158       //////////////////// accounts
159       $bullet_item = '';
160       $bullet_item .=  l_person_t(plc_my_person_id(),"My Account");
161       $bullet_item .= ul_start();
162       if (plc_is_admin() || plc_is_pi()) 
163         $bullet_item .= leaf( href( l_persons_site(plc_my_site_id()), "My Site Accounts"));
164       if (plc_is_admin()) {
165         $bullet_item .= leaf(href(l_persons_peer('local'),'Local Accounts (slow)'));
166         $bullet_item .= leaf(href(l_persons(),'All Accounts (slow)'));
167       }
168         
169       $bullet_item .= ul_end();
170       $items [] = expanded($bullet_item);
171
172       //////////////////// Sites
173       $bullet_item = '';
174       $bullet_item .= href(l_sites(),"Sites");
175       $bullet_item .= ul_start();
176       $bullet_item .= plc_my_site_links();
177       if ( plc_is_admin() ) 
178         $bullet_item .= leaf( href(l_sites_pending(),"Pending Requests"));
179       $bullet_item .= ul_end();
180       $items[] = expanded($bullet_item);
181
182       //////////////////// Nodes
183       $bullet_item = '';
184       $bullet_item .= href(l_nodes(),"Nodes");
185       $bullet_item .= ul_start();
186       $bullet_item .= plc_my_node_links();
187       if (plc_is_admin() || plc_is_pi() || plc_is_tech()) 
188         $bullet_item .= leaf( href (l_register_node(),"Register Node"));
189       $bullet_item .= ul_end();
190       $items [] = expanded($bullet_item);
191
192       //////////////////// Slices
193       $bullet_item = '';
194       //if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) ) 
195       if (plc_is_admin()) {
196         $bullet_item .= href(l_slices(),"Slices");
197       } else {
198         $bullet_item .= href(l_slices(),"My Slices");
199       }
200       $bullet_item .= ul_start();
201       if (plc_is_admin()) 
202         $bullet_item .= leaf ( href(l_slices_my_site(), 'My Site Slices'));
203       if( plc_is_admin() || plc_is_pi() ) {
204         $bullet_item .= leaf(href(l_slice_add(),"Create Slice"));
205       }
206       if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) ) 
207         $bullet_item .= leaf(href(l_sirius(),"Sirius"));
208       $bullet_item .= ul_end();
209       $items [] = expanded($bullet_item);
210
211       //////////////////// Admin
212       if( plc_is_admin() || plc_is_pi() ) {
213         $bullet_item = '';
214         $bullet_item .= href(l_admin(),"Admin search");
215         $bullet_item .= ul_start();
216         if ( plc_is_admin() )
217           $bullet_item .= leaf( href (l_node_add(),"Add Node"));
218         $bullet_item .= leaf( href( l_tags(),"Tags"));
219         $bullet_item .= leaf( href( l_nodegroups(),"Node groups"));
220         $bullet_item .= leaf (href(l_peers(),'Peers'));
221         if ( plc_is_admin() )
222           $bullet_item .= leaf (href(l_events(),'Events'));
223         $bullet_item .= ul_end();
224         $items [] = expanded($bullet_item);
225       }
226
227       $bullet_item = '';
228       $bullet_item .= href(l_about(),'About MyPLC');
229       $bullet_item .= ul_start();
230       $bullet_item .= leaf ( href (l_doc_plcapi(),"PLCAPI doc"));
231       $bullet_item .= leaf ( href (l_doc_nmapi(),"NMAPI doc"));
232       $bullet_item .= ul_end();
233       $items[] = expanded($bullet_item);
234
235       //$block['content'] = theme('list_item', $items);
236       $block['content'] = menu_theme($items);
237     }
238
239     /*
240      ob_start();
241      print '<pre>';
242      print_r($_SESSION);
243      print '</pre>';
244      $block['content'] .= ob_get_contents();
245      ob_end_clean();
246     */
247
248     return $block;
249   }
250 }
251
252 function planetlab_login_validate($form_id, $form_values) {
253   global $user, $plc;
254
255   if ($form_values['name'] && $form_values['pass']) {
256     // Drupal login succeeded
257     if (($user = user_authenticate($form_values['name'], trim($form_values['pass']))) &&
258         $user->uid) {
259       return;
260     }
261
262     $plc = new PLCSession($form_values['name'], $form_values['pass']);
263
264     // PlanetLab login failed
265     if (!$plc->person) {
266       form_set_error('login', t('Sorry. Unrecognized username or password.'));
267       watchdog('planetlab', t('Login attempt failed for %user.', array('%user' => theme('placeholder', $form_values['name']))));
268     }
269
270     // PlanetLab login succeeded
271     else {
272       // Login admins to Drupal as the superuser
273       if (in_array('admin', $plc->person['roles'])) {
274         $user = user_load(array('uid' => 1));
275       }
276     }
277   }
278 }
279
280 function planetlab_login_submit($form_id, $form_values) {
281   global $plc;
282
283   // Our referring page is encased in a query string of the form
284   // "destination=referrer".
285   parse_str(drupal_get_destination()); // => $destination
286
287   // The referrer itself is a URL path with the original query string,
288   // e.g. "referer.php?query".
289   extract(parse_url($destination)); // => $query
290
291   // Which we then have to parse again as a query string.
292   parse_str($query); // => $url
293
294   if ($plc->person) {
295     // To handle the edge case where this function is called during a
296     // bootstrap, check for the existence of t().
297     if (function_exists('t')) {
298       $message = t('Session opened for %name.', array('%name' => theme('placeholder', $plc->person['email'])));
299     }
300     else {
301       $message = "Session opened for ". check_plain($person['email']);
302     }
303     watchdog('planetlab', $message);
304
305     if (empty($url)) {
306       // Create a timestamped final URL so that browsers don't return the user to
307       // a cached page (where it would appear as if they never logged in or out).
308       return array('time='. time());
309     } else {
310       // Make sure that redirections are always local
311       $url = urldecode($url);
312       if ($url[0] != "/") {
313         $url = "/$url";
314       }
315       header("Location: $url");
316       exit();
317     }
318   }
319 }
320
321 function planetlab_logout() {
322   global $plc;
323
324   if ($plc->person) {
325     // Invalidate PlanetLab session
326     $plc->logout();
327     watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
328   }
329
330   // Destroy the current session:
331   session_destroy();
332
333   // The time prevents caching.
334   drupal_goto(NULL, 'time='. time());
335 }
336
337 function planetlab_user($type, &$edit, &$user, $category = NULL) {
338   switch ($type) {
339   case 'logout':
340     if ($plc->person) {
341       $plc->logout();
342       watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
343     }
344     break;
345   }
346 }
347
348 function planetlab_page() {
349   $path = $_SERVER['DOCUMENT_ROOT'] . preg_replace('/^db\//', '/planetlab/', $_GET['q']);
350
351   // error_log("Requested " . $_GET['q'] . " -> $path");
352
353   if (is_dir($path)) {
354     foreach (array('index.php', 'index.html', 'index.htm') as $index) {
355       if (is_file($path . "/$index")) {
356         $path .= "/$index";
357         break;
358       }
359     }
360   }
361
362   if (is_file($path)) {
363     if (preg_match('/.php$/', $path)) {
364       ob_start();
365       include $path;
366       $output = ob_get_contents();
367       ob_end_clean();
368     } else {
369       $output = file_get_contents($path);
370     }
371     return $output;
372   }
373             
374   drupal_not_found();
375 }
376
377 function theme_planetlab($content) {
378   return $content;
379 }
380
381 ?>