<?php
/**
 * PAM authentication backend
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Bruno De Fraine
 * @author     Dennis Wagelaar
 * @author     Andreas Gohr <andi@splitbrain.org>
 * @author     Chris Smith <chris@jalakai.co.uk>
 */

define('DOKU_AUTH', dirname(__FILE__));
require_once(DOKU_AUTH.'/basic.class.php');

define('SYSTEM_USERFILE','/etc/passwd');
define('SYSTEM_GROUPFILE','/etc/group');

// we only accept page ids for auth_plain
if(isset($_REQUEST['u']))
  $_REQUEST['u'] = cleanID($_REQUEST['u']);
if(isset($_REQUEST['acl_user']))
  $_REQUEST['acl_user'] = cleanID($_REQUEST['acl_user']);
// the same goes for password reset requests
if(isset($_POST['login'])){
  $_POST['login'] = cleanID($_POST['login']);
}

class auth_pam extends auth_basic {

    var $users = null;
    var $_pattern = array();

    /**
     * Constructor
     *
     * Carry out sanity checks to ensure the object is
     * able to operate. Set capabilities.
     *
     * @author  Bruno De Fraine
     * @author  Christopher Smith <chris@jalakai.co.uk>
     */
    function auth_pam() {
      if (!function_exists('pam_auth') || !@is_readable(SYSTEM_USERFILE)){
        $this->success = false;
      }else{
        $this->cando['getUsers']     = true;
        $this->cando['getUserCount'] = true;
      }
    }

    /**
     * Check user+password [required auth function]
     *
     * Checks if the given user exists and the given
     * plaintext password is correct
     *
     * @author  Dennis Wagelaar
     * @return  bool
     */
    function checkPass($user,$pass){
      return pam_auth($user, $pass);
    }

    /**
     * Return user info
     *
     * Returns info about the given user needs to contain
     * at least these fields:
     *
     * name string  full name of the user
     * mail string  email addres of the user
     * grps array   list of groups the user is in
     *
     * @author  Andreas Gohr <andi@splitbrain.org>
     */
    function getUserData($user){

      if($this->users === null) $this->_loadUserData();
      return isset($this->users[$user]) ? $this->users[$user] : false;
    }

    /**
     * Return a count of the number of user which meet $filter criteria
     *
     * @author  Chris Smith <chris@jalakai.co.uk>
     */
    function getUserCount($filter=array()) {

      if($this->users === null) $this->_loadUserData();

      if (!count($filter)) return count($this->users);

      $count = 0;
      $this->_constructPattern($filter);

      foreach ($this->users as $user => $info) {
          $count += $this->_filter($user, $info);
      }

      return $count;
    }

    /**
     * Bulk retrieval of user data
     *
     * @author  Chris Smith <chris@jalakai.co.uk>
     * @param   start     index of first user to be returned
     * @param   limit     max number of users to be returned
     * @param   filter    array of field/pattern pairs
     * @return  array of userinfo (refer getUserData for internal userinfo details)
     */
    function retrieveUsers($start=0,$limit=0,$filter=array()) {

      if ($this->users === null) $this->_loadUserData();

      ksort($this->users);

      $i = 0;
      $count = 0;
      $out = array();
      $this->_constructPattern($filter);

      foreach ($this->users as $user => $info) {
        if ($this->_filter($user, $info)) {
          if ($i >= $start) {
            $out[$user] = $info;
            $count++;
            if (($limit > 0) && ($count >= $limit)) break;
          }
          $i++;
        }
      }

      return $out;
    }

    /**
     * Load all user data
     *
     * loads the user file into a datastructure
     *
     * @author  Bruno De Fraine
     * @author  Dennis Wagelaar
     * @author  Andreas Gohr <andi@splitbrain.org>
     */
    function _loadUserData(){
      $this->users = array();

      if(!@file_exists(SYSTEM_USERFILE)) return;

      $lines = file(SYSTEM_USERFILE);
      foreach($lines as $line){
        $line = trim($line);
        if(empty($line)) continue;

        $row    = split(":",$line,7);

        $this->users[$row[0]]['name'] = urldecode($row[4]);
        $this->users[$row[0]]['mail'] = $row[0].'@'.$_SERVER['SERVER_NAME'];
        $this->users[$row[0]]['grps'] = array();
      }

      if(@file_exists(SYSTEM_GROUPFILE)) {
        $lines = file(SYSTEM_GROUPFILE);
        foreach($lines as $line) {
          $line = trim($line);
          if(empty($line)) continue;

          $row    = split(":",$line,4);
          $users  = split(",",$row[3]);

          foreach($users as $user){
            // Append groupname to user's groups
            $this->users[$user]['grps'][] = $row[0];
          }
        }
      }
    }

    /**
     * return 1 if $user + $info match $filter criteria, 0 otherwise
     *
     * @author   Chris Smith <chris@jalakai.co.uk>
     */
    function _filter($user, $info) {
        // FIXME
        foreach ($this->_pattern as $item => $pattern) {
            if ($item == 'user') {
                if (!preg_match($pattern, $user)) return 0;
            } else if ($item == 'grps') {
                if (!count(preg_grep($pattern, $info['grps']))) return 0;
            } else {
                if (!preg_match($pattern, $info[$item])) return 0;
            }
        }
        return 1;
    }

    function _constructPattern($filter) {
      $this->_pattern = array();
      foreach ($filter as $item => $pattern) {
//        $this->_pattern[$item] = '/'.preg_quote($pattern,"/").'/';          // don't allow regex characters
        $this->_pattern[$item] = '/'.str_replace('/','\/',$pattern).'/';    // allow regex characters
      }
    }
}

//Setup VIM: ex: et ts=2 enc=utf-8 :
