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 error_reporting(0);
11
12 require_once 'plc_config.php';
13 require_once 'plc_session.php';
14 require_once 'plc_functions.php';
15
16 drupal_set_html_head('<link href="/planetlab/css/plc_style.css" rel="stylesheet" type="text/css"/>');
17
18 function planetlab_help($section) {
19   switch ($section) {
20   case 'admin/modules#description':
21     return t('Enables authenticated login via a PlanetLab API server.');
22   }
23 }
24
25 function planetlab_info($field = 0) {
26   $info['name'] = 'PlanetLab';
27
28   if ($field) {
29     return $info[$field];
30   } else {
31     return $info;
32   }
33 }
34
35 function planetlab_menu($may_cache) {
36   $items = array();
37
38   if ($may_cache) {
39     $items[] = array(
40                      'path' => 'planetlab/common/logout',
41                      'title' => t('Logout of %s', array('%s' => variable_get('site_name', 'local'))),
42                      'callback' => 'planetlab_logout',
43                      'access' => TRUE,
44                      'type' => MENU_CALLBACK
45                      );
46     $items[] = array(
47                      'path' => 'db',
48                      'title' => variable_get('site_name', 'local'),
49                      'callback' => 'planetlab_page',
50                      'access' => TRUE,
51                      'type' => MENU_CALLBACK
52                      );
53   }
54
55   return $items;
56 }
57
58 //////////////////// formatting helpers - specific to module presentation
59 function ul_start () { return '<ul class="menu">'; }
60 function ul_end () { return '</ul>'; }
61 function leaf($text) { return '<li class="leaf">' . $text . '</li>'; }
62 function expanded($text) { return '<li class="expanded">' . $text . '</li>'; }
63 function p($text) { return '<p>' . $text . '</p>'; }
64
65 # this should get embedded into a ul_start()/ul_end() pair
66 function plc_my_site_links() {
67   $html = '';
68   $sites = plc_my_sites();
69   if (count($sites)>1) foreach ($sites as $site) {
70       $html .= leaf( href(l_site($site['site_id']),$site['abbreviated_name']));
71     } else {
72     $html .= leaf( href(l_site(plc_my_site_id()),"My Site"));
73   }
74   return $html;
75 }
76
77 // ditto
78 function plc_my_node_links () {
79   $html = '';
80   if (count (plc_my_site_ids()) == 1) {
81     $html .= leaf( href (l_nodes_my_site() ,"My Site Nodes"));
82   } else {
83     $html .= leaf( href (l_nodes_all_my_site(),"All My Sites Nodes"));
84   }
85   return $html;
86 }
87
88 // fake theme to look like menu
89 function menu_theme ($menu) {
90   $result = '';
91   $result .= ul_start();
92   foreach ($menu as $item) $result .= $item;
93   $result .= ul_end();
94   return $result;
95 }
96
97 function planetlab_block($op = 'list', $delta = 0, $edit = array()) {
98   global $user, $plc;
99
100   if ($op == 'list') {
101     $blocks[0]['info'] = t('PlanetLab login');
102
103     return $blocks;
104
105   } else if ($op == 'view') {
106     $block = array();
107
108     if ($plc->hide_planetlab_block) {
109       // do nothing
110       // this is a private hook from the Vicci module to hide the planetlab module
111     } else if (!$plc->person) {
112       // Force login via HTTPS
113       unset($_GET['time']);
114       $form['#action'] = "https://" . $_SERVER['HTTP_HOST'] . url($_GET['q'], drupal_get_destination());
115       $form['#id'] = 'planetlab-login-form';
116       $form['name'] = array('#type' => 'textfield',
117                             '#title' => t('E-mail'),
118                             '#maxlength' => 60,
119                             '#size' => 25,
120                             '#required' => TRUE,
121                             );
122       $form['pass'] = array('#type' => 'password',
123                             '#title' => t('Password'),
124                             '#size' => 25,
125                             '#required' => TRUE,
126                             );
127       $form['submit'] = array('#type' => 'submit',
128                               '#value' => t('Log in'),
129                               );
130
131       $block['subject'] = t('%s login', array('%s' => variable_get('site_name', 'local')));
132       $block['content'] = drupal_get_form('planetlab_login_block', $form, 'planetlab_login');
133       $block['content'] .= p('');
134       $block['content'] .= p( href (l_reset_password(),"Forgot your password?") );
135       $block['content'] .= p( href(l_person_register(),"Create an account") );
136       $block['content'] .= p( href(l_site_register(),"File a site registration") );
137     } else {
138       $block['subject'] = truncate($plc->person['email'],30);
139
140       //////////////////// Logout 
141       $bullet_item = '';
142       if ($user->uid) {
143         // Drupal logout (destroys the session and cleans up $user)
144         // Thierry unclear when this triggers, I suspect this is obsolete
145         $bullet_item .= l(t('Logout of %s', 
146                           array('%s' => variable_get('site_name', 'local'))), 'logout');
147       } else {
148         // PlanetLab logout (just destroy the session)
149         $bullet_item .= href (l_logout(),'Logout');
150       }
151       $bullet_item .= ul_start();
152       // logout 
153       if ( $plc->alt_person && $plc->alt_auth) {
154         $email = truncate($plc->person['email'],20); 
155         $bullet_item .= leaf( href( l_sulogout(),"Un-become $email"));
156       } 
157       $bullet_item .= ul_end();
158       $items []= expanded ($bullet_item);
159
160       //////////////////// accounts
161       $bullet_item = '';
162       $bullet_item .=  l_person_t(plc_my_person_id(),"My Account");
163       $bullet_item .= ul_start();
164       if (plc_is_admin() || plc_is_pi()) 
165         $bullet_item .= leaf( href( l_persons_site(plc_my_site_id()), "My Site Accounts"));
166       if (plc_is_admin()) {
167         $bullet_item .= leaf(href(l_persons_peer('local'),'Local Accounts (slow)'));
168         $bullet_item .= leaf(href(l_persons(),'All Accounts (slow)'));
169       }
170         
171       $bullet_item .= ul_end();
172       $items [] = expanded($bullet_item);
173
174       //////////////////// Sites
175       $bullet_item = '';
176       $bullet_item .= href(l_sites(),"Sites");
177       $bullet_item .= ul_start();
178       $bullet_item .= plc_my_site_links();
179       if ( plc_is_admin() ) 
180         $bullet_item .= leaf( href(l_sites_pending(),"Pending Requests"));
181       $bullet_item .= ul_end();
182       $items[] = expanded($bullet_item);
183
184       //////////////////// Nodes
185       $bullet_item = '';
186       $bullet_item .= href(l_nodes(),"Nodes");
187       $bullet_item .= ul_start();
188       $bullet_item .= plc_my_node_links();
189       if (plc_is_admin() || plc_is_pi() || plc_is_tech()) 
190         $bullet_item .= leaf( href (l_register_node(),"Register Node"));
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()); // => $destination
288
289   // The referrer itself is a URL path with the original query string,
290   // e.g. "referer.php?query".
291   extract(parse_url($destination)); // => $query
292
293   // Which we then have to parse again as a query string.
294   parse_str($query); // => $url
295
296   if ($plc->person) {
297     // To handle the edge case where this function is called during a
298     // bootstrap, check for the existence of t().
299     if (function_exists('t')) {
300       $message = t('Session opened for %name.', array('%name' => theme('placeholder', $plc->person['email'])));
301     }
302     else {
303       $message = "Session opened for ". check_plain($person['email']);
304     }
305     watchdog('planetlab', $message);
306
307     if (empty($url)) {
308       // Create a timestamped final URL so that browsers don't return the user to
309       // a cached page (where it would appear as if they never logged in or out).
310       return array('time='. time());
311     } else {
312       // Make sure that redirections are always local
313       $url = urldecode($url);
314       if ($url[0] != "/") {
315         $url = "/$url";
316       }
317       header("Location: $url");
318       exit();
319     }
320   }
321 }
322
323 function planetlab_logout() {
324   global $plc;
325
326   if ($plc->person) {
327     // Invalidate PlanetLab session
328     $plc->logout();
329     watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
330   }
331
332   // Destroy the current session:
333   session_destroy();
334
335   // The time prevents caching.
336   drupal_goto(NULL, 'time='. time());
337 }
338
339 function planetlab_user($type, &$edit, &$user, $category = NULL) {
340   switch ($type) {
341   case 'logout':
342     if ($plc->person) {
343       $plc->logout();
344       watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
345     }
346     break;
347   }
348 }
349
350 function isValidFileName($file) {
351
352     /* don't allow .. and allow any "word" character \ / */
353
354     return preg_match('/^(((?:\.)(?!\.))|\w)+$/', $file);
355
356 }
357
358 function planetlab_page() {
359   $path = $_SERVER['DOCUMENT_ROOT'] . preg_replace('/^db\//', '/planetlab/', $_GET['q']);
360
361   // error_log("Requested " . $_GET['q'] . " -> $path");
362
363   if (is_dir($path)) {
364     foreach (array('index.php', 'index.html', 'index.htm') as $index) {
365       if (is_file($path . "/$index")) {
366         $path .= "/$index";
367         break;
368       }
369     }
370   }
371
372   if (is_file($path)) {
373     if (preg_match('/.php$/', $path)) {
374       ob_start();
375       include $path;
376       $output = ob_get_contents();
377       ob_end_clean();
378     } else {
379          if (isValidFileName($path)) {
380             $output = file_get_contents($path);
381          }
382          else {
383             $output = "";
384          }
385     }
386     return $output;
387   }
388             
389   drupal_not_found();
390 }
391
392 function theme_planetlab($content) {
393   return $content;
394 }
395
396 ?>