svncommit
2006-11-21 84f9312e1d17725db6040554a993db38292d46bd
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | rcube_shared.inc                                                      |
6  |                                                                       |
7  | This file is part of the RoundCube PHP suite                          |
8  | Copyright (C) 2005, RoundCube Dev. - Switzerland                      |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 11  | CONTENTS:                                                             |
12  |   Shared functions and classes used in PHP projects                   |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id$
19
20 */
21
22
23 // ********* round cube schared classes *********
24
25 class rcube_html_page
26   {
27   var $css;
28   
29   var $scripts_path = '';
30   var $script_files = array();
a0109c 31   var $external_scripts = array();
4e17e6 32   var $scripts = array();
7cc38e 33   var $charset = 'ISO-8859-1';
4e17e6 34   
T 35   var $script_tag_file = "<script type=\"text/javascript\" src=\"%s%s\"></script>\n";
36   var $script_tag      = "<script type=\"text/javascript\">\n<!--\n%s\n\n//-->\n</script>\n";
8d4bcd 37   var $default_template = "<html>\n<head><title></title></head>\n<body></body>\n</html>";
a0109c 38   var $tag_format_external_script = "<script type=\"text/javascript\" src=\"%s\"></script>\n";
S 39
4e17e6 40   var $title = '';
T 41   var $header = '';
42   var $footer = '';
43   var $body = '';
44   var $body_attrib = array();
45   var $meta_tags = array();
46
47
48   // PHP 5 constructor
49   function __construct()
50     {
51     $this->css = new rcube_css();
52     }
53
54   // PHP 4 compatibility
55   function rcube_html_page()
56     {
57     $this->__construct();
58     }
59
60
61   function include_script($file, $position='head')
62     {
63     static $sa_files = array();
64     
65     if (in_array($file, $sa_files))
66       return;
67       
68     if (!is_array($this->script_files[$position]))
69       $this->script_files[$position] = array();
70       
71     $this->script_files[$position][] = $file;
72     }
73     
a0109c 74   function include_external_script($script_location, $position='head')
S 75   {
76      if (!is_array($this->external_scripts[$position]))
77      {
78         $this->external_scripts[$position] = array();
79      }
80      
81      $this->external_scripts[$position][] = $script_location;
82   }
83
4e17e6 84   function add_script($script, $position='head')
T 85     {
86     if (!isset($this->scripts[$position]))
a0109c 87       $this->scripts[$position] = "\n$script";
S 88     else
89       $this->scripts[$position] .= "\n$script";
4e17e6 90     }
T 91
92
41fa0b 93   function set_title($t)
4e17e6 94     {
41fa0b 95     $this->title = $t;
4e17e6 96     }
41fa0b 97
4e17e6 98
7cc38e 99   function set_charset($charset)
T 100     {
f88d41 101     global $MBSTRING;
13c1af 102     
7cc38e 103     $this->charset = $charset;
13c1af 104     
T 105     if ($MBSTRING && function_exists("mb_internal_encoding"))
f88d41 106       {
13c1af 107       if(!@mb_internal_encoding($charset))
f88d41 108         $MBSTRING = FALSE;
T 109       }
7cc38e 110     }
41fa0b 111
3f9edb 112   function get_charset()
0af7e8 113     {
3f9edb 114     return $this->charset;
0af7e8 115     }
7cc38e 116
4e17e6 117
41fa0b 118   function reset()
T 119     {
120     $this->css = new rcube_css();
121     $this->script_files = array();
122     $this->scripts = array();
123     $this->title = '';
124     }
125
126
4e17e6 127   function write($templ='', $base_path='')
T 128     {
41fa0b 129     $output = empty($templ) ? $this->default_template : trim($templ);
8d4bcd 130     
4e17e6 131     // set default page title
T 132     if (!strlen($this->title))
ea7c46 133       $this->title = 'RoundCube Mail';
4e17e6 134   
T 135     // replace specialchars in content
136     $__page_title = rep_specialchars_output($this->title, 'html', 'show', FALSE);
137     $__page_header = $__page_body = $__page_footer = '';
7cc38e 138     
T 139     
140     // include meta tag with charset
141     if (!empty($this->charset))
ea7c46 142       {
T 143       header('Content-Type: text/html; charset='.$this->charset);
144       $__page_header = '<meta http-equiv="content-type" content="text/html; charset='.$this->charset.'" />'."\n";
145       }
4e17e6 146   
T 147   
148     // definition of the code to be placed in the document header and footer
149     if (is_array($this->script_files['head']))
150       foreach ($this->script_files['head'] as $file)
151         $__page_header .= sprintf($this->script_tag_file, $this->scripts_path, $file);
152
a0109c 153    if (is_array($this->external_scripts['head']))
S 154    {
155       foreach ($this->external_scripts['head'] as $xscript)
156       {
157          $__page_header .= sprintf($this->tag_format_external_script, $xscript);
158       }
159    }
160
4e17e6 161     if (strlen($this->scripts['head']))
T 162       $__page_header .= sprintf($this->script_tag, $this->scripts['head']);
163           
164     if (is_array($this->script_files['foot']))
a0109c 165       {
4e17e6 166       foreach ($this->script_files['foot'] as $file)
T 167         $__page_footer .= sprintf($this->script_tag_file, $this->scripts_path, $file);
a0109c 168       }
4e17e6 169
T 170     if (strlen($this->scripts['foot']))
171       $__page_footer .= sprintf($this->script_tag, $this->scripts['foot']);
172
173     $__page_header .= $this->css->show();
174   
175     // find page header
176     if($hpos = strpos(strtolower($output), '</head>'))
177       $__page_header .= "\n";
178     else 
179       {
180       if (!is_numeric($hpos))
181         $hpos = strpos(strtolower($output), '<body');
182       if (!is_numeric($hpos) && ($hpos = strpos(strtolower($output), '<html')))
183         {
184         while($output[$hpos]!='>')
185         $hpos++;
186         $hpos++;
187         }
188   
189       $__page_header = "<head>\n<title>$__page_title</title>\n$__page_header\n</head>\n";
190       }
191   
192     // add page hader
193     if($hpos)
194       $output = substr($output,0,$hpos) . $__page_header . substr($output,$hpos,strlen($output));
195     else
196       $output = $__page_header . $output;
197   
198   
199     // find page body
200     if($bpos = strpos(strtolower($output), '<body'))
201       {
202       while($output[$bpos]!='>') $bpos++;
203       $bpos++;
204       }
205     else
206       $bpos = strpos(strtolower($output), '</head>')+7;
207   
208     // add page body
209     if($bpos && $__page_body)
210       $output = substr($output,0,$bpos) . "\n$__page_body\n" . substr($output,$bpos,strlen($output));
211   
212   
213     // find and add page footer
a0109c 214     $output_lc = strtolower($output);
4ec0e7 215     if(($fpos = strrstr($output_lc, '</body>')) ||
T 216        ($fpos = strrstr($output_lc, '</html>')))
674a0f 217       $output = substr($output,0,$fpos) . "$__page_footer\n" . substr($output,$fpos);
4e17e6 218     else
T 219       $output .= "\n$__page_footer";
220   
221   
222     // reset those global vars
223     $__page_header = $__page_footer = '';
224   
225   
a0109c 226     // correct absolute paths in images and other tags
4e17e6 227     $output = preg_replace('/(src|href|background)=(["\']?)(\/[a-z0-9_\-]+)/Ui', "\\1=\\2$base_path\\3", $output);
dd53e2 228     $output = str_replace('$__skin_path', $base_path, $output);
4e17e6 229   
3f9edb 230     print rcube_charset_convert($output, 'UTF-8', $this->charset);
4e17e6 231     }
T 232     
233     
234   function _parse($templ)
235     {
236     
237     }
238   }
239
240
241
242
243 class rcube_css
244   {
245   var $css_data = array();
246
247   var $css_groups = array();
248
249   var $include_files = array();
250
251   var $grouped_output = TRUE;
252
253   var $content_type = 'text/css';
254
255   var $base_path = '';
256
257   var $indent_chars = "\t";
258
259
260   // add or overwrite a css definition
261   // either pass porperty and value as separate arguments
262   // or provide an associative array as second argument
263   function set_style($selector, $property, $value='')
264     {
265     $a_elements = $this->_parse_selectors($selector);
266     foreach ($a_elements as $element)
267       {
268       if (!is_array($property))
269         $property = array($property => $value);
270
271       foreach ($property as $name => $value)
272         $this->css_data[$element][strtolower($name)] = $value;
273       }
274
275     // clear goups array
276     $this->css_groups = array();
277     }
278
279
280   // unset a style property
281   function remove_style($selector, $property)
282     {
283     if (!is_array($property))
284       $property = array($property);
285
286     foreach ($property as $key)
287       unset($this->css_data[$selector][strtolower($key)]);
288
289     // clear goups array
290     $this->css_groups = array();
291     }
292
293
294   // define base path for external css files
295   function set_basepath($path)
296     {
297     $this->base_path = preg_replace('/\/$/', '', $path);
298     }
299
300
301   // enable/disable grouped output
302   function set_grouped_output($grouped)
303     {
304     $this->grouped_output = $grouped;
305     }
306
307
308   // add a css file as external source
309   function include_file($filename, $media='')
310     {
311     // include multiple files
312     if (is_array($filename))
313       {
314       foreach ($filename as $file)
315         $this->include_file($file, $media);
316       }
317     // add single file
318     else if (!in_array($filename, $this->include_files))
319       $this->include_files[] = array('file' => $filename,
320                                      'media' => $media);
321     }
322
323
324   // parse css code
325   function import_string($str)
326     {
327     $ret = FALSE;
328     if (strlen($str))
329       $ret = $this->_parse($str);
330
331     return $ret;
332     }
333
334
335   // open and parse a css file
336   function import_file($file)
337     {
338     $ret = FALSE;
339
340     if (!is_file($file))
341       return $ret;
342
343     // for php version >= 4.3.0
344     if (function_exists('file_get_contents'))
345       $ret = $this->_parse(file_get_contents($file));
346
347     // for order php versions
348     else if ($fp = fopen($file, 'r'))
349       {
350       $ret = $this->_parse(fread($fp, filesize($file)));
351       fclose($fp);
352       }
353
354     return $ret;
355     }
356
357
358   // copy all properties inherited from superior styles to a specific selector
359   function copy_inherited_styles($selector)
360     {
361     // get inherited props from body and tag/class selectors
362     $css_props = $this->_get_inherited_styles($selector);
363
364     // write modified props back and clear goups array
365     if (sizeof($css_props))
366       {
367       $this->css_data[$selector] = $css_props;
368       $this->css_groups = array();
369       }
370     }
371
372
373   // return css definition for embedding in HTML
374   function show()
375     {
376     $out = '';
377
378     // include external css files
379     if (sizeof($this->include_files))
380       foreach ($this->include_files as $file_arr)
381       $out .= sprintf('<link rel="stylesheet" type="%s" href="%s"%s>'."\n",
382                         $this->content_type,
383                         $this->_get_file_path($file_arr['file']),
384                         $file_arr['media'] ? ' media="'.$file_arr['media'].'"' : '');
385
386
387     // compose css string
388     if (sizeof($this->css_data))
389       $out .= sprintf("<style type=\"%s\">\n<!--\n\n%s-->\n</style>",
390                       $this->content_type,
391                       $this->to_string());
392
393
394     return $out;
395     }
396
397
398   // return valid css code of the current styles grid
399   function to_string($selector=NULL)
400     {
401     // return code for a single selector
402     if ($selector)
403       {
404       $indent_str = $this->indent_chars;
405       $this->indent_chars = '';
406
407       $prop_arr = $this->to_array($selector);
408       $out = $this->_style2string($prop_arr, TRUE);
409
410       $this->indent_chars = $indent_str;
411       }
412
413     // compose css code for complete data grid
414     else
415       {
416       $out = '';
417       $css_data = $this->to_array();
418
419       foreach ($css_data as $key => $prop_arr)
420         $out .= sprintf("%s {\n%s}\n\n",
421                         $key,
422                         $this->_style2string($prop_arr, TRUE));
423       }
424
425     return $out;
426     }
427
428
429   // return a single-line string of a css definition
430   function to_inline($selector)
431     {
432     if ($this->css_data[$selector])
433       return str_replace('"', '\\"', $this->_style2string($this->css_data[$selector], FALSE));
434     }
435
436
437   // return an associative array with selector(s) as key and styles array as value
438   function to_array($selector=NULL)
439     {
440     if (!$selector && $this->grouped_output)
441       {
442       // build groups if desired
443       if (!sizeof($this->css_groups))
444         $this->_build_groups();
445
446       // modify group array to get an array(selector => properties)
447       $out_arr = array();
448       foreach ($this->css_groups as $group_arr)
449         {
450         $key = join(', ', $group_arr['selectors']);
451         $out_arr[$key] = $group_arr['properties'];
452         }
453       }
454     else
455       $out_arr = $this->css_data;
456
457     return $selector ? $out_arr[$selector] : $out_arr;
458     }
459
460
461   // create a css file
462   function to_file($filepath)
463     {
464     if ($fp = fopen($filepath, 'w'))
465       {
466       fwrite($fp, $this->to_string());
467       fclose($fp);
468       return TRUE;
469       }
470
471     return FALSE;
472     }
473
474
475   // alias method for import_string() [DEPRECATED]
476   function add($str)
477     {
478     $this->import_string($str);
479     }
480
481   // alias method for to_string() [DEPRECATED]
482   function get()
483     {
484     return $this->to_string();
485     }
486
487
488
489   // ******** private methods ********
490
491
492   // parse a string and add styles to internal data grid
493   function _parse($str)
494     {
495     // remove comments
496     $str = preg_replace("/\/\*(.*)?\*\//Usi", '', $str);
497
498     // parse style definitions
499     if (!preg_match_all ('/([a-z0-9\.#*:_][a-z0-9\.\-_#:*,\[\]\(\)\s\"\'\+\|>~=]+)\s*\{([^\}]*)\}/ims', $str, $matches, PREG_SET_ORDER))
500       return FALSE;
501
502
503     foreach ($matches as $match_arr)
504       {
505       // split selectors into array
506       $a_keys = $this->_parse_selectors(trim($match_arr[1]));
507
508       // parse each property of an element
509       $codes = explode(";", trim($match_arr[2]));
510       foreach ($codes as $code)
511         {
512         if (strlen(trim($code))>0)
513           {
514           // find the property and the value
515           if (!($sep = strpos($code, ':')))
516             continue;
517
518           $property = strtolower(trim(substr($code, 0, $sep)));
519           $value    = trim(substr($code, $sep+1));
520
521           // add the property to the object array
522           foreach ($a_keys as $key)
523             $this->css_data[$key][$property] = $value;
524           }
525         }
526       }
527
528     // clear goups array
529     if (sizeof($matches))
530       {
531       $this->css_groups = array();
532       return TRUE;
533       }
534
535     return FALSE;
536     }
537
538
539   // split selector group
540   function _parse_selectors($selector)
541     {
542     // trim selector and remove multiple spaces
543     $selector = preg_replace('/\s+/', ' ', trim($selector));
544
545     if (strpos($selector, ','))
546       return preg_split('/[\t\s\n\r]*,[\t\s\n\r]*/mi', $selector);
547     else
548       return array($selector);
549     }
550
551
552   // compare identical styles and make groups
553   function _build_groups()
554     {
555     // clear group array
556     $this->css_groups = array();
557     $string_group_map = array();
558
559     // bulild css string for each selector and check if the same is already defines
560     foreach ($this->css_data as $selector => $prop_arr)
561       {
562       // make shure to compare props in the same order
563       ksort($prop_arr);
564       $compare_str = preg_replace('/[\s\t]+/', '', $this->_style2string($prop_arr, FALSE));
565
566       // add selector to extisting group
567       if (isset($string_group_map[$compare_str]))
568         {
569         $group_index = $string_group_map[$compare_str];
570         $this->css_groups[$group_index]['selectors'][] = $selector;
571         }
572
573       // create new group
574       else
575         {
576         $i = sizeof($this->css_groups);
577         $string_group_map[$compare_str] = $i;
578         $this->css_groups[$i] = array('selectors' => array($selector),
579                                       'properties' => $this->css_data[$selector]);
580         }
581       }
582     }
583
584
585   // convert the prop array into a valid css definition
586   function _style2string($prop_arr, $multiline=TRUE)
587     {
588     $out = '';
589     $delm   = $multiline ? "\n" : '';
590     $spacer = $multiline ? ' ' : '';
591     $indent = $multiline ? $this->indent_chars : '';
592
593     if (is_array($prop_arr))
594       foreach ($prop_arr as $prop => $value)
595         if (strlen($value))
596           $out .= sprintf('%s%s:%s%s;%s',
597                           $indent,
598                           $prop,
599                           $spacer,
600                           $value,
601                           $delm);
602
603     return $out;
604     }
605
606
607   // copy all properties inherited from superior styles to a specific selector
608   function _get_inherited_styles($selector, $loop=FALSE)
609     {
610     $css_props = $this->css_data[$selector] ? $this->css_data[$selector] : array();
611
612     // get styles from tag selector
613     if (preg_match('/(([a-z0-9]*)(\.[^\s]+)?)$/i', $selector, $regs))
614       {
615       $sel = $regs[1];
616       $tagname = $regs[2];
617       $class = $regs[3];
618
619       if ($sel && is_array($this->css_data[$sel]))
620         $css_props = $this->_merge_styles($this->css_data[$sel], $css_props);
621
622       if ($class && is_array($this->css_data[$class]))
623         $css_props = $this->_merge_styles($this->css_data[$class], $css_props);
624
625       if ($tagname && is_array($this->css_data[$tagname]))
626         $css_props = $this->_merge_styles($this->css_data[$tagname], $css_props);
627       }
628
629     // analyse inheritance
630     if (strpos($selector, ' '))
631       {
632       $a_hier = split(' ', $selector);
633       if (sizeof($a_hier)>1)
634         {
635         array_pop($a_hier);
636         $base_selector = join(' ', $a_hier);
637
638         // call this method recursively
639         $new_props = $this->_get_inherited_styles($base_selector, TRUE);
640         $css_props = $this->_merge_styles($new_props, $css_props);
641         }
642       }
643
644     // get body style
645     if (!$loop && is_array($this->css_data['body']))
646       $css_props = $this->_merge_styles($this->css_data['body'], $css_props);
647
648     return $css_props;
649     }
650
651
652   // merge two arrays with style properties together like a browser would do
653   function _merge_styles($one, $two)
654     {
655     // these properties are additive
656     foreach (array('text-decoration') as $prop)
657       if ($one[$prop] && $two[$prop])
658         {
659         // if value contains 'none' it's ignored
660         if (strstr($one[$prop], 'none'))
661           continue;
662         else if (strstr($two[$prop], 'none'))
663           unset($two[$prop]);
664
665         $a_values_one = split(' ', $one[$prop]);
666         $a_values_two = split(' ', $two[$prop]);
667         $two[$prop] = join(' ', array_unique(array_merge($a_values_one, $a_values_two)));
668         }
669
670     return array_merge($one, $two);
671     }
672
673
674   // resolve file path
675   function _get_file_path($file)
676     {
677     if (!$this->base_path && $GLOBALS['CSS_PATH'])
678       $this->set_basepath($GLOBALS['CSS_PATH']);
679
680     $base = ($file{0}=='/' || $file{0}=='.' || substr($file, 0, 7)=='http://') ? '' :
681             ($this->base_path ? $this->base_path.'/' : '');
682     return $base.$file;
683     }
684
685   }
686
687
688
689 class base_form_element
690   {
691   var $uppertags = FALSE;
692   var $upperattribs = FALSE;
693   var $upperprops = FALSE;
694   var $newline = FALSE;
695   
696   var $attrib = array();
697
698
699   // create string with attributes
700   function create_attrib_string($tagname='')
701     {
702     if (!sizeof($this->attrib))
703       return '';
704
705     if ($this->name!='')
706       $this->attrib['name'] = $this->name;
707
708     $attrib_arr = array();
709     foreach ($this->attrib as $key => $value)
710       {
711       // don't output some internally used attributes
712       if (in_array($key, array('form', 'quicksearch')))
713         continue;
714
715       // skip if size if not numeric
716       if (($key=='size' && !is_numeric($value)))
717         continue;
718         
719       // skip empty eventhandlers
720       if ((strpos($key,'on')===0 && $value==''))
721         continue;
722
723       // encode textarea content
724       if ($key=='value')
725         $value = rep_specialchars_output($value, 'html', 'replace', FALSE);
726
727       // attributes with no value
728       if (in_array($key, array('checked', 'multiple', 'disabled', 'selected')))
729         {
730         if ($value)
731           $attrib_arr[] = $key;
732         }
733       // don't convert size of value attribute
734       else if ($key=='value')
735         $attrib_arr[] = sprintf('%s="%s"', $this->_conv_case($key, 'attrib'), $value, 'value');
736         
737       // regular tag attributes
738       else
739         $attrib_arr[] = sprintf('%s="%s"', $this->_conv_case($key, 'attrib'), $this->_conv_case($value, 'value'));
740       }
741
742     return sizeof($attrib_arr) ? ' '.implode(' ', $attrib_arr) : '';
743     }
744     
745     
746   // convert tags and attributes to upper-/lowercase
747   // $type can either be "tag" or "attrib"
748   function _conv_case($str, $type='attrib')
749     {
750     if ($type == 'tag')
751       return $this->uppertags ? strtoupper($str) : strtolower($str);
752     else if ($type == 'attrib')
753       return $this->upperattribs ? strtoupper($str) : strtolower($str);
754     else if ($type == 'value')
755       return $this->upperprops ? strtoupper($str) : strtolower($str);
756     }    
757   }
758
759
760 class input_field extends base_form_element
761   {
762   var $type = 'text';
763   
764   // PHP 5 constructor
765   function __construct($attrib=NULL)
766     {
767     if (is_array($attrib))
768       $this->attrib = $attrib;
769
770     if ($attrib['type'])
771       $this->type = $attrib['type'];    
772
773     if ($attrib['newline'])
774       $this->newline = TRUE;    
775     }
776
777   // PHP 4 compatibility
778   function input_field($attrib=array())
779     {
780     $this->__construct($attrib);
781     }  
782
783   // compose input tag
784   function show($value=NULL, $attrib=NULL)
785     {
786     // overwrite object attributes
787     if (is_array($attrib))
788       $this->attrib = array_merge($this->attrib, $attrib);
789
790     // set value attribute
791     if ($value!==NULL)
792       $this->attrib['value'] = $value;
793
794     $this->attrib['type'] = $this->type;
795
796     // return final tag
797     return sprintf('<%s%s />%s',
798                    $this->_conv_case('input', 'tag'),
799                    $this->create_attrib_string(),
800                    ($this->newline ? "\n" : ""));    
801     }  
802   }
803
804
805 class textfield extends input_field
806   {
807   var $type = 'text';
808   }
809
810 class passwordfield extends input_field
811   {
812   var $type = 'password';
813   }
814
815 class radiobutton extends input_field
816   {
817   var $type = 'radio';
818   }
819
820 class checkbox extends input_field
821   {
822   var $type = 'checkbox';
823
824
825   function show($value='', $attrib=NULL)
826     {
827     // overwrite object attributes
828     if (is_array($attrib))
829       $this->attrib = array_merge($this->attrib, $attrib);    
830
831     $this->attrib['type'] = $this->type;
832
833     if ($value && (string)$value==(string)$this->attrib['value'])
834       $this->attrib['checked'] = TRUE;
835     else
836       $this->attrib['checked'] = FALSE;
837
838     // return final tag
839     return sprintf('<%s%s />%s',
840                    $this->_conv_case('input', 'tag'),
841                    $this->create_attrib_string(),
842                    ($this->newline ? "\n" : ""));    
843     }
844   }
845
846
847 class textarea extends base_form_element
848   {
849   // PHP 5 constructor
850   function __construct($attrib=array())
851     {
852     $this->attrib = $attrib;
853
854     if ($attrib['newline'])
855       $this->newline = TRUE;    
856     }
857
858   // PHP 4 compatibility
859   function textarea($attrib=array())
860     {
861     $this->__construct($attrib);
862     }
863     
864   function show($value='', $attrib=NULL)
865     {
866     // overwrite object attributes
867     if (is_array($attrib))
868       $this->attrib = array_merge($this->attrib, $attrib);
869     
870     // take value attribute as content
871     if ($value=='')
872       $value = $this->attrib['value'];
873     
874     // make shure we don't print the value attribute
875     if (isset($this->attrib['value']))
876       unset($this->attrib['value']);
877
a0109c 878     if (strlen($value) && !isset($this->attrib['mce_editable']))
4e17e6 879       $value = rep_specialchars_output($value, 'html', 'replace', FALSE);
a0109c 880
4e17e6 881     // return final tag
T 882     return sprintf('<%s%s>%s</%s>%s',
883                    $this->_conv_case('textarea', 'tag'),
884                    $this->create_attrib_string(),
885                    $value,
886                    $this->_conv_case('textarea', 'tag'),
887                    ($this->newline ? "\n" : ""));       
888     }
889   }
890
891
892 class hiddenfield extends base_form_element
893   {
894   var $fields_arr = array();
895   var $newline = TRUE;
896
897   // PHP 5 constructor
898   function __construct($attrib=NULL)
899     {
900     if (is_array($attrib))
901       $this->add($attrib);
902     }
903
904   // PHP 4 compatibility
905   function hiddenfield($attrib=NULL)
906     {
907     $this->__construct($attrib);
908     }
909
910   // add a hidden field to this instance
911   function add($attrib)
912     {
913     $this->fields_arr[] = $attrib;
914     }
915
916
917   function show()
918     {
919     $out = '';
920     foreach ($this->fields_arr as $attrib)
921       {
922       $this->attrib = $attrib;
923       $this->attrib['type'] = 'hidden';
924       
925       $out .= sprintf('<%s%s />%s',
926                    $this->_conv_case('input', 'tag'),
927                    $this->create_attrib_string(),
928                    ($this->newline ? "\n" : ""));   
929       }
930
931     return $out;
932     }
933   }
934
935
936 class select extends base_form_element
937   {
938   var $options = array();
939
940   /*
941   syntax:
942   -------
943   // create instance. arguments are used to set attributes of select-tag
944   $select = new select(array('name' => 'fieldname'));
945
946   // add one option
947   $select->add('Switzerland', 'CH');
948
949   // add multiple options
950   $select->add(array('Switzerland', 'Germany'),
951                array('CH', 'DE'));
952
953   // add 10 blank options with 50 chars
954   // used to fill with javascript (necessary for 4.x browsers)
955   $select->add_blank(10, 50);
956
957   // generate pulldown with selection 'Switzerland'  and return html-code
958   // as second argument the same attributes available to instanciate can be used
959   print $select->show('CH');
960   */
961
962   // PHP 5 constructor
963   function __construct($attrib=NULL)
964     {
965     if (is_array($attrib))
966       $this->attrib = $attrib;
967
968     if ($attrib['newline'])
969       $this->newline = TRUE;
970     }
971
972   // PHP 4 compatibility
973   function select($attrib=NULL)
974     {
975     $this->__construct($attrib);
976     }
977
978
979   function add($names, $values=NULL)
980     {
981     if (is_array($names))
982       {
983       foreach ($names as $i => $text)
984         $this->options[] = array('text' => $text, 'value' => (string)$values[$i]);
985       }
986     else
987       {
988       $this->options[] = array('text' => $names, 'value' => (string)$values);
989       }
990     }
991
992     
993   function add_blank($nr, $width=0)
994     {
995     $text = $width ? str_repeat('&nbsp;', $width) : '';
996     
997     for ($i=0; $i < $nr; $i++)
998       $this->options[] = array('text' => $text);
999     }
1000
1001   
1002   function show($select=array(), $attrib=NULL)
1003     {
1004     $options_str = "\n";
1005     $value_str = $this->_conv_case(' value="%s"', 'attrib');
1006     
1007     if (!is_array($select))
1008       $select = array((string)$select);
1009     
1010     foreach ($this->options as $option)
1011       {
1012       $selected = ((strlen($option['value']) && in_array($option['value'], $select, TRUE)) ||
1013                    (in_array($option['text'], $select, TRUE))) ? $this->_conv_case(' selected', 'attrib') : '';
1014                   
1015       $options_str .= sprintf("<%s%s%s>%s</%s>\n",
1016                              $this->_conv_case('option', 'tag'),
1017                              strlen($option['value']) ? sprintf($value_str, $option['value']) : '',
1018                              $selected, 
1019                              rep_specialchars_output($option['text'], 'html', 'replace', FALSE),
1020                              $this->_conv_case('option', 'tag'));
1021       }
1022                              
1023     // return final tag
1024     return sprintf('<%s%s>%s</%s>%s',
1025                    $this->_conv_case('select', 'tag'),
1026                    $this->create_attrib_string(),
1027                    $options_str,
1028                    $this->_conv_case('select', 'tag'),
1029                    ($this->newline ? "\n" : ""));    
1030     }
1031   }
1032
1033
1034
1035
1036 // ********* rcube schared functions *********
1037
1038
1039 // provide details about the client's browser
1040 function rcube_browser()
1041   {
de2e1e 1042   $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
4e17e6 1043
T 1044   $bw['ver'] = 0;
1045   $bw['win'] = stristr($HTTP_USER_AGENT, 'win');
1046   $bw['mac'] = stristr($HTTP_USER_AGENT, 'mac');
1047   $bw['linux'] = stristr($HTTP_USER_AGENT, 'linux');
1048   $bw['unix']  = stristr($HTTP_USER_AGENT, 'unix');
1049
1050   $bw['ns4'] = stristr($HTTP_USER_AGENT, 'mozilla/4') && !stristr($HTTP_USER_AGENT, 'msie');
1051   $bw['ns']  = ($bw['ns4'] || stristr($HTTP_USER_AGENT, 'netscape'));
1052   $bw['ie']  = stristr($HTTP_USER_AGENT, 'msie');
1053   $bw['mz']  = stristr($HTTP_USER_AGENT, 'mozilla/5');
1054   $bw['opera'] = stristr($HTTP_USER_AGENT, 'opera');
1055   $bw['safari'] = stristr($HTTP_USER_AGENT, 'safari');
1056
1057   if($bw['ns'])
1058     {
1059     $test = eregi("mozilla\/([0-9\.]+)", $HTTP_USER_AGENT, $regs);
1060     $bw['ver'] = $test ? (float)$regs[1] : 0;
1061     }
1062   if($bw['mz'])
1063     {
1064     $test = ereg("rv:([0-9\.]+)", $HTTP_USER_AGENT, $regs);
1065     $bw['ver'] = $test ? (float)$regs[1] : 0;
1066     }
1067   if($bw['ie'])
1068     {
1069     $test = eregi("msie ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
1070     $bw['ver'] = $test ? (float)$regs[1] : 0;
1071     }
1072   if($bw['opera'])
1073     {
1074     $test = eregi("opera ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
1075     $bw['ver'] = $test ? (float)$regs[1] : 0;
1076     }
1077
1078   if(eregi(" ([a-z]{2})-([a-z]{2})", $HTTP_USER_AGENT, $regs))
1079     $bw['lang'] =  $regs[1];
1080   else
1081     $bw['lang'] =  'en';
1082
1083   $bw['dom'] = ($bw['mz'] || $bw['safari'] || ($bw['ie'] && $bw['ver']>=5) || ($bw['opera'] && $bw['ver']>=7));
1084   $bw['pngalpha'] = $bw['mz'] || $bw['safari'] || ($bw['ie'] && $bw['ver']>=5.5) ||
1085                     ($bw['ie'] && $bw['ver']>=5 && $bw['mac']) || ($bw['opera'] && $bw['ver']>=7) ? TRUE : FALSE;
1086
1087   return $bw;
1088   }
1089
1090
1091 // get text in the desired language from the language file
1092 function rcube_label($attrib)
1093   {
7cc38e 1094   global $sess_user_lang, $INSTALL_PATH, $OUTPUT;
a95e0e 1095   static $sa_text_data, $s_language, $utf8_decode;
4e17e6 1096
T 1097   // extract attributes
1098   if (is_string($attrib))
1099     $attrib = array('name' => $attrib);
1100     
1101   $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
1102   $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
1103
1104   $command_name = strlen($attrib['command']) ? $attrib['command'] : NULL;
1105   $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
1106
1107
1108   // load localized texts
1109   if (!$sa_text_data || $s_language != $sess_user_lang)
1110     {
1111     $sa_text_data = array();
1112     
1113     // get english labels (these should be complete)
0af7e8 1114     @include($INSTALL_PATH.'program/localization/en_US/labels.inc');
T 1115     @include($INSTALL_PATH.'program/localization/en_US/messages.inc');
4e17e6 1116
T 1117     if (is_array($labels))
1118       $sa_text_data = $labels;
1119     if (is_array($messages))
1120       $sa_text_data = array_merge($sa_text_data, $messages);
1121     
1122     // include user language files
1123     if ($sess_user_lang!='en' && is_dir($INSTALL_PATH.'program/localization/'.$sess_user_lang))
1124       {
1125       include_once($INSTALL_PATH.'program/localization/'.$sess_user_lang.'/labels.inc');
1126       include_once($INSTALL_PATH.'program/localization/'.$sess_user_lang.'/messages.inc');
0af7e8 1127
4e17e6 1128       if (is_array($labels))
T 1129         $sa_text_data = array_merge($sa_text_data, $labels);
1130       if (is_array($messages))
1131         $sa_text_data = array_merge($sa_text_data, $messages);
1132       }
1133       
1134     $s_language = $sess_user_lang;
1135     }
1136
1137   // text does not exist
1138   if (!($text_item = $sa_text_data[$alias]))
1139     {
1140     /*
1141     raise_error(array('code' => 500,
1142                       'type' => 'php',
1143                       'line' => __LINE__,
1144                       'file' => __FILE__,
1145                       'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
1146     */
1147     return "[$alias]";
1148     }
1149
1150   // make text item array 
1151   $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
1152
1153   // decide which text to use
1154   if ($nr==1)
1155     $text = $a_text_item['single'];
1156   else if ($nr>0)
1157     $text = $a_text_item['multiple'];
1158   else if ($nr==0)
1159     {
1160     if ($a_text_item['none'])
1161       $text = $a_text_item['none'];
1162     else if ($a_text_item['single'])
1163       $text = $a_text_item['single'];
1164     else if ($a_text_item['multiple'])
1165       $text = $a_text_item['multiple'];
1166     }
1167
1168   // default text is single
1169   if ($text=='')
1170     $text = $a_text_item['single'];
1171
1172   // replace vars in text
1173   if (is_array($attrib['vars']))
1174     {
1175     foreach ($attrib['vars'] as $var_key=>$var_value)
1176       $a_replace_vars[substr($var_key, 0, 1)=='$' ? substr($var_key, 1) : $var_key] = $var_value;
1177     }
1178
1179   if ($a_replace_vars)
1180     $text = preg_replace('/\${?([_a-z]{1}[_a-z0-9]*)}?/ei', '$a_replace_vars["\1"]', $text);
1181
1182   // remove variables in text which were not available in arg $vars and $nr
1183   eval("\$text = <<<EOF
1184 $text
1185 EOF;
1186 ");
a95e0e 1187
4e17e6 1188   // format output
T 1189   if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
1190     return ucfirst($text);
1191   else if ($attrib['uppercase'])
1192     return strtoupper($text);
1193   else if ($attrib['lowercase'])
1194     return strtolower($text);
1195   else
1196     return $text;
1197
1198   return $text;
1199   }
1200
1201
1202 // send HTTP header for no-cacheing steps
1203 function send_nocacheing_headers()
1204   {
1205   if (headers_sent())
1206     return;
1207
1208   header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
1209   header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
1210   header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1211   header("Pragma: no-cache");
1212   }
1213
1214
1215 // send header with expire date 30 days in future
1216 function send_future_expire_header()
1217   {
1218   if (!headers_sent())
1219     header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+2600000)." GMT");
1220   }
1221
1222
1223 // function to convert an array to a javascript array
1224 function array2js($arr, $type='')
1225   {
1226   if (!$type)
1227     $type = 'mixed';
1228
1229   if (is_array($arr))
1230     {
1231     // no items in array
1232     if (!sizeof($arr))
1233       return 'new Array()';
1234     else
1235       {
1236       $a_pairs = array();
1237       $keys_arr = array_keys($arr);
1238       $is_assoc = $have_numeric = 0;
1239
1240       for ($i=0; $i<sizeof($keys_arr); ++$i)
1241         {
1242         if(is_numeric($keys_arr[$i]))
1243           $have_numeric = 1;
1244         if (!is_numeric($keys_arr[$i]) || $keys_arr[$i]!=$i)
1245           $is_assoc = 1;
1246         if($is_assoc && $have_numeric)
1247           break;
1248         }
1249
1250       $previous_was_array = false;
1251       while (list($key, $value) = each($arr))
1252         {
1253         // enclose key with quotes if it is not variable-name conform
1254         if (!ereg("^[_a-zA-Z]{1}[_a-zA-Z0-9]*$", $key) /* || is_js_reserved_word($key) */)
1255           $key = "'$key'";
1256
a0109c 1257         if (!is_array($value) && is_string($value))
4e17e6 1258           {
T 1259           $value = str_replace("\r\n", '\n', $value);
1260           $value = str_replace("\n", '\n', $value);
1261           }
1262
1263         $is_string = false;
1264         if (!is_array($value))
1265           {
1266           if ($type=='string')
1267             $is_string = true;
a0109c 1268           else if (($type == 'mixed' && is_bool($value)) || $type == 'bool')
S 1269             {
1270             $is_string = false;
1271             $value = $value ? "true" : "false";
1272             }
4e17e6 1273           else if ((($type=='mixed' && is_numeric($value)) || $type=='int') && strlen($value)<16)   // js interprets numbers with digits >15 as ...e+... 
T 1274             $is_string = FALSE;
1275           else
1276             $is_string = TRUE;
1277           }
1278
1279         if ($is_string)
1280           $value = "'".preg_replace("/(?<!\\\)'/", "\'", $value)."'";
1281
1282         $a_pairs[] = sprintf("%s%s",
1283                              $is_assoc ? "$key:" : '',
1284                              is_array($value) ? array2js($value, $type) : $value);
1285         }
1286
1287       if ($a_pairs)
1288         {
1289         if ($is_assoc)
1290           $return = '{'.implode(',', $a_pairs).'}';
1291         else
1292           $return = '['.implode(',', $a_pairs).']';
1293         }
1294
1295       return $return;
1296       }
1297     }
1298   else
a0109c 1299     {
4e17e6 1300     return $arr;
a0109c 1301     }
4e17e6 1302   }
T 1303
1304
1305 // similar function as in_array() ut case-insensitive
1306 function in_array_nocase($needle, $haystack)
1307   {
1308   foreach ($haystack as $value)
1309     {
1310     if (strtolower($needle)===strtolower($value))
1311       return TRUE;
1312     }
1313     
1314   return FALSE;
1315   }
1316
1317
1318
1319 // find out if the string content means TRUE or FALSE
1320 function get_boolean($str)
1321   {
1322   $str = strtolower($str);
1323   if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
1324     return FALSE;
1325   else
1326     return TRUE;
1327   }
1328
1329
3ea0e3 1330 // create a human readable string for a number of bytes
T 1331 function show_bytes($bytes)
4e17e6 1332   {
3ea0e3 1333   if ($bytes > 1073741824)
T 1334     {
1335     $gb = $bytes/1073741824;
1336     $str = sprintf($gb>=10 ? "%d GB" : "%.1f GB", $gb);
1337     }
1338   else if ($bytes > 1048576)
1339     {
1340     $mb = $bytes/1048576;
1341     $str = sprintf($mb>=10 ? "%d MB" : "%.1f MB", $mb);
1342     }
1343   else if ($bytes > 1024)
1344     $str = sprintf("%d KB",  round($bytes/1024));
4e17e6 1345   else
3ea0e3 1346     $str = sprintf('%d B', $bytes);
T 1347
1348   return $str;
4e17e6 1349   }
T 1350
1351
1352 // convert paths like ../xxx to an absolute path using a base url
1353 function make_absolute_url($path, $base_url)
1354     {
1355     $host_url = $base_url;
1356     $abs_path = $path;
1357
1358     // cut base_url to the last directory
1359     if (strpos($base_url, '/')>7)
1360       {
1361       $host_url = substr($base_url, 0, strpos($base_url, '/'));
1362       $base_url = substr($base_url, 0, strrpos($base_url, '/'));
1363       }
1364
1365     // $path is absolute
1366     if ($path{0}=='/')
1367       $abs_path = $host_url.$path;
1368     else
1369       {
1370       // strip './' because its the same as ''
1371       $path = preg_replace('/^\.\//', '', $path);
1372
1373       if(preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
1374         foreach($matches as $a_match)
1375           {
1376           if (strrpos($base_url, '/'))
1377             $base_url = substr($base_url, 0, strrpos($base_url, '/'));
1378           
1379           $path = substr($path, 3);
1380           }
1381
1382       $abs_path = $base_url.'/'.$path;
1383       }
1384       
1385     return $abs_path;
1386     }
1387
1388
bac7d1 1389 // replace the middle part of a string with ...
T 1390 // if it is longer than the allowed length
9fee0e 1391 function abbrevate_string($str, $maxlength, $place_holder='...')
T 1392   {
1393   $length = strlen($str);
1394   $first_part_length = floor($maxlength/2) - strlen($place_holder);
1395   
1396   if ($length > $maxlength)
1397     {
1398     $second_starting_location = $length - $maxlength + $first_part_length + 1;
1399     $str = substr($str, 0, $first_part_length) . $place_holder . substr($str, $second_starting_location, $length);
1400     }
1401
1402   return $str;
1403   }
1cded8 1404
T 1405
bac7d1 1406 // make sure the string ends with a slash
T 1407 function slashify($str)
1408   {
1409   return unslashify($str).'/';
1410   }
1411
1412
1413 // remove slash at the end of the string
1414 function unslashify($str)
1415   {
1416   return preg_replace('/\/$/', '', $str);
1417   }
1418   
1419
1cded8 1420 // delete all files within a folder
T 1421 function clear_directory($dir_path)
1422   {
1423   $dir = @opendir($dir_path);
1424   if(!$dir) return FALSE;
1425
1426   while ($file = readdir($dir))
1427     if (strlen($file)>2)
1428       unlink("$dir_path/$file");
1429
1430   closedir($dir);
1431   return TRUE;
1432   }
9fee0e 1433
T 1434
cc9570 1435 // create a unix timestamp with a specified offset from now
T 1436 function get_offset_time($offset_str, $factor=1)
1437   {
1438   if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
1439     {
1440     $amount = (int)$regs[1];
1441     $unit = strtolower($regs[2]);
1442     }
1443   else
1444     {
1445     $amount = (int)$offset_str;
1446     $unit = 's';
1447     }
1448     
1449   $ts = mktime();
1450   switch ($unit)
1451     {
1452     case 'w':
1453       $amount *= 7;
1454     case 'd':
1455       $amount *= 24;
1456     case 'h':
1457       $amount *= 60;
1458     case 'h':
1459       $amount *= 60;
1460     case 's':
1461       $ts += $amount * $factor;
1462     }
1463
1464   return $ts;
1465   }
1466
1467
a0109c 1468 /**
S 1469  * strrstr
1470  *
1471  * return the last occurence of a string in another string
1472  * @param haystack string string in which to search
1473  * @param needle string string for which to search
1474  * @return index of needle within haystack, or false if not found
1475  */
1476 function strrstr($haystack, $needle)
1477   {
1478     $pver = phpversion();
1479     if ($pver[0] >= 5)
1480       {
1481         return strrpos($haystack, $needle);
1482       }
1483     else
1484       {
1485         $index = strpos(strrev($haystack), strrev($needle));
1486         if($index === false) {
1487             return false;
1488         }
1489         $index = strlen($haystack) - strlen($needle) - $index;
1490         return $index;
1491       }
1492   }
1493
1494
f88d41 1495 ?>