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