alecpl
2008-06-15 67effe9904d62880ab5bdaaf58b97af7113ed97f
commit | author | age
47124c 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_template.php                                    |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2006-2008, RoundCube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Class to handle HTML page output using a skin template.             |
13  |   Extends rcube_html_page class from rcube_shared.inc                 |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
19  $Id$
20
21  */
22
23
24 /**
25  * Class to create HTML page output using a skin template
26  *
27  * @package View
28  * @todo Documentation
29  * @uses rcube_html_page
30  */
31 class rcube_template extends rcube_html_page
32 {
197601 33     var $app;
47124c 34     var $config;
T 35     var $framed = false;
36     var $pagetitle = '';
37     var $env = array();
38     var $js_env = array();
39     var $js_commands = array();
40     var $object_handlers = array();
41
42     public $ajax_call = false;
43
44     /**
45      * Constructor
46      *
47      * @todo   Use jQuery's $(document).ready() here.
197601 48      * @todo   Replace $this->config with the real rcube_config object
47124c 49      */
197601 50     public function __construct($task, $framed = false)
47124c 51     {
T 52         parent::__construct();
53
197601 54         $this->app = rcmail::get_instance();
T 55         $this->config = $this->app->config->all();
56         
57         //$this->framed = $framed;
83a763 58         $this->set_env('task', $task);
47124c 59
e58df3 60     // load the correct skin (in case user-defined)
A 61     if (empty($this->config['skin']) || !is_readable('skins/'.$this->config['skin']))
67effe 62         $this->config['skin'] = 'default';
e58df3 63
A 64     $this->config['skin_path'] = 'skins/'.$this->config['skin'];
65
47124c 66         // add common javascripts
T 67         $javascript = 'var '.JS_OBJECT_NAME.' = new rcube_webmail();';
68
69         // don't wait for page onload. Call init at the bottom of the page (delayed)
70         $javascript_foot = "if (window.call_init)\n call_init('".JS_OBJECT_NAME."');";
71
72         $this->add_script($javascript, 'head_top');
73         $this->add_script($javascript_foot, 'foot');
74         $this->scripts_path = 'program/js/';
75         $this->include_script('common.js');
76         $this->include_script('app.js');
77
78         // register common UI objects
79         $this->add_handlers(array(
80             'loginform'       => array($this, 'login_form'),
81             'username'        => array($this, 'current_username'),
82             'message'         => array($this, 'message_container'),
83             'charsetselector' => array($this, 'charset_selector'),
84         ));
85     }
86
87     /**
88      * Set environment variable
89      *
90      * @param string Property name
91      * @param mixed Property value
92      * @param boolean True if this property should be added to client environment
93      */
94     public function set_env($name, $value, $addtojs = true)
95     {
96         $this->env[$name] = $value;
97         if ($addtojs || isset($this->js_env[$name])) {
98             $this->js_env[$name] = $value;
99         }
100     }
101
102
103     /**
104      * Set page title variable
105      */
106     public function set_pagetitle($title)
107     {
108         $this->pagetitle = $title;
109     }
110
e58df3 111     /**
A 112      * Set skin
113      */
114     public function set_skin($skin)
115     {
116     if (!empty($skin) && is_dir('skins/'.$skin) && is_readable('skins/'.$skin))
117         $this->config['skin_path'] = 'skins/'.$skin;
118     }
119
120     /**
121      * Check if a specific template exists
122      *
123      * @param string Template name
124      * @return boolean True if template exists
125      */
126     public function template_exists($name)
127     {
128     $filename = $this->config['skin_path'] . '/templates/' . $name . '.html';
129
130     return (is_file($filename) && is_readable($filename));
131     }
47124c 132
T 133     /**
134      * Register a template object handler
135      *
136      * @param  string Object name
137      * @param  string Function name to call
138      * @return void
139      */
140     public function add_handler($obj, $func)
141     {
142         $this->object_handlers[$obj] = $func;
143     }
144
145     /**
146      * Register a list of template object handlers
147      *
148      * @param  array Hash array with object=>handler pairs
149      * @return void
150      */
151     public function add_handlers($arr)
152     {
153         $this->object_handlers = array_merge($this->object_handlers, $arr);
154     }
155
156     /**
157      * Register a GUI object to the client script
158      *
159      * @param  string Object name
160      * @param  string Object ID
161      * @return void
162      */
163     public function add_gui_object($obj, $id)
164     {
165         $this->add_script(JS_OBJECT_NAME.".gui_object('$obj', '$id');");
166     }
167
168     /**
169      * Call a client method
170      *
171      * @param string Method to call
172      * @param ... Additional arguments
173      */
174     public function command()
175     {
176         $this->js_commands[] = func_get_args();
177     }
178
179
180     /**
181      * Add a localized label to the client environment
182      */
183     public function add_label()
184     {
185         $arg_list = func_get_args();
186         foreach ($arg_list as $i => $name) {
187             $this->command('add_label', $name, rcube_label($name));
188         }
189     }
190
191
192     /**
193      * Invoke display_message command
194      *
195      * @param string Message to display
196      * @param string Message type [notice|confirm|error]
197      * @param array Key-value pairs to be replaced in localized text
198      * @uses self::command()
199      */
200     public function show_message($message, $type='notice', $vars=NULL)
201     {
202         $this->command(
203             'display_message',
204             rcube_label(array('name' => $message, 'vars' => $vars)),
205             $type);
206     }
207
208
209     /**
210      * Delete all stored env variables and commands
211      *
212      * @return void
213      * @uses   rcube_html::reset()
214      * @uses   self::$env
215      * @uses   self::$js_env
216      * @uses   self::$js_commands
217      * @uses   self::$object_handlers
218      */
219     public public function reset()
220     {
221         $this->env = array();
222         $this->js_env = array();
223         $this->js_commands = array();
224         $this->object_handlers = array();
225         parent::reset();
226     }
227
228
229     /**
230      * Send the request output to the client.
231      * This will either parse a skin tempalte or send an AJAX response
232      *
233      * @param string  Template name
234      * @param boolean True if script should terminate (default)
235      */
236     public function send($templ = null, $exit = true)
237     {
238         if ($templ != 'iframe') {
239             $this->parse($templ, false);
240         }
241         else {
242             $this->framed = $templ == 'iframe' ? true : $this->framed;
243             $this->write();
244         }
245
246         if ($exit) {
247             exit;
248         }
249     }
250
251     /**
252      * Process template and write to stdOut
253      *
254      * @param string HTML template
255      * @see rcube_html_page::write()
256      * @override
257      */
258     public function write($template = '')
259     {
260         // unlock interface after iframe load
261         if ($this->framed) {
262             array_unshift($this->js_commands, array('set_busy', false));
263         }
264         // write all env variables to client
265         $js = $this->framed ? "if(window.parent) {\n" : '';
266         $js .= $this->get_js_commands() . ($this->framed ? ' }' : '');
267         $this->add_script($js, 'head_top');
268
269         // call super method
270         parent::write($template, $this->config['skin_path']);
271     }
272
273     /**
274      * Parse a specific skin template and deliver to stdout
275      *
276      * Either returns nothing, or exists hard (exit();)
277      *
278      * @param  string  Template name
279      * @param  boolean Exit script
280      * @return void
281      * @link   http://php.net/manual/en/function.exit.php
282      */
283     private function parse($name = 'main', $exit = true)
284     {
285         $skin_path = $this->config['skin_path'];
286
287         // read template file
288         $templ = '';
289         $path = "$skin_path/templates/$name.html";
290
291         if (($fp = fopen($path, 'r')) === false) {
292             $message = '';
293             ob_start();
294             fopen($path, 'r');
295             $message.= ob_get_contents();
296             ob_end_clean();
f92b2f 297             raise_error(array(
47124c 298                 'code' => 501,
T 299                 'type' => 'php',
300                 'line' => __LINE__,
301                 'file' => __FILE__,
302                 'message' => 'Error loading template for '.$name.': '.$message
303                 ), true, true);
304             return false;
305         }
306         $templ = fread($fp, filesize($path));
307         fclose($fp);
308
309         // parse for specialtags
310         $output = $this->parse_conditions($templ);
311         $output = $this->parse_xml($output);
312
313         // add debug console
314         if ($this->config['debug_level'] & 8) {
315             $this->add_footer('<div style="position:absolute;top:5px;left:5px;width:400px;padding:0.2em;background:white;opacity:0.8;z-index:9000">
316                 <a href="#toggle" onclick="con=document.getElementById(\'dbgconsole\');con.style.display=(con.style.display==\'none\'?\'block\':\'none\');return false">console</a>
317                 <form action="/" name="debugform"><textarea name="console" id="dbgconsole" rows="20" cols="40" wrap="off" style="display:none;width:400px;border:none;font-size:x-small"></textarea></form></div>'
318             );
319         }
320         $output = $this->parse_with_globals($output);
321         $this->write(trim($output), $skin_path);
322         if ($exit) {
323             exit;
324         }
325     }
326
327
328     /**
329      * Return executable javascript code for all registered commands
330      *
331      * @return string $out
332      */
333     private function get_js_commands()
334     {
335         $out = '';
336         if (!$this->framed && !empty($this->js_env)) {
337             $out .= JS_OBJECT_NAME . '.set_env('.json_serialize($this->js_env).");\n";
338         }
339         foreach ($this->js_commands as $i => $args) {
340             $method = array_shift($args);
341             foreach ($args as $i => $arg) {
342                 $args[$i] = json_serialize($arg);
343             }
344             $parent = $this->framed || preg_match('/^parent\./', $method);
345             $out .= sprintf(
346                 "%s.%s(%s);\n",
347             ($parent ? 'parent.' : '') . JS_OBJECT_NAME,
348             preg_replace('/^parent\./', '', $method),
349             implode(',', $args)
350             );
351         }
352         // add command to set page title
353         if ($this->ajax_call && !empty($this->pagetitle)) {
354             $out .= sprintf(
355                 "this.set_pagetitle('%s');\n",
356                 JQ((!empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '') . $this->pagetitle)
357             );
358         }
359         return $out;
360     }
361
362     /**
363      * Make URLs starting with a slash point to skin directory
364      *
365      * @param  string Input string
366      * @return string
367      */
368     public function abs_url($str)
369     {
370         return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
371     }
372
373
374     /*****  Template parsing methods  *****/
375
376     /**
377      * Replace all strings ($varname)
378      * with the content of the according global variable.
379      */
380     private function parse_with_globals($input)
381     {
197601 382         $GLOBALS['__comm_path'] = Q($this->app->comm_path);
47124c 383         return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
T 384     }
385
386     /**
387      * Public wrapper to dipp into template parsing.
388      *
389      * @param  string $input
390      * @return string
391      * @uses   rcube_template::parse_xml()
392      * @since  0.1-rc1
393      */
394     public function just_parse($input)
395     {
396         return $this->parse_xml($input);
397     }
398
399     /**
400      * Parse for conditional tags
401      *
402      * @param  string $input
403      * @return string
404      */
405     private function parse_conditions($input)
406     {
407         $matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE);
408         if ($matches && count($matches) == 4) {
409             if (preg_match('/^(else|endif)$/i', $matches[1])) {
410                 return $matches[0] . $this->parse_conditions($matches[3]);
411             }
412             $attrib = parse_attrib_string($matches[2]);
413             if (isset($attrib['condition'])) {
414                 $condmet = $this->check_condition($attrib['condition']);
415                 $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
416                 if ($condmet) {
417                     $result = $submatches[0];
418                     $result.= ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>/Uis', '', $submatches[3], 1) : $submatches[3]);
419                 }
420                 else {
421                     $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
422                 }
423                 return $matches[0] . $this->parse_conditions($result);
424             }
f92b2f 425             raise_error(array(
47124c 426                 'code' => 500,
T 427                 'type' => 'php',
428                 'line' => __LINE__,
429                 'file' => __FILE__,
430                 'message' => "Unable to parse conditional tag " . $matches[2]
431             ), true, false);
432         }
433         return $input;
434     }
435
436
437     /**
438      * Determines if a given condition is met
439      *
440      * @todo   Get rid off eval() once I understand what this does.
441      * @todo   Extend this to allow real conditions, not just "set"
442      * @param  string Condition statement
443      * @return boolean True if condition is met, False is not
444      */
445     private function check_condition($condition)
446     {
447         $condition = preg_replace(
448             array(
449                 '/session:([a-z0-9_]+)/i',
450                 '/config:([a-z0-9_]+)/i',
451                 '/env:([a-z0-9_]+)/i',
452                 '/request:([a-z0-9_]+)/ie'
453             ),
454             array(
455                 "\$_SESSION['\\1']",
456                 "\$this->config['\\1']",
457                 "\$this->env['\\1']",
458                 "get_input_value('\\1', RCUVE_INPUT_GPC)"
459             ),
460             $condition);
461             
462             return eval("return (".$condition.");");
463     }
464
465
466     /**
467      * Search for special tags in input and replace them
468      * with the appropriate content
469      *
470      * @param  string Input string to parse
471      * @return string Altered input string
472      * @todo   Maybe a cache.
473      */
474     private function parse_xml($input)
475     {
476         return preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "\$this->xml_command('\\1', '\\2')", $input);
477     }
478
479
480     /**
481      * Convert a xml command tag into real content
482      *
483      * @param  string Tag command: object,button,label, etc.
484      * @param  string Attribute string
485      * @return string Tag/Object content
486      */
487     private function xml_command($command, $str_attrib, $add_attrib = array())
488     {
489         $command = strtolower($command);
490         $attrib  = parse_attrib_string($str_attrib) + $add_attrib;
491
492         // empty output if required condition is not met
493         if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
494             return '';
495         }
496
497         // execute command
498         switch ($command) {
499             // return a button
500             case 'button':
875a48 501                 if ($attrib['name'] || $attrib['command']) {
47124c 502                     return $this->button($attrib);
T 503                 }
504                 break;
505
506             // show a label
507             case 'label':
508                 if ($attrib['name'] || $attrib['command']) {
509                     return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
510                 }
511                 break;
512
513             // include a file
514             case 'include':
515                 $path = realpath($this->config['skin_path'].$attrib['file']);
516                 if ($fsize = filesize($path)) {
517                     if ($this->config['skin_include_php']) {
518                         $incl = $this->include_php($path);
519                     }
520                     else if ($fp = fopen($path, 'r')) {
521                         $incl = fread($fp, $fsize);
522                         fclose($fp);
523                     }
524                     return $this->parse_xml($incl);
525                 }
526                 break;
527
528             case 'plugin.include':
529                 //rcube::tfk_debug(var_export($this->config['skin_path'], true));
530                 $path = realpath($this->config['skin_path'].$attrib['file']);
531                 if (!$path) {
532                     //rcube::tfk_debug("Does not exist:");
533                     //rcube::tfk_debug($this->config['skin_path']);
534                     //rcube::tfk_debug($attrib['file']);
535                     //rcube::tfk_debug($path);
536                 }
537                 $incl = file_get_contents($path);
538                 if ($incl) {
539                     return $this->parse_xml($incl);
540                 }
541                 break;
542
543             // return code for a specific application object
544             case 'object':
545                 $object = strtolower($attrib['name']);
546
547                 // we are calling a class/method
548                 if (($handler = $this->object_handlers[$object]) && is_array($handler)) {
549                     if ((is_object($handler[0]) && method_exists($handler[0], $handler[1])) ||
550                     (is_string($handler[0]) && class_exists($handler[0])))
551                     return call_user_func($handler, $attrib);
552                 }
553                 else if (function_exists($handler)) {
554                     // execute object handler function
555                     return call_user_func($handler, $attrib);
556                 }
557
558                 if ($object=='productname') {
559                     $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
560                     return Q($name);
561                 }
562                 if ($object=='version') {
c8fb2b 563                     $ver = (string)RCMAIL_VERSION;
T 564                     if (is_file(INSTALL_PATH . '.svn/entries')) {
565                         if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
566                           $ver .= ' [SVN r'.$regs[1].']';
567                     }
568                     return $ver;
47124c 569                 }
T 570                 if ($object=='pagetitle') {
83a763 571                     $task  = $this->env['task'];
47124c 572                     $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
T 573
574                     if (!empty($this->pagetitle)) {
575                         $title .= $this->pagetitle;
576                     }
577                     else if ($task == 'login') {
578                         $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $this->config['product_name'])));
579                     }
580                     else {
581                         $title .= ucfirst($task);
582                     }
583
584                     return Q($title);
585                 }
586                 break;
587             
588             // return variable
589             case 'var':
590                 $var = explode(':', $attrib['name']);
591                 $name = $var[1];
592                 $value = '';
593
594                 switch ($var[0]) {
595                     case 'env':
596                         $value = $this->env[$name];
597                         break;
598                     case 'config':
599                         $value = $this->config[$name];
600                         if (is_array($value) && $value[$_SESSION['imap_host']]) {
601                             $value = $value[$_SESSION['imap_host']];
602                         }
603                         break;
604                     case 'request':
605                         $value = get_input_value($name, RCUBE_INPUT_GPC);
606                         break;
607                     case 'session':
608                         $value = $_SESSION[$name];
609                         break;
610                 }
611
612                 if (is_array($value)) {
613                     $value = implode(', ', $value);
614                 }
615
616                 return Q($value);
617                 break;
618         }
619         return '';
620     }
621
622     /**
623      * Include a specific file and return it's contents
624      *
625      * @param string File path
626      * @return string Contents of the processed file
627      */
628     private function include_php($file)
629     {
630         ob_start();
631         include $file;
632         $out = ob_get_contents();
633         ob_end_clean();
634
635         return $out;
636     }
637
638     /**
639      * Create and register a button
640      *
641      * @param  array Named button attributes
642      * @return string HTML button
643      * @todo   Remove all inline JS calls and use jQuery instead.
644      * @todo   Remove all sprintf()'s - they are pretty, but also slow.
645      */
646     private function button($attrib)
647     {
648         static $sa_buttons = array();
649         static $s_button_count = 100;
650
651         // these commands can be called directly via url
652         $a_static_commands = array('compose', 'list');
653
654         if (!($attrib['command'] || $attrib['name'])) {
655             return '';
656         }
ae0c82 657
A 658         $browser   = new rcube_browser();
659
47124c 660         // try to find out the button type
T 661         if ($attrib['type']) {
662             $attrib['type'] = strtolower($attrib['type']);
663         }
664         else {
665             $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
666         }
667         $command = $attrib['command'];
668
669         // take the button from the stack
670         if ($attrib['name'] && $sa_buttons[$attrib['name']]) {
671             $attrib = $sa_buttons[$attrib['name']];
672         }
673         else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class']) {
674             // add button to button stack
675             if (!$attrib['name']) {
676                 $attrib['name'] = $command;
677             }
678             if (!$attrib['image']) {
679                 $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
680             }
681             $sa_buttons[$attrib['name']] = $attrib;
682         }
683         else if ($command && $sa_buttons[$command]) {
684             // get saved button for this command/name
685             $attrib = $sa_buttons[$command];
686         }
687
688         // set border to 0 because of the link arround the button
689         if ($attrib['type']=='image' && !isset($attrib['border'])) {
690             $attrib['border'] = 0;
691         }
692         if (!$attrib['id']) {
693             $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
694         }
695         // get localized text for labels and titles
696         if ($attrib['title']) {
697             $attrib['title'] = Q(rcube_label($attrib['title']));
698         }
699         if ($attrib['label']) {
700             $attrib['label'] = Q(rcube_label($attrib['label']));
701         }
702         if ($attrib['alt']) {
703             $attrib['alt'] = Q(rcube_label($attrib['alt']));
704         }
705         // set title to alt attribute for IE browsers
706         if ($browser->ie && $attrib['title'] && !$attrib['alt']) {
707             $attrib['alt'] = $attrib['title'];
708             unset($attrib['title']);
709         }
710
711         // add empty alt attribute for XHTML compatibility
712         if (!isset($attrib['alt'])) {
713             $attrib['alt'] = '';
714         }
715
716         // register button in the system
717         if ($attrib['command']) {
718             $this->add_script(sprintf(
719                 "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
720                 JS_OBJECT_NAME,
721                 $command,
722                 $attrib['id'],
723                 $attrib['type'],
ae0c82 724                 $attrib['imageact'] ? $this->abs_url($attrib['imageact']) : $attrib['classact'],
A 725                 $attrib['imagesel'] ? $this->abs_url($attrib['imagesel']) : $attrib['classsel'],
726                 $attrib['imageover'] ? $this->abs_url($attrib['imageover']) : ''
47124c 727             ));
T 728
729             // make valid href to specific buttons
197601 730             if (in_array($attrib['command'], rcmail::$main_tasks)) {
47124c 731                 $attrib['href'] = Q(rcmail_url(null, null, $attrib['command']));
T 732             }
733             else if (in_array($attrib['command'], $a_static_commands)) {
734                 $attrib['href'] = Q(rcmail_url($attrib['command']));
735             }
736         }
737
738         // overwrite attributes
739         if (!$attrib['href']) {
740             $attrib['href'] = '#';
741         }
742         if ($command) {
743             $attrib['onclick'] = sprintf(
744                 "return %s.command('%s','%s',this)",
745                 JS_OBJECT_NAME,
746                 $command,
747                 $attrib['prop']
748             );
749         }
750         if ($command && $attrib['imageover']) {
751             $attrib['onmouseover'] = sprintf(
752                 "return %s.button_over('%s','%s')",
753                 JS_OBJECT_NAME,
754                 $command,
755                 $attrib['id']
756             );
757             $attrib['onmouseout'] = sprintf(
758                 "return %s.button_out('%s','%s')",
759                 JS_OBJECT_NAME,
760                 $command,
761                 $attrib['id']
762             );
763         }
764
765         if ($command && $attrib['imagesel']) {
766             $attrib['onmousedown'] = sprintf(
767                 "return %s.button_sel('%s','%s')",
768                 JS_OBJECT_NAME,
769                 $command,
770                 $attrib['id']
771             );
772             $attrib['onmouseup'] = sprintf(
773                 "return %s.button_out('%s','%s')",
774                 JS_OBJECT_NAME,
775                 $command,
776                 $attrib['id']
777             );
778         }
779
780         $out = '';
781
782         // generate image tag
783         if ($attrib['type']=='image') {
784             $attrib_str = html::attrib_string(
785                 $attrib,
786                 array(
787                     'style', 'class', 'id', 'width',
788                     'height', 'border', 'hspace',
23bba0 789                     'vspace', 'align', 'alt', 'tabindex'
47124c 790                 )
T 791             );
ae0c82 792             $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
47124c 793             if ($attrib['label']) {
T 794                 $btn_content .= ' '.$attrib['label'];
795             }
796             $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
797         }
798         else if ($attrib['type']=='link') {
799             $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
23bba0 800             $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style', 'tabindex');
47124c 801         }
T 802         else if ($attrib['type']=='input') {
803             $attrib['type'] = 'button';
804
805             if ($attrib['label']) {
806                 $attrib['value'] = $attrib['label'];
807             }
808
809             $attrib_str = html::attrib_string(
810                 $attrib,
811                 array(
812                     'type', 'value', 'onclick',
23bba0 813                     'id', 'class', 'style', 'tabindex'
47124c 814                 )
T 815             );
816             $out = sprintf('<input%s disabled="disabled" />', $attrib_str);
817         }
818
819         // generate html code for button
820         if ($btn_content) {
821             $attrib_str = html::attrib_string($attrib, $link_attrib);
822             $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
823         }
824
825         return $out;
826     }
827
828
829     /*  ************* common functions delivering gui objects **************  */
830
831
832     /**
197601 833      * Create a form tag with the necessary hidden fields
T 834      *
835      * @param array Named tag parameters
836      * @return string HTML code for the form
837      */
838     public function form_tag($attrib, $content = null)
839     {
840       if ($this->framed) {
841         $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
842         $hidden = $hiddenfield->show();
843       }
844       
845       if (!$content)
846         $attrib['noclose'] = true;
847       
848       return html::tag('form',
849         $attrib + array('action' => "./", 'method' => "get"),
850         $hidden . $content);
851     }
852
853
854     /**
47124c 855      * GUI object 'username'
T 856      * Showing IMAP username of the current session
857      *
858      * @param array Named tag parameters (currently not used)
859      * @return string HTML code for the gui object
860      */
197601 861     public function current_username($attrib)
47124c 862     {
T 863         static $username;
864
865         // alread fetched
866         if (!empty($username)) {
867             return $username;
868         }
869
870         // get e-mail address form default identity
7e9cec 871         if ($sql_arr = $this->app->user->get_identity()) {
T 872             $username = $sql_arr['email'];
47124c 873         }
T 874         else {
7e9cec 875             $username = $this->app->user->get_username();
47124c 876         }
T 877
878         return $username;
879     }
880
881
882     /**
883      * GUI object 'loginform'
884      * Returns code for the webmail login form
885      *
886      * @param array Named parameters
887      * @return string HTML code for the gui object
888      */
889     private function login_form($attrib)
890     {
197601 891         $default_host = $this->config['default_host'];
47124c 892
T 893         $_SESSION['temp'] = true;
894
895         $input_user   = new html_inputfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30, 'autocomplete' => 'off'));
896         $input_pass   = new html_passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
897         $input_action = new html_hiddenfield(array('name' => '_action', 'value' => 'login'));
898         $input_host   = null;
899
900         if (is_array($default_host)) {
901             $input_host = new html_select(array('name' => '_host', 'id' => 'rcmloginhost'));
902
903             foreach ($default_host as $key => $value) {
904                 if (!is_array($value)) {
905                     $input_host->add($value, (is_numeric($key) ? $value : $key));
906                 }
907                 else {
908                     $input_host = null;
909                     break;
910                 }
911             }
912         }
913         else if (!strlen($default_host)) {
914             $input_host = new html_inputfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
915         }
916
917         $form_name  = !empty($attrib['form']) ? $attrib['form'] : 'form';
918         $this->add_gui_object('loginform', $form_name);
919
920         // create HTML table with two cols
921         $table = new html_table(array('cols' => 2));
922
923         $table->add('title', html::label('rcmloginuser', Q(rcube_label('username'))));
924         $table->add(null, $input_user->show(get_input_value('_user', RCUVE_INPUT_POST)));
925
926         $table->add('title', html::label('rcmloginpwd', Q(rcube_label('password'))));
927         $table->add(null, $input_pass->show());
928
929         // add host selection row
930         if (is_object($input_host)) {
931             $table->add('title', html::label('rcmloginhost', Q(rcube_label('server'))));
932             $table->add(null, $input_host->show(get_input_value('_host', RCUVE_INPUT_POST)));
933         }
934
197601 935         $out = $input_action->show();
47124c 936         $out .= $table->show();
T 937
938         // surround html output with a form tag
939         if (empty($attrib['form'])) {
197601 940             $out = $this->form_tag(array('name' => $form_name, 'method' => "post"), $out);
47124c 941         }
T 942
943         return $out;
944     }
945
946
947     /**
948      * GUI object 'searchform'
949      * Returns code for search function
950      *
951      * @param array Named parameters
952      * @return string HTML code for the gui object
953      */
954     private function search_form($attrib)
955     {
956         // add some labels to client
957         $this->add_label('searching');
958
959         $attrib['name'] = '_q';
960
961         if (empty($attrib['id'])) {
962             $attrib['id'] = 'rcmqsearchbox';
963         }
964         $input_q = new html_inputfield($attrib);
965         $out = $input_q->show();
966
967         $this->add_gui_object('qsearchbox', $attrib['id']);
968
969         // add form tag around text field
970         if (empty($attrib['form'])) {
197601 971             $out = $this->form_tag(array(
T 972                 'name' => "rcmqsearchform",
973                 'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
974                 'style' => "display:inline"),
975               $out);
47124c 976         }
T 977
978         return $out;
979     }
980
981
982     /**
983      * Builder for GUI object 'message'
984      *
985      * @param array Named tag parameters
986      * @return string HTML code for the gui object
987      */
988     private function message_container($attrib)
989     {
990         if (isset($attrib['id']) === false) {
991             $attrib['id'] = 'rcmMessageContainer';
992         }
993
994         $this->add_gui_object('message', $attrib['id']);
995         return html::div($attrib, "");
996     }
997
998
999     /**
1000      * GUI object 'charsetselector'
1001      *
1002      * @param array Named parameters for the select tag
1003      * @return string HTML code for the gui object
1004      */
1005     static function charset_selector($attrib)
1006     {
1007         // pass the following attributes to the form class
1008         $field_attrib = array('name' => '_charset');
1009         foreach ($attrib as $attr => $value) {
1010             if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex'))) {
1011                 $field_attrib[$attr] = $value;
1012             }
1013         }
1014         $charsets = array(
1015             'US-ASCII'     => 'ASCII (English)',
1016             'EUC-JP'       => 'EUC-JP (Japanese)',
1017             'EUC-KR'       => 'EUC-KR (Korean)',
1018             'BIG5'         => 'BIG5 (Chinese)',
1019             'GB2312'       => 'GB2312 (Chinese)',
1020             'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1021             'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
1022             'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1023             'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1024             'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1025             'Windows-1251' => 'Windows-1251 (Cyrillic)',
1026             'Windows-1252' => 'Windows-1252 (Western)',
1027             'Windows-1255' => 'Windows-1255 (Hebrew)',
1028             'Windows-1256' => 'Windows-1256 (Arabic)',
1029             'Windows-1257' => 'Windows-1257 (Baltic)',
1030             'UTF-8'        => 'UTF-8'
1031             );
1032
1033             $select = new html_select($field_attrib);
1034             $select->add(array_values($charsets), array_keys($charsets));
1035
1036             $set = $_POST['_charset'] ? $_POST['_charset'] : $this->get_charset();
1037             return $select->show($set);
1038     }
1039
1040 }  // end class rcube_template
1041
1042