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