]> git.donarmstrong.com Git - roundcube.git/blob - installer/rcube_install.php
Imported Upstream version 0.7.1
[roundcube.git] / installer / rcube_install.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | rcube_install.php                                                     |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail package                    |
8  | Copyright (C) 2008-2011, The Roundcube Dev Team                       |
9  | Licensed under the GNU Public License                                 |
10  +-----------------------------------------------------------------------+
11
12  $Id:  $
13
14 */
15
16
17 /**
18  * Class to control the installation process of the Roundcube Webmail package
19  *
20  * @category Install
21  * @package  Roundcube
22  * @author Thomas Bruederli
23  */
24 class rcube_install
25 {
26   var $step;
27   var $is_post = false;
28   var $failures = 0;
29   var $config = array();
30   var $configured = false;
31   var $last_error = null;
32   var $db_map = array('pgsql' => 'postgres', 'mysqli' => 'mysql', 'sqlsrv' => 'mssql');
33   var $email_pattern = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9])';
34   var $bool_config_props = array();
35
36   var $obsolete_config = array('db_backend', 'double_auth');
37   var $replaced_config = array(
38     'skin_path' => 'skin',
39     'locale_string' => 'language',
40     'multiple_identities' => 'identities_level',
41     'addrbook_show_images' => 'show_images',
42     'imap_root' => 'imap_ns_personal',
43   );
44   
45   // these config options are required for a working system
46   var $required_config = array(
47     'db_dsnw', 'db_table_contactgroups', 'db_table_contactgroupmembers',
48     'des_key', 'session_lifetime',
49   );
50   
51   /**
52    * Constructor
53    */
54   function rcube_install()
55   {
56     $this->step = intval($_REQUEST['_step']);
57     $this->is_post = $_SERVER['REQUEST_METHOD'] == 'POST';
58   }
59   
60   /**
61    * Singleton getter
62    */
63   function get_instance()
64   {
65     static $inst;
66     
67     if (!$inst)
68       $inst = new rcube_install();
69     
70     return $inst;
71   }
72   
73   /**
74    * Read the default config files and store properties
75    */
76   function load_defaults()
77   {
78     $this->_load_config('.php.dist');
79   }
80
81
82   /**
83    * Read the local config files and store properties
84    */
85   function load_config()
86   {
87     $this->config = array();
88     $this->_load_config('.php');
89     $this->configured = !empty($this->config);
90   }
91
92   /**
93    * Read the default config file and store properties
94    * @access private
95    */
96   function _load_config($suffix)
97   {
98     if (is_readable($main_inc = RCMAIL_CONFIG_DIR . '/main.inc' . $suffix)) {
99       include($main_inc);
100       if (is_array($rcmail_config))
101         $this->config += $rcmail_config;
102     }
103     if (is_readable($db_inc = RCMAIL_CONFIG_DIR . '/db.inc'. $suffix)) {
104       include($db_inc);
105       if (is_array($rcmail_config))
106         $this->config += $rcmail_config;
107     }
108   }
109   
110   
111   /**
112    * Getter for a certain config property
113    *
114    * @param string Property name
115    * @param string Default value
116    * @return string The property value
117    */
118   function getprop($name, $default = '')
119   {
120     $value = $this->config[$name];
121     
122     if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"]))
123       $value = rcube_install::random_key(24);
124     
125     return $value !== null && $value !== '' ? $value : $default;
126   }
127
128
129   /**
130    * Take the default config file and replace the parameters
131    * with the submitted form data
132    *
133    * @param string Which config file (either 'main' or 'db')
134    * @return string The complete config file content
135    */
136   function create_config($which, $force = false)
137   {
138     $out = @file_get_contents(RCMAIL_CONFIG_DIR . "/{$which}.inc.php.dist");
139
140     if (!$out)
141       return '[Warning: could not read the config template file]';
142
143     foreach ($this->config as $prop => $default) {
144
145       $is_default = !isset($_POST["_$prop"]);
146       $value      = !$is_default || $this->bool_config_props[$prop] ? $_POST["_$prop"] : $default;
147
148       // convert some form data
149       if ($prop == 'debug_level' && !$is_default) {
150         if (is_array($value)) {
151           $val = 0;
152           foreach ($value as $dbgval)
153             $val += intval($dbgval);
154           $value = $val;
155         }
156       }
157       else if ($which == 'db' && $prop == 'db_dsnw' && !empty($_POST['_dbtype'])) {
158         if ($_POST['_dbtype'] == 'sqlite')
159           $value = sprintf('%s://%s?mode=0646', $_POST['_dbtype'], $_POST['_dbname']{0} == '/' ? '/' . $_POST['_dbname'] : $_POST['_dbname']);
160         else if ($_POST['_dbtype'])
161           $value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'], 
162             rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
163       }
164       else if ($prop == 'smtp_auth_type' && $value == '0') {
165         $value = '';
166       }
167       else if ($prop == 'default_host' && is_array($value)) {
168         $value = rcube_install::_clean_array($value);
169         if (count($value) <= 1)
170           $value = $value[0];
171       }
172       else if ($prop == 'pagesize') {
173         $value = max(2, intval($value));
174       }
175       else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
176         $value = '%u';
177       }
178       else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
179         $value = '%p';
180       }
181       else if ($prop == 'default_imap_folders') {
182             $value = array();
183             foreach ($this->config['default_imap_folders'] as $_folder) {
184               switch ($_folder) {
185               case 'Drafts': $_folder = $this->config['drafts_mbox']; break;
186               case 'Sent':   $_folder = $this->config['sent_mbox']; break;
187               case 'Junk':   $_folder = $this->config['junk_mbox']; break;
188               case 'Trash':  $_folder = $this->config['trash_mbox']; break;
189           }
190             if (!in_array($_folder, $value))
191               $value[] = $_folder;
192         }
193       }
194       else if (is_bool($default)) {
195         $value = (bool)$value;
196       }
197       else if (is_numeric($value)) {
198         $value = intval($value);
199       }
200
201       // skip this property
202       if (!$force && !$this->configured && ($value == $default))
203         continue;
204
205       // save change
206       $this->config[$prop] = $value;
207
208       // replace the matching line in config file
209       $out = preg_replace(
210         '/(\$rcmail_config\[\''.preg_quote($prop).'\'\])\s+=\s+(.+);/Uie',
211         "'\\1 = ' . rcube_install::_dump_var(\$value, \$prop) . ';'",
212         $out);
213     }
214
215     return trim($out);
216   }
217
218
219   /**
220    * Check the current configuration for missing properties
221    * and deprecated or obsolete settings
222    *
223    * @return array List with problems detected
224    */
225   function check_config()
226   {
227     $this->config = array();
228     $this->load_defaults();
229     $defaults = $this->config;
230     
231     $this->load_config();
232     if (!$this->configured)
233       return null;
234     
235     $out = $seen = array();
236     $required = array_flip($this->required_config);
237     
238     // iterate over the current configuration
239     foreach ($this->config as $prop => $value) {
240       if ($replacement = $this->replaced_config[$prop]) {
241         $out['replaced'][] = array('prop' => $prop, 'replacement' => $replacement);
242         $seen[$replacement] = true;
243       }
244       else if (!$seen[$prop] && in_array($prop, $this->obsolete_config)) {
245         $out['obsolete'][] = array('prop' => $prop);
246         $seen[$prop] = true;
247       }
248     }
249     
250     // iterate over default config
251     foreach ($defaults as $prop => $value) {
252       if (!isset($seen[$prop]) && !isset($this->config[$prop]) && isset($required[$prop]))
253         $out['missing'][] = array('prop' => $prop);
254     }
255
256     // check config dependencies and contradictions
257     if ($this->config['enable_spellcheck'] && $this->config['spellcheck_engine'] == 'pspell') {
258       if (!extension_loaded('pspell')) {
259         $out['dependencies'][] = array('prop' => 'spellcheck_engine',
260           'explain' => 'This requires the <tt>pspell</tt> extension which could not be loaded.');
261       }
262       else if (!empty($this->config['spellcheck_languages'])) {
263         foreach ($this->config['spellcheck_languages'] as $lang => $descr)
264           if (!pspell_new($lang))
265             $out['dependencies'][] = array('prop' => 'spellcheck_languages',
266               'explain' => "You are missing pspell support for language $lang ($descr)");
267       }
268     }
269     
270     if ($this->config['log_driver'] == 'syslog') {
271       if (!function_exists('openlog')) {
272         $out['dependencies'][] = array('prop' => 'log_driver',
273           'explain' => 'This requires the <tt>sylog</tt> extension which could not be loaded.');
274       }
275       if (empty($this->config['syslog_id'])) {
276         $out['dependencies'][] = array('prop' => 'syslog_id',
277           'explain' => 'Using <tt>syslog</tt> for logging requires a syslog ID to be configured');
278       }
279     }
280     
281     // check ldap_public sources having global_search enabled
282     if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
283       foreach ($this->config['ldap_public'] as $ldap_public) {
284         if ($ldap_public['global_search']) {
285           $out['replaced'][] = array('prop' => 'ldap_public::global_search', 'replacement' => 'autocomplete_addressbooks');
286           break;
287         }
288       }
289     }
290     
291     return $out;
292   }
293   
294   
295   /**
296    * Merge the current configuration with the defaults
297    * and copy replaced values to the new options.
298    */
299   function merge_config()
300   {
301     $current = $this->config;
302     $this->config = array();
303     $this->load_defaults();
304
305     foreach ($this->replaced_config as $prop => $replacement) {
306       if (isset($current[$prop])) {
307         if ($prop == 'skin_path')
308           $this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
309         else if ($prop == 'multiple_identities')
310           $this->config[$replacement] = $current[$prop] ? 2 : 0;
311         else
312           $this->config[$replacement] = $current[$prop];
313       }
314       unset($current[$prop]);
315     }
316     
317     foreach ($this->obsolete_config as $prop) {
318       unset($current[$prop]);
319     }
320     
321     // add all ldap_public sources having global_search enabled to autocomplete_addressbooks
322     if (is_array($current['ldap_public'])) {
323       foreach ($current['ldap_public'] as $key => $ldap_public) {
324         if ($ldap_public['global_search']) {
325           $this->config['autocomplete_addressbooks'][] = $key;
326           unset($current['ldap_public'][$key]['global_search']);
327         }
328       }
329     }
330     
331     if ($current['keep_alive'] && $current['session_lifetime'] < $current['keep_alive'])
332       $current['session_lifetime'] = max(10, ceil($current['keep_alive'] / 60) * 2);
333
334     $this->config  = array_merge($this->config, $current);
335
336     foreach ((array)$current['ldap_public'] as $key => $values) {
337       $this->config['ldap_public'][$key] = $current['ldap_public'][$key];
338     }
339   }
340   
341   /**
342    * Compare the local database schema with the reference schema
343    * required for this version of Roundcube
344    *
345    * @param boolean True if the schema schould be updated
346    * @return boolean True if the schema is up-to-date, false if not or an error occured
347    */
348   function db_schema_check($DB, $update = false)
349   {
350     if (!$this->configured)
351       return false;
352     
353     // read reference schema from mysql.initial.sql
354     $db_schema = $this->db_read_schema(INSTALL_PATH . 'SQL/mysql.initial.sql');
355     $errors = array();
356     
357     // check list of tables
358     $existing_tables = $DB->list_tables();
359
360     foreach ($db_schema as $table => $cols) {
361       $table = !empty($this->config['db_table_'.$table]) ? $this->config['db_table_'.$table] : $table;
362       if (!in_array($table, $existing_tables)) {
363         $errors[] = "Missing table '".$table."'";
364       }
365       else {  // compare cols
366         $db_cols = $DB->list_cols($table);
367         $diff = array_diff(array_keys($cols), $db_cols);
368         if (!empty($diff))
369           $errors[] = "Missing columns in table '$table': " . join(',', $diff);
370       }
371     }
372     
373     return !empty($errors) ? $errors : false;
374   }
375
376   /**
377    * Utility function to read database schema from an .sql file
378    */
379   private function db_read_schema($schemafile)
380   {
381     $lines = file($schemafile);
382     $table_block = false;
383     $schema = array();
384     foreach ($lines as $line) {
385       if (preg_match('/^\s*create table `?([a-z0-9_]+)`?/i', $line, $m)) {
386         $table_block = $m[1];
387       }
388       else if ($table_block && preg_match('/^\s*`?([a-z0-9_-]+)`?\s+([a-z]+)/', $line, $m)) {
389         $col = $m[1];
390         if (!in_array(strtoupper($col), array('PRIMARY','KEY','INDEX','UNIQUE','CONSTRAINT','REFERENCES','FOREIGN'))) {
391           $schema[$table_block][$col] = $m[2];
392         }
393       }
394     }
395     
396     return $schema;
397   }
398   
399   
400   /**
401    * Compare the local database schema with the reference schema
402    * required for this version of Roundcube
403    *
404    * @param boolean True if the schema schould be updated
405    * @return boolean True if the schema is up-to-date, false if not or an error occured
406    */
407   function mdb2_schema_check($update = false)
408   {
409     if (!$this->configured)
410       return false;
411     
412     $options = array(
413       'use_transactions' => false,
414       'log_line_break' => "\n",
415       'idxname_format' => '%s',
416       'debug' => false,
417       'quote_identifier' => true,
418       'force_defaults' => false,
419       'portability' => true
420     );
421     
422     $dsnw = $this->config['db_dsnw'];
423     $schema = MDB2_Schema::factory($dsnw, $options);
424     $schema->db->supported['transactions'] = false;
425     
426     if (PEAR::isError($schema)) {
427       $this->raise_error(array('code' => $schema->getCode(), 'message' => $schema->getMessage() . ' ' . $schema->getUserInfo()));
428       return false;
429     }
430     else {
431       $definition = $schema->getDefinitionFromDatabase();
432       $definition['charset'] = 'utf8';
433       
434       if (PEAR::isError($definition)) {
435         $this->raise_error(array('code' => $definition->getCode(), 'message' => $definition->getMessage() . ' ' . $definition->getUserInfo()));
436         return false;
437       }
438       
439       // load reference schema
440       $dsn_arr = MDB2::parseDSN($this->config['db_dsnw']);
441
442       $ref_schema = INSTALL_PATH . 'SQL/' . $dsn_arr['phptype'] . '.schema.xml';
443       
444       if (is_readable($ref_schema)) {
445         $reference = $schema->parseDatabaseDefinition($ref_schema, false, array(), $schema->options['fail_on_invalid_names']);
446         
447         if (PEAR::isError($reference)) {
448           $this->raise_error(array('code' => $reference->getCode(), 'message' => $reference->getMessage() . ' ' . $reference->getUserInfo()));
449         }
450         else {
451           $diff = $schema->compareDefinitions($reference, $definition);
452           
453           if (empty($diff)) {
454             return true;
455           }
456           else if ($update) {
457             // update database schema with the diff from the above check
458             $success = $schema->alterDatabase($reference, $definition, $diff);
459             
460             if (PEAR::isError($success)) {
461               $this->raise_error(array('code' => $success->getCode(), 'message' => $success->getMessage() . ' ' . $success->getUserInfo()));
462             }
463             else
464               return true;
465           }
466           echo '<pre>'; var_dump($diff); echo '</pre>';
467           return false;
468         }
469       }
470       else
471         $this->raise_error(array('message' => "Could not find reference schema file ($ref_schema)"));
472         return false;
473     }
474     
475     return false;
476   }
477   
478   
479   /**
480    * Getter for the last error message
481    *
482    * @return string Error message or null if none exists
483    */
484   function get_error()
485   {
486       return $this->last_error['message'];
487   }
488   
489   
490   /**
491    * Return a list with all imap hosts configured
492    *
493    * @return array Clean list with imap hosts
494    */
495   function get_hostlist()
496   {
497     $default_hosts = (array)$this->getprop('default_host');
498     $out = array();
499     
500     foreach ($default_hosts as $key => $name) {
501       if (!empty($name))
502         $out[] = rcube_parse_host(is_numeric($key) ? $name : $key);
503     }
504     
505     return $out;
506   }
507
508   /**
509    * Create a HTML dropdown to select a previous version of Roundcube
510    */
511   function versions_select($attrib = array())
512   {
513     $select = new html_select($attrib);
514     $select->add(array(
515         '0.1-stable', '0.1.1',
516         '0.2-alpha', '0.2-beta', '0.2-stable',
517         '0.3-stable', '0.3.1',
518         '0.4-beta', '0.4.2',
519         '0.5-beta', '0.5', '0.5.1',
520         '0.6-beta', '0.6',
521         '0.7-beta', '0.7',
522     ));
523     return $select;
524   }
525
526   /**
527    * Return a list with available subfolders of the skin directory
528    */
529   function list_skins()
530   {
531     $skins = array();
532     $skindir = INSTALL_PATH . 'skins/';
533     foreach (glob($skindir . '*') as $path) {
534       if (is_dir($path) && is_readable($path)) {
535         $skins[] = substr($path, strlen($skindir));
536       }
537     }
538     return $skins;
539   }
540   
541   /**
542    * Display OK status
543    *
544    * @param string Test name
545    * @param string Confirm message
546    */
547   function pass($name, $message = '')
548   {
549     echo Q($name) . ':&nbsp; <span class="success">OK</span>';
550     $this->_showhint($message);
551   }
552   
553   
554   /**
555    * Display an error status and increase failure count
556    *
557    * @param string Test name
558    * @param string Error message
559    * @param string URL for details
560    */
561   function fail($name, $message = '', $url = '')
562   {
563     $this->failures++;
564     
565     echo Q($name) . ':&nbsp; <span class="fail">NOT OK</span>';
566     $this->_showhint($message, $url);
567   }
568
569
570   /**
571    * Display an error status for optional settings/features
572    *
573    * @param string Test name
574    * @param string Error message
575    * @param string URL for details
576    */
577   function optfail($name, $message = '', $url = '')
578   {
579     echo Q($name) . ':&nbsp; <span class="na">NOT OK</span>';
580     $this->_showhint($message, $url);
581   }
582   
583   
584   /**
585    * Display warning status
586    *
587    * @param string Test name
588    * @param string Warning message
589    * @param string URL for details
590    */
591   function na($name, $message = '', $url = '')
592   {
593     echo Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
594     $this->_showhint($message, $url);
595   }
596   
597   
598   function _showhint($message, $url = '')
599   {
600     $hint = Q($message);
601     
602     if ($url)
603       $hint .= ($hint ? '; ' : '') . 'See <a href="' . Q($url) . '" target="_blank">' . Q($url) . '</a>';
604       
605     if ($hint)
606       echo '<span class="indent">(' . $hint . ')</span>';
607   }
608   
609   
610   static function _clean_array($arr)
611   {
612     $out = array();
613     
614     foreach (array_unique($arr) as $k => $val) {
615       if (!empty($val)) {
616         if (is_numeric($k))
617           $out[] = $val;
618         else
619           $out[$k] = $val;
620       }
621     }
622     
623     return $out;
624   }
625   
626   
627   static function _dump_var($var, $name=null) {
628     // special values
629     switch ($name) {
630     case 'syslog_facility':
631       $list = array(32 => 'LOG_AUTH', 80 => 'LOG_AUTHPRIV', 72 => ' LOG_CRON',
632                     24 => 'LOG_DAEMON', 0 => 'LOG_KERN', 128 => 'LOG_LOCAL0',
633                     136 => 'LOG_LOCAL1', 144 => 'LOG_LOCAL2', 152 => 'LOG_LOCAL3',
634                     160 => 'LOG_LOCAL4', 168 => 'LOG_LOCAL5', 176 => 'LOG_LOCAL6',
635                     184 => 'LOG_LOCAL7', 48 => 'LOG_LPR', 16 => 'LOG_MAIL',
636                     56 => 'LOG_NEWS', 40 => 'LOG_SYSLOG', 8 => 'LOG_USER', 64 => 'LOG_UUCP');
637       if ($val = $list[$var])
638         return $val;
639       break;
640     }
641
642
643     if (is_array($var)) {
644       if (empty($var)) {
645         return 'array()';
646       }
647       else {  // check if all keys are numeric
648         $isnum = true;
649         foreach ($var as $key => $value) {
650           if (!is_numeric($key)) {
651             $isnum = false;
652             break;
653           }
654         }
655         
656         if ($isnum)
657           return 'array(' . join(', ', array_map(array('rcube_install', '_dump_var'), $var)) . ')';
658       }
659     }
660     
661     return var_export($var, true);
662   }
663   
664   
665   /**
666    * Initialize the database with the according schema
667    *
668    * @param object rcube_db Database connection
669    * @return boolen True on success, False on error
670    */
671   function init_db($DB)
672   {
673     $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
674     
675     // read schema file from /SQL/*
676     $fname = INSTALL_PATH . "SQL/$engine.initial.sql";
677     if ($sql = @file_get_contents($fname)) {
678       $this->exec_sql($sql, $DB);
679     }
680     else {
681       $this->fail('DB Schema', "Cannot read the schema file: $fname");
682       return false;
683     }
684     
685     if ($err = $this->get_error()) {
686       $this->fail('DB Schema', "Error creating database schema: $err");
687       return false;
688     }
689
690     return true;
691   }
692   
693   
694   /**
695    * Update database with SQL statements from SQL/*.update.sql
696    *
697    * @param object rcube_db Database connection
698    * @param string Version to update from
699    * @return boolen True on success, False on error
700    */
701   function update_db($DB, $version)
702   {
703     $version = strtolower($version);
704     $engine = isset($this->db_map[$DB->db_provider]) ? $this->db_map[$DB->db_provider] : $DB->db_provider;
705     
706     // read schema file from /SQL/*
707     $fname = INSTALL_PATH . "SQL/$engine.update.sql";
708     if ($lines = @file($fname, FILE_SKIP_EMPTY_LINES)) {
709       $from = false; $sql = '';
710       foreach ($lines as $line) {
711         $is_comment = preg_match('/^--/', $line);
712         if (!$from && $is_comment && preg_match('/from version\s([0-9.]+[a-z-]*)/', $line, $m)) {
713           $v = strtolower($m[1]);
714           if ($v == $version || version_compare($version, $v, '<='))
715             $from = true;
716         }
717         if ($from && !$is_comment)
718           $sql .= $line. "\n";
719       }
720       
721       if ($sql)
722         $this->exec_sql($sql, $DB);
723     }
724     else {
725       $this->fail('DB Schema', "Cannot read the update file: $fname");
726       return false;
727     }
728     
729     if ($err = $this->get_error()) {
730       $this->fail('DB Schema', "Error updating database: $err");
731       return false;
732     }
733
734     return true;
735   }
736   
737   
738   /**
739    * Execute the given SQL queries on the database connection
740    *
741    * @param string SQL queries to execute
742    * @param object rcube_db Database connection
743    * @return boolen True on success, False on error
744    */
745   function exec_sql($sql, $DB)
746   {
747     $buff = '';
748     foreach (explode("\n", $sql) as $line) {
749       if (preg_match('/^--/', $line) || trim($line) == '')
750         continue;
751         
752       $buff .= $line . "\n";
753       if (preg_match('/(;|^GO)$/', trim($line))) {
754         $DB->query($buff);
755         $buff = '';
756         if ($DB->is_error())
757           break;
758       }
759     }
760     
761     return !$DB->is_error();
762   }
763   
764   
765   /**
766    * Handler for Roundcube errors
767    */
768   function raise_error($p)
769   {
770       $this->last_error = $p;
771   }
772   
773   
774   /**
775    * Generarte a ramdom string to be used as encryption key
776    *
777    * @param int Key length
778    * @return string The generated random string
779    * @static
780    */
781   function random_key($length)
782   {
783     $alpha = 'ABCDEFGHIJKLMNOPQERSTUVXYZabcdefghijklmnopqrtsuvwxyz0123456789+*%&?!$-_=';
784     $out = '';
785     
786     for ($i=0; $i < $length; $i++)
787       $out .= $alpha{rand(0, strlen($alpha)-1)};
788     
789     return $out;
790   }
791   
792 }
793