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