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