<?php
/**
 * AJAX autocompletion code for group names.
 *
 * @author Jan Dittberner <jan@dittberner.info>
 * @version $Id$
 * @license GPL
 * @package WebDAVAdmin
 *
 * Copyright (c) 2007 Jan Dittberner
 *
 * This file is part of WebDAVAdmin.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

if (!isset($_SERVER['DavAdminConfDir'])) {
  header('HTTP/1.0 500 Internal Server Error');
  header('Status: 500 Internal Server Error');
  header('Content-Type: text/plain;charset=utf8');
  print("The Server is not configured correctly. " .
        "Please tell your Administrator to set the " .
        "DavAdminConfDir environment variable.");
  exit();
}
/** Include configuration information. */
require_once($_SERVER['DavAdminConfDir'] . '/config.inc.php');

// output is plain text (JSON or an error message)
header("Content-Type: text/plain; charset=UTF-8");

/**
 * Gets group names for autocompletion.
 *
 * @param string $part Comma separated list of groups and beginning of
 * a new group entry
 * @return list of Comma separated lists of groups
 */
function getGroups($part) {
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  preg_match_all($regexp, $part, $matches);
  $array = $matches[1];
  $last_string = trim(array_pop($array));
  $retval = array();
  if ($last_string != '') {
    $groups = file($GLOBALS['davconfig']['group.file']);
    foreach ($groups as $line) {
      list($group, $users) = explode(":", $line);
      $group = trim($group);
      if (stripos($group, $last_string) === 0) {
        array_push($retval, $group);
      }
    }
  }
  return json_encode($retval);
}

// split group list part from requested URL.
$parts = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], "/") + 1);
print getGroups($parts);
?>