source: github/installer/rcube_install.php @ 5fed074

HEADdev-browser-capabilitiespdo
Last change on this file since 5fed074 was 5fed074, checked in by Aleksander Machniak <alec@…>, 13 months ago

Always use 1 step as a fallback (#1488490)

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