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