return multiple site list for 'my site' link.
[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
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       //////////////////// Logout
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('Logout 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(),'Logout'));
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       $site_item .= plc_my_site_links(); # leaf( href(l_site(plc_my_site_id()),"My Site"));
133       if ( $is_admin ) 
134         $site_item .= leaf( href(l_sites_pending(),"Pending Requests"));
135       $site_item .= ul_end();
136       $items[] = expanded($site_item);
137
138       //////////////////// Users
139       $user_item = '';
140       $user_item .= href(l_persons(),'Users');
141       $user_item .= ul_start();
142       $user_item .= leaf( l_person_t(plc_my_person_id(),"My Account"));
143       if (is_pi) 
144         $user_item .= leaf( href( l_persons_site(plc_my_site_id()), "My Users"));
145       if ( $plc->alt_person && $plc->alt_auth) {
146         $email = truncate($plc->person['email'],20); 
147         $user_item .= leaf( href( l_sulogout(),"Logout of $email"));
148       } 
149       $user_item .= ul_end();
150       $items [] = expanded($user_item);
151
152       //////////////////// Nodes
153       $node_item = '';
154       $node_item .= href(l_nodes(),"Nodes");
155       $node_item .= ul_start();
156       $node_item .= leaf( href (l_nodes_site (plc_my_site_id()),"My Site Nodes"));
157       $node_item .= leaf( href (l_node_add(),"Add Node"));
158       $node_item .= ul_end();
159       $items [] = expanded($node_item);
160
161       //////////////////// Slices
162       $slice_item = '';
163       //if( !( $is_tech && ! $is_user && ! $is_pi && ! $is_admin ) ) 
164       $slice_item .= href(l_slices(),"Slices");
165       $slice_item .= ul_start();
166       if( $is_admin || $is_pi ) {
167         $slice_item .= leaf(href(l_slice_add(),"Create Slice"));
168       }
169       if( !( $is_tech && ! $is_user && ! $is_pi && ! $is_admin ) ) 
170         $slice_item .= leaf(href(l_sirius(),"Sirius"));
171       $slice_item .= ul_end();
172       $items [] = expanded($slice_item);
173
174       //////////////////// Admin
175       if( plc_is_admin() || plc_is_pi() ) {
176         $bullet_item = '';
177         $bullet_item .= href(l_admin(),"Admin search");
178         $bullet_item .= ul_start();
179         $bullet_item .= leaf( href (l_node_add(),"Add Node"));
180         $bullet_item .= leaf( href( l_tags(),"Tags"));
181         $bullet_item .= leaf( href( l_nodegroups(),"Node groups"));
182         $bullet_item .= leaf (href(l_peers(),'Peers'));
183         if ( plc_is_admin() )
184           $bullet_item .= leaf (href(l_events(),'Events'));
185         $bullet_item .= ul_end();
186         $items [] = expanded($bullet_item);
187       }
188
189       $doc_item = '';
190       $doc_item .= href(l_about(),'About MyPLC');
191       $doc_item .= ul_start();
192       $doc_item .= leaf ( href (l_doc_plcapi(),"PLCAPI doc"));
193       $doc_item .= leaf ( href (l_doc_nmapi(),"NMAPI doc"));
194       $doc_item .= ul_end();
195       $items[] = expanded($doc_item);
196
197       //$block['content'] = theme('list_item', $items);
198       $block['content'] = menu_theme($items);
199     }
200
201     /*
202      ob_start();
203      print '<pre>';
204      print_r($_SESSION);
205      print '</pre>';
206      $block['content'] .= ob_get_contents();
207      ob_end_clean();
208     */
209
210     return $block;
211   }
212 }
213
214 function planetlab_login_validate($form_id, $form_values) {
215   global $user, $plc;
216
217   if ($form_values['name'] && $form_values['pass']) {
218     // Drupal login succeeded
219     if (($user = user_authenticate($form_values['name'], trim($form_values['pass']))) &&
220         $user->uid) {
221       return;
222     }
223
224     $plc = new PLCSession($form_values['name'], $form_values['pass']);
225
226     // PlanetLab login failed
227     if (!$plc->person) {
228       form_set_error('login', t('Sorry. Unrecognized username or password.'));
229       watchdog('planetlab', t('Login attempt failed for %user.', array('%user' => theme('placeholder', $form_values['name']))));
230     }
231
232     // PlanetLab login succeeded
233     else {
234       // Login admins to Drupal as the superuser
235       if (in_array('admin', $plc->person['roles'])) {
236         $user = user_load(array('uid' => 1));
237       }
238     }
239   }
240 }
241
242 function planetlab_login_submit($form_id, $form_values) {
243   global $plc;
244
245   // Our referring page is encased in a query string of the form
246   // "destination=referrer".
247   parse_str(drupal_get_destination()); // => $destination
248
249   // The referrer itself is a URL path with the original query string,
250   // e.g. "referer.php?query".
251   extract(parse_url($destination)); // => $query
252
253   // Which we then have to parse again as a query string.
254   parse_str($query); // => $url
255
256   if ($plc->person) {
257     // To handle the edge case where this function is called during a
258     // bootstrap, check for the existence of t().
259     if (function_exists('t')) {
260       $message = t('Session opened for %name.', array('%name' => theme('placeholder', $plc->person['email'])));
261     }
262     else {
263       $message = "Session opened for ". check_plain($person['email']);
264     }
265     watchdog('planetlab', $message);
266
267     if (empty($url)) {
268       // Create a timestamped final URL so that browsers don't return the user to
269       // a cached page (where it would appear as if they never logged in or out).
270       return array('time='. time());
271     } else {
272       // Make sure that redirections are always local
273       $url = urldecode($url);
274       if ($url[0] != "/") {
275         $url = "/$url";
276       }
277       header("Location: $url");
278       exit();
279     }
280   }
281 }
282
283 function planetlab_logout() {
284   global $plc;
285
286   if ($plc->person) {
287     // Invalidate PlanetLab session
288     $plc->logout();
289     watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
290   }
291
292   // Destroy the current session:
293   session_destroy();
294
295   // The time prevents caching.
296   drupal_goto(NULL, 'time='. time());
297 }
298
299 function planetlab_user($type, &$edit, &$user, $category = NULL) {
300   switch ($type) {
301   case 'logout':
302     if ($plc->person) {
303       $plc->logout();
304       watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
305     }
306     break;
307   }
308 }
309
310 function planetlab_page() {
311   $path = $_SERVER['DOCUMENT_ROOT'] . preg_replace('/^db\//', '/planetlab/', $_GET['q']);
312
313   // error_log("Requested " . $_GET['q'] . " -> $path");
314
315   if (is_dir($path)) {
316     foreach (array('index.php', 'index.html', 'index.htm') as $index) {
317       if (is_file($path . "/$index")) {
318         $path .= "/$index";
319         break;
320       }
321     }
322   }
323
324   if (is_file($path)) {
325     if (preg_match('/.php$/', $path)) {
326       ob_start();
327       include $path;
328       $output = ob_get_contents();
329       ob_end_clean();
330     } else {
331       $output = file_get_contents($path);
332     }
333     return $output;
334   }
335             
336   drupal_not_found();
337 }
338
339 function theme_planetlab($content) {
340   return $content;
341 }
342
343 ?>