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