bugfix for ticket #540
[plewww.git] / planetlab / includes / plc_functions.php
1 <?php
2
3 // $Id$
4
5 // will trash this eventually
6   //require_once 'plc_functions_trash.php';
7
8 // utility
9 function my_is_int ($x) {
10     return (is_numeric($x) ? intval($x) == $x : false);
11 }
12
13 //////////////////////////////////////////////////////////// roles & other checks on global $plc
14 function plc_is_admin () {
15   global $plc;
16   return in_array( 10, $plc->person['role_ids']);
17 }
18 function plc_is_pi () {
19   global $plc;
20   return in_array( 20, $plc->person['role_ids']);
21 }
22 function plc_is_user () {
23   global $plc;
24   return in_array( 30, $plc->person['role_ids']);
25 }
26 function plc_is_tech () {
27   global $plc;
28   return in_array( 40, $plc->person['role_ids']);
29 }
30 function plc_in_site ($site_id) {
31   global $plc;
32   return in_array( $site_id, $plc->person['site_ids']);
33 }
34
35 function plc_my_site_ids () {
36   global $plc;
37   return $plc->person['site_ids'];
38 }
39 function plc_my_sites () {
40   global $plc;
41   global $api;
42   return $api->GetSites($plc->person['site_ids'], array('site_id', 'abbreviated_name'));
43 }
44
45 function plc_my_site_id () {
46   global $plc;
47   return $plc->person['site_ids'][0];
48 }
49
50 function plc_my_person () {
51   return $plc->person;
52 }
53 function plc_my_person_id () {
54   global $plc;
55   return $plc->person['person_id'];
56 }
57
58 //////////////////////////////////////////////////////////// links    
59 function href ($url,$text) { return "<a href='" . $url . "'>" . $text . "</a>"; }
60
61 // naming scheme is
62 // l_objects()                  -> the url to the page that list objects
63 // l_object($object_id)         -> the url to hte page thas details object with given id
64 // l_object_t($object_id,text)  -> an <a> tag that shows text and links to the above
65 // l_object_add ()              -> the url to that object-afding page
66
67 function l_actions ()                   { return "/db/common/actions.php"; }
68 // some complex node actions are kept separate, e.g. the ones related to getbootmedium
69 function l_actions_download ()          { return "/db/nodes/node_downloads.php"; }
70 function l_register_node ()             { return "/registerwizard/index.php"; }
71 function l_pcu_add ()                   { return "/registerwizard/index.php/register/stage1_addpcu"; }
72 function l_pcu ($pcu_id)                { return "/db/sites/pcu.php?id=$pcu_id"; }
73
74 function l_nodes ()                     { return "/db/nodes/index.php"; }
75 function l_nodes_peer ($peer_id)        { return "/db/nodes/index.php?peerscope=$peer_id"; }
76 function l_node ($node_id)              { return "/db/nodes/node.php?id=$node_id"; }
77 function l_node_t ($node_id,$text)      { return href (l_node($node_id),$text); }
78 function l_node_obj($node)              { return href(l_node($node['node_id']),$node['hostname']); }
79 function l_node_add ()                  { return "/db/nodes/node_add.php"; }
80 function l_nodes_site ($site_id)        { return "/db/nodes/index.php?site_id=$site_id"; }
81 function l_nodes_my_site ()             { return l_nodes_site(plc_my_site_id()) . "&active_line_tab=My site nodes"; }
82 function l_nodes_all_my_site ()         { return l_nodes_person(plc_my_person_id()) . "&active_line_tab=All My site nodes"; }
83 function l_nodes_person ($person_id)    { return "/db/nodes/index.php?person_id=$person_id"; }
84 function l_nodes_slice ($slice_id)      { return "/db/nodes/index.php?slice_id=$slice_id"; }
85
86 function l_interface ($interface_id)    { return "/db/nodes/interface.php?id=$interface_id"; }
87 function l_interface_tags($interface_id){ return "/db/nodes/interface.php?id=$interface_id&show_details=0&show_tags=1"; }
88 function l_interface_t ($interface_id,$text) { 
89                                           return href (l_interface($interface_id),$text); }
90 function l_interface_add($node_id)      { return "/db/nodes/interface.php?node_id=$node_id"; }
91
92 function l_sites ()                     { return "/db/sites/index.php"; }
93 function l_sites_peer ($peer_id)        { return "/db/sites/index.php?peerscope=$peer_id"; }
94 function l_site ($site_id)              { return "/db/sites/index.php?id=$site_id"; }
95 function l_site_t ($site_id,$text)      { return href (l_site($site_id),$text); }
96 function l_site_obj($site)              { return href (l_site($site['site_id']),$site['name']); }
97
98 function l_slices ()                    { return "/db/slices/index.php"; }
99 function l_slices_peer ($peer_id)       { return "/db/slices/index.php?peerscope=$peer_id"; }
100 function l_slice ($slice_id)            { return "/db/slices/index.php?id=$slice_id"; }
101 function l_slice_t ($slice_id,$text)    { return href (l_slice($slice_id),$text); }
102 function l_slice_add ()                 { return "/db/slices/slice_add.php"; }
103 function l_slices_site($site_id)        { return "/db/slices/index.php?site_id=$site_id"; }
104 function l_slices_my_site()             { return l_slices_site(plc_my_site_id()) . "&active_line_tab=My site slices"; }
105 function l_slices_person($person_id)    { return "/db/slices/index.php?person_id=$person_id"; }
106 function l_slices_local()               { return "/db/slices/index.php?peerscope=local"; }
107 // from an object
108 function l_slice_obj ($slice)           { return l_slice_t ($slice['slice_id'],$slice['name']); }
109
110 function l_sliver ($node_id,$slice_id)  { return "/db/nodes/slivers.php?node_id=$node_id&slice_id=$slice_id"; }
111 function l_sliver_t ($node_id,$slice_id,$text) { 
112                                           return href (l_sliver($node_id,$slice_id),$text) ; }
113
114 function l_persons ()                   { return "/db/persons/index.php&active_line_tab=All Accounts"; }
115 function l_persons_peer ($peer_id)      { return "/db/persons/index.php?peerscope=$peer_id&active_line_tab=Local Accounts"; }
116 function l_person ($person_id)          { return "/db/persons/index.php?id=$person_id"; }
117 function l_person_t ($person_id,$text)  { return href (l_person($person_id),$text); }
118 function l_persons_site ($site_id)      { return "/db/persons/index.php?site_id=$site_id"; }
119 function l_persons_slice ($slice_id)    { return "/db/persons/index.php?slice_id=$slice_id"; }
120 function l_person_obj ($person)         { return l_person_t($person['person_id'],$person['email']); }
121
122 function l_tags ()                      { return "/db/tags/index.php"; }
123 function l_tag ($tag_type_id)           { return "/db/tags/index.php?id=$tag_type_id"; }
124 function l_tag_obj ($tag)               { return href(l_tag($tag['tag_type_id']),$tag['tagname']); }
125
126 function l_nodegroups ()                { return "/db/tags/nodegroups.php"; }
127 function l_nodegroup ($nodegroup_id)    { return "/db/tags/nodegroup.php?id=$nodegroup_id"; }
128 function l_nodegroup_t ($nodegroup_id,$text) { 
129                                           return href(l_nodegroup($nodegroup_id),$text); }
130
131 function l_events ()                    { return "/db/events/index.php"; }
132 function l_event ($type,$param,$id)     { return "/db/events/index.php?type=$type&$param=$id"; }
133
134 function l_peers()                      { return "/db/peers/index.php"; }
135 function l_peer($peer_id)               { return "/db/peers/index.php?id=$peer_id"; }
136 function l_peer_t($peer_id,$text)       { return href(l_peer($peer_id),$text); }
137
138 function l_comon($id_name,$id_value)    { return "/db/nodes/comon.php?$id_name=$id_value"; }
139 function l_sirius()                     { return "/db/sirius/index.php"; }
140 function l_about()                      { return "/db/common/about.php"; }
141 function l_doc_plcapi()                 { return "/db/doc/PLCAPI.php"; }
142 function l_doc_nmapi()                  { return "/db/doc/NMAPI.php"; }
143 function l_admin()                      { return "/db/common/adminsearch.php"; }
144
145 function l_login()                      { return "/db/common/login.php"; }
146 function l_logout()                     { return "/planetlab/common/logout.php"; }
147 function l_sulogout()                   { return "/planetlab/common/sulogout.php"; }
148 function l_reset_password()             { return "/db/persons/reset_password.php"; }
149 function l_person_register()            { return "/db/persons/register.php"; }
150 function l_site_register()              { return "/db/sites/register.php"; }
151 function l_sites_pending()              { return "/db/sites/join_request.php"; }
152
153
154 //////////////////////////////////////////////////////////// nav tabs
155 function tab_nodes ()           { return array ('label'=>'All nodes','url'=>l_nodes(), 
156                                                 'bubble'=>'Display nodes from all peers'); }
157 function tab_nodes_local ()     { return array ('label'=>'Local nodes', 'url'=>l_nodes_peer('local'), 
158                                                 'bubble'=>'Display all nodes local to this peer'); }
159 function tab_nodes_site($site_id){ return array ('label'=>'Site nodes', 'url'=>l_nodes_site($site_id), 
160                                                  'bubble'=>'Display nodes on that site'); }
161 function tab_nodes_slice($slice_id){ return array ('label'=>'Slice nodes', 'url'=>l_nodes_slice($slice_id), 
162                                                  'bubble'=>'Display nodes for that slice'); }
163 function tab_nodes_mysite ()    { return array ('label'=>'My site nodes', 'url'=>l_nodes_my_site(), 
164                                                 'bubble'=>'Display nodes on my site'); }
165 function tab_nodes_all_mysite (){ return array ('label'=>'All My site nodes', 'url'=>l_nodes_all_my_site(),
166                                                 'bubble'=>'Display nodes on all my sites'); }
167 function tab_node($node)        { return array ('label'=>'Node '.$node['hostname'], 'url'=>l_node($node['node_id']),
168                                                 'bubble'=>'Details for ' . $node['hostname']); }
169 //////////
170 function tab_site($site)        { return array ('label'=>'Site '.$site['login_base'], 'url'=>l_site($site['site_id']),
171                                                 'bubble'=>'Details for ' . $site['name']); }
172 function tab_mysite()           { return array ('label'=>'My site', 'url'=>l_site(plc_my_site_id()),
173                                                 'bubble'=>'Details for site ' . plc_my_site_id()); }
174 function tab_sites ()           { return array ('label'=>'All sites' , 'url'=>l_sites(), 'bubble'=> 'Display all sites'); }
175 function tab_sites_local ()     { return array ('label'=>'Local sites' , 'url'=>l_sites_peer('local'), 
176                                                 'bubble'=> 'Display all siteslocal to this peer'); }
177 //////////
178 function tab_slices()           { return array ('label'=>'All slices', 'url'=>l_slices(),
179                                                 'bubble' => 'Display all slices'); }
180 function tab_slices_person()    { return array ('label'=>'My slices', 'url'=>l_slices_person(plc_my_person_id()),
181                                                 'bubble' => 'Display my all slices'); }
182 function tab_slices_mysite ()   { return array ('label'=>'My site slices', 'url'=>l_slices_my_site(), 
183                                                 'bubble'=>'Display all slices on my site'); }
184 function tab_slices_local ()    { return array ('label'=>'Local slices', 'url'=>l_slices_local(), 
185                                                 'bubble'=>'Display all slices local to this peer'); }
186 function tab_slice($slice)      { return array ('label'=>'Slice '.$slice['name'], 'url'=>l_slice($slice['slice_id']),
187                                                 'bubble' => 'Details for ' . $slice['name']); }
188 //////////
189 function tab_persons()          { return array ('label'=>'All Accounts', 'url'=>l_persons(),
190                                                 'bubble'=>'Display users from all peers'); }
191 function tab_persons_local()    { return array ('label'=>'Local Accounts', 'url'=>l_persons_peer('local'),
192                                                 'bubble'=>'Display all users local to this peer'); }
193 function tab_persons_mysite()   { return array ('label'=>'My site accounts' , 'url'=>l_persons_site(plc_my_site_id()),
194                                                 'bubble'=>'Display accounts on site ' . plc_my_site_id()); }
195 function tab_person($person)    { return array ('label'=>'Account '.$person['email'], 'url'=>l_person($person['person_id']),
196                                                 'bubble'=>'Details for ' . $person['email']); }
197 //////////
198 function tab_tags()             { return array ('label'=>'Tag Types', 'url'=>l_tags(),
199                                                 'bubble' => 'Display and create tag types'); }
200 function tab_nodegroups()       { return array ('label'=>'Nodegroups', 'url'=>l_nodegroups(),
201                                                 'bubble' => 'Display and create nodegroups'); }
202
203 // only partial tab
204 function tablook_event()        { return array('image'=>'/planetlab/icons/event.png','height'=>18);}
205 function tablook_comon()        { return array('image'=>'/planetlab/icons/comon.png','height'=>18);}
206
207 ////////////////////
208
209 //////////////////////////////////////////////////////////// validation functions
210 function topdomain ($hostname) {
211   $exploded=array_reverse(explode(".",$hostname));
212   return $exploded[0];
213 }
214
215 function is_valid_email_addr ($email) {
216   if (ereg("^.+@.+\\..+$", $email) ) {
217     return true;
218   } else {
219     return false;
220   }
221 }
222
223 function is_valid_url ($url) {
224   if (ereg("^(http|https)://.+\..+$", strtolower($url) ) ) {
225     return true;
226   } else {
227     return false;
228   }
229 }
230
231 function is_valid_ip ($ip) {
232   if (ereg("^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$", $ip ) ) {
233       // it's at least in the right format, now check to see if
234       // each part is equal to less than 255
235       $parts= explode( '.', $ip );
236       $count= count($parts);
237
238       for( $i= 0; $i < $count; $i++ ) {
239         if( intval($parts[$i]) > 255 )
240           return false;
241       }
242
243       return true;
244   } else {
245     return false;
246   }
247 }
248
249 function is_valid_network_addr($network_addr,$mask) {
250   $lNetwork= ip2long($network_addr);
251   $lMask= ip2long($mask);
252
253   // are they the correct format?
254   if( $lNetwork == -1 || $lMask == -1 )
255     return false;
256
257   // is network address valid for the mask?
258   if( ($lNetwork & $lMask) != $lNetwork )
259     return false;
260
261   return true;
262 }
263
264
265 // returns whether or not a network address is in the reserved space
266 // in the case of a invalid network address, false will be returned.
267 function is_reserved_network_addr($network_addr) {
268   $lNetwork= ip2long($network_addr);
269
270   if( $lNetwork == -1 )
271     return false;
272
273   // does the network address fall in a reserved block?
274   $reserved_ips = array (
275                          array('10.0.0.0','10.255.255.255'),
276                          array('172.16.0.0','172.31.0.0'),
277                          array('192.168.0.0','192.168.255.0')
278                          );
279   foreach ($reserved_ips as $r) {
280     $min = ip2long($r[0]);
281     $max = ip2long($r[1]);
282       
283     if (($lNetwork >= $min) && ($lNetwork <= $max))
284       return true;
285   }
286
287   return false;
288 }
289
290 ////////////////////////////////////////////////////////////  roles
291 function plc_role_global_hash ($api) {
292   $hash=array();
293   $roles=$api->GetRoles();
294   foreach ($roles as $role) {
295     $hash[$role['role_id']]=$role['name'];
296   }
297   return $hash;
298 }
299
300 //////////////////////////////////////////////////////////// nodegroups
301 // hash by 'tagname=value'
302 function plc_nodegroup_global_hash ($api,$tagnames=NULL) {
303   $filter=NULL;
304   // xxx somehow this does not work; I've checked that the feature is working from plcsh
305   // but I suspect the php marshalling or something; no time to fix, get all nodegroups for now
306   // if ($tagnames) $filter=array("tagname"=>$tagnames);
307   $nodegroups=$api->GetNodeGroups($filter);
308   $hash=array();
309   if ($nodegroups) foreach ($nodegroups as $nodegroup) {
310       $key=$nodegroup['tagname']."=".$nodegroup['value'];
311       $hash[$key]=$nodegroup;
312     }
313   return $hash;
314 }
315   
316 //////////////////////////////////////////////////////////// titles
317 function t_site($site) { return " on site " . $site['name'] . " (" . $site['login_base'] .")"; }
318 function t_slice ($slice) { return " running slice " . $slice['name'] . " (" . $slice['slice_id'] . ")"; }
319 function t_person ($person) { return " belonging to " . $person['email'] . " (" . $person['person_id'] . ")"; }
320
321 //////////////////////////////////////////////////////////// html fragments
322 function plc_vertical_table ($messages, $class="") {
323   if ( empty( $messages) ) return "";
324   $formatted = "";
325   $formatted .= "<table";
326   if ($class) $formatted .= " class='" . $class . "'";
327   $formatted .= ">";
328   foreach ($messages as $message) {
329     $formatted .= "<tr><td>" . $message . "</td></tr>";
330   }
331   $formatted .= "</table>";
332   return $formatted;
333 }
334 function plc_itemize ($messages, $class="") {
335   if ( empty( $messages) ) return "";
336   $formatted = "";
337   $formatted .= "<ul";
338   if ($class) $formatted .= " class='" . $class . "'";
339   $formatted .= ">";
340   foreach ($messages as $message) {
341     $formatted .= "<li>" . $message . "</li>";
342   }
343   $formatted .= "</ul>";
344   return $formatted;
345 }
346
347 //////////
348 // should use the same channel as the php errors..
349 function plc_error_html ($text)         { return  "<div class='plc-error'> " . $text . "</div>"; }
350 function plc_error ($text)              { print plc_error_html ("Error " . $text); }
351
352 function plc_errors ($errors) {
353   if ($errors) {
354     print( "<div class='plc-error'>" );
355     print( "<p>The following errors occured:</p>" );
356     print("<ul>");
357     foreach( $errors as $error ) 
358       print( "<li>$error</li>\n" );
359     print( "</ul></div>\n" );
360   }
361 }
362
363 function plc_warning_html ($text)       { return "<span class='plc-warning'>" . $text . "</span>";}
364 function plc_warning ($text)            { print plc_warning_html("Warning " . $text); }
365
366 function bold_html ($text)              { return "<span class='bold'>$text</span>"; }
367
368 // shows a php variable verbatim with a heading message
369 function plc_debug ($message,$object) {
370   print "<br>" . $message . "<pre>";
371   print_r ($object);
372   print "</pre>";
373 }
374
375 function truncate ($text,$numb,$etc = "...") {
376   if (strlen($text) > $numb) {
377     $text = substr($text, 0, $numb);
378     $text = $text.$etc;
379   }
380   return $text;
381 }
382 function html_div ($text,$class="") {
383   $html="<div";
384   if ($class) $html .= " class='$class'";
385   $html .= ">$text</div>";
386   return $html;
387 }
388
389 if (! function_exists ("drupal_set_error")) {
390   function drupal_set_error ($text) {
391     drupal_set_message ("<span class=error>$text</span>");
392   }
393  }
394
395 //////////////////////////////////////////////////////////// sort out for obsolete / trash
396 // builds a table from an array of strings, with the given class
397 // attempt to normalize the delete buttons and confirmations
398 function plc_delete_icon($width=15) {
399   return "<img width='$width' src='/planetlab/icons/delete.png'>";
400 }
401
402 function plc_add_icon($width=15) {
403   return "<img width='$width' src='/planetlab/icons/add.png'>";
404 }
405
406 function plc_bubble($text,$bubble) {
407   return "<span title='$bubble'>$text</span>";
408 }
409 function plc_delete_icon_bubble ($bubble,$width=15) {
410   return plc_bubble(plc_delete_icon($width),$bubble);
411 }
412
413 function plc_event_button($type,$param,$id) {
414   return '<a href="' . l_event($type,$param,$id) . '"> <span title="Related events"> <img src="/planetlab/icons/event.png" width=18></span></a>';
415 }
416
417 function plc_comon_button ($id_name, $id_value,$target="") {
418   $result='<a ';
419   if (!empty($target)) {
420     $result.='target="' . $target . '" ';
421   }
422   $result.='href="' . l_comon($id_name,$id_value) . '">';
423   $result.='<span title="Link to Comon"> <img src="/planetlab/icons/comon.png" width="18"></span></a>';
424   return $result;
425 }
426
427 ////////////////////
428 function plc_redirect ($url) {
429   header ("Location: " . $url);
430   exit ();
431 }
432
433 //////////////////// the options for an interface - suitable for plekit/form
434 //>>> GetNetworkMethods()
435 //[u'static', u'dhcp', u'proxy', u'tap', u'ipmi', u'unknown']
436 function interface_method_selectors ($api, $method, $primary) {
437   if ($primary) {
438     $builtin_methods=array("static"=>"Static",
439                            "dhcp"=>"DHCP");
440   } else {
441     $builtin_methods=array("static"=>"Static",
442                            "dhcp"=>"DHCP", 
443                            "proxy"=>"Proxy",  
444                            "tap"=>"TUN/TAP",
445                            "ipmi"=>"IPMI");
446   }
447   $selectors=array();
448   foreach ($builtin_methods as $value=>$display) {
449     $selector=array('display'=>$display, 'value'=>$value);
450     if ($value == $method) $selector['selected']=true;
451     $selectors []= $selector;
452   }
453   return $selectors;
454 }
455
456 // displays bandwidth with kbps Mbps Gbps as needed
457 function pretty_bandwidth ($bw) {
458   if ($bw < 1000)               return $bw;
459   if ($bw < 1000000)            return strval($bw/1000) . " kbps";
460   if ($bw < 1000000000)         return strval($bw/1000000) . " Mbps";
461   else                          return strval($bw/1000000000) . " Gbps";
462 }
463
464 //////////////////// 
465 function instantiation_label ($slice) {
466   $instantiation_labels = array ('not-instantiated'=>'NOT',
467                                  'plc-instantiated'=>'PLC',
468                                  'delegated' => 'DEL',
469                                  'nm-controller' => 'NM');
470   $result=$instantiation_labels[$slice['instantiation']];
471   if (!$result) $result = $slice['instantiation'];
472   if (!$result) $result = '??';
473   return $result;
474 }
475   
476 //////////////////// toggle areas
477 // get_arg ('show_persons',false) returns $_GET['show_persons'] if set and false otherwise
478 function get_arg ($name,$default,$method='get') {
479   if ($method == 'get') $var=$_GET; else $var=$_POST;
480   if (isset ($var[$name])) return $var[$name];
481   else return $default;
482 }
483
484 //////////////////// number of ...
485 function count_english ($objs,$name) {
486   $count=count($objs);
487   if ($count == 0) return 'No ' . $name;
488   else if ($count == 1) return 'One ' . $name;
489   else return $count . ' ' . $name . 's';
490 }
491 function count_english_warning ($objs, $name) {
492   $x=count_english ($objs,$name);
493   if (count ($objs) == 0) $x=plc_warning_html($x . ' !!');
494   return $x;
495 }
496 ?>