Textpattern PHP Cross Reference Content Management Systems

Source: /textpattern/vendors/Textpattern/Password/Generator.php - 91 lines - 2027 bytes - Summary - Text - Print

Description: Generates a password.

   1  <?php
   2  
   3  /*
   4   * Textpattern Content Management System
   5   * http://textpattern.com
   6   *
   7   * Copyright (C) 2016 The Textpattern Development Team
   8   *
   9   * This file is part of Textpattern.
  10   *
  11   * Textpattern is free software; you can redistribute it and/or
  12   * modify it under the terms of the GNU General Public License
  13   * as published by the Free Software Foundation, version 2.
  14   *
  15   * Textpattern is distributed in the hope that it will be useful,
  16   * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18   * GNU General Public License for more details.
  19   *
  20   * You should have received a copy of the GNU General Public License
  21   * along with Textpattern. If not, see <http://www.gnu.org/licenses/>.
  22   */
  23  
  24  /**
  25   * Generates a password.
  26   *
  27   * <code>
  28   * echo Txp::get('\Textpattern\Password\Generator')->generate(16);
  29   * </code>
  30   *
  31   * @since   4.6.0
  32   * @package Password
  33   */
  34  
  35  namespace Textpattern\Password;
  36  
  37  class Generator
  38  {
  39      /**
  40       * Stores the character table.
  41       *
  42       * @var array
  43       */
  44  
  45      protected $chars;
  46  
  47      /**
  48       * Gets the character table.
  49       *
  50       * @return array
  51       */
  52  
  53      public function getCharacterTable()
  54      {
  55          if (!$this->chars) {
  56              $this->chars = str_split(PASSWORD_SYMBOLS);
  57          }
  58  
  59          return $this->chars;
  60      }
  61  
  62      /**
  63       * Generates a random password.
  64       *
  65       * <code>
  66       * echo Txp::get('\Textpattern\Password\Generator')->generate(16);
  67       * </code>
  68       *
  69       * @param  int $length The length of the generated password
  70       * @return string The password
  71       */
  72  
  73      public function generate($length)
  74      {
  75          $pool = false;
  76          $pass = '';
  77  
  78          for ($i = 0; $i < $length; $i++) {
  79              if (!$pool) {
  80                  $pool = $this->getCharacterTable();
  81              }
  82  
  83              $index = mt_rand(0, count($pool) - 1);
  84              $pass .= $pool[$index];
  85              unset($pool[$index]);
  86              $pool = array_values($pool);
  87          }
  88  
  89          return $pass;
  90      }
  91  }

title

Description

title

Description

title

Description

title

title

Body