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