bugfix: the slice page was broken when nobody is in slice
[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 (property_exists($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 (ko)"));
190       }
191       $bullet_item .= ul_end();
192       $items [] = expanded($bullet_item);
193
194       //////////////////// Slices
195       $bullet_item = '';
196       //if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) )
197       if (plc_is_admin()) {
198         $bullet_item .= href(l_slices(),"Slices");
199       } else {
200         $bullet_item .= href(l_slices(),"My Slices");
201       }
202       $bullet_item .= ul_start();
203       if (plc_is_admin())
204         $bullet_item .= leaf ( href(l_slices_my_site(), 'My Site Slices'));
205       if( plc_is_admin() || plc_is_pi() ) {
206         $bullet_item .= leaf(href(l_slice_add(),"Create Slice"));
207       }
208       if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) )
209         $bullet_item .= leaf(href(l_sirius(),"Sirius"));
210       $bullet_item .= ul_end();
211       $items [] = expanded($bullet_item);
212
213       //////////////////// Admin
214       if( plc_is_admin() || plc_is_pi() ) {
215         $bullet_item = '';
216         $bullet_item .= href(l_admin(),"Admin search");
217         $bullet_item .= ul_start();
218         if ( plc_is_admin() )
219           $bullet_item .= leaf( href (l_node_add(),"Add Node"));
220         $bullet_item .= leaf( href( l_tags(),"Tags"));
221         $bullet_item .= leaf( href( l_nodegroups(),"Node groups"));
222         $bullet_item .= leaf (href(l_peers(),'Peers'));
223         if ( plc_is_admin() )
224           $bullet_item .= leaf (href(l_events(),'Events'));
225         $bullet_item .= ul_end();
226         $items [] = expanded($bullet_item);
227       }
228
229       $bullet_item = '';
230       $bullet_item .= href(l_about(),'About MyPLC');
231       $bullet_item .= ul_start();
232       $bullet_item .= leaf ( href (l_doc_plcapi(),"PLCAPI doc"));
233       $bullet_item .= leaf ( href (l_doc_nmapi(),"NMAPI doc"));
234       $bullet_item .= ul_end();
235       $items[] = expanded($bullet_item);
236
237       //$block['content'] = theme('list_item', $items);
238       $block['content'] = menu_theme($items);
239     }
240
241     /*
242      ob_start();
243      print '<pre>';
244      print_r($_SESSION);
245      print '</pre>';
246      $block['content'] .= ob_get_contents();
247      ob_end_clean();
248     */
249
250     return $block;
251   }
252 }
253
254 function planetlab_login_validate($form_id, $form_values) {
255   global $user, $plc;
256
257   if ($form_values['name'] && $form_values['pass']) {
258     // Drupal login succeeded
259     if (($user = user_authenticate($form_values['name'], trim($form_values['pass']))) &&
260         $user->uid) {
261       return;
262     }
263
264     $plc = new PLCSession($form_values['name'], $form_values['pass']);
265
266     // PlanetLab login failed
267     if (!$plc->person) {
268       form_set_error('login', t('Sorry. Unrecognized username or password.'));
269       watchdog('planetlab', t('Login attempt failed for %user.', array('%user' => theme('placeholder', $form_values['name']))));
270     }
271
272     // PlanetLab login succeeded
273     else {
274       // Login admins to Drupal as the superuser
275       if (in_array('admin', $plc->person['roles'])) {
276         $user = user_load(array('uid' => 1));
277       }
278     }
279   }
280 }
281
282 function planetlab_login_submit($form_id, $form_values) {
283   global $plc;
284
285   // Our referring page is encased in a query string of the form
286   // "destination=referrer".
287   parse_str(drupal_get_destination(), $variables);
288   $destination = $variables['destination'];
289
290   // The referrer itself is a URL path with the original query string,
291   // e.g. "referer.php?query".
292   extract(parse_url($destination)); // => $query
293
294   // Which we then have to parse again as a query string.
295   parse_str($query, $variables);
296   $url = $variables['url'];
297
298   if ($plc->person) {
299     // To handle the edge case where this function is called during a
300     // bootstrap, check for the existence of t().
301     if (function_exists('t')) {
302       $message = t('Session opened for %name.', array('%name' => theme('placeholder', $plc->person['email'])));
303     }
304     else {
305       $message = "Session opened for ". check_plain($person['email']);
306     }
307     watchdog('planetlab', $message);
308
309     if (empty($url)) {
310       // Create a timestamped final URL so that browsers don't return the user to
311       // a cached page (where it would appear as if they never logged in or out).
312       return array('time='. time());
313     } else {
314       // Make sure that redirections are always local
315       $url = urldecode($url);
316       if ($url[0] != "/") {
317         $url = "/$url";
318       }
319       header("Location: $url");
320       exit();
321     }
322   }
323 }
324
325 function planetlab_logout() {
326   global $plc;
327
328   if ($plc->person) {
329     // Invalidate PlanetLab session
330     $plc->logout();
331     watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
332   }
333
334   // Destroy the current session:
335   session_destroy();
336
337   // The time prevents caching.
338   drupal_goto(NULL, 'time='. time());
339 }
340
341 function planetlab_user($type, &$edit, &$user, $category = NULL) {
342   switch ($type) {
343   case 'logout':
344     if ($plc->person) {
345       $plc->logout();
346       watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
347     }
348     break;
349   }
350 }
351
352 function isValidFileName($file) {
353
354     /* don't allow .. and allow any "word" character \ / */
355
356     return preg_match('/^(((?:\.)(?!\.))|\w)+$/', $file);
357
358 }
359
360 function planetlab_page() {
361   $path = $_SERVER['DOCUMENT_ROOT'] . preg_replace('/^db\//', '/planetlab/', $_GET['q']);
362
363   // error_log("Requested " . $_GET['q'] . " -> $path");
364
365   if (is_dir($path)) {
366     foreach (array('index.php', 'index.html', 'index.htm') as $index) {
367       if (is_file($path . "/$index")) {
368         $path .= "/$index";
369         break;
370       }
371     }
372   }
373
374   if (is_file($path)) {
375     if (preg_match('/.php$/', $path)) {
376       ob_start();
377       include $path;
378       $output = ob_get_contents();
379       ob_end_clean();
380     } else {
381          if (isValidFileName($path)) {
382             $output = file_get_contents($path);
383          }
384          else {
385             $output = "";
386          }
387     }
388     return $output;
389   }
390
391   drupal_not_found();
392 }
393
394 function theme_planetlab($content) {
395   return $content;
396 }
397
398 ?>