[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/lib/plugins/authplain/ -> auth.php (source)

   1  <?php
   2  use dokuwiki\Utf8\Sort;
   3  
   4  /**
   5   * Plaintext authentication backend
   6   *
   7   * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
   8   * @author     Andreas Gohr <andi@splitbrain.org>
   9   * @author     Chris Smith <chris@jalakai.co.uk>
  10   * @author     Jan Schumann <js@schumann-it.com>
  11   */
  12  class auth_plugin_authplain extends DokuWiki_Auth_Plugin
  13  {
  14      /** @var array user cache */
  15      protected $users = null;
  16  
  17      /** @var array filter pattern */
  18      protected $pattern = array();
  19  
  20      /** @var bool safe version of preg_split */
  21      protected $pregsplit_safe = false;
  22  
  23      /**
  24       * Constructor
  25       *
  26       * Carry out sanity checks to ensure the object is
  27       * able to operate. Set capabilities.
  28       *
  29       * @author  Christopher Smith <chris@jalakai.co.uk>
  30       */
  31      public function __construct()
  32      {
  33          parent::__construct();
  34          global $config_cascade;
  35  
  36          if (!@is_readable($config_cascade['plainauth.users']['default'])) {
  37              $this->success = false;
  38          } else {
  39              if (@is_writable($config_cascade['plainauth.users']['default'])) {
  40                  $this->cando['addUser']   = true;
  41                  $this->cando['delUser']   = true;
  42                  $this->cando['modLogin']  = true;
  43                  $this->cando['modPass']   = true;
  44                  $this->cando['modName']   = true;
  45                  $this->cando['modMail']   = true;
  46                  $this->cando['modGroups'] = true;
  47              }
  48              $this->cando['getUsers']     = true;
  49              $this->cando['getUserCount'] = true;
  50              $this->cando['getGroups']    = true;
  51          }
  52  
  53          $this->pregsplit_safe = version_compare(PCRE_VERSION, '6.7', '>=');
  54      }
  55  
  56      /**
  57       * Check user+password
  58       *
  59       * Checks if the given user exists and the given
  60       * plaintext password is correct
  61       *
  62       * @author  Andreas Gohr <andi@splitbrain.org>
  63       * @param string $user
  64       * @param string $pass
  65       * @return  bool
  66       */
  67      public function checkPass($user, $pass)
  68      {
  69          $userinfo = $this->getUserData($user);
  70          if ($userinfo === false) return false;
  71  
  72          return auth_verifyPassword($pass, $this->users[$user]['pass']);
  73      }
  74  
  75      /**
  76       * Return user info
  77       *
  78       * Returns info about the given user needs to contain
  79       * at least these fields:
  80       *
  81       * name string  full name of the user
  82       * mail string  email addres of the user
  83       * grps array   list of groups the user is in
  84       *
  85       * @author  Andreas Gohr <andi@splitbrain.org>
  86       * @param string $user
  87       * @param bool $requireGroups  (optional) ignored by this plugin, grps info always supplied
  88       * @return array|false
  89       */
  90      public function getUserData($user, $requireGroups = true)
  91      {
  92          if ($this->users === null) $this->loadUserData();
  93          return isset($this->users[$user]) ? $this->users[$user] : false;
  94      }
  95  
  96      /**
  97       * Creates a string suitable for saving as a line
  98       * in the file database
  99       * (delimiters escaped, etc.)
 100       *
 101       * @param string $user
 102       * @param string $pass
 103       * @param string $name
 104       * @param string $mail
 105       * @param array  $grps list of groups the user is in
 106       * @return string
 107       */
 108      protected function createUserLine($user, $pass, $name, $mail, $grps)
 109      {
 110          $groups   = join(',', $grps);
 111          $userline = array($user, $pass, $name, $mail, $groups);
 112          $userline = str_replace('\\', '\\\\', $userline); // escape \ as \\
 113          $userline = str_replace(':', '\\:', $userline); // escape : as \:
 114          $userline = join(':', $userline)."\n";
 115          return $userline;
 116      }
 117  
 118      /**
 119       * Create a new User
 120       *
 121       * Returns false if the user already exists, null when an error
 122       * occurred and true if everything went well.
 123       *
 124       * The new user will be added to the default group by this
 125       * function if grps are not specified (default behaviour).
 126       *
 127       * @author  Andreas Gohr <andi@splitbrain.org>
 128       * @author  Chris Smith <chris@jalakai.co.uk>
 129       *
 130       * @param string $user
 131       * @param string $pwd
 132       * @param string $name
 133       * @param string $mail
 134       * @param array  $grps
 135       * @return bool|null|string
 136       */
 137      public function createUser($user, $pwd, $name, $mail, $grps = null)
 138      {
 139          global $conf;
 140          global $config_cascade;
 141  
 142          // user mustn't already exist
 143          if ($this->getUserData($user) !== false) {
 144              msg($this->getLang('userexists'), -1);
 145              return false;
 146          }
 147  
 148          $pass = auth_cryptPassword($pwd);
 149  
 150          // set default group if no groups specified
 151          if (!is_array($grps)) $grps = array($conf['defaultgroup']);
 152  
 153          // prepare user line
 154          $userline = $this->createUserLine($user, $pass, $name, $mail, $grps);
 155  
 156          if (!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) {
 157              msg($this->getLang('writefail'), -1);
 158              return null;
 159          }
 160  
 161          $this->users[$user] = compact('pass', 'name', 'mail', 'grps');
 162          return $pwd;
 163      }
 164  
 165      /**
 166       * Modify user data
 167       *
 168       * @author  Chris Smith <chris@jalakai.co.uk>
 169       * @param   string $user      nick of the user to be changed
 170       * @param   array  $changes   array of field/value pairs to be changed (password will be clear text)
 171       * @return  bool
 172       */
 173      public function modifyUser($user, $changes)
 174      {
 175          global $ACT;
 176          global $config_cascade;
 177  
 178          // sanity checks, user must already exist and there must be something to change
 179          if (($userinfo = $this->getUserData($user)) === false) {
 180              msg($this->getLang('usernotexists'), -1);
 181              return false;
 182          }
 183  
 184          // don't modify protected users
 185          if (!empty($userinfo['protected'])) {
 186              msg(sprintf($this->getLang('protected'), hsc($user)), -1);
 187              return false;
 188          }
 189  
 190          if (!is_array($changes) || !count($changes)) return true;
 191  
 192          // update userinfo with new data, remembering to encrypt any password
 193          $newuser = $user;
 194          foreach ($changes as $field => $value) {
 195              if ($field == 'user') {
 196                  $newuser = $value;
 197                  continue;
 198              }
 199              if ($field == 'pass') $value = auth_cryptPassword($value);
 200              $userinfo[$field] = $value;
 201          }
 202  
 203          $userline = $this->createUserLine(
 204              $newuser,
 205              $userinfo['pass'],
 206              $userinfo['name'],
 207              $userinfo['mail'],
 208              $userinfo['grps']
 209          );
 210  
 211          if (!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^'.$user.':/', $userline, true)) {
 212              msg('There was an error modifying your user data. You may need to register again.', -1);
 213              // FIXME, io functions should be fail-safe so existing data isn't lost
 214              $ACT = 'register';
 215              return false;
 216          }
 217  
 218          $this->users[$newuser] = $userinfo;
 219          return true;
 220      }
 221  
 222      /**
 223       * Remove one or more users from the list of registered users
 224       *
 225       * @author  Christopher Smith <chris@jalakai.co.uk>
 226       * @param   array  $users   array of users to be deleted
 227       * @return  int             the number of users deleted
 228       */
 229      public function deleteUsers($users)
 230      {
 231          global $config_cascade;
 232  
 233          if (!is_array($users) || empty($users)) return 0;
 234  
 235          if ($this->users === null) $this->loadUserData();
 236  
 237          $deleted = array();
 238          foreach ($users as $user) {
 239              // don't delete protected users
 240              if (!empty($this->users[$user]['protected'])) {
 241                  msg(sprintf($this->getLang('protected'), hsc($user)), -1);
 242                  continue;
 243              }
 244              if (isset($this->users[$user])) $deleted[] = preg_quote($user, '/');
 245          }
 246  
 247          if (empty($deleted)) return 0;
 248  
 249          $pattern = '/^('.join('|', $deleted).'):/';
 250          if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) {
 251              msg($this->getLang('writefail'), -1);
 252              return 0;
 253          }
 254  
 255          // reload the user list and count the difference
 256          $count = count($this->users);
 257          $this->loadUserData();
 258          $count -= count($this->users);
 259          return $count;
 260      }
 261  
 262      /**
 263       * Return a count of the number of user which meet $filter criteria
 264       *
 265       * @author  Chris Smith <chris@jalakai.co.uk>
 266       *
 267       * @param array $filter
 268       * @return int
 269       */
 270      public function getUserCount($filter = array())
 271      {
 272  
 273          if ($this->users === null) $this->loadUserData();
 274  
 275          if (!count($filter)) return count($this->users);
 276  
 277          $count = 0;
 278          $this->constructPattern($filter);
 279  
 280          foreach ($this->users as $user => $info) {
 281              $count += $this->filter($user, $info);
 282          }
 283  
 284          return $count;
 285      }
 286  
 287      /**
 288       * Bulk retrieval of user data
 289       *
 290       * @author  Chris Smith <chris@jalakai.co.uk>
 291       *
 292       * @param   int   $start index of first user to be returned
 293       * @param   int   $limit max number of users to be returned
 294       * @param   array $filter array of field/pattern pairs
 295       * @return  array userinfo (refer getUserData for internal userinfo details)
 296       */
 297      public function retrieveUsers($start = 0, $limit = 0, $filter = array())
 298      {
 299  
 300          if ($this->users === null) $this->loadUserData();
 301  
 302          Sort::ksort($this->users);
 303  
 304          $i     = 0;
 305          $count = 0;
 306          $out   = array();
 307          $this->constructPattern($filter);
 308  
 309          foreach ($this->users as $user => $info) {
 310              if ($this->filter($user, $info)) {
 311                  if ($i >= $start) {
 312                      $out[$user] = $info;
 313                      $count++;
 314                      if (($limit > 0) && ($count >= $limit)) break;
 315                  }
 316                  $i++;
 317              }
 318          }
 319  
 320          return $out;
 321      }
 322  
 323      /**
 324       * Retrieves groups.
 325       * Loads complete user data into memory before searching for groups.
 326       *
 327       * @param   int   $start index of first group to be returned
 328       * @param   int   $limit max number of groups to be returned
 329       * @return  array
 330       */
 331      public function retrieveGroups($start = 0, $limit = 0)
 332      {
 333          $groups = [];
 334  
 335          if ($this->users === null) $this->loadUserData();
 336          foreach($this->users as $user => $info) {
 337              $groups = array_merge($groups, array_diff($info['grps'], $groups));
 338          }
 339          Sort::ksort($groups);
 340  
 341          if($limit > 0) {
 342              return array_splice($groups, $start, $limit);
 343          }
 344          return array_splice($groups, $start);
 345      }
 346  
 347      /**
 348       * Only valid pageid's (no namespaces) for usernames
 349       *
 350       * @param string $user
 351       * @return string
 352       */
 353      public function cleanUser($user)
 354      {
 355          global $conf;
 356          return cleanID(str_replace(':', $conf['sepchar'], $user));
 357      }
 358  
 359      /**
 360       * Only valid pageid's (no namespaces) for groupnames
 361       *
 362       * @param string $group
 363       * @return string
 364       */
 365      public function cleanGroup($group)
 366      {
 367          global $conf;
 368          return cleanID(str_replace(':', $conf['sepchar'], $group));
 369      }
 370  
 371      /**
 372       * Load all user data
 373       *
 374       * loads the user file into a datastructure
 375       *
 376       * @author  Andreas Gohr <andi@splitbrain.org>
 377       */
 378      protected function loadUserData()
 379      {
 380          global $config_cascade;
 381  
 382          $this->users = $this->readUserFile($config_cascade['plainauth.users']['default']);
 383  
 384          // support protected users
 385          if (!empty($config_cascade['plainauth.users']['protected'])) {
 386              $protected = $this->readUserFile($config_cascade['plainauth.users']['protected']);
 387              foreach (array_keys($protected) as $key) {
 388                  $protected[$key]['protected'] = true;
 389              }
 390              $this->users = array_merge($this->users, $protected);
 391          }
 392      }
 393  
 394      /**
 395       * Read user data from given file
 396       *
 397       * ignores non existing files
 398       *
 399       * @param string $file the file to load data from
 400       * @return array
 401       */
 402      protected function readUserFile($file)
 403      {
 404          $users = array();
 405          if (!file_exists($file)) return $users;
 406  
 407          $lines = file($file);
 408          foreach ($lines as $line) {
 409              $line = preg_replace('/#.*$/', '', $line); //ignore comments
 410              $line = trim($line);
 411              if (empty($line)) continue;
 412  
 413              $row = $this->splitUserData($line);
 414              $row = str_replace('\\:', ':', $row);
 415              $row = str_replace('\\\\', '\\', $row);
 416  
 417              $groups = array_values(array_filter(explode(",", $row[4])));
 418  
 419              $users[$row[0]]['pass'] = $row[1];
 420              $users[$row[0]]['name'] = urldecode($row[2]);
 421              $users[$row[0]]['mail'] = $row[3];
 422              $users[$row[0]]['grps'] = $groups;
 423          }
 424          return $users;
 425      }
 426  
 427      /**
 428       * Get the user line split into it's parts
 429       *
 430       * @param string $line
 431       * @return string[]
 432       */
 433      protected function splitUserData($line)
 434      {
 435          // due to a bug in PCRE 6.6, preg_split will fail with the regex we use here
 436          // refer github issues 877 & 885
 437          if ($this->pregsplit_safe) {
 438              return preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5);       // allow for : escaped as \:
 439          }
 440  
 441          $row = array();
 442          $piece = '';
 443          $len = strlen($line);
 444          for ($i=0; $i<$len; $i++) {
 445              if ($line[$i]=='\\') {
 446                  $piece .= $line[$i];
 447                  $i++;
 448                  if ($i>=$len) break;
 449              } elseif ($line[$i]==':') {
 450                  $row[] = $piece;
 451                  $piece = '';
 452                  continue;
 453              }
 454              $piece .= $line[$i];
 455          }
 456          $row[] = $piece;
 457  
 458          return $row;
 459      }
 460  
 461      /**
 462       * return true if $user + $info match $filter criteria, false otherwise
 463       *
 464       * @author   Chris Smith <chris@jalakai.co.uk>
 465       *
 466       * @param string $user User login
 467       * @param array  $info User's userinfo array
 468       * @return bool
 469       */
 470      protected function filter($user, $info)
 471      {
 472          foreach ($this->pattern as $item => $pattern) {
 473              if ($item == 'user') {
 474                  if (!preg_match($pattern, $user)) return false;
 475              } elseif ($item == 'grps') {
 476                  if (!count(preg_grep($pattern, $info['grps']))) return false;
 477              } else {
 478                  if (!preg_match($pattern, $info[$item])) return false;
 479              }
 480          }
 481          return true;
 482      }
 483  
 484      /**
 485       * construct a filter pattern
 486       *
 487       * @param array $filter
 488       */
 489      protected function constructPattern($filter)
 490      {
 491          $this->pattern = array();
 492          foreach ($filter as $item => $pattern) {
 493              $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
 494          }
 495      }
 496  }