Page MenuHomePhorge

No OneTemporary

Authored By
Unknown
Size
153 KB
Referenced Files
None
Subscribers
None
diff --git a/lib/Auth.php b/lib/Auth.php
index 92901e3..544b066 100644
--- a/lib/Auth.php
+++ b/lib/Auth.php
@@ -1,347 +1,359 @@
<?php
/*
+--------------------------------------------------------------------------+
| This file is part of the Kolab Web Admin Panel |
| |
| Copyright (C) 2011-2012, Kolab Systems AG |
| |
| This program is free software: you can redistribute it and/or modify |
| it under the terms of the GNU Affero General Public License as published |
| by the Free Software Foundation, either version 3 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public License |
| along with this program. If not, see <http://www.gnu.org/licenses/> |
+--------------------------------------------------------------------------+
| Author: Aleksander Machniak <machniak@kolabsys.com> |
| Author: Jeroen van Meeuwen <vanmeeuwen@kolabsys.com> |
+--------------------------------------------------------------------------+
*/
class Auth {
static private $instance = array();
private $_auth = array();
private $conf;
private $domains = array();
/**
* Return an instance of Auth, associated with $domain.
*
* If $domain is not specified, the 'kolab' 'primary_domain' is used.
*/
static function get_instance($domain = NULL)
{
$conf = Conf::get_instance();
if ($domain === NULL) {
$domain = $conf->get('primary_domain');
}
if (!isset(self::$instance[$domain])) {
self::$instance[$domain] = new Auth($domain);
}
return self::$instance[$domain];
}
public function __construct($domain = NULL)
{
if (!$this->conf) {
$this->conf = Conf::get_instance();
}
if ($domain === NULL) {
$domain = $this->conf->get('primary_domain');
}
$this->domain = $domain;
$this->connect($domain);
}
/**
* Authenticate $username with $password.
*
* The following forms for a username exist:
*
* - "cn=Directory Manager"
*
* This is considered a DN, as it succeeds to parse as such. The
* very name of this user may have already caused you to suspect
* that the user is not associated with one domain per-se. It is
* our intention this user does therefor not have a
* $_SESSION['user']->domain, but instead a
* $_SESSION['user']->working_domain. In any case, obtain the
* current domain for any user through
* $_SESSION['user']->get_domain().
*
* NOTE/TODO: For now, even cn=Directory Manager is set to the
* default domain. I wish there was more time...
*
* - "user@domain.tld"
*
* While it may seem obvious, this user is to be authenticated
* against the 'domain.tld' realm.
*
* - "user"
*
* This user is to be authenticated against the 'kolab'
* 'primary_domain'.
*
* @param string $username User name (DN or mail)
* @param string $password User password
*
* @return bool|string User ID or False on failure
*/
public function authenticate($username, $password)
{
// TODO: Log authentication request.
// error_log("Authentication request for $username");
if (strpos($username, '@')) {
// Case-sensitivity does not matter for strstr() on '@', which
// has no case.
$user_domain = strstr($username, '@');
if (isset($this->_auth[$user_domain])) {
// We know this domain
$domain = $user_domain;
}
else {
// Attempt to find the primary domain name space for the
// domain used in the authentication request.
//
// This will enable john@example.org to login using 'alias'
// domains as well, such as 'john@example.ch'.
$associated_domain = $this->primary_for_valid_domain($user_domain);
if ($associated_domain) {
$domain = $user_domain;
}
else {
// It seems we do not know about this domain.
$domain = FALSE;
}
}
}
else {
$domain = $this->conf->get('primary_domain');
}
// TODO: Debug logging for the use of a current or the creation of
// a new authentication class instance.
if ($this->domain == $domain) {
$result = $this->_auth[$domain]->authenticate($username, $password);
}
else {
$result = Auth::get_instance($domain)->authenticate($username, $password);
}
return $result;
}
public function connect($domain = NULL)
{
if ($domain === NULL) {
$domain = $this->conf->get('primary_domain');
}
if ($domain) {
$auth_method = strtoupper($this->conf->get($domain, 'auth_mechanism'));
}
if (empty($auth_method)) {
// Use the default authentication technology
$auth_method = strtoupper($this->conf->get('kolab', 'auth_mechanism'));
}
if (!$auth_method) {
// Use LDAP by default
$auth_method = 'LDAP';
}
if (!isset($this->_auth[$domain])) {
require_once 'Auth/' . $auth_method . '.php';
$this->_auth[$domain] = new $auth_method($domain);
}
}
// TODO: Dummy function to be removed
public function attr_details($attribute)
{
$conf = Conf::get_instance();
return $this->_auth[$conf->get('kolab', 'primary_domain')]->attribute_details((array)($attribute));
}
// TODO: Dummy function to be removed
public function attrs_allowed($objectclasses = array())
{
$conf = Conf::get_instance();
return $this->_auth[$conf->get('kolab', 'primary_domain')]->allowed_attributes($objectclasses);
}
public function allowed_attributes($objectclasses = array())
{
if (!is_array($objectclasses)) {
$objectclasses = (array)($objectclasses);
}
return $this->_auth[$_SESSION['user']->get_domain()]->allowed_attributes($objectclasses);
}
public function attribute_details($attributes = array())
{
if (!is_array($attributes)) {
$attributes = (array)($attributes);
}
return $this->_auth[$_SESSION['user']->get_domain()]->attribute_details($attributes);
}
public function find_user_groups($member_dn)
{
return $this->_auth[$_SESSION['user']->get_domain()]->find_user_groups($member_dn);
}
public function get_attribute($subject, $attribute)
{
return $this->_auth[$_SESSION['user']->get_domain()]->get_attribute($subject, $attribute);
}
public function get_attributes($subject, $attributes)
{
return $this->_auth[$_SESSION['user']->get_domain()]->get_attributes($subject, $attributes);
}
public function group_add($attributes, $typeid = null)
{
return $this->_auth[$_SESSION['user']->get_domain()]->group_add($attributes, $typeid);
}
public function group_edit($group, $attributes, $typeid = null)
{
return $this->_auth[$_SESSION['user']->get_domain()]->group_edit($group, $attributes, $typeid);
}
public function group_delete($subject)
{
return $this->_auth[$_SESSION['user']->get_domain()]->group_delete($subject);
}
public function group_find_by_attribute($attribute)
{
return $this->_auth[$_SESSION['user']->get_domain()]->group_find_by_attribute($attribute);
}
public function group_info($groupdata)
{
return $this->_auth[$_SESSION['user']->get_domain()]->group_info($groupdata);
}
public function group_members_list($groupdata)
{
return $this->_auth[$_SESSION['user']->get_domain()]->group_members_list($groupdata);
}
public function list_domains()
{
// TODO: Consider a normal user does not have privileges on
// the base_dn where domain names and configuration is stored.
return $this->_auth[$this->domain]->list_domains();
}
public function list_rights($subject)
{
return $this->_auth[$this->domain]->effective_rights($subject);
}
public function list_users($domain = NULL, $attributes = array(), $search = array(), $params = array())
{
$this->connect($domain);
if ($domain === NULL) {
$domain = $this->conf->get('primary_domain');
}
$users = $this->_auth[$domain]->list_users($attributes, $search, $params);
return $users;
}
public function list_groups($domain = NULL, $attributes = array(), $search = array(), $params = array())
{
$this->connect($domain);
if ($domain === NULL) {
$domain = $this->conf->get('primary_domain');
}
$groups = $this->_auth[$domain]->list_groups($attributes, $search, $params);
return $groups;
}
public function list_roles($domain = NULL, $attributes = array(), $search = array(), $params = array())
{
$this->connect($domain);
if ($domain === NULL) {
$domain = $this->conf->get('primary_domain');
}
$roles = $this->_auth[$domain]->list_roles($attributes, $search, $params);
return $roles;
}
public function primary_for_valid_domain($domain)
{
$this->domains = $this->list_domains();
if (array_key_exists($domain, $this->domains)) {
return $domain;
}
else if (in_array($domain, $this->domains)) {
// We know it's not a key!
foreach ($this->domains as $parent_domain => $child_domains) {
if (in_array($domain, $child_domains)) {
return $parent_domain;
}
}
return FALSE;
}
else {
return FALSE;
}
}
+ public function search()
+ {
+ $this->connect($domain);
+ if ($domain === NULL) {
+ $domain = $this->conf->get('primary_domain');
+ }
+
+ $result = $this->_auth[$domain]->search(func_get_args());
+
+ return $result;
+ }
+
public function user_add($attributes, $typeid = null)
{
return $this->_auth[$_SESSION['user']->get_domain()]->user_add($attributes, $typeid);
}
public function user_edit($user, $attributes, $typeid = null)
{
return $this->_auth[$_SESSION['user']->get_domain()]->user_edit($user, $attributes, $typeid);
}
public function user_delete($userdata)
{
return $this->_auth[$_SESSION['user']->get_domain()]->user_delete($userdata);
}
public function user_find_by_attribute($attribute)
{
return $this->_auth[$_SESSION['user']->get_domain()]->user_find_by_attribute($attribute);
}
public function user_info($userdata)
{
return $this->_auth[$_SESSION['user']->get_domain()]->user_info($userdata);
}
}
diff --git a/lib/Auth/LDAP.php b/lib/Auth/LDAP.php
index 2f805fd..7699a33 100644
--- a/lib/Auth/LDAP.php
+++ b/lib/Auth/LDAP.php
@@ -1,1816 +1,1880 @@
<?php
/*
+--------------------------------------------------------------------------+
| This file is part of the Kolab Web Admin Panel |
| |
| Copyright (C) 2011-2012, Kolab Systems AG |
| |
| This program is free software: you can redistribute it and/or modify |
| it under the terms of the GNU Affero General Public License as published |
| by the Free Software Foundation, either version 3 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public License |
| along with this program. If not, see <http://www.gnu.org/licenses/> |
+--------------------------------------------------------------------------+
| Author: Aleksander Machniak <machniak@kolabsys.com> |
| Author: Jeroen van Meeuwen <vanmeeuwen@kolabsys.com> |
+--------------------------------------------------------------------------+
*/
/**
* Kolab LDAP handling abstraction class.
*/
class LDAP
{
public $_name = "LDAP";
private $conn;
private $bind_dn;
private $bind_pw;
private $attribute_level_rights_map = array(
"r" => "read",
"s" => "search",
"w" => "write",
"o" => "delete",
"c" => "compare",
"W" => "write",
"O" => "delete"
);
private $entry_level_rights_map = array(
"a" => "add",
"d" => "delete",
"n" => "modrdn",
"v" => "read"
);
// This is the default and should actually be set through Conf.
private $_ldap_uri = 'ldap://localhost:389/';
private $conf;
/**
* Class constructor
*/
public function __construct($domain = null)
{
$this->conf = Conf::get_instance();
// See if we are to connect to any domain explicitly defined.
if (!isset($domain) || empty($domain)) {
// If not, attempt to get the domain from the session.
if (isset($_SESSION['user'])) {
try {
$domain = $_SESSION['user']->get_domain();
} catch (Exception $e) {
// TODO: Debug logging
error_log("Warning, user not authenticated yet");
}
}
}
// Continue and default to the primary domain.
$this->domain = $domain ? $domain : $this->conf->get('primary_domain');
$this->_ldap_uri = $this->conf->get('ldap_uri');
$this->_ldap_server = parse_url($this->_ldap_uri, PHP_URL_HOST);
$this->_ldap_port = parse_url($this->_ldap_uri, PHP_URL_PORT);
$this->_ldap_scheme = parse_url($this->_ldap_uri, PHP_URL_SCHEME);
// Catch cases in which the ldap server port has not been explicitely defined
if (!$this->_ldap_port) {
if ($this->_ldap_scheme == "ldaps") {
$this->_ldap_port = 636;
}
else {
$this->_ldap_port = 389;
}
}
// We can also use the parse_url() to pass on the bind dn and pw:
//
// $ldap = new LDAP('ldap://uid=svc-kwap,ou=Services,ou=Accounts,dc=kanarip,dc=com:VerySecret@localhost/');
// and the following line uncommented:
//
// echo "<pre>"; print_r(parse_url($ldap_uri)); echo "</pre>";
//
// creates:
//
// array
// (
// [scheme] => ldap
// [host] => localhost
// [user] => uid=svc-kwap,ou=Services,ou=Accounts,dc=kanarip,dc=com
// [pass] => VerySecret
// [path] => /
// )
}
/**********************************************************
*********** Public methods ************
**********************************************************/
/**
* Authentication
*
* @param string $username User name (DN or mail)
* @param string $password User password
*
* @return bool|string User ID or False on failure
*/
public function authenticate($username, $password)
{
error_log("LDAP authentication request for $username");
if (!$this->_connect()) {
return false;
}
// Attempt to explode the username to see if it is in fact a DN,
// such as would be the case for 'cn=Directory Manager' or
// 'uid=admin'.
$is_dn = ldap_explode_dn($username, 1);
if (!$is_dn) {
error_log("Username is not a DN");
list($this->userid, $this->domain) = $this->_qualify_id($username);
$root_dn = $this->domain_root_dn($this->domain);
$user_dn = $this->_get_user_dn($root_dn, '(mail=' . $username . ')');
error_log("Found user DN: $user_dn for user: $username");
}
else {
$user_dn = $username;
$root_dn = "";
}
if (($bind_ok = $this->_bind($user_dn, $password)) == true) {
// $this->_unbind();
if (isset($_SESSION['user'])) {
$_SESSION['user']->user_root_dn = $root_dn;
$_SESSION['user']->user_bind_dn = $user_dn;
$_SESSION['user']->user_bind_pw = $password;
error_log("Successfully bound with User DN: " . $_SESSION['user']->user_bind_dn);
}
else {
error_log("Successfully bound with User DN: " . $user_dn . " but not saving it to the session");
}
// @TODO: return unique attribute
return $user_dn;
}
else {
error_log("LDAP Error: " . $this->_errstr());
return false;
}
}
public function attribute_details($attributes = array())
{
$_schema = $this->init_schema();
$attribs = $_schema->getAll('attributes');
$attributes_details = array();
foreach ($attributes as $attribute) {
if (array_key_exists($attribute, $attribs)) {
$attrib_details = $attribs[$attribute];
if (!empty($attrib_details['sup'])) {
foreach ($attrib_details['sup'] as $super_attrib) {
$_attrib_details = $attribs[$super_attrib];
if (is_array($_attrib_details)) {
$attrib_details = array_merge($_attrib_details, $attrib_details);
}
}
}
} elseif (array_key_exists(strtolower($attribute), $attribs)) {
$attrib_details = $attribs[strtolower($attribute)];
if (!empty($attrib_details['sup'])) {
foreach ($attrib_details['sup'] as $super_attrib) {
$_attrib_details = $attribs[$super_attrib];
if (is_array($_attrib_details)) {
$attrib_details = array_merge($_attrib_details, $attrib_details);
}
}
}
} else {
error_log("No schema details exist for attribute $attribute (which is strange)");
}
// The relevant parts only, please
$attributes_details[$attribute] = Array(
'type' => (array_key_exists('single-value', $attrib_details) && $attrib_details['single-value']) ? "text" : "list",
'description' => $attrib_details['desc'],
'syntax' => $attrib_details['syntax'],
'max-length' => (array_key_exists('max_length', $attrib_details)) ? $attrib_details['max-length'] : false,
);
}
return $attributes_details;
}
public function allowed_attributes($objectclasses = Array())
{
$_schema = $this->init_schema();
if (!is_array($objectclasses)) {
return false;
}
if (empty($objectclasses)) {
return false;
}
$may = Array();
$must = Array();
$superclasses = Array();
foreach ($objectclasses as $objectclass) {
$superclass = $_schema->superclass($objectclass);
if (!empty($superclass)) {
$superclasses = array_merge($superclass, $superclasses);
}
$_may = $_schema->may($objectclass);
if (is_array($_may)) {
$may = array_merge($may, $_may);
} /* else {
} */
$_must = $_schema->must($objectclass);
if (is_array($_must)) {
$must = array_merge($must, $_must);
} /* else {
var_dump($_must);
} */
}
return Array('may' => $may, 'must' => $must, 'super' => $superclasses);
}
public function domain_add($domain, $domain_alias = false, $prepopulate = true)
{
// Apply some routines for access control to this function here.
if ($domain_alias) {
return $this->_domain_add_alias($domain, $domain_alias);
}
else {
return $this->_domain_add_new($domain, $prepopulate);
}
}
public function effective_rights($subject)
{
$attributes = array();
$output = array();
$conf = Conf::get_instance();
$entry_dn = $this->entry_dn($subject);
if (!$entry_dn) {
$entry_dn = $conf->get($subject . "_base_dn");
}
if (!$entry_dn) {
$entry_dn = $conf->get("base_dn");
}
//console("effective_rights for $subject resolves to $entry_dn");
$command = array(
// TODO: Very 64-bit specific
'/usr/lib64/mozldap/ldapsearch',
'-x',
'-h',
$this->_ldap_server,
'-p',
$this->_ldap_port,
'-b',
$conf->get('base_dn'),
'-D',
'"' . $_SESSION['user']->user_bind_dn . '"',
'-w',
'"' . $_SESSION['user']->user_bind_pw . '"',
'-J',
'"' . implode(
':',
array(
'1.3.6.1.4.1.42.2.27.9.5.2', // OID
'true', // Criticality
'dn:' . $_SESSION['user']->user_bind_dn // User DN
)
) . '"',
'"(entrydn=' . $entry_dn . ')"',
'"*"',
);
//console("Executing command " . implode(' ', $command));
exec(implode(' ', $command), $output);
//console("Output", $output);
$lines = array();
foreach ($output as $line_num => $line) {
if (substr($line, 0, 1) == " ") {
$lines[count($lines)-1] .= trim($line);
} else {
$lines[] = trim($line);
}
}
foreach ($lines as $line) {
$line_components = explode(':', $line);
$attribute_name = array_shift($line_components);
$attribute_value = trim(implode(':', $line_components));
switch ($attribute_name) {
case "attributeLevelRights":
$attributes[$attribute_name] = $this->parse_attribute_level_rights($attribute_value);
break;
case "dn":
$attributes[$attribute_name] = $attribute_value;
break;
case "entryLevelRights":
$attributes[$attribute_name] = $this->parse_entry_level_rights($attribute_value);
break;
default:
break;
}
}
return $attributes;
}
public function get_attribute($subject_dn, $attribute)
{
- $result = $this->search($subject_dn, '(objectclass=*)', (array)($attribute));
+ $result = $this->_search($subject_dn, '(objectclass=*)', (array)($attribute));
$result = self::normalize_result($result);
$dn = key($result);
$attr = key($result[$dn]);
return $result[$dn][$attr];
}
public function get_attributes($subject_dn, $attributes)
{
- $result = $this->search($subject_dn, '(objectclass=*)', $attributes);
+ $result = $this->_search($subject_dn, '(objectclass=*)', $attributes);
$result = self::normalize_result($result);
if (!empty($result)) {
$result = array_pop($result);
return $result;
}
return false;
}
public function list_domains()
{
$domains = $this->domains_list();
$domains = self::normalize_result($domains);
return $domains;
}
public function list_groups($attributes = array(), $search = array(), $params = array())
{
if (!empty($params['sort_by'])) {
if (!in_array($params['sort_by'], $attributes)) {
$attributes[] = $params['sort_by'];
}
}
$groups = $this->groups_list($attributes, $search);
$groups = self::normalize_result($groups);
if (!empty($params['sort_by'])) {
$this->sort_result_key = $params['sort_by'];
uasort($groups, array($this, 'sort_result'));
if ($params['sort_order'] == 'DESC') {
$groups = array_reverse($groups, true);
}
}
return $groups;
}
public function list_users($attributes = array(), $search = array(), $params = array())
{
if (!empty($params['sort_by'])) {
if (is_array($params['sort_by'])) {
foreach ($params['sort_by'] as $attrib) {
if (!in_array($attrib, $attributes)) {
$attributes[] = $attrib;
}
}
} else {
if (!in_array($params['sort_by'], $attributes)) {
$attributes[] = $params['sort_by'];
}
}
}
$users = $this->users_list($attributes, $search);
$users = self::normalize_result($users);
if (!empty($params['sort_by'])) {
$this->sort_result_key = $params['sort_by'];
uasort($users, array($this, 'sort_result'));
if ($params['sort_order'] == 'DESC') {
$users = array_reverse($users, true);
}
}
return $users;
}
public function list_roles($attributes = array(), $search = array(), $params = array())
{
if (!empty($params['sort_by'])) {
if (!in_array($params['sort_by'], $attributes)) {
$attributes[] = $params['sort_by'];
}
}
$roles = $this->roles_list($attributes, $search);
$roles = self::normalize_result($roles);
if (!empty($params['sort_by'])) {
$this->sort_result_key = $params['sort_by'];
uasort($roles, array($this, 'sort_result'));
if ($params['sort_order'] == 'DESC') {
$roles = array_reverse($roles, true);
}
}
return $roles;
}
public function user_add($attrs, $typeid = null)
{
if ($typeid == null) {
$type_str = 'user';
}
else {
$db = SQL::get_instance();
$_key = $db->fetch_assoc($db->query("SELECT `key` FROM user_types WHERE id = ?", $typeid));
$type_str = $_key['key'];
}
// Check if the user_type has a specific base DN specified.
$base_dn = $this->conf->get($this->domain, $type_str . "_user_base_dn");
// If not, take the regular user_base_dn
if (!$base_dn)
$base_dn = $this->conf->get($this->domain, "user_base_dn");
// If no user_base_dn either, take the user type specific from the parent
// configuration
if (!$base_dn)
$base_dn = $this->conf->get('ldap', $type_str . "_user_base_dn");
+ if (!empty($attrs['ou'])) {
+ $base_dn = $attrs['ou'];
+ }
+
// TODO: The rdn is configurable as well.
// Use [$type_str . "_"]user_rdn_attr
$dn = "uid=" . $attrs['uid'] . "," . $base_dn;
return $this->_add($dn, $attrs);
}
public function user_edit($user, $attributes, $typeid = null)
{
/*
// Get the type "key" string for the next few settings.
if ($typeid == null) {
$type_str = 'user';
}
else {
$db = SQL::get_instance();
$_key = $db->fetch_assoc($db->query("SELECT `key` FROM user_types WHERE id = ?", $typeid));
$type_str = $_key['key'];
}
*/
$unique_attr = $this->unique_attribute();
$attributes[$unique_attr] = $user;
// Now that values have been re-generated where necessary, compare
// the new group attributes to the original group attributes.
$_user = $this->entry_find_by_attribute(array($unique_attr => $attributes[$unique_attr]));
if (!$_user) {
console("Could not find user");
return false;
}
$_user_dn = key($_user);
$_user = $this->user_info($_user_dn, array());
// We should start throwing stuff over the fence here.
return $this->modify_entry($_user_dn, $_user[$_user_dn], $attributes);
}
public function user_delete($user)
{
$user_dn = $this->entry_dn($user);
if (!$user_dn) {
return false;
}
return $this->_delete($user_dn);
}
/**
* User attributes
*
*
*/
public function user_info($user)
{
$user_dn = $this->entry_dn($user);
if (!$user_dn)
return false;
- return self::normalize_result($this->search($user_dn));
+ return self::normalize_result($this->_search($user_dn));
}
public function user_find_by_attribute($attribute)
{
return $this->entry_find_by_attribute($attribute);
}
public function find_user_groups($member_dn)
{
error_log(__FILE__ . "(" . __LINE__ . "): " . $member_dn);
$groups = array();
$root_dn = $this->domain_root_dn($this->domain);
// TODO: Do not query for both, it's either one or the other
- $entries = $this->search($root_dn, "(|" .
+ $entries = $this->_search($root_dn, "(|" .
"(&(objectclass=groupofnames)(member=$member_dn))" .
"(&(objectclass=groupofuniquenames)(uniquemember=$member_dn))" .
")");
$entries = self::normalize_result($entries);
foreach ($entries as $entry_dn => $entry_attributes) {
$groups[] = $entry_dn;
}
return $groups;
}
public function group_add($attrs, $typeid = null)
{
if ($typeid == null) {
$type_str = 'group';
}
else {
$db = SQL::get_instance();
$_key = $db->fetch_assoc($db->query("SELECT `key` FROM group_types WHERE id = ?", $typeid));
$type_str = $_key['key'];
}
// Check if the group_type has a specific base DN specified.
$base_dn = $this->conf->get($type_str . "_group_base_dn");
// If not, take the regular user_base_dn
if (!$base_dn)
$base_dn = $this->conf->get("group_base_dn");
// TODO: The rdn is configurable as well.
// Use [$type_str . "_"]user_rdn_attr
$dn = "cn=" . $attrs['cn'] . "," . $base_dn;
return $this->_add($dn, $attrs);
}
public function group_edit($group, $attributes, $typeid = null)
{
/*
// Get the type "key" string for the next few settings.
if ($typeid == null) {
$type_str = 'group';
}
else {
$db = SQL::get_instance();
$_key = $db->fetch_assoc($db->query("SELECT `key` FROM group_types WHERE id = ?", $typeid));
$type_str = $_key['key'];
}
*/
// Group identifier
$unique_attr = $this->unique_attribute();
$attributes[$unique_attr] = $group;
// Now that values have been re-generated where necessary, compare
// the new group attributes to the original group attributes.
$_group = $this->entry_find_by_attribute(array($unique_attr => $attributes[$unique_attr]));
if (!$_group) {
console("Could not find group");
return false;
}
$_group_dn = key($_group);
$_group = $this->group_info($_group_dn, array());
// We should start throwing stuff over the fence here.
return $this->modify_entry($_group_dn, $_group, $attributes);
}
public function group_delete($group)
{
$group_dn = $this->entry_dn($group);
if (!$group_dn) {
return false;
}
return $this->_delete($group_dn);
}
public function group_info($group)
{
$group_dn = $this->entry_dn($group);
if (!$group_dn) {
return false;
}
- return self::normalize_result($this->search($group_dn));
+ return self::normalize_result($this->_search($group_dn));
}
public function group_members_list($group)
{
$group_dn = $this->entry_dn($group);
if (!$group_dn) {
return false;
}
return $this->_list_group_members($group_dn);
}
public function group_find_by_attribute($attribute)
{
return $this->entry_find_by_attribute($attribute);
}
/*
Translate a domain name into it's corresponding root dn.
*/
private function domain_root_dn($domain = '')
{
$conf = Conf::get_instance();
if ($domain == '') {
return false;
}
if (!$this->_connect()) {
return false;
}
error_log("Searching for domain $domain");
error_log("From domain to root dn");
if (($this->_bind($conf->get('ldap', 'bind_dn'), $conf->get('ldap', 'bind_pw'))) == false) {
error_log("WARNING: Invalid Service bind credentials supplied");
$this->_bind($conf->manager_bind_dn, $conf->manager_bind_pw);
}
// TODO: Get domain_attr from config
$results = ldap_search($this->conn, $conf->get('domain_base_dn'), '(associatedDomain=' . $domain . ')');
if (!$result) {
// Not a multi-domain setup
$domain_name = $conf->get('kolab', 'primary_domain');
return $this->_standard_root_dn($domain_name);
}
$domain = ldap_first_entry($this->conn, $results);
$domain_info = ldap_get_attributes($this->conn, $domain);
// echo "<pre>"; print_r($domain_info); echo "</pre>";
// TODO: Also very 389 specific
if (isset($domain_info['inetDomainBaseDN'][0])) {
$domain_rootdn = $domain_info['inetDomainBaseDN'][0];
}
else {
$domain_rootdn = $this->_standard_root_dn($domain_info['associatedDomain']);
}
$this->_unbind();
error_log("Using $domain_rootdn");
return $domain_rootdn;
}
private function init_schema()
{
$conf = Conf::get_instance();
$this->_ldap_uri = $this->conf->get('ldap_uri');
$this->_ldap_server = parse_url($this->_ldap_uri, PHP_URL_HOST);
$this->_ldap_port = parse_url($this->_ldap_uri, PHP_URL_PORT);
$this->_ldap_scheme = parse_url($this->_ldap_uri, PHP_URL_SCHEME);
require_once("Net/LDAP2.php");
$_ldap_cfg = Array(
'host' => $this->_ldap_server,
'port' => $this->_ldap_port,
'tls' => false,
'version' => 3,
'binddn' => $conf->get('bind_dn'),
'bindpw' => $conf->get('bind_pw')
);
$_ldap_schema_cache_cfg = Array(
'path' => "/tmp/Net_LDAP2_Schema.cache",
'max_age' => 86400,
);
$_ldap_schema_cache = new Net_LDAP2_SimpleFileSchemaCache($_ldap_schema_cache_cfg);
$_ldap = Net_LDAP2::connect($_ldap_cfg);
$result = $_ldap->registerSchemaCache($_ldap_schema_cache);
$_schema = $_ldap->schema('cn=schema');
return $_schema;
}
- private function search($base_dn, $search_filter = '(objectClass=*)', $attributes = array('*'))
+ public function search($base_dn, $search_filter = '(objectClass=*)', $attributes = array('*'))
+ {
+ //console("Auth::LDAP::search", $base_dn);
+
+ // We may have been passed on func_get_arg()
+ if (is_array($base_dn)) {
+ $_base_dn = array_shift($base_dn);
+
+ if (count($base_dn) > 0) {
+ $search_filter = array_shift($base_dn);
+ } else {
+ $search_filter = '(objectclass=*)';
+ }
+
+ if (count($base_dn) > 0) {
+ $attributes = array_shift($base_dn);
+ } else {
+ $attributes = array('*');
+ }
+ } else {
+ $_base_dn = $base_dn;
+ }
+
+ $result = self::normalize_result($this->__search($_base_dn, $search_filter, $attributes));
+ $result = array_keys($result);
+ //console($result);
+
+ return $result;
+ }
+
+ private function _search($base_dn, $search_filter = '(objectClass=*)', $attributes = array('*'))
{
- return $this->_search($base_dn, $search_filter, $attributes);
+ return $this->__search($base_dn, $search_filter, $attributes);
}
private function domains_list()
{
$section = $this->conf->get('kolab', 'auth_mechanism');
$base_dn = $this->conf->get($section, 'domain_base_dn');
$filter = $this->conf->get($section, 'kolab_domain_filter');
- return $this->search($base_dn, $filter);
+ return $this->_search($base_dn, $filter);
}
private function users_list($attributes = array(), $search = array())
{
$conf = Conf::get_instance();
$base_dn = $conf->get('user_base_dn');
if (!$base_dn)
$base_dn = $conf->get('base_dn');
$filter = $conf->get('user_filter');
if (empty($attributes) || !is_array($attributes)) {
$attributes = array('*');
}
if ($s_filter = $this->_search_filter($search)) {
// join search filter with objectClass filter
$filter = '(&' . $filter . $s_filter . ')';
}
- return $this->search($base_dn, $filter, $attributes);
+ return $this->_search($base_dn, $filter, $attributes);
}
private function roles_list($attributes = array(), $search = array())
{
$conf = Conf::get_instance();
$base_dn = $conf->get('base_dn');
// TODO: From config
$filter = "(&(objectclass=ldapsubentry)(objectclass=nsroledefinition))";
if (empty($attributes) || !is_array($attributes)) {
$attributes = array('*');
}
if ($s_filter = $this->_search_filter($search)) {
// join search filter with objectClass filter
$filter = '(&' . $filter . $s_filter . ')';
}
- return $this->search($base_dn, $filter, $attributes);
+ return $this->_search($base_dn, $filter, $attributes);
}
private function groups_list($attributes = array(), $search = array())
{
$conf = Conf::get_instance();
$base_dn = $conf->get('group_base_dn');
if (!$base_dn)
$base_dn = $conf->get('base_dn');
$filter = $conf->get('group_filter');
if (empty($attributes) || !is_array($attributes)) {
$attributes = array('*');
}
if ($s_filter = $this->_search_filter($search)) {
// join search filter with objectClass filter
$filter = '(&' . $filter . $s_filter . ')';
}
- return $this->search($base_dn, $filter, $attributes);
+ return $this->_search($base_dn, $filter, $attributes);
}
public static function normalize_result($__result)
{
if (!is_array($__result)) {
return array();
}
$conf = Conf::get_instance();
$dn_attr = $conf->get($conf->get('kolab', 'auth_mechanism'), 'domain_name_attribute');
$result = array();
for ($x = 0; $x < $__result["count"]; $x++) {
$dn = $__result[$x]['dn'];
$result[$dn] = array();
for ($y = 0; $y < $__result[$x]["count"]; $y++) {
$attr = $__result[$x][$y];
if ($__result[$x][$attr]["count"] == 1) {
switch ($attr) {
case "objectclass":
$result[$dn][$attr] = strtolower($__result[$x][$attr][0]);
break;
default:
$result[$dn][$attr] = $__result[$x][$attr][0];
break;
}
}
else {
$result[$dn][$attr] = array();
for ($z = 0; $z < $__result[$x][$attr]["count"]; $z++) {
// The first result in the array is the primary domain.
if ($z == 0 && $attr == $dn_attr) {
$result[$dn]['primary_domain'] = $__result[$x][$attr][$z];
}
switch ($attr) {
case "objectclass":
$result[$dn][$attr][] = strtolower($__result[$x][$attr][$z]);
break;
default:
$result[$dn][$attr][] = $__result[$x][$attr][$z];
break;
}
}
}
}
}
return $result;
}
private function entry_find_by_attribute($attribute)
{
if (empty($attribute) || !is_array($attribute) || count($attribute) > 1) {
return false;
}
if (empty($attribute[key($attribute)])) {
return false;
}
$filter = "(&";
foreach ($attribute as $key => $value) {
$filter .= "(" . $key . "=" . $value . ")";
}
$filter .= ")";
$base_dn = $this->domain_root_dn($this->domain);
- $result = self::normalize_result($this->search($base_dn, $filter, array_keys($attribute)));
+ $result = self::normalize_result($this->_search($base_dn, $filter, array_keys($attribute)));
if (count($result) > 0) {
error_log("Results found: " . implode(', ', array_keys($result)));
return $result;
}
else {
error_log("No result");
return false;
}
}
private function entry_dn($subject)
{
$is_dn = ldap_explode_dn($subject, 1);
if (is_array($is_dn) && array_key_exists("count", $is_dn) && $is_dn["count"] > 1) {
return $subject;
}
$unique_attr = $this->unique_attribute();
$subject = $this->entry_find_by_attribute(array($unique_attr => $subject));
if (!empty($subject)) {
return key($subject);
}
}
private function parse_attribute_level_rights($attribute_value)
{
$attribute_value = str_replace(", ", ",", $attribute_value);
$attribute_values = explode(",", $attribute_value);
$attribute_value = array();
foreach ($attribute_values as $access_right) {
$access_right_components = explode(":", $access_right);
$access_attribute = strtolower(array_shift($access_right_components));
$access_value = array_shift($access_right_components);
$attribute_value[$access_attribute] = array();
for ($i = 0; $i < strlen($access_value); $i++) {
$method = $this->attribute_level_rights_map[substr($access_value, $i, 1)];
if (!in_array($method, $attribute_value[$access_attribute])) {
$attribute_value[$access_attribute][] = $method;
}
}
}
return $attribute_value;
}
private function parse_entry_level_rights($attribute_value)
{
$_attribute_value = array();
for ($i = 0; $i < strlen($attribute_value); $i++) {
$method = $this->entry_level_rights_map[substr($attribute_value, $i, 1)];
if (!in_array($method, $_attribute_value)) {
$_attribute_value[] = $method;
}
}
return $_attribute_value;
}
private function modify_entry($subject_dn, $old_attrs, $new_attrs)
{
//console("OLD ATTRIBUTES", $old_attrs);
//console("NEW ATTRIBUTES", $new_attrs);
// TODO: Get $rdn_attr - we have type_id in $new_attrs
$dn_components = ldap_explode_dn($subject_dn, 0);
$rdn_components = explode('=', $dn_components[0]);
$rdn_attr = $rdn_components[0];
//console($rdn_attr);
$mod_array = Array(
"add" => Array(), // For use with ldap_mod_add()
"del" => Array(), // For use with ldap_mod_del()
"replace" => Array(), // For use with ldap_mod_replace()
"rename" => Array(), // For use with ldap_rename()
);
+ // This is me cheating. Remove this special attribute.
+ $old_ou = $old_attrs['ou'];
+ $new_ou = $new_attrs['ou'];
+ unset($old_attrs['ou']);
+ unset($new_attrs['ou']);
+
// Compare each attribute value of the old attrs with the corresponding value
// in the new attrs, if any.
foreach ($old_attrs as $attr => $old_attr_value) {
+
if (array_key_exists($attr, $new_attrs)) {
$_sort1 = false;
$_sort2 = false;
if (is_array($new_attrs[$attr])) {
$_sort1 = $new_attrs[$attr];
sort($_sort1);
}
if (is_array($old_attr_value)) {
$_sort2 = $old_attr_value;
sort($_sort2);
}
if (!($new_attrs[$attr] === $old_attr_value) && !($_sort1 === $_sort2)) {
console("Attribute $attr changed from", $old_attr_value, "to", $new_attrs[$attr]);
if ($attr === $rdn_attr) {
- $mod_array['rename'][$subject_dn] = $rdn_attr . '=' . $new_attrs[$attr];
+ $mod_array['rename']['dn'] = $subject_dn;
+ $mod_array['rename']['new_rdn'] = $rdn_attr . '=' . $new_attrs[$attr];
} else {
if (empty($new_attrs[$attr])) {
switch ($attr) {
case "userpassword":
break;
default:
console("Adding to del: $attr");
$mod_array['del'][$attr] = (array)($old_attr_value);
break;
}
} else {
console("Adding to replace: $attr");
$mod_array['replace'][$attr] = (array)($new_attrs[$attr]);
}
}
} else {
console("Attribute $attr unchanged");
}
} else {
// TODO: Since we're not shipping the entire object back and forth, and only post
// part of the data... we don't know what is actually removed (think modifiedtimestamp, etc.)
console("Group attribute $attr not mentioned in \$new_attrs..., but not explicitly removed... by assumption");
}
}
foreach ($new_attrs as $attr => $value) {
if (array_key_exists($attr, $old_attrs)) {
if (empty($value)) {
if (!array_key_exists($attr, $mod_array['del'])) {
switch ($attr) {
case "userpassword":
break;
default:
console("Adding to del(2): $attr");
$mod_array['del'][$attr] = (array)($old_attrs[$attr]);
break;
}
}
} else {
if (!($old_attrs[$attr] === $value) && !($attr === $rdn_attr)) {
if (!array_key_exists($attr, $mod_array['replace'])) {
console("Adding to replace(2): $attr");
$mod_array['replace'][$attr] = $value;
}
}
}
} else {
if (!empty($value)) {
$mod_array['add'][$attr] = $value;
}
}
}
- console($mod_array);
+ if (!($old_ou === $new_ou)) {
+ $mod_array['rename']['new_parent'] = $new_ou;
+ if (empty($mod_array['rename']['dn']) || empty($mod_array['rename']['new_rdn'])) {
+ $mod_array['rename']['dn'] = $subject_dn;
+ $mod_array['rename']['new_rdn'] = $rdn_attr . '=' . $new_attrs[$rdn_attr];
+ }
+ }
+
+ //console($mod_array);
$result = $this->modify_entry_attributes($subject_dn, $mod_array);
if ($result) {
return $mod_array;
}
}
private function modify_entry_attributes($subject_dn, $attributes)
{
$this->_bind($_SESSION['user']->user_bind_dn, $_SESSION['user']->user_bind_pw);
// Opportunities to set false include failed ldap commands.
$result = true;
if (is_array($attributes['replace']) && !empty($attributes['replace'])) {
$result = ldap_mod_replace($this->conn, $subject_dn, $attributes['replace']);
}
if (!$result) {
console("Failed to replace the following attributes", $attributes['replace']);
return false;
}
if (is_array($attributes['del']) && !empty($attributes['del'])) {
$result = ldap_mod_del($this->conn, $subject_dn, $attributes['del']);
}
if (!$result) {
console("Failed to delete the following attributes", $attributes['del']);
return false;
}
if (is_array($attributes['add']) && !empty($attributes['add'])) {
$result = ldap_mod_add($this->conn, $subject_dn, $attributes['add']);
}
if (!$result) {
console("Failed to add the following attributes", $attributes['add']);
return false;
}
if (is_array($attributes['rename']) && !empty($attributes['rename'])) {
- $olddn = key($attributes['rename']);
- $newrdn = $attributes['rename'][$olddn];
- $result = ldap_rename($this->conn, $olddn, $newrdn, NULL, true);
+ $olddn = $attributes['rename']['dn'];
+ $newrdn = $attributes['rename']['new_rdn'];
+ if (!empty($attributes['rename']['new_parent'])) {
+ $new_parent = $attributes['rename']['new_parent'];
+ } else {
+ $new_parent = null;
+ }
+
+ console("Attempt to rename $olddn to $newrdn,$new_parent");
+
+ $result = ldap_rename($this->conn, $olddn, $newrdn, $new_parent, true);
}
if (!$result) {
+ error_log("LDAP Error: " . $this->_errstr());
return false;
}
if ($result) {
return true;
} else {
return false;
}
}
/**
* Result sorting callback for uasort()
*/
public function sort_result($a, $b)
{
if (is_array($this->sort_result_key)) {
foreach ($this->sort_result_key as $attrib) {
if (array_key_exists($attrib, $a) && !$str1) {
$str1 = $a[$attrib];
}
if (array_key_exists($attrib, $b) && !$str2) {
$str2 = $b[$attrib];
}
}
} else {
$str1 = $a[$this->sort_result_key];
$str2 = $b[$this->sort_result_key];
}
return strcmp(mb_strtoupper($str1), mb_strtoupper($str2));
}
/**
* Qualify a username.
*
* Where username is 'kanarip@kanarip.com', the function will return an
* array containing 'kanarip' and 'kanarip.com'. However, where the
* username is 'kanarip', the domain name is to be assumed the
* management domain name.
*/
private function _qualify_id($username)
{
$conf = Conf::get_instance();
$username_parts = explode('@', $username);
if (count($username_parts) == 1) {
$domain_name = $conf->get('primary_domain');
}
else {
$domain_name = array_pop($username_parts);
}
return array(implode('@', $username_parts), $domain_name);
}
public function user_type_attribute_filter($type = false)
{
global $conf;
// If the user type does not exist, issue warning and continue with
// the "All attributes" array.
if (!isset($conf->user_types[$type])) {
return array('*');
}
$attributes_filter = array();
foreach ($conf->user_types[$type]['attributes'] as $key => $value) {
$attributes_filter[] = is_array($value) ? $key : $value;
}
return $attributes_filter;
}
public function user_type_search_filter($type = false)
{
global $conf;
// TODO: If the user type has not been specified we should actually
// iterate and mix and match:
//
// (|(&(type1))(&(type2)))
// If the user type does not exist, issue warning and continue with
// the "All" search filter.
if (!isset($conf->user_types[$type])) {
return "(objectClass=*)";
}
$search_filter = "(&";
// We want from user_types[$type]['attributes']['objectClasses']
foreach ($conf->user_types[$type]['attributes']['objectClass'] as $key => $value) {
$search_filter .= "(objectClass=" . $value . ")";
}
$search_filter .= ")";
print "<li>" . $search_filter;
return $search_filter;
}
/***********************************************************
************ Shortcut functions ****************
***********************************************************/
/*
Shortcut to ldap_add()
*/
private function _add($entry_dn, $attributes)
{
// Always bind with the session credentials
$this->_bind($_SESSION['user']->user_bind_dn, $_SESSION['user']->user_bind_pw);
- console("Entry DN", $entry_dn);
- console("Attributes", $attributes);
+ //console("Entry DN", $entry_dn);
+ //console("Attributes", $attributes);
foreach ($attributes as $attr_name => $attr_value) {
if (empty($attr_value)) {
unset($attributes[$attr_name]);
}
}
if (($add_result = ldap_add($this->conn, $entry_dn, $attributes)) == false) {
// Issue warning
return false;
}
return true;
}
/**
* Shortcut to ldap_bind()
*/
private function _bind($dn, $pw)
{
$this->_connect();
if (!$this->conn || !$dn || !$pw) {
return false;
}
if ($dn == $this->bind_dn && $pw == $this->bind_pw) {
return true;
}
// TODO: Debug logging
error_log("->_bind() Binding with $dn");
$this->bind_dn = $dn;
$this->bind_pw = $pw;
if (($bind_ok = ldap_bind($this->conn, $dn, $pw)) == false) {
error_log("LDAP Error: " . $this->_errstr());
// Issue error message
return false;
}
return true;
}
/**
* Shortcut to ldap_connect()
*/
private function _connect()
{
if ($this->conn) {
return true;
}
// TODO: Debug logging
error_log("Connecting to " . $this->_ldap_server . " on port " . $this->_ldap_port);
$connection = ldap_connect($this->_ldap_server, $this->_ldap_port);
if ($connection == false) {
$this->conn = null;
// TODO: Debug logging
error_log("Not connected: " . ldap_err2str() . "(no.) " . ldap_errno());
return false;
}
$this->conn = $connection;
+
+ ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
+
// TODO: Debug logging
error_log("Connected!");
return true;
}
/**
* Shortcut to ldap_delete()
*/
private function _delete($entry_dn)
{
// Always bind with the session credentials
$this->_bind($_SESSION['user']->user_bind_dn, $_SESSION['user']->user_bind_pw);
if (($delete_result = ldap_delete($this->conn, $entry_dn)) == false) {
// Issue warning
return false;
}
else {
return true;
}
}
/**
* Shortcut to ldap_disconnect()
*/
private function _disconnect()
{
if (!$this->conn) {
return true;
}
if (($result = ldap_close($this->conn)) == true) {
$this->conn = null;
$this->bind_dn = null;
$this->bind_pw = null;
return true;
}
return false;
}
/**
* Shortcut to ldap_err2str() over ldap_errno()
*/
private function _errstr()
{
if ($errno = @ldap_errno($this->conn)) {
if ($err2str = @ldap_err2str($errno)) {
return $err2str;
}
}
// Issue warning
return null;
}
/**
* Shortcut to ldap_get_entries() over ldap_list()
*
* Takes a $base_dn and $filter like ldap_list(), and returns an
* array obtained through ldap_get_entries().
*/
private function _list($base_dn, $filter)
{
if (!$this->conn) {
return null;
}
$ldap_entries = array( "count" => 0 );
if (($ldap_list = @ldap_list($this->conn, $base_dn, $filter)) == false) {
//message("LDAP Error: Could not search " . $base_dn . ": " . $this->_errstr() );
}
else {
if (($ldap_entries = @ldap_get_entries($this->conn, $ldap_list)) == false) {
//message("LDAP Error: No entries for " . $filter . " in " . $base_dn . ": " . $this->_errstr());
}
}
return $ldap_entries;
}
/**
* Shortcut to ldap_search()
*/
- private function _search($base_dn, $search_filter = '(objectClass=*)', $attributes = array('*'))
+ private function __search($base_dn, $search_filter = '(objectClass=*)', $attributes = array('*'))
{
if (!$this->_connect()) {
return false;
}
+ $attributes = (array)($attributes);
+
error_log("Searching $base_dn with filter: $search_filter");
// error_log("Searching with user: " . $_SESSION['user']->user_bind_dn);
$this->_bind($_SESSION['user']->user_bind_dn, $_SESSION['user']->user_bind_pw);
if (!in_array($this->unique_attribute(), $attributes)) {
$attributes[] = $this->unique_attribute();
}
if (($search_results = @ldap_search($this->conn, $base_dn, $search_filter, $attributes)) == false) {
//message("Could not search in " . __METHOD__ . " in " . __FILE__ . " on line " . __LINE__ . ": " . $this->_errstr());
return false;
}
if (($entries = ldap_get_entries($this->conn, $search_results)) == false) {
//message("Could not get the results of the search: " . $this->_errstr());
return false;
}
return $entries;
}
/**
* Create LDAP search filter string according to defined parameters.
*/
private function _search_filter($search)
{
if (empty($search) || !is_array($search) || empty($search['params'])) {
return null;
}
$filter = '';
foreach ((array) $search['params'] as $field => $param) {
$value = self::_quote_string($param['value']);
switch ((string)$param['type']) {
case 'prefix':
$prefix = '';
$suffix = '*';
break;
case 'suffix':
$prefix = '*';
$suffix = '';
break;
case 'exact':
$prefix = '';
$suffix = '';
break;
case 'both':
default:
$prefix = '*';
$suffix = '*';
break;
}
$filter .= "($field=$prefix" . $value . "$suffix)";
}
// join search parameters with specified operator ('OR' or 'AND')
if (count($search['params']) > 1) {
$filter = '(' . ($search['operator'] == 'AND' ? '&' : '|') . $filter . ')';
}
return $filter;
}
/**
* Shortcut to ldap_unbind()
*/
private function _unbind($yes = false, $really = false)
{
if ($yes && $really) {
if ($this->conn) {
ldap_unbind($this->conn);
}
$this->conn = null;
$this->bind_dn = null;
$this->bind_pw = null;
}
else {
// What?
//
// - attempt bind as anonymous
// - in case of fail, bind as user
}
return true;
}
/*
Utility functions
*/
/**
* Probe the root dn with the user credentials.
*
* When a list of domains is retrieved, this does not mean the user
* actually has access. Given the root dn for each domain however, we
* can in fact attempt to list / search the root dn and see if we get
* any results. If we don't, maybe this user is not authorized for the
* domain at all?
*/
private function _probe_root_dn($entry_root_dn)
{
error_log("Running for entry root dn: " . $entry_root_dn);
if (($tmpconn = ldap_connect($this->_ldap_server)) == false) {
//message("LDAP Error: " . $this->_errstr());
return false;
}
error_log("User DN: " . $_SESSION['user']->user_bind_dn);
if (($bind_success = ldap_bind($tmpconn, $_SESSION['user']->user_bind_dn, $_SESSION['user']->user_bind_pw)) == false) {
//message("LDAP Error: " . $this->_errstr());
return false;
}
if (($list_success = ldap_list($tmpconn, $entry_root_dn, '(objectClass=*)', array('*', 'aci'))) == false) {
//message("LDAP Error: " . $this->_errstr());
return false;
}
// print_r(ldap_get_entries($tmpconn, $list_success));
/*
if (ldap_count_entries($tmpconn, $list_success) == 0) {
echo "<li>Listed things, but got no results";
return false;
}
*/
return true;
}
/**
* From a domain name, such as 'kanarip.com', create a standard root
* dn, such as 'dc=kanarip,dc=com'.
*
* As the parameter $associatedDomains, either pass it an array (such
* as may have been returned by ldap_get_entries() or perhaps
* ldap_list()), where the function will assume the first value
* ($array[0]) to be the uber-level domain name, or pass it a string
* such as 'kanarip.nl'.
*
* @return string
*/
private function _standard_root_dn($associatedDomains)
{
if (is_array($associatedDomains)) {
// Usually, the associatedDomain in position 0 is the naming attribute associatedDomain
if ($associatedDomains['count'] > 1) {
// Issue a debug message here
$relevant_associatedDomain = $associatedDomains[0];
}
else {
$relevant_associatedDomain = $associatedDomains[0];
}
}
else {
$relevant_associatedDomain = $associatedDomains;
}
return "dc=" . implode(',dc=', explode('.', $relevant_associatedDomain));
}
// @TODO: this function isn't used anymore
private function _get_group_dn($root_dn, $search_filter)
{
// TODO: Why does this use privileged credentials?
if (($this->_bind($this->conf->get('bind_dn'), $this->conf->get('bind_pw'))) == false) {
$this->_bind($this->conf->get('manager_bind_dn'), $this->conf->get('manager_bind_pw'));
}
error_log("Searching for a group dn in $root_dn, with search filter: $search_filter");
$search_results = ldap_search($this->conn, $root_dn, $search_filter);
if (ldap_count_entries($this->conn, $search_results) == 0) {
return false;
}
if (($first_entry = ldap_first_entry($this->conn, $search_results)) == false) {
return false;
}
$group_dn = ldap_get_dn($this->conn, $first_entry);
return $group_dn;
}
private function _get_user_dn($root_dn, $search_filter)
{
// TODO: Why does this use privileged credentials?
if (($this->_bind($this->conf->get('bind_dn'), $this->conf->get('bind_pw'))) == false) {
//message("WARNING: Invalid Service bind credentials supplied");
$this->_bind($this->conf->get('manager_bind_dn'), $this->conf->get('manager_bind_pw'));
}
error_log("Searching for a user dn in $root_dn, with search filter: $search_filter");
$search_results = ldap_search($this->conn, $root_dn, $search_filter);
if (!$search_results || ldap_count_entries($this->conn, $search_results) == 0) {
//message("No entries found for the user dn in " . __METHOD__);
return false;
}
if (($first_entry = ldap_first_entry($this->conn, $search_results)) == false) {
return false;
}
$user_dn = ldap_get_dn($this->conn, $first_entry);
return $user_dn;
}
private function _list_group_members($dn, $entry = null)
{
$group_members = array();
if (is_array($entry) && in_array('objectclass', $entry)) {
if (!in_array(array('groupofnames', 'groupofuniquenames', 'groupofurls'), $entry['objectclass'])) {
error_log("Called _list_groups_members on a non-group!");
}
else {
error_log("Called list_group_members(" . $dn . ")");
}
}
- $entries = self::normalize_result($this->search($dn));
+ $entries = self::normalize_result($this->_search($dn));
//console("ENTRIES for \$dn $dn", $entries);
foreach ($entries as $entry_dn => $entry) {
if (!isset($entry['objectclass'])) {
continue;
}
foreach ($entry['objectclass'] as $objectclass) {
switch (strtolower($objectclass)) {
case "groupofnames":
$group_members = array_merge($group_members, $this->_list_group_member($entry_dn, $entry));
break;
case "groupofuniquenames":
$group_members = array_merge($group_members, $this->_list_group_uniquemember($entry_dn, $entry));
break;
case "groupofurls":
$group_members = array_merge($group_members, $this->_list_group_memberurl($entry_dn, $entry));
break;
}
}
}
return array_filter($group_members);
}
private function _list_group_member($dn, $entry)
{
error_log("Called _list_group_member(" . $dn . ")");
$group_members = array();
if (empty($entry['member'])) {
return $group_members;
}
// Use the member attributes to return an array of member ldap objects
// NOTE that the member attribute is supposed to contain a DN
foreach ($entry['member'] as $member) {
$result = @ldap_read($this->conn, $member, '(objectclass=*)');
if (!$result) {
continue;
}
$member_entry = self::normalize_result(@ldap_get_entries($this->conn, $result));
$group_members[$member] = array_pop($member_entry);
// Nested groups
// $group_group_members = $this->_list_group_members($member, $member_entry);
// if ($group_group_members) {
// $group_members = array_merge($group_group_members, $group_members);
// }
}
return array_filter($group_members);
}
private function _list_group_uniquemember($dn, $entry)
{
//console("Called _list_group_uniquemember(" . $dn . ")", $entry);
// Use the member attributes to return an array of member ldap objects
// NOTE that the member attribute is supposed to contain a DN
$group_members = array();
if (empty($entry['uniquemember'])) {
return $group_members;
}
if (is_string($entry['uniquemember'])) {
//console("uniquemember for entry is not an array");
$entry['uniquemember'] = Array( $entry['uniquemember'] );
}
foreach ($entry['uniquemember'] as $member) {
$result = @ldap_read($this->conn, $member, '(objectclass=*)');
if (!$result) {
continue;
}
$member_entry = self::normalize_result(@ldap_get_entries($this->conn, $result));
$group_members[$member] = array_pop($member_entry);
// Nested groups
$group_group_members = $this->_list_group_members($member, $member_entry);
if ($group_group_members) {
$group_members = array_merge($group_group_members, $group_members);
}
}
return array_filter($group_members);
}
private function _list_group_memberurl($dn, $entry)
{
error_log("Called _list_group_memberurl(" . $dn . ")");
// Use the member attributes to return an array of member ldap objects
// NOTE that the member attribute is supposed to contain a DN
$group_members = array();
foreach ((array)$entry['memberurl'] as $url) {
$ldap_uri_components = $this->_parse_memberurl($url);
- $entries = self::normalize_result($this->search($ldap_uri_components[3], $ldap_uri_components[6]));
+ $entries = self::normalize_result($this->_search($ldap_uri_components[3], $ldap_uri_components[6]));
foreach ($entries as $entry_dn => $_entry) {
$group_members[$entry_dn] = $_entry;
error_log("Found " . $entry_dn);
// Nested group
// $group_group_members = $this->_list_group_members($entry_dn, $_entry);
// if ($group_group_members) {
// $group_members = array_merge($group_members, $group_group_members);
// }
}
}
return array_filter($group_members);
}
/**
* memberUrl attribute parser
*
* @param string $url URL string
*
* @return array URL elements
*/
private function _parse_memberurl($url)
{
error_log("Parsing URL: " . $url);
preg_match('/(.*):\/\/(.*)\/(.*)\?(.*)\?(.*)\?(.*)/', $url, $matches);
return $matches;
}
/**
* Returns name of the unique attribute
*/
private function unique_attribute()
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
return $unique_attr;
}
/**
* Quotes attribute value string
*
* @param string $str Attribute value
* @param bool $dn True if the attribute is a DN
*
* @return string Quoted string
*/
private static function _quote_string($str, $dn=false)
{
// take firt entry if array given
if (is_array($str)) {
$str = reset($str);
}
if ($dn) {
$replace = array(
',' => '\2c',
'=' => '\3d',
'+' => '\2b',
'<' => '\3c',
'>' => '\3e',
';' => '\3b',
"\\"=> '\5c',
'"' => '\22',
'#' => '\23'
);
}
else {
$replace = array(
'*' => '\2a',
'(' => '\28',
')' => '\29',
"\\" => '\5c',
'/' => '\2f'
);
}
return strtr($str, $replace);
}
}
diff --git a/lib/api/kolab_api_service_form_value.php b/lib/api/kolab_api_service_form_value.php
index 7d4647f..33850e3 100644
--- a/lib/api/kolab_api_service_form_value.php
+++ b/lib/api/kolab_api_service_form_value.php
@@ -1,657 +1,707 @@
<?php
/*
+--------------------------------------------------------------------------+
| This file is part of the Kolab Web Admin Panel |
| |
| Copyright (C) 2011-2012, Kolab Systems AG |
| |
| This program is free software: you can redistribute it and/or modify |
| it under the terms of the GNU Affero General Public License as published |
| by the Free Software Foundation, either version 3 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public License |
| along with this program. If not, see <http://www.gnu.org/licenses/> |
+--------------------------------------------------------------------------+
| Author: Aleksander Machniak <machniak@kolabsys.com> |
| Author: Jeroen van Meeuwen <vanmeeuwen@kolabsys.com> |
+--------------------------------------------------------------------------+
*/
/**
* Service providing functionality related to HTML forms generation/validation.
*/
class kolab_api_service_form_value extends kolab_api_service
{
/**
* Returns service capabilities.
*
* @param string $domain Domain name
*
* @return array Capabilities list
*/
public function capabilities($domain)
{
return array(
'generate' => 'r',
'validate' => 'r',
'select_options' => 'r',
'list_options' => 'r',
);
}
/**
* Generation of auto-filled field values.
*
* @param array $getdata GET parameters
* @param array $postdata POST parameters. Required parameters:
* - attributes: list of attribute names
* - type_id: Type identifier
* - object_type: Object type (user, group, etc.)
*
* @return array Response with attribute name as a key
*/
public function generate($getdata, $postdata)
{
$attribs = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);
$attributes = (array) $postdata['attributes'];
$result = array();
foreach ($attributes as $attr_name) {
if (empty($attr_name)) {
continue;
}
$method_name = 'generate_' . strtolower($attr_name) . '_' . strtolower($postdata['object_type']);
if (!method_exists($this, $method_name)) {
//console("Method $method_name doesn't exist");
$method_name = 'generate_' . strtolower($attr_name);
if (!method_exists($this, $method_name)) {
continue;
}
}
$result[$attr_name] = $this->{$method_name}($postdata, $attribs);
}
return $result;
}
/**
* Validation of field values.
*
* @param array $getdata GET parameters
* @param array $postdata POST parameters. Required parameters:
* - type_id: Type identifier
* - object_type: Object type (user, group, etc.)
*
* @return array Response with attribute name as a key
*/
public function validate($getdata, $postdata)
{
$attribs = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);
$result = array();
foreach ((array)$postdata as $attr_name => $attr_value) {
if (empty($attr_name) || $attr_name == 'type_id' || $attr_name == 'object_type') {
continue;
}
$method_name = 'validate_' . strtolower($attr_name);
if (!method_exists($this, $method_name)) {
$result[$attr_name] = 'OK';
continue;
}
$result[$attr_name] = $this->{$method_name}($attr_value);
}
return $result;
}
/**
* Generation of values for fields of type SELECT.
*
* @param array $getdata GET parameters
* @param array $postdata POST parameters. Required parameters:
* - attributes: list of attribute names
* - type_id: Type identifier
* - object_type: Object type (user, group, etc.)
*
* @return array Response with attribute name as a key
*/
public function select_options($getdata, $postdata)
{
+ //console("form_value.select_options postdata", $postdata);
+
$attribs = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);
$attributes = (array) $postdata['attributes'];
$result = array();
foreach ($attributes as $attr_name) {
if (empty($attr_name)) {
continue;
}
$method_name = 'select_options_' . strtolower($attr_name);
if (!method_exists($this, $method_name)) {
$result[$attr_name] = array();
continue;
}
$result[$attr_name] = $this->{$method_name}($postdata, $attribs);
}
return $result;
}
/**
* Generation of values for fields of type LIST.
*
* @param array $getdata GET parameters
* @param array $postdata POST parameters. Required parameters:
* - attribute: attribute name
* - type_id: Type identifier
* - object_type: Object type (user, group, etc.)
*
* @return array Response with attribute name as a key
*/
public function list_options($getdata, $postdata)
{
//console($postdata);
$attribs = $this->object_type_attributes($postdata['object_type'], $postdata['type_id']);
$attr_name = $postdata['attribute'];
$result = array(
// return search value, so client can match response to request
'search' => $postdata['search'],
'list' => array(),
);
if (empty($attr_name)) {
return $result;
}
$method_name = 'list_options_' . strtolower($attr_name);
//console($method_name);
if (!method_exists($this, $method_name)) {
return $result;
}
//console("Still here");
$result['list'] = $this->{$method_name}($postdata, $attribs);
return $result;
}
private function generate_alias($postdata, $attribs = array())
{
return $this->generate_secondary_mail($postdata, $attribs);
}
private function generate_cn($postdata, $attribs = array())
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['cn'])) {
// Use Data Please
foreach ($attribs['auto_form_fields']['cn']['data'] as $key) {
if (!isset($postdata[$key]) && !($key == $unique_attr)) {
throw new Exception("Key not set: " . $key, 12356);
}
}
// TODO: Generate using policy from configuration
$cn = trim($postdata['givenname'] . " " . $postdata['sn']);
return $cn;
}
}
private function generate_displayname($postdata, $attribs = array())
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['displayname'])) {
// Use Data Please
foreach ($attribs['auto_form_fields']['displayname']['data'] as $key) {
if (!isset($postdata[$key]) && !($key == $unique_attr)) {
throw new Exception("Key not set: " . $key, 12356);
}
}
// TODO: Generate using policy from configuration
$displayname = $postdata['givenname'];
if ($postdata['sn']) {
$displayname = $postdata['sn'] . ", " . $displayname;
}
// TODO: Figure out what may be sent as an additional comment;
//
// Examples:
//
// - van Meeuwen, Jeroen (Kolab Systems)
// - Doe, John (Contractor)
//
return $displayname;
}
}
private function generate_gidnumber($postdata, $attribs = array())
{
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['gidnumber'])) {
$auth = Auth::get_instance($_SESSION['user']->get_domain());
$conf = Conf::get_instance();
// TODO: Take a policy to use a known group ID, a known group (by name?)
// and/or create user private groups.
$search = Array(
'params' => Array(
'objectclass' => Array(
'type' => 'exact',
'value' => 'posixgroup',
),
),
);
$groups = $auth->list_groups(NULL, Array('gidnumber'), $search);
$highest_gidnumber = $conf->get('gidnumber_lower_barrier');
if (!$highest_gidnumber) {
$highest_gidnumber = 1000;
}
foreach ($groups as $dn => $attributes) {
if (!array_key_exists('gidnumber', $attributes)) {
continue;
}
if ($attributes['gidnumber'] > $highest_gidnumber) {
$highest_gidnumber = $attributes['gidnumber'];
}
}
//$users = $auth->list_users();
//console($groups);
return ($highest_gidnumber + 1);
}
}
private function generate_homedirectory($postdata, $attribs = array())
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['homedirectory'])) {
// Use Data Please
foreach ($attribs['auto_form_fields']['homedirectory']['data'] as $key) {
if (!isset($postdata[$key]) && !($key == $unique_attr)) {
throw new Exception("Key not set: " . $key, 12356);
}
}
// TODO: Home directory attribute to use
$uid = $this->generate_uid($postdata, $attribs);
// TODO: Home directory base path from configuration?
return '/home/' . $uid;
}
}
private function generate_mail($postdata, $attribs = array())
{
return $this->generate_primary_mail($postdata, $attribs);
}
private function generate_mail_group($postdata, $attribs = array())
{
return $this->generate_primary_mail_group($postdata, $attribs);
}
private function generate_mailalternateaddress($postdata, $attribs = array())
{
return $this->generate_secondary_mail($postdata, $attribs);
}
private function generate_mailhost($postdata, $attribs = array())
{
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['uidnumber'])) {
// This value is determined by the Kolab Daemon
return '';
}
}
private function generate_password($postdata, $attribs = array())
{
// TODO: Password complexity policy.
exec("head -c 200 /dev/urandom | tr -dc _A-Z-a-z-0-9 | head -c15", $userpassword_plain);
return $userpassword_plain[0];
}
private function generate_userpassword($postdata, $attribs = array())
{
return $this->generate_password($postdata, $attribs);
}
private function generate_primary_mail($postdata, $attribs = array())
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['mail'])) {
// Use Data Please
foreach ($attribs['auto_form_fields']['mail']['data'] as $key) {
if (!isset($postdata[$key]) && !($key == $unique_attr)) {
throw new Exception("Key not set: " . $key, 12356);
}
}
if (array_key_exists('uid', $attribs['auto_form_fields'])) {
if (!array_key_exists('uid', $postdata)) {
$postdata['uid'] = $this->generate_uid($postdata, $attribs);
}
}
$primary_mail = kolab_recipient_policy::primary_mail($postdata);
return $primary_mail;
}
}
private function generate_primary_mail_group($postdata, $attribs = array())
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['mail'])) {
// Use Data Please
foreach ($attribs['auto_form_fields']['mail']['data'] as $key) {
if (!isset($postdata[$key]) && !($key == $unique_attr)) {
throw new Exception("Key not set: " . $key, 12356);
}
}
$primary_mail = kolab_recipient_policy::primary_mail_group($postdata);
return $primary_mail;
}
}
private function generate_secondary_mail($postdata, $attribs = array())
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
$secondary_mail_address = Array();
if (isset($attribs['auto_form_fields'])) {
if (isset($attribs['auto_form_fields']['alias'])) {
$secondary_mail_key = 'alias';
} elseif (isset($attribs['auto_form_fields']['mailalternateaddress'])) {
$secondary_mail_key = 'mailalternateaddress';
} else {
throw new Exception("No valid input for secondary mail address(es)", 478);
}
foreach ($attribs['auto_form_fields'][$secondary_mail_key]['data'] as $key) {
if (!isset($postdata[$key]) && !($key == $unique_attr)) {
throw new Exception("Key not set: " . $key, 456789);
}
}
if (array_key_exists('uid', $attribs['auto_form_fields'])) {
if (!array_key_exists('uid', $postdata)) {
$postdata['uid'] = $this->generate_uid($postdata, $attribs);
}
}
$secondary_mail = kolab_recipient_policy::secondary_mail($postdata);
return $secondary_mail;
}
}
private function generate_uid($postdata, $attribs = array())
{
$conf = Conf::get_instance();
$unique_attr = $conf->get('unique_attribute');
if (!$unique_attr) {
$unique_attr = 'nsuniqueid';
}
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['uid'])) {
// Use Data Please
foreach ($attribs['auto_form_fields']['uid']['data'] as $key) {
if (!isset($postdata[$key]) && !($key == $unique_attr)) {
throw new Exception("Key not set: " . $key, 12356);
}
}
// TODO: Use preferredlanguage
if (isset($postdata['preferredlanguage'])) {
//console("Using locale for " . $postdata['preferredlanguage']);
setlocale(LC_ALL, $postdata['preferredlanguage']);
}
/* else {
console("No locale specified...!");
}
*/
$uid = iconv('UTF-8', 'ASCII//TRANSLIT', $postdata['sn']);
$uid = strtolower($uid);
$uid = preg_replace('/[^a-z-_]/i', '', $uid);
$orig_uid = $uid;
$auth = Auth::get_instance($_SESSION['user']->get_domain());
$x = 2;
while (($user_found = $auth->user_find_by_attribute(array('uid' => $uid)))) {
$user_found_dn = key($user_found);
$user_found_unique_attr = $auth->get_attribute($user_found_dn, $unique_attr);
//console("user that i found info", $user_found_unique_attr);
if ($user_found_unique_attr == $postdata[$unique_attr]) {
break;
}
$uid = $orig_uid . $x;
$x++;
}
return $uid;
}
}
private function generate_uidnumber($postdata, $attribs = array())
{
if (isset($attribs['auto_form_fields']) && isset($attribs['auto_form_fields']['uidnumber'])) {
$auth = Auth::get_instance($_SESSION['user']->get_domain());
$conf = Conf::get_instance();
$search = Array(
'params' => Array(
'objectclass' => Array(
'type' => 'exact',
'value' => 'posixaccount',
),
),
);
$users = $auth->list_users(NULL, Array('uidnumber'), $search);
$highest_uidnumber = $conf->get('uidnumber_lower_barrier');
if (!$highest_uidnumber) {
$highest_uidnumber = 1000;
}
foreach ($users as $dn => $attributes) {
if (!array_key_exists('uidnumber', $attributes)) {
continue;
}
if ($attributes['uidnumber'] > $highest_uidnumber) {
$highest_uidnumber = $attributes['uidnumber'];
}
}
return ($highest_uidnumber + 1);
}
}
private function list_options_kolabdelegate($postdata, $attribs = array())
{
$service = $this->controller->get_service('users');
$keyword = array('value' => $postdata['search']);
$data = array(
'attributes' => array('displayname', 'mail'),
'page_size' => 15,
'search' => array(
'displayname' => $keyword,
'cn' => $keyword,
'mail' => $keyword,
),
);
$result = $service->users_list(null, $data);
$list = $result['list'];
// convert to key=>value array
foreach ($list as $idx => $value) {
$list[$idx] = $value['displayname'];
if (!empty($value['mail'])) {
$list[$idx] .= ' <' . $value['mail'] . '>';
}
}
return $list;
}
private function list_options_nsrole($postdata, $attribs = array())
{
error_log("Listing options for attribute 'nsrole', while the expected attribute to use is 'nsroledn'");
return $this->list_options_nsroledn($postdata, $attribs);
}
private function list_options_nsroledn($postdata, $attribs = Array())
{
$service = $this->controller->get_service('roles');
$keyword = array('value' => $postdata['search']);
$data = array(
'attributes' => array('cn'),
'page_size' => 15,
'search' => array(
'displayname' => $keyword,
'cn' => $keyword,
'mail' => $keyword,
),
);
$result = $service->roles_list(null, $data);
$list = $result['list'];
// convert to key=>value array
foreach ($list as $idx => $value) {
$list[$idx] = $value['cn'];
}
return $list;
}
private function list_options_uniquemember($postdata, $attribs = array())
{
$service = $this->controller->get_service('users');
$keyword = array('value' => $postdata['search']);
$data = array(
'attributes' => array('displayname', 'mail'),
'page_size' => 15,
'search' => array(
'displayname' => $keyword,
'cn' => $keyword,
'mail' => $keyword,
),
);
$result = $service->users_list(null, $data);
$list = $result['list'];
// convert to key=>value array
foreach ($list as $idx => $value) {
$list[$idx] = $value['displayname'];
if (!empty($value['mail'])) {
$list[$idx] .= ' <' . $value['mail'] . '>';
}
}
return $list;
}
private function select_options_c($postdata, $attribs = array())
{
return $this->_select_options_from_db('c');
}
+ private function select_options_ou($postdata, $attribs = array())
+ {
+ $auth = Auth::get_instance();
+ $conf = Conf::get_instance();
+
+ $unique_attr = $conf->get('unique_attribute');
+
+ $base_dn = $conf->get('user_base_dn');
+ if (!$base_dn) {
+ $base_dn = $conf->get('base_dn');
+ }
+
+ $subject = $auth->search($base_dn, '(' . $unique_attr . '=' . $postdata['id'] . ')');
+
+ $subject_dn = $subject[0];
+
+ $subject_dn_components = ldap_explode_dn($subject_dn, 0);
+ unset($subject_dn_components['count']);
+
+ array_shift($subject_dn_components);
+
+ $subject_parent_ou = strtolower(implode(',', $subject_dn_components));
+
+ $ous = $auth->search($base_dn, '(objectclass=organizationalunit)');
+
+ $_ous = array();
+
+ foreach ($ous as $ou) {
+ $_ous[] = strtolower($ou);
+ }
+
+ sort($_ous);
+
+ $_ous['default'] = $subject_parent_ou;
+
+ return $_ous;
+ }
+
private function select_options_preferredlanguage($postdata, $attribs = array())
{
- return $this->_select_options_from_db('preferredlanguage');
+ $options = $this->_select_options_from_db('preferredlanguage');
+
+ $conf = Conf::get_instance();
+ $default = $conf->get('default_locale');
+ if (!$default) {
+ $default = 'en_US';
+ }
+
+ $options['default'] = $default;
+
+ return $options;
}
private function _select_options_from_db($attribute)
{
if (empty($attribute)) {
return false;
}
$db = SQL::get_instance();
$result = $db->fetch_assoc($db->query("SELECT option_values FROM options WHERE attribute = ?", $attribute));
$result = json_decode($result['option_values']);
if (empty($result)) {
return false;
} else {
return $result;
}
}
}
diff --git a/lib/client/kolab_client_task_user.php b/lib/client/kolab_client_task_user.php
index c66cb8b..fa94be7 100644
--- a/lib/client/kolab_client_task_user.php
+++ b/lib/client/kolab_client_task_user.php
@@ -1,375 +1,374 @@
<?php
/*
+--------------------------------------------------------------------------+
| This file is part of the Kolab Web Admin Panel |
| |
| Copyright (C) 2011-2012, Kolab Systems AG |
| |
| This program is free software: you can redistribute it and/or modify |
| it under the terms of the GNU Affero General Public License as published |
| by the Free Software Foundation, either version 3 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public License |
| along with this program. If not, see <http://www.gnu.org/licenses/> |
+--------------------------------------------------------------------------+
| Author: Aleksander Machniak <machniak@kolabsys.com> |
+--------------------------------------------------------------------------+
*/
class kolab_client_task_user extends kolab_client_task
{
protected $ajax_only = true;
protected $menu = array(
'add' => 'user.add',
);
/**
* Default action.
*/
public function action_default()
{
$this->output->set_object('content', 'user', true);
$this->output->set_object('task_navigation', $this->menu());
$this->action_list();
}
/**
* Users list action.
*/
public function action_list()
{
$page_size = 20;
$page = (int) self::get_input('page', 'POST');
if (!$page || $page < 1) {
$page = 1;
}
// request parameters
$post = array(
'attributes' => array('displayname', 'cn'),
// 'sort_order' => 'ASC',
'sort_by' => array('displayname', 'cn'),
'page_size' => $page_size,
'page' => $page,
);
// search parameters
if (!empty($_POST['search'])) {
$search = self::get_input('search', 'POST', true);
$field = self::get_input('field', 'POST');
$method = self::get_input('method', 'POST');
$search_request = array(
$field => array(
'value' => $search,
'type' => $method,
),
);
}
else if (!empty($_POST['search_request'])) {
$search_request = self::get_input('search_request', 'POST');
$search_request = @unserialize(base64_decode($search_request));
}
if (!empty($search_request)) {
$post['search'] = $search_request;
$post['search_operator'] = 'OR';
}
// get users list
$result = $this->api->post('users.list', null, $post);
$count = $result->get('count');
$result = (array) $result->get('list');
// calculate records
if ($count) {
$start = 1 + max(0, $page - 1) * $page_size;
$end = min($start + $page_size - 1, $count);
}
$rows = $head = $foot = array();
$cols = array('name');
$i = 0;
// table header
$head[0]['cells'][] = array('class' => 'name', 'body' => $this->translate('user.list'));
// table footer (navigation)
if ($count) {
$pages = ceil($count / $page_size);
$prev = max(0, $page - 1);
$next = $page < $pages ? $page + 1 : 0;
$count_str = kolab_html::span(array(
'content' => $this->translate('user.list.records', $start, $end, $count)), true);
$prev = kolab_html::a(array(
'class' => 'prev' . ($prev ? '' : ' disabled'),
'href' => '#',
'onclick' => $prev ? "kadm.command('user.list', {page: $prev})" : "return false",
));
$next = kolab_html::a(array(
'class' => 'next' . ($next ? '' : ' disabled'),
'href' => '#',
'onclick' => $next ? "kadm.command('user.list', {page: $next})" : "return false",
));
$foot_body = kolab_html::span(array('content' => $prev . $count_str . $next));
}
$foot[0]['cells'][] = array('class' => 'listnav', 'body' => $foot_body);
// table body
if (!empty($result)) {
foreach ($result as $idx => $item) {
if (!is_array($item) || (empty($item['displayname']) && empty($item['cn']))) {
continue;
}
$i++;
$cells = array();
$cells[] = array('class' => 'name', 'body' => kolab_html::escape(empty($item['displayname']) ? $item['cn'] : $item['displayname']),
'onclick' => "kadm.command('user.info', '$idx')");
$rows[] = array('id' => $i, 'class' => 'selectable', 'cells' => $cells);
}
}
else {
$rows[] = array('cells' => array(
0 => array('class' => 'empty-body', 'body' => $this->translate('user.norecords')
)));
}
$table = kolab_html::table(array(
'id' => 'userlist',
'class' => 'list',
'head' => $head,
'body' => $rows,
'foot' => $foot,
));
$this->output->set_env('search_request', $search_request ? base64_encode(serialize($search_request)) : null);
$this->output->set_env('list_page', $page);
$this->output->set_env('list_count', $count);
$this->watermark('taskcontent');
$this->output->set_object('userlist', $table);
}
/**
* User information (form) action.
*/
public function action_info()
{
$id = $this->get_input('id', 'POST');
$result = $this->api->get('user.info', array('user' => $id));
$user = $result->get();
$output = $this->user_form(null, $user);
$this->output->set_object('taskcontent', $output);
}
/**
* Users adding (form) action.
*/
public function action_add()
{
$data = $this->get_input('data', 'POST');
$output = $this->user_form(null, $data, true);
$this->output->set_object('taskcontent', $output);
}
private function user_form($attribs, $data = array())
{
if (empty($attribs['id'])) {
$attribs['id'] = 'user-form';
}
// Form sections
$sections = array(
'personal' => 'user.personal',
'contact_info' => 'user.contact_info',
'system' => 'user.system',
'config' => 'user.config',
'other' => 'user.other',
);
// field-to-section map and fields order
$fields_map = array(
'type_id' => 'personal',
'type_id_name' => 'personal',
- /* Sensibly first */
- 'title' => 'personal',
/* Probably input */
'givenname' => 'personal',
'sn' => 'personal',
/* Possibly input */
'initials' => 'personal',
'o' => 'personal',
+ 'title' => 'personal',
/* Probably generated */
'cn' => 'personal',
'displayname' => 'personal',
'ou' => 'personal',
'preferredlanguage' => 'personal',
/* Address lines together */
'street' => 'contact_info',
'postofficebox' => 'contact_info',
'roomnumber' => 'contact_info',
'postalcode' => 'contact_info',
'l' => 'contact_info',
'c' => 'contact_info',
/* Probably input */
'mobile' => 'contact_info',
'facsimiletelephonenumber' => 'contact_info',
'telephonenumber' => 'contact_info',
'homephone' => 'contact_info',
'pager' => 'contact_info',
'mail' => 'contact_info',
'alias' => 'contact_info',
'mailalternateaddress' => 'contact_info',
/* POSIX Attributes first */
'uid' => 'system',
'userpassword' => 'system',
'userpassword2' => 'system',
'uidnumber' => 'system',
'gidnumber' => 'system',
'homedirectory' => 'system',
'loginshell' => 'system',
'nsrole' => 'system',
'nsroledn' => 'system',
/* Kolab Settings */
'kolabhomeserver' => 'config',
'mailhost' => 'config',
'mailquota' => 'config',
'cyrususerquota' => 'config',
'kolabfreebusyfuture' => 'config',
'kolabinvitationpolicy' => 'config',
'kolabdelegate' => 'config',
'kolaballowsmtprecipient' => 'config',
'kolaballowsmtpsender' => 'config',
);
// Prepare fields
list($fields, $types, $type) = $this->form_prepare('user', $data, array('userpassword2'));
$add_mode = empty($data['id']);
$accttypes = array();
foreach ($types as $idx => $elem) {
$accttypes[$idx] = array('value' => $idx, 'content' => $elem['name']);
}
// Add user type id selector
$fields['type_id'] = array(
'section' => 'personal',
'type' => kolab_form::INPUT_SELECT,
'options' => $accttypes,
'onchange' => "kadm.user_save(true, 'personal')",
);
// Add password confirmation
if (isset($fields['userpassword'])) {
$fields['userpassword2'] = $fields['userpassword'];
}
// Hide account type selector if there's only one type
if (count($accttypes) < 2 || !$add_mode) {
$fields['type_id']['type'] = kolab_form::INPUT_HIDDEN;
}
// Create mode
if ($add_mode) {
// copy password to password confirm field
$data['userpassword2'] = $data['userpassword'];
// Page title
$title = $this->translate('user.add');
}
// Edit mode
else {
$title = $data['displayname'];
if (empty($title)) {
$title = $data['cn'];
}
// remove password
$data['userpassword'] = '';
// Add user type name
$fields['type_id_name'] = array(
'label' => 'user.type_id',
'section' => 'personal',
'value' => $accttypes[$type]['content'],
);
// Roles (extract role names)
if (!empty($fields['nsrole']) && !empty($data['nsrole'])) {
$data['nsrole'] = array_combine($data['nsrole'], $data['nsrole']);
foreach ($data['nsrole'] as $dn => $val) {
// @TODO: maybe ldap_explode_dn() would be better?
if (preg_match('/^cn=([^,]+)/i', $val, $m)) {
$data['nsrole'][$dn] = $m[1];
}
}
}
}
// Create form object and populate with fields
$form = $this->form_create('user', $attribs, $sections, $fields, $fields_map, $data, $add_mode);
$form->set_title(kolab_html::escape($title));
$this->output->add_translation('user.password.mismatch',
'user.add.success', 'user.edit.success', 'user.delete.success');
return $form->output();
}
/**
* Users search form.
*
* @return string HTML output of the form
*/
public function search_form()
{
$form = new kolab_form(array('id' => 'search-form'));
$form->add_section('criteria', kolab_html::escape($this->translate('search.criteria')));
$form->add_element(array(
'section' => 'criteria',
'label' => $this->translate('search.field'),
'name' => 'field',
'type' => kolab_form::INPUT_SELECT,
'options' => array(
'displayname' => kolab_html::escape($this->translate('search.name')),
'email' => kolab_html::escape($this->translate('search.email')),
'uid' => kolab_html::escape($this->translate('search.uid')),
),
));
$form->add_element(array(
'section' => 'criteria',
'label' => $this->translate('search.method'),
'name' => 'method',
'type' => kolab_form::INPUT_SELECT,
'options' => array(
'both' => kolab_html::escape($this->translate('search.contains')),
'exact' => kolab_html::escape($this->translate('search.is')),
'prefix' => kolab_html::escape($this->translate('search.prefix')),
),
));
return $form->output();
}
}
diff --git a/lib/kolab_client_task.php b/lib/kolab_client_task.php
index 23ad468..0bbef04 100644
--- a/lib/kolab_client_task.php
+++ b/lib/kolab_client_task.php
@@ -1,1061 +1,1061 @@
<?php
/*
+--------------------------------------------------------------------------+
| This file is part of the Kolab Web Admin Panel |
| |
| Copyright (C) 2011-2012, Kolab Systems AG |
| |
| This program is free software: you can redistribute it and/or modify |
| it under the terms of the GNU Affero General Public License as published |
| by the Free Software Foundation, either version 3 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public License |
| along with this program. If not, see <http://www.gnu.org/licenses/> |
+--------------------------------------------------------------------------+
| Author: Aleksander Machniak <machniak@kolabsys.com> |
| Author: Jeroen van Meeuwen <vanmeeuwen@kolabsys.com> |
+--------------------------------------------------------------------------+
*/
class kolab_client_task
{
/**
* @var kolab_client_output
*/
protected $output;
/**
* @var kolab_client_api
*/
protected $api;
/**
* @var Conf
*/
protected $config;
protected $ajax_only = false;
protected $page_title = 'Kolab Admin Panel';
protected $menu = array();
protected $cache = array();
protected static $translation = array();
/**
* Class constructor.
*/
public function __construct()
{
$this->config_init();
$this->output_init();
$this->api_init();
ini_set('session.use_cookies', 'On');
session_start();
$this->auth();
}
/**
* Localization initialization.
*/
private function locale_init()
{
$language = $this->get_language();
$LANG = array();
if (!$language) {
$language = 'en_US';
}
@include INSTALL_PATH . '/locale/en_US.php';
if ($language != 'en_US') {
@include INSTALL_PATH . "/locale/$language.php";
}
setlocale(LC_ALL, $language . '.utf8', 'en_US.utf8');
self::$translation = $LANG;
}
/**
* Configuration initialization.
*/
private function config_init()
{
$this->config = Conf::get_instance();
}
/**
* Output initialization.
*/
private function output_init()
{
$skin = $this->config_get('skin', 'default');
$this->output = new kolab_client_output($skin);
}
/**
* API initialization
*/
private function api_init()
{
$url = $this->config_get('api_url', '');
// TODO: Debug logging
//console($url);
if (!$url) {
$url = kolab_utils::https_check() ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
$url .= preg_replace('/\/?\?.*$/', '', $_SERVER['REQUEST_URI']);
$url .= '/api';
}
// TODO: Debug logging
//console($url);
$this->api = new kolab_client_api($url);
}
/**
* Returns system language (locale) setting.
*
* @return string Language code
*/
private function get_language()
{
$aliases = array(
'de' => 'de_DE',
'en' => 'en_US',
'pl' => 'pl_PL',
);
// UI language
$langs = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
$langs = explode(',', $langs);
if (!empty($_SESSION['user']) && !empty($_SESSION['user']['language'])) {
array_unshift($langs, $_SESSION['user']['language']);
}
while ($lang = array_shift($langs)) {
$lang = explode(';', $lang);
$lang = $lang[0];
$lang = str_replace('-', '_', $lang);
if (file_exists(INSTALL_PATH . "/locale/$lang.php")) {
return $lang;
}
if (isset($aliases[$lang]) && ($alias = $aliases[$lang])
&& file_exists(INSTALL_PATH . "/locale/$alias.php")
) {
return $alias;
}
}
return null;
}
/**
* User authentication (and authorization).
*/
private function auth()
{
if (isset($_POST['login'])) {
$login = $this->get_input('login', 'POST');
if ($login['username']) {
$result = $this->api->login($login['username'], $login['password']);
//console($result);
if ($token = $result->get('session_token')) {
$user = array(
'token' => $token,
'id' => $result->get('userid'),
'domain' => $result->get('domain')
);
$this->api->set_session_token($user['token']);
// find user settings
$res = $this->api->get('user.info', array('user' => $user['id']));
$res = $res->get();
if (is_array($res) && !empty($res)) {
$user['language'] = $res['preferredlanguage'];
$user['fullname'] = $res['cn'];
}
// @TODO: why user.info returns empty result for 'cn=Directory Manager' login?
else if (preg_match('/^cn=([a-zA-Z ]+)/', $login['username'], $m)) {
$user['fullname'] = ucwords($m[1]);
}
// Save user data
$_SESSION['user'] = $user;
if (($language = $this->get_language()) && $language != 'en_US') {
$_SESSION['user']['language'] = $language;
$session_config['language'] = $language;
}
// Configure API session
if (!empty($session_config)) {
$this->api->post('system.configure', null, $session_config);
}
header('Location: ?');
die;
}
else {
$code = $result->get_error_code();
$str = $result->get_error_str();
$label = 'loginerror';
if ($code == kolab_client_api::ERROR_INTERNAL
|| $code == kolab_client_api::ERROR_CONNECTION
) {
$label = 'internalerror';
$this->raise_error(500, 'Login failed. ' . $str);
}
$this->output->command('display_message', $label, 'error');
}
}
}
else if (!empty($_SESSION['user']) && !empty($_SESSION['user']['token'])) {
$this->api->set_session_token($_SESSION['user']['token']);
return;
}
}
/**
* Main execution.
*/
public function run()
{
// Initialize locales
$this->locale_init();
// Assign self to template variable
$this->output->assign('engine', $this);
// Session check
if (empty($_SESSION['user']) || empty($_SESSION['user']['token'])) {
$this->action_logout();
}
// Run security checks
$this->input_checks();
$action = $this->get_input('action', 'GET');
if ($action) {
$method = 'action_' . $action;
if (method_exists($this, $method)) {
$this->$method();
}
}
else if (method_exists($this, 'action_default')) {
$this->action_default();
}
}
/**
* Security checks and input validation.
*/
public function input_checks()
{
$ajax = $this->output->is_ajax();
// Check AJAX-only tasks
if ($this->ajax_only && !$ajax) {
$this->raise_error(500, 'Invalid request type!', null, true);
}
// CSRF prevention
$token = $ajax ? kolab_utils::get_request_header('X-Session-Token') : $this->get_input('token');
$task = $this->get_task();
if ($task != 'main' && $token != $_SESSION['user']['token']) {
$this->raise_error(403, 'Invalid request data!', null, true);
}
}
/**
* Logout action.
*/
private function action_logout()
{
if (!empty($_SESSION['user']) && !empty($_SESSION['user']['token'])) {
$this->api->logout();
}
$_SESSION = array();
if ($this->output->is_ajax()) {
$this->output->command('main_logout');
}
else {
$this->output->add_translation('loginerror', 'internalerror');
}
$this->output->send('login');
exit;
}
/**
* Error action (with error logging).
*
* @param int $code Error code
* @param string $msg Error message
* @param array $args Optional arguments (type, file, line)
* @param bool $output Enable to send output and finish
*/
public function raise_error($code, $msg, $args = array(), $output = false)
{
$log_line = sprintf("%s Error: %s (%s)",
isset($args['type']) ? $args['type'] : 'PHP',
$msg . (isset($args['file']) ? sprintf(' in %s on line %d', $args['file'], $args['line']) : ''),
$_SERVER['REQUEST_METHOD']);
if (!write_log('errors', $log_line)) {
// send error to PHPs error handler if write_log() didn't succeed
trigger_error($msg, E_USER_ERROR);
}
if (!$output) {
return;
}
if ($this->output->is_ajax()) {
header("HTTP/1.0 $code $msg");
die;
}
$this->output->assign('error_code', $code);
$this->output->assign('error_message', $msg);
$this->output->send('error');
exit;
}
/**
* Output sending.
*/
public function send()
{
$template = $this->get_task();
if ($this->page_title) {
$this->output->assign('pagetitle', $this->page_title);
}
$this->output->send($template);
exit;
}
/**
* Returns name of the current task.
*
* @return string Task name
*/
public function get_task()
{
$class_name = get_class($this);
if (preg_match('/^kolab_client_task_([a-z]+)$/', $class_name, $m)) {
return $m[1];
}
}
/**
* Returns configuration option value.
*
* @param string $name Option name
* @param mixed $fallback Default value
*
* @return mixed Option value
*/
public function config_get($name, $fallback = null)
{
// @TODO: remove this check
if ($name == "devel_mode")
return TRUE;
$value = $this->config->get('kolab_wap', $name);
return $value !== null ? $value : $fallback;
}
/**
* Returns translation of defined label/message.
*
* @return string Translated string.
*/
public static function translate()
{
$args = func_get_args();
if (is_array($args[0])) {
$args = $args[0];
}
$label = $args[0];
if (isset(self::$translation[$label])) {
$content = trim(self::$translation[$label]);
}
else {
$content = $label;
}
for ($i = 1, $len = count($args); $i < $len; $i++) {
$content = str_replace('$'.$i, $args[$i], $content);
}
return $content;
}
/**
* Returns input parameter value.
*
* @param string $name Parameter name
* @param string $type Parameter type (GET|POST|NULL)
* @param bool $allow_html Disables stripping of insecure content (HTML tags)
*
* @see kolab_utils::get_input
* @return mixed Input value.
*/
public static function get_input($name, $type = null, $allow_html = false)
{
if ($type == 'GET') {
$type = kolab_utils::REQUEST_GET;
}
else if ($type == 'POST') {
$type = kolab_utils::REQUEST_POST;
}
else {
$type = kolab_utils::REQUEST_ANY;
}
return kolab_utils::get_input($name, $type, $allow_html);
}
/**
* Returns task menu output.
*
* @return string HTML output
*/
protected function menu()
{
if (empty($this->menu)) {
return '';
}
$task = $this->get_task();
$capabilities = $this->capabilities();
//console($capabilities);
foreach ($this->menu as $idx => $label) {
//console("$task: $task, idx: $idx, label: $label");
if (in_array($task, array('user', 'group'))) {
if (!array_key_exists($task . "." . $idx, $capabilities['actions'])) {
//console("$task.$idx not in \$capabilities['actions'], skipping", $capabilities['actions']);
continue;
}
}
if (strpos($idx, '.')) {
$action = $idx;
$class = preg_replace('/\.[a-z_-]+$/', '', $idx);
}
else {
$action = $task . '.' . $idx;
$class = $idx;
}
$menu[$idx] = sprintf('<li class="%s">'
.'<a href="#%s" onclick="return kadm.command(\'%s\', \'\', this)">%s</a></li>',
$class, $idx, $action, $this->translate($label));
}
if (is_array($menu))
return '<ul>' . implode("\n", $menu) . '</ul>';
else
return '<ul>' . $menu . '</ul>';
}
/**
* Adds watermark page definition into main page.
*/
protected function watermark($name)
{
$this->output->command('set_watermark', $name);
}
/**
* Returns list of user types.
*
* @return array List of user types
*/
protected function user_types()
{
if (isset($_SESSION['user_types'])) {
return $_SESSION['user_types'];
}
$result = $this->api->post('user_types.list');
$list = $result->get('list');
if (is_array($list) && !$this->config_get('devel_mode')) {
$_SESSION['user_types'] = $list;
}
return $list;
}
/**
* Returns user name.
*
* @param string $dn User DN attribute value
*
* @return string User name (displayname)
*/
protected function user_name($dn)
{
if (!empty($this->cache['user_names']) && isset($this->cache['user_names'][$dn])) {
return $this->cache['user_names'][$dn];
}
$result = $this->api->get('user.info', array('user' => $dn));
$username = $result->get('displayname');
if (empty($username)) {
$username = $result->get('cn');
}
if (empty($username)) {
if (preg_match('/^cn=([a-zA=Z ]+)/', $dn, $m)) {
$username = ucwords($m[1]);
}
}
return $this->cache['user_names'][$dn] = $username;
}
/**
* Returns list of system capabilities.
*
* @return array List of system capabilities
*/
protected function capabilities()
{
if (!isset($_SESSION['capabilities'])) {
$result = $this->api->post('system.capabilities');
$list = $result->get('list');
if (is_array($list)) {
$_SESSION['capabilities'] = $list;
}
}
$domain = $_SESSION['user']['domain'];
return $_SESSION['capabilities'][$domain];
}
/**
* Returns system capability
*
* @param string $name Capability (key) name
*
* @return array Capability value if supported, NULL otherwise
*/
protected function get_capability($name)
{
$caps = $this->capabilities();
return $caps[$name];
}
/**
* Returns execution time in seconds
*
* @param string Execution time
*/
public function gentime()
{
return sprintf('%.4f', microtime(true) - KADM_START);
}
/**
* Returns HTML output of login form
*
* @param string HTML output
*/
public function login_form()
{
$post = $this->get_input('login', 'POST');
$username = kolab_html::label(array(
'for' => 'login_name',
'content' => $this->translate('login.username')), true)
. kolab_html::input(array(
'type' => 'text',
'id' => 'login_name',
'name' => 'login[username]',
'value' => $post['username'],
'autofocus' => true));
$password = kolab_html::label(array(
'for' => 'login_pass',
'content' => $this->translate('login.password')), true)
. kolab_html::input(array(
'type' => 'password',
'id' => 'login_pass',
'name' => 'login[password]',
'value' => ''));
$button = kolab_html::input(array(
'type' => 'submit',
'id' => 'login_submit',
'value' => $this->translate('login.login')));
$form = kolab_html::form(array(
'id' => 'login_form',
'name' => 'login',
'method' => 'post',
'action' => '?'),
kolab_html::span(array('content' => $username))
. kolab_html::span(array('content' => $password))
. $button);
return $form;
}
/**
* Returns form element definition based on field attributes
*
* @param array $field Field attributes
* @param array $data Attribute values
*
* @return array Field definition
*/
protected function form_element_type($field, $data = array())
{
$result = array();
switch ($field['type']) {
case 'select':
case 'multiselect':
if (!isset($field['values'])) {
$data['attributes'] = array($field['name']);
$resp = $this->api->post('form_value.select_options', null, $data);
$field['values'] = $resp->get($field['name']);
}
if (!empty($field['values']['default'])) {
$result['value'] = $field['values']['default'];
unset($field['values']['default']);
}
$result['type'] = kolab_form::INPUT_SELECT;
if (!empty($field['values'])) {
$result['options'] = array_combine($field['values'], $field['values']);
}
else {
$result['options'] = array('');
}
if ($field['type'] == 'multiselect') {
$result['multiple'] = true;
}
break;
case 'list':
$result['type'] = kolab_form::INPUT_TEXTAREA;
$result['data-type'] = kolab_form::TYPE_LIST;
if (!empty($field['maxlength'])) {
$result['data-maxlength'] = $field['maxlength'];
}
if (!empty($field['autocomplete'])) {
$result['data-autocomplete'] = true;
}
break;
default:
$result['type'] = kolab_form::INPUT_TEXT;
if (isset($field['maxlength'])) {
$result['maxlength'] = $field['maxlength'];
}
}
$result['required'] = empty($field['optional']);
return $result;
}
/**
* HTML Form elements preparation.
*
* @param string $name Object name (user, group, etc.)
* @param array $data Object data
* @param array $extra_fields Extra field names
*
* @return array Fields list, Object types list, Current type ID
*/
protected function form_prepare($name, &$data, $extra_fields = array())
{
$types = (array) $this->{$name . '_types'}();
$form_id = $attribs['id'];
$add_mode = empty($data['id']);
$event_fields = array();
$auto_fields = array();
$form_fields = array();
$fields = array();
$auto_attribs = array();
$extra_fields = array_flip($extra_fields);
// Selected account type
if (!empty($data['type_id'])) {
$type = $data['type_id'];
}
else {
$data['type_id'] = $type = key($types);
}
if ($type) {
$auto_fields = (array) $types[$type]['attributes']['auto_form_fields'];
$form_fields = (array) $types[$type]['attributes']['form_fields'];
}
// Mark automatically generated fields as read-only, etc.
foreach ($auto_fields as $idx => $field) {
//console("\$field value for \$auto_fields[\$idx] (idx: $idx)", $auto_fields[$idx]);
if (!is_array($field)) {
//console("not an array... unsetting");
unset($auto_fields[$idx]);
continue;
}
// merge with field definition from
if (isset($form_fields[$idx])) {
$field = array_merge($field, $form_fields[$idx]);
}
// remove auto-generated value on type change, it will be re-generated
else if ($add_mode) {
unset($data[$idx]);
}
$field['name'] = $idx;
- $fields[$idx] = $this->form_element_type($field);
+ $fields[$idx] = $this->form_element_type($field, $data);
$fields[$idx]['readonly'] = true;
$extra_fields[$idx] = true;
// build auto_attribs and event_fields lists
$is_data = 0;
if (!empty($field['data'])) {
foreach ($field['data'] as $fd) {
$event_fields[$fd][] = $idx;
if (isset($data[$fd])) {
$is_data++;
}
}
if (count($field['data']) == $is_data) {
$auto_attribs[] = $idx;
}
}
else {
//console("\$field['data'] is empty for \$auto_fields[\$idx] (idx: $idx)");
$auto_attribs[] = $idx;
// Unset the $auto_field array key to prevent the form field from
// becoming disabled/readonly
unset($auto_fields[$idx]);
}
}
// Other fields
foreach ($form_fields as $idx => $field) {
if (!isset($fields[$idx])) {
$field['name'] = $idx;
- $fields[$idx] = $this->form_element_type($field);
+ $fields[$idx] = $this->form_element_type($field, $data);
}
else {
unset($extra_fields[$idx]);
}
$fields[$idx]['readonly'] = false;
// Attach on-change events to some fields, to update
// auto-generated field values
if (!empty($event_fields[$idx])) {
$event = json_encode(array_unique($event_fields[$idx]));
$fields[$idx]['onchange'] = "kadm.form_value_change($event)";
}
}
// Get the rights on the entry and attribute level
$result = $this->api->get("user.effective_rights", array($name => $data['id']));
$attribute_rights = $result->get('attributeLevelRights');
$entry_rights = $result->get('entryLevelRights');
$data['effective_rights'] = array(
'attribute' => $attribute_rights,
'entry' => $entry_rights,
);
foreach ($fields as $idx => $field) {
if (!array_key_exists($idx, $attribute_rights)) {
// If the entry level rights contain 'add' and 'delete', well, you're an admin
if (in_array('add', $entry_rights) && in_array('delete', $entry_rights)) {
$fields[$idx]['readonly'] = false;
}
else {
$fields[$idx]['readonly'] = true;
}
}
else {
// No entry level rights, check on attribute level
if (!in_array('write', $attribute_rights[$idx])) {
$fields[$idx]['readonly'] = true;
}
}
}
// Register list of auto-generated fields
$this->output->set_env('auto_fields', $auto_fields);
// Register list of disabled fields
$this->output->set_env('extra_fields', array_keys($extra_fields));
// (Re-|Pre-)populate auto_form_fields
if ($add_mode) {
if (!empty($auto_attribs)) {
$data = array_merge((array)$data, array(
'attributes' => $auto_attribs,
'object_type' => $name,
));
$resp = $this->api->post('form_value.generate', null, $data);
$data = array_merge((array)$data, (array)$resp->get());
}
}
else {
// Add common information fields
$add_fields = array(
'creatorsname' => 'createtimestamp',
'modifiersname' => 'modifytimestamp',
);
foreach ($add_fields as $idx => $val) {
if (!empty($data[$idx])) {
if ($value = $this->user_name($data[$idx])) {
if ($data[$val]) {
$value .= ' (' . strftime('%x %X', strtotime($data[$val])) . ')';
}
$fields[$idx] = array(
'label' => $idx,
'section' => 'system',
'value' => $value,
);
}
}
}
// Add debug information
if ($this->config_get('devel_mode')) {
ksort($data);
$debug = kolab_html::escape(print_r($data, true));
$debug = preg_replace('/(^Array\n\(|\n*\)$|\t)/', '', $debug);
$debug = str_replace("\n ", "\n", $debug);
$debug = '<pre class="debug">' . $debug . '</pre>';
$fields['debug'] = array(
'label' => 'debug',
'section' => 'system',
'value' => $debug,
);
}
}
// Add object type hidden field
$fields['object_type'] = array(
'section' => 'system',
'type' => kolab_form::INPUT_HIDDEN,
'value' => $name,
);
// Add entry identifier
if (!$add_mode) {
$fields['id'] = array(
'section' => 'system',
'type' => kolab_form::INPUT_HIDDEN,
'value' => $data['id']
);
$fields['entrydn'] = Array(
'section' => 'system',
'type' => kolab_form::INPUT_HIDDEN,
'value' => $data['entrydn']
);
}
return array($fields, $types, $type);
}
/**
* HTML Form creation.
*
* @param string $name Object name (user, group, etc.)
* @param array $attribs HTML attributes of the form
* @param array $sections List of form sections
* @param array $fields Fields list (from self::form_prepare())
* @param array $fields_map Fields map (used for sorting and sections assignment)
* @param array $data Object data (with effective rights, see form_prepare())
*
* @return kolab_form HTML Form object
*/
protected function form_create($name, $attribs, $sections, $fields, $fields_map, $data, $add_mode)
{
// Assign sections to fields
foreach ($fields as $idx => $field) {
if (!$field['section']) {
$fields[$idx]['section'] = isset($fields_map[$idx]) ? $fields_map[$idx] : 'other';
}
}
// Sort
foreach ($fields_map as $idx => $val) {
if (array_key_exists($idx, $fields)) {
$fields_map[$idx] = $fields[$idx];
unset($fields[$idx]);
}
else {
unset($fields_map[$idx]);
}
}
if (!empty($fields)) {
$fields_map = array_merge($fields_map, $fields);
}
$form = new kolab_form($attribs);
$assoc_fields = array();
$req_fields = array();
$writeable = 0;
$auto_fields = $this->output->get_env('auto_fields');
//console("\$auto_fields", $auto_fields);
// Parse elements and add them to the form object
foreach ($sections as $section_idx => $section) {
$form->add_section($section_idx, kolab_html::escape($this->translate($section)));
foreach ($fields_map as $idx => $field) {
if ($field['section'] != $section_idx) {
continue;
}
if (empty($field['label'])) {
$field['label'] = "$name.$idx";
}
$field['label'] = kolab_html::escape($this->translate($field['label']));
$field['description'] = "$name.$idx.desc";
$field['section'] = $section_idx;
if (empty($field['value']) && !empty($data[$idx])) {
$field['value'] = $data[$idx];
// Convert data for the list field with autocompletion
if ($field['data-type'] == kolab_form::TYPE_LIST && kolab_utils::is_assoc($data[$idx])) {
$assoc_fields[$idx] = $data[$idx];
$field['value'] = array_keys($data[$idx]);
}
if (is_array($field['value'])) {
$field['value'] = implode("\n", $field['value']);
}
}
/*
if (!empty($field['suffix'])) {
$field['suffix'] = kolab_html::escape($this->translate($field['suffix']));
}
*/
if (!empty($field['options'])) {
foreach ($field['options'] as $opt_idx => $option) {
if (is_array($option)) {
$field['options'][$opt_idx]['content'] = kolab_html::escape($this->translate($option['content']));
}
else {
$field['options'][$opt_idx] = kolab_html::escape($this->translate($option));
}
}
}
if (!empty($field['description'])) {
$description = $this->translate($field['description']);
if ($description != $field['description']) {
$field['title'] = $description;
}
unset($field['description']);
}
if (empty($field['name'])) {
$field['name'] = $idx;
}
if (empty($field['readonly']) && empty($field['disabled'])) {
// count writeable fields
if ($field['type'] && $field['type'] != kolab_form::INPUT_HIDDEN) {
$writeable++;
}
if (!empty($field['required'])) {
$req_fields[] = $idx;
}
}
$form->add_element($field);
}
}
if (!empty($data['section'])) {
$form->activate_section($data['section']);
}
if ($writeable) {
$form->add_button(array(
'value' => kolab_html::escape($this->translate('submit.button')),
'onclick' => "kadm.{$name}_save()",
));
}
if (!empty($data['id']) && in_array('delete', $data['effective_rights']['entry'])) {
$id = $data['id'];
$form->add_button(array(
'value' => kolab_html::escape($this->translate('delete.button')),
'onclick' => "kadm.{$name}_delete('{$id}')",
));
}
$this->output->set_env('form_id', $attribs['id']);
$this->output->set_env('assoc_fields', $assoc_fields);
$this->output->set_env('required_fields', $req_fields);
$this->output->add_translation('form.required.empty');
return $form;
}
}
diff --git a/lib/locale/en_US.php b/lib/locale/en_US.php
index 44ee0f0..82fdac4 100644
--- a/lib/locale/en_US.php
+++ b/lib/locale/en_US.php
@@ -1,136 +1,136 @@
<?php
$LANG['loading'] = 'Loading...';
$LANG['saving'] = 'Saving data...';
$LANG['deleting'] = 'Deleting data...';
$LANG['error'] = 'Error';
$LANG['servererror'] = 'Server Error!';
$LANG['loginerror'] = 'Incorrect username or password!';
$LANG['internalerror'] = 'Internal system error!';
$LANG['welcome'] = 'Welcome to the Kolab Groupware Server Maintenance';
$LANG['reqtime'] = 'Request time: $1 sec.';
$LANG['debug'] = 'Debug info';
$LANG['info'] = 'Information';
$LANG['creatorsname'] = 'Created by';
$LANG['modifiersname'] = 'Modified by';
$LANG['login.username'] = 'Username:';
$LANG['login.password'] = 'Password:';
$LANG['login.login'] = 'Login';
$LANG['form.required.empty'] = 'Some of the required fields are empty!';
$LANG['search'] = 'Search';
$LANG['search.criteria'] = 'Search criteria';
$LANG['search.reset'] = 'Reset';
$LANG['search.field'] = 'Field:';
$LANG['search.method'] = 'Method:';
$LANG['search.contains'] = 'contains';
$LANG['search.is'] = 'is';
$LANG['search.prefix'] = 'begins with';
$LANG['search.name'] = 'name';
$LANG['search.email'] = 'email';
$LANG['search.uid'] = 'UID';
$LANG['search.loading'] = 'Searching...';
$LANG['search.acchars'] = 'At least $min characters required for autocompletion';
$LANG['menu.users'] = 'Users';
$LANG['menu.groups'] = 'Groups';
$LANG['menu.about'] = 'About';
$LANG['menu.kolab'] = 'Kolab';
$LANG['menu.kolabsys'] = 'Kolab Systems';
$LANG['menu.technology'] = 'Technology';
$LANG['user.add'] = 'Add User';
$LANG['user.c'] = 'Country';
$LANG['user.cn'] = 'Common name';
$LANG['user.config'] = 'Configuration';
$LANG['user.contact'] = 'Contact';
$LANG['user.contact_info'] = 'Contact Information';
$LANG['user.homephone'] = 'Home Phone Number';
$LANG['user.kolaballowsmtprecipient'] = 'Recipient(s) Access List';
$LANG['user.kolaballowsmtpsender'] = 'Sender Access List';
$LANG['user.kolabdelegate'] = 'Delegates';
$LANG['user.kolabinvitationpolicy'] = 'Invitation Handling Policy';
$LANG['user.l'] = 'City, Region';
$LANG['user.list'] = 'Users List';
$LANG['user.list.records'] = '$1 to $2 of $3';
$LANG['user.mailquota'] = 'Quota';
$LANG['user.mailquota.desc'] = 'Leave blank for unlimited';
$LANG['user.mobile'] = 'Mobile Phone Number';
$LANG['user.name'] = 'Name';
$LANG['user.norecords'] = 'No user records found!';
$LANG['user.other'] = 'Other';
$LANG['user.o'] = 'Organization';
$LANG['user.pager'] = 'Pager Number';
$LANG['user.personal'] = 'Personal';
$LANG['user.postalcode'] = 'Postal Code';
$LANG['user.sn'] = 'Surname';
$LANG['user.system'] = 'System';
$LANG['user.telephonenumber'] = 'Phone Number';
+$LANG['user.title'] = 'Job Title';
$LANG['user.givenname'] = 'Given name';
$LANG['user.displayname'] = 'Display name';
$LANG['user.mail'] = 'Primary Email Address';
$LANG['user.mailhost'] = 'Email Server';
$LANG['user.kolabhomeserver'] = 'Email Server';
$LANG['user.initials'] = 'Middle name';
-$LANG['user.title'] = 'Title';
$LANG['user.country'] = 'Country';
$LANG['user.country.desc'] = '2 letter code from ISO 3166-1';
$LANG['user.phone'] = 'Phone number';
$LANG['user.fax'] = 'Fax number';
$LANG['user.room'] = 'Room number';
$LANG['user.street'] = 'Street';
$LANG['user.city'] = 'City';
$LANG['user.postbox'] = 'Postal box';
$LANG['user.postcode'] = 'Postal code';
$LANG['user.org'] = 'Organization';
$LANG['user.orgunit'] = 'Organizational Unit';
$LANG['user.fbinterval'] = 'Free-Busy interval';
$LANG['user.fbinterval.desc'] = 'Leave blank for default (60 days)';
$LANG['user.type_id'] = 'Account type';
$LANG['user.alias'] = 'Secondary Email Address(es)';
$LANG['user.mailalternateaddress'] = 'Secondary Email Address(es)';
$LANG['user.invitation-policy'] = 'Invitation policy';
$LANG['user.delegate'] = 'Email delegates';
$LANG['user.delegate.desc'] = 'Others allowed to send emails with a "From" address of this account';
$LANG['user.smtp-recipients'] = 'Allowed recipients';
$LANG['user.smtp-recipients.desc'] = 'Restricts allowed recipients of SMTP messages';
$LANG['user.uid'] = 'Unique identity (UID)';
$LANG['user.nsrole'] = 'Role(s)';
$LANG['user.nsroledn'] = $LANG['user.nsrole'];
$LANG['user.userpassword'] = 'Password';
$LANG['user.userpassword2'] = 'Confirm password';
$LANG['user.password.mismatch'] = 'Passwords do not match!';
$LANG['user.homeserver'] = 'Mailbox home server';
$LANG['user.add.success'] = 'User created successfully.';
$LANG['user.delete.success'] = 'User deleted successfully.';
$LANG['user.edit.success'] = 'User edited successfully.';
$LANG['user.preferredlanguage'] = 'Native tongue';
$LANG['user.gidnumber'] = 'Primary group number';
$LANG['user.homedirectory'] = 'Home directory';
$LANG['user.loginshell'] = 'Shell';
$LANG['user.uidnumber'] = 'User ID number';
$LANG['group.add'] = 'Add Group';
$LANG['group.norecords'] = 'No group records found!';
$LANG['group.list'] = 'Groups List';
$LANG['group.list.records'] = '$1 to $2 of $3';
$LANG['group.cn'] = 'Common name';
$LANG['group.mail'] = 'Primary Email Address';
$LANG['group.type_id'] = 'Group type';
$LANG['group.add.success'] = 'Group created successfully.';
$LANG['group.delete.success'] = 'Group deleted successfully.';
$LANG['group.edit.success'] = 'Group edited successfully.';
$LANG['group.gidnumber'] = 'Primary group number';
$LANG['group.uniquemember'] = 'Members';
$LANG['group.system'] = 'System';
$LANG['group.other'] = 'Other';
$LANG['MB'] = 'MB';
$LANG['days'] = 'days';
$LANG['submit.button'] = 'Submit';
$LANG['delete.button'] = 'Delete';
$LANG['about.community'] = 'This is the Community Edition of the <b>Kolab Server</b>.';
$LANG['about.warranty'] = 'It comes with absolutely <b>no warranties</b> and is typically run entirely self supported. You can find help & information on the community <a href="http://kolab.org">web site</a> & <a href="http://wiki.kolab.org">wiki</a>.';
$LANG['about.support'] = 'Professional support is available from <a href="http://kolabsys.com">Kolab Systems</a>.';

File Metadata

Mime Type
text/x-diff
Expires
Sat, Apr 4, 1:39 AM (1 w, 5 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
18821966
Default Alt Text
(153 KB)

Event Timeline