remove error_reporting(0) that has been causing all the pain with logs
[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       // do nothing
111       // this is a private hook from the Vicci module to hide the planetlab module
112     } else if (!$plc->person) {
113       // Force login via HTTPS
114       unset($_GET['time']);
115       $form['#action'] = "https://" . $_SERVER['HTTP_HOST'] . url($_GET['q'], drupal_get_destination());
116       $form['#id'] = 'planetlab-login-form';
117       $form['name'] = array('#type' => 'textfield',
118                             '#title' => t('E-mail'),
119                             '#maxlength' => 60,
120                             '#size' => 25,
121                             '#required' => TRUE,
122                             );
123       $form['pass'] = array('#type' => 'password',
124                             '#title' => t('Password'),
125                             '#size' => 25,
126                             '#required' => TRUE,
127                             );
128       $form['submit'] = array('#type' => 'submit',
129                               '#value' => t('Log in'),
130                               );
131
132       $block['subject'] = t('%s login', array('%s' => variable_get('site_name', 'local')));
133       $block['content'] = drupal_get_form('planetlab_login_block', $form, 'planetlab_login');
134       $block['content'] .= p('');
135       $block['content'] .= p( href (l_reset_password(),"Forgot your password?") );
136       $block['content'] .= p( href(l_person_register(),"Create an account") );
137       $block['content'] .= p( href(l_site_register(),"File a site registration") );
138     } else {
139       $block['subject'] = truncate($plc->person['email'],30);
140
141       //////////////////// Logout 
142       $bullet_item = '';
143       if ($user->uid) {
144         // Drupal logout (destroys the session and cleans up $user)
145         // Thierry unclear when this triggers, I suspect this is obsolete
146         $bullet_item .= l(t('Logout of %s', 
147                           array('%s' => variable_get('site_name', 'local'))), 'logout');
148       } else {
149         // PlanetLab logout (just destroy the session)
150         $bullet_item .= href (l_logout(),'Logout');
151       }
152       $bullet_item .= ul_start();
153       // logout 
154       if ( $plc->alt_person && $plc->alt_auth) {
155         $email = truncate($plc->person['email'],20); 
156         $bullet_item .= leaf( href( l_sulogout(),"Un-become $email"));
157       } 
158       $bullet_item .= ul_end();
159       $items []= expanded ($bullet_item);
160
161       //////////////////// accounts
162       $bullet_item = '';
163       $bullet_item .=  l_person_t(plc_my_person_id(),"My Account");
164       $bullet_item .= ul_start();
165       if (plc_is_admin() || plc_is_pi()) 
166         $bullet_item .= leaf( href( l_persons_site(plc_my_site_id()), "My Site Accounts"));
167       if (plc_is_admin()) {
168         $bullet_item .= leaf(href(l_persons_peer('local'),'Local Accounts (slow)'));
169         $bullet_item .= leaf(href(l_persons(),'All Accounts (slow)'));
170       }
171         
172       $bullet_item .= ul_end();
173       $items [] = expanded($bullet_item);
174
175       //////////////////// Sites
176       $bullet_item = '';
177       $bullet_item .= href(l_sites(),"Sites");
178       $bullet_item .= ul_start();
179       $bullet_item .= plc_my_site_links();
180       if ( plc_is_admin() ) 
181         $bullet_item .= leaf( href(l_sites_pending(),"Pending Requests"));
182       $bullet_item .= ul_end();
183       $items[] = expanded($bullet_item);
184
185       //////////////////// Nodes
186       $bullet_item = '';
187       $bullet_item .= href(l_nodes(),"Nodes");
188       $bullet_item .= ul_start();
189       $bullet_item .= plc_my_node_links();
190       if (plc_is_admin() || plc_is_pi() || plc_is_tech()) {
191               $bullet_item .= leaf( href (l_register_node(), "Register Node (ko)"));
192       }
193       $bullet_item .= ul_end();
194       $items [] = expanded($bullet_item);
195
196       //////////////////// Slices
197       $bullet_item = '';
198       //if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) ) 
199       if (plc_is_admin()) {
200         $bullet_item .= href(l_slices(),"Slices");
201       } else {
202         $bullet_item .= href(l_slices(),"My Slices");
203       }
204       $bullet_item .= ul_start();
205       if (plc_is_admin()) 
206         $bullet_item .= leaf ( href(l_slices_my_site(), 'My Site Slices'));
207       if( plc_is_admin() || plc_is_pi() ) {
208         $bullet_item .= leaf(href(l_slice_add(),"Create Slice"));
209       }
210       if( !( plc_is_tech() && ! plc_is_user() && ! plc_is_pi() && ! plc_is_admin() ) ) 
211         $bullet_item .= leaf(href(l_sirius(),"Sirius"));
212       $bullet_item .= ul_end();
213       $items [] = expanded($bullet_item);
214
215       //////////////////// Admin
216       if( plc_is_admin() || plc_is_pi() ) {
217         $bullet_item = '';
218         $bullet_item .= href(l_admin(),"Admin search");
219         $bullet_item .= ul_start();
220         if ( plc_is_admin() )
221           $bullet_item .= leaf( href (l_node_add(),"Add Node"));
222         $bullet_item .= leaf( href( l_tags(),"Tags"));
223         $bullet_item .= leaf( href( l_nodegroups(),"Node groups"));
224         $bullet_item .= leaf (href(l_peers(),'Peers'));
225         if ( plc_is_admin() )
226           $bullet_item .= leaf (href(l_events(),'Events'));
227         $bullet_item .= ul_end();
228         $items [] = expanded($bullet_item);
229       }
230
231       $bullet_item = '';
232       $bullet_item .= href(l_about(),'About MyPLC');
233       $bullet_item .= ul_start();
234       $bullet_item .= leaf ( href (l_doc_plcapi(),"PLCAPI doc"));
235       $bullet_item .= leaf ( href (l_doc_nmapi(),"NMAPI doc"));
236       $bullet_item .= ul_end();
237       $items[] = expanded($bullet_item);
238
239       //$block['content'] = theme('list_item', $items);
240       $block['content'] = menu_theme($items);
241     }
242
243     /*
244      ob_start();
245      print '<pre>';
246      print_r($_SESSION);
247      print '</pre>';
248      $block['content'] .= ob_get_contents();
249      ob_end_clean();
250     */
251
252     return $block;
253   }
254 }
255
256 function planetlab_login_validate($form_id, $form_values) {
257   global $user, $plc;
258
259   if ($form_values['name'] && $form_values['pass']) {
260     // Drupal login succeeded
261     if (($user = user_authenticate($form_values['name'], trim($form_values['pass']))) &&
262         $user->uid) {
263       return;
264     }
265
266     $plc = new PLCSession($form_values['name'], $form_values['pass']);
267
268     // PlanetLab login failed
269     if (!$plc->person) {
270       form_set_error('login', t('Sorry. Unrecognized username or password.'));
271       watchdog('planetlab', t('Login attempt failed for %user.', array('%user' => theme('placeholder', $form_values['name']))));
272     }
273
274     // PlanetLab login succeeded
275     else {
276       // Login admins to Drupal as the superuser
277       if (in_array('admin', $plc->person['roles'])) {
278         $user = user_load(array('uid' => 1));
279       }
280     }
281   }
282 }
283
284 function planetlab_login_submit($form_id, $form_values) {
285   global $plc;
286
287   // Our referring page is encased in a query string of the form
288   // "destination=referrer".
289   parse_str(drupal_get_destination()); // => $destination
290
291   // The referrer itself is a URL path with the original query string,
292   // e.g. "referer.php?query".
293   extract(parse_url($destination)); // => $query
294
295   // Which we then have to parse again as a query string.
296   parse_str($query); // => $url
297
298   if ($plc->person) {
299     // To handle the edge case where this function is called during a
300     // bootstrap, check for the existence of t().
301     if (function_exists('t')) {
302       $message = t('Session opened for %name.', array('%name' => theme('placeholder', $plc->person['email'])));
303     }
304     else {
305       $message = "Session opened for ". check_plain($person['email']);
306     }
307     watchdog('planetlab', $message);
308
309     if (empty($url)) {
310       // Create a timestamped final URL so that browsers don't return the user to
311       // a cached page (where it would appear as if they never logged in or out).
312       return array('time='. time());
313     } else {
314       // Make sure that redirections are always local
315       $url = urldecode($url);
316       if ($url[0] != "/") {
317         $url = "/$url";
318       }
319       header("Location: $url");
320       exit();
321     }
322   }
323 }
324
325 function planetlab_logout() {
326   global $plc;
327
328   if ($plc->person) {
329     // Invalidate PlanetLab session
330     $plc->logout();
331     watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
332   }
333
334   // Destroy the current session:
335   session_destroy();
336
337   // The time prevents caching.
338   drupal_goto(NULL, 'time='. time());
339 }
340
341 function planetlab_user($type, &$edit, &$user, $category = NULL) {
342   switch ($type) {
343   case 'logout':
344     if ($plc->person) {
345       $plc->logout();
346       watchdog('planetlab', t('Session closed for %name.', array('%name' => theme('placeholder', $plc->person['email']))));
347     }
348     break;
349   }
350 }
351
352 function isValidFileName($file) {
353
354     /* don't allow .. and allow any "word" character \ / */
355
356     return preg_match('/^(((?:\.)(?!\.))|\w)+$/', $file);
357
358 }
359
360 function planetlab_page() {
361   $path = $_SERVER['DOCUMENT_ROOT'] . preg_replace('/^db\//', '/planetlab/', $_GET['q']);
362
363   // error_log("Requested " . $_GET['q'] . " -> $path");
364
365   if (is_dir($path)) {
366     foreach (array('index.php', 'index.html', 'index.htm') as $index) {
367       if (is_file($path . "/$index")) {
368         $path .= "/$index";
369         break;
370       }
371     }
372   }
373
374   if (is_file($path)) {
375     if (preg_match('/.php$/', $path)) {
376       ob_start();
377       include $path;
378       $output = ob_get_contents();
379       ob_end_clean();
380     } else {
381          if (isValidFileName($path)) {
382             $output = file_get_contents($path);
383          }
384          else {
385             $output = "";
386          }
387     }
388     return $output;
389   }
390             
391   drupal_not_found();
392 }
393
394 function theme_planetlab($content) {
395   return $content;
396 }
397
398 ?>