Merge pull request #9 from LDAPAccountManager/type_api

new type API
This commit is contained in:
gruberroland 2017-01-08 21:06:10 +01:00 committed by GitHub
commit 08771b3ffd
55 changed files with 2375 additions and 1606 deletions

6
composer.json Normal file
View File

@ -0,0 +1,6 @@
{
"require-dev" : {
"phpunit/phpunit" : "4.5.0",
"squizlabs/php_codesniffer" : "2.7.1"
}
}

View File

@ -12,6 +12,9 @@
@ -47,7 +50,17 @@ This is a list of API changes for all LAM releases.
<br> <br>
<h2>5.5 -&gt; 5.6</h2> <h2>5.5 -&gt; 5.6</h2>
Functions in lib/types.inc got namespace LAM/TYPES (e.g. getTypeAlias()).<br> <ul>
<li>
Functions in lib/types.inc got namespace LAM/TYPES (e.g. getTypeAlias()).</li>
<li>
New API to access configured account types: LAM\TYPES\TypeManager.</li>
<li>class baseType: new function getSuffixFilter()</li>
<li>moved getSuffixList() from baseType to ConfiguredType<br>
</li>
</ul>
<h2>5.4 -&gt; 5.5</h2>Functions Ldap::encrypt/decrypt in ldap.inc moved to lamEncrypt/lamDecrypt in security.inc.<br> <h2>5.4 -&gt; 5.5</h2>Functions Ldap::encrypt/decrypt in ldap.inc moved to lamEncrypt/lamDecrypt in security.inc.<br>
<br> <br>

View File

@ -4,7 +4,7 @@ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Tilo Lutz Copyright (C) 2003 - 2006 Tilo Lutz
2009 - 2016 Roland Gruber 2009 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -672,13 +672,14 @@ function searchLDAPByAttribute($name, $value, $objectClass, $attributes, $scopes
elseif (sizeof($filterParts) > 1) { elseif (sizeof($filterParts) > 1) {
$filter = '(& ' . implode(' ', $filterParts) . ')'; $filter = '(& ' . implode(' ', $filterParts) . ')';
} }
$activeTypes = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
for ($s = 0; $s < sizeof($scopes); $s++) { $activeTypes = $typeManager->getConfiguredTypes();
if (!in_array($scopes[$s], $activeTypes)) { foreach ($activeTypes as $type) {
if (!in_array($type->getScope(), $scopes)) {
continue; // skip non-active account types continue; // skip non-active account types
} }
// search LDAP // search LDAP
$entries = searchLDAPPaged($_SESSION['ldap']->server(), escapeDN($_SESSION['config']->get_Suffix($scopes[$s])), $entries = searchLDAPPaged($_SESSION['ldap']->server(), escapeDN($type->getSuffix()),
$filter, $attributes, 0, $_SESSION['config']->get_searchLimit()); $filter, $attributes, 0, $_SESSION['config']->get_searchLimit());
if (ldap_errno($_SESSION['ldap']->server()) == 4) { if (ldap_errno($_SESSION['ldap']->server()) == 4) {
logNewMessage(LOG_WARNING, 'LDAP size limit exeeded. Please increase the limit on your server.'); logNewMessage(LOG_WARNING, 'LDAP size limit exeeded. Please increase the limit on your server.');
@ -703,9 +704,14 @@ function searchLDAPByFilter($filter, $attributes, $scopes, $attrsOnly = false) {
if ($attrsOnly) { if ($attrsOnly) {
$readAttributesOnly = 1; $readAttributesOnly = 1;
} }
for ($s = 0; $s < sizeof($scopes); $s++) { $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
foreach ($types as $type) {
if (!in_array($type->getScope(), $scopes)) {
continue;
}
// search LDAP // search LDAP
$entries = searchLDAPPaged($_SESSION['ldap']->server(), escapeDN($_SESSION['config']->get_Suffix($scopes[$s])), $entries = searchLDAPPaged($_SESSION['ldap']->server(), escapeDN($type->getSuffix()),
$filter, $attributes, $readAttributesOnly, $_SESSION['config']->get_searchLimit()); $filter, $attributes, $readAttributesOnly, $_SESSION['config']->get_searchLimit());
if (ldap_errno($_SESSION['ldap']->server()) == 4) { if (ldap_errno($_SESSION['ldap']->server()) == 4) {
logNewMessage(LOG_WARNING, 'LDAP size limit exeeded. Please increase the limit on your server.'); logNewMessage(LOG_WARNING, 'LDAP size limit exeeded. Please increase the limit on your server.');
@ -1461,4 +1467,31 @@ function validateReCAPTCHA($secretKey) {
return $responseJSON->{'success'} === true; return $responseJSON->{'success'} === true;
} }
class LAMException extends Exception {
private $title;
/**
* Constructor.
*
* @param string $title title
* @param string $message message (optional)
* @param Exception $cause (optional)
*/
public function __construct($title, $message = null, $cause = null) {
parent::__construct($message, null, $cause);
$this->title = $title;
}
/**
* Returns the message title.
*
* @return string title
*/
public function getTitle() {
return $this->title;
}
}
?> ?>

View File

@ -3,7 +3,7 @@
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2005 - 2014 Roland Gruber Copyright (C) 2005 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -34,7 +34,7 @@ $Id$
* @package types * @package types
*/ */
class baseType { class baseType {
/** label to create another account */ /** label to create another account */
public $LABEL_CREATE_ANOTHER_ACCOUNT; public $LABEL_CREATE_ANOTHER_ACCOUNT;
/** label to return to account list */ /** label to return to account list */
@ -47,7 +47,7 @@ class baseType {
$this->LABEL_CREATE_ANOTHER_ACCOUNT = _('Create another account'); $this->LABEL_CREATE_ANOTHER_ACCOUNT = _('Create another account');
$this->LABEL_BACK_TO_ACCOUNT_LIST = _('Back to account list'); $this->LABEL_BACK_TO_ACCOUNT_LIST = _('Back to account list');
} }
/** /**
* Returns the alias name of this account type. * Returns the alias name of this account type.
* This function must be overwritten by the child classes. * This function must be overwritten by the child classes.
@ -57,7 +57,7 @@ class baseType {
public function getAlias() { public function getAlias() {
return "baseType"; return "baseType";
} }
/** /**
* Returns the description of this account type. * Returns the description of this account type.
* This function must be overwritten by the child classes. * This function must be overwritten by the child classes.
@ -67,7 +67,7 @@ class baseType {
public function getDescription() { public function getDescription() {
return "base type"; return "base type";
} }
/** /**
* Returns the class name for the list object. * Returns the class name for the list object.
* *
@ -76,7 +76,7 @@ class baseType {
public function getListClassName() { public function getListClassName() {
return "lamList"; return "lamList";
} }
/** /**
* Returns the default attribute list for this account type. * Returns the default attribute list for this account type.
* This function must be overwritten by the child classes. * This function must be overwritten by the child classes.
@ -96,7 +96,7 @@ class baseType {
public function getListAttributeDescriptions() { public function getListAttributeDescriptions() {
return array(); return array();
} }
/** /**
* Returns if entries of this type may be created via file upload. * Returns if entries of this type may be created via file upload.
* *
@ -105,7 +105,7 @@ class baseType {
public function supportsFileUpload() { public function supportsFileUpload() {
return true; return true;
} }
/** /**
* Returns the the title text for the title bar on the new/edit page. * Returns the the title text for the title bar on the new/edit page.
* *
@ -128,72 +128,34 @@ class baseType {
public function getTitleBarSubtitle($container) { public function getTitleBarSubtitle($container) {
return null; return null;
} }
/** /**
* Returns a list of LDAP suffixes for this type. * Returns the LDAP filter to find the possible suffixes for this account type.
* *
* @return array sorted list of possible suffixes for this type. * @return string LDAP filter
*/ */
public function getSuffixList() { public function getSuffixFilter() {
if (isset($_SESSION["config"])) { return "(|(objectClass=organizationalunit)(objectClass=country)(objectClass=organization)(objectClass=krbRealmContainer)(objectClass=container))";
$suffix = $_SESSION["config"]->get_Suffix(get_class($this));
$connection = $_SESSION["ldap"]->server();
}
else {
$suffix = $_SESSION['selfServiceProfile']->LDAPSuffix;
$connection = $_SESSION['ldapHandle'];
}
$ret = array();
$filter = "(|(objectClass=organizationalunit)(objectClass=country)(objectClass=organization)(objectClass=krbRealmContainer)(objectClass=container))";
$sr = @ldap_search($connection, escapeDN($suffix),$filter , array('dn', 'objectClass'), 0, 0, 0, LDAP_DEREF_NEVER);
if ($sr) {
$units = ldap_get_entries($connection, $sr);
cleanLDAPResult($units);
// extract Dns
$count = sizeof($units);
for ($i = 0; $i < $count; $i++) {
if (in_array('container', $units[$i]['objectclass'])) {
// Active Directory fix, hide system containers
if (preg_match('/.*cn=system,dc=.+/i', $units[$i]['dn']) || preg_match('/.*CN=program data,dc=.+/i', $units[$i]['dn'])) {
continue;
}
}
$ret[] = $units[$i]['dn'];
}
}
// add root suffix if needed
$found = false;
for ($i = 0; $i < sizeof($ret); $i++) { // search suffix case-intensitive
if (strtolower($suffix) == strtolower($ret[$i])) {
$found = true;
break;
}
}
if (!$found) {
$ret[] = $suffix;
}
usort($ret, 'compareDN');
return $ret;
} }
/** /**
* This function is called after the edit page is processed and before the page content is generated. * This function is called after the edit page is processed and before the page content is generated.
* This can be used to run custom handlers after each page processing. * This can be used to run custom handlers after each page processing.
* *
* @param accountContainer $container account container * @param accountContainer $container account container
*/ */
public function runEditPagePostAction(&$container) { public function runEditPagePostAction(&$container) {
} }
/** /**
* Returns a list of configuration options. * Returns a list of configuration options.
* *
* The field names are used as keywords to load and save settings. * The field names are used as keywords to load and save settings.
* We recommend to use the type name as prefix for them (e.g. user_someSetting) to avoid naming conflicts. * We recommend to use the type name as prefix for them (e.g. user_someSetting) to avoid naming conflicts.
* *
* @return mixed htmlElement or array of htmlElement * @return mixed htmlElement or array of htmlElement
* *
* @see htmlElement * @see htmlElement
*/ */
public function get_configOptions() { public function get_configOptions() {
@ -212,7 +174,11 @@ class baseType {
public function check_configOptions(&$options) { public function check_configOptions(&$options) {
return array(); return array();
} }
public function supportsMultipleConfigs() {
return false;
}
} }
?> ?>

View File

@ -614,66 +614,82 @@ class LAMConfig {
$line = trim($line); // remove spaces at the beginning and end $line = trim($line); // remove spaces at the beginning and end
if (($line == "")||($line[0] == "#")) continue; // ignore comments and empty lines if (($line == "")||($line[0] == "#")) continue; // ignore comments and empty lines
// search keywords // search keywords
for ($i = 0; $i < sizeof($this->settings); $i++) { $parts = explode(': ', $line);
$keyword = $this->settings[$i]; $keyword = $parts[0];
$keylen = strlen($keyword); if (!in_array($keyword, $this->settings)) {
if (strtolower(substr($line, 0, $keylen + 2)) == strtolower($keyword . ": ")) { continue;
// module settings }
if (strtolower(substr($line, 0, $keylen + 2)) == "modules: ") { $startIndex = strlen($keyword) + 2;
$option = substr($line, $keylen + 2, strlen($line) - $keylen - 2); if (sizeof($parts) == 1) {
$pos = strpos($option, ":"); // empty global settings
$this->moduleSettings[substr($option, 0, $pos)] = explode(LAMConfig::LINE_SEPARATOR, substr($option, $pos + 2)); $this->$keyword = '';
} }
// type settings elseif (sizeof($parts) == 2) {
elseif (strtolower(substr($line, 0, $keylen + 2)) == "types: ") { // global setting with value
$option = substr($line, $keylen + 2, strlen($line) - $keylen - 2); $this->$keyword = substr($line, $startIndex);
$pos = strpos($option, ":"); }
$this->typeSettings[substr($option, 0, $pos)] = substr($option, $pos + 2); else {
} $subKeyword = $parts[1];
// tool settings $startIndex = $startIndex + strlen($subKeyword) + 2;
elseif (strtolower(substr($line, 0, $keylen + 2)) == "tools: ") { // module settings
$option = substr($line, $keylen + 2, strlen($line) - $keylen - 2); if ($keyword == 'modules') {
$pos = strpos($option, ":"); $option = substr($line, $startIndex);
$this->toolSettings[substr($option, 0, $pos)] = substr($option, $pos + 2); $this->moduleSettings[$subKeyword] = explode(LAMConfig::LINE_SEPARATOR, $option);
}
// job settings
elseif (strtolower(substr($line, 0, $keylen + 2)) == "jobs: ") {
$option = substr($line, $keylen + 2, strlen($line) - $keylen - 2);
$pos = strpos($option, ":");
$this->jobSettings[substr($option, 0, $pos)] = explode(LAMConfig::LINE_SEPARATOR, substr($option, $pos + 2));
}
// general settings
else {
$this->$keyword = substr($line, $keylen + 2, strlen($line) - $keylen - 2);
}
break;
} }
elseif (strtolower($line) == strtolower($keyword . ":")) { // type settings
// set empty options if ($keyword == 'types') {
$this->$keyword = ''; $option = substr($line, $startIndex);
$this->typeSettings[$subKeyword] = $option;
}
// tool settings
if ($keyword == 'tools') {
$option = substr($line, $startIndex);
$this->toolSettings[$subKeyword] = $option;
}
// job settings
if ($keyword == 'jobs') {
$option = substr($line, $startIndex);
$this->jobSettings[$subKeyword] = explode(LAMConfig::LINE_SEPARATOR, $option);
} }
} }
} }
fclose($file); fclose($file);
} }
// check types $this->removeInvalidTypes();
$this->removeInvalidModules();
return true;
}
/**
* Removes any non-existing types from the configuration.
*/
private function removeInvalidTypes() {
$allTypes = LAM\TYPES\getTypes(); $allTypes = LAM\TYPES\getTypes();
$activeTypes = $this->get_ActiveTypes(); $activeTypes = $this->get_ActiveTypes();
for ($i = 0; $i < sizeof($activeTypes); $i++) { for ($i = 0; $i < sizeof($activeTypes); $i++) {
if (!in_array($activeTypes[$i], $allTypes)) { if (!in_array(\LAM\TYPES\getScopeFromTypeId($activeTypes[$i]), $allTypes)) {
unset($activeTypes[$i]); unset($activeTypes[$i]);
} }
} }
$activeTypes = array_values($activeTypes); $activeTypes = array_values($activeTypes);
$this->set_ActiveTypes($activeTypes); $this->set_ActiveTypes($activeTypes);
// check modules }
$scopes = $this->get_ActiveTypes();
for ($s = 0; $s < sizeof($scopes); $s++) { /**
$scope = $scopes[$s]; * Removes any non-existing modules from the configuration.
$moduleVar = "modules_" . $scope; */
private function removeInvalidModules() {
$types = $this->get_ActiveTypes();
$availableByScope = array();
foreach ($types as $type) {
$scope = \LAM\TYPES\getScopeFromTypeId($type);
$moduleVar = "modules_" . $type;
if (isset($this->typeSettings[$moduleVar])){ if (isset($this->typeSettings[$moduleVar])){
$modules = explode(",", $this->typeSettings[$moduleVar]); $modules = explode(",", $this->typeSettings[$moduleVar]);
$available = getAvailableModules($scope); if (empty($availableByScope[$scope])) {
$availableByScope[$scope] = getAvailableModules($scope);
}
$available = $availableByScope[$scope];
// only return available modules // only return available modules
$ret = array(); $ret = array();
for ($i = 0; $i < sizeof($modules); $i++) { for ($i = 0; $i < sizeof($modules); $i++) {
@ -682,7 +698,6 @@ class LAMConfig {
$this->typeSettings[$moduleVar] = implode(",", $ret); $this->typeSettings[$moduleVar] = implode(",", $ret);
} }
} }
return true;
} }
/** Saves preferences to config file */ /** Saves preferences to config file */

View File

@ -1,4 +1,6 @@
<?php <?php
use LAM\TYPES\ConfiguredType;
/* /*
$Id$ $Id$
@ -103,7 +105,7 @@ class lamList {
/** /**
* Constructor * Constructor
* *
* @param string $type account type * @param LAM\TYPES\ConfiguredType $type account type
* @return lamList list object * @return lamList list object
*/ */
public function __construct($type) { public function __construct($type) {
@ -122,8 +124,8 @@ class lamList {
*/ */
private function listReadOptionsFromCookie() { private function listReadOptionsFromCookie() {
if (sizeof($this->configOptions) > 0) { if (sizeof($this->configOptions) > 0) {
if (isset($_COOKIE["ListOptions_" . $this->type])) { if (isset($_COOKIE["ListOptions_" . $this->type->getId()])) {
$cookieValue = $_COOKIE["ListOptions_" . $this->type]; $cookieValue = $_COOKIE["ListOptions_" . $this->type->getId()];
$valueParts = explode(";", $cookieValue); $valueParts = explode(";", $cookieValue);
$values = array(); $values = array();
for ($i = 0; $i < sizeof($valueParts); $i++) { for ($i = 0; $i < sizeof($valueParts); $i++) {
@ -172,7 +174,7 @@ class lamList {
// show form // show form
echo "<div class=\"ui-tabs-panel ui-widget-content ui-corner-bottom\">"; echo "<div class=\"ui-tabs-panel ui-widget-content ui-corner-bottom\">";
echo "<div id=\"listTabContentArea\">\n"; echo "<div id=\"listTabContentArea\">\n";
echo ("<form action=\"list.php?type=" . $this->type . "&amp;norefresh=true\" method=\"post\">\n"); echo ("<form action=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true\" method=\"post\">\n");
// draw account list if accounts were found // draw account list if accounts were found
if (sizeof($this->entries) > 0) { if (sizeof($this->entries) > 0) {
// buttons // buttons
@ -289,12 +291,12 @@ class lamList {
if ($count > $this->maxPageEntries) { if ($count > $this->maxPageEntries) {
echo("<td class=\"activepage\" align=\"right\">"); echo("<td class=\"activepage\" align=\"right\">");
if ($this->page != 1) { if ($this->page != 1) {
echo("<a title=\"" . _('Jump to first page') . "\" href=\"list.php?type=" . $this->type . "&amp;norefresh=true&amp;page=1" . echo("<a title=\"" . _('Jump to first page') . "\" href=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true&amp;page=1" .
"&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" . "&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" .
"<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-first.png\"></a>\n"); "<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-first.png\"></a>\n");
} }
if ($this->page > 11) { if ($this->page > 11) {
echo("<a title=\"" . _('Jump 10 pages backward') . "\" href=\"list.php?type=" . $this->type . "&amp;norefresh=true&amp;page=" . ($this->page - 10) . echo("<a title=\"" . _('Jump 10 pages backward') . "\" href=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true&amp;page=" . ($this->page - 10) .
"&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" . "&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" .
"<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-previous.png\"></a>\n"); "<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-previous.png\"></a>\n");
} }
@ -307,24 +309,24 @@ class lamList {
continue; continue;
} }
if ($i == $this->page - 1) { if ($i == $this->page - 1) {
$url = "list.php?type=" . $this->type . "&amp;norefresh=true" . $url = "list.php?type=" . $this->type->getId() . "&amp;norefresh=true" .
"&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter; "&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter;
echo '<input type="number" class="listPageInput" id="listNavPage" name="listNavPage"' echo '<input type="number" class="listPageInput" id="listNavPage" name="listNavPage"'
. ' value="' . ($i + 1) . '" min="1" max="' . $pageCount . '"' . ' value="' . ($i + 1) . '" min="1" max="' . $pageCount . '"'
. ' onkeypress="listPageNumberKeyPress(\'' . $url . '\', event);">'; . ' onkeypress="listPageNumberKeyPress(\'' . $url . '\', event);">';
} }
else { else {
echo "&nbsp;<a href=\"list.php?type=" . $this->type . "&amp;norefresh=true&amp;page=" . ($i + 1) . echo "&nbsp;<a href=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true&amp;page=" . ($i + 1) .
"&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" . ($i + 1) . "</a>\n"; "&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" . ($i + 1) . "</a>\n";
} }
} }
if ($this->page < ($pageCount - 10)) { if ($this->page < ($pageCount - 10)) {
echo("<a title=\"" . _('Jump 10 pages forward') . "\" href=\"list.php?type=" . $this->type . "&amp;norefresh=true&amp;page=" . ($this->page + 10) . echo("<a title=\"" . _('Jump 10 pages forward') . "\" href=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true&amp;page=" . ($this->page + 10) .
"&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" . "&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" .
"<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-next.png\"></a>\n"); "<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-next.png\"></a>\n");
} }
if ($this->page < $pageCount) { if ($this->page < $pageCount) {
echo("<a title=\"" . _('Jump to last page') . "\" href=\"list.php?type=" . $this->type . "&amp;norefresh=true&amp;page=" . $pageCount . echo("<a title=\"" . _('Jump to last page') . "\" href=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true&amp;page=" . $pageCount .
"&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" . "&amp;sort=" . $this->sortColumn . "&amp;sortdirection=" . $this->sortDirection . $filter . "\">" .
"<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-last.png\"></a>\n"); "<img height=16 width=16 class=\"align-middle\" alt=\"\" src=\"../../graphics/go-last.png\"></a>\n");
} }
@ -352,8 +354,8 @@ class lamList {
protected function listPrintTableHeader() { protected function listPrintTableHeader() {
$filter = $this->getFilterAsTextForURL(); $filter = $this->getFilterAsTextForURL();
// print table header // print table header
echo "<table id=\"accountTable\" frame=\"box\" rules=\"none\" class=\"" . $this->type . "-border collapse accountlist ui-corner-all\" width=\"100%\"><thead>\n"; echo "<table id=\"accountTable\" frame=\"box\" rules=\"none\" class=\"" . $this->type->getScope() . "-border collapse accountlist ui-corner-all\" width=\"100%\"><thead>\n";
echo "<tr class=\"" . $this->type . "-dark\">\n"; echo "<tr class=\"" . $this->type->getScope() . "-dark\">\n";
echo "<th width=22 height=34><a href=\"#\" onClick=\"list_switchAccountSelection();\"><img height=16 width=16 src=\"../../graphics/selectDown.png\" alt=\"select all\"></a></th>\n"; echo "<th width=22 height=34><a href=\"#\" onClick=\"list_switchAccountSelection();\"><img height=16 width=16 src=\"../../graphics/selectDown.png\" alt=\"select all\"></a></th>\n";
echo "<td>&nbsp;<a href=\"#\" onClick=\"list_switchAccountSelection();\">" . echo "<td>&nbsp;<a href=\"#\" onClick=\"list_switchAccountSelection();\">" .
"<font color=\"black\"><small>" . _("Select all") . "</small></font></a></td>\n"; "<font color=\"black\"><small>" . _("Select all") . "</small></font></a></td>\n";
@ -364,17 +366,17 @@ class lamList {
if ($this->sortDirection < 0) { if ($this->sortDirection < 0) {
$sortImage = "sort_desc.png"; $sortImage = "sort_desc.png";
} }
echo "<th align=\"left\"><a href=\"list.php?type=" . $this->type . "&amp;". echo "<th align=\"left\"><a href=\"list.php?type=" . $this->type->getId() . "&amp;".
"sort=" . strtolower($this->attrArray[$k]) . $filter . "&amp;norefresh=y" . "\">" . $this->descArray[$k] . "sort=" . strtolower($this->attrArray[$k]) . $filter . "&amp;norefresh=y" . "\">" . $this->descArray[$k] .
"&nbsp;<img height=16 width=16 style=\"vertical-align: middle;\" src=\"../../graphics/$sortImage\" alt=\"sort direction\"></a></th>\n"; "&nbsp;<img height=16 width=16 style=\"vertical-align: middle;\" src=\"../../graphics/$sortImage\" alt=\"sort direction\"></a></th>\n";
} }
else echo "<th align=\"left\"><a href=\"list.php?type=" . $this->type . "&amp;". else echo "<th align=\"left\"><a href=\"list.php?type=" . $this->type->getId() . "&amp;".
"sort=" . strtolower($this->attrArray[$k]) . $filter . "&amp;norefresh=y" . "\">" . $this->descArray[$k] . "</a></th>\n"; "sort=" . strtolower($this->attrArray[$k]) . $filter . "&amp;norefresh=y" . "\">" . $this->descArray[$k] . "</a></th>\n";
} }
echo "</tr>\n"; echo "</tr>\n";
// print filter row // print filter row
echo "<tr align=\"center\" class=\"" . $this->type . "-bright\">\n"; echo "<tr align=\"center\" class=\"" . $this->type->getScope() . "-bright\">\n";
echo "<td width=22 height=34>"; echo "<td width=22 height=34>";
printHelpLink(getHelp('', '250'), '250'); printHelpLink(getHelp('', '250'), '250');
echo "</td>\n"; echo "</td>\n";
@ -389,7 +391,7 @@ class lamList {
$clearFilterButton->setTitle(_('Clear filter')); $clearFilterButton->setTitle(_('Clear filter'));
$filterGroup->addElement($clearFilterButton); $filterGroup->addElement($clearFilterButton);
} }
parseHtml(null, $filterGroup, array(), false, $this->tabindex, $this->type); parseHtml(null, $filterGroup, array(), false, $this->tabindex, $this->type->getScope());
echo "</td>\n"; echo "</td>\n";
// print input boxes for filters // print input boxes for filters
for ($k = 0; $k < sizeof($this->descArray); $k++) { for ($k = 0; $k < sizeof($this->descArray); $k++) {
@ -416,10 +418,10 @@ class lamList {
} }
} }
$filterInput = new htmlInputField('filter' . strtolower($attrName), $value); $filterInput = new htmlInputField('filter' . strtolower($attrName), $value);
$filterInput->setCSSClasses(array($this->type . '-dark')); $filterInput->setCSSClasses(array($this->type->getScope() . '-dark'));
$filterInput->setFieldSize('15'); $filterInput->setFieldSize('15');
$filterInput->setOnKeyPress("SubmitForm('apply_filter', event);"); $filterInput->setOnKeyPress("SubmitForm('apply_filter', event);");
parseHtml(null, $filterInput, array(), false, $this->tabindex, $this->type); parseHtml(null, $filterInput, array(), false, $this->tabindex, $this->type->getScope());
} }
/** /**
@ -459,14 +461,14 @@ class lamList {
$index = $sortMapping[$i]; $index = $sortMapping[$i];
$rowID = base64_encode($info[$index]['dn']); $rowID = base64_encode($info[$index]['dn']);
if ((($i - $table_begin) % 2) == 1) { if ((($i - $table_begin) % 2) == 1) {
$classes = ' ' . $this->type . '-bright'; $classes = ' ' . $this->type->getScope() . '-bright';
} }
else { else {
$classes = ' ' . $this->type . '-dark'; $classes = ' ' . $this->type->getScope() . '-dark';
} }
echo("<tr class=\"$classes\"" . echo("<tr class=\"$classes\"" .
" onClick=\"list_click('" . $rowID . "')\"\n" . " onClick=\"list_click('" . $rowID . "')\"\n" .
" onDblClick=\"top.location.href='../account/edit.php?type=" . $this->type . "&amp;DN=" . rawurlencode($info[$index]['dn']) . "'\">\n"); " onDblClick=\"top.location.href='../account/edit.php?type=" . $this->type->getId() . "&amp;DN=" . rawurlencode($info[$index]['dn']) . "'\">\n");
echo " <td align=\"center\"><input class=\"accountBoxUnchecked\" onClick=\"list_click('" . $rowID . "')\"" . echo " <td align=\"center\"><input class=\"accountBoxUnchecked\" onClick=\"list_click('" . $rowID . "')\"" .
" type=\"checkbox\" name=\"" . $rowID . "\"></td>\n"; " type=\"checkbox\" name=\"" . $rowID . "\"></td>\n";
$this->listPrintToolLinks($info[$index], $rowID); $this->listPrintToolLinks($info[$index], $rowID);
@ -480,7 +482,7 @@ class lamList {
} }
// display select all link // display select all link
$colspan = sizeof($this->attrArray) + 1; $colspan = sizeof($this->attrArray) + 1;
echo "<tr class=\"" . $this->type . "-bright\">\n"; echo "<tr class=\"" . $this->type->getScope() . "-bright\">\n";
echo "<td align=\"center\"><a href=\"#\" onClick=\"list_switchAccountSelection();\"><img height=16 width=16 src=\"../../graphics/select.png\" alt=\"select all\"></a></td>\n"; echo "<td align=\"center\"><a href=\"#\" onClick=\"list_switchAccountSelection();\"><img height=16 width=16 src=\"../../graphics/select.png\" alt=\"select all\"></a></td>\n";
echo "<td colspan=$colspan>&nbsp;<a href=\"#\" onClick=\"list_switchAccountSelection();\">" . echo "<td colspan=$colspan>&nbsp;<a href=\"#\" onClick=\"list_switchAccountSelection();\">" .
"<font color=\"black\"><small>" . _("Select all") . "</small></font></a></td>\n"; "<font color=\"black\"><small>" . _("Select all") . "</small></font></a></td>\n";
@ -499,13 +501,13 @@ class lamList {
$toolCount = 0; $toolCount = 0;
$group = new htmlGroup(); $group = new htmlGroup();
// edit link // edit link
$editLink = new htmlLink('', "../account/edit.php?type=" . $this->type . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/edit.png'); $editLink = new htmlLink('', "../account/edit.php?type=" . $this->type->getId() . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/edit.png');
$editLink->setTitle(_("Edit")); $editLink->setTitle(_("Edit"));
$group->addElement($editLink); $group->addElement($editLink);
$toolCount++; $toolCount++;
// delete link // delete link
if (checkIfWriteAccessIsAllowed($this->type) && checkIfDeleteEntriesIsAllowed($this->type)) { if (checkIfWriteAccessIsAllowed($this->type->getId()) && checkIfDeleteEntriesIsAllowed($this->type->getId())) {
$deleteLink = new htmlLink('', "deletelink.php?type=" . $this->type . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/delete.png'); $deleteLink = new htmlLink('', "deletelink.php?type=" . $this->type->getId() . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/delete.png');
$deleteLink->setTitle(_("Delete")); $deleteLink->setTitle(_("Delete"));
$group->addElement($deleteLink); $group->addElement($deleteLink);
$toolCount++; $toolCount++;
@ -518,14 +520,14 @@ class lamList {
// additional tools // additional tools
$tools = $this->getAdditionalTools(); $tools = $this->getAdditionalTools();
for ($i = 0; $i < sizeof($tools); $i++) { for ($i = 0; $i < sizeof($tools); $i++) {
$toolLink = new htmlLink('', $tools[$i]->getLinkTarget() . "?type=" . $this->type . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/' . $tools[$i]->getImage()); $toolLink = new htmlLink('', $tools[$i]->getLinkTarget() . "?type=" . $this->type->getId() . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/' . $tools[$i]->getImage());
$toolLink->setTitle($tools[$i]->getName()); $toolLink->setTitle($tools[$i]->getName());
$group->addElement($toolLink); $group->addElement($toolLink);
$toolCount++; $toolCount++;
} }
$width = ($toolCount * 20) + 20; $width = ($toolCount * 20) + 20;
echo "<td align='center' style=\"white-space: nowrap; width: ${width}px;\">"; echo "<td align='center' style=\"white-space: nowrap; width: ${width}px;\">";
parseHtml(null, $group, array(), false, $this->tabindex, $this->type); parseHtml(null, $group, array(), false, $this->tabindex, $this->type->getScope());
echo "</td>\n"; echo "</td>\n";
} }
@ -560,16 +562,16 @@ class lamList {
} }
// check if button was pressed and if we have to add/delete an account or call file upload // check if button was pressed and if we have to add/delete an account or call file upload
if (isset($_POST['new']) || isset($_POST['del']) || isset($_POST['fileUpload'])){ if (isset($_POST['new']) || isset($_POST['del']) || isset($_POST['fileUpload'])){
if (!checkIfWriteAccessIsAllowed($this->type)) { if (!checkIfWriteAccessIsAllowed($this->type->getId())) {
die(); die();
} }
// add new account // add new account
if (isset($_POST['new']) && checkIfNewEntriesAreAllowed($this->type)){ if (isset($_POST['new']) && checkIfNewEntriesAreAllowed($this->type->getId())){
metaRefresh("../account/edit.php?type=" . $this->type . "&amp;suffix=" . $this->suffix); metaRefresh("../account/edit.php?type=" . $this->type->getId() . "&amp;suffix=" . $this->suffix);
exit; exit;
} }
// delete account(s) // delete account(s)
elseif (isset($_POST['del']) && checkIfDeleteEntriesIsAllowed($this->type)){ elseif (isset($_POST['del']) && checkIfDeleteEntriesIsAllowed($this->type->getId())){
// search for checkboxes // search for checkboxes
$accounts = array_keys($_POST, "on"); $accounts = array_keys($_POST, "on");
// build DN list // build DN list
@ -578,13 +580,13 @@ class lamList {
$_SESSION['delete_dn'][] = base64_decode($accounts[$i]); $_SESSION['delete_dn'][] = base64_decode($accounts[$i]);
} }
if (sizeof($accounts) > 0) { if (sizeof($accounts) > 0) {
metaRefresh("../delete.php?type=" . $this->type); metaRefresh("../delete.php?type=" . $this->type->getId());
exit; exit;
} }
} }
// file upload // file upload
elseif (isset($_POST['fileUpload']) && checkIfNewEntriesAreAllowed($this->type)){ elseif (isset($_POST['fileUpload']) && checkIfNewEntriesAreAllowed($this->type->getId())){
metaRefresh("../upload/masscreate.php?type=" . $this->type); metaRefresh("../upload/masscreate.php?type=" . $this->type->getId());
exit; exit;
} }
} }
@ -662,7 +664,7 @@ class lamList {
$cookieValue .= $this->configOptions[$i]->getID() . "=" . $this->configOptions[$i]->getValue() . ';'; $cookieValue .= $this->configOptions[$i]->getID() . "=" . $this->configOptions[$i]->getValue() . ';';
} }
// save options as cookie for one year // save options as cookie for one year
setcookie("ListOptions_" . $this->type, $cookieValue, time()+60*60*24*365, "/", null, null, true); setcookie("ListOptions_" . $this->type->getId(), $cookieValue, time()+60*60*24*365, "/", null, null, true);
// notify subclasses // notify subclasses
$this->listConfigurationChanged(); $this->listConfigurationChanged();
} }
@ -688,17 +690,17 @@ class lamList {
$selAccounts[] = $id; $selAccounts[] = $id;
} }
// get possible PDF structures // get possible PDF structures
$pdf_structures = getPDFStructureDefinitions($this->type); $pdf_structures = \LAM\PDF\getPDFStructures($this->type->getId());
$this->listPrintHeader(); $this->listPrintHeader();
echo "<div class=\"ui-tabs-nav " . $this->type . "-bright\">"; echo "<div class=\"ui-tabs-nav " . $this->type->getScope() . "-bright\">";
echo "<div class=\"smallPaddingContent\">\n"; echo "<div class=\"smallPaddingContent\">\n";
$refresh = '&amp;norefresh=true'; $refresh = '&amp;norefresh=true';
if (isset($_GET['refresh']) && ($_GET['refresh'] == 'true')) { if (isset($_GET['refresh']) && ($_GET['refresh'] == 'true')) {
$refresh = '&amp;refresh=true'; $refresh = '&amp;refresh=true';
} }
echo "<form action=\"list.php?type=" . $this->type . $refresh . "\" method=\"post\">\n"; echo "<form action=\"list.php?type=" . $this->type->getId() . $refresh . "\" method=\"post\">\n";
$container = new htmlTable(); $container = new htmlTable();
$container->addElement(new htmlSubTitle(_('Create PDF file')), true); $container->addElement(new htmlSubTitle(_('Create PDF file')), true);
@ -735,7 +737,7 @@ class lamList {
$container->addElement(new htmlHiddenInput('clickedAccount', $id)); $container->addElement(new htmlHiddenInput('clickedAccount', $id));
addSecurityTokenToMetaHTML($container); addSecurityTokenToMetaHTML($container);
parseHtml(null, $container, array(), false, $this->tabindex, $this->type); parseHtml(null, $container, array(), false, $this->tabindex, $this->type->getScope());
$this->listPrintFooter(); $this->listPrintFooter();
} }
@ -753,7 +755,7 @@ class lamList {
$suffixList[getAbstractDN($this->possibleSuffixes[$i])] = $this->possibleSuffixes[$i]; $suffixList[getAbstractDN($this->possibleSuffixes[$i])] = $this->possibleSuffixes[$i];
} }
$suffixSelect = new htmlSelect('suffix', $suffixList, array($this->suffix)); $suffixSelect = new htmlSelect('suffix', $suffixList, array($this->suffix));
$suffixSelect->setOnchangeEvent("listOUchanged('" . $this->type . "', this)"); $suffixSelect->setOnchangeEvent("listOUchanged('" . $this->type->getId() . "', this)");
$suffixSelect->setRightToLeftTextDirection(true); $suffixSelect->setRightToLeftTextDirection(true);
$suffixSelect->setSortElements(false); $suffixSelect->setSortElements(false);
$suffixSelect->setHasDescriptiveElements(true); $suffixSelect->setHasDescriptiveElements(true);
@ -774,23 +776,22 @@ class lamList {
$left = new htmlGroup(); $left = new htmlGroup();
// button part // button part
$left->alignment = htmlElement::ALIGN_LEFT; $left->alignment = htmlElement::ALIGN_LEFT;
if (checkIfWriteAccessIsAllowed($this->type)) { if (checkIfWriteAccessIsAllowed($this->type->getId())) {
// add button // add button
if (checkIfNewEntriesAreAllowed($this->type)) { if (checkIfNewEntriesAreAllowed($this->type->getId())) {
$newButton = new htmlButton('new', $this->labels['newEntry']); $newButton = new htmlButton('new', $this->labels['newEntry']);
$newButton->setIconClass('createButton'); $newButton->setIconClass('createButton');
$left->addElement($newButton); $left->addElement($newButton);
} }
// delete button // delete button
if (!$createOnly && checkIfDeleteEntriesIsAllowed($this->type)) { if (!$createOnly && checkIfDeleteEntriesIsAllowed($this->type->getId())) {
$left->addElement(new htmlSpacer('1px', null)); $left->addElement(new htmlSpacer('1px', null));
$delButton = new htmlButton('del', $this->labels['deleteEntry']); $delButton = new htmlButton('del', $this->labels['deleteEntry']);
$delButton->setIconClass('deleteButton'); $delButton->setIconClass('deleteButton');
$left->addElement($delButton); $left->addElement($delButton);
} }
$type = new $this->type();
$toolSettings = $_SESSION['config']->getToolSettings(); $toolSettings = $_SESSION['config']->getToolSettings();
if ($type->supportsFileUpload() && checkIfNewEntriesAreAllowed($this->type) if ($this->type->getBaseType()->supportsFileUpload() && checkIfNewEntriesAreAllowed($this->type->getId())
&& !(isset($toolSettings['tool_hide_toolFileUpload']) && ($toolSettings['tool_hide_toolFileUpload'] == 'true'))) { && !(isset($toolSettings['tool_hide_toolFileUpload']) && ($toolSettings['tool_hide_toolFileUpload'] == 'true'))) {
$left->addElement(new htmlSpacer('20px', null)); $left->addElement(new htmlSpacer('20px', null));
$uploadButton = new htmlButton('fileUpload', _('File upload')); $uploadButton = new htmlButton('fileUpload', _('File upload'));
@ -815,7 +816,7 @@ class lamList {
$this->addExtraInputElementsToTopArea($left, $right); $this->addExtraInputElementsToTopArea($left, $right);
$table->addElement($left); $table->addElement($left);
$table->addElement($right); $table->addElement($right);
parseHtml(null, $table, array(), false, $this->tabindex, $this->type); parseHtml(null, $table, array(), false, $this->tabindex, $this->type->getScope());
} }
/** /**
@ -844,8 +845,8 @@ class lamList {
</form></div></div> </form></div></div>
<script type="text/javascript"> <script type="text/javascript">
jQuery(document).ready(function() { jQuery(document).ready(function() {
jQuery('#tab_<?php echo $this->type; ?>').addClass('ui-tabs-active'); jQuery('#tab_<?php echo $this->type->getId(); ?>').addClass('ui-tabs-active');
jQuery('#tab_<?php echo $this->type; ?>').addClass('ui-state-active'); jQuery('#tab_<?php echo $this->type->getId(); ?>').addClass('ui-state-active');
window.onload = listResizeITabContentDiv; window.onload = listResizeITabContentDiv;
window.onresize = listResizeITabContentDiv; window.onresize = listResizeITabContentDiv;
jQuery('#filterButton').button(); jQuery('#filterButton').button();
@ -862,33 +863,10 @@ class lamList {
* @return array attribute list * @return array attribute list
*/ */
protected function listGetAttributeDescriptionList() { protected function listGetAttributeDescriptionList() {
$attrs = $this->type->getAttributes();
$ret = array(); $ret = array();
$attr_string = $_SESSION["config"]->get_listAttributes($this->type); foreach ($attrs as $attr) {
$temp_array = explode(";", $attr_string); $ret[$attr->getAttributeName()] = $attr->getAlias();
$hash_table = LAM\TYPES\getListAttributeDescriptions($this->type);
$hash_table = array_change_key_case($hash_table, CASE_LOWER);
// generate column attributes and descriptions
for ($i = 0; $i < sizeof($temp_array); $i++) {
// if value is predifined, look up description in hash_table
if (substr($temp_array[$i],0,1) == "#") {
$attr = strtolower(substr($temp_array[$i],1));
if (isset($hash_table[$attr])) {
$ret[$attr] = $hash_table[$attr];
}
else {
$ret[$attr] = $attr;
}
}
// if not predefined, the attribute is seperated by a ":" from description
else {
$attr = explode(":", $temp_array[$i]);
if (isset($attr[1])) {
$ret[$attr[0]] = $attr[1];
}
else {
$ret[$attr[0]] = $attr[0];
}
}
} }
return $ret; return $ret;
} }
@ -932,9 +910,18 @@ class lamList {
$this->sortDirection = $_GET['sortdirection']; $this->sortDirection = $_GET['sortdirection'];
} }
// check search suffix // check search suffix
if (isset($_POST['suffix'])) $this->suffix = $_POST['suffix']; // new suffix selected via combobox if (isset($_POST['suffix'])) {
elseif (isset($_GET['suffix'])) $this->suffix = $_GET['suffix']; // new suffix selected via combobox // new suffix selected via combobox
elseif (!$this->suffix) $this->suffix = $_SESSION["config"]->get_Suffix($this->type); // default suffix $this->suffix = $_POST['suffix'];
}
elseif (isset($_GET['suffix'])) {
// new suffix selected via combobox
$this->suffix = $_GET['suffix'];
}
elseif (!$this->suffix) {
// default suffix
$this->suffix = $this->type->getSuffix();
}
// check if LDAP data should be refreshed // check if LDAP data should be refreshed
$this->refresh = true; $this->refresh = true;
if (isset($_GET['norefresh'])) $this->refresh = false; if (isset($_GET['norefresh'])) $this->refresh = false;
@ -949,10 +936,10 @@ class lamList {
protected function listRefreshData() { protected function listRefreshData() {
// check suffix // check suffix
if (!$this->suffix) { if (!$this->suffix) {
$this->suffix = $_SESSION["config"]->get_Suffix($this->type); // default suffix $this->suffix = $this->type->getSuffix(); // default suffix
} }
// configure search filter // configure search filter
$module_filter = get_ldap_filter($this->type); // basic filter is provided by modules $module_filter = get_ldap_filter($this->type->getId()); // basic filter is provided by modules
$filter = "(&" . $module_filter . $this->buildLDAPAttributeFilter() . ")"; $filter = "(&" . $module_filter . $this->buildLDAPAttributeFilter() . ")";
$attrs = $this->attrArray; $attrs = $this->attrArray;
// remove virtual attributes from list // remove virtual attributes from list
@ -975,8 +962,7 @@ class lamList {
call_user_func_array('StatusMessage', $lastError); call_user_func_array('StatusMessage', $lastError);
} }
// generate list of possible suffixes // generate list of possible suffixes
$typeObj = new $this->type(); $this->possibleSuffixes = $this->type->getSuffixList();
$this->possibleSuffixes = $typeObj->getSuffixList();
} }
/** /**
@ -1039,7 +1025,7 @@ class lamList {
*/ */
protected function listPrintConfigurationPage() { protected function listPrintConfigurationPage() {
echo "<div id=\"settingsDialog\" class=\"hidden\">\n"; echo "<div id=\"settingsDialog\" class=\"hidden\">\n";
echo "<form id=\"settingsDialogForm\" action=\"list.php?type=" . $this->type . "&amp;norefresh=true\" method=\"post\">\n"; echo "<form id=\"settingsDialogForm\" action=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true\" method=\"post\">\n";
echo '<table width="100%"><tr><td>'; echo '<table width="100%"><tr><td>';
$configContainer = new htmlTable(); $configContainer = new htmlTable();
@ -1049,7 +1035,7 @@ class lamList {
$configContainer->addElement(new htmlHiddenInput('saveConfigOptions', 'ok')); $configContainer->addElement(new htmlHiddenInput('saveConfigOptions', 'ok'));
addSecurityTokenToMetaHTML($configContainer); addSecurityTokenToMetaHTML($configContainer);
parseHtml('', $configContainer, array(), false, $this->tabindex, $this->type); parseHtml('', $configContainer, array(), false, $this->tabindex, $this->type->getScope());
echo "</td></tr></table>\n"; echo "</td></tr></table>\n";
echo '</form>'; echo '</form>';

View File

@ -1,4 +1,7 @@
<?php <?php
use LAM\TYPES\ConfiguredType;
use function LAM\TYPES\getScopeFromTypeId;
/* /*
$Id$ $Id$
@ -88,18 +91,24 @@ function is_base_module($name, $scope) {
/** /**
* Returns the LDAP filter used by the account lists * Returns the LDAP filter used by the account lists
* *
* @param string $scope the account type ("user", "group", "host") * @param string $typeId the account type ("user", "group", "host")
* @return string LDAP filter * @return string LDAP filter
*/ */
function get_ldap_filter($scope) { function get_ldap_filter($typeId) {
$mods = $_SESSION['config']->get_AccountModules($scope); $typeManager = new \LAM\TYPES\TypeManager();
$filters = array(); $type = $typeManager->getConfiguredType($typeId);
$mods = $_SESSION['config']->get_AccountModules($typeId);
$filters = array('or' => array(), 'and' => array());
$orFilter = ''; $orFilter = '';
for ($i = 0; $i < sizeof($mods); $i++) { for ($i = 0; $i < sizeof($mods); $i++) {
$module = moduleCache::getModule($mods[$i], $scope); $module = moduleCache::getModule($mods[$i], $type->getScope());
$modinfo = $module->get_ldap_filter(); $modinfo = $module->get_ldap_filter();
if (isset($modinfo['or'])) $filters['or'][] = $modinfo['or']; if (isset($modinfo['or'])) {
if (isset($modinfo['and'])) $filters['and'][] = $modinfo['and']; $filters['or'][] = $modinfo['or'];
}
if (isset($modinfo['and'])) {
$filters['and'][] = $modinfo['and'];
}
} }
// build OR filter // build OR filter
if (sizeof($filters['or']) == 1) { if (sizeof($filters['or']) == 1) {
@ -109,15 +118,17 @@ function get_ldap_filter($scope) {
$orFilter = "(|" . implode("", $filters['or']) . ")"; $orFilter = "(|" . implode("", $filters['or']) . ")";
} }
// add built OR filter to AND filters // add built OR filter to AND filters
if ($orFilter != '') $filters['and'][] = $orFilter; if (!empty($orFilter)) {
$filters['and'][] = $orFilter;
}
// add type filter // add type filter
$typeSettings = $_SESSION['config']->get_typeSettings(); $typeSettings = $_SESSION['config']->get_typeSettings();
if (isset($typeSettings['filter_' . $scope]) && ($typeSettings['filter_' . $scope] != '')) { if (isset($typeSettings['filter_' . $typeId]) && ($typeSettings['filter_' . $typeId] != '')) {
if (strpos($typeSettings['filter_' . $scope], '(') === 0) { if (strpos($typeSettings['filter_' . $typeId], '(') === 0) {
$filters['and'][] = $typeSettings['filter_' . $scope]; $filters['and'][] = $typeSettings['filter_' . $typeId];
} }
else { else {
$filters['and'][] = '(' . $typeSettings['filter_' . $scope] . ')'; $filters['and'][] = '(' . $typeSettings['filter_' . $typeId] . ')';
} }
} }
// collapse AND filters // collapse AND filters
@ -138,12 +149,12 @@ function get_ldap_filter($scope) {
* *
* The list is already sorted by the priority given by the nodules. * The list is already sorted by the priority given by the nodules.
* *
* @param string $scope account type (user, group, host) * @param string $typeId account type (user, group, host)
* @param array $selectedModules return only RDN attributes of these modules * @param array $selectedModules return only RDN attributes of these modules
* @return array list of LDAP attributes * @return array list of LDAP attributes
*/ */
function getRDNAttributes($scope, $selectedModules=null) { function getRDNAttributes($typeId, $selectedModules=null) {
$mods = $_SESSION['config']->get_AccountModules($scope); $mods = $_SESSION['config']->get_AccountModules($typeId);
if ($selectedModules != null) { if ($selectedModules != null) {
$mods = $selectedModules; $mods = $selectedModules;
} }
@ -153,7 +164,7 @@ function getRDNAttributes($scope, $selectedModules=null) {
$attrs_high = array(); $attrs_high = array();
for ($i = 0; $i < sizeof($mods); $i++) { for ($i = 0; $i < sizeof($mods); $i++) {
// get list of attributes // get list of attributes
$module = moduleCache::getModule($mods[$i], $scope); $module = moduleCache::getModule($mods[$i], \LAM\TYPES\getScopeFromTypeId($typeId));
$attrs = $module->get_RDNAttributes(); $attrs = $module->get_RDNAttributes();
$keys = array_keys($attrs); $keys = array_keys($attrs);
// sort attributes // sort attributes
@ -391,14 +402,14 @@ function getHelp($module,$helpID,$scope='') {
/** /**
* Returns a list of available PDF entries. * Returns a list of available PDF entries.
* *
* @param string $scope account type (user, group, host) * @param string $typeId account type (user, group, host)
* @return array PDF entries (field ID => field label) * @return array PDF entries (field ID => field label)
*/ */
function getAvailablePDFFields($scope) { function getAvailablePDFFields($typeId) {
$mods = $_SESSION['config']->get_AccountModules($scope); $mods = $_SESSION['config']->get_AccountModules($typeId);
$return = array(); $return = array();
for ($i = 0; $i < sizeof($mods); $i++) { for ($i = 0; $i < sizeof($mods); $i++) {
$module = moduleCache::getModule($mods[$i], $scope); $module = moduleCache::getModule($mods[$i], getScopeFromTypeId($typeId));
$fields = $module->get_pdfFields(); $fields = $module->get_pdfFields();
$return[$mods[$i]] = array(); $return[$mods[$i]] = array();
if (is_array($fields)) { if (is_array($fields)) {
@ -593,14 +604,17 @@ function doUploadPostActions($scope, &$data, $ids, $failed, $selectedModules, &$
*/ */
function getRequiredExtensions() { function getRequiredExtensions() {
$extList = array(); $extList = array();
$scopes = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
for ($i = 0; $i < sizeof($scopes); $i++) { $types = $typeManager->getConfiguredTypes();
$mods = $_SESSION['config']->get_AccountModules($scopes[$i]); foreach ($types as $type) {
$mods = $_SESSION['config']->get_AccountModules($type->getId());
for ($m = 0; $m < sizeof($mods); $m++) { for ($m = 0; $m < sizeof($mods); $m++) {
$module = moduleCache::getModule($mods[$m], $scopes[$i]); $module = moduleCache::getModule($mods[$m], $type->getScope());
$ext = $module->getRequiredExtensions(); $ext = $module->getRequiredExtensions();
for ($e = 0; $e < sizeof($ext); $e++) { for ($e = 0; $e < sizeof($ext); $e++) {
if (!in_array($ext[$e], $extList)) $extList[] = $ext[$e]; if (!in_array($ext[$e], $extList)) {
$extList[] = $ext[$e];
}
} }
} }
} }
@ -688,17 +702,12 @@ class accountContainer {
/** /**
* Constructor * Constructor
* *
* @param string $type account type * @param ConfiguredType $type account type
* @param string $base key in $_SESSION where this object is saved * @param string $base key in $_SESSION where this object is saved
* @param integer $randomID random ID to avoid parallel editing (default: null) * @param integer $randomID random ID to avoid parallel editing (default: null)
*/ */
function __construct($type, $base, $randomID = null) { function __construct($type, $base, $randomID = null) {
/* Set the type of account. Valid if (!($type instanceof ConfiguredType)) trigger_error('Argument of accountContainer must be ConfiguredType.', E_USER_ERROR);
* types are: user, group, host
*/
// Check input variable
if (!is_string($type)) trigger_error('Argument of accountContainer must be string.', E_USER_ERROR);
if (!is_string($base)) trigger_error('Argument of accountContainer must be string.', E_USER_ERROR); if (!is_string($base)) trigger_error('Argument of accountContainer must be string.', E_USER_ERROR);
$this->type = $type; $this->type = $type;
$this->base = $base; $this->base = $base;
@ -800,11 +809,11 @@ class accountContainer {
/** /**
* Returns the accout type of this object (e.g. user, group, host). * Returns the accout type of this object (e.g. user, group, host).
* *
* @return string account type * @return ConfiguredType account type
*/ */
function get_type() { function get_type() {
return $this->type; return $this->type;
} }
/** /**
* This function is called when the user clicks on any button on the account pages. * This function is called when the user clicks on any button on the account pages.
@ -812,7 +821,7 @@ class accountContainer {
*/ */
function continue_main() { function continue_main() {
if (!empty($_POST['account_randomID']) && ($this->randomID != $_POST['account_randomID'])) { if (!empty($_POST['account_randomID']) && ($this->randomID != $_POST['account_randomID'])) {
metaRefresh("../lists/list.php?type=" . $this->type . '&amp;accountEditInvalidID=true'); metaRefresh("../lists/list.php?type=" . $this->type->getId() . '&amp;accountEditInvalidID=true');
exit(); exit();
} }
$oldPage = $this->current_page; $oldPage = $this->current_page;
@ -821,7 +830,7 @@ class accountContainer {
$result = array(); $result = array();
$stopProcessing = false; // when set to true, no module options are displayed $stopProcessing = false; // when set to true, no module options are displayed
$errorsOccured = false; $errorsOccured = false;
$typeObject = new $this->type(); $typeObject = $this->type->getBaseType();
$profileLoaded = $this->loadProfileIfRequested(); $profileLoaded = $this->loadProfileIfRequested();
if ($this->subpage=='') $this->subpage='attributes'; if ($this->subpage=='') $this->subpage='attributes';
if (isset($_POST['accountContainerReset'])) { if (isset($_POST['accountContainerReset'])) {
@ -843,30 +852,30 @@ class accountContainer {
if (isset($_POST['accountContainerCreateAgain'])) { if (isset($_POST['accountContainerCreateAgain'])) {
// open fresh account page // open fresh account page
unset($_SESSION[$this->base]); unset($_SESSION[$this->base]);
metaRefresh("edit.php?type=" . $this->type . "&amp;suffix=" . $this->dnSuffix); metaRefresh("edit.php?type=" . $this->type->getId() . "&amp;suffix=" . $this->dnSuffix);
exit(); exit();
} }
// reedit account // reedit account
if (isset($_POST['accountContainerBackToEdit'])) { if (isset($_POST['accountContainerBackToEdit'])) {
// open fresh account page // open fresh account page
unset($_SESSION[$this->base]); unset($_SESSION[$this->base]);
metaRefresh("edit.php?type=" . $this->type . "&amp;DN=" . urlencode($this->finalDN)); metaRefresh("edit.php?type=" . $this->type->getId() . "&amp;DN=" . urlencode($this->finalDN));
exit(); exit();
} }
// back to account list // back to account list
if (isset($_POST['accountContainerBackToList'])) { if (isset($_POST['accountContainerBackToList'])) {
// Return to account list // Return to account list
unset($_SESSION[$this->base]); unset($_SESSION[$this->base]);
metaRefresh("../lists/list.php?type=" . $this->type . '&amp;accountEditBack=true'); metaRefresh("../lists/list.php?type=" . $this->type->getId() . '&amp;accountEditBack=true');
exit; exit;
} }
// create PDF file // create PDF file
if (isset($_POST['accountContainerCreatePDF'])) { if (isset($_POST['accountContainerCreatePDF'])) {
metaRefresh('../lists/list.php?printPDF=1&amp;type=' . $this->type . "&amp;refresh=true&amp;PDFSessionID=" . $this->base); metaRefresh('../lists/list.php?printPDF=1&amp;type=' . $this->type->getId() . "&amp;refresh=true&amp;PDFSessionID=" . $this->base);
exit; exit;
} }
// module actions // module actions
if ((sizeof($_POST) > 0) && checkIfWriteAccessIsAllowed($this->type)) { if ((sizeof($_POST) > 0) && checkIfWriteAccessIsAllowed($this->type->getId())) {
$result = call_user_func(array(&$this->module[$this->order[$this->current_page]], 'process_'.$this->subpage)); $result = call_user_func(array(&$this->module[$this->order[$this->current_page]], 'process_'.$this->subpage));
if (is_array($result)) { // messages were returned, check for errors if (is_array($result)) { // messages were returned, check for errors
for ($i = 0; $i < sizeof($result); $i++) { for ($i = 0; $i < sizeof($result); $i++) {
@ -987,13 +996,13 @@ class accountContainer {
} }
} }
echo '<div id="passwordMessageArea"></div>'; echo '<div id="passwordMessageArea"></div>';
echo "<table class=\"".$this->type."-bright\" border=0 width=\"100%\" style=\"border-collapse: collapse;\">\n"; echo "<table class=\"".$this->type->getScope()."-bright\" border=0 width=\"100%\" style=\"border-collapse: collapse;\">\n";
if (checkIfWriteAccessIsAllowed($this->type)) { if (checkIfWriteAccessIsAllowed($this->type->getId())) {
echo "<tr class=\"".$this->type."-bright\"><td style=\"padding: 15px 15px 0px 15px;\">\n"; echo "<tr class=\"" . $this->type->getScope() . "-bright\"><td style=\"padding: 15px 15px 0px 15px;\">\n";
$this->printCommonControls($tabindex); $this->printCommonControls($tabindex);
echo "</td></tr>\n"; echo "</td></tr>\n";
} }
echo "<tr class=\"".$this->type."-bright\" valign=\"top\"><td style=\"padding: 15px;\">"; echo "<tr class=\"" . $this->type->getScope() . "-bright\" valign=\"top\"><td style=\"padding: 15px;\">";
// print title bar // print title bar
echo '<div class="titleBar ui-corner-top">'; echo '<div class="titleBar ui-corner-top">';
echo '<table width="100%"><tr>'; echo '<table width="100%"><tr>';
@ -1021,10 +1030,10 @@ class accountContainer {
// RDN selection // RDN selection
$group->addElement(new htmlOutputText(_('RDN identifier'))); $group->addElement(new htmlOutputText(_('RDN identifier')));
$group->addElement(new htmlSpacer('2px', null)); $group->addElement(new htmlSpacer('2px', null));
$rdnlist = getRDNAttributes($this->type); $rdnlist = getRDNAttributes($this->type->getId());
$group->addElement(new htmlSelect('accountContainerRDN', $rdnlist, array($this->rdn))); $group->addElement(new htmlSelect('accountContainerRDN', $rdnlist, array($this->rdn)));
$group->addElement(new htmlHelpLink('301')); $group->addElement(new htmlHelpLink('301'));
parseHtml(null, $group, array(), true, $tabindex, $this->type); parseHtml(null, $group, array(), true, $tabindex, $this->type->getScope());
echo '</td>'; echo '</td>';
echo '</tr></table>'; echo '</tr></table>';
if ($this->titleBarSubtitle != null) { if ($this->titleBarSubtitle != null) {
@ -1044,7 +1053,7 @@ class accountContainer {
// display html-code from modules // display html-code from modules
$return = call_user_func(array($this->module[$this->order[$this->current_page]], 'display_html_'.$this->subpage)); $return = call_user_func(array($this->module[$this->order[$this->current_page]], 'display_html_'.$this->subpage));
$y = 5000; $y = 5000;
parseHtml($this->order[$this->current_page], $return, array(), false, $y, $this->type); parseHtml($this->order[$this->current_page], $return, array(), false, $y, $this->type->getScope());
echo "</div>\n"; echo "</div>\n";
echo '</td>'; echo '</td>';
echo '</tr>'; echo '</tr>';
@ -1114,9 +1123,9 @@ class accountContainer {
if (!(strpos($buttonImage, 'http') === 0) && !(strpos($buttonImage, '/') === 0)) { if (!(strpos($buttonImage, 'http') === 0) && !(strpos($buttonImage, '/') === 0)) {
$buttonImage = '../../graphics/' . $buttonImage; $buttonImage = '../../graphics/' . $buttonImage;
} }
$moduleContainer->addElement(new htmlImage($buttonImage, null, null, getModuleAlias($name, $this->type))); $moduleContainer->addElement(new htmlImage($buttonImage, null, null, getModuleAlias($name, $this->type->getScope())));
} }
$moduleContainer->addElement(new htmlTableExtendedInputCheckbox('password_cb_' . $name, true, getModuleAlias($name, $this->type), null, false)); $moduleContainer->addElement(new htmlTableExtendedInputCheckbox('password_cb_' . $name, true, getModuleAlias($name, $this->type->getScope()), null, false));
$moduleContainer->addElement(new htmlSpacer('10px', null)); $moduleContainer->addElement(new htmlSpacer('10px', null));
} }
} }
@ -1125,7 +1134,7 @@ class accountContainer {
// generate HTML // generate HTML
$tabindex = 2000; $tabindex = 2000;
if ($printContainer) { if ($printContainer) {
parseHtml(null, $container, array(), false, $tabindex, $this->type); parseHtml(null, $container, array(), false, $tabindex, $this->type->getScope());
} }
echo "</div>\n"; echo "</div>\n";
} }
@ -1260,7 +1269,7 @@ class accountContainer {
$rightGroup = new htmlGroup(); $rightGroup = new htmlGroup();
$rightGroup->alignment = htmlElement::ALIGN_RIGHT; $rightGroup->alignment = htmlElement::ALIGN_RIGHT;
// profile selection // profile selection
$profilelist = getAccountProfiles($this->type); $profilelist = \LAM\PROFILES\getAccountProfiles($this->type->getId());
if (sizeof($profilelist) > 0) { if (sizeof($profilelist) > 0) {
$rightGroup->addElement(new htmlSelect('accountContainerSelectLoadProfile', $profilelist, array($this->lastLoadedProfile))); $rightGroup->addElement(new htmlSelect('accountContainerSelectLoadProfile', $profilelist, array($this->lastLoadedProfile)));
$profileButton = new htmlButton('accountContainerLoadProfile', _('Load profile')); $profileButton = new htmlButton('accountContainerLoadProfile', _('Load profile'));
@ -1275,7 +1284,7 @@ class accountContainer {
} }
$table->addElement($rightGroup); $table->addElement($rightGroup);
parseHtml(null, $table, array(), false, $tabindex, $this->type); parseHtml(null, $table, array(), false, $tabindex, $this->type->getScope());
?> ?>
<script type="text/javascript"> <script type="text/javascript">
jQuery(document).ready(function() { jQuery(document).ready(function() {
@ -1347,7 +1356,7 @@ class accountContainer {
else { else {
$text = _("Account was modified successfully."); $text = _("Account was modified successfully.");
} }
echo "<div class=\"".$this->type."-bright smallPaddingContent\">"; echo "<div class=\"" . $this->type->getScope() . "-bright smallPaddingContent\">";
$container = new htmlTable(); $container = new htmlTable();
// show messages // show messages
@ -1368,9 +1377,9 @@ class accountContainer {
$container->addElement($message, true); $container->addElement($message, true);
$container->addElement(new htmlSpacer(null, '20px'), true); $container->addElement(new htmlSpacer(null, '20px'), true);
$type = new $this->type(); $type = $this->type->getBaseType();
$buttonGroup = new htmlGroup(); $buttonGroup = new htmlGroup();
if (checkIfNewEntriesAreAllowed($this->type)) { if (checkIfNewEntriesAreAllowed($this->type->getId())) {
$createButton = new htmlButton('accountContainerCreateAgain', $type->LABEL_CREATE_ANOTHER_ACCOUNT); $createButton = new htmlButton('accountContainerCreateAgain', $type->LABEL_CREATE_ANOTHER_ACCOUNT);
$createButton->setIconClass('createButton'); $createButton->setIconClass('createButton');
$buttonGroup->addElement($createButton); $buttonGroup->addElement($createButton);
@ -1390,7 +1399,7 @@ class accountContainer {
$container->addElement($buttonGroup, true); $container->addElement($buttonGroup, true);
$tabindex = 1; $tabindex = 1;
parseHtml(null, $container, array(), false, $tabindex, $this->type); parseHtml(null, $container, array(), false, $tabindex, $this->type->getScope());
echo "</div>\n"; echo "</div>\n";
$this->printPageFooter(); $this->printPageFooter();
@ -1403,13 +1412,13 @@ class accountContainer {
*/ */
private function loadProfileIfRequested() { private function loadProfileIfRequested() {
if (isset($_POST['accountContainerLoadProfile']) && isset($_POST['accountContainerSelectLoadProfile'])) { if (isset($_POST['accountContainerLoadProfile']) && isset($_POST['accountContainerSelectLoadProfile'])) {
$profile = loadAccountProfile($_POST['accountContainerSelectLoadProfile'], $this->type); $profile = \LAM\PROFILES\loadAccountProfile($_POST['accountContainerSelectLoadProfile'], $this->type->getId());
$this->lastLoadedProfile = $_POST['accountContainerSelectLoadProfile']; $this->lastLoadedProfile = $_POST['accountContainerSelectLoadProfile'];
// pass profile to each module // pass profile to each module
$modules = array_keys($this->module); $modules = array_keys($this->module);
foreach ($modules as $module) $this->module[$module]->load_profile($profile); foreach ($modules as $module) $this->module[$module]->load_profile($profile);
if (isset($profile['ldap_rdn'][0])) { if (isset($profile['ldap_rdn'][0])) {
if (in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type))) { if (in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type->getId()))) {
$this->rdn = $profile['ldap_rdn'][0]; $this->rdn = $profile['ldap_rdn'][0];
} }
} }
@ -1437,7 +1446,7 @@ class accountContainer {
$buttonImage = $this->module[$this->order[$i]]->getIcon(); $buttonImage = $this->module[$this->order[$i]]->getIcon();
$activatedClass = ''; $activatedClass = '';
if ($this->order[$this->current_page] == $this->order[$i]) { if ($this->order[$this->current_page] == $this->order[$i]) {
$activatedClass = ' ui-tabs-selected ui-state-active ' . $this->type . '-bright'; $activatedClass = ' ui-tabs-selected ui-state-active ' . $this->type->getScope() . '-bright';
} }
// print button // print button
echo '<li class="ui-state-default ui-corner-left' . $activatedClass . '">'; echo '<li class="ui-state-default ui-corner-left' . $activatedClass . '">';
@ -1551,11 +1560,11 @@ class accountContainer {
function load_account($dn, $infoAttributes = array()) { function load_account($dn, $infoAttributes = array()) {
logNewMessage(LOG_DEBUG, "Edit account " . $dn); logNewMessage(LOG_DEBUG, "Edit account " . $dn);
$this->module = array(); $this->module = array();
$modules = $_SESSION['config']->get_AccountModules($this->type); $modules = $_SESSION['config']->get_AccountModules($this->type->getId());
$search = substr($dn, 0, strpos($dn, ',')); $search = substr($dn, 0, strpos($dn, ','));
$searchAttrs = array('*', '+'); $searchAttrs = array('*', '+');
foreach ($modules as $module) { foreach ($modules as $module) {
$modTmp = new $module($this->type); $modTmp = new $module($this->type->getScope());
$searchAttrs = array_merge($searchAttrs, $modTmp->getManagedHiddenAttributes()); $searchAttrs = array_merge($searchAttrs, $modTmp->getManagedHiddenAttributes());
} }
$result = @ldap_read($_SESSION['ldap']->server(), escapeDN($dn), escapeDN($search), $searchAttrs, 0, 0, 0, LDAP_DEREF_NEVER); $result = @ldap_read($_SESSION['ldap']->server(), escapeDN($dn), escapeDN($search), $searchAttrs, 0, 0, 0, LDAP_DEREF_NEVER);
@ -1592,7 +1601,7 @@ class accountContainer {
foreach ($modules as $module) { foreach ($modules as $module) {
if (!isset($this->module[$module])) { if (!isset($this->module[$module])) {
$this->module[$module] = new $module($this->type); $this->module[$module] = new $module($this->type->getScope());
$this->module[$module]->init($this->base); $this->module[$module]->init($this->base);
} }
$this->module[$module]->load_attributes($attr); $this->module[$module]->load_attributes($attr);
@ -1601,7 +1610,7 @@ class accountContainer {
// sort module buttons // sort module buttons
$this->sortModules(); $this->sortModules();
// get titles // get titles
$typeObject = new $this->type(); $typeObject = $this->type->getBaseType();
$this->titleBarTitle = $typeObject->getTitleBarTitle($this); $this->titleBarTitle = $typeObject->getTitleBarTitle($this);
$this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this); $this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
return array(); return array();
@ -1622,7 +1631,7 @@ class accountContainer {
$aliases = array(); $aliases = array();
$ldapAttributesTemp = array(); $ldapAttributesTemp = array();
foreach ($modules as $module) { foreach ($modules as $module) {
$moduleObj = moduleCache::getModule($module, $this->type); $moduleObj = moduleCache::getModule($module, $this->type->getScope());
$objectClasses = array_merge($objectClasses, $moduleObj->getManagedObjectClasses()); $objectClasses = array_merge($objectClasses, $moduleObj->getManagedObjectClasses());
$aliases = array_merge($aliases, $moduleObj->getLDAPAliases()); $aliases = array_merge($aliases, $moduleObj->getLDAPAliases());
$ldapAttributesTemp = array_merge($ldapAttributesTemp, $moduleObj->getManagedAttributes()); $ldapAttributesTemp = array_merge($ldapAttributesTemp, $moduleObj->getManagedAttributes());
@ -1688,22 +1697,22 @@ class accountContainer {
* This function will prepare the object for a new account. * This function will prepare the object for a new account.
*/ */
function new_account() { function new_account() {
logNewMessage(LOG_DEBUG, "New account with type " . $this->type); logNewMessage(LOG_DEBUG, "New account with type " . $this->type->getId());
$this->isNewAccount = true; $this->isNewAccount = true;
$this->lastLoadedProfile = 'default'; $this->lastLoadedProfile = 'default';
$modules = $_SESSION['config']->get_AccountModules($this->type); $modules = $_SESSION['config']->get_AccountModules($this->type->getId());
foreach ($modules as $module) { foreach ($modules as $module) {
$this->module[$module] = new $module($this->type); $this->module[$module] = new $module($this->type->getScope());
$this->module[$module]->init($this->base); $this->module[$module]->init($this->base);
} }
// sort module buttons // sort module buttons
$this->sortModules(); $this->sortModules();
$profile = loadAccountProfile('default', $this->type); $profile = \LAM\PROFILES\loadAccountProfile('default', $this->type->getId());
// pass profile to each module // pass profile to each module
$modules = array_keys($this->module); $modules = array_keys($this->module);
foreach ($modules as $module) $this->module[$module]->load_profile($profile); foreach ($modules as $module) $this->module[$module]->load_profile($profile);
if (isset($profile['ldap_rdn'][0])) { if (isset($profile['ldap_rdn'][0])) {
if (in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type))) { if (in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type->getId()))) {
$this->rdn = $profile['ldap_rdn'][0]; $this->rdn = $profile['ldap_rdn'][0];
} }
} }
@ -1711,7 +1720,7 @@ class accountContainer {
$this->dnSuffix = $profile['ldap_suffix'][0]; $this->dnSuffix = $profile['ldap_suffix'][0];
} }
// get titles // get titles
$typeObject = new $this->type(); $typeObject = $this->type->getBaseType();
$this->titleBarTitle = $typeObject->getTitleBarTitle($this); $this->titleBarTitle = $typeObject->getTitleBarTitle($this);
$this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this); $this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
return 0; return 0;
@ -1723,14 +1732,14 @@ class accountContainer {
* @return array list of status messages * @return array list of status messages
*/ */
function save_account() { function save_account() {
if (!checkIfWriteAccessIsAllowed($this->type)) { if (!checkIfWriteAccessIsAllowed($this->type->getId())) {
die(); die();
} }
$this->finalDN = $this->dn_orig; $this->finalDN = $this->dn_orig;
$errors = array(); $errors = array();
$ldapUser = $_SESSION['ldap']->decrypt_login(); $ldapUser = $_SESSION['ldap']->decrypt_login();
$ldapUser = $ldapUser[0]; $ldapUser = $ldapUser[0];
$module = array_keys ($this->module); $module = array_keys($this->module);
$attributes = array(); $attributes = array();
// load attributes // load attributes
foreach ($module as $singlemodule) { foreach ($module as $singlemodule) {
@ -1740,7 +1749,7 @@ class accountContainer {
// merge changes // merge changes
$DNs = array_keys($temp); $DNs = array_keys($temp);
if (is_array($temp)) $attributes = array_merge_recursive($temp, $attributes); if (is_array($temp)) $attributes = array_merge_recursive($temp, $attributes);
for ($i=0; $i<count($DNs); $i++) { for ($i = 0; $i < count($DNs); $i++) {
$ops = array_keys($temp[$DNs[$i]]); $ops = array_keys($temp[$DNs[$i]]);
for ($j=0; $j<count($ops); $j++) { for ($j=0; $j<count($ops); $j++) {
$attrs = array_keys($temp[$DNs[$i]][$ops[$j]]); $attrs = array_keys($temp[$DNs[$i]][$ops[$j]]);
@ -2027,7 +2036,7 @@ class accountContainer {
for ($i = 0; $i < sizeof($modules); $i++) { for ($i = 0; $i < sizeof($modules); $i++) {
// insert waiting modules // insert waiting modules
for ($w = 0; $w < sizeof($depModules); $w++) { for ($w = 0; $w < sizeof($depModules); $w++) {
$dependencies = $this->module[$depModules[$w]]->get_dependencies($this->type); $dependencies = $this->module[$depModules[$w]]->get_dependencies($this->type->getScope());
$dependencies = $dependencies['depends']; $dependencies = $dependencies['depends'];
$everything_found = true; $everything_found = true;
for ($d = 0; $d < sizeof($dependencies); $d++) { for ($d = 0; $d < sizeof($dependencies); $d++) {
@ -2045,7 +2054,7 @@ class accountContainer {
} }
} }
// check next module // check next module
$dependencies = $this->module[$modules[$i]]->get_dependencies($this->type); $dependencies = $this->module[$modules[$i]]->get_dependencies($this->type->getScope());
if (is_array($dependencies['depends'])) { if (is_array($dependencies['depends'])) {
$everything_found = true; $everything_found = true;
$dependencies = $dependencies['depends']; $dependencies = $dependencies['depends'];
@ -2138,8 +2147,7 @@ class accountContainer {
if ($this->cachedOUs != null) { if ($this->cachedOUs != null) {
return $this->cachedOUs; return $this->cachedOUs;
} }
$typeObj = new $this->type(); $this->cachedOUs = $this->type->getSuffixList();
$this->cachedOUs = $typeObj->getSuffixList();
return $this->cachedOUs; return $this->cachedOUs;
} }

View File

@ -4,7 +4,7 @@ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Tilo Lutz Copyright (C) 2003 - 2006 Tilo Lutz
2005 - 2016 Roland Gruber 2005 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -37,8 +37,6 @@ $Id$
*/ */
class inetOrgPerson extends baseModule implements passwordService { class inetOrgPerson extends baseModule implements passwordService {
/** caches the list of possible managers */
private $cachedManagers = null;
/** clear text password */ /** clear text password */
private $clearTextPassword = null; private $clearTextPassword = null;
/** cache for departments */ /** cache for departments */
@ -2809,7 +2807,13 @@ class inetOrgPerson extends baseModule implements passwordService {
} }
else { else {
$userObj = new user(); $userObj = new user();
$ouList = $userObj->getSuffixList(); $filter = $userObj->getSuffixFilter();
$suffix = $_SESSION['selfServiceProfile']->LDAPSuffix;
$foundOus = searchLDAPPaged($_SESSION['ldapHandle'], $suffix, $filter, array('dn'), false, 0);
$ouList = array();
foreach ($foundOus as $foundOu) {
$ouList[] = $foundOu['dn'];
}
if (!empty($attributes['ou'][0]) && !in_array($attributes['ou'][0], $ouList)) { if (!empty($attributes['ou'][0]) && !in_array($attributes['ou'][0], $ouList)) {
$ouList[] = $attributes['ou'][0]; $ouList[] = $attributes['ou'][0];
usort($ouList, 'compareDN'); usort($ouList, 'compareDN');
@ -3489,28 +3493,6 @@ class inetOrgPerson extends baseModule implements passwordService {
return array(); return array();
} }
/**
* Returns a list of possible managers.
*
* @return array list of format array(abstract DN => DN)
*/
private function getManagers() {
if ($this->cachedManagers != null) {
return $this->cachedManagers;
}
$dnUsers = searchLDAPByAttribute(null, null, 'inetOrgPerson', array('dn'), array('user'));
for ($i = 0; $i < sizeof($dnUsers); $i++) {
$dnUsers[$i] = $dnUsers[$i]['dn'];
}
usort($dnUsers, 'compareDN');
array_unshift($dnUsers, '-');
$this->cachedManagers = array();
for ($i = 0; $i < sizeof($dnUsers); $i++) {
$this->cachedManagers[getAbstractDN($dnUsers[$i])] = $dnUsers[$i];
}
return $this->cachedManagers;
}
/** /**
* Loads cached data from LDAP such as departmets etc. * Loads cached data from LDAP such as departmets etc.
*/ */

View File

@ -36,7 +36,7 @@ class nisMailAliasUser extends baseModule {
/** alias cache */ /** alias cache */
private $cachedAliasList = null; private $cachedAliasList = null;
/** recipient entries to delete (list of arrays: dn => attributes) */ /** recipient entries to delete (list of arrays: dn => attributes) */
private $recipientsToDelete = array(); private $recipientsToDelete = array();
/** complete alias entries to delete */ /** complete alias entries to delete */
@ -45,10 +45,10 @@ class nisMailAliasUser extends baseModule {
private $aliasesToAdd = array(); private $aliasesToAdd = array();
/** alias entries to extend with new recipients (list of arrays: dn => recipients) */ /** alias entries to extend with new recipients (list of arrays: dn => recipients) */
private $recipientsToAdd = array(); private $recipientsToAdd = array();
/** /**
* Returns true if this module can manage accounts of the current type, otherwise false. * Returns true if this module can manage accounts of the current type, otherwise false.
* *
* @return boolean true if module fits * @return boolean true if module fits
*/ */
public function can_manage() { public function can_manage() {
@ -59,7 +59,7 @@ class nisMailAliasUser extends baseModule {
* Returns meta data that is interpreted by parent class * Returns meta data that is interpreted by parent class
* *
* @return array array with meta data * @return array array with meta data
* *
* @see baseModule::get_metaData() * @see baseModule::get_metaData()
*/ */
function get_metaData() { function get_metaData() {
@ -122,7 +122,7 @@ class nisMailAliasUser extends baseModule {
/** /**
* Returns the HTML meta data for the main account page. * Returns the HTML meta data for the main account page.
* *
* @return htmlElement HTML meta data * @return htmlElement HTML meta data
*/ */
function display_html_attributes() { function display_html_attributes() {
@ -247,10 +247,10 @@ class nisMailAliasUser extends baseModule {
} }
return $errors; return $errors;
} }
/** /**
* Removes a recipient from the given DN. * Removes a recipient from the given DN.
* *
* @param String $recipient recipient as user name or email * @param String $recipient recipient as user name or email
* @param String $dn alias DN * @param String $dn alias DN
*/ */
@ -300,7 +300,7 @@ class nisMailAliasUser extends baseModule {
/** /**
* Removes an alias with the given DN. * Removes an alias with the given DN.
* *
* @param String $dn alias DN * @param String $dn alias DN
*/ */
private function deleteAlias($dn) { private function deleteAlias($dn) {
@ -324,10 +324,10 @@ class nisMailAliasUser extends baseModule {
unset($this->recipientsToDelete[$dn]); unset($this->recipientsToDelete[$dn]);
} }
} }
/** /**
* Returns the HTML meta data for the add page. * Returns the HTML meta data for the add page.
* *
* @return htmlElement HTML meta data * @return htmlElement HTML meta data
*/ */
function display_html_add() { function display_html_add() {
@ -357,9 +357,18 @@ class nisMailAliasUser extends baseModule {
$return->addElement(new htmlHiddenInput('recipient', $recipient), true); $return->addElement(new htmlHiddenInput('recipient', $recipient), true);
// new mail alias // new mail alias
$return->addElement(new htmlSubTitle(_('Create new alias')), true); $return->addElement(new htmlSubTitle(_('Create new alias')), true);
$typeObj = new mailAlias(); $typeManager = new \LAM\TYPES\TypeManager();
$ous = $typeObj->getSuffixList(); $mailAliasTypes = $typeManager->getConfiguredTypesForScope('mailAlias');
$return->addElement(new htmlTableExtendedSelect('new_ou', $ous, array(), _('Suffix'), 'suffix'), true); $ous = array();
foreach ($mailAliasTypes as $type) {
$ous = array_merge($ous, $type->getSuffixList());
}
$ous = array_unique($ous);
usort($ous, 'compareDN');
$suffixSelect = new htmlTableExtendedSelect('new_ou', $ous, array(), _('Suffix'), 'suffix');
$suffixSelect->setRightToLeftTextDirection(true);
$suffixSelect->setSortElements(false);
$return->addElement($suffixSelect, true);
$newAliasCn = empty($_POST['new_cn']) ? '' : $_POST['new_cn']; $newAliasCn = empty($_POST['new_cn']) ? '' : $_POST['new_cn'];
$return->addElement(new htmlTableExtendedInputField(_('Alias name'), 'new_cn', $newAliasCn, 'newAlias'), true); $return->addElement(new htmlTableExtendedInputField(_('Alias name'), 'new_cn', $newAliasCn, 'newAlias'), true);
$return->addVerticalSpace('5px'); $return->addVerticalSpace('5px');
@ -367,9 +376,9 @@ class nisMailAliasUser extends baseModule {
$addButton->setIconClass('createButton'); $addButton->setIconClass('createButton');
$addButton->colspan = 5; $addButton->colspan = 5;
$return->addElement($addButton, true); $return->addElement($addButton, true);
$return->addVerticalSpace('20px'); $return->addVerticalSpace('20px');
// add to existing alias // add to existing alias
$return->addElement(new htmlSubTitle(_('Add to existing alias')), true); $return->addElement(new htmlSubTitle(_('Add to existing alias')), true);
$aliasesToAdd = array(); $aliasesToAdd = array();
@ -388,7 +397,7 @@ class nisMailAliasUser extends baseModule {
$addButton->setIconClass('createButton'); $addButton->setIconClass('createButton');
$addButton->colspan = 5; $addButton->colspan = 5;
$return->addElement($addButton, true); $return->addElement($addButton, true);
$return->addElement(new htmlEqualWidth(array('new_ou', 'new_cn', 'ex_cn'))); $return->addElement(new htmlEqualWidth(array('new_ou', 'new_cn', 'ex_cn')));
return $return; return $return;
} }
@ -446,13 +455,13 @@ class nisMailAliasUser extends baseModule {
} }
} }
} }
return $errors; return $errors;
} }
/** /**
* Allows the module to run commands after the LDAP entry is changed or created. * Allows the module to run commands after the LDAP entry is changed or created.
* *
* Calling this method requires the existence of an enclosing {@link accountContainer}. * Calling this method requires the existence of an enclosing {@link accountContainer}.
* *
* @param boolean $newAccount new account * @param boolean $newAccount new account
@ -545,7 +554,7 @@ class nisMailAliasUser extends baseModule {
/** /**
* Returns a list of configuration options. * Returns a list of configuration options.
* *
* Calling this method does not require the existence of an enclosing {@link accountContainer}.<br> * Calling this method does not require the existence of an enclosing {@link accountContainer}.<br>
* <br> * <br>
* The field names are used as keywords to load and save settings. * The field names are used as keywords to load and save settings.
@ -554,7 +563,7 @@ class nisMailAliasUser extends baseModule {
* @param array $scopes account types (user, group, host) * @param array $scopes account types (user, group, host)
* @param array $allScopes list of all active account modules and their scopes (module => array(scopes)) * @param array $allScopes list of all active account modules and their scopes (module => array(scopes))
* @return mixed htmlElement or array of htmlElement * @return mixed htmlElement or array of htmlElement
* *
* @see baseModule::get_metaData() * @see baseModule::get_metaData()
* @see htmlElement * @see htmlElement
*/ */
@ -584,10 +593,10 @@ class nisMailAliasUser extends baseModule {
$this->cachedAliasList = searchLDAPByAttribute('cn', '*', 'nisMailAlias', array('dn', 'cn', 'rfc822MailMember'), array('mailAlias')); $this->cachedAliasList = searchLDAPByAttribute('cn', '*', 'nisMailAlias', array('dn', 'cn', 'rfc822MailMember'), array('mailAlias'));
return $this->cachedAliasList; return $this->cachedAliasList;
} }
/** /**
* Returns the user name of this account. * Returns the user name of this account.
* *
* @return String user name * @return String user name
*/ */
private function getUserName() { private function getUserName() {
@ -605,10 +614,10 @@ class nisMailAliasUser extends baseModule {
} }
return null; return null;
} }
/** /**
* Returns the email addresses of this account. * Returns the email addresses of this account.
* *
* @return String mail addresses * @return String mail addresses
*/ */
private function getMailAddresses() { private function getMailAddresses() {
@ -620,10 +629,10 @@ class nisMailAliasUser extends baseModule {
} }
return null; return null;
} }
/** /**
* Returns if the mail alias type is active. Otherwise, aliases cannot be managed. * Returns if the mail alias type is active. Otherwise, aliases cannot be managed.
* *
* @return boolean is active * @return boolean is active
*/ */
private function isMailAliasTypeActive() { private function isMailAliasTypeActive() {

View File

@ -67,7 +67,7 @@ function createModulePDF($accounts, $pdf_structure="default", $returnAsString =
$account_type = $accounts[0]->get_type(); $account_type = $accounts[0]->get_type();
// Get PDF structure from xml file // Get PDF structure from xml file
$load = loadPDFStructureDefinitions($account_type,$pdf_structure); $load = \LAM\PDF\loadPDFStructure($account_type->getId(), $pdf_structure);
$structure = $load['structure']; $structure = $load['structure'];
// get list of PDF keys // get list of PDF keys
$pdfKeys = array(); $pdfKeys = array();

View File

@ -1,10 +1,14 @@
<?php <?php
namespace LAM\PDF;
use \htmlStatusMessage;
use \LAMException;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Michael Duergner Copyright (C) 2003 - 2006 Michael Duergner
2011 - 2016 Roland Gruber 2011 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -36,19 +40,20 @@ include_once("ldap.inc");
/** /**
* This function will return all available PDF structure definitions for the submitted * This function will return all available PDF structure definitions for the submitted
* account scope. * account type.
* *
* @param string $scope The account scope the PDF structure definitions should be * @param string $typeId the account type
* returned.
* @param string $profile server profile name * @param string $profile server profile name
* *
* @return array $scope All available PDF structure definitions for the submitted account * @return array All available PDF structure definitions for the submitted account
* scope. Each entry is a string being the filename that may be passed to the * scope. Each entry is a string being the filename that may be passed to the
* createModulePDF() function as second argument. * createModulePDF() function as second argument.
*/ */
function getPDFStructureDefinitions($scope = "user", $profile = null) { function getPDFStructures($typeId, $profile = null) {
$return = array(); $return = array();
if (!preg_match('/[a-zA-Z]+/', $typeId)) {
return null;
}
if (!isset($profile)) { if (!isset($profile)) {
$profile = $_SESSION['config']->getName(); $profile = $_SESSION['config']->getName();
} }
@ -57,7 +62,7 @@ function getPDFStructureDefinitions($scope = "user", $profile = null) {
$dirHandle = opendir($path); $dirHandle = opendir($path);
while($file = readdir($dirHandle)) { while($file = readdir($dirHandle)) {
$struct_file = explode('.',$file); $struct_file = explode('.',$file);
if(!is_dir($path.$file) && ($file != '.') && ($file != '..') && (sizeof($struct_file) == 3) && ($struct_file[1] == $scope) && ($struct_file[2] == 'xml')) { if(!is_dir($path.$file) && ($file != '.') && ($file != '..') && (sizeof($struct_file) == 3) && ($struct_file[1] == $typeId) && ($struct_file[2] == 'xml')) {
array_push($return, $struct_file[0]); array_push($return, $struct_file[0]);
} }
} }
@ -67,22 +72,24 @@ function getPDFStructureDefinitions($scope = "user", $profile = null) {
} }
/** /**
* This function is used to get pdf structure from xml file. * This function is used to get the PDF structure from XML file.
* Used in createModulePDF.
* *
* @param string $scope The account scope for wich the PDF structure should be returned. * @param string $typeId the account type
* @param string $pdf_structure Structure name of selected scope wich should be returned. * @param string $name structure name
* *
* @return array PDF structure * @return array PDF structure
*/ */
function loadPDFStructureDefinitions($scope='user',$pdf_structure='default') { function loadPDFStructure($typeId, $name='default') {
if (!isValidPDFStructureName($name) || !preg_match('/[a-zA-Z]+/', $typeId)) {
return null;
}
$parser = new xmlParser(); $parser = new xmlParser();
$file = dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName() . '/' . $pdf_structure . '.' . $scope . '.xml'; $file = dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName() . '/' . $name . '.' . $typeId . '.xml';
$xml = $parser->parse($file); $xml = $parser->parse($file);
$border = array(); $border = array();
$structure = array(); $structure = array();
$complete_page_definitions = array('filename' => 'printLogo.jpg', 'headline' => 'LDAP Account Manager'); $complete_page_definitions = array('filename' => 'printLogo.jpg', 'headline' => 'LDAP Account Manager');
if($xml[0][$xml[1]['PDF'][0]]['attributes']['TYPE'] == $scope) { if (!empty($xml)) {
$border['start'] = $xml[1]['PDF'][0]; $border['start'] = $xml[1]['PDF'][0];
$page_definitions = $xml[0][$xml[1]['PDF'][0]]['attributes']; $page_definitions = $xml[0][$xml[1]['PDF'][0]]['attributes'];
foreach($page_definitions as $key => $value) { foreach($page_definitions as $key => $value) {
@ -90,23 +97,24 @@ function loadPDFStructureDefinitions($scope='user',$pdf_structure='default') {
unset($page_definitions[$key]); unset($page_definitions[$key]);
} }
$border['end'] = $xml[1]['PDF'][1]; $border['end'] = $xml[1]['PDF'][1];
$structure = array_slice($xml[0],$border['start'] + 1,$border['end'] - ($border['start'] + 1));
} }
$structure = array_slice($xml[0],$border['start'] + 1,$border['end'] - ($border['start'] + 1));
return array('structure' => $structure, 'page_definitions' => $complete_page_definitions); return array('structure' => $structure, 'page_definitions' => $complete_page_definitions);
} }
/** /**
* Saves PDF structure definitions to XML file in format: <name>.<scope>.xml * Saves PDF structure to XML file in format: <name>.<typeId>.xml
* *
* @param string $scope account type * @param string $typeId account type
* @param string $definition Name of definition * @param string $name name of structure
* @return string "no perms" if access denied or "ok". * @return string "no perms" if access denied or "ok".
*/ */
function savePDFStructureDefinitions($scope,$definition) { function savePDFStructure($typeId, $name) {
if (!preg_match('/[a-zA-Z0-9\-\_]+/',$definition)) return 'no perms'; if (!isValidPDFStructureName($name) || !preg_match('/[a-zA-Z]+/', $typeId)) {
if (!preg_match('/[a-zA-Z]+/',$scope)) return 'no perms'; return 'no perms';
$struct_file = dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName() . '/' . $definition . '.' . $scope . '.xml'; }
$struct_file = dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName() . '/' . $name . '.' . $typeId . '.xml';
if(!is_writable(dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName())) { if(!is_writable(dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName())) {
return 'no perms'; return 'no perms';
} }
@ -115,11 +123,9 @@ function savePDFStructureDefinitions($scope,$definition) {
if (!$handle) return 'no perms'; if (!$handle) return 'no perms';
$pdf_attributes = ''; $pdf_attributes = '';
foreach($_SESSION['currentPageDefinitions'] as $key => $value) { foreach($_SESSION['currentPageDefinitions'] as $key => $value) {
if($key != 'type') { $pdf_attributes .= ' ' . $key . '="' . $value . '"';
$pdf_attributes .= ' ' . $key . '="' . $value . '"';
}
} }
$file = '<pdf type="' . $scope . "\"" . $pdf_attributes . ">\n"; $file = '<pdf' . $pdf_attributes . ">\n";
foreach($_SESSION['currentPDFStructure'] as $entry) { foreach($_SESSION['currentPDFStructure'] as $entry) {
$ident = ''; $ident = '';
for($i=0;$i<$entry['level'] -1;$i++) { for($i=0;$i<$entry['level'] -1;$i++) {
@ -156,15 +162,16 @@ function savePDFStructureDefinitions($scope,$definition) {
/** /**
* Deletes XML file with PDF structure definitions. * Deletes XML file with PDF structure definitions.
* *
* @param string $scope account type * @param string $typeId account type
* @param string $definition Name of definition to delete * @param string $name Name of definition to delete
* *
* @return boolean True if file was deleted or false if a problem occured. * @return boolean True if file was deleted or false if a problem occured.
*/ */
function deletePDFStructureDefinition($scope, $definition) { function deletePDFStructure($typeId, $name) {
if (!preg_match('/[a-zA-Z0-9\-\_]+/',$definition)) return false; if (!isValidPDFStructureName($name) || !preg_match('/[a-zA-Z]+/',$typeId)) {
if (!preg_match('/[a-zA-Z]+/',$scope)) return false; return false;
$file = dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName() . '/' . $definition . '.' . $scope . '.xml'; }
$file = dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName() . '/' . $name . '.' . $typeId . '.xml';
if(is_file($file) && is_writable($file)) { if(is_file($file) && is_writable($file)) {
return unlink($file); return unlink($file);
} }
@ -195,46 +202,50 @@ function getAvailableLogos() {
return $return; return $return;
} }
/**
* Copies a PDF structure from the given source to target.
*
* @param \LAM\TYPES\ConfiguredType $sourceType source type
* @param string $sourceStructureName structure name
* @param \LAM\TYPES\ConfiguredType $targetType target type
* @throws Exception
*/
function copyStructure($sourceType, $sourceStructureName, $targetType) {
if (!isValidPDFStructureName($sourceStructureName)) {
throw new LAMException(_('Failed to copy'));
}
$sourceConfig = $sourceType->getTypeManager()->getConfig()->getName();
$sourceTypeId = $sourceType->getId();
$targetConfig = $targetType->getTypeManager()->getConfig()->getName();
$targetTypeId = $targetType->getId();
$basePath = dirname(__FILE__) . '/../config/pdf/';
$src = $basePath . $sourceConfig . '/' . $sourceStructureName . '.' . $sourceTypeId . '.xml';
$dst = $basePath . $targetConfig . '/' . $sourceStructureName . '.' . $targetTypeId . '.xml';
if (!@copy($src, $dst)) {
throw new LAMException(_('Failed to copy'), $sourceConfig . ': ' . $sourceStructureName);
}
}
/** /**
* Copies PDF profiles to other server profiles. * Copies a PDF structure from the given source to global templates.
* *
* @param array $pdfProfiles PDF profile names * @param \LAM\TYPES\ConfiguredType $sourceType source type
* @param String $scope account scope * @param string $sourceName structure name
* @param array $dests destinations * @throws Exception
*
* @return boolean operation succeeded
*/ */
function copyPdfProfiles($pdfProfiles, $scope, $dests = array()) { function copyStructureToTemplates($sourceType, $sourceName) {
$state = true; if (!isValidPDFStructureName($sourceName)) {
$profilePath = substr(__FILE__, 0, strlen(__FILE__) - 17) . 'config/pdf/'; throw new LAMException(_('Failed to copy'));
foreach ($pdfProfiles as $profile) { }
//part 1: server profile $sourceConfig = $sourceType->getTypeManager()->getConfig()->getName();
//part 2: account profile $sourceTypeId = $sourceType->getId();
$tmpArr = explode('##', $profile); $basePath = dirname(__FILE__) . '/../config/pdf/';
$src = $profilePath . $tmpArr[0] . '/' . $tmpArr[1] . '.' . $scope . '.xml'; $templatePath = dirname(__FILE__) . '/../config/templates/pdf/';
if (!empty($dests)) { $src = $basePath . $sourceConfig . '/' . $sourceName . '.' . $sourceTypeId . '.xml';
foreach ($dests as $dest) { $dst = $templatePath . $sourceName . '.' . $sourceType->getScope() . '.xml';
if ($dest == 'templates*') { if (!@copy($src, $dst)) {
$dst = substr(__FILE__, 0, strlen(__FILE__) - 17) . 'config/templates/pdf/' . $tmpArr[1] . '.' . $scope . '.xml'; throw new LAMException(_('Failed to copy'), $sourceConfig . ': ' . $sourceName);
} else {
$dst = $profilePath . $dest . '/' . $tmpArr[1] . '.' . $scope . '.xml';
}
if (!@copy($src, $dst)) {
StatusMessage('ERROR', _('Failed to export!'), $tmpArr[1] . '.' . $scope . '.xml');
$state = false;
}
}
} else {
$dst = $profilePath . $_SESSION['config']->getName() . '/' . $tmpArr[1] . '.' . $scope . '.xml';
if (!@copy($src, $dst)) {
StatusMessage('ERROR', _('Failed to import!'), $tmpArr[1] . '.' . $scope . '.xml');
$state = false;
}
}
} }
return $state;
} }
/** /**
@ -282,14 +293,15 @@ function deletePDFLogo($name) {
return new htmlStatusMessage('ERROR', _('File does not exist.'), htmlspecialchars($name)); return new htmlStatusMessage('ERROR', _('File does not exist.'), htmlspecialchars($name));
} }
// check if still in use // check if still in use
$activeTypes = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
$activeTypes = $typeManager->getConfiguredTypes();
foreach ($activeTypes as $type) { foreach ($activeTypes as $type) {
$structures = getPDFStructureDefinitions($type); $structures = getPDFStructures($type->getId());
foreach ($structures as $structure) { foreach ($structures as $structure) {
$data = loadPDFStructureDefinitions($type, $structure); $data = loadPDFStructure($type->getId(), $structure);
if ($data['page_definitions']['filename'] == $name) { if ($data['page_definitions']['filename'] == $name) {
return new htmlStatusMessage('ERROR', _('Unable to delete logo file.'), return new htmlStatusMessage('ERROR', _('Unable to delete logo file.'),
sprintf(_('Logo is still in use by PDF structure "%s" in account type "%s".'), $structure, LAM\TYPES\getTypeAlias($type))); sprintf(_('Logo is still in use by PDF structure "%s" in account type "%s".'), $structure, $type->getAlias()));
} }
} }
} }
@ -304,4 +316,49 @@ function deletePDFLogo($name) {
} }
} }
/**
* Returns if the give structure name is valid.
*
* @param string $name structure name
* @return boolean is valid
*/
function isValidPDFStructureName($name) {
return preg_match('/[a-zA-Z0-9\-\_]+/',$name) === 1;
}
/**
* Installs template structures to the current server profile.
*/
function installPDFTemplates() {
$templatePath = dirname(__FILE__) . '/../config/templates/pdf';
$templateDir = @dir($templatePath);
$allTemplates = array();
if ($templateDir) {
$entry = $templateDir->read();
while ($entry){
$parts = explode('.', $entry);
if ((strlen($entry) > 3) && (sizeof($parts) == 3)) {
$name = $parts[0];
$scope = $parts[1];
$allTemplates[$scope][] = $name;
}
$entry = $templateDir->read();
}
}
$basePath = dirname(__FILE__) . '/../config/pdf/' . $_SESSION['config']->getName() . '/';
$typeManager = new \LAM\TYPES\TypeManager();
foreach ($typeManager->getConfiguredTypes() as $type) {
if (empty($allTemplates[$type->getScope()])) {
continue;
}
foreach ($allTemplates[$type->getScope()] as $templateName) {
$path = $basePath . $templateName . '.' . $type->getId() . '.xml';
if (!is_file($path)) {
$template = $templatePath . '/' . $templateName . '.' . $scope . '.xml';
@copy($template, $path);
}
}
}
}
?> ?>

View File

@ -1,9 +1,11 @@
<?php <?php
namespace LAM\PROFILES;
use \LAMException;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Roland Gruber Copyright (C) 2003 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -32,26 +34,26 @@ $Id$
/** /**
* Returns an array of string with all available profiles for the given account type * Returns an array of string with all available profiles for the given account type
* *
* @param string $scope account type * @param string $typeId account type
* @param string $profile server profile name * @param string $profile server profile name
* @return array profile names * @return array profile names
*/ */
function getAccountProfiles($scope, $profile = null) { function getAccountProfiles($typeId, $profile = null) {
if (!isset($profile)) { if (!isset($profile)) {
$profile = $_SESSION['config']->getName(); $profile = $_SESSION['config']->getName();
} }
$dir = @dir(substr(__FILE__, 0, strlen(__FILE__) - 17) . "/config/profiles/" . $profile); $dir = @dir(dirname(__FILE__) . "/../config/profiles/" . $profile);
$ret = array(); $ret = array();
$pos = 0; $pos = 0;
if ($dir) { if ($dir) {
$entry = $dir->read(); $entry = $dir->read();
while ($entry){ while ($entry){
// check if filename ends with .<scope> // check if filename ends with .<typeId>
if (strrpos($entry, '.')) { if (strrpos($entry, '.')) {
$pos = strrpos($entry, '.'); $pos = strrpos($entry, '.');
if (substr($entry, $pos + 1) == $scope) { if (substr($entry, $pos + 1) == $typeId) {
$name = substr($entry, 0, $pos); $name = substr($entry, 0, $pos);
$ret[] = $name; $ret[] = $name;
} }
@ -67,13 +69,17 @@ function getAccountProfiles($scope, $profile = null) {
* Loads an profile of the given account type * Loads an profile of the given account type
* *
* @param string $profile name of the profile (without .<scope> extension) * @param string $profile name of the profile (without .<scope> extension)
* @param string $scope account type * @param string $typeId account type
* @return array hash array (attribute => value) * @return array hash array (attribute => value)
*/ */
function loadAccountProfile($profile, $scope) { function loadAccountProfile($profile, $typeId) {
if (!preg_match("/^[0-9a-z _-]+$/i", $profile) || !preg_match("/^[a-z]+$/i", $scope)) return false; $typeManager = new \LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($typeId);
if (!isValidProfileName($profile) || !preg_match("/^[a-z0-9_]+$/i", $typeId) || ($type == null)) {
return false;
}
$settings = array(); $settings = array();
$file = substr(__FILE__, 0, strlen(__FILE__) - 17) . "/config/profiles/" . $_SESSION['config']->getName() . '/' . $profile . "." . $scope; $file = substr(__FILE__, 0, strlen(__FILE__) - 17) . "/config/profiles/" . $_SESSION['config']->getName() . '/' . $profile . "." . $typeId;
if (is_file($file) == True) { if (is_file($file) == True) {
$file = @fopen($file, "r"); $file = @fopen($file, "r");
if ($file) { if ($file) {
@ -111,17 +117,21 @@ function loadAccountProfile($profile, $scope) {
* *
* @param array $attributes hash array (attribute => value) * @param array $attributes hash array (attribute => value)
* @param string $profile name of the account profile (without .<scope> extension) * @param string $profile name of the account profile (without .<scope> extension)
* @param string $scope account type * @param string $typeId account type
* @return boolean true, if saving succeeded * @return boolean true, if saving succeeded
*/ */
function saveAccountProfile($attributes, $profile, $scope) { function saveAccountProfile($attributes, $profile, $typeId) {
if (!isLoggedIn()) return false; if (!isLoggedIn()) return false;
// check profile name // check profile name and type id
if (!preg_match("/^[0-9a-z _-]+$/i", $profile) || !preg_match("/^[a-z]+$/i", $scope)) return false; $typeManager = new \LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($typeId);
if (!isValidProfileName($profile) || !preg_match("/^[a-z0-9_]+$/i", $typeId) || ($type == null)) {
return false;
}
if (!is_array($attributes)) { if (!is_array($attributes)) {
return false; return false;
} }
$path = substr(__FILE__, 0, strlen(__FILE__) - 17) . "/config/profiles/" . $_SESSION['config']->getName() . '/' . $profile . "." . $scope; $path = substr(__FILE__, 0, strlen(__FILE__) - 17) . "/config/profiles/" . $_SESSION['config']->getName() . '/' . $profile . "." . $typeId;
$file = @fopen($path, "w"); $file = @fopen($path, "w");
if ($file) { if ($file) {
// write attributes // write attributes
@ -148,59 +158,113 @@ function saveAccountProfile($attributes, $profile, $scope) {
* Deletes an account profile * Deletes an account profile
* *
* @param string $file name of profile (Without .<scope> extension) * @param string $file name of profile (Without .<scope> extension)
* @param string $scope account type * @param string $typeId account type
* @return boolean true if profile was deleted * @return boolean true if profile was deleted
*/ */
function delAccountProfile($file, $scope) { function delAccountProfile($file, $typeId) {
if (!isLoggedIn()) return false; if (!isLoggedIn()) {
if (!preg_match("/^[0-9a-z _-]+$/i", $file) || !preg_match("/^[a-z]+$/i", $scope)) return false; return false;
$prof = substr(__FILE__, 0, strlen(__FILE__) - 16) . "config/profiles/". $_SESSION['config']->getName() . '/' . $file . "." . $scope; }
$typeManager = new \LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($typeId);
if (!isValidProfileName($file) || !preg_match("/^[a-z0-9_]+$/i", $typeId) || ($type == null)) {
return false;
}
$prof = substr(__FILE__, 0, strlen(__FILE__) - 16) . "config/profiles/". $_SESSION['config']->getName() . '/' . $file . "." . $typeId;
if (is_file($prof)) { if (is_file($prof)) {
return @unlink($prof); return @unlink($prof);
} }
else return false; else return false;
} }
/**
* Returns if the given profile name is valid.
*
* @param string $name profile name
*/
function isValidProfileName($name) {
return preg_match("/^[0-9a-z _-]+$/i", $name);
}
/** /**
* Copies account profiles to other server profiles. * Copies an account profile from the given source to target.
* *
* @param array $accountProfiles account profile names * @param \LAM\TYPES\ConfiguredType $sourceType source type
* @param String $scope account scope * @param string $sourceProfileName profile name
* @param array $dests destinations * @param \LAM\TYPES\ConfiguredType $targetType target type
* * @throws Exception
* @return boolean operation succeeded
*/ */
function copyAccountProfiles($accountProfiles, $scope, $dests = array()) { function copyAccountProfile($sourceType, $sourceProfileName, $targetType) {
$state = true; if (!isValidProfileName($sourceProfileName)) {
$profilePath = substr(__FILE__, 0, strlen(__FILE__) - 17) . '/config/profiles/'; throw new LAMException(_('Failed to copy'));
foreach ($accountProfiles as $profile) { }
//part 1: server profile $sourceConfig = $sourceType->getTypeManager()->getConfig()->getName();
//part 2: account profile $sourceTypeId = $sourceType->getId();
$tmpArr = explode('##', $profile); $targetConfig = $targetType->getTypeManager()->getConfig()->getName();
$src = $profilePath . $tmpArr[0] . '/' . $tmpArr[1] . '.' . $scope; $targetTypeId = $targetType->getId();
if (!empty($dests)) { $profilePath = dirname(__FILE__) . '/../config/profiles/';
foreach ($dests as $dest) { $src = $profilePath . $sourceConfig . '/' . $sourceProfileName . '.' . $sourceTypeId;
if ($dest == 'templates*') { $dst = $profilePath . $targetConfig . '/' . $sourceProfileName . '.' . $targetTypeId;
$dst = substr(__FILE__, 0, strlen(__FILE__) - 17) . '/config/templates/profiles/' . $tmpArr[1] . '.' . $scope; if (!@copy($src, $dst)) {
} else { throw new LAMException(_('Failed to copy'), $sourceConfig . ': ' . $sourceProfileName);
$dst = $profilePath . $dest . '/' . $tmpArr[1] . '.' . $scope; }
} }
if (!@copy($src, $dst)) {
StatusMessage('ERROR', _('Failed to export!'), $tmpArr[1] . '.' . $scope); /**
$state = false; * Copies an account profile from the given source to global templates.
} *
* @param \LAM\TYPES\ConfiguredType $sourceType source type
* @param string $sourceProfileName profile name
* @throws Exception
*/
function copyAccountProfileToTemplates($sourceType, $sourceProfileName) {
if (!isValidProfileName($sourceProfileName)) {
throw new LAMException(_('Failed to copy'));
}
$sourceConfig = $sourceType->getTypeManager()->getConfig()->getName();
$sourceTypeId = $sourceType->getId();
$profilePath = dirname(__FILE__) . '/../config/profiles/';
$templatePath = dirname(__FILE__) . '/../config/templates/profiles/';
$src = $profilePath . $sourceConfig . '/' . $sourceProfileName . '.' . $sourceTypeId;
$dst = $templatePath . $sourceProfileName . '.' . $sourceType->getScope();
if (!@copy($src, $dst)) {
throw new LAMException(_('Failed to copy'), $sourceConfig . ': ' . $sourceProfileName);
}
}
/**
* Installs template profiles to the current server profile.
*/
function installProfileTemplates() {
$templatePath = dirname(__FILE__) . '/../config/templates/profiles';
$templateDir = @dir($templatePath);
$allTemplates = array();
if ($templateDir) {
$entry = $templateDir->read();
while ($entry){
$parts = explode('.', $entry);
if ((strlen($entry) > 3) && (sizeof($parts) == 2)) {
$name = $parts[0];
$scope = $parts[1];
$allTemplates[$scope][] = $name;
} }
} else { $entry = $templateDir->read();
$dst = $profilePath . $_SESSION['config']->getName() . '/' . $tmpArr[1] . '.' . $scope; }
if (!@copy($src, $dst)) { }
StatusMessage('ERROR', _('Failed to import!'), $tmpArr[1] . '.' . $scope); $basePath = dirname(__FILE__) . '/../config/profiles/' . $_SESSION['config']->getName() . '/';
$state = false; $typeManager = new \LAM\TYPES\TypeManager();
foreach ($typeManager->getConfiguredTypes() as $type) {
if (empty($allTemplates[$type->getScope()])) {
continue;
}
foreach ($allTemplates[$type->getScope()] as $templateName) {
$path = $basePath . $templateName . '.' . $type->getId();
if (!is_file($path)) {
$template = $templatePath . '/' . $templateName . '.' . $scope;
@copy($template, $path);
} }
} }
} }
return $state;
} }
?> ?>

View File

@ -1,9 +1,10 @@
<?php <?php
namespace LAM\TOOLS\UPLOAD;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2009 - 2011 Roland Gruber Copyright (C) 2009 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -33,7 +34,7 @@ $Id$
* *
* @package tools * @package tools
*/ */
class toolFileUpload implements LAMTool { class toolFileUpload implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
@ -114,7 +115,9 @@ class toolFileUpload implements LAMTool {
* @return boolean visible * @return boolean visible
*/ */
function isVisible() { function isVisible() {
return (sizeof($_SESSION['config']->get_ActiveTypes()) > 0); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
} }
/** /**

View File

@ -1,20 +1,21 @@
<?php <?php
namespace LAM\TOOLS\MULTI_EDIT;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2013 Roland Gruber Copyright (C) 2013 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -30,56 +31,56 @@ $Id$
/** /**
* Multi edit tool that allows LDAP operations on multiple entries. * Multi edit tool that allows LDAP operations on multiple entries.
* *
* @package tools * @package tools
*/ */
class toolMultiEdit implements LAMTool { class toolMultiEdit implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
* *
* @return string name * @return string name
*/ */
function getName() { function getName() {
return _("Multi edit"); return _("Multi edit");
} }
/** /**
* returns a description text for the tool. * returns a description text for the tool.
* *
* @return string description * @return string description
*/ */
function getDescription() { function getDescription() {
return _("Performs modifications on multiple LDAP entries."); return _("Performs modifications on multiple LDAP entries.");
} }
/** /**
* Returns a link to the tool page (relative to templates/). * Returns a link to the tool page (relative to templates/).
* *
* @return string link * @return string link
*/ */
function getLink() { function getLink() {
return "multiEdit.php"; return "multiEdit.php";
} }
/** /**
* Returns if the tool requires write access to LDAP. * Returns if the tool requires write access to LDAP.
* *
* @return boolean true if write access is needed * @return boolean true if write access is needed
*/ */
function getRequiresWriteAccess() { function getRequiresWriteAccess() {
return true; return true;
} }
/** /**
* Returns if the tool requires password change rights. * Returns if the tool requires password change rights.
* *
* @return boolean true if password change rights are needed * @return boolean true if password change rights are needed
*/ */
function getRequiresPasswordChangeRights() { function getRequiresPasswordChangeRights() {
return true; return true;
} }
/** /**
* Returns the link to the tool image (relative to graphics/) * Returns the link to the tool image (relative to graphics/)
* *
@ -88,7 +89,7 @@ class toolMultiEdit implements LAMTool {
function getImageLink() { function getImageLink() {
return 'edit.png'; return 'edit.png';
} }
/** /**
* Returns the prefered position of this tool on the tools page. * Returns the prefered position of this tool on the tools page.
* The position may be between 0 and 1000. 0 is the top position. * The position may be between 0 and 1000. 0 is the top position.
@ -98,16 +99,16 @@ class toolMultiEdit implements LAMTool {
function getPosition() { function getPosition() {
return 400; return 400;
} }
/** /**
* Returns a list of sub tools or an empty array. * Returns a list of sub tools or an empty array.
* *
* @return array list of subtools (LAMTool) * @return array list of subtools (LAMTool)
*/ */
function getSubTools() { function getSubTools() {
return array(); return array();
} }
/** /**
* Returns if the tool is visible in the menu. * Returns if the tool is visible in the menu.
* *
@ -116,16 +117,16 @@ class toolMultiEdit implements LAMTool {
function isVisible() { function isVisible() {
return true; return true;
} }
/** /**
* Returns if a tool may be hidden by configuration in the LAM server profile. * Returns if a tool may be hidden by configuration in the LAM server profile.
* *
* @return boolean hideable * @return boolean hideable
*/ */
function isHideable() { function isHideable() {
return true; return true;
} }
} }
?> ?>

View File

@ -1,20 +1,21 @@
<?php <?php
namespace LAM\TOOLS\OU_EDIT;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2009 - 2011 Roland Gruber Copyright (C) 2009 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -30,56 +31,56 @@ $Id$
/** /**
* OU editor * OU editor
* *
* @package tools * @package tools
*/ */
class toolOUEditor implements LAMTool { class toolOUEditor implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
* *
* @return string name * @return string name
*/ */
function getName() { function getName() {
return _("OU editor"); return _("OU editor");
} }
/** /**
* returns a description text for the tool. * returns a description text for the tool.
* *
* @return string description * @return string description
*/ */
function getDescription() { function getDescription() {
return _("Manages OU objects in your LDAP tree."); return _("Manages OU objects in your LDAP tree.");
} }
/** /**
* Returns a link to the tool page (relative to templates/). * Returns a link to the tool page (relative to templates/).
* *
* @return string link * @return string link
*/ */
function getLink() { function getLink() {
return "ou_edit.php"; return "ou_edit.php";
} }
/** /**
* Returns if the tool requires write access to LDAP. * Returns if the tool requires write access to LDAP.
* *
* @return boolean true if write access is needed * @return boolean true if write access is needed
*/ */
function getRequiresWriteAccess() { function getRequiresWriteAccess() {
return true; return true;
} }
/** /**
* Returns if the tool requires password change rights. * Returns if the tool requires password change rights.
* *
* @return boolean true if password change rights are needed * @return boolean true if password change rights are needed
*/ */
function getRequiresPasswordChangeRights() { function getRequiresPasswordChangeRights() {
return true; return true;
} }
/** /**
* Returns the link to the tool image (relative to graphics/) * Returns the link to the tool image (relative to graphics/)
* *
@ -88,7 +89,7 @@ class toolOUEditor implements LAMTool {
function getImageLink() { function getImageLink() {
return 'ou.png'; return 'ou.png';
} }
/** /**
* Returns the prefered position of this tool on the tools page. * Returns the prefered position of this tool on the tools page.
* The position may be between 0 and 1000. 0 is the top position. * The position may be between 0 and 1000. 0 is the top position.
@ -98,34 +99,36 @@ class toolOUEditor implements LAMTool {
function getPosition() { function getPosition() {
return 500; return 500;
} }
/** /**
* Returns a list of sub tools or an empty array. * Returns a list of sub tools or an empty array.
* *
* @return array list of subtools (LAMTool) * @return array list of subtools (LAMTool)
*/ */
function getSubTools() { function getSubTools() {
return array(); return array();
} }
/** /**
* Returns if the tool is visible in the menu. * Returns if the tool is visible in the menu.
* *
* @return boolean visible * @return boolean visible
*/ */
function isVisible() { function isVisible() {
return (sizeof($_SESSION['config']->get_ActiveTypes()) > 0); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
} }
/** /**
* Returns if a tool may be hidden by configuration in the LAM server profile. * Returns if a tool may be hidden by configuration in the LAM server profile.
* *
* @return boolean hideable * @return boolean hideable
*/ */
function isHideable() { function isHideable() {
return true; return true;
} }
} }
?> ?>

View File

@ -1,20 +1,21 @@
<?php <?php
namespace LAM\TOOLS\PDF_EDITOR;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2009 - 2011 Roland Gruber Copyright (C) 2009 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -30,56 +31,56 @@ $Id$
/** /**
* PDF editor * PDF editor
* *
* @package tools * @package tools
*/ */
class toolPDFEditor implements LAMTool { class toolPDFEditor implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
* *
* @return string name * @return string name
*/ */
function getName() { function getName() {
return _("PDF editor"); return _("PDF editor");
} }
/** /**
* returns a description text for the tool. * returns a description text for the tool.
* *
* @return string description * @return string description
*/ */
function getDescription() { function getDescription() {
return _("This tool allows you to customize the PDF pages."); return _("This tool allows you to customize the PDF pages.");
} }
/** /**
* Returns a link to the tool page (relative to templates/). * Returns a link to the tool page (relative to templates/).
* *
* @return string link * @return string link
*/ */
function getLink() { function getLink() {
return "pdfedit/pdfmain.php"; return "pdfedit/pdfmain.php";
} }
/** /**
* Returns if the tool requires write access to LDAP. * Returns if the tool requires write access to LDAP.
* *
* @return boolean true if write access is needed * @return boolean true if write access is needed
*/ */
function getRequiresWriteAccess() { function getRequiresWriteAccess() {
return true; return true;
} }
/** /**
* Returns if the tool requires password change rights. * Returns if the tool requires password change rights.
* *
* @return boolean true if password change rights are needed * @return boolean true if password change rights are needed
*/ */
function getRequiresPasswordChangeRights() { function getRequiresPasswordChangeRights() {
return true; return true;
} }
/** /**
* Returns the link to the tool image (relative to graphics/) * Returns the link to the tool image (relative to graphics/)
* *
@ -88,7 +89,7 @@ class toolPDFEditor implements LAMTool {
function getImageLink() { function getImageLink() {
return 'pdf.png'; return 'pdf.png';
} }
/** /**
* Returns the prefered position of this tool on the tools page. * Returns the prefered position of this tool on the tools page.
* The position may be between 0 and 1000. 0 is the top position. * The position may be between 0 and 1000. 0 is the top position.
@ -98,34 +99,36 @@ class toolPDFEditor implements LAMTool {
function getPosition() { function getPosition() {
return 200; return 200;
} }
/** /**
* Returns a list of sub tools or an empty array. * Returns a list of sub tools or an empty array.
* *
* @return array list of subtools (LAMTool) * @return array list of subtools (LAMTool)
*/ */
function getSubTools() { function getSubTools() {
return array(); return array();
} }
/** /**
* Returns if the tool is visible in the menu. * Returns if the tool is visible in the menu.
* *
* @return boolean visible * @return boolean visible
*/ */
function isVisible() { function isVisible() {
return (sizeof($_SESSION['config']->get_ActiveTypes()) > 0); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
} }
/** /**
* Returns if a tool may be hidden by configuration in the LAM server profile. * Returns if a tool may be hidden by configuration in the LAM server profile.
* *
* @return boolean hideable * @return boolean hideable
*/ */
function isHideable() { function isHideable() {
return true; return true;
} }
} }
?> ?>

View File

@ -1,20 +1,21 @@
<?php <?php
namespace LAM\TOOLS\PROFILE_EDITOR;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2009 - 2011 Roland Gruber Copyright (C) 2009 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -30,56 +31,56 @@ $Id$
/** /**
* Profile editor * Profile editor
* *
* @package tools * @package tools
*/ */
class toolProfileEditor implements LAMTool { class toolProfileEditor implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
* *
* @return string name * @return string name
*/ */
function getName() { function getName() {
return _("Profile editor"); return _("Profile editor");
} }
/** /**
* returns a description text for the tool. * returns a description text for the tool.
* *
* @return string description * @return string description
*/ */
function getDescription() { function getDescription() {
return _("Here you can manage your account profiles."); return _("Here you can manage your account profiles.");
} }
/** /**
* Returns a link to the tool page (relative to templates/). * Returns a link to the tool page (relative to templates/).
* *
* @return string link * @return string link
*/ */
function getLink() { function getLink() {
return "profedit/profilemain.php"; return "profedit/profilemain.php";
} }
/** /**
* Returns if the tool requires write access to LDAP. * Returns if the tool requires write access to LDAP.
* *
* @return boolean true if write access is needed * @return boolean true if write access is needed
*/ */
function getRequiresWriteAccess() { function getRequiresWriteAccess() {
return true; return true;
} }
/** /**
* Returns if the tool requires password change rights. * Returns if the tool requires password change rights.
* *
* @return boolean true if password change rights are needed * @return boolean true if password change rights are needed
*/ */
function getRequiresPasswordChangeRights() { function getRequiresPasswordChangeRights() {
return true; return true;
} }
/** /**
* Returns the link to the tool image (relative to graphics/) * Returns the link to the tool image (relative to graphics/)
* *
@ -88,7 +89,7 @@ class toolProfileEditor implements LAMTool {
function getImageLink() { function getImageLink() {
return 'edit.png'; return 'edit.png';
} }
/** /**
* Returns the prefered position of this tool on the tools page. * Returns the prefered position of this tool on the tools page.
* The position may be between 0 and 1000. 0 is the top position. * The position may be between 0 and 1000. 0 is the top position.
@ -98,34 +99,36 @@ class toolProfileEditor implements LAMTool {
function getPosition() { function getPosition() {
return 100; return 100;
} }
/** /**
* Returns a list of sub tools or an empty array. * Returns a list of sub tools or an empty array.
* *
* @return array list of subtools (LAMTool) * @return array list of subtools (LAMTool)
*/ */
function getSubTools() { function getSubTools() {
return array(); return array();
} }
/** /**
* Returns if the tool is visible in the menu. * Returns if the tool is visible in the menu.
* *
* @return boolean visible * @return boolean visible
*/ */
function isVisible() { function isVisible() {
return (sizeof($_SESSION['config']->get_ActiveTypes()) > 0); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
} }
/** /**
* Returns if a tool may be hidden by configuration in the LAM server profile. * Returns if a tool may be hidden by configuration in the LAM server profile.
* *
* @return boolean hideable * @return boolean hideable
*/ */
function isHideable() { function isHideable() {
return true; return true;
} }
} }
?> ?>

View File

@ -1,4 +1,5 @@
<?php <?php
namespace LAM\TOOLS\SCHEMA;
/* /*
$Id$ $Id$
@ -9,12 +10,12 @@ $Id$
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -30,56 +31,56 @@ $Id$
/** /**
* Schema browser * Schema browser
* *
* @package tools * @package tools
*/ */
class toolSchemaBrowser implements LAMTool { class toolSchemaBrowser implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
* *
* @return string name * @return string name
*/ */
function getName() { function getName() {
return _("Schema browser"); return _("Schema browser");
} }
/** /**
* returns a description text for the tool. * returns a description text for the tool.
* *
* @return string description * @return string description
*/ */
function getDescription() { function getDescription() {
return _("Here you can browse LDAP object classes and attributes."); return _("Here you can browse LDAP object classes and attributes.");
} }
/** /**
* Returns a link to the tool page (relative to templates/). * Returns a link to the tool page (relative to templates/).
* *
* @return string link * @return string link
*/ */
function getLink() { function getLink() {
return "schema/schema.php"; return "schema/schema.php";
} }
/** /**
* Returns if the tool requires write access to LDAP. * Returns if the tool requires write access to LDAP.
* *
* @return boolean true if write access is needed * @return boolean true if write access is needed
*/ */
function getRequiresWriteAccess() { function getRequiresWriteAccess() {
return false; return false;
} }
/** /**
* Returns if the tool requires password change rights. * Returns if the tool requires password change rights.
* *
* @return boolean true if password change rights are needed * @return boolean true if password change rights are needed
*/ */
function getRequiresPasswordChangeRights() { function getRequiresPasswordChangeRights() {
return false; return false;
} }
/** /**
* Returns the link to the tool image (relative to graphics/) * Returns the link to the tool image (relative to graphics/)
* *
@ -88,7 +89,7 @@ class toolSchemaBrowser implements LAMTool {
function getImageLink() { function getImageLink() {
return 'schemaBrowser.png'; return 'schemaBrowser.png';
} }
/** /**
* Returns the prefered position of this tool on the tools page. * Returns the prefered position of this tool on the tools page.
* The position may be between 0 and 1000. 0 is the top position. * The position may be between 0 and 1000. 0 is the top position.
@ -98,16 +99,16 @@ class toolSchemaBrowser implements LAMTool {
function getPosition() { function getPosition() {
return 600; return 600;
} }
/** /**
* Returns a list of sub tools or an empty array. * Returns a list of sub tools or an empty array.
* *
* @return array list of subtools (LAMTool) * @return array list of subtools (LAMTool)
*/ */
function getSubTools() { function getSubTools() {
return array(); return array();
} }
/** /**
* Returns if the tool is visible in the menu. * Returns if the tool is visible in the menu.
* *
@ -116,16 +117,16 @@ class toolSchemaBrowser implements LAMTool {
function isVisible() { function isVisible() {
return true; return true;
} }
/** /**
* Returns if a tool may be hidden by configuration in the LAM server profile. * Returns if a tool may be hidden by configuration in the LAM server profile.
* *
* @return boolean hideable * @return boolean hideable
*/ */
function isHideable() { function isHideable() {
return true; return true;
} }
} }
?> ?>

View File

@ -1,20 +1,21 @@
<?php <?php
namespace LAM\TOOLS\SERVER_INFO;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2009 - 2011 Roland Gruber Copyright (C) 2009 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -30,56 +31,56 @@ $Id$
/** /**
* Server information * Server information
* *
* @package tools * @package tools
*/ */
class toolServerInformation implements LAMTool { class toolServerInformation implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
* *
* @return string name * @return string name
*/ */
function getName() { function getName() {
return _("Server information"); return _("Server information");
} }
/** /**
* returns a description text for the tool. * returns a description text for the tool.
* *
* @return string description * @return string description
*/ */
function getDescription() { function getDescription() {
return _("Information about the LDAP server."); return _("Information about the LDAP server.");
} }
/** /**
* Returns a link to the tool page (relative to templates/). * Returns a link to the tool page (relative to templates/).
* *
* @return string link * @return string link
*/ */
function getLink() { function getLink() {
return "serverInfo.php"; return "serverInfo.php";
} }
/** /**
* Returns if the tool requires write access to LDAP. * Returns if the tool requires write access to LDAP.
* *
* @return boolean true if write access is needed * @return boolean true if write access is needed
*/ */
function getRequiresWriteAccess() { function getRequiresWriteAccess() {
return false; return false;
} }
/** /**
* Returns if the tool requires password change rights. * Returns if the tool requires password change rights.
* *
* @return boolean true if password change rights are needed * @return boolean true if password change rights are needed
*/ */
function getRequiresPasswordChangeRights() { function getRequiresPasswordChangeRights() {
return true; return true;
} }
/** /**
* Returns the link to the tool image (relative to graphics/) * Returns the link to the tool image (relative to graphics/)
* *
@ -88,7 +89,7 @@ class toolServerInformation implements LAMTool {
function getImageLink() { function getImageLink() {
return 'tree_info.png'; return 'tree_info.png';
} }
/** /**
* Returns the prefered position of this tool on the tools page. * Returns the prefered position of this tool on the tools page.
* The position may be between 0 and 1000. 0 is the top position. * The position may be between 0 and 1000. 0 is the top position.
@ -98,16 +99,16 @@ class toolServerInformation implements LAMTool {
function getPosition() { function getPosition() {
return 700; return 700;
} }
/** /**
* Returns a list of sub tools or an empty array. * Returns a list of sub tools or an empty array.
* *
* @return array list of subtools (LAMTool) * @return array list of subtools (LAMTool)
*/ */
function getSubTools() { function getSubTools() {
return array(); return array();
} }
/** /**
* Returns if the tool is visible in the menu. * Returns if the tool is visible in the menu.
* *
@ -116,16 +117,16 @@ class toolServerInformation implements LAMTool {
function isVisible() { function isVisible() {
return true; return true;
} }
/** /**
* Returns if a tool may be hidden by configuration in the LAM server profile. * Returns if a tool may be hidden by configuration in the LAM server profile.
* *
* @return boolean hideable * @return boolean hideable
*/ */
function isHideable() { function isHideable() {
return true; return true;
} }
} }
?> ?>

View File

@ -1,20 +1,21 @@
<?php <?php
namespace LAM\TOOLS\TESTS;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2009 - 2011 Roland Gruber Copyright (C) 2009 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or the Free Software Foundation; either version 2 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@ -30,56 +31,56 @@ $Id$
/** /**
* Tests page * Tests page
* *
* @package tools * @package tools
*/ */
class toolTests implements LAMTool { class toolTests implements \LAMTool {
/** /**
* Returns the name of the tool. * Returns the name of the tool.
* *
* @return string name * @return string name
*/ */
function getName() { function getName() {
return _("Tests"); return _("Tests");
} }
/** /**
* returns a description text for the tool. * returns a description text for the tool.
* *
* @return string description * @return string description
*/ */
function getDescription() { function getDescription() {
return _("Here you can test if certain LAM features work on your installation."); return _("Here you can test if certain LAM features work on your installation.");
} }
/** /**
* Returns a link to the tool page (relative to templates/). * Returns a link to the tool page (relative to templates/).
* *
* @return string link * @return string link
*/ */
function getLink() { function getLink() {
return "tests/index.php"; return "tests/index.php";
} }
/** /**
* Returns if the tool requires write access to LDAP. * Returns if the tool requires write access to LDAP.
* *
* @return boolean true if write access is needed * @return boolean true if write access is needed
*/ */
function getRequiresWriteAccess() { function getRequiresWriteAccess() {
return true; return true;
} }
/** /**
* Returns if the tool requires password change rights. * Returns if the tool requires password change rights.
* *
* @return boolean true if password change rights are needed * @return boolean true if password change rights are needed
*/ */
function getRequiresPasswordChangeRights() { function getRequiresPasswordChangeRights() {
return true; return true;
} }
/** /**
* Returns the link to the tool image (relative to graphics/) * Returns the link to the tool image (relative to graphics/)
* *
@ -88,7 +89,7 @@ class toolTests implements LAMTool {
function getImageLink() { function getImageLink() {
return 'tests.png'; return 'tests.png';
} }
/** /**
* Returns the prefered position of this tool on the tools page. * Returns the prefered position of this tool on the tools page.
* The position may be between 0 and 1000. 0 is the top position. * The position may be between 0 and 1000. 0 is the top position.
@ -98,21 +99,21 @@ class toolTests implements LAMTool {
function getPosition() { function getPosition() {
return 1000; return 1000;
} }
/** /**
* Returns a list of sub tools or an empty array. * Returns a list of sub tools or an empty array.
* *
* @return array list of subtools (LAMTool) * @return array list of subtools (LAMTool)
*/ */
function getSubTools() { function getSubTools() {
$return = array(); $return = array();
$lamdaemonTest = new LAMSubTool(); $lamdaemonTest = new \LAMSubTool();
$lamdaemonTest->name = _("Lamdaemon test"); $lamdaemonTest->name = _("Lamdaemon test");
$lamdaemonTest->link = 'tests/lamdaemonTest.php'; $lamdaemonTest->link = 'tests/lamdaemonTest.php';
$lamdaemonTest->description = _("Check if quotas and homedirectories can be managed."); $lamdaemonTest->description = _("Check if quotas and homedirectories can be managed.");
$lamdaemonTest->image = 'lamdaemonSmall.png'; $lamdaemonTest->image = 'lamdaemonSmall.png';
$return[] = $lamdaemonTest; $return[] = $lamdaemonTest;
$schemaTest = new LAMSubTool(); $schemaTest = new \LAMSubTool();
$schemaTest->name = _("Schema test"); $schemaTest->name = _("Schema test");
$schemaTest->link = 'tests/schemaTest.php'; $schemaTest->link = 'tests/schemaTest.php';
$schemaTest->description = _("Check if the LDAP schema fits the requirements of the selected account modules."); $schemaTest->description = _("Check if the LDAP schema fits the requirements of the selected account modules.");
@ -120,25 +121,27 @@ class toolTests implements LAMTool {
$return[] = $schemaTest; $return[] = $schemaTest;
return $return; return $return;
} }
/** /**
* Returns if the tool is visible in the menu. * Returns if the tool is visible in the menu.
* *
* @return boolean visible * @return boolean visible
*/ */
function isVisible() { function isVisible() {
return (sizeof($_SESSION['config']->get_ActiveTypes()) > 0); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
} }
/** /**
* Returns if a tool may be hidden by configuration in the LAM server profile. * Returns if a tool may be hidden by configuration in the LAM server profile.
* *
* @return boolean hideable * @return boolean hideable
*/ */
function isHideable() { function isHideable() {
return true; return true;
} }
} }
?> ?>

View File

@ -73,16 +73,21 @@ function getTypes() {
* Returns the alias name of an account type. * Returns the alias name of an account type.
* *
* @param string $type type name * @param string $type type name
* @param \LAMConfig $config config (optional, uses $_SESSION['config'] by default)
* @return string type alias * @return string type alias
*/ */
function getTypeAlias($type) { function getTypeAlias($type, $config = null) {
if (!empty($_SESSION['config'])) { if (($config == null) && !empty($_SESSION['config'])) {
$typeSettings = $_SESSION['config']->get_typeSettings(); $config = $_SESSION['config'];
}
if ($config != null) {
$typeSettings = $config->get_typeSettings();
if (!empty($typeSettings['customLabel_' . $type])) { if (!empty($typeSettings['customLabel_' . $type])) {
return $typeSettings['customLabel_' . $type]; return $typeSettings['customLabel_' . $type];
} }
} }
$obj = new $type(); $scope = getScopeFromTypeId($type);
$obj = new $scope();
return $obj->getAlias(); return $obj->getAlias();
} }
@ -132,6 +137,17 @@ function getListAttributeDescriptions($type) {
return $obj->getListAttributeDescriptions(); return $obj->getListAttributeDescriptions();
} }
/**
* Returns the account type for a given type id.
*
* @param string $typeId type id (e.g. user_1)
* @return string scope (e.g. user)
*/
function getScopeFromTypeId($typeId) {
$parts = explode('_', $typeId);
return $parts[0];
}
/** /**
* Represents a configured account type variant. * Represents a configured account type variant.
* *
@ -144,42 +160,46 @@ class ConfiguredType {
private $id; private $id;
private $suffix; private $suffix = null;
private $attributes; private $attributes = null;
private $alias; private $alias = null;
private $ldapFilter; private $additionalLdapFilter = null;
private $hidden; private $hidden = null;
private $baseType;
private $typeManager;
/** /**
* Constructor * Constructor
* *
* @param TypeManager $typeManager type manager
* @param string $scope account type * @param string $scope account type
* @param string $id unique ID for this configuration * @param string $id unique ID for this configuration
* @param string $suffix LDAP base suffix
* @param array $attributes list of ListAttribute
* @param string $alias alias name for display
* @param string $ldapFilter additional LDAP filter
* @param boolean $hidden hidden in GUI
*/ */
public function __construct($scope, $id, $suffix, $attributes, $alias, public function __construct(&$typeManager, $scope, $id) {
$ldapFilter, $hidden) { $this->typeManager = &$typeManager;
$this->scope = $scope; $this->scope = $scope;
$this->id = $id; $this->id = $id;
$this->suffix = $suffix; }
$this->attributes = $attributes;
$this->alias = $alias; /**
$this->ldapFilter = $ldapFilter; * Returns the owning type manager.
$this->hidden = $hidden; *
* @return TypeManager type manager
*/
public function getTypeManager() {
return $this->typeManager;
} }
/** /**
* Returns the account type (e.g. 'user'). * Returns the account type (e.g. 'user').
* *
* @return string $scope account type * @return string account type
*/ */
public function getScope() { public function getScope() {
return $this->scope; return $this->scope;
@ -188,7 +208,7 @@ class ConfiguredType {
/** /**
* Returns a unique id for this configuration. * Returns a unique id for this configuration.
* *
* @return string $id unique id * @return string unique id
*/ */
public function getId() { public function getId() {
return $this->id; return $this->id;
@ -197,48 +217,128 @@ class ConfiguredType {
/** /**
* Returns the LDAP suffix. * Returns the LDAP suffix.
* *
* @return string $suffix LDAP suffix * @return string LDAP suffix
*/ */
public function getSuffix() { public function getSuffix() {
if ($this->suffix !== null) {
return $this->suffix;
}
$this->suffix = $this->typeManager->getConfig()->get_Suffix($this->id);
return $this->suffix; return $this->suffix;
} }
/** /**
* Returns a list of configured attributes. * Returns a list of configured attributes.
* *
* @return array $attributes list of ListAttribute * @return ListAttribute[] list of ListAttribute
*/ */
public function getAttributes() { public function getAttributes() {
if ($this->attributes !== null) {
return $this->attributes;
}
$attributeString = $this->typeManager->getConfig()->get_listAttributes($this->id);
$attributeSpecs = explode(';', $attributeString);
$attributes = array();
foreach ($attributeSpecs as $attributeSpec) {
$attributes[] = new ListAttribute($attributeSpec, $this->scope);
}
$this->attributes = $attributes;
return $this->attributes; return $this->attributes;
} }
/** /**
* Returns the alias name. * Returns the alias name.
* *
* @return string $alias alias name * @return string alias name
*/ */
public function getAlias() { public function getAlias() {
if ($this->alias !== null) {
return $this->alias;
}
$this->alias = getTypeAlias($this->id, $this->typeManager->getConfig());
return $this->alias; return $this->alias;
} }
/** /**
* Returns the additional LDAP filter. * Returns the additional LDAP filter.
* *
* @return string $ldapFilter LDAP filter * @return string LDAP filter
*/ */
public function getLdapFilter() { public function getAdditionalLdapFilter() {
return $this->ldapFilter; if ($this->additionalLdapFilter !== null) {
return $this->additionalLdapFilter;
}
$this->additionalLdapFilter = $this->typeManager->getConfig()->get_Suffix($typeId);
return $this->additionalLdapFilter;
} }
/** /**
* Returns if this configuration is hidden. * Returns if this configuration is hidden.
* *
* @return boolean $hidden hidden * @return boolean hidden
*/ */
public function isHidden() { public function isHidden() {
if ($this->hidden !== null) {
return $this->hidden;
}
$this->hidden = isAccountTypeHidden($this->id);
return $this->hidden; return $this->hidden;
} }
/**
* Returns the base type of this configured type.
*
* @return \baseType base type
*/
public function getBaseType() {
if ($this->baseType != null) {
return $this->baseType;
}
$scope = $this->scope;
$this->baseType = new $scope();
return $this->baseType;
}
/**
* Returns a list of LDAP suffixes for this type.
*
* @return array sorted list of possible suffixes for this type.
*/
public function getSuffixList() {
$connection = $_SESSION["ldap"]->server();
$ret = array();
$filter = $this->getBaseType()->getSuffixFilter();
$sr = @ldap_search($connection, escapeDN($this->getSuffix()), $filter, array('dn', 'objectClass'), 0, 0, 0, LDAP_DEREF_NEVER);
if ($sr) {
$units = ldap_get_entries($connection, $sr);
cleanLDAPResult($units);
// extract Dns
$count = sizeof($units);
for ($i = 0; $i < $count; $i++) {
if (in_array('container', $units[$i]['objectclass'])) {
// Active Directory fix, hide system containers
if (preg_match('/.*cn=system,dc=.+/i', $units[$i]['dn']) || preg_match('/.*CN=program data,dc=.+/i', $units[$i]['dn'])) {
continue;
}
}
$ret[] = $units[$i]['dn'];
}
}
// add root suffix if needed
$found = false;
for ($i = 0; $i < sizeof($ret); $i++) { // search suffix case-intensitive
if (strtolower($this->getSuffix()) == strtolower($ret[$i])) {
$found = true;
break;
}
}
if (!$found) {
$ret[] = $this->getSuffix();
}
usort($ret, 'compareDN');
return $ret;
}
} }
/** /**
@ -314,6 +414,35 @@ class ListAttribute {
*/ */
class TypeManager { class TypeManager {
private $config;
/**
* Constructor
*
* @param \LAMConfig $config configuration (uses $_SESSION['config'] by default)
*/
public function __construct(&$config = null) {
if ($config == null) {
$config = &$_SESSION['config'];
}
$this->config = &$config;
}
/**
* Returns the configured type with the given id or null.
*
* @param string $typeId type id
* @return \LAM\TYPES\ConfiguredType|NULL type
*/
public function getConfiguredType($typeId) {
$configuredTypes = array();
$activeTypes = $this->config->get_ActiveTypes();
if (in_array($typeId, $activeTypes)) {
return $this->buildConfiguredType($typeId);
}
return null;
}
/** /**
* Returns a list of configured account types. * Returns a list of configured account types.
* *
@ -321,44 +450,64 @@ class TypeManager {
*/ */
public function getConfiguredTypes() { public function getConfiguredTypes() {
$configuredTypes = array(); $configuredTypes = array();
$activeTypes = $_SESSION['config']->get_ActiveTypes(); $activeTypes = $this->config->get_ActiveTypes();
foreach ($activeTypes as $typeId) { foreach ($activeTypes as $typeId) {
$configuredTypes[] = $this->buildConfiguredType($typeId); $configuredTypes[] = $this->buildConfiguredType($typeId);
} }
return $configuredTypes; return $configuredTypes;
} }
/**
* Returns a list of configured types for this scope.
*
* @param string $scope scope (e.g. user)
* @return \LAM\TYPES\ConfiguredType[] list of ConfiguredType
*/
public function getConfiguredTypesForScope($scope) {
$allTypes = $this->getConfiguredTypes();
$scopedTypes = array();
foreach ($allTypes as $type) {
if ($type->getScope() == $scope) {
$scopedTypes[] = $type;
}
}
return $scopedTypes;
}
/** /**
* Builds a configured account type. * Builds a configured account type.
* *
* @param string $typeId type id * @param string $typeId type id
*/ */
private function buildConfiguredType($typeId) { private function buildConfiguredType($typeId) {
$parts = explode('_', $typeId); $scope = getScopeFromTypeId($typeId);
$scope = $parts[0]; return new ConfiguredType($this, $scope, $typeId);
$suffix = $_SESSION['config']->get_Suffix($typeId);
$attributes = $this->getAttributes($typeId, $scope);
$alias = getTypeAlias($typeId);
$ldapFilter = $_SESSION['config']->get_Suffix($typeId);
$hidden = isAccountTypeHidden($typeId);
return new ConfiguredType($scope, $typeId, $suffix, $attributes, $alias, $ldapFilter, $hidden);
} }
/** /**
* Builds the list of account list attributes. * Generates a new unique type id for the given scope.
* *
* @param string $typeId type id * @param string $scope account type (e.g. user)
* @param string $scope account type
* @return \LAM\TYPES\ListAttribute[] list attributes
*/ */
private function getAttributes($typeId, $scope) { public function generateNewTypeId($scope) {
$attributeString = $_SESSION['config']->get_listAttributes($typeId); $activeTypes = $this->config->get_ActiveTypes();
$attributeSpecs = explode(';', $attributeString); if (!in_array($scope, $activeTypes)) {
$attributes = array(); return $scope;
foreach ($attributeSpecs as $attributeSpec) {
$attributes[] = new ListAttribute($attributeSpec, $scope);
} }
return $attributes; $counter = 1;
while (in_array($scope . '_' . $counter, $activeTypes)) {
$counter++;
}
return $scope . '_' . $counter;
}
/**
* Returns the associated config object.
*
* @return \LAMConfig config
*/
public function getConfig() {
return $this->config;
} }
} }

View File

@ -5,7 +5,7 @@
This code is part of LDAP Account Manager (http://www.sourceforge.net/projects/lam) This code is part of LDAP Account Manager (http://www.sourceforge.net/projects/lam)
Copyright (C) 2009 - 2012 Pozdnyak Pavel Copyright (C) 2009 - 2012 Pozdnyak Pavel
2010 - 2013 Roland Gruber 2010 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -160,14 +160,14 @@ class lamAsteriskExtList extends lamList {
/** /**
* Groups the extensions. * Groups the extensions.
* *
* (non-PHPdoc) * (non-PHPdoc)
* @see lamList::listRefreshData() * @see lamList::listRefreshData()
*/ */
protected function listRefreshData() { protected function listRefreshData() {
parent::listRefreshData(); parent::listRefreshData();
// configure search filter // configure search filter
$module_filter = get_ldap_filter($this->type); // basic filter is provided by modules $module_filter = get_ldap_filter($this->type->getId()); // basic filter is provided by modules
$filter = "(&" . $module_filter . $this->buildLDAPAttributeFilter() . ")"; $filter = "(&" . $module_filter . $this->buildLDAPAttributeFilter() . ")";
$attrs = $this->attrArray; $attrs = $this->attrArray;
$attrs[] = "astpriority"; $attrs[] = "astpriority";
@ -176,17 +176,16 @@ class lamAsteriskExtList extends lamList {
if ($lastError != null) { if ($lastError != null) {
call_user_func_array('StatusMessage', $lastError); call_user_func_array('StatusMessage', $lastError);
} }
$entries = $this->normalizeLdapOutput($entries); $entries = $this->normalizeLdapOutput($entries);
$this->entries = $entries; $this->entries = $entries;
// generate list of possible suffixes // generate list of possible suffixes
$typeObj = new $this->type(); $this->possibleSuffixes = $this->type->getSuffixList();
$this->possibleSuffixes = $typeObj->getSuffixList();
} }
/** /**
* Groups the extensions. * Groups the extensions.
* *
* @param array $entries extension entries * @param array $entries extension entries
*/ */
private function normalizeLdapOutput($entries){ private function normalizeLdapOutput($entries){
@ -198,7 +197,7 @@ class lamAsteriskExtList extends lamList {
} }
return array_values($entries); return array_values($entries);
} }
} }
?> ?>

View File

@ -4,7 +4,7 @@ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2008 Thomas Manninger Copyright (C) 2008 Thomas Manninger
2009 - 2014 Roland Gruber 2009 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -37,7 +37,7 @@ $Id$
**/ **/
class dhcp extends baseType { class dhcp extends baseType {
/** /**
* Constructs a new DHCP type object. * Constructs a new DHCP type object.
*/ */
@ -46,7 +46,7 @@ class dhcp extends baseType {
$this->LABEL_CREATE_ANOTHER_ACCOUNT = _('Create another DHCP entry'); $this->LABEL_CREATE_ANOTHER_ACCOUNT = _('Create another DHCP entry');
$this->LABEL_BACK_TO_ACCOUNT_LIST = _('Back to DHCP list'); $this->LABEL_BACK_TO_ACCOUNT_LIST = _('Back to DHCP list');
} }
/** /**
* Returns the alias name of this account type. * Returns the alias name of this account type.
* *
@ -220,7 +220,7 @@ class lamDHCPList extends lamList {
// Search after the fixed ip entry // Search after the fixed ip entry
if (is_array($entry['dhcpstatements'])) { if (is_array($entry['dhcpstatements'])) {
foreach($entry['dhcpstatements'] AS $id => $value) { foreach($entry['dhcpstatements'] AS $id => $value) {
if (!is_array($value) && array_shift( explode(" ", $value) ) == "fixed-address") { if (!is_array($value) && array_shift( explode(" ", $value) ) == "fixed-address") {
$ip = explode(" ", $value); $ip = explode(" ", $value);
echo $ip['1']; echo $ip['1'];
@ -260,15 +260,15 @@ class lamDHCPList extends lamList {
parent::listPrintTableCellContent($entry, $attribute); parent::listPrintTableCellContent($entry, $attribute);
} }
} }
/** /**
* Add DCP main settings button. * Add DCP main settings button.
* *
* @param htmlGroup $left left part * @param htmlGroup $left left part
* @param htmlGroup $right right part * @param htmlGroup $right right part
*/ */
protected function addExtraInputElementsToTopArea(&$left, &$right) { protected function addExtraInputElementsToTopArea(&$left, &$right) {
if (checkIfWriteAccessIsAllowed($this->type)) { if (checkIfWriteAccessIsAllowed($this->type->getId())) {
$left->addElement(new htmlSpacer('20px', null)); $left->addElement(new htmlSpacer('20px', null));
$dhcpButton = new htmlButton('dhcpDefaults', $this->labels['dhcpDefaults']); $dhcpButton = new htmlButton('dhcpDefaults', $this->labels['dhcpDefaults']);
$dhcpButton->setIconClass('settingsButton'); $dhcpButton->setIconClass('settingsButton');
@ -278,7 +278,7 @@ class lamDHCPList extends lamList {
/** /**
* Manages all POST actions (e.g. button pressed) for the account lists. * Manages all POST actions (e.g. button pressed) for the account lists.
* *
* @return String HTML fragment to insert into beginning of account list * @return String HTML fragment to insert into beginning of account list
*/ */
function listDoPost() { function listDoPost() {

View File

@ -829,10 +829,10 @@ class lamUserList extends lamList {
_('Locked') => self::FILTER_LOCKED _('Locked') => self::FILTER_LOCKED
); );
$filterInput = new htmlSelect('filter' . strtolower($attrName), $filterOptions, array($value)); $filterInput = new htmlSelect('filter' . strtolower($attrName), $filterOptions, array($value));
$filterInput->setCSSClasses(array($this->type . '-dark')); $filterInput->setCSSClasses(array($this->type->getScope() . '-dark'));
$filterInput->setHasDescriptiveElements(true); $filterInput->setHasDescriptiveElements(true);
$filterInput->setOnchangeEvent('document.getElementsByName(\'apply_filter\')[0].click();'); $filterInput->setOnchangeEvent('document.getElementsByName(\'apply_filter\')[0].click();');
parseHtml(null, $filterInput, array(), false, $this->tabindex, $this->type); parseHtml(null, $filterInput, array(), false, $this->tabindex, $this->type->getScope());
} }
/** /**

View File

@ -112,13 +112,6 @@ function upgradeConfigToServerProfileFolders($profiles) {
return; return;
} }
// copy default configs
if (!file_exists('../config/templates')) {
@mkdir('../config/templates', 0700);
recursiveCopy('../config/pdf/', '../config/templates/pdf/', $profiles, 'default.');
recursiveCopy('../config/profiles/', '../config/templates/profiles/', $profiles, 'default.');
}
foreach ($profiles as $profile) { foreach ($profiles as $profile) {
// upgrade PDF configs // upgrade PDF configs
$dir = '../config/pdf/' . $profile; $dir = '../config/pdf/' . $profile;

View File

@ -6,7 +6,7 @@ use accountContainer;
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2016 Roland Gruber Copyright (C) 2016 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -46,7 +46,7 @@ class Uploader {
private $accounts = null; private $accounts = null;
private $data = null; private $data = null;
private $scope = null; private $type = null;
private $endTime; private $endTime;
const TIME_LIMIT = 10; const TIME_LIMIT = 10;
@ -61,11 +61,13 @@ class Uploader {
/** /**
* Constructor * Constructor
*
* @param \LAM\TYPES\ConfiguredType $type account type
*/ */
public function __construct($scope) { public function __construct($type) {
$this->accounts = unserialize(lamDecrypt($_SESSION['mass_accounts'])); $this->accounts = unserialize(lamDecrypt($_SESSION['mass_accounts']));
$this->data = unserialize(lamDecrypt($_SESSION['mass_data'])); $this->data = unserialize(lamDecrypt($_SESSION['mass_data']));
$this->scope = $scope; $this->type = $type;
$startTime = time(); $startTime = time();
$maxTime = get_cfg_var('max_execution_time') - 5; $maxTime = get_cfg_var('max_execution_time') - 5;
if ($maxTime > Uploader::TIME_LIMIT) $maxTime = Uploader::TIME_LIMIT; if ($maxTime > Uploader::TIME_LIMIT) $maxTime = Uploader::TIME_LIMIT;
@ -131,7 +133,7 @@ class Uploader {
$preAttributes[$key] = &$attrs[$key]; $preAttributes[$key] = &$attrs[$key];
} }
$preAttributes['dn'] = &$dn; $preAttributes['dn'] = &$dn;
$preMessages = doUploadPreActions($this->scope, $_SESSION['mass_selectedModules'], $preAttributes); $preMessages = doUploadPreActions($this->type->getScope(), $_SESSION['mass_selectedModules'], $preAttributes);
$preActionOk = true; $preActionOk = true;
for ($i = 0; $i < sizeof($preMessages); $i++) { for ($i = 0; $i < sizeof($preMessages); $i++) {
if (($preMessages[$i][0] == 'ERROR') || ($preMessages[$i][0] == 'WARN')) { if (($preMessages[$i][0] == 'ERROR') || ($preMessages[$i][0] == 'WARN')) {
@ -202,7 +204,7 @@ class Uploader {
'pdfFinished' => $pdfFinished, 'pdfFinished' => $pdfFinished,
'allDone' => $allDone, 'allDone' => $allDone,
'errorHtml' => $errorHtml, 'errorHtml' => $errorHtml,
'scope' => $this->scope 'typeId' => $this->type->getId()
); );
return json_encode($status); return json_encode($status);
} }
@ -211,10 +213,10 @@ class Uploader {
* Checks for security violations and stops processing if needed. * Checks for security violations and stops processing if needed.
*/ */
private function securityCheck() { private function securityCheck() {
if (!isLoggedIn() || empty($this->scope) if (!isLoggedIn() || empty($this->type)
|| isAccountTypeHidden($this->scope) || $this->type->isHidden()
|| !checkIfNewEntriesAreAllowed($this->scope) || !checkIfNewEntriesAreAllowed($this->type->getId())
|| !checkIfWriteAccessIsAllowed($this->scope)) { || !checkIfWriteAccessIsAllowed($this->type->getId())) {
die; die;
} }
} }
@ -229,7 +231,7 @@ class Uploader {
while (!isset($_SESSION['mass_postActions']['finished']) && ($this->endTime > time())) { while (!isset($_SESSION['mass_postActions']['finished']) && ($this->endTime > time())) {
$return = $this->runModulePostActions(); $return = $this->runModulePostActions();
} }
$title = _("Additional tasks for module:") . ' ' . getModuleAlias($return['module'], $this->scope); $title = _("Additional tasks for module:") . ' ' . getModuleAlias($return['module'], $this->type->getScope());
$progress = round($return['progress'], 2); $progress = round($return['progress'], 2);
$finished = isset($_SESSION['mass_postActions']['finished']); $finished = isset($_SESSION['mass_postActions']['finished']);
return $this->buildUploadStatus(100, true, $title, $progress, $finished); return $this->buildUploadStatus(100, true, $title, $progress, $finished);
@ -241,7 +243,7 @@ class Uploader {
* @return array status array * @return array status array
*/ */
private function runModulePostActions() { private function runModulePostActions() {
$return = doUploadPostActions($this->scope, $this->data, $_SESSION['mass_ids'], $_SESSION['mass_failed'], $_SESSION['mass_selectedModules'], $this->accounts); $return = doUploadPostActions($this->type->getScope(), $this->data, $_SESSION['mass_ids'], $_SESSION['mass_failed'], $_SESSION['mass_selectedModules'], $this->accounts);
if ($return['status'] == 'finished') { if ($return['status'] == 'finished') {
$_SESSION['mass_postActions']['finished'] = true; $_SESSION['mass_postActions']['finished'] = true;
} }
@ -283,7 +285,8 @@ class Uploader {
} }
} }
// load account // load account
$_SESSION['mass_pdfAccount'] = new accountContainer($this->scope, 'mass_pdfAccount'); $typeManager = new \LAM\TYPES\TypeManager();
$_SESSION['mass_pdfAccount'] = new accountContainer($this->type, 'mass_pdfAccount');
$pdfErrors = $_SESSION['mass_pdfAccount']->load_account($dn, $infoAttributes); $pdfErrors = $_SESSION['mass_pdfAccount']->load_account($dn, $infoAttributes);
if (sizeof($pdfErrors) > 0) { if (sizeof($pdfErrors) > 0) {
$_SESSION['mass_errors'] = array_merge($_SESSION['mass_errors'], $pdfErrors); $_SESSION['mass_errors'] = array_merge($_SESSION['mass_errors'], $pdfErrors);

View File

@ -1,9 +1,11 @@
<?php <?php
namespace LAM\PDF;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Michael Duergner Copyright (C) 2003 - 2006 Michael Duergner
2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -22,44 +24,44 @@ $Id$
/** /**
* Simple XML parser. * Simple XML parser.
* *
* @author Michael Duergner * @author Michael Duergner
* @package PDF * @package PDF
*/ */
/** /**
* Simple XML parser. * Simple XML parser.
* *
* @author Michael Duergner * @author Michael Duergner
* @package PDF * @package PDF
*/ */
class xmlParser { class xmlParser {
/** XML parser */ /** XML parser */
private $xmlParser; private $xmlParser;
/** /**
* Constructor * Constructor
*/ */
function __construct() { function __construct() {
$this->xmlParser = xml_parser_create(); $this->xmlParser = xml_parser_create();
xml_set_object($this->xmlParser,$this); xml_set_object($this->xmlParser, $this);
xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, 1); xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, 1);
xml_parser_set_option($this->xmlParser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->xmlParser, XML_OPTION_SKIP_WHITE, 1);
} }
/** /**
* Starts the parsing. * Starts the parsing.
* *
* @param String $filename file name * @param String $filename file name
* @return array XML structure * @return array XML structure
*/ */
function parse($filename) { function parse($filename) {
if(file_exists($filename)) { if(file_exists($filename)) {
$xmlStructure = array(); $xmlStructure = array();
$xmlIndex = array(); $xmlIndex = array();
xml_parse_into_struct($this->xmlParser,implode("\n",file($filename)),$xmlStructure,$xmlIndex); xml_parse_into_struct($this->xmlParser, implode("\n", file($filename)), $xmlStructure, $xmlIndex);
return array($xmlStructure,$xmlIndex); return array($xmlStructure, $xmlIndex);
} }
return array(); return array();
} }

View File

@ -4,7 +4,7 @@ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Tilo Lutz Copyright (C) 2003 - 2006 Tilo Lutz
2005 - 2015 Roland Gruber 2005 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -57,14 +57,13 @@ if (!isLoggedIn()) {
// Set correct language, codepages, .... // Set correct language, codepages, ....
setlanguage(); setlanguage();
$typeManager = new LAM\TYPES\TypeManager();
//load account //load account
if (isset($_GET['DN'])) { if (isset($_GET['DN'])) {
$type = $typeManager->getConfiguredType($_GET['type']);
$DN = str_replace("\\'", '', $_GET['DN']); $DN = str_replace("\\'", '', $_GET['DN']);
$type = str_replace("\\'", '', $_GET['type']); if ($type->isHidden()) {
if ($_GET['type'] == $type) $type = str_replace("'", '',$_GET['type']); logNewMessage(LOG_ERR, 'User tried to access hidden account type: ' . $type->getId());
if (isAccountTypeHidden($type)) {
logNewMessage(LOG_ERR, 'User tried to access hidden account type: ' . $type);
die(); die();
} }
if ($_GET['DN'] == $DN) { if ($_GET['DN'] == $DN) {
@ -75,10 +74,10 @@ if (isset($_GET['DN'])) {
$DN = substr($DN, 0, -1); $DN = substr($DN, 0, -1);
} }
} }
$suffix = strtolower($_SESSION['config']->get_Suffix($type)); $suffix = strtolower($type->getSuffix());
$DNlower = strtolower($DN); $DNlower = strtolower($DN);
if (strpos($DNlower, $suffix) !== (strlen($DNlower) - strlen($suffix))) { if (strpos($DNlower, $suffix) !== (strlen($DNlower) - strlen($suffix))) {
logNewMessage(LOG_ERR, 'User tried to access entry of type ' . $type . ' outside suffix ' . $suffix); logNewMessage(LOG_ERR, 'User tried to access entry of type ' . $type->getId() . ' outside suffix ' . $suffix);
die(); die();
} }
$_SESSION['account'] = new accountContainer($type, 'account', getRandomNumber()); $_SESSION['account'] = new accountContainer($type, 'account', getRandomNumber());
@ -94,14 +93,13 @@ if (isset($_GET['DN'])) {
} }
// new account // new account
else if (count($_POST)==0) { else if (count($_POST)==0) {
$type = str_replace("\\'", '', $_GET['type']); $type = $typeManager->getConfiguredType($_GET['type']);
if ($_GET['type'] == $type) $type = str_replace("'", '',$_GET['type']); if ($type->isHidden()) {
if (isAccountTypeHidden($type)) { logNewMessage(LOG_ERR, 'User tried to access hidden account type: ' . $type->getId());
logNewMessage(LOG_ERR, 'User tried to access hidden account type: ' . $type);
die(); die();
} }
elseif (!checkIfNewEntriesAreAllowed($type)) { elseif (!checkIfNewEntriesAreAllowed($type->getId())) {
logNewMessage(LOG_ERR, 'User tried to create entry of forbidden account type: ' . $type); logNewMessage(LOG_ERR, 'User tried to create entry of forbidden account type: ' . $type->getId());
die(); die();
} }
$_SESSION['account'] = new accountContainer($type, 'account', getRandomNumber()); $_SESSION['account'] = new accountContainer($type, 'account', getRandomNumber());

View File

@ -1,4 +1,16 @@
<?php <?php
namespace LAM\CONFIG;
use \htmlTable;
use \htmlOutputText;
use \htmlHelpLink;
use \htmlHiddenInput;
use \htmlButton;
use \htmlSpacer;
use \htmlElement;
use \htmlImage;
use \htmlSortableList;
use \htmlSubTitle;
use \htmlDiv;
/* /*
$Id$ $Id$
@ -95,8 +107,6 @@ if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
} }
} }
$types = $conf->get_ActiveTypes();
echo $_SESSION['header']; echo $_SESSION['header'];
echo "<title>" . _("LDAP Account Manager Configuration") . "</title>\n"; echo "<title>" . _("LDAP Account Manager Configuration") . "</title>\n";
@ -209,15 +219,12 @@ jQuery(document).ready(function() {
<div class="ui-tabs-panel ui-widget-content ui-corner-bottom user-bright"> <div class="ui-tabs-panel ui-widget-content ui-corner-bottom user-bright">
<?php <?php
$typeManager = new \LAM\TYPES\TypeManager($conf);
$account_list = array(); $types = $typeManager->getConfiguredTypes();
for ($i = 0; $i < sizeof($types); $i++) {
$account_list[] = array($types[$i], LAM\TYPES\getTypeAlias($types[$i]));
}
$container = new htmlTable(); $container = new htmlTable();
for ($i = 0; $i < sizeof($account_list); $i++) { foreach ($types as $type) {
config_showAccountModules($account_list[$i][0], $account_list[$i][1], $container); config_showAccountModules($type, $container);
} }
$legendContainer = new htmlTable(); $legendContainer = new htmlTable();
@ -260,20 +267,19 @@ echo "</html>\n";
/** /**
* Displays the module selection boxes and checks if dependencies are fulfilled. * Displays the module selection boxes and checks if dependencies are fulfilled.
* *
* @param string $scope account type * @param \LAM\TYPES\ConfiguredType $type account type
* @param string $title title for module selection (e.g. "User modules")
* @param htmlTable $container meta HTML container * @param htmlTable $container meta HTML container
*/ */
function config_showAccountModules($scope, $title, &$container) { function config_showAccountModules($type, &$container) {
$conf = &$_SESSION['conf_config']; $conf = &$_SESSION['conf_config'];
$typeSettings = $conf->get_typeSettings(); $typeSettings = $conf->get_typeSettings();
// account modules // account modules
$available = getAvailableModules($scope, true); $available = getAvailableModules($type->getScope(), true);
$selected = !empty($typeSettings['modules_' . $scope]) ? $typeSettings['modules_' . $scope] : ''; $selected = !empty($typeSettings['modules_' . $type->getId()]) ? $typeSettings['modules_' . $type->getId()] : '';
$selected = explode(',', $selected); $selected = explode(',', $selected);
$sortedAvailable = array(); $sortedAvailable = array();
for ($i = 0; $i < sizeof($available); $i++) { for ($i = 0; $i < sizeof($available); $i++) {
$sortedAvailable[$available[$i]] = getModuleAlias($available[$i], $scope); $sortedAvailable[$available[$i]] = getModuleAlias($available[$i], $type->getScope());
} }
natcasesort($sortedAvailable); natcasesort($sortedAvailable);
@ -281,18 +287,18 @@ function config_showAccountModules($scope, $title, &$container) {
$selOptions = array(); $selOptions = array();
for ($i = 0; $i < sizeof($selected); $i++) { for ($i = 0; $i < sizeof($selected); $i++) {
if (in_array($selected[$i], $available)) { // selected modules must be available if (in_array($selected[$i], $available)) { // selected modules must be available
if (is_base_module($selected[$i], $scope)) { // mark base modules if (is_base_module($selected[$i], $type->getScope())) { // mark base modules
$selOptions[getModuleAlias($selected[$i], $scope) . " (" . $selected[$i] . ")(*)"] = $selected[$i]; $selOptions[getModuleAlias($selected[$i], $type->getScope()) . " (" . $selected[$i] . ")(*)"] = $selected[$i];
} }
else { else {
$selOptions[getModuleAlias($selected[$i], $scope) . " (" . $selected[$i] . ")"] = $selected[$i]; $selOptions[getModuleAlias($selected[$i], $type->getScope()) . " (" . $selected[$i] . ")"] = $selected[$i];
} }
} }
} }
$availOptions = array(); $availOptions = array();
foreach ($sortedAvailable as $key => $value) { foreach ($sortedAvailable as $key => $value) {
if (! in_array($key, $selected)) { // display non-selected modules if (! in_array($key, $selected)) { // display non-selected modules
if (is_base_module($key, $scope)) { // mark base modules if (is_base_module($key, $type->getScope())) { // mark base modules
$availOptions[$value . " (" . $key . ")(*)"] = $key; $availOptions[$value . " (" . $key . ")(*)"] = $key;
} }
else { else {
@ -302,7 +308,7 @@ function config_showAccountModules($scope, $title, &$container) {
} }
// add account module selection // add account module selection
$container->addElement(new htmlSubTitle($title, '../../graphics/' . $scope . '.png'), true); $container->addElement(new htmlSubTitle($type->getAlias(), '../../graphics/' . $type->getScope() . '.png'), true);
$container->addElement(new htmlOutputText(_("Selected modules"))); $container->addElement(new htmlOutputText(_("Selected modules")));
$container->addElement(new htmlOutputText('')); $container->addElement(new htmlOutputText(''));
$container->addElement(new htmlOutputText(_("Available modules")), true); $container->addElement(new htmlOutputText(_("Available modules")), true);
@ -313,17 +319,17 @@ function config_showAccountModules($scope, $title, &$container) {
$listElements = array(); $listElements = array();
foreach ($selOptions as $key => $value) { foreach ($selOptions as $key => $value) {
$el = new htmlTable('100%'); $el = new htmlTable('100%');
$mod = new $value($scope); $mod = new $value($type->getScope());
$el->addElement(new htmlImage('../../graphics/' . $mod->getIcon(), '16px', '16px')); $el->addElement(new htmlImage('../../graphics/' . $mod->getIcon(), '16px', '16px'));
$el->addElement(new htmlOutputText($key)); $el->addElement(new htmlOutputText($key));
$delButton = new htmlButton('del_' . $scope . '_' . $value, 'del.png', true); $delButton = new htmlButton('del_' . $type->getId() . '_' . $value, 'del.png', true);
$delButton->alignment = htmlElement::ALIGN_RIGHT; $delButton->alignment = htmlElement::ALIGN_RIGHT;
$el->addElement($delButton); $el->addElement($delButton);
$listElements[] = $el; $listElements[] = $el;
} }
$selSortable = new htmlSortableList($listElements, $scope . '_selected', '350px'); $selSortable = new htmlSortableList($listElements, $type->getId() . '_selected', '350px');
$selSortable->alignment = htmlElement::ALIGN_TOP; $selSortable->alignment = htmlElement::ALIGN_TOP;
$selSortable->setOnUpdate('updateModulePositions(\'positions_' . $scope . '\', ui.item.data(\'posOrig\'), ui.item.index());'); $selSortable->setOnUpdate('updateModulePositions(\'positions_' . $type->getId() . '\', ui.item.data(\'posOrig\'), ui.item.index());');
$container->addElement($selSortable); $container->addElement($selSortable);
} }
else { else {
@ -335,10 +341,10 @@ function config_showAccountModules($scope, $title, &$container) {
if (sizeof($availOptions) > 0) { if (sizeof($availOptions) > 0) {
$availTable = new htmlTable(); $availTable = new htmlTable();
foreach ($availOptions as $text => $key) { foreach ($availOptions as $text => $key) {
$mod = new $key($scope); $mod = new $key($type->getScope());
$availTable->addElement(new htmlImage('../../graphics/' . $mod->getIcon(), '16px', '16px')); $availTable->addElement(new htmlImage('../../graphics/' . $mod->getIcon(), '16px', '16px'));
$availTable->addElement(new htmlOutputText($text)); $availTable->addElement(new htmlOutputText($text));
$addButton = new htmlButton('add_' . $scope . '_' . $key, 'add.png', true); $addButton = new htmlButton('add_' . $type->getId() . '_' . $key, 'add.png', true);
$addButton->alignment = htmlElement::ALIGN_RIGHT; $addButton->alignment = htmlElement::ALIGN_RIGHT;
$availTable->addElement($addButton, true); $availTable->addElement($addButton, true);
} }
@ -351,7 +357,7 @@ function config_showAccountModules($scope, $title, &$container) {
for ($i = 0; $i < sizeof($selOptions); $i++) { for ($i = 0; $i < sizeof($selOptions); $i++) {
$positions[] = $i; $positions[] = $i;
} }
$container->addElement(new htmlHiddenInput('positions_' . $scope, implode(',', $positions)), true); $container->addElement(new htmlHiddenInput('positions_' . $type->getId(), implode(',', $positions)), true);
// spacer to next account type // spacer to next account type
$container->addElement(new htmlSpacer(null, '30px'), true); $container->addElement(new htmlSpacer(null, '30px'), true);
} }
@ -368,11 +374,13 @@ function checkInput() {
$errors = array(); $errors = array();
$conf = &$_SESSION['conf_config']; $conf = &$_SESSION['conf_config'];
$typeSettings = $conf->get_typeSettings(); $typeSettings = $conf->get_typeSettings();
$accountTypes = $conf->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager($conf);
for ($t = 0; $t < sizeof($accountTypes); $t++) { $accountTypes = $typeManager->getConfiguredTypes();
$scope = $accountTypes[$t]; foreach ($accountTypes as $type) {
$scope = $type->getScope();
$typeId = $type->getId();
$available = getAvailableModules($scope, true); $available = getAvailableModules($scope, true);
$selected_temp = (isset($typeSettings['modules_' . $scope])) ? $typeSettings['modules_' . $scope] : ''; $selected_temp = (isset($typeSettings['modules_' . $typeId])) ? $typeSettings['modules_' . $typeId] : '';
$selected_temp = explode(',', $selected_temp); $selected_temp = explode(',', $selected_temp);
$selected = array(); $selected = array();
// only use available modules as selected // only use available modules as selected
@ -382,7 +390,7 @@ function checkInput() {
} }
} }
// reorder based on sortable list // reorder based on sortable list
$sorting = $_POST['positions_' . $scope]; $sorting = $_POST['positions_' . $typeId];
if (!empty($sorting)) { if (!empty($sorting)) {
$sorting = explode(',', $sorting); $sorting = explode(',', $sorting);
$sortTmp = array(); $sortTmp = array();
@ -394,17 +402,17 @@ function checkInput() {
// remove modules from selection // remove modules from selection
$new_selected = array(); $new_selected = array();
for ($i = 0; $i < sizeof($selected); $i++) { for ($i = 0; $i < sizeof($selected); $i++) {
if (!isset($_POST['del_' . $scope . '_' . $selected[$i]])) { if (!isset($_POST['del_' . $typeId . '_' . $selected[$i]])) {
$new_selected[] = $selected[$i]; $new_selected[] = $selected[$i];
} }
} }
$selected = $new_selected; $selected = $new_selected;
$typeSettings['modules_' . $scope] = implode(',', $selected); $typeSettings['modules_' . $typeId] = implode(',', $selected);
// add modules to selection // add modules to selection
foreach ($available as $modName) { foreach ($available as $modName) {
if (isset($_POST['add_' . $scope . '_' . $modName])) { if (isset($_POST['add_' . $typeId . '_' . $modName])) {
$selected[] = $modName; $selected[] = $modName;
$typeSettings['modules_' . $scope] = implode(',', $selected); $typeSettings['modules_' . $typeId] = implode(',', $selected);
break; break;
} }
} }
@ -412,7 +420,7 @@ function checkInput() {
$depends = check_module_depends($selected, getModulesDependencies($scope)); $depends = check_module_depends($selected, getModulesDependencies($scope));
if ($depends != false) { if ($depends != false) {
for ($i = 0; $i < sizeof($depends); $i++) { for ($i = 0; $i < sizeof($depends); $i++) {
$errors[] = array('ERROR', LAM\TYPES\getTypeAlias($scope), _("Unsolved dependency:") . ' ' . $errors[] = array('ERROR', $type->getAlias(), _("Unsolved dependency:") . ' ' .
$depends[$i][0] . " (" . $depends[$i][1] . ")"); $depends[$i][0] . " (" . $depends[$i][1] . ")");
} }
} }
@ -420,7 +428,7 @@ function checkInput() {
$conflicts = check_module_conflicts($selected, getModulesDependencies($scope)); $conflicts = check_module_conflicts($selected, getModulesDependencies($scope));
if ($conflicts != false) { if ($conflicts != false) {
for ($i = 0; $i < sizeof($conflicts); $i++) { for ($i = 0; $i < sizeof($conflicts); $i++) {
$errors[] = array('ERROR', LAM\TYPES\getTypeAlias($scope), _("Conflicting module:") . ' ' . $errors[] = array('ERROR', $type->getAlias(), _("Conflicting module:") . ' ' .
$conflicts[$i][0] . " (" . $conflicts[$i][1] . ")"); $conflicts[$i][0] . " (" . $conflicts[$i][1] . ")");
} }
} }
@ -432,7 +440,7 @@ function checkInput() {
} }
} }
if ($baseCount != 1) { if ($baseCount != 1) {
$errors[] = array('ERROR', LAM\TYPES\getTypeAlias($scope), _("No or more than one base module selected!")); $errors[] = array('ERROR', $type->getAlias(), _("No or more than one base module selected!"));
} }
} }
$conf->set_typeSettings($typeSettings); $conf->set_typeSettings($typeSettings);

View File

@ -1,4 +1,16 @@
<?php <?php
namespace LAM\CONFIG;
use \htmlTable;
use \htmlSubTitle;
use \htmlImage;
use \htmlOutputText;
use \htmlSpacer;
use \htmlButton;
use \htmlElement;
use \htmlGroup;
use \htmlTableExtendedInputField;
use \LAMConfig;
use \htmlTableExtendedInputCheckbox;
/* /*
$Id$ $Id$
@ -105,15 +117,22 @@ if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
} }
$typeSettings = $conf->get_typeSettings(); $typeSettings = $conf->get_typeSettings();
$allTypes = LAM\TYPES\getTypes(); $allScopes = \LAM\TYPES\getTypes();
$activeTypes = $conf->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager($conf);
$availableTypes = array(); $activeTypes = $typeManager->getConfiguredTypes();
for ($i = 0; $i < sizeof($allTypes); $i++) { $activeScopes = array();
if (!in_array($allTypes[$i], $activeTypes)) { foreach ($activeTypes as $activeType) {
$availableTypes[$allTypes[$i]] = LAM\TYPES\getTypeAlias($allTypes[$i]); $activeScopes[] = $activeType->getScope();
}
$activeScopes = array_unique($activeScopes);
$availableScopes = array();
foreach ($allScopes as $scope) {
$scopeObj = new $scope();
if (!in_array($scope, $activeScopes) || $scopeObj->supportsMultipleConfigs()) {
$availableScopes[$scope] = $scopeObj->getAlias();
} }
} }
natcasesort($availableTypes); natcasesort($availableScopes);
echo $_SESSION['header']; echo $_SESSION['header'];
@ -223,14 +242,14 @@ jQuery(document).ready(function() {
$container = new htmlTable(); $container = new htmlTable();
// show available types // show available types
if (sizeof($availableTypes) > 0) { if (sizeof($availableScopes) > 0) {
$container->addElement(new htmlSubTitle(_("Available account types")), true); $container->addElement(new htmlSubTitle(_("Available account types")), true);
$availableContainer = new htmlTable(); $availableContainer = new htmlTable();
foreach ($availableTypes as $key => $value) { foreach ($availableScopes as $key => $value) {
$availableContainer->addElement(new htmlImage('../../graphics/' . $key . '.png')); $availableContainer->addElement(new htmlImage('../../graphics/' . $key . '.png'));
$availableContainer->addElement(new htmlOutputText($value)); $availableContainer->addElement(new htmlOutputText($value));
$availableContainer->addElement(new htmlSpacer('10px', null)); $availableContainer->addElement(new htmlSpacer('10px', null));
$availableContainer->addElement(new htmlOutputText(LAM\TYPES\getTypeDescription($key))); $availableContainer->addElement(new htmlOutputText(\LAM\TYPES\getTypeDescription($key)));
$button = new htmlButton('add_' . $key, 'add.png', true); $button = new htmlButton('add_' . $key, 'add.png', true);
$button->setTitle(_("Add")); $button->setTitle(_("Add"));
$availableContainer->addElement($button, true); $availableContainer->addElement($button, true);
@ -244,59 +263,58 @@ $_SESSION['conftypes_optionTypes'] = array();
if (sizeof($activeTypes) > 0) { if (sizeof($activeTypes) > 0) {
$container->addElement(new htmlSubTitle(_("Active account types")), true); $container->addElement(new htmlSubTitle(_("Active account types")), true);
$activeContainer = new htmlTable(); $activeContainer = new htmlTable();
for ($i = 0; $i < sizeof($activeTypes); $i++) { foreach ($activeTypes as $activeType) {
// title // title
$titleGroup = new htmlGroup(); $titleGroup = new htmlGroup();
$titleGroup->colspan = 6; $titleGroup->colspan = 6;
$titleGroup->addElement(new htmlImage('../../graphics/' . $activeTypes[$i] . '.png')); $titleGroup->addElement(new htmlImage('../../graphics/' . $activeType->getScope() . '.png'));
$titleText = new htmlOutputText(LAM\TYPES\getTypeAlias($activeTypes[$i])); $titleText = new htmlOutputText($activeType->getAlias());
$titleText->setIsBold(true); $titleText->setIsBold(true);
$titleGroup->addElement($titleText); $titleGroup->addElement($titleText);
$titleGroup->addElement(new htmlSpacer('10px', null)); $titleGroup->addElement(new htmlSpacer('10px', null));
$titleGroup->addElement(new htmlOutputText(LAM\TYPES\getTypeDescription($activeTypes[$i]))); $titleGroup->addElement(new htmlOutputText($activeType->getBaseType()->getDescription()));
$activeContainer->addElement($titleGroup); $activeContainer->addElement($titleGroup);
// delete button // delete button
$delButton = new htmlButton('rem_'. $activeTypes[$i], 'del.png', true); $delButton = new htmlButton('rem_'. $activeType->getId(), 'del.png', true);
$delButton->alignment = htmlElement::ALIGN_RIGHT; $delButton->alignment = htmlElement::ALIGN_RIGHT;
$delButton->setTitle(_("Remove this account type")); $delButton->setTitle(_("Remove this account type"));
$activeContainer->addElement($delButton, true); //del.png $activeContainer->addElement($delButton, true); //del.png
$activeContainer->addElement(new htmlSpacer(null, '5px'), true); $activeContainer->addElement(new htmlSpacer(null, '5px'), true);
// LDAP suffix // LDAP suffix
$suffixInput = new htmlTableExtendedInputField(_("LDAP suffix"), 'suffix_' . $activeTypes[$i], $typeSettings['suffix_' . $activeTypes[$i]], '202'); $suffixInput = new htmlTableExtendedInputField(_("LDAP suffix"), 'suffix_' . $activeType->getId(), $typeSettings['suffix_' . $activeType->getId()], '202');
$suffixInput->setFieldSize(40); $suffixInput->setFieldSize(40);
$activeContainer->addElement($suffixInput); $activeContainer->addElement($suffixInput);
$activeContainer->addElement(new htmlSpacer('20px', null)); $activeContainer->addElement(new htmlSpacer('20px', null));
// list attributes // list attributes
if (isset($typeSettings['attr_' . $activeTypes[$i]])) { if (isset($typeSettings['attr_' . $activeType->getId()])) {
$attributes = $typeSettings['attr_' . $activeTypes[$i]]; $attributes = $typeSettings['attr_' . $activeType->getId()];
} }
else { else {
$attributes = LAM\TYPES\getDefaultListAttributes($activeTypes[$i]); $attributes = \LAM\TYPES\getDefaultListAttributes($activeType->getScope());
} }
$attrsInput = new htmlTableExtendedInputField(_("List attributes"), 'attr_' . $activeTypes[$i], $attributes, '206'); $attrsInput = new htmlTableExtendedInputField(_("List attributes"), 'attr_' . $activeType->getId(), $attributes, '206');
$attrsInput->setFieldSize(40); $attrsInput->setFieldSize(40);
$attrsInput->setFieldMaxLength(1000); $attrsInput->setFieldMaxLength(1000);
$activeContainer->addElement($attrsInput, true); $activeContainer->addElement($attrsInput, true);
// custom label // custom label
$customLabel = ''; $customLabel = '';
if (isset($typeSettings['customLabel_' . $activeTypes[$i]])) { if (isset($typeSettings['customLabel_' . $activeType->getId()])) {
$customLabel = $typeSettings['customLabel_' . $activeTypes[$i]]; $customLabel = $typeSettings['customLabel_' . $activeType->getId()];
} }
$customLabelInput = new htmlTableExtendedInputField(_('Custom label'), 'customLabel_' . $activeTypes[$i], $customLabel, '264'); $customLabelInput = new htmlTableExtendedInputField(_('Custom label'), 'customLabel_' . $activeType->getId(), $customLabel, '264');
$customLabelInput->setFieldSize(40); $customLabelInput->setFieldSize(40);
$activeContainer->addElement($customLabelInput); $activeContainer->addElement($customLabelInput);
$activeContainer->addElement(new htmlSpacer('20px', null)); $activeContainer->addElement(new htmlSpacer('20px', null));
// LDAP filter // LDAP filter
$filter = ''; $filter = '';
if (isset($typeSettings['filter_' . $activeTypes[$i]])) { if (isset($typeSettings['filter_' . $activeType->getId()])) {
$filter = $typeSettings['filter_' . $activeTypes[$i]]; $filter = $typeSettings['filter_' . $activeType->getId()];
} }
$filterInput = new htmlTableExtendedInputField(_("Additional LDAP filter"), 'filter_' . $activeTypes[$i], $filter, '260'); $filterInput = new htmlTableExtendedInputField(_("Additional LDAP filter"), 'filter_' . $activeType->getId(), $filter, '260');
$filterInput->setFieldSize(40); $filterInput->setFieldSize(40);
$activeContainer->addElement($filterInput, true); $activeContainer->addElement($filterInput, true);
// type options // type options
$typeObj = new $activeTypes[$i]; $typeConfigOptions = $activeType->getBaseType()->get_configOptions();
$typeConfigOptions = $typeObj->get_configOptions();
if (!empty($typeConfigOptions)) { if (!empty($typeConfigOptions)) {
foreach ($typeConfigOptions as $typeConfigOption) { foreach ($typeConfigOptions as $typeConfigOption) {
$activeContainer->addElement($typeConfigOption, true); $activeContainer->addElement($typeConfigOption, true);
@ -314,35 +332,35 @@ if (sizeof($activeTypes) > 0) {
// read-only // read-only
if (isLAMProVersion() && ($conf->getAccessLevel() == LAMConfig::ACCESS_ALL)) { if (isLAMProVersion() && ($conf->getAccessLevel() == LAMConfig::ACCESS_ALL)) {
$isReadOnly = false; $isReadOnly = false;
if (isset($typeSettings['readOnly_' . $activeTypes[$i]])) { if (isset($typeSettings['readOnly_' . $activeType->getId()])) {
$isReadOnly = $typeSettings['readOnly_' . $activeTypes[$i]]; $isReadOnly = $typeSettings['readOnly_' . $activeType->getId()];
} }
$readOnly = new htmlTableExtendedInputCheckbox('readOnly_' . $activeTypes[$i], $isReadOnly, _('Read-only'), '265'); $readOnly = new htmlTableExtendedInputCheckbox('readOnly_' . $activeType->getId(), $isReadOnly, _('Read-only'), '265');
$readOnly->setElementsToDisable(array('hideNewButton_' . $activeTypes[$i], 'hideDeleteButton_' . $activeTypes[$i])); $readOnly->setElementsToDisable(array('hideNewButton_' . $activeType->getId(), 'hideDeleteButton_' . $activeType->getId()));
$advancedOptions->addElement($readOnly); $advancedOptions->addElement($readOnly);
$advancedOptions->addElement(new htmlSpacer('20px', null)); $advancedOptions->addElement(new htmlSpacer('20px', null));
} }
// hidden type // hidden type
$hidden = false; $hidden = false;
if (isset($typeSettings['hidden_' . $activeTypes[$i]])) { if (isset($typeSettings['hidden_' . $activeType->getId()])) {
$hidden = $typeSettings['hidden_' . $activeTypes[$i]]; $hidden = $typeSettings['hidden_' . $activeType->getId()];
} }
$advancedOptions->addElement(new htmlTableExtendedInputCheckbox('hidden_' . $activeTypes[$i], $hidden, _('Hidden'), '261')); $advancedOptions->addElement(new htmlTableExtendedInputCheckbox('hidden_' . $activeType->getId(), $hidden, _('Hidden'), '261'));
if (isLAMProVersion() && ($conf->getAccessLevel() == LAMConfig::ACCESS_ALL)) { if (isLAMProVersion() && ($conf->getAccessLevel() == LAMConfig::ACCESS_ALL)) {
$advancedOptions->addElement(new htmlSpacer('20px', null)); $advancedOptions->addElement(new htmlSpacer('20px', null));
// hide button to create new accounts // hide button to create new accounts
$hideNewButton = false; $hideNewButton = false;
if (isset($typeSettings['hideNewButton_' . $activeTypes[$i]])) { if (isset($typeSettings['hideNewButton_' . $activeType->getId()])) {
$hideNewButton = $typeSettings['hideNewButton_' . $activeTypes[$i]]; $hideNewButton = $typeSettings['hideNewButton_' . $activeType->getId()];
} }
$advancedOptions->addElement(new htmlTableExtendedInputCheckbox('hideNewButton_' . $activeTypes[$i], $hideNewButton, _('No new entries'), '262')); $advancedOptions->addElement(new htmlTableExtendedInputCheckbox('hideNewButton_' . $activeType->getId(), $hideNewButton, _('No new entries'), '262'));
$advancedOptions->addElement(new htmlSpacer('20px', null)); $advancedOptions->addElement(new htmlSpacer('20px', null));
// hide button to delete accounts // hide button to delete accounts
$hideDeleteButton = false; $hideDeleteButton = false;
if (isset($typeSettings['hideDeleteButton_' . $activeTypes[$i]])) { if (isset($typeSettings['hideDeleteButton_' . $activeType->getId()])) {
$hideDeleteButton = $typeSettings['hideDeleteButton_' . $activeTypes[$i]]; $hideDeleteButton = $typeSettings['hideDeleteButton_' . $activeType->getId()];
} }
$advancedOptions->addElement(new htmlTableExtendedInputCheckbox('hideDeleteButton_' . $activeTypes[$i], $hideDeleteButton, _('Disallow delete'), '263'), true); $advancedOptions->addElement(new htmlTableExtendedInputCheckbox('hideDeleteButton_' . $activeType->getId(), $hideDeleteButton, _('Disallow delete'), '263'), true);
} }
$activeContainer->addElement($advancedOptions, true); $activeContainer->addElement($advancedOptions, true);
@ -391,6 +409,7 @@ function checkInput() {
} }
$errors = array(); $errors = array();
$conf = &$_SESSION['conf_config']; $conf = &$_SESSION['conf_config'];
$typeManager = new \LAM\TYPES\TypeManager($conf);
$typeSettings = $conf->get_typeSettings(); $typeSettings = $conf->get_typeSettings();
$accountTypes = $conf->get_ActiveTypes(); $accountTypes = $conf->get_ActiveTypes();
$postKeys = array_keys($_POST); $postKeys = array_keys($_POST);
@ -404,17 +423,12 @@ function checkInput() {
$accountTypes = array_flip($accountTypes); $accountTypes = array_flip($accountTypes);
$accountTypes = array_values($accountTypes); $accountTypes = array_values($accountTypes);
} }
// check if add button was pressed
else if (substr($key, 0, 4) == "add_") {
$type = substr($key, 4);
$accountTypes[] = $type;
}
// set suffixes // set suffixes
elseif (substr($key, 0, 7) == "suffix_") { elseif (substr($key, 0, 7) == "suffix_") {
$typeSettings[$key] = trim($_POST[$key]); $typeSettings[$key] = trim($_POST[$key]);
$type = substr($postKeys[$i], 7); $type = substr($postKeys[$i], 7);
if (strlen($_POST[$key]) < 1) { if (strlen($_POST[$key]) < 1) {
$errors[] = array("ERROR", _("LDAP Suffix is invalid!"), LAM\TYPES\getTypeAlias($type)); $errors[] = array("ERROR", _("LDAP Suffix is invalid!"), \LAM\TYPES\getTypeAlias($type));
} }
} }
// set attributes // set attributes
@ -422,7 +436,7 @@ function checkInput() {
$typeSettings[$key] = $_POST[$key]; $typeSettings[$key] = $_POST[$key];
$type = substr($postKeys[$i], 5); $type = substr($postKeys[$i], 5);
if (!is_string($_POST[$key]) || !preg_match("/^((#[^:;]+)|([^:;]*:[^:;]+))(;((#[^:;]+)|([^:;]*:[^:;]+)))*$/", $_POST[$key])) { if (!is_string($_POST[$key]) || !preg_match("/^((#[^:;]+)|([^:;]*:[^:;]+))(;((#[^:;]+)|([^:;]*:[^:;]+)))*$/", $_POST[$key])) {
$errors[] = array("ERROR", _("List attributes are invalid!"), LAM\TYPES\getTypeAlias($type)); $errors[] = array("ERROR", _("List attributes are invalid!"), \LAM\TYPES\getTypeAlias($type));
} }
} }
// set filter // set filter
@ -435,28 +449,36 @@ function checkInput() {
} }
} }
$typeConfigOptions = extractConfigOptionsFromPOST($_SESSION['conftypes_optionTypes']); $typeConfigOptions = extractConfigOptionsFromPOST($_SESSION['conftypes_optionTypes']);
for ($i = 0; $i < sizeof($accountTypes); $i++) { foreach ($accountTypes as $accountType) {
// set hidden // set hidden
$key = "hidden_" . $accountTypes[$i]; $key = "hidden_" . $accountType;
$typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on')); $typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on'));
if (isLAMProVersion() && ($conf->getAccessLevel() == LAMConfig::ACCESS_ALL)) { if (isLAMProVersion() && ($conf->getAccessLevel() == LAMConfig::ACCESS_ALL)) {
// set if new entries are allowed // set if new entries are allowed
$key = "hideNewButton_" . $accountTypes[$i]; $key = "hideNewButton_" . $accountType;
$typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on')); $typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on'));
// set if deletion of entries is allowed // set if deletion of entries is allowed
$key = "hideDeleteButton_" . $accountTypes[$i]; $key = "hideDeleteButton_" . $accountType;
$typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on')); $typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on'));
// set if account type is read-only // set if account type is read-only
$key = "readOnly_" . $accountTypes[$i]; $key = "readOnly_" . $accountType;
$typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on')); $typeSettings[$key] = (isset($_POST[$key]) && ($_POST[$key] == 'on'));
} }
// check dynamic type settings // check dynamic type settings
$typeObj = new $accountTypes[$i]; $typeObj = $typeManager->getConfiguredType($accountType)->getBaseType();
$typeMessages = $typeObj->check_configOptions($typeConfigOptions); $typeMessages = $typeObj->check_configOptions($typeConfigOptions);
if (!empty($typeMessages)) { if (!empty($typeMessages)) {
$errors = array_merge($errors, $typeMessages); $errors = array_merge($errors, $typeMessages);
} }
} }
// new type
foreach ($_POST as $key => $value) {
// check if add button was pressed
if (substr($key, 0, 4) == "add_") {
$scope = substr($key, 4);
$accountTypes[] = $typeManager->generateNewTypeId($scope);
}
}
// add dynamic type settings // add dynamic type settings
foreach ($typeConfigOptions as $key => $value) { foreach ($typeConfigOptions as $key => $value) {
$typeSettings[$key] = implode(LAMConfig::LINE_SEPARATOR, $value); $typeSettings[$key] = implode(LAMConfig::LINE_SEPARATOR, $value);

View File

@ -1,4 +1,9 @@
<?php <?php
namespace LAM\CONFIG;
use \moduleCache;
use \htmlSpacer;
use \htmlTable;
use \htmlButton;
/* /*
$Id$ $Id$
@ -94,7 +99,7 @@ if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
} }
} }
$allTypes = LAM\TYPES\getTypes(); $allTypes = \LAM\TYPES\getTypes();
echo $_SESSION['header']; echo $_SESSION['header'];
@ -203,13 +208,16 @@ jQuery(document).ready(function() {
// module settings // module settings
$types = $conf->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager($conf);
$types = $typeManager->getConfiguredTypes();
// get list of scopes of modules // get list of scopes of modules
$scopes = array(); $scopes = array();
for ($m = 0; $m < sizeof($types); $m++) { foreach ($types as $type) {
$mods = $conf->get_AccountModules($types[$m]); $mods = $conf->get_AccountModules($type->getId());
for ($i = 0; $i < sizeof($mods); $i++) $scopes[$mods[$i]][] = $types[$m]; for ($i = 0; $i < sizeof($mods); $i++) {
$scopes[$mods[$i]][] = $type->getScope();
}
} }
// get module options // get module options
@ -281,7 +289,8 @@ function checkInput() {
return array(); return array();
} }
$conf = &$_SESSION['conf_config']; $conf = &$_SESSION['conf_config'];
$types = $conf->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager($conf);
$types = $typeManager->getConfiguredTypes();
// check module options // check module options
// create option array to check and save // create option array to check and save
@ -289,9 +298,11 @@ function checkInput() {
// get list of scopes of modules // get list of scopes of modules
$scopes = array(); $scopes = array();
for ($m = 0; $m < sizeof($types); $m++) { foreach ($types as $type) {
$mods = $conf->get_AccountModules($types[$m]); $mods = $conf->get_AccountModules($type->getId());
for ($i = 0; $i < sizeof($mods); $i++) $scopes[$mods[$i]][] = $types[$m]; for ($i = 0; $i < sizeof($mods); $i++) {
$scopes[$mods[$i]][] = $type->getScope();
}
} }
// check options // check options
$errors = checkConfigOptions($scopes, $options); $errors = checkConfigOptions($scopes, $options);

View File

@ -1,10 +1,11 @@
<?php <?php
namespace LAM\DELETE;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Tilo Lutz Copyright (C) 2003 - 2006 Tilo Lutz
Copyright (C) 2007 - 2016 Roland Gruber Copyright (C) 2007 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -66,18 +67,22 @@ if (!empty($_POST)) {
validateSecurityToken(); validateSecurityToken();
} }
if (isset($_POST['type']) && !preg_match('/^[a-z0-9_]+$/i', $_POST['type'])) { $typeManager = new \LAM\TYPES\TypeManager();
if (isset($_POST['type']) && ($typeManager->getConfiguredType($_POST['type']) == null)) {
logNewMessage(LOG_ERR, 'Invalid type: ' . $_POST['type']); logNewMessage(LOG_ERR, 'Invalid type: ' . $_POST['type']);
die(); die();
} }
if (isset($_GET['type']) && isset($_SESSION['delete_dn'])) { if (isset($_GET['type']) && isset($_SESSION['delete_dn'])) {
if (!preg_match('/^[a-z0-9_]+$/i', $_GET['type'])) { $typeId = $_GET['type'];
logNewMessage(LOG_ERR, 'Invalid type: ' . $_GET['type']); $type = $typeManager->getConfiguredType($typeId);
if ($type == null) {
logNewMessage(LOG_ERR, 'Invalid type: ' . $type->getId());
die(); die();
} }
if (!checkIfDeleteEntriesIsAllowed($_GET['type']) || !checkIfWriteAccessIsAllowed($_GET['type'])) { if (!checkIfDeleteEntriesIsAllowed($type->getId()) || !checkIfWriteAccessIsAllowed($type->getId())) {
logNewMessage(LOG_ERR, 'User tried to delete entries of forbidden type '. $_GET['type']); logNewMessage(LOG_ERR, 'User tried to delete entries of forbidden type '. $type->getId());
die(); die();
} }
// Create account list // Create account list
@ -88,14 +93,14 @@ if (isset($_GET['type']) && isset($_SESSION['delete_dn'])) {
} }
//load account //load account
$_SESSION['account'] = new accountContainer($_GET['type'], 'account'); $_SESSION['account'] = new \accountContainer($type, 'account');
// Show HTML Page // Show HTML Page
include 'main_header.php'; include 'main_header.php';
echo "<div class=\"".$_GET['type']."-bright smallPaddingContent\">"; echo "<div class=\"" . $type->getScope() . "-bright smallPaddingContent\">";
echo "<br>\n"; echo "<br>\n";
echo "<form action=\"delete.php\" method=\"post\">\n"; echo "<form action=\"delete.php\" method=\"post\">\n";
echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">'; echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">';
echo "<input name=\"type\" type=\"hidden\" value=\"" . $_GET['type'] . "\">\n"; echo "<input name=\"type\" type=\"hidden\" value=\"" . $type->getId() . "\">\n";
echo "<b>" . _("Do you really want to remove the following accounts?") . "</b>"; echo "<b>" . _("Do you really want to remove the following accounts?") . "</b>";
echo "<br><br>\n"; echo "<br><br>\n";
echo "<table border=0>\n"; echo "<table border=0>\n";
@ -116,12 +121,12 @@ if (isset($_GET['type']) && isset($_SESSION['delete_dn'])) {
echo "<br>\n"; echo "<br>\n";
// Print delete rows from modules // Print delete rows from modules
echo "<table border=0 width=\"100%\">\n<tr><td valign=\"top\" width=\"15%\" >"; echo "<table border=0 width=\"100%\">\n<tr><td valign=\"top\" width=\"15%\" >";
$modules = $_SESSION['config']->get_AccountModules($_GET['type']); $modules = $_SESSION['config']->get_AccountModules($type->getId());
$values = array(); $values = array();
$tabindex = 100; $tabindex = 100;
foreach ($modules as $module) { foreach ($modules as $module) {
$module = moduleCache::getModule($module, $_GET['type']); $module = \moduleCache::getModule($module, $type->getScope());
parseHtml(get_class($module), $module->display_html_delete(), $values, true, $tabindex, $_GET['type']); parseHtml(get_class($module), $module->display_html_delete(), $values, true, $tabindex, $type->getScope());
} }
echo "</table>\n"; echo "</table>\n";
echo "<br>\n"; echo "<br>\n";
@ -130,7 +135,7 @@ if (isset($_GET['type']) && isset($_SESSION['delete_dn'])) {
echo "</form>\n"; echo "</form>\n";
echo "</div>\n"; echo "</div>\n";
?> ?>
<script type="text/javascript" language="javascript"> <script type="text/javascript">
jQuery(document).ready(function() { jQuery(document).ready(function() {
jQuery('#submitButton').button(); jQuery('#submitButton').button();
jQuery('#cancelButton').button(); jQuery('#cancelButton').button();
@ -150,16 +155,18 @@ elseif (isset($_POST['cancelAllOk'])) {
} }
if (isset($_POST['delete'])) { if (isset($_POST['delete'])) {
if (!checkIfDeleteEntriesIsAllowed($_POST['type']) || !checkIfWriteAccessIsAllowed($_POST['type'])) { $typeId = $_POST['type'];
logNewMessage(LOG_ERR, 'User tried to delete entries of forbidden type '. $_POST['type']); $type = $typeManager->getConfiguredType($typeId);
if (!checkIfDeleteEntriesIsAllowed($type->getId()) || !checkIfWriteAccessIsAllowed($type->getId())) {
logNewMessage(LOG_ERR, 'User tried to delete entries of forbidden type '. $type->getId());
die(); die();
} }
// Show HTML Page // Show HTML Page
include 'main_header.php'; include 'main_header.php';
echo "<form action=\"delete.php\" method=\"post\">\n"; echo "<form action=\"delete.php\" method=\"post\">\n";
echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">'; echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">';
echo "<input name=\"type\" type=\"hidden\" value=\"" . $_POST['type'] . "\">\n"; echo "<input name=\"type\" type=\"hidden\" value=\"" . $type->getId() . "\">\n";
echo "<div class=\"".$_POST['type']."-bright smallPaddingContent\"><br>\n"; echo "<div class=\"" . $type->getScope() . "-bright smallPaddingContent\"><br>\n";
echo "<br>\n"; echo "<br>\n";
// Delete dns // Delete dns
@ -301,7 +308,7 @@ if (isset($_POST['delete'])) {
echo "</div>\n"; echo "</div>\n";
echo "</form>\n"; echo "</form>\n";
?> ?>
<script type="text/javascript" language="javascript"> <script type="text/javascript">
jQuery(document).ready(function() { jQuery(document).ready(function() {
jQuery('#backButton').button(); jQuery('#backButton').button();
<?php <?php

View File

@ -3,7 +3,7 @@
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2016 Roland Gruber Copyright (C) 2003 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -422,33 +422,21 @@ function equalHeight(elementIDs) {
* @param title dialog title * @param title dialog title
* @param okText text for Ok button * @param okText text for Ok button
* @param cancelText text for Cancel button * @param cancelText text for Cancel button
* @param scope account type * @param typeId account type
* @param selectFieldName name of select box with profile name * @param selectFieldName name of select box with profile name
* @param serverProfile profile name
*/ */
function showDistributionDialog(title, okText, cancelText, scope, type, selectFieldName, serverProfile) { function showDistributionDialog(title, okText, cancelText, typeId, type, selectFieldName) {
// show dialog // show dialog
var buttonList = {}; var buttonList = {};
var dialogId = ''; var dialogId = '';
if (type == 'export') { if (type == 'export') {
// show structure name to export jQuery('#name_' + typeId).val(jQuery('#' + selectFieldName).val());
jQuery('#exportName').text(jQuery('[name=' + selectFieldName + ']').val()); dialogId = 'exportDialog_' + typeId;
dialogId = 'exportDialog'; buttonList[okText] = function() { document.forms["exportDialogForm_" + typeId].submit(); };
buttonList[okText] = function() { document.forms["exportDialogForm"].submit(); };
jQuery('<input>').attr({
type: 'hidden',
name: 'exportProfiles[]',
value: serverProfile + '##' + jQuery('[name=' + selectFieldName + ']').val()
}).appendTo('form');
jQuery('<input>').attr({
type: 'hidden',
name: 'scope',
value: scope
}).appendTo('form');
} else if (type == 'import') { } else if (type == 'import') {
dialogId = 'importDialog_' + scope; dialogId = 'importDialog_' + typeId;
buttonList[okText] = function() { document.forms["importDialogForm_" + scope].submit(); }; buttonList[okText] = function() { document.forms["importDialogForm_" + typeId].submit(); };
} }
buttonList[cancelText] = function() { jQuery(this).dialog("close"); }; buttonList[cancelText] = function() { jQuery(this).dialog("close"); };
@ -460,9 +448,9 @@ function showDistributionDialog(title, okText, cancelText, scope, type, selectFi
width: 'auto' width: 'auto'
}); });
if (type == 'export') { if (type == 'export') {
equalWidth(new Array('#passwd', '#destServerProfiles')); equalWidth(new Array('#passwd_' + typeId, '#destServerProfiles_' + typeId));
} else if (type == 'import') { } else if (type == 'import') {
equalWidth(new Array('#passwd_' + scope, '#importProfiles_' + scope)); equalWidth(new Array('#passwd_' + typeId, '#importProfiles'));
} }
} }
@ -769,6 +757,6 @@ window.lam.upload.uploadDone = function(jsonData) {
jQuery('#uploadContent').html(htmlOut); jQuery('#uploadContent').html(htmlOut);
} }
else { else {
top.location.href = '../lists/list.php?type=' + jsonData.scope + '&uploadAllOk'; top.location.href = '../lists/list.php?type=' + jsonData.typeId + '&uploadAllOk';
} }
} }

View File

@ -41,22 +41,23 @@ startSecureSession();
setlanguage(); setlanguage();
$type = $_GET['type']; $typeManager = new LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($_GET['type']);
// check if list is hidden // check if list is hidden
if (isAccountTypeHidden($type)) { if ($type->isHidden()) {
logNewMessage(LOG_ERR, 'User tried to access hidden account list: ' . $type); logNewMessage(LOG_ERR, 'User tried to access hidden account list: ' . $type->getId());
die(); die();
} }
// create list object if needed // create list object if needed
$listClass = LAM\TYPES\getListClassName($type); $listClass = LAM\TYPES\getListClassName($type->getScope());
if (!isset($_SESSION['list_' . $type])) { if (!isset($_SESSION['list_' . $type->getId()])) {
$list = new $listClass($type); $list = new $listClass($type);
$_SESSION['list_' . $type] = $list; $_SESSION['list_' . $type->getId()] = $list;
} }
// show page // show page
$_SESSION['list_' . $type]->showPage(); $_SESSION['list_' . $type->getId()]->showPage();
?> ?>

View File

@ -1,9 +1,10 @@
<?php <?php
namespace LAM\INIT;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2014 Roland Gruber Copyright (C) 2003 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -29,22 +30,30 @@ $Id$
*/ */
/** config object */ /** config object */
include_once('../lib/config.inc'); include_once '../lib/config.inc';
/** profiles */
include_once '../lib/profiles.inc';
// start session // start session
startSecureSession(); startSecureSession();
setlanguage(); setlanguage();
\LAM\PROFILES\installProfileTemplates();
\LAM\PDF\installPDFTemplates();
// check if all suffixes in conf-file exist // check if all suffixes in conf-file exist
$conf = $_SESSION['config']; $conf = $_SESSION['config'];
$new_suffs = array(); $new_suffs = array();
// get list of active types // get list of active types
$types = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
for ($i = 0; $i < sizeof($types); $i++) { $types = $typeManager->getConfiguredTypes();
$info = @ldap_read($_SESSION['ldap']->server(), escapeDN($conf->get_Suffix($types[$i])), "(objectClass=*)", array('objectClass'), 0, 0, 0, LDAP_DEREF_NEVER); foreach ($types as $type) {
$info = @ldap_read($_SESSION['ldap']->server(), escapeDN($type->getSuffix()), "(objectClass=*)", array('objectClass'), 0, 0, 0, LDAP_DEREF_NEVER);
$res = @ldap_get_entries($_SESSION['ldap']->server(), $info); $res = @ldap_get_entries($_SESSION['ldap']->server(), $info);
if (!$res && !in_array($conf->get_Suffix($types[$i]), $new_suffs)) $new_suffs[] = $conf->get_Suffix($types[$i]); if (!$res && !in_array($type->getSuffix(), $new_suffs)) {
$new_suffs[] = $type->getSuffix();
}
} }
// display page to add suffixes, if needed // display page to add suffixes, if needed
@ -53,11 +62,11 @@ if ((sizeof($new_suffs) > 0) && checkIfWriteAccessIsAllowed()) {
} }
else { else {
if (sizeof($types) > 0) { if (sizeof($types) > 0) {
for ($i = 0; $i < sizeof($types); $i++) { foreach ($types as $type) {
if (isAccountTypeHidden($types[$i])) { if ($type->isHidden()) {
continue; continue;
} }
metaRefresh("lists/list.php?type=" . $types[$i]); metaRefresh("lists/list.php?type=" . $type->getId());
break; break;
} }
} }
@ -65,4 +74,5 @@ else {
metaRefresh("tree/treeViewContainer.php"); metaRefresh("tree/treeViewContainer.php");
} }
} }
?> ?>

View File

@ -1,4 +1,5 @@
<?php <?php
namespace LAM\HEADER;
/* /*
$Id$ $Id$
@ -197,21 +198,27 @@ jQuery(document).ready(function() {
<div class="ui-tabs ui-widget ui-widget-content ui-corner-all"> <div class="ui-tabs ui-widget ui-widget-content ui-corner-all">
<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"> <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
<?php <?php
$typeManager = new LAM\TYPES\TypeManager(); printTypeTabs($headerPrefix);
$types = $typeManager->getConfiguredTypes();
$linkList = array();
foreach ($types as $type) {
if ($type->isHidden()) {
continue;
}
$link = '<a href="' . $headerPrefix . 'lists/list.php?type=' . $type->getId() .
'" onmouseover="jQuery(this).addClass(\'tabs-hover\');" onmouseout="jQuery(this).removeClass(\'tabs-hover\');">' .
'<img height="16" width="16" alt="' . $type->getId() . '" src="' . $headerPrefix . '../graphics/' . $type->getScope() . '.png">&nbsp;' .
$type->getAlias() . '</a>';
echo '<li id="tab_' . $type->getId() . '" class="ui-state-default ui-corner-top">';
echo $link;
echo "</li>\n";
}
?> ?>
</ul> </ul>
<?php
function printTypeTabs($headerPrefix) {
$typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
$linkList = array();
foreach ($types as $type) {
if ($type->isHidden()) {
continue;
}
$link = '<a href="' . $headerPrefix . 'lists/list.php?type=' . $type->getId() .
'" onmouseover="jQuery(this).addClass(\'tabs-hover\');" onmouseout="jQuery(this).removeClass(\'tabs-hover\');">' .
'<img height="16" width="16" alt="' . $type->getId() . '" src="' . $headerPrefix . '../graphics/' . $type->getScope() . '.png">&nbsp;' .
$type->getAlias() . '</a>';
echo '<li id="tab_' . $type->getId() . '" class="ui-state-default ui-corner-top">';
echo $link;
echo "</li>\n";
}
}

View File

@ -3,7 +3,7 @@
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2011 - 2016 Roland Gruber Copyright (C) 2011 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -90,7 +90,8 @@ class lamAjax {
} }
elseif ($function == 'upload') { elseif ($function == 'upload') {
include_once('../../lib/upload.inc'); include_once('../../lib/upload.inc');
$uploader = new LAM\UPLOAD\Uploader($_GET['scope']); $typeManager = new \LAM\TYPES\TypeManager();
$uploader = new LAM\UPLOAD\Uploader($typeManager->getConfiguredType($_GET['typeId']));
ob_start(); ob_start();
$jsonOut = $uploader->doUpload(); $jsonOut = $uploader->doUpload();
ob_end_clean(); ob_end_clean();

View File

@ -1,4 +1,22 @@
<?php <?php
namespace LAM\TOOLS\MULTI_EDIT;
use \htmlTable;
use \htmlTitle;
use \htmlSelect;
use \htmlOutputText;
use \htmlHelpLink;
use \htmlInputField;
use \htmlSubTitle;
use \htmlTableExtendedInputField;
use \htmlButton;
use \htmlStatusMessage;
use \htmlSpacer;
use \htmlHiddenInput;
use \htmlGroup;
use \htmlDiv;
use \htmlJavaScript;
use \htmlLink;
use \htmlInputTextarea;
/* /*
$Id$ $Id$
@ -85,11 +103,15 @@ function displayStartPage() {
$hideRules = array(); $hideRules = array();
$container->addElement(new htmlOutputText(_('LDAP suffix'))); $container->addElement(new htmlOutputText(_('LDAP suffix')));
$suffixGroup = new htmlTable(); $suffixGroup = new htmlTable();
$types = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
$suffixes = array(); $suffixes = array();
foreach ($types as $type) { foreach ($types as $type) {
$suffixes[LAM\TYPES\getTypeAlias($type)] = $_SESSION['config']->get_Suffix($type); if ($type->isHidden()) {
$hideRules[$_SESSION['config']->get_Suffix($type)] = array('otherSuffix'); continue;
}
$suffixes[$type->getAlias()] = $type->getSuffix();
$hideRules[$type->getSuffix()] = array('otherSuffix');
} }
$treeSuffix = $_SESSION['config']->get_Suffix('tree'); $treeSuffix = $_SESSION['config']->get_Suffix('tree');
if (!empty($treeSuffix)) { if (!empty($treeSuffix)) {

View File

@ -1,9 +1,20 @@
<?php <?php
namespace LAM\TOOLS\OU_EDIT;
use \htmlTable;
use \htmlSpacer;
use \htmlOutputText;
use \htmlButton;
use \htmlHiddenInput;
use \htmlSubTitle;
use \htmlStatusMessage;
use \htmlSelect;
use \htmlHelpLink;
use \htmlInputField;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2016 Roland Gruber Copyright (C) 2003 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -51,8 +62,6 @@ if (!empty($_POST)) {
validateSecurityToken(); validateSecurityToken();
} }
$types = $_SESSION['config']->get_ActiveTypes();
// check if deletion was canceled // check if deletion was canceled
if (isset($_POST['abort'])) { if (isset($_POST['abort'])) {
display_main(null, null); display_main(null, null);
@ -166,19 +175,21 @@ function display_main($message, $error) {
$container->addElement($msg, true); $container->addElement($msg, true);
} }
$typeManager = new \LAM\TYPES\TypeManager();
$typeList = $typeManager->getConfiguredTypes();
$types = array(); $types = array();
$typeList = $_SESSION['config']->get_ActiveTypes(); foreach ($typeList as $type) {
for ($i = 0; $i < sizeof($typeList); $i++) { if ($type->isHidden() || !checkIfWriteAccessIsAllowed($type->getId())) {
if (isAccountTypeHidden($typeList[$i]) || !checkIfWriteAccessIsAllowed($typeList[$i])) {
continue; continue;
} }
$types[$typeList[$i]] = LAM\TYPES\getTypeAlias($typeList[$i]); $types[$type->getId()] = $type->getAlias();
} }
natcasesort($types); natcasesort($types);
$options = array(); $options = array();
foreach ($types as $name => $title) { foreach ($types as $typeId => $title) {
$type = $typeManager->getConfiguredType($typeId);
$elements = array(); $elements = array();
$units = searchLDAPByAttribute(null, null, 'organizationalunit', array('dn'), array($name)); $units = searchLDAP($type->getSuffix(), '(objectclass=organizationalunit)', array('dn'));
for ($u = 0; $u < sizeof($units); $u++) { for ($u = 0; $u < sizeof($units); $u++) {
$elements[getAbstractDN($units[$u]['dn'])] = $units[$u]['dn']; $elements[getAbstractDN($units[$u]['dn'])] = $units[$u]['dn'];
} }

View File

@ -1,4 +1,21 @@
<?php <?php
namespace LAM\TOOLS\PDF_EDITOR;
use \htmlTable;
use \htmlTitle;
use \htmlStatusMessage;
use \LAMCfgMain;
use \htmlSubTitle;
use \htmlSelect;
use \htmlImage;
use \htmlSpacer;
use \htmlButton;
use \htmlLink;
use \htmlOutputText;
use \htmlInputFileUpload;
use \htmlHelpLink;
use \htmlInputField;
use \htmlHiddenInput;
use \htmlDiv;
/* /*
$Id$ $Id$
@ -23,7 +40,7 @@ $Id$
*/ */
/** /**
* This is the main window of the pdf structure editor. * This is the main window of the PDF structure editor.
* *
* @author Michael Duergner * @author Michael Duergner
* @author Roland Gruber * @author Roland Gruber
@ -55,10 +72,9 @@ if (!empty($_POST)) {
setlanguage(); setlanguage();
// Unset pdf structure definitions in session if set // Unset PDF structure definitions in session if set
if(isset($_SESSION['currentPDFStructure'])) { if(isset($_SESSION['currentPDFStructure'])) {
unset($_SESSION['currentPDFStructure']); unset($_SESSION['currentPDFStructure']);
unset($_SESSION['availablePDFFields']);
unset($_SESSION['currentPageDefinitions']); unset($_SESSION['currentPageDefinitions']);
} }
@ -70,60 +86,89 @@ if (!$_SESSION['ldap'] || !$_SESSION['ldap']->server()) {
// check if new template should be created // check if new template should be created
if(isset($_POST['createNewTemplate'])) { if(isset($_POST['createNewTemplate'])) {
metaRefresh('pdfpage.php?type=' . htmlspecialchars($_POST['scope'])); metaRefresh('pdfpage.php?type=' . htmlspecialchars($_POST['typeId']));
exit(); exit();
} }
$scopes = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
$sortedScopes = array(); $types = $typeManager->getConfiguredTypes();
for ($i = 0; $i < sizeof($scopes); $i++) { $sortedTypes = array();
if (isAccountTypeHidden($scopes[$i]) || !checkIfWriteAccessIsAllowed($scopes[$i])) { foreach ($types as $type) {
if ($type->isHidden() || !checkIfWriteAccessIsAllowed($type->getId())) {
continue; continue;
} }
$sortedScopes[$scopes[$i]] = LAM\TYPES\getTypeAlias($scopes[$i]); $sortedTypes[$type->getId()] = $type->getAlias();
} }
natcasesort($sortedScopes); natcasesort($sortedTypes);
$container = new htmlTable(); $container = new htmlTable();
$container->addElement(new htmlTitle(_('PDF editor')), true); $container->addElement(new htmlTitle(_('PDF editor')), true);
if (isset($_POST['deleteProfile']) && ($_POST['deleteProfile'] == 'true')) { if (isset($_POST['deleteProfile']) && ($_POST['deleteProfile'] == 'true')) {
// delete structure // delete structure
if (deletePDFStructureDefinition($_POST['profileDeleteType'], $_POST['profileDeleteName'])) { if (\LAM\PDF\deletePDFStructure($_POST['profileDeleteType'], $_POST['profileDeleteName'])) {
$message = new htmlStatusMessage('INFO', _('Deleted PDF structure.'), LAM\TYPES\getTypeAlias($_POST['profileDeleteType']) . ': ' . htmlspecialchars($_POST['profileDeleteName'])); $message = new htmlStatusMessage('INFO', _('Deleted PDF structure.'), \LAM\TYPES\getTypeAlias($_POST['profileDeleteType']) . ': ' . htmlspecialchars($_POST['profileDeleteName']));
$message->colspan = 10; $message->colspan = 10;
$container->addElement($message, true); $container->addElement($message, true);
} }
else { else {
$message = new htmlStatusMessage('ERROR', _('Unable to delete PDF structure!'), LAM\TYPES\getTypeAlias($_POST['profileDeleteType']) . ': ' . htmlspecialchars($_POST['profileDeleteName'])); $message = new htmlStatusMessage('ERROR', _('Unable to delete PDF structure!'), \LAM\TYPES\getTypeAlias($_POST['profileDeleteType']) . ': ' . htmlspecialchars($_POST['profileDeleteName']));
$message->colspan = 10; $message->colspan = 10;
$container->addElement($message, true); $container->addElement($message, true);
} }
} }
if (isset($_POST['importexport']) && ($_POST['importexport'] === '1')) { $configProfiles = getConfigProfiles();
$serverProfiles = array();
foreach ($configProfiles as $profileName) {
$serverProfiles[$profileName] = new \LAMConfig($profileName);
}
// import structures
if (!empty($_POST['import'])) {
$cfg = new LAMCfgMain(); $cfg = new LAMCfgMain();
$impExpMessage = null; $typeId = $_POST['typeId'];
if (isset($_POST['importProfiles_' . $_POST['scope']])) { // check master password
// check master password $errMessage = null;
if (!$cfg->checkPassword($_POST['passwd_' . $_POST['scope']])) { if (!$cfg->checkPassword($_POST['passwd_i_' . $_POST['typeId']])) {
$impExpMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!')); $errMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!'));
}
elseif (copyPdfProfiles($_POST['importProfiles_' . $_POST['scope']], $_POST['scope'])) {
$impExpMessage = new htmlStatusMessage('INFO', _('Import successful'));
}
} else if (isset($_POST['exportProfiles'])) {
// check master password
if (!$cfg->checkPassword($_POST['passwd'])) {
$impExpMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!'));
}
elseif (copyPdfProfiles($_POST['exportProfiles'], $_POST['scope'], $_POST['destServerProfiles'])) {
$impExpMessage = new htmlStatusMessage('INFO', _('Export successful'));
}
} }
if ($impExpMessage != null) { elseif (!empty($_POST['importProfiles_' . $typeId])) {
$impExpMessage->colspan = 10; $options = array();
$container->addElement($impExpMessage, true); foreach ($_POST['importProfiles_' . $typeId] as $importProfiles) {
$parts = explode('##', $importProfiles);
$options[] = array('conf' => $parts[0], 'typeId' => $parts[1], 'name' => $parts[2]);
}
$errMessage = importStructures($_POST['typeId'], $options, $serverProfiles, $typeManager);
}
if ($errMessage != null) {
$errMessage->colspan = 10;
$container->addElement($errMessage, true);
}
}
// export structures
if (!empty($_POST['export'])) {
$cfg = new LAMCfgMain();
$typeId = $_POST['typeId'];
// check master password
$errMessage = null;
if (!$cfg->checkPassword($_POST['passwd_e_' . $_POST['typeId']])) {
$errMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!'));
}
elseif (!empty($_POST['exportProfiles_' . $typeId])) {
$options = array();
foreach ($_POST['exportProfiles_' . $typeId] as $importProfiles) {
$parts = explode('##', $importProfiles);
$options[] = array('conf' => $parts[0], 'typeId' => $parts[1]);
}
$typeId = $_POST['typeId'];
$name = $_POST['name_' . $typeId];
$errMessage = exportStructures($typeId, $name, $options, $serverProfiles, $typeManager);
}
if ($errMessage != null) {
$errMessage->colspan = 10;
$container->addElement($errMessage, true);
} }
} }
@ -131,34 +176,36 @@ if (isset($_POST['importexport']) && ($_POST['importexport'] === '1')) {
if (isset($_POST['uploadLogo']) && !empty($_FILES['logoUpload']) && !empty($_FILES['logoUpload']['size'])) { if (isset($_POST['uploadLogo']) && !empty($_FILES['logoUpload']) && !empty($_FILES['logoUpload']['size'])) {
$file = $_FILES['logoUpload']['tmp_name']; $file = $_FILES['logoUpload']['tmp_name'];
$filename = $_FILES['logoUpload']['name']; $filename = $_FILES['logoUpload']['name'];
$container->addElement(uploadPDFLogo($file, $filename), true); $container->addElement(\LAM\PDF\uploadPDFLogo($file, $filename), true);
} }
// delete logo file // delete logo file
if (isset($_POST['delLogo'])) { if (isset($_POST['delLogo'])) {
$toDel = $_POST['logo']; $toDel = $_POST['logo'];
$container->addElement(deletePDFLogo($toDel), true); $container->addElement(\LAM\PDF\deletePDFLogo($toDel), true);
} }
// get list of account types // get list of account types
$availableScopes = ''; $availableTypes = array();
$templateClasses = array(); $templateClasses = array();
foreach ($sortedScopes as $scope => $title) { foreach ($sortedTypes as $typeId => $title) {
$type = $typeManager->getConfiguredType($typeId);
$templateClasses[] = array( $templateClasses[] = array(
'scope' => $scope, 'typeId' => $type->getId(),
'scope' => $type->getScope(),
'title' => $title, 'title' => $title,
'templates' => ""); 'templates' => "");
$availableScopes[$title] = $scope; $availableTypes[$title] = $type->getId();
} }
// get list of templates for each account type // get list of templates for each account type
for ($i = 0; $i < sizeof($templateClasses); $i++) { for ($i = 0; $i < sizeof($templateClasses); $i++) {
$templateClasses[$i]['templates'] = getPDFStructureDefinitions($templateClasses[$i]['scope']); $templateClasses[$i]['templates'] = \LAM\PDF\getPDFStructures($templateClasses[$i]['typeId']);
} }
// check if a template should be edited // check if a template should be edited
for ($i = 0; $i < sizeof($templateClasses); $i++) { for ($i = 0; $i < sizeof($templateClasses); $i++) {
if (isset($_POST['editTemplate_' . $templateClasses[$i]['scope']]) || isset($_POST['editTemplate_' . $templateClasses[$i]['scope'] . '_x'])) { if (isset($_POST['editTemplate_' . $templateClasses[$i]['typeId']]) || isset($_POST['editTemplate_' . $templateClasses[$i]['typeId'] . '_x'])) {
metaRefresh('pdfpage.php?type=' . htmlspecialchars($templateClasses[$i]['scope']) . '&edit=' . htmlspecialchars($_POST['template_' . $templateClasses[$i]['scope']])); metaRefresh('pdfpage.php?type=' . htmlspecialchars($templateClasses[$i]['typeId']) . '&edit=' . htmlspecialchars($_POST['template_' . $templateClasses[$i]['typeId']]));
exit; exit;
} }
} }
@ -176,13 +223,13 @@ include '../main_header.php';
} }
// new template // new template
if (!empty($availableScopes)) { if (!empty($availableTypes)) {
$container->addElement(new htmlSubTitle(_('Create a new PDF structure')), true); $container->addElement(new htmlSubTitle(_('Create a new PDF structure')), true);
$newPDFContainer = new htmlTable(); $newPDFContainer = new htmlTable();
$newScopeSelect = new htmlSelect('scope', $availableScopes); $newProfileSelect = new htmlSelect('typeId', $availableTypes);
$newScopeSelect->setHasDescriptiveElements(true); $newProfileSelect->setHasDescriptiveElements(true);
$newScopeSelect->setWidth('15em'); $newProfileSelect->setWidth('15em');
$newPDFContainer->addElement($newScopeSelect); $newPDFContainer->addElement($newProfileSelect);
$newPDFContainer->addElement(new htmlSpacer('10px', null)); $newPDFContainer->addElement(new htmlSpacer('10px', null));
$newPDFContainer->addElement(new htmlButton('createNewTemplate', _('Create'))); $newPDFContainer->addElement(new htmlButton('createNewTemplate', _('Create')));
$container->addElement($newPDFContainer, true); $container->addElement($newPDFContainer, true);
@ -190,8 +237,6 @@ include '../main_header.php';
} }
// existing templates // existing templates
$configProfiles = getConfigProfiles();
$container->addElement(new htmlSubTitle(_("Manage existing PDF structures")), true); $container->addElement(new htmlSubTitle(_("Manage existing PDF structures")), true);
$existingContainer = new htmlTable(); $existingContainer = new htmlTable();
for ($i = 0; $i < sizeof($templateClasses); $i++) { for ($i = 0; $i < sizeof($templateClasses); $i++) {
@ -203,29 +248,29 @@ include '../main_header.php';
$existingContainer->addElement(new htmlSpacer('3px', null)); $existingContainer->addElement(new htmlSpacer('3px', null));
$existingContainer->addElement(new htmlOutputText($templateClasses[$i]['title'])); $existingContainer->addElement(new htmlOutputText($templateClasses[$i]['title']));
$existingContainer->addElement(new htmlSpacer('3px', null)); $existingContainer->addElement(new htmlSpacer('3px', null));
$select = new htmlSelect('template_' . $templateClasses[$i]['scope'], $templateClasses[$i]['templates']); $select = new htmlSelect('template_' . $templateClasses[$i]['typeId'], $templateClasses[$i]['templates']);
$select->setWidth('15em'); $select->setWidth('15em');
$existingContainer->addElement($select); $existingContainer->addElement($select);
$existingContainer->addElement(new htmlSpacer('3px', null)); $existingContainer->addElement(new htmlSpacer('3px', null));
$exEditButton = new htmlButton('editTemplate_' . $templateClasses[$i]['scope'], 'edit.png', true); $exEditButton = new htmlButton('editTemplate_' . $templateClasses[$i]['typeId'], 'edit.png', true);
$exEditButton->setTitle(_('Edit')); $exEditButton->setTitle(_('Edit'));
$existingContainer->addElement($exEditButton); $existingContainer->addElement($exEditButton);
$deleteLink = new htmlLink(null, '#', '../../graphics/delete.png'); $deleteLink = new htmlLink(null, '#', '../../graphics/delete.png');
$deleteLink->setTitle(_('Delete')); $deleteLink->setTitle(_('Delete'));
$deleteLink->setOnClick("profileShowDeleteDialog('" . _('Delete') . "', '" . _('Ok') . "', '" . _('Cancel') . "', '" . $templateClasses[$i]['scope'] . "', '" . 'template_' . $templateClasses[$i]['scope'] . "');"); $deleteLink->setOnClick("profileShowDeleteDialog('" . _('Delete') . "', '" . _('Ok') . "', '" . _('Cancel') . "', '" . $templateClasses[$i]['typeId'] . "', '" . 'template_' . $templateClasses[$i]['typeId'] . "');");
$existingContainer->addElement($deleteLink); $existingContainer->addElement($deleteLink);
if (count($configProfiles) > 1) { if (count($configProfiles) > 1) {
$importLink = new htmlLink(null, '#', '../../graphics/import.png'); $importLink = new htmlLink(null, '#', '../../graphics/import.png');
$importLink->setTitle(_('Import PDF structures')); $importLink->setTitle(_('Import PDF structures'));
$importLink->setOnClick("showDistributionDialog('" . _("Import PDF structures") . "', '" . $importLink->setOnClick("showDistributionDialog('" . _("Import PDF structures") . "', '" .
_('Ok') . "', '" . _('Cancel') . "', '" . $templateClasses[$i]['scope'] . "', 'import');"); _('Ok') . "', '" . _('Cancel') . "', '" . $templateClasses[$i]['typeId'] . "', 'import');");
$existingContainer->addElement($importLink); $existingContainer->addElement($importLink);
} }
$exportLink = new htmlLink(null, '#', '../../graphics/export.png'); $exportLink = new htmlLink(null, '#', '../../graphics/export.png');
$exportLink->setTitle(_('Export PDF structure')); $exportLink->setTitle(_('Export PDF structure'));
$exportLink->setOnClick("showDistributionDialog('" . _("Export PDF structure") . "', '" . $exportLink->setOnClick("showDistributionDialog('" . _("Export PDF structure") . "', '" .
_('Ok') . "', '" . _('Cancel') . "', '" . $templateClasses[$i]['scope'] . "', 'export', '" . 'template_' . $templateClasses[$i]['scope'] . "', '" . $_SESSION['config']->getName() . "');"); _('Ok') . "', '" . _('Cancel') . "', '" . $templateClasses[$i]['typeId'] . "', 'export', '" . 'template_' . $templateClasses[$i]['typeId'] . "', '" . $_SESSION['config']->getName() . "');");
$existingContainer->addElement($exportLink); $existingContainer->addElement($exportLink);
$existingContainer->addNewLine(); $existingContainer->addNewLine();
} }
@ -235,7 +280,7 @@ include '../main_header.php';
$logoContainer = new htmlTable(); $logoContainer = new htmlTable();
$logoContainer->addElement(new htmlSpacer(null, '30px'), true); $logoContainer->addElement(new htmlSpacer(null, '30px'), true);
$logoContainer->addElement(new htmlSubTitle(_('Manage logos')), true); $logoContainer->addElement(new htmlSubTitle(_('Manage logos')), true);
$logos = getAvailableLogos(); $logos = \LAM\PDF\getAvailableLogos();
$logoOptions = array(); $logoOptions = array();
foreach ($logos as $logo) { foreach ($logos as $logo) {
$file = $logo['filename']; $file = $logo['filename'];
@ -263,25 +308,32 @@ include '../main_header.php';
echo "</div>\n"; echo "</div>\n";
for ($i = 0; $i < sizeof($templateClasses); $i++) { for ($i = 0; $i < sizeof($templateClasses); $i++) {
$typeId = $templateClasses[$i]['typeId'];
$scope = $templateClasses[$i]['scope']; $scope = $templateClasses[$i]['scope'];
$tmpArr = array(); $importOptions = array();
foreach ($configProfiles as $profile) { foreach ($configProfiles as $profile) {
if ($profile != $_SESSION['config']->getName()) { $typeManagerImport = new \LAM\TYPES\TypeManager($serverProfiles[$profile]);
$accountProfiles = getPDFStructureDefinitions($scope, $profile); $typesImport = $typeManagerImport->getConfiguredTypesForScope($scope);
for ($p = 0; $p < sizeof($accountProfiles); $p++) { foreach ($typesImport as $typeImport) {
$tmpArr[$profile][$accountProfiles[$p]] = $profile . '##' . $accountProfiles[$p]; if (($profile != $_SESSION['config']->getName()) || ($typeImport->getId() != $typeId)) {
$accountProfiles = \LAM\PDF\getPDFStructures($typeImport->getId(), $profile);
if (!empty($accountProfiles)) {
foreach ($accountProfiles as $accountProfile) {
$importOptions[$profile][$typeImport->getAlias() . ': ' . $accountProfile] = $profile . '##' . $typeImport->getId() . '##' . $accountProfile;
}
}
} }
} }
} }
//import dialog //import dialog
echo "<div id=\"importDialog_$scope\" class=\"hidden\">\n"; echo "<div id=\"importDialog_$typeId\" class=\"hidden\">\n";
echo "<form id=\"importDialogForm_$scope\" method=\"post\" action=\"pdfmain.php\">\n"; echo "<form id=\"importDialogForm_$typeId\" method=\"post\" action=\"pdfmain.php\">\n";
$container = new htmlTable(); $container = new htmlTable();
$container->addElement(new htmlOutputText(_('PDF structures')), true); $container->addElement(new htmlOutputText(_('PDF structures')), true);
$select = new htmlSelect('importProfiles_' . $scope, $tmpArr, array(), count($tmpArr, 1) < 15 ? count($tmpArr, 1) : 15); $select = new htmlSelect('importProfiles_' . $typeId, $importOptions, array(), count($importOptions, 1) < 15 ? count($importOptions, 1) : 15);
$select->setMultiSelect(true); $select->setMultiSelect(true);
$select->setHasDescriptiveElements(true); $select->setHasDescriptiveElements(true);
$select->setContainsOptgroups(true); $select->setContainsOptgroups(true);
@ -293,12 +345,56 @@ include '../main_header.php';
$container->addElement(new htmlSpacer(null, '10px'), true); $container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Master password")), true); $container->addElement(new htmlOutputText(_("Master password")), true);
$exportPasswd = new htmlInputField('passwd_' . $scope); $exportPasswd = new htmlInputField('passwd_i_' . $typeId);
$exportPasswd->setIsPassword(true); $exportPasswd->setIsPassword(true);
$container->addElement($exportPasswd); $container->addElement($exportPasswd);
$container->addElement(new htmlHelpLink('236')); $container->addElement(new htmlHelpLink('236'));
$container->addElement(new htmlHiddenInput('importexport', '1')); $container->addElement(new htmlHiddenInput('import', '1'));
$container->addElement(new htmlHiddenInput('scope', $scope), true); $container->addElement(new htmlHiddenInput('typeId', $typeId), true);
addSecurityTokenToMetaHTML($container);
parseHtml(null, $container, array(), false, $tabindex, 'user');
echo '</form>';
echo "</div>\n";
//export dialog
echo "<div id=\"exportDialog_$typeId\" class=\"hidden\">\n";
echo "<form id=\"exportDialogForm_$typeId\" method=\"post\" action=\"pdfmain.php\">\n";
$container = new htmlTable();
$container->addElement(new htmlOutputText(_("Target server profile")), true);
$exportOptions = array();
foreach ($configProfiles as $profile) {
$typeManagerExport = new \LAM\TYPES\TypeManager($serverProfiles[$profile]);
$typesExport = $typeManagerExport->getConfiguredTypesForScope($scope);
foreach ($typesExport as $typeExport) {
if (($profile != $_SESSION['config']->getName()) || ($typeExport->getId() != $typeId)) {
$exportOptions[$typeManagerExport->getConfig()->getName()][$typeExport->getAlias()] = $profile . '##' . $typeExport->getId();
}
}
}
$exportOptions['*' . _('Global templates')][_('Global templates')] = 'templates*##';
$select = new htmlSelect('exportProfiles_' . $typeId, $exportOptions, array(), count($exportOptions) < 10 ? count($exportOptions, 1) : 10);
$select->setHasDescriptiveElements(true);
$select->setContainsOptgroups(true);
$select->setMultiSelect(true);
$container->addElement($select);
$container->addElement(new htmlHelpLink('363'), true);
$container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Master password")), true);
$exportPasswd = new htmlInputField('passwd_e_' . $typeId);
$exportPasswd->setIsPassword(true);
$container->addElement($exportPasswd);
$container->addElement(new htmlHelpLink('236'));
$container->addElement(new htmlHiddenInput('export', '1'), true);
$container->addElement(new htmlHiddenInput('typeId', $typeId), true);
$container->addElement(new htmlHiddenInput('name_' . $typeId, '_'), true);
addSecurityTokenToMetaHTML($container); addSecurityTokenToMetaHTML($container);
parseHtml(null, $container, array(), false, $tabindex, 'user'); parseHtml(null, $container, array(), false, $tabindex, 'user');
@ -307,52 +403,6 @@ include '../main_header.php';
echo "</div>\n"; echo "</div>\n";
} }
//export dialog
echo "<div id=\"exportDialog\" class=\"hidden\">\n";
echo "<form id=\"exportDialogForm\" method=\"post\" action=\"pdfmain.php\">\n";
$container = new htmlTable();
$container->addElement(new htmlOutputText(_('PDF structure')), true);
$expStructGroup = new htmlTable();
$expStructGroup->addElement(new htmlSpacer('10px', null));
$expStructGroup->addElement(new htmlDiv('exportName', ''));
$container->addElement($expStructGroup, true);
$container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Target server profile")), true);
foreach ($configProfiles as $key => $value) {
$tmpProfiles[$value] = $value;
}
natcasesort($tmpProfiles);
$tmpProfiles['*' . _('Global templates')] = 'templates*';
$findProfile = array_search($_SESSION['config']->getName(), $tmpProfiles);
if ($findProfile !== false) {
unset($tmpProfiles[$findProfile]);
}
$select = new htmlSelect('destServerProfiles', $tmpProfiles, array(), count($tmpProfiles) < 10 ? count($tmpProfiles) : 10);
$select->setHasDescriptiveElements(true);
$select->setSortElements(false);
$select->setMultiSelect(true);
$container->addElement($select);
$container->addElement(new htmlHelpLink('409'), true);
$container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Master password")), true);
$exportPasswd = new htmlInputField('passwd');
$exportPasswd->setIsPassword(true);
$container->addElement($exportPasswd);
$container->addElement(new htmlHelpLink('236'));
$container->addElement(new htmlHiddenInput('importexport', '1'), true);
addSecurityTokenToMetaHTML($container);
parseHtml(null, $container, array(), false, $tabindex, 'user');
echo '</form>';
echo "</div>\n";
// form for delete action // form for delete action
echo '<div id="deleteProfileDialog" class="hidden"><form id="deleteProfileForm" action="pdfmain.php" method="post">'; echo '<div id="deleteProfileDialog" class="hidden"><form id="deleteProfileForm" action="pdfmain.php" method="post">';
echo _("Do you really want to delete this PDF structure?"); echo _("Do you really want to delete this PDF structure?");
@ -365,4 +415,77 @@ echo '<div id="deleteProfileDialog" class="hidden"><form id="deleteProfileForm"
echo '</form></div>'; echo '</form></div>';
include '../main_footer.php'; include '../main_footer.php';
/**
* Imports the selected PDF structures.
*
* @param string $typeId type id
* @param array $options options
* @param \LAMConfig[] $serverProfiles server profiles (name => profile object)
* @param \LAM\TYPES\TypeManager $typeManager type manager
* @return \htmlStatusMessage message or null
*/
function importStructures($typeId, $options, &$serverProfiles, &$typeManager) {
foreach ($options as $option) {
$sourceConfName = $option['conf'];
$sourceTypeId = $option['typeId'];
$sourceName = $option['name'];
$sourceTypeManager = new \LAM\TYPES\TypeManager($serverProfiles[$sourceConfName]);
$sourceType = $sourceTypeManager->getConfiguredType($sourceTypeId);
$targetType = $typeManager->getConfiguredType($typeId);
if (($sourceType != null) && ($targetType != null)) {
try {
\LAM\PDF\copyStructure($sourceType, $sourceName, $targetType);
}
catch (\LAMException $e) {
return new \htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
}
}
}
return new \htmlStatusMessage('INFO', _('Import successful'));
}
/**
* Exports the selected account profile.
*
* @param string $typeId source type id
* @param string $name profile name
* @param array $options options
* @param \LAMConfig[] $serverProfiles server profiles (name => profile object)
* @param \LAM\TYPES\TypeManager $typeManager type manager
* @return \htmlStatusMessage message or null
*/
function exportStructures($typeId, $name, $options, &$serverProfiles, &$typeManager) {
$sourceType = $typeManager->getConfiguredType($typeId);
if ($sourceType == null) {
return null;
}
foreach ($options as $option) {
$targetConfName = $option['conf'];
if ($targetConfName == 'templates*') {
try {
\LAM\PDF\copyStructureToTemplates($sourceType, $name);
}
catch (\LAMException $e) {
return new \htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
}
}
else {
$targetTypeId = $option['typeId'];
$targetTypeManager = new \LAM\TYPES\TypeManager($serverProfiles[$targetConfName]);
$targetType = $targetTypeManager->getConfiguredType($targetTypeId);
if ($targetType != null) {
try {
\LAM\PDF\copyStructure($sourceType, $name, $targetType);
}
catch (\LAMException $e) {
return new \htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
}
}
}
}
return new \htmlStatusMessage('INFO', _('Export successful'));
}
?> ?>

View File

@ -1,10 +1,25 @@
<?php <?php
namespace LAM\TOOLS\PDF_EDITOR;
use \htmlTable;
use \htmlTitle;
use \htmlTableExtendedInputField;
use \htmlSpacer;
use \htmlTableExtendedSelect;
use \htmlButton;
use \htmlOutputText;
use \htmlGroup;
use \htmlSelect;
use \htmlInputField;
use \htmlSubTitle;
use \htmlFieldset;
use \htmlInputTextarea;
use \htmlHiddenInput;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2006 Michael Duergner Copyright (C) 2003 - 2006 Michael Duergner
2007 - 2015 Roland Gruber 2007 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -66,15 +81,17 @@ if (!$_SESSION['ldap'] || !$_SESSION['ldap']->server()) {
} }
// Write $_POST variables to $_GET when form was submitted via post // Write $_POST variables to $_GET when form was submitted via post
if(isset($_POST['type'])) { if (isset($_POST['type'])) {
$_GET = $_POST; $_GET = $_POST;
if($_POST['pdfname'] == '') { if ($_POST['pdfname'] == '') {
unset($_GET['pdfname']); unset($_GET['pdfname']);
} }
} }
if (isAccountTypeHidden($_GET['type']) || !checkIfWriteAccessIsAllowed($_GET['type'])) { $typeManager = new \LAM\TYPES\TypeManager();
logNewMessage(LOG_ERR, 'User tried to access hidden PDF structure: ' . $_GET['type']); $type = $typeManager->getConfiguredType($_GET['type']);
if ($type->isHidden() || !checkIfWriteAccessIsAllowed($type->getId())) {
logNewMessage(LOG_ERR, 'User tried to access hidden PDF structure: ' . $type->getId());
die(); die();
} }
@ -112,11 +129,11 @@ if(isset($_GET['submit'])) {
$saveErrors[] = array('ERROR', _('PDF structure name not valid'), _('The name for that PDF-structure you submitted is not valid. A valid name must consist of the following characters: \'a-z\',\'A-Z\',\'0-9\',\'_\',\'-\'.')); $saveErrors[] = array('ERROR', _('PDF structure name not valid'), _('The name for that PDF-structure you submitted is not valid. A valid name must consist of the following characters: \'a-z\',\'A-Z\',\'0-9\',\'_\',\'-\'.'));
} }
else { else {
$return = savePDFStructureDefinitions($_GET['type'],$_GET['pdfname']); $return = \LAM\PDF\savePDFStructure($type->getId(), $_GET['pdfname']);
if($return == 'ok') { if($return == 'ok') {
metaRefresh('pdfmain.php?savedSuccessfully=' . $_GET['pdfname']); metaRefresh('pdfmain.php?savedSuccessfully=' . $_GET['pdfname']);
exit; exit;
} }
elseif($return == 'no perms'){ elseif($return == 'no perms'){
$saveErrors[] = array('ERROR', _("Could not save PDF structure, access denied."), $_GET['pdfname']); $saveErrors[] = array('ERROR', _("Could not save PDF structure, access denied."), $_GET['pdfname']);
} }
@ -141,7 +158,7 @@ elseif(isset($_GET['add_sectionText'])) {
StatusMessage('ERROR',_('No section text specified'),_('The headline for a new section must contain at least one character.')); StatusMessage('ERROR',_('No section text specified'),_('The headline for a new section must contain at least one character.'));
} }
else { else {
$attributes = array(); $attributes = array();
$attributes['NAME'] = $_GET['new_section_text']; $attributes['NAME'] = $_GET['new_section_text'];
$entry = array(array('tag' => 'SECTION','type' => 'open','level' => '2','attributes' => $attributes),array('tag' => 'SECTION','type' => 'close','level' => '2')); $entry = array(array('tag' => 'SECTION','type' => 'open','level' => '2','attributes' => $attributes),array('tag' => 'SECTION','type' => 'close','level' => '2'));
// Insert new field in structure // Insert new field in structure
@ -339,23 +356,20 @@ foreach ($_GET as $key => $value) {
if(!isset($_SESSION['currentPDFStructure'])) { if(!isset($_SESSION['currentPDFStructure'])) {
// Load structure file to be edit // Load structure file to be edit
if(isset($_GET['edit'])) { if(isset($_GET['edit'])) {
$load = loadPDFStructureDefinitions($_GET['type'],$_GET['edit']); $load = \LAM\PDF\loadPDFStructure($type->getId(), $_GET['edit']);
$_SESSION['currentPDFStructure'] = $load['structure']; $_SESSION['currentPDFStructure'] = $load['structure'];
$_SESSION['currentPageDefinitions'] = $load['page_definitions']; $_SESSION['currentPageDefinitions'] = $load['page_definitions'];
$_GET['pdfname'] = $_GET['edit']; $_GET['pdfname'] = $_GET['edit'];
} }
// Load default structure file when creating a new one // Load default structure file when creating a new one
else { else {
$load = loadPDFStructureDefinitions($_GET['type']); $load = \LAM\PDF\loadPDFStructure($type->getId());
$_SESSION['currentPDFStructure'] = $load['structure']; $_SESSION['currentPDFStructure'] = $load['structure'];
$_SESSION['currentPageDefinitions'] = $load['page_definitions']; $_SESSION['currentPageDefinitions'] = $load['page_definitions'];
} }
} }
// Load available fields from modules when not set in session $availablePDFFields = getAvailablePDFFields($type->getId());
if(!isset($_SESSION['availablePDFFields'])) {
$_SESSION['availablePDFFields'] = getAvailablePDFFields($_GET['type']);
}
// Create the values for the dropdown boxes for section headline defined by // Create the values for the dropdown boxes for section headline defined by
// value entries and fetch all available modules // value entries and fetch all available modules
@ -363,9 +377,9 @@ $modules = array();
$section_items_array = array(); $section_items_array = array();
$section_items = ''; $section_items = '';
$sortedModules = array(); $sortedModules = array();
foreach($_SESSION['availablePDFFields'] as $module => $fields) { foreach($availablePDFFields as $module => $fields) {
if ($module != 'main') { if ($module != 'main') {
$title = getModuleAlias($module, $_GET['type']); $title = getModuleAlias($module, $type->getScope());
} }
else { else {
$title = _('Main'); $title = _('Main');
@ -374,7 +388,7 @@ foreach($_SESSION['availablePDFFields'] as $module => $fields) {
} }
natcasesort($sortedModules); natcasesort($sortedModules);
foreach($sortedModules as $module => $title) { foreach($sortedModules as $module => $title) {
$values = $_SESSION['availablePDFFields'][$module]; $values = $availablePDFFields[$module];
if (!is_array($values) || (sizeof($values) < 1)) { if (!is_array($values) || (sizeof($values) < 1)) {
continue; continue;
} }
@ -402,7 +416,7 @@ if (sizeof($saveErrors) > 0) {
$newFieldFieldElements = array(); $newFieldFieldElements = array();
foreach($sortedModules as $module => $title) { foreach($sortedModules as $module => $title) {
$fields = $_SESSION['availablePDFFields'][$module]; $fields = $availablePDFFields[$module];
if (isset($fields) && is_array($fields) && (sizeof($fields) > 0)) { if (isset($fields) && is_array($fields) && (sizeof($fields) > 0)) {
$moduleFields = array(); $moduleFields = array();
foreach ($fields as $field => $fieldLabel) { foreach ($fields as $field => $fieldLabel) {
@ -429,10 +443,10 @@ if (isset($_SESSION['currentPageDefinitions']['headline'])) {
$headline = $_SESSION['currentPageDefinitions']['headline']; $headline = $_SESSION['currentPageDefinitions']['headline'];
} }
// logo // logo
$logoFiles = getAvailableLogos(); $logoFiles = \LAM\PDF\getAvailableLogos();
$logos = array(_('No logo') => 'none'); $logos = array(_('No logo') => 'none');
foreach($logoFiles as $logoFile) { foreach($logoFiles as $logoFile) {
$logos[$logoFile['filename'] . ' (' . $logoFile['infos'][0] . ' x ' . $logoFile['infos'][1] . ")"] = $logoFile['filename']; $logos[$logoFile['filename'] . ' (' . $logoFile['infos'][0] . ' x ' . $logoFile['infos'][1] . ")"] = $logoFile['filename'];
} }
$selectedLogo = array('printLogo.jpg'); $selectedLogo = array('printLogo.jpg');
if (isset($_SESSION['currentPageDefinitions']['filename'])) { if (isset($_SESSION['currentPageDefinitions']['filename'])) {
@ -442,7 +456,7 @@ if (isset($_SESSION['currentPageDefinitions']['filename'])) {
?> ?>
<form id="inputForm" action="pdfpage.php" method="post" onSubmit="saveScrollPosition('inputForm')"> <form id="inputForm" action="pdfpage.php" method="post" onSubmit="saveScrollPosition('inputForm')">
<?php <?php
$sectionElements = array(_('Beginning') => 0); $sectionElements = array();
$nonTextSectionElements = array(); $nonTextSectionElements = array();
$container = new htmlTable(); $container = new htmlTable();
@ -472,7 +486,7 @@ $structureContent = new htmlTable();
for ($key = 0; $key < sizeof($_SESSION['currentPDFStructure']); $key++) { for ($key = 0; $key < sizeof($_SESSION['currentPDFStructure']); $key++) {
$entry = $_SESSION['currentPDFStructure'][$key]; $entry = $_SESSION['currentPDFStructure'][$key];
// create the up/down/remove links // create the up/down/remove links
$linkBase = 'pdfpage.php?type=' . $_GET['type'] . '&pdfname=' . $structureName . '&headline=' . $headline . '&logoFile=' . $selectedLogo[0] . '&foldingmarks=' . $foldingMarks; $linkBase = 'pdfpage.php?type=' . $type->getId() . '&pdfname=' . $structureName . '&headline=' . $headline . '&logoFile=' . $selectedLogo[0] . '&foldingmarks=' . $foldingMarks;
$linkUp = new htmlButton('up_' . $key, 'up.gif', true); $linkUp = new htmlButton('up_' . $key, 'up.gif', true);
$linkUp->setTitle(_("Up")); $linkUp->setTitle(_("Up"));
$linkDown = new htmlButton('down_' . $key, 'down.gif', true); $linkDown = new htmlButton('down_' . $key, 'down.gif', true);
@ -481,10 +495,10 @@ for ($key = 0; $key < sizeof($_SESSION['currentPDFStructure']); $key++) {
$linkRemove->setTitle(_("Remove")); $linkRemove->setTitle(_("Remove"));
$emptyBox = new htmlOutputText(''); $emptyBox = new htmlOutputText('');
// We have a new section to start // We have a new section to start
if($entry['tag'] == "SECTION" && $entry['type'] == "open") { if(($entry['tag'] == "SECTION") && ($entry['type'] == 'open')) {
$name = $entry['attributes']['NAME']; $name = $entry['attributes']['NAME'];
if(preg_match("/^_[a-zA-Z0-9_]+_[a-zA-Z0-9_]+/",$name)) { if(preg_match("/^_[a-zA-Z0-9_]+_[a-zA-Z0-9_]+/",$name)) {
$section_headline = translateFieldIDToName(substr($name,1), $_GET['type']); $section_headline = translateFieldIDToName(substr($name,1), $type->getScope(), $availablePDFFields);
} }
else { else {
$section_headline = $name; $section_headline = $name;
@ -496,7 +510,7 @@ for ($key = 0; $key < sizeof($_SESSION['currentPDFStructure']); $key++) {
if(preg_match("/^_[a-zA-Z0-9_]+_[a-zA-Z0-9_]+/",$name)) { if(preg_match("/^_[a-zA-Z0-9_]+_[a-zA-Z0-9_]+/",$name)) {
$headlineElements = array(); $headlineElements = array();
foreach($section_items_array as $item) { foreach($section_items_array as $item) {
$headlineElements[translateFieldIDToName($item, $_GET['type'])] = '_' . $item; $headlineElements[translateFieldIDToName($item, $type->getScope(), $availablePDFFields)] = '_' . $item;
} }
$sectionHeadlineSelect = new htmlSelect('section_' . $key, $headlineElements, array($name)); $sectionHeadlineSelect = new htmlSelect('section_' . $key, $headlineElements, array($name));
$sectionHeadlineSelect->setHasDescriptiveElements(true); $sectionHeadlineSelect->setHasDescriptiveElements(true);
@ -566,7 +580,7 @@ for ($key = 0; $key < sizeof($_SESSION['currentPDFStructure']); $key++) {
// Get name of current entry // Get name of current entry
$name = $entry['attributes']['NAME']; $name = $entry['attributes']['NAME'];
$structureContent->addElement(new htmlSpacer('10px', null)); $structureContent->addElement(new htmlSpacer('10px', null));
$fieldOutput = new htmlOutputText(translateFieldIDToName($name, $_GET['type'])); $fieldOutput = new htmlOutputText(translateFieldIDToName($name, $type->getScope(), $availablePDFFields));
$structureContent->addElement($fieldOutput); $structureContent->addElement($fieldOutput);
if ($_SESSION['currentPDFStructure'][$key - 1]['tag'] != 'SECTION') { if ($_SESSION['currentPDFStructure'][$key - 1]['tag'] != 'SECTION') {
$structureContent->addElement($linkUp); $structureContent->addElement($linkUp);
@ -583,6 +597,7 @@ for ($key = 0; $key < sizeof($_SESSION['currentPDFStructure']); $key++) {
$structureContent->addElement($linkRemove, true); $structureContent->addElement($linkRemove, true);
} }
} }
$sectionElements[_('End')] = sizeof($_SESSION['currentPDFStructure']);
$structureContent->colspan = 3; $structureContent->colspan = 3;
$mainContent->addElement($structureContent); $mainContent->addElement($structureContent);
$container->addElement(new htmlFieldset($mainContent), true); $container->addElement(new htmlFieldset($mainContent), true);
@ -621,19 +636,21 @@ $newTextFieldContent->addElement(new htmlButton('add_text', _('Add')));
$container->addElement(new htmlFieldset($newTextFieldContent, _("Text field")), true); $container->addElement(new htmlFieldset($newTextFieldContent, _("Text field")), true);
// new field // new field
$container->addElement(new htmlSubTitle(_('New field')), true); if (!empty($nonTextSectionElements)) {
$newFieldContainer = new htmlTable(); $container->addElement(new htmlSubTitle(_('New field')), true);
$newFieldFieldSelect = new htmlSelect('new_field', $newFieldFieldElements); $newFieldContainer = new htmlTable();
$newFieldFieldSelect->setHasDescriptiveElements(true); $newFieldFieldSelect = new htmlSelect('new_field', $newFieldFieldElements);
$newFieldFieldSelect->setContainsOptgroups(true); $newFieldFieldSelect->setHasDescriptiveElements(true);
$newFieldContainer->addElement($newFieldFieldSelect); $newFieldFieldSelect->setContainsOptgroups(true);
$newFieldContainer->addElement(new htmlSpacer('10px', null)); $newFieldContainer->addElement($newFieldFieldSelect);
$newFieldSectionSelect = new htmlTableExtendedSelect('add_field_position', $nonTextSectionElements, array(), _('Position')); $newFieldContainer->addElement(new htmlSpacer('10px', null));
$newFieldSectionSelect->setHasDescriptiveElements(true); $newFieldSectionSelect = new htmlTableExtendedSelect('add_field_position', $nonTextSectionElements, array(), _('Position'));
$newFieldContainer->addElement($newFieldSectionSelect); $newFieldSectionSelect->setHasDescriptiveElements(true);
$newFieldContainer->addElement(new htmlButton('add_new_field', _('Add'))); $newFieldContainer->addElement($newFieldSectionSelect);
$container->addElement(new htmlFieldset($newFieldContainer), true); $newFieldContainer->addElement(new htmlButton('add_new_field', _('Add')));
$container->addElement(new htmlSpacer(null, '20px'), true); $container->addElement(new htmlFieldset($newFieldContainer), true);
$container->addElement(new htmlSpacer(null, '20px'), true);
}
// buttons // buttons
$buttonContainer = new htmlTable(); $buttonContainer = new htmlTable();
@ -644,13 +661,13 @@ $cancelButton->setIconClass('cancelButton');
$buttonContainer->addElement($saveButton); $buttonContainer->addElement($saveButton);
$buttonContainer->addElement($cancelButton); $buttonContainer->addElement($cancelButton);
$buttonContainer->addElement(new htmlHiddenInput('modules', $modules)); $buttonContainer->addElement(new htmlHiddenInput('modules', $modules));
$buttonContainer->addElement(new htmlHiddenInput('type', $_GET['type'])); $buttonContainer->addElement(new htmlHiddenInput('type', $type->getId()));
$container->addElement($buttonContainer, true); $container->addElement($buttonContainer, true);
addSecurityTokenToMetaHTML($container); addSecurityTokenToMetaHTML($container);
$tabindex = 1; $tabindex = 1;
parseHtml(null, $container, array(), false, $tabindex, $_GET['type']); parseHtml(null, $container, array(), false, $tabindex, $type->getScope());
if ((sizeof($saveErrors) == 0) && isset($_POST['scrollPositionTop']) && isset($_POST['scrollPositionLeft'])) { if ((sizeof($saveErrors) == 0) && isset($_POST['scrollPositionTop']) && isset($_POST['scrollPositionLeft'])) {
// scroll to last position // scroll to last position
@ -671,9 +688,10 @@ include '../main_footer.php';
* *
* @param String $id field ID * @param String $id field ID
* @param String $scope account type * @param String $scope account type
* @param array $availablePDFFields available PDF fields
*/ */
function translateFieldIDToName($id, $scope) { function translateFieldIDToName($id, $scope, $availablePDFFields) {
foreach ($_SESSION['availablePDFFields'] as $module => $fields) { foreach ($availablePDFFields as $module => $fields) {
if (!(strpos($id, $module . '_') === 0)) { if (!(strpos($id, $module . '_') === 0)) {
continue; continue;
} }

View File

@ -1,4 +1,19 @@
<?php <?php
namespace LAM\TOOLS\PROFILE_EDITOR;
use \htmlTable;
use \htmlTitle;
use \htmlStatusMessage;
use \LAMCfgMain;
use \htmlSubTitle;
use \htmlSpacer;
use \htmlSelect;
use \htmlButton;
use \htmlImage;
use \htmlLink;
use \htmlOutputText;
use \htmlHelpLink;
use \htmlHiddenInput;
use \htmlInputField;
/* /*
$Id$ $Id$
@ -51,16 +66,18 @@ if (!empty($_POST)) {
validateSecurityToken(); validateSecurityToken();
} }
$types = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
$profileClasses = array(); $profileClasses = array();
$profileClassesTemp = array(); $profileClassesTemp = array();
for ($i = 0; $i < sizeof($types); $i++) { foreach ($types as $type) {
if (isAccountTypeHidden($types[$i]) || !checkIfWriteAccessIsAllowed($types[$i])) { if ($type->isHidden() || !checkIfWriteAccessIsAllowed($type->getId())) {
continue; continue;
} }
$profileClassesTemp[LAM\TYPES\getTypeAlias($types[$i])] = array( $profileClassesTemp[$type->getAlias()] = array(
'scope' => $types[$i], 'typeId' => $type->getId(),
'title' => LAM\TYPES\getTypeAlias($types[$i]), 'scope' => $type->getScope(),
'title' => $type->getAlias(),
'profiles' => ""); 'profiles' => "");
} }
$profileClassesKeys = array_keys($profileClassesTemp); $profileClassesKeys = array_keys($profileClassesTemp);
@ -83,9 +100,9 @@ elseif (isset($_POST['createProfileButton'])) {
} }
// check if a profile should be edited // check if a profile should be edited
for ($i = 0; $i < sizeof($profileClasses); $i++) { for ($i = 0; $i < sizeof($profileClasses); $i++) {
if (isset($_POST['editProfile_' . $profileClasses[$i]['scope']]) || isset($_POST['editProfile_' . $profileClasses[$i]['scope'] . '_x'])) { if (isset($_POST['editProfile_' . $profileClasses[$i]['typeId']]) || isset($_POST['editProfile_' . $profileClasses[$i]['typeId'] . '_x'])) {
metaRefresh("profilepage.php?type=" . htmlspecialchars($profileClasses[$i]['scope']) . metaRefresh("profilepage.php?type=" . htmlspecialchars($profileClasses[$i]['typeId']) .
"&amp;edit=" . htmlspecialchars($_POST['profile_' . $profileClasses[$i]['scope']])); "&amp;edit=" . htmlspecialchars($_POST['profile_' . $profileClasses[$i]['typeId']]));
exit; exit;
} }
} }
@ -99,53 +116,78 @@ $container = new htmlTable();
$container->addElement(new htmlTitle(_("Profile editor")), true); $container->addElement(new htmlTitle(_("Profile editor")), true);
if (isset($_POST['deleteProfile']) && ($_POST['deleteProfile'] == 'true')) { if (isset($_POST['deleteProfile']) && ($_POST['deleteProfile'] == 'true')) {
if (isAccountTypeHidden($_POST['profileDeleteType'])) { $type = $typeManager->getConfiguredType($_POST['profileDeleteType']);
if ($type->isHidden()) {
logNewMessage(LOG_ERR, 'User tried to delete hidden account type profile: ' . $_POST['profileDeleteType']); logNewMessage(LOG_ERR, 'User tried to delete hidden account type profile: ' . $_POST['profileDeleteType']);
die(); die();
} }
// delete profile // delete profile
if (delAccountProfile($_POST['profileDeleteName'], $_POST['profileDeleteType'])) { if (\LAM\PROFILES\delAccountProfile($_POST['profileDeleteName'], $_POST['profileDeleteType'])) {
$message = new htmlStatusMessage('INFO', _('Deleted profile.'), LAM\TYPES\getTypeAlias($_POST['profileDeleteType']) . ': ' . htmlspecialchars($_POST['profileDeleteName'])); $message = new htmlStatusMessage('INFO', _('Deleted profile.'), $type->getAlias() . ': ' . htmlspecialchars($_POST['profileDeleteName']));
$message->colspan = 10; $message->colspan = 10;
$container->addElement($message, true); $container->addElement($message, true);
} }
else { else {
$message = new htmlStatusMessage('ERROR', _('Unable to delete profile!'), LAM\TYPES\getTypeAlias($_POST['profileDeleteType']) . ': ' . htmlspecialchars($_POST['profileDeleteName'])); $message = new htmlStatusMessage('ERROR', _('Unable to delete profile!'), $type->getAlias() . ': ' . htmlspecialchars($_POST['profileDeleteName']));
$message->colspan = 10; $message->colspan = 10;
$container->addElement($message, true); $container->addElement($message, true);
} }
} }
// check if profiles should be imported or exported $configProfiles = getConfigProfiles();
if (isset($_POST['importexport']) && ($_POST['importexport'] === '1')) { $serverProfiles = array();
foreach ($configProfiles as $profileName) {
$serverProfiles[$profileName] = new \LAMConfig($profileName);
}
// import profiles
if (!empty($_POST['import'])) {
$cfg = new LAMCfgMain(); $cfg = new LAMCfgMain();
$impExpMessage = null; // check master password
if (isset($_POST['importProfiles_' . $_POST['scope']])) { $errMessage = null;
// check master password if (!$cfg->checkPassword($_POST['passwd_i_' . $_POST['typeId']])) {
if (!$cfg->checkPassword($_POST['passwd_' . $_POST['scope']])) { $errMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!'));
$impExpMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!'));
}
elseif (copyAccountProfiles($_POST['importProfiles_' . $_POST['scope']], $_POST['scope'])) {
$impExpMessage = new htmlStatusMessage('INFO', _('Import successful'));
}
} else if (isset($_POST['exportProfiles'])) {
// check master password
if (!$cfg->checkPassword($_POST['passwd'])) {
$impExpMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!'));
}
elseif (copyAccountProfiles($_POST['exportProfiles'], $_POST['scope'], $_POST['destServerProfiles'])) {
$impExpMessage = new htmlStatusMessage('INFO', _('Export successful'));
}
} }
if ($impExpMessage != null) { elseif (!empty($_POST['importProfiles'])) {
$impExpMessage->colspan = 10; $options = array();
$container->addElement($impExpMessage, true); foreach ($_POST['importProfiles'] as $importProfiles) {
$parts = explode('##', $importProfiles);
$options[] = array('conf' => $parts[0], 'typeId' => $parts[1], 'name' => $parts[2]);
}
$errMessage = importProfiles($_POST['typeId'], $options, $serverProfiles, $typeManager);
}
if ($errMessage != null) {
$errMessage->colspan = 10;
$container->addElement($errMessage, true);
}
}
// export profiles
if (!empty($_POST['export'])) {
$cfg = new LAMCfgMain();
// check master password
$errMessage = null;
if (!$cfg->checkPassword($_POST['passwd_e_' . $_POST['typeId']])) {
$errMessage = new htmlStatusMessage('ERROR', _('Master password is wrong!'));
}
elseif (!empty($_POST['exportProfiles'])) {
$options = array();
foreach ($_POST['exportProfiles'] as $importProfiles) {
$parts = explode('##', $importProfiles);
$options[] = array('conf' => $parts[0], 'typeId' => $parts[1]);
}
$typeId = $_POST['typeId'];
$name = $_POST['name_' . $typeId];
$errMessage = exportProfiles($typeId, $name, $options, $serverProfiles, $typeManager);
}
if ($errMessage != null) {
$errMessage->colspan = 10;
$container->addElement($errMessage, true);
} }
} }
// get list of profiles for each account type // get list of profiles for each account type
for ($i = 0; $i < sizeof($profileClasses); $i++) { for ($i = 0; $i < sizeof($profileClasses); $i++) {
$profileList = getAccountProfiles($profileClasses[$i]['scope']); $profileList = \LAM\PROFILES\getAccountProfiles($profileClasses[$i]['typeId']);
natcasesort($profileList); natcasesort($profileList);
$profileClasses[$i]['profiles'] = $profileList; $profileClasses[$i]['profiles'] = $profileList;
} }
@ -161,7 +203,7 @@ if (!empty($profileClasses)) {
$container->addElement(new htmlSubTitle(_('Create a new profile')), true); $container->addElement(new htmlSubTitle(_('Create a new profile')), true);
$sortedTypes = array(); $sortedTypes = array();
for ($i = 0; $i < sizeof($profileClasses); $i++) { for ($i = 0; $i < sizeof($profileClasses); $i++) {
$sortedTypes[$profileClasses[$i]['title']] = $profileClasses[$i]['scope']; $sortedTypes[$profileClasses[$i]['title']] = $profileClasses[$i]['typeId'];
} }
natcasesort($sortedTypes); natcasesort($sortedTypes);
$newContainer = new htmlTable(); $newContainer = new htmlTable();
@ -181,39 +223,37 @@ $container->addElement(new htmlSubTitle(_('Manage existing profiles')), true);
$existingContainer = new htmlTable(); $existingContainer = new htmlTable();
$existingContainer->colspan = 5; $existingContainer->colspan = 5;
$configProfiles = getConfigProfiles();
for ($i = 0; $i < sizeof($profileClasses); $i++) { for ($i = 0; $i < sizeof($profileClasses); $i++) {
if ($i > 0) { if ($i > 0) {
$existingContainer->addElement(new htmlSpacer(null, '10px'), true); $existingContainer->addElement(new htmlSpacer(null, '10px'), true);
} }
$existingContainer->addElement(new htmlImage('../../graphics/' . $profileClasses[$i]['scope'] . '.png')); $existingContainer->addElement(new htmlImage('../../graphics/' . \LAM\TYPES\getScopeFromTypeId($profileClasses[$i]['typeId']) . '.png'));
$existingContainer->addElement(new htmlSpacer('3px', null)); $existingContainer->addElement(new htmlSpacer('3px', null));
$existingContainer->addElement(new htmlOutputText($profileClasses[$i]['title'])); $existingContainer->addElement(new htmlOutputText($profileClasses[$i]['title']));
$existingContainer->addElement(new htmlSpacer('3px', null)); $existingContainer->addElement(new htmlSpacer('3px', null));
$select = new htmlSelect('profile_' . $profileClasses[$i]['scope'], $profileClasses[$i]['profiles']); $select = new htmlSelect('profile_' . $profileClasses[$i]['typeId'], $profileClasses[$i]['profiles']);
$select->setWidth('15em'); $select->setWidth('15em');
$existingContainer->addElement($select); $existingContainer->addElement($select);
$existingContainer->addElement(new htmlSpacer('3px', null)); $existingContainer->addElement(new htmlSpacer('3px', null));
$editButton = new htmlButton('editProfile_' . $profileClasses[$i]['scope'], 'edit.png', true); $editButton = new htmlButton('editProfile_' . $profileClasses[$i]['typeId'], 'edit.png', true);
$editButton->setTitle(_('Edit')); $editButton->setTitle(_('Edit'));
$existingContainer->addElement($editButton); $existingContainer->addElement($editButton);
$deleteLink = new htmlLink(null, '#', '../../graphics/delete.png'); $deleteLink = new htmlLink(null, '#', '../../graphics/delete.png');
$deleteLink->setTitle(_('Delete')); $deleteLink->setTitle(_('Delete'));
$deleteLink->setOnClick("profileShowDeleteDialog('" . _('Delete') . "', '" . _('Ok') . "', '" . _('Cancel') . "', '" . $profileClasses[$i]['scope'] . "', '" . 'profile_' . $profileClasses[$i]['scope'] . "');"); $deleteLink->setOnClick("profileShowDeleteDialog('" . _('Delete') . "', '" . _('Ok') . "', '" . _('Cancel') . "', '" . $profileClasses[$i]['typeId'] . "', '" . 'profile_' . $profileClasses[$i]['typeId'] . "');");
$existingContainer->addElement($deleteLink); $existingContainer->addElement($deleteLink);
if (count($configProfiles) > 1) { if (count($configProfiles) > 1) {
$importLink = new htmlLink(null, '#', '../../graphics/import.png'); $importLink = new htmlLink(null, '#', '../../graphics/import.png');
$importLink->setTitle(_('Import profiles')); $importLink->setTitle(_('Import profiles'));
$importLink->setOnClick("showDistributionDialog('" . _("Import profiles") . "', '" . $importLink->setOnClick("showDistributionDialog('" . _("Import profiles") . "', '" .
_('Ok') . "', '" . _('Cancel') . "', '" . $profileClasses[$i]['scope'] . "', 'import');"); _('Ok') . "', '" . _('Cancel') . "', '" . $profileClasses[$i]['typeId'] . "', 'import');");
$existingContainer->addElement($importLink); $existingContainer->addElement($importLink);
} }
$exportLink = new htmlLink(null, '#', '../../graphics/export.png'); $exportLink = new htmlLink(null, '#', '../../graphics/export.png');
$exportLink->setTitle(_('Export profile')); $exportLink->setTitle(_('Export profile'));
$exportLink->setOnClick("showDistributionDialog('" . _("Export profile") . "', '" . $exportLink->setOnClick("showDistributionDialog('" . _("Export profile") . "', '" .
_('Ok') . "', '" . _('Cancel') . "', '" . $profileClasses[$i]['scope'] . "', 'export', '" . 'profile_' . $profileClasses[$i]['scope'] . "', '" . $_SESSION['config']->getName() . "');"); _('Ok') . "', '" . _('Cancel') . "', '" . $profileClasses[$i]['typeId'] . "', 'export', '" . 'profile_' . $profileClasses[$i]['typeId'] . "');");
$existingContainer->addElement($exportLink); $existingContainer->addElement($exportLink);
$existingContainer->addNewLine(); $existingContainer->addNewLine();
} }
@ -228,27 +268,32 @@ echo "</form>\n";
echo "</div>\n"; echo "</div>\n";
for ($i = 0; $i < sizeof($profileClasses); $i++) { for ($i = 0; $i < sizeof($profileClasses); $i++) {
$typeId = $profileClasses[$i]['typeId'];
$scope = $profileClasses[$i]['scope']; $scope = $profileClasses[$i]['scope'];
$tmpArr = array(); $importOptions = array();
foreach ($configProfiles as $profile) { foreach ($configProfiles as $profile) {
if ($profile != $_SESSION['config']->getName()) { $typeManagerImport = new \LAM\TYPES\TypeManager($serverProfiles[$profile]);
$accountProfiles = getAccountProfiles($scope, $profile); $typesImport = $typeManagerImport->getConfiguredTypesForScope($scope);
if (!empty($accountProfiles)) { foreach ($typesImport as $typeImport) {
for ($p = 0; $p < sizeof($accountProfiles); $p++) { if (($profile != $_SESSION['config']->getName()) || ($typeImport->getId() != $typeId)) {
$tmpArr[$profile][$accountProfiles[$p]] = $profile . '##' . $accountProfiles[$p]; $accountProfiles = \LAM\PROFILES\getAccountProfiles($typeImport->getId(), $profile);
if (!empty($accountProfiles)) {
for ($p = 0; $p < sizeof($accountProfiles); $p++) {
$importOptions[$profile][$typeImport->getAlias() . ': ' . $accountProfiles[$p]] = $profile . '##' . $typeImport->getId() . '##' . $accountProfiles[$p];
}
} }
} }
} }
} }
//import dialog //import dialog
echo "<div id=\"importDialog_$scope\" class=\"hidden\">\n"; echo "<div id=\"importDialog_$typeId\" class=\"hidden\">\n";
echo "<form id=\"importDialogForm_$scope\" method=\"post\" action=\"profilemain.php\">\n"; echo "<form id=\"importDialogForm_$typeId\" method=\"post\" action=\"profilemain.php\">\n";
$container = new htmlTable(); $container = new htmlTable();
$container->addElement(new htmlOutputText(_('Profiles')), true); $container->addElement(new htmlOutputText(_('Profiles')), true);
$select = new htmlSelect('importProfiles_' . $scope, $tmpArr, array(), count($tmpArr, 1) < 15 ? count($tmpArr, 1) : 15); $select = new htmlSelect('importProfiles', $importOptions, array(), count($importOptions, 1) < 15 ? count($importOptions, 1) : 15);
$select->setMultiSelect(true); $select->setMultiSelect(true);
$select->setHasDescriptiveElements(true); $select->setHasDescriptiveElements(true);
$select->setContainsOptgroups(true); $select->setContainsOptgroups(true);
@ -260,67 +305,65 @@ for ($i = 0; $i < sizeof($profileClasses); $i++) {
$container->addElement(new htmlSpacer(null, '10px'), true); $container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Master password")), true); $container->addElement(new htmlOutputText(_("Master password")), true);
$exportPasswd = new htmlInputField('passwd_' . $scope); $exportPasswd = new htmlInputField('passwd_i_' . $typeId);
$exportPasswd->setIsPassword(true); $exportPasswd->setIsPassword(true);
$container->addElement($exportPasswd); $container->addElement($exportPasswd);
$container->addElement(new htmlHelpLink('236')); $container->addElement(new htmlHelpLink('236'));
$container->addElement(new htmlHiddenInput('importexport', '1')); $container->addElement(new htmlHiddenInput('import', '1'));
$container->addElement(new htmlHiddenInput('scope', $scope), true); $container->addElement(new htmlHiddenInput('typeId', $typeId), true);
addSecurityTokenToMetaHTML($container); addSecurityTokenToMetaHTML($container);
parseHtml(null, $container, array(), false, $tabindex, 'user'); parseHtml(null, $container, array(), false, $tabindex, 'user');
echo '</form>'; echo '</form>';
echo "</div>\n"; echo "</div>\n";
//export dialog
echo "<div id=\"exportDialog_$typeId\" class=\"hidden\">\n";
echo "<form id=\"exportDialogForm_$typeId\" method=\"post\" action=\"profilemain.php\">\n";
$container = new htmlTable();
$container->addElement(new htmlOutputText(_("Target server profile")), true);
$exportOptions = array();
foreach ($configProfiles as $profile) {
$typeManagerExport = new \LAM\TYPES\TypeManager($serverProfiles[$profile]);
$typesExport = $typeManagerExport->getConfiguredTypesForScope($scope);
foreach ($typesExport as $typeExport) {
if (($profile != $_SESSION['config']->getName()) || ($typeExport->getId() != $typeId)) {
$exportOptions[$typeManagerExport->getConfig()->getName()][$typeExport->getAlias()] = $profile . '##' . $typeExport->getId();
}
}
}
$exportOptions['*' . _('Global templates')][_('Global templates')] = 'templates*##';
$select = new htmlSelect('exportProfiles', $exportOptions, array(), count($exportOptions) < 10 ? count($exportOptions, 1) : 10);
$select->setHasDescriptiveElements(true);
$select->setContainsOptgroups(true);
$select->setMultiSelect(true);
$container->addElement($select);
$container->addElement(new htmlHelpLink('363'), true);
$container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Master password")), true);
$exportPasswd = new htmlInputField('passwd_e_' . $typeId);
$exportPasswd->setIsPassword(true);
$container->addElement($exportPasswd);
$container->addElement(new htmlHelpLink('236'));
$container->addElement(new htmlHiddenInput('export', '1'), true);
$container->addElement(new htmlHiddenInput('typeId', $typeId), true);
$container->addElement(new htmlHiddenInput('name_' . $typeId, '_'), true);
addSecurityTokenToMetaHTML($container);
parseHtml(null, $container, array(), false, $tabindex, 'user');
echo '</form>';
echo "</div>\n";
} }
//export dialog
echo "<div id=\"exportDialog\" class=\"hidden\">\n";
echo "<form id=\"exportDialogForm\" method=\"post\" action=\"profilemain.php\">\n";
$container = new htmlTable();
$container->addElement(new htmlOutputText(_('Profile name')), true);
$expStructGroup = new htmlTable();
$expStructGroup->addElement(new htmlSpacer('10px', null));
$expStructGroup->addElement(new htmlDiv('exportName', ''));
$container->addElement($expStructGroup, true);
$container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Target server profile")), true);
foreach ($configProfiles as $key => $value) {
$tmpProfiles[$value] = $value;
}
natcasesort($tmpProfiles);
$tmpProfiles['*' . _('Global templates')] = 'templates*';
$findProfile = array_search($_SESSION['config']->getName(), $tmpProfiles);
if ($findProfile !== false) {
unset($tmpProfiles[$findProfile]);
}
$select = new htmlSelect('destServerProfiles', $tmpProfiles, array(), count($tmpProfiles) < 10 ? count($tmpProfiles) : 10);
$select->setHasDescriptiveElements(true);
$select->setSortElements(false);
$select->setMultiSelect(true);
$container->addElement($select);
$container->addElement(new htmlHelpLink('363'), true);
$container->addElement(new htmlSpacer(null, '10px'), true);
$container->addElement(new htmlOutputText(_("Master password")), true);
$exportPasswd = new htmlInputField('passwd');
$exportPasswd->setIsPassword(true);
$container->addElement($exportPasswd);
$container->addElement(new htmlHelpLink('236'));
$container->addElement(new htmlHiddenInput('importexport', '1'), true);
addSecurityTokenToMetaHTML($container);
parseHtml(null, $container, array(), false, $tabindex, 'user');
echo '</form>';
echo "</div>\n";
// form for delete action // form for delete action
echo '<div id="deleteProfileDialog" class="hidden"><form id="deleteProfileForm" action="profilemain.php" method="post">'; echo '<div id="deleteProfileDialog" class="hidden"><form id="deleteProfileForm" action="profilemain.php" method="post">';
echo _("Do you really want to delete this profile?"); echo _("Do you really want to delete this profile?");
@ -334,4 +377,75 @@ echo '</form></div>';
include '../main_footer.php'; include '../main_footer.php';
/**
* Imports the selected account profiles.
*
* @param string $typeId type id
* @param array $options options
* @param \LAMConfig[] $serverProfiles server profiles (name => profile object)
* @param \LAM\TYPES\TypeManager $typeManager type manager
* @return \htmlStatusMessage message or null
*/
function importProfiles($typeId, $options, &$serverProfiles, &$typeManager) {
foreach ($options as $option) {
$sourceConfName = $option['conf'];
$sourceTypeId = $option['typeId'];
$sourceName = $option['name'];
$sourceTypeManager = new \LAM\TYPES\TypeManager($serverProfiles[$sourceConfName]);
$sourceType = $sourceTypeManager->getConfiguredType($sourceTypeId);
$targetType = $typeManager->getConfiguredType($typeId);
if (($sourceType != null) && ($targetType != null)) {
try {
\LAM\PROFILES\copyAccountProfile($sourceType, $sourceName, $targetType);
}
catch (\LAMException $e) {
return new \htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
}
}
}
return new \htmlStatusMessage('INFO', _('Import successful'));
}
/**
* Exports the selected account profile.
*
* @param string $typeId source type id
* @param string $name profile name
* @param array $options options
* @param \LAMConfig[] $serverProfiles server profiles (name => profile object)
* @param \LAM\TYPES\TypeManager $typeManager type manager
* @return \htmlStatusMessage message or null
*/
function exportProfiles($typeId, $name, $options, &$serverProfiles, &$typeManager) {
$sourceType = $typeManager->getConfiguredType($typeId);
if ($sourceType == null) {
return null;
}
foreach ($options as $option) {
$targetConfName = $option['conf'];
if ($targetConfName == 'templates*') {
try {
\LAM\PROFILES\copyAccountProfileToTemplates($sourceType, $name);
}
catch (\LAMException $e) {
return new \htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
}
}
else {
$targetTypeId = $option['typeId'];
$targetTypeManager = new \LAM\TYPES\TypeManager($serverProfiles[$targetConfName]);
$targetType = $targetTypeManager->getConfiguredType($targetTypeId);
if ($targetType != null) {
try {
\LAM\PROFILES\copyAccountProfile($sourceType, $name, $targetType);
}
catch (\LAMException $e) {
return new \htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
}
}
}
}
return new \htmlStatusMessage('INFO', _('Export successful'));
}
?> ?>

View File

@ -1,9 +1,18 @@
<?php <?php
namespace LAM\TOOLS\PROFILE_EDITOR;
use \htmlTable;
use \htmlTitle;
use \htmlTableExtendedInputField;
use \htmlSpacer;
use \htmlTableExtendedSelect;
use \htmlFieldset;
use \htmlButton;
use \htmlHiddenInput;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2003 - 2015 Roland Gruber Copyright (C) 2003 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -62,10 +71,16 @@ if (!$_SESSION['ldap'] || !$_SESSION['ldap']->server()) {
} }
// copy type and profile name from POST to GET // copy type and profile name from POST to GET
if (isset($_POST['profname'])) $_GET['edit'] = $_POST['profname']; if (isset($_POST['profname'])) {
if (isset($_POST['accounttype'])) $_GET['type'] = $_POST['accounttype']; $_GET['edit'] = $_POST['profname'];
}
if (isset($_POST['accounttype'])) {
$_GET['type'] = $_POST['accounttype'];
}
if (isAccountTypeHidden($_GET['type']) || !checkIfWriteAccessIsAllowed($_GET['type'])) { $typeManager = new \LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($_GET['type']);
if ($type->isHidden() || !checkIfWriteAccessIsAllowed($_GET['type'])) {
logNewMessage(LOG_ERR, 'User tried to access hidden account type profile: ' . $_GET['type']); logNewMessage(LOG_ERR, 'User tried to access hidden account type profile: ' . $_GET['type']);
die(); die();
} }
@ -108,19 +123,19 @@ if (isset($_POST['save'])) {
$options[$element] = explode("\r\n", $_POST[$element]); $options[$element] = explode("\r\n", $_POST[$element]);
} }
} }
// remove double slashes if magic quotes are on // remove double slashes if magic quotes are on
if (get_magic_quotes_gpc() == 1) { if (get_magic_quotes_gpc() == 1) {
foreach ($opt_keys as $element) { foreach ($opt_keys as $element) {
if (isset($options[$element][0]) && is_string($options[$element][0])) $options[$element][0] = stripslashes($options[$element][0]); if (isset($options[$element][0]) && is_string($options[$element][0])) $options[$element][0] = stripslashes($options[$element][0]);
} }
} }
// check options // check options
$errors = checkProfileOptions($_POST['accounttype'], $options); $errors = checkProfileOptions($_POST['accounttype'], $options);
if (sizeof($errors) == 0) { // input data is valid, save profile if (sizeof($errors) == 0) { // input data is valid, save profile
// save profile // save profile
if (saveAccountProfile($options, $_POST['profname'], $_POST['accounttype'])) { if (\LAM\PROFILES\saveAccountProfile($options, $_POST['profname'], $_POST['accounttype'])) {
metaRefresh('profilemain.php?savedSuccessfully=' . $_POST['profname']); metaRefresh('profilemain.php?savedSuccessfully=' . $_POST['profname']);
exit(); exit();
} }
@ -140,15 +155,12 @@ if (sizeof($errors) > 0) {
call_user_func_array('StatusMessage', $errors[$i]); call_user_func_array('StatusMessage', $errors[$i]);
} }
} }
// empty list of attribute types // empty list of attribute types
$_SESSION['profile_types'] = array(); $_SESSION['profile_types'] = array();
// check if account type is valid
$type = $_GET['type'];
// get module options // get module options
$options = getProfileOptions($type); $options = getProfileOptions($type->getId());
// load old profile or POST values if needed // load old profile or POST values if needed
$old_options = array(); $old_options = array();
@ -169,11 +181,11 @@ if (isset($_POST['save'])) {
} }
} }
elseif (isset($_GET['edit'])) { elseif (isset($_GET['edit'])) {
$old_options = loadAccountProfile($_GET['edit'], $type); $old_options = \LAM\PROFILES\loadAccountProfile($_GET['edit'], $type->getId());
} }
// display formular // display formular
echo "<form action=\"profilepage.php?type=$type\" method=\"post\">\n"; echo "<form action=\"profilepage.php?type=" . $type->getId() . "\" method=\"post\">\n";
echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">'; echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">';
$profName = ''; $profName = '';
@ -192,11 +204,10 @@ $dnContent->addElement(new htmlTableExtendedInputField(_("Profile name") . '*',
$dnContent->addElement(new htmlSpacer(null, '10px'), true); $dnContent->addElement(new htmlSpacer(null, '10px'), true);
// suffix box // suffix box
// get root suffix // get root suffix
$rootsuffix = $_SESSION['config']->get_Suffix($type); $rootsuffix = $type->getSuffix();
// get subsuffixes // get subsuffixes
$suffixes = array('-' => '-'); $suffixes = array('-' => '-');
$typeObj = new $type(); $possibleSuffixes = $type->getSuffixList();
$possibleSuffixes = $typeObj->getSuffixList();
foreach ($possibleSuffixes as $suffix) { foreach ($possibleSuffixes as $suffix) {
$suffixes[getAbstractDN($suffix)] = $suffix; $suffixes[getAbstractDN($suffix)] = $suffix;
} }
@ -210,7 +221,7 @@ $suffixSelect->setSortElements(false);
$suffixSelect->setRightToLeftTextDirection(true); $suffixSelect->setRightToLeftTextDirection(true);
$dnContent->addElement($suffixSelect, true); $dnContent->addElement($suffixSelect, true);
// RDNs // RDNs
$rdns = getRDNAttributes($type); $rdns = getRDNAttributes($type->getId());
$selectedRDN = array(); $selectedRDN = array();
if (isset($old_options['ldap_rdn'][0])) { if (isset($old_options['ldap_rdn'][0])) {
$selectedRDN[] = $old_options['ldap_rdn'][0]; $selectedRDN[] = $old_options['ldap_rdn'][0];
@ -220,22 +231,22 @@ $dnContent->addElement(new htmlTableExtendedSelect('ldap_rdn', $rdns, $selectedR
$container->addElement(new htmlFieldset($dnContent, _("General settings"), '../../graphics/logo32.png'), true); $container->addElement(new htmlFieldset($dnContent, _("General settings"), '../../graphics/logo32.png'), true);
$container->addElement(new htmlSpacer(null, '15px'), true); $container->addElement(new htmlSpacer(null, '15px'), true);
$_SESSION['profile_types'] = parseHtml(null, $container, $old_options, false, $tabindex, $type); $_SESSION['profile_types'] = parseHtml(null, $container, $old_options, false, $tabindex, $type->getScope());
// display module options // display module options
$modules = array_keys($options); $modules = array_keys($options);
for ($m = 0; $m < sizeof($modules); $m++) { for ($m = 0; $m < sizeof($modules); $m++) {
// ignore modules without options // ignore modules without options
if (sizeof($options[$modules[$m]]) < 1) continue; if (sizeof($options[$modules[$m]]) < 1) continue;
$module = new $modules[$m]($type); $module = new $modules[$m]($type->getId());
$icon = $module->getIcon(); $icon = $module->getIcon();
if (($icon != null) && !(strpos($icon, 'http') === 0) && !(strpos($icon, '/') === 0)) { if (($icon != null) && !(strpos($icon, 'http') === 0) && !(strpos($icon, '/') === 0)) {
$icon = '../../graphics/' . $icon; $icon = '../../graphics/' . $icon;
} }
$container = new htmlTable(); $container = new htmlTable();
$container->addElement(new htmlFieldset($options[$modules[$m]], getModuleAlias($modules[$m], $type), $icon), true); $container->addElement(new htmlFieldset($options[$modules[$m]], getModuleAlias($modules[$m], $type->getScope()), $icon), true);
$container->addElement(new htmlSpacer(null, '15px'), true); $container->addElement(new htmlSpacer(null, '15px'), true);
$_SESSION['profile_types'] = array_merge($_SESSION['profile_types'], parseHtml($modules[$m], $container, $old_options, false, $tabindex, $type)); $_SESSION['profile_types'] = array_merge($_SESSION['profile_types'], parseHtml($modules[$m], $container, $old_options, false, $tabindex, $type->getScope()));
} }
// profile name and submit/abort buttons // profile name and submit/abort buttons
@ -246,9 +257,9 @@ $buttonTable->addElement($saveButton);
$cancelButton = new htmlButton('abort', _('Cancel')); $cancelButton = new htmlButton('abort', _('Cancel'));
$cancelButton->setIconClass('cancelButton'); $cancelButton->setIconClass('cancelButton');
$buttonTable->addElement($cancelButton); $buttonTable->addElement($cancelButton);
$buttonTable->addElement(new htmlHiddenInput('accounttype', $type)); $buttonTable->addElement(new htmlHiddenInput('accounttype', $type->getId()));
$_SESSION['profile_types'] = array_merge($_SESSION['profile_types'], parseHtml(null, $buttonTable, $old_options, false, $tabindex, $type)); $_SESSION['profile_types'] = array_merge($_SESSION['profile_types'], parseHtml(null, $buttonTable, $old_options, false, $tabindex, $type->getScope()));
?> ?>
<script type="text/javascript"> <script type="text/javascript">

View File

@ -62,11 +62,13 @@ if (!is_array($classes)) {
} }
else { else {
// loop for active account types // loop for active account types
for ($t = 0; $t < sizeof($types); $t++) { $typeManager = new \LAM\TYPES\TypeManager();
$modules = $_SESSION['config']->get_AccountModules($types[$t]); $types = $typeManager->getConfiguredTypes();
$container->addElement(new htmlSubTitle(LAM\TYPES\getTypeAlias($types[$t])), true); foreach ($types as $type) {
$modules = $_SESSION['config']->get_AccountModules($type->getId());
$container->addElement(new htmlSubTitle($type->getAlias()), true);
for ($m = 0; $m < sizeof($modules); $m++) { for ($m = 0; $m < sizeof($modules); $m++) {
$error = checkSchemaForModule($modules[$m], $types[$t]); $error = checkSchemaForModule($modules[$m], $type->getScope());
$message = _("No problems found."); $message = _("No problems found.");
$icon = '../../graphics/pass.png'; $icon = '../../graphics/pass.png';
if ($error != null) { if ($error != null) {
@ -74,7 +76,7 @@ else {
$message = $error; $message = $error;
} }
// module name // module name
$container->addElement(new htmlOutputText(getModuleAlias($modules[$m], $types[$t]))); $container->addElement(new htmlOutputText(getModuleAlias($modules[$m], $type->getScope())));
$container->addElement(new htmlSpacer('10px', null)); $container->addElement(new htmlSpacer('10px', null));
// icon // icon
$container->addElement(new htmlImage($icon)); $container->addElement(new htmlImage($icon));

View File

@ -1,9 +1,17 @@
<?php <?php
namespace LAM\UPLOAD;
use \htmlTable;
use \htmlSpacer;
use \htmlStatusMessage;
use \htmlLink;
use \htmlTitle;
use \htmlButton;
use \htmlHiddenInput;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2004 - 2016 Roland Gruber Copyright (C) 2004 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -89,20 +97,22 @@ if (isset($_GET['showldif'])) {
} }
include '../main_header.php'; include '../main_header.php';
$scope = htmlspecialchars($_POST['scope']); $typeId = htmlspecialchars($_POST['typeId']);
$typeManager = new \LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($typeId);
// check if account type is ok // check if account type is ok
if (isAccountTypeHidden($scope)) { if ($type->isHidden()) {
logNewMessage(LOG_ERR, 'User tried to access hidden upload: ' . $scope); logNewMessage(LOG_ERR, 'User tried to access hidden upload: ' . $type->getId());
die(); die();
} }
if (!checkIfNewEntriesAreAllowed($scope) || !checkIfWriteAccessIsAllowed($scope)) { if (!checkIfNewEntriesAreAllowed($type->getId()) || !checkIfWriteAccessIsAllowed($type->getId())) {
logNewMessage(LOG_ERR, 'User tried to access forbidden upload: ' . $scope); logNewMessage(LOG_ERR, 'User tried to access forbidden upload: ' . $type->getId());
die(); die();
} }
echo '<form enctype="multipart/form-data" action="masscreate.php" method="post">'; echo '<form enctype="multipart/form-data" action="masscreate.php" method="post">';
echo '<div class="' . $scope . '-bright smallPaddingContent">'; echo '<div class="' . $type->getScope() . '-bright smallPaddingContent">';
$container = new htmlTable(); $container = new htmlTable();
$selectedModules = explode(',', $_POST['selectedModules']); $selectedModules = explode(',', $_POST['selectedModules']);
@ -111,7 +121,7 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) {
$data = array(); // input values without first row $data = array(); // input values without first row
$ids = array(); // <column name> => <column number for $data> $ids = array(); // <column name> => <column number for $data>
// get input fields from modules // get input fields from modules
$columns = getUploadColumns($scope, $selectedModules); $columns = getUploadColumns($type->getScope(), $selectedModules);
// read input file // read input file
$handle = fopen ($_FILES['inputfile']['tmp_name'], "r"); $handle = fopen ($_FILES['inputfile']['tmp_name'], "r");
if (($head = fgetcsv($handle, 2000)) !== false ) { // head row if (($head = fgetcsv($handle, 2000)) !== false ) { // head row
@ -184,15 +194,15 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) {
$container->addElement(new htmlStatusMessage("ERROR", $errors[$i][0], $errors[$i][1]), true); $container->addElement(new htmlStatusMessage("ERROR", $errors[$i][0], $errors[$i][1]), true);
} }
$container->addElement(new htmlSpacer(null, '10px'), true); $container->addElement(new htmlSpacer(null, '10px'), true);
massPrintBackButton($scope, $selectedModules, $container); massPrintBackButton($type->getId(), $selectedModules, $container);
} }
// let modules build accounts // let modules build accounts
else { else {
$accounts = buildUploadAccounts($scope, $data, $ids, $selectedModules); $accounts = buildUploadAccounts($type->getId(), $data, $ids, $selectedModules);
if ($accounts != false) { if ($accounts != false) {
$rdnList = getRDNAttributes($scope, $selectedModules); $rdnList = getRDNAttributes($type->getId(), $selectedModules);
$suffix = $_SESSION['config']->get_Suffix($scope); $suffix = $type->getSuffix();
// set DN // set DN
foreach ($accounts as $i => $account) { foreach ($accounts as $i => $account) {
// check against list of possible RDN attributes // check against list of possible RDN attributes
@ -220,7 +230,7 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) {
$_SESSION['mass_postActions'] = array(); $_SESSION['mass_postActions'] = array();
$_SESSION['mass_data'] = lamEncrypt(serialize($data)); $_SESSION['mass_data'] = lamEncrypt(serialize($data));
$_SESSION['mass_ids'] = $ids; $_SESSION['mass_ids'] = $ids;
$_SESSION['mass_scope'] = $scope; $_SESSION['mass_typeId'] = $type->getId();
$_SESSION['mass_selectedModules'] = $selectedModules; $_SESSION['mass_selectedModules'] = $selectedModules;
if (isset($_SESSION['mass_pdf'])) { if (isset($_SESSION['mass_pdf'])) {
unset($_SESSION['mass_pdf']); unset($_SESSION['mass_pdf']);
@ -240,25 +250,25 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) {
$buttonContainer->addElement(new htmlLink(_("Upload accounts to LDAP"), 'massDoUpload.php', '../../graphics/up.gif', true)); $buttonContainer->addElement(new htmlLink(_("Upload accounts to LDAP"), 'massDoUpload.php', '../../graphics/up.gif', true));
$buttonContainer->addElement(new htmlLink(_("Show LDIF file"), 'massBuildAccounts.php?showldif=true', '../../graphics/edit.png', true)); $buttonContainer->addElement(new htmlLink(_("Show LDIF file"), 'massBuildAccounts.php?showldif=true', '../../graphics/edit.png', true));
$buttonContainer->addElement(new htmlSpacer('10px', null)); $buttonContainer->addElement(new htmlSpacer('10px', null));
massPrintBackButton($scope, $selectedModules, $buttonContainer); massPrintBackButton($type->getId(), $selectedModules, $buttonContainer);
$container->addElement($buttonContainer, true); $container->addElement($buttonContainer, true);
} }
} }
else { else {
$container->addElement(new htmlSpacer(null, '10px'), true); $container->addElement(new htmlSpacer(null, '10px'), true);
massPrintBackButton($scope, $selectedModules, $container); massPrintBackButton($type->getId(), $selectedModules, $container);
} }
} }
} }
else { else {
$container->addElement(new htmlStatusMessage('ERROR', _('Please provide a file to upload.')), true); $container->addElement(new htmlStatusMessage('ERROR', _('Please provide a file to upload.')), true);
$container->addElement(new htmlSpacer(null, '10px'), true); $container->addElement(new htmlSpacer(null, '10px'), true);
massPrintBackButton($scope, $selectedModules, $container); massPrintBackButton($type->getId(), $selectedModules, $container);
} }
addSecurityTokenToMetaHTML($container); addSecurityTokenToMetaHTML($container);
$tabindex = 1; $tabindex = 1;
parseHtml(null, $container, array(), false, $tabindex, $scope); parseHtml(null, $container, array(), false, $tabindex, $type->getScope());
echo '</div>'; echo '</div>';
echo '</form>'; echo '</form>';
@ -267,15 +277,15 @@ include '../main_footer.php';
/** /**
* Prints a back button to the page where the user enters a file to upload. * Prints a back button to the page where the user enters a file to upload.
* *
* @param String $scope account type (e.g. user) * @param String $typeId account type (e.g. user)
* @param array $selectedModules selected modules for upload * @param array $selectedModules selected modules for upload
* @param htmlTable $container table container * @param htmlTable $container table container
*/ */
function massPrintBackButton($scope, $selectedModules, &$container) { function massPrintBackButton($typeId, $selectedModules, &$container) {
$backButton = new htmlButton('submit', _('Back')); $backButton = new htmlButton('submit', _('Back'));
$backButton->setIconClass('backButton'); $backButton->setIconClass('backButton');
$container->addElement($backButton); $container->addElement($backButton);
$container->addElement(new htmlHiddenInput('type', $scope)); $container->addElement(new htmlHiddenInput('type', $typeId));
$createPDF = 0; $createPDF = 0;
if (isset($_POST['createPDF']) && ($_POST['createPDF'] == 'on')) { if (isset($_POST['createPDF']) && ($_POST['createPDF'] == 'on')) {
$createPDF = 1; $createPDF = 1;
@ -283,7 +293,7 @@ function massPrintBackButton($scope, $selectedModules, &$container) {
$container->addElement(new htmlHiddenInput('createPDF', $createPDF)); $container->addElement(new htmlHiddenInput('createPDF', $createPDF));
$container->addElement(new htmlHiddenInput('pdfStructure', $_POST['pdfStructure'])); $container->addElement(new htmlHiddenInput('pdfStructure', $_POST['pdfStructure']));
for ($i = 0; $i < sizeof($selectedModules); $i++) { for ($i = 0; $i < sizeof($selectedModules); $i++) {
$container->addElement(new htmlHiddenInput($scope . '_' . $selectedModules[$i], 'on')); $container->addElement(new htmlHiddenInput($typeId . '___' . $selectedModules[$i], 'on'));
} }
} }

View File

@ -1,9 +1,10 @@
<?php <?php
namespace LAM\UPLOAD;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2004 - 2013 Roland Gruber Copyright (C) 2004 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -61,24 +62,26 @@ if (!isLoggedIn()) {
setlanguage(); setlanguage();
include '../main_header.php'; include '../main_header.php';
$scope = htmlspecialchars($_SESSION['mass_scope']); $typeId = htmlspecialchars($_SESSION['mass_typeId']);
$typeManager = new \LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($typeId);
// check if account type is ok // check if account type is ok
if (isAccountTypeHidden($scope)) { if ($type->isHidden()) {
logNewMessage(LOG_ERR, 'User tried to access hidden upload: ' . $scope); logNewMessage(LOG_ERR, 'User tried to access hidden upload: ' . $type->getId());
die(); die();
} }
if (!checkIfNewEntriesAreAllowed($scope) || !checkIfWriteAccessIsAllowed($scope)) { if (!checkIfNewEntriesAreAllowed($type->getId()) || !checkIfWriteAccessIsAllowed($type->getId())) {
logNewMessage(LOG_ERR, 'User tried to access forbidden upload: ' . $scope); logNewMessage(LOG_ERR, 'User tried to access forbidden upload: ' . $type->getId());
die(); die();
} }
echo '<div id="uploadContent" class="' . $scope . '-bright smallPaddingContent">'; echo '<div id="uploadContent" class="' . $type->getScope() . '-bright smallPaddingContent">';
$tokenPrefix = '?' . getSecurityTokenName() . '=' . getSecurityTokenValue(); $tokenPrefix = '?' . getSecurityTokenName() . '=' . getSecurityTokenValue();
?> ?>
<script type="text/javascript"> <script type="text/javascript">
jQuery(document).ready(function(){ jQuery(document).ready(function(){
window.lam.upload.continueUpload('../misc/ajax.php' + '<?php echo $tokenPrefix; ?>' + '&function=upload&scope=' + '<?php echo $scope ?>'); window.lam.upload.continueUpload('../misc/ajax.php' + '<?php echo $tokenPrefix; ?>' + '&function=upload&typeId=' + '<?php echo $type->getId() ?>');
}); });
</script> </script>

View File

@ -1,9 +1,28 @@
<?php <?php
namespace LAM\UPLOAD;
use \htmlTable;
use \htmlTableExtendedSelect;
use \htmlSpacer;
use \htmlOutputText;
use \htmlGroup;
use \htmlElement;
use \htmlImage;
use \htmlTableExtendedInputCheckbox;
use \htmlDiv;
use \htmlHiddenInput;
use \htmlButton;
use \htmlTitle;
use \htmlInputFileUpload;
use \htmlLink;
use \htmlSubTitle;
use \htmlHelpLink;
use \htmlTableRow;
use \moduleCache;
/* /*
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2004 - 2016 Roland Gruber Copyright (C) 2004 - 2017 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -74,17 +93,18 @@ if (isset($_GET['getCSV'])) {
exit; exit;
} }
LAM\UPLOAD\Uploader::cleanSession(); Uploader::cleanSession();
include '../main_header.php'; include '../main_header.php';
// get possible types and remove those which do not support file upload // get possible types and remove those which do not support file upload
$types = $_SESSION['config']->get_ActiveTypes(); $typeManager = new \LAM\TYPES\TypeManager();
$types = $typeManager->getConfiguredTypes();
$count = sizeof($types); $count = sizeof($types);
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
$myType = new $types[$i](); $myType = $types[$i];
if (!$myType->supportsFileUpload() || isAccountTypeHidden($types[$i]) if (!$myType->getBaseType()->supportsFileUpload() || $myType->isHidden()
|| !checkIfNewEntriesAreAllowed($types[$i]) || !checkIfWriteAccessIsAllowed($types[$i])) { || !checkIfNewEntriesAreAllowed($myType->getId()) || !checkIfWriteAccessIsAllowed($myType->getId())) {
unset($types[$i]); unset($types[$i]);
} }
} }
@ -93,26 +113,27 @@ $types = array_values($types);
// check if account specific page should be shown // check if account specific page should be shown
if (isset($_POST['type'])) { if (isset($_POST['type'])) {
// get selected type // get selected type
$scope = htmlspecialchars($_POST['type']); $typeId = htmlspecialchars($_POST['type']);
$type = $typeManager->getConfiguredType($typeId);
// get selected modules // get selected modules
$selectedModules = array(); $selectedModules = array();
$checkedBoxes = array_keys($_POST, 'on'); $checkedBoxes = array_keys($_POST, 'on');
for ($i = 0; $i < sizeof($checkedBoxes); $i++) { for ($i = 0; $i < sizeof($checkedBoxes); $i++) {
if (strpos($checkedBoxes[$i], $scope . '_') === 0) { if (strpos($checkedBoxes[$i], $typeId . '___') === 0) {
$selectedModules[] = substr($checkedBoxes[$i], strlen($scope) + 1); $selectedModules[] = substr($checkedBoxes[$i], strlen($typeId) + strlen('___'));
} }
} }
$deps = getModulesDependencies($scope); $deps = getModulesDependencies($type->getScope());
$depErrors = check_module_depends($selectedModules, $deps); $depErrors = check_module_depends($selectedModules, $deps);
if (is_array($depErrors) && (sizeof($depErrors) > 0)) { if (is_array($depErrors) && (sizeof($depErrors) > 0)) {
for ($i = 0; $i < sizeof($depErrors); $i++) { for ($i = 0; $i < sizeof($depErrors); $i++) {
StatusMessage('ERROR', _("Unsolved dependency:") . ' ' . StatusMessage('ERROR', _("Unsolved dependency:") . ' ' .
getModuleAlias($depErrors[$i][0], $scope) . " (" . getModuleAlias($depErrors[$i][0], $type->getScope()) . " (" .
getModuleAlias($depErrors[$i][1], $scope) . ")"); getModuleAlias($depErrors[$i][1], $type->getScope()) . ")");
} }
} }
else { else {
showMainPage($scope, $selectedModules); showMainPage($type, $selectedModules);
exit; exit;
} }
} }
@ -120,7 +141,7 @@ if (isset($_POST['type'])) {
// show start page // show start page
$divClass = 'user'; $divClass = 'user';
if (isset($_REQUEST['type'])) { if (isset($_REQUEST['type'])) {
$divClass = $_REQUEST['type']; $divClass = \LAM\TYPES\getScopeFromTypeId($_REQUEST['type']);
} }
echo '<div class="' . $divClass . '-bright smallPaddingContent">'; echo '<div class="' . $divClass . '-bright smallPaddingContent">';
echo "<div class=\"title\">\n"; echo "<div class=\"title\">\n";
@ -141,15 +162,15 @@ $table = new htmlTable();
// account type // account type
$typeList = array(); $typeList = array();
for ($i = 0; $i < sizeof($types); $i++) { foreach ($types as $type) {
$typeList[LAM\TYPES\getTypeAlias($types[$i])] = $types[$i]; $typeList[$type->getAlias()] = $type->getId();
} }
$selectedType = array(); $selectedType = array();
if (isset($_REQUEST['type'])) { if (isset($_REQUEST['type'])) {
$selectedType[] = $_REQUEST['type']; $selectedType[] = $_REQUEST['type'];
} }
elseif (!empty($types)) { elseif (!empty($types)) {
$selectedType[] = $types[0]; $selectedType[] = $types[0]->getId();
} }
$typeSelect = new htmlTableExtendedSelect('type', $typeList, $selectedType, _("Account type")); $typeSelect = new htmlTableExtendedSelect('type', $typeList, $selectedType, _("Account type"));
$typeSelect->setHasDescriptiveElements(true); $typeSelect->setHasDescriptiveElements(true);
@ -162,32 +183,32 @@ $moduleLabel = new htmlOutputText(_('Selected modules'));
$moduleLabel->alignment = htmlElement::ALIGN_TOP; $moduleLabel->alignment = htmlElement::ALIGN_TOP;
$table->addElement($moduleLabel); $table->addElement($moduleLabel);
$moduleGroup = new htmlGroup(); $moduleGroup = new htmlGroup();
for ($i = 0; $i < sizeof($types); $i++) { foreach ($types as $type) {
$divClasses = array('typeOptions'); $divClasses = array('typeOptions');
if ((!isset($_REQUEST['type']) && ($i != 0)) || (isset($_REQUEST['type']) && ($_REQUEST['type'] != $types[$i]))) { if ((!isset($_REQUEST['type']) && ($i != 0)) || (isset($_REQUEST['type']) && ($_REQUEST['type'] != $type->getId()))) {
$divClasses[] = 'hidden'; $divClasses[] = 'hidden';
} }
$innerTable = new htmlTable(); $innerTable = new htmlTable();
$modules = $_SESSION['config']->get_AccountModules($types[$i]); $modules = $_SESSION['config']->get_AccountModules($type->getId());
for ($m = 0; $m < sizeof($modules); $m++) { for ($m = 0; $m < sizeof($modules); $m++) {
if (($m != 0) && ($m%3 == 0)) { if (($m != 0) && ($m%3 == 0)) {
echo $innerTable->addNewLine(); echo $innerTable->addNewLine();
} }
$module = moduleCache::getModule($modules[$m], $types[$i]); $module = moduleCache::getModule($modules[$m], $type->getScope());
$iconImage = $module->getIcon(); $iconImage = $module->getIcon();
if (!is_null($iconImage) && !(strpos($iconImage, 'http') === 0) && !(strpos($iconImage, '/') === 0)) { if (!is_null($iconImage) && !(strpos($iconImage, 'http') === 0) && !(strpos($iconImage, '/') === 0)) {
$iconImage = '../../graphics/' . $iconImage; $iconImage = '../../graphics/' . $iconImage;
} }
$innerTable->addElement(new htmlImage($iconImage)); $innerTable->addElement(new htmlImage($iconImage));
$enabled = true; $enabled = true;
if (is_base_module($modules[$m], $types[$i])) { if (is_base_module($modules[$m], $type->getScope())) {
$enabled = false; $enabled = false;
} }
$checked = true; $checked = true;
if (isset($_POST['submit']) && !isset($_POST[$types[$i] . '_' . $modules[$m]])) { if (isset($_POST['submit']) && !isset($_POST[$type->getId() . '___' . $modules[$m]])) {
$checked = false; $checked = false;
} }
$checkbox = new htmlTableExtendedInputCheckbox($types[$i] . '_' . $modules[$m], $checked, getModuleAlias($modules[$m], $types[$i]), null, false); $checkbox = new htmlTableExtendedInputCheckbox($type->getId() . '___' . $modules[$m], $checked, getModuleAlias($modules[$m], $type->getScope()), null, false);
$checkbox->setIsEnabled($enabled); $checkbox->setIsEnabled($enabled);
if ($enabled) { if ($enabled) {
$innerTable->addElement($checkbox); $innerTable->addElement($checkbox);
@ -196,12 +217,12 @@ for ($i = 0; $i < sizeof($types); $i++) {
$boxGroup = new htmlGroup(); $boxGroup = new htmlGroup();
$boxGroup->addElement($checkbox); $boxGroup->addElement($checkbox);
// add hidden field to fake disabled checkbox value // add hidden field to fake disabled checkbox value
$boxGroup->addElement(new htmlHiddenInput($types[$i] . '_' . $modules[$m], 'on')); $boxGroup->addElement(new htmlHiddenInput($type->getId() . '___' . $modules[$m], 'on'));
$innerTable->addElement($boxGroup); $innerTable->addElement($boxGroup);
} }
$innerTable->addElement(new htmlSpacer('10px', null)); $innerTable->addElement(new htmlSpacer('10px', null));
} }
$typeDiv = new htmlDiv($types[$i], $innerTable); $typeDiv = new htmlDiv($type->getId(), $innerTable);
$typeDiv->setCSSClasses($divClasses); $typeDiv->setCSSClasses($divClasses);
$moduleGroup->addElement($typeDiv); $moduleGroup->addElement($typeDiv);
} }
@ -231,10 +252,11 @@ include '../main_footer.php';
/** /**
* Displays the acount type specific main page of the upload. * Displays the acount type specific main page of the upload.
* *
* @param string $scope account type * @param \LAM\TYPES\ConfiguredType $type account type
* @param array $selectedModules list of selected account modules * @param array $selectedModules list of selected account modules
*/ */
function showMainPage($scope, $selectedModules) { function showMainPage($type, $selectedModules) {
$scope = $type->getScope();
echo '<div class="' . $scope . '-bright smallPaddingContent">'; echo '<div class="' . $scope . '-bright smallPaddingContent">';
// get input fields from modules // get input fields from modules
$columns = getUploadColumns($scope, $selectedModules); $columns = getUploadColumns($scope, $selectedModules);
@ -257,7 +279,7 @@ function showMainPage($scope, $selectedModules) {
$inputContainer->addElement(new htmlInputFileUpload('inputfile')); $inputContainer->addElement(new htmlInputFileUpload('inputfile'));
$inputContainer->addElement(new htmlSpacer('10px', null)); $inputContainer->addElement(new htmlSpacer('10px', null));
$inputContainer->addElement(new htmlLink(_("Download sample CSV file"), 'masscreate.php?getCSV=1', '../../graphics/save.png', true)); $inputContainer->addElement(new htmlLink(_("Download sample CSV file"), 'masscreate.php?getCSV=1', '../../graphics/save.png', true));
$inputContainer->addElement(new htmlHiddenInput('scope', $scope)); $inputContainer->addElement(new htmlHiddenInput('typeId', $type->getId()));
$inputContainer->addElement(new htmlHiddenInput('selectedModules', implode(',', $selectedModules)), true); $inputContainer->addElement(new htmlHiddenInput('selectedModules', implode(',', $selectedModules)), true);
// PDF // PDF
$createPDF = false; $createPDF = false;
@ -267,7 +289,7 @@ function showMainPage($scope, $selectedModules) {
$pdfCheckbox = new htmlTableExtendedInputCheckbox('createPDF', $createPDF, _('Create PDF files')); $pdfCheckbox = new htmlTableExtendedInputCheckbox('createPDF', $createPDF, _('Create PDF files'));
$pdfCheckbox->setTableRowsToShow(array('pdfStructure')); $pdfCheckbox->setTableRowsToShow(array('pdfStructure'));
$inputContainer->addElement($pdfCheckbox, true); $inputContainer->addElement($pdfCheckbox, true);
$pdfStructures = getPDFStructureDefinitions($scope); $pdfStructures = \LAM\PDF\getPDFStructures($type->getId());
$pdfSelected = array(); $pdfSelected = array();
if (isset($_POST['pdfStructure'])) { if (isset($_POST['pdfStructure'])) {
$pdfSelected = array($_POST['pdfStructure']); $pdfSelected = array($_POST['pdfStructure']);
@ -321,9 +343,9 @@ function showMainPage($scope, $selectedModules) {
$dnSuffixRowCells[] = $columnSpacer; $dnSuffixRowCells[] = $columnSpacer;
$dnSuffixRowCells[] = new htmlOutputText('dn_suffix'); $dnSuffixRowCells[] = new htmlOutputText('dn_suffix');
$dnSuffixRowCells[] = $columnSpacer; $dnSuffixRowCells[] = $columnSpacer;
$dnSuffixRowCells[] = new htmlOutputText($_SESSION['config']->get_Suffix($scope)); $dnSuffixRowCells[] = new htmlOutputText($type->getSuffix());
$dnSuffixRowCells[] = $columnSpacer; $dnSuffixRowCells[] = $columnSpacer;
$dnSuffixRowCells[] = new htmlOutputText($_SESSION['config']->get_Suffix($scope)); $dnSuffixRowCells[] = new htmlOutputText($type->getSuffix());
$dnSuffixRowCells[] = $columnSpacer; $dnSuffixRowCells[] = $columnSpacer;
$dnSuffixRowCells[] = new htmlOutputText(''); $dnSuffixRowCells[] = new htmlOutputText('');
$dnSuffixRowCells[] = new htmlSpacer(null, '25px'); $dnSuffixRowCells[] = new htmlSpacer(null, '25px');
@ -340,7 +362,7 @@ function showMainPage($scope, $selectedModules) {
$dnRDNRowCells[] = $columnSpacer; $dnRDNRowCells[] = $columnSpacer;
$dnRDNRowCells[] = new htmlOutputText('dn_rdn'); $dnRDNRowCells[] = new htmlOutputText('dn_rdn');
$dnRDNRowCells[] = $columnSpacer; $dnRDNRowCells[] = $columnSpacer;
$rdnAttributes = getRDNAttributes($scope, $selectedModules); $rdnAttributes = getRDNAttributes($type->getId(), $selectedModules);
$dnRDNRowCells[] = new htmlOutputText($rdnAttributes[0]); $dnRDNRowCells[] = new htmlOutputText($rdnAttributes[0]);
$dnRDNRowCells[] = $columnSpacer; $dnRDNRowCells[] = $columnSpacer;
$dnRDNRowCells[] = new htmlOutputText(''); $dnRDNRowCells[] = new htmlOutputText('');
@ -456,9 +478,9 @@ function showMainPage($scope, $selectedModules) {
$sampleCSV_head[] = "\"" . $columns[$modules[$m]][$i]['name'] . "\""; $sampleCSV_head[] = "\"" . $columns[$modules[$m]][$i]['name'] . "\"";
} }
} }
$RDNs = getRDNAttributes($scope, $selectedModules); $RDNs = getRDNAttributes($type->getId(), $selectedModules);
// DN attributes // DN attributes
$sampleCSV_row[] = "\"" . $_SESSION['config']->get_Suffix($scope) . "\""; $sampleCSV_row[] = "\"" . $type->getSuffix() . "\"";
$sampleCSV_row[] = "\"" . $RDNs[0] . "\""; $sampleCSV_row[] = "\"" . $RDNs[0] . "\"";
// module attributes // module attributes
for ($m = 0; $m < sizeof($modules); $m++) { for ($m = 0; $m < sizeof($modules); $m++) {

View File

@ -21,7 +21,7 @@
*/ */
include_once (dirname ( __FILE__ ) . '/../utils/configuration.inc'); include_once 'lam/tests/utils/configuration.inc';
/** /**
* LAMConfig test case. * LAMConfig test case.
@ -252,6 +252,12 @@ class LAMConfigTest extends PHPUnit_Framework_TestCase {
$this->assertEquals($val, $this->lAMConfig->get_scriptPath()); $this->assertEquals($val, $this->lAMConfig->get_scriptPath());
$this->doSave(); $this->doSave();
$this->assertEquals($val, $this->lAMConfig->get_scriptPath()); $this->assertEquals($val, $this->lAMConfig->get_scriptPath());
// empty script
$val = '';
$this->lAMConfig->set_scriptPath($val);
$this->assertEquals($val, $this->lAMConfig->get_scriptPath());
$this->doSave();
$this->assertEquals($val, $this->lAMConfig->get_scriptPath());
} }
/** /**

View File

@ -21,200 +21,203 @@
*/ */
include_once (dirname ( __FILE__ ) . '/../../../lib/baseModule.inc'); if (is_readable('lam/lib/modules/ppolicyUser.inc')) {
include_once (dirname ( __FILE__ ) . '/../../../lib/modules.inc');
include_once (dirname ( __FILE__ ) . '/../../../lib/passwordExpirationJob.inc');
include_once (dirname ( __FILE__ ) . '/../../../lib/modules/ppolicyUser.inc');
/** include_once 'lam/lib/baseModule.inc';
* Checks the ppolicy expire job. include_once 'lam/lib/modules.inc';
* include_once 'lam/lib/passwordExpirationJob.inc';
* @author Roland Gruber include_once 'lam/lib/modules/ppolicyUser.inc';
*
*/
class PPolicyUserPasswordNotifyJobTest extends PHPUnit_Framework_TestCase {
private $job; /**
* Checks the ppolicy expire job.
*
* @author Roland Gruber
*
*/
class PPolicyUserPasswordNotifyJobTest extends PHPUnit_Framework_TestCase {
const JOB_ID = 'jobID'; private $job;
const WARNING = '14';
const DEFAULT_POLICY = 'cn=default,dc=test';
const NOEXPIRE_POLICY = 'cn=noexpire,dc=test';
const ONE_YEAR_POLICY = 'cn=policy1,dc=test';
private $options = array(); const JOB_ID = 'jobID';
const WARNING = '14';
const DEFAULT_POLICY = 'cn=default,dc=test';
const NOEXPIRE_POLICY = 'cn=noexpire,dc=test';
const ONE_YEAR_POLICY = 'cn=policy1,dc=test';
public function setUp() { private $options = array();
$this->job = $this->getMockBuilder('PPolicyPasswordNotifyJob')
->setMethods(array('getDBLastPwdChangeTime', 'setDBLastPwdChangeTime', 'sendMail',
'findUsers', 'getConfigPrefix', 'getPolicyOptions'))
->getMock();
$this->job->method('getConfigPrefix')->willReturn('test');
$this->job->method('sendMail')->willReturn(true);
$this->job->method('getPolicyOptions')->willReturn(array(
PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY => array('pwdmaxage' => 365 * 3600 * 24),
PPolicyUserPasswordNotifyJobTest::DEFAULT_POLICY => array('pwdmaxage' => 14 * 3600 * 24),
PPolicyUserPasswordNotifyJobTest::NOEXPIRE_POLICY => array('pwdmaxage' => 0),
));
$this->options['test_mailNotificationPeriod' . PPolicyUserPasswordNotifyJobTest::JOB_ID][0] = PPolicyUserPasswordNotifyJobTest::WARNING;
$this->options['test_mailDefaultPolicy' . PPolicyUserPasswordNotifyJobTest::JOB_ID][0] = PPolicyUserPasswordNotifyJobTest::DEFAULT_POLICY;
}
public function testNoAccounts() { public function setUp() {
$this->job->method('findUsers')->willReturn(array()); $this->job = $this->getMockBuilder('PPolicyPasswordNotifyJob')
->setMethods(array('getDBLastPwdChangeTime', 'setDBLastPwdChangeTime', 'sendMail',
'findUsers', 'getConfigPrefix', 'getPolicyOptions'))
->getMock();
$this->job->method('getConfigPrefix')->willReturn('test');
$this->job->method('sendMail')->willReturn(true);
$this->job->method('getPolicyOptions')->willReturn(array(
PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY => array('pwdmaxage' => 365 * 3600 * 24),
PPolicyUserPasswordNotifyJobTest::DEFAULT_POLICY => array('pwdmaxage' => 14 * 3600 * 24),
PPolicyUserPasswordNotifyJobTest::NOEXPIRE_POLICY => array('pwdmaxage' => 0),
));
$this->options['test_mailNotificationPeriod' . PPolicyUserPasswordNotifyJobTest::JOB_ID][0] = PPolicyUserPasswordNotifyJobTest::WARNING;
$this->options['test_mailDefaultPolicy' . PPolicyUserPasswordNotifyJobTest::JOB_ID][0] = PPolicyUserPasswordNotifyJobTest::DEFAULT_POLICY;
}
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testNoAccounts() {
$this->job->expects($this->never())->method('sendMail'); $this->job->method('findUsers')->willReturn(array());
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testAccountDoesNotExpire() { $pdo = array();
$this->job->method('findUsers')->willReturn(array(array( $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
'dn' => 'cn=noexpire,dc=dn', }
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::NOEXPIRE_POLICY),
'pwdchangedtime' => array('20000101112233Z')
)));
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testAccountDoesNotExpire() {
$this->job->expects($this->never())->method('sendMail'); $this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=noexpire,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::NOEXPIRE_POLICY),
'pwdchangedtime' => array('20000101112233Z')
)));
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testAccountLocked() { $pdo = array();
$this->job->method('findUsers')->willReturn(array(array( $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
'dn' => 'cn=locked,dc=dn', }
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdaccountlockedtime' => array('20010101112233Z'),
'pwdchangedtime' => array('20000101112233Z')
)));
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testAccountLocked() {
$this->job->expects($this->never())->method('sendMail'); $this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=locked,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdaccountlockedtime' => array('20010101112233Z'),
'pwdchangedtime' => array('20000101112233Z')
)));
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testAccountExpired() { $pdo = array();
$this->job->method('findUsers')->willReturn(array(array( $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
'dn' => 'cn=expired,dc=dn', }
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array('20000101112233Z'),
)));
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testAccountExpired() {
$this->job->expects($this->never())->method('sendMail'); $this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=expired,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array('20000101112233Z'),
)));
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testWarningNotReached() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$lastChangeNow = floor($now->format('U')/3600/24); }
$this->job->method('getDBLastPwdChangeTime')->willReturn($lastChangeNow);
$date = new DateTime('now', new DateTimeZone('UTC'));
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=notReached,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testWarningNotReached() {
$this->job->expects($this->never())->method('sendMail'); $now = new DateTime('now', getTimeZone());
$lastChangeNow = floor($now->format('U')/3600/24);
$this->job->method('getDBLastPwdChangeTime')->willReturn($lastChangeNow);
$date = new DateTime('now', new DateTimeZone('UTC'));
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=notReached,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testAlreadyWarned() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$date = new DateTime('now', new DateTimeZone('UTC')); }
$date->sub(new DateInterval('P360D'));
$this->job->method('getDBLastPwdChangeTime')->willReturn($date->format('YmdHis') . 'Z');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=alreadyWarned,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$this->job->expects($this->once())->method('getDBLastPwdChangeTime'); public function testAlreadyWarned() {
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); $now = new DateTime('now', getTimeZone());
$this->job->expects($this->never())->method('sendMail'); $date = new DateTime('now', new DateTimeZone('UTC'));
$date->sub(new DateInterval('P360D'));
$this->job->method('getDBLastPwdChangeTime')->willReturn($date->format('YmdHis') . 'Z');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=alreadyWarned,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$pdo = array(); $this->job->expects($this->once())->method('getDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
} $this->job->expects($this->never())->method('sendMail');
public function testWarning() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$date = new DateTime('now', new DateTimeZone('UTC')); }
$date->sub(new DateInterval('P360D'));
$this->job->method('getDBLastPwdChangeTime')->willReturn('20001111101010Z');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=alreadyWarned,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$this->job->expects($this->once())->method('getDBLastPwdChangeTime'); public function testWarning() {
$this->job->expects($this->once())->method('setDBLastPwdChangeTime'); $now = new DateTime('now', getTimeZone());
$this->job->expects($this->once())->method('sendMail'); $date = new DateTime('now', new DateTimeZone('UTC'));
$date->sub(new DateInterval('P360D'));
$this->job->method('getDBLastPwdChangeTime')->willReturn('20001111101010Z');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=alreadyWarned,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$pdo = array(); $this->job->expects($this->once())->method('getDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->once())->method('setDBLastPwdChangeTime');
} $this->job->expects($this->once())->method('sendMail');
public function testWarningDryRun() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$date = new DateTime('now', new DateTimeZone('UTC')); }
$date->sub(new DateInterval('P360D'));
$this->job->method('getDBLastPwdChangeTime')->willReturn('20001111101010Z');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=alreadyWarned,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$this->job->expects($this->once())->method('getDBLastPwdChangeTime'); public function testWarningDryRun() {
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); $now = new DateTime('now', getTimeZone());
$this->job->expects($this->never())->method('sendMail'); $date = new DateTime('now', new DateTimeZone('UTC'));
$date->sub(new DateInterval('P360D'));
$this->job->method('getDBLastPwdChangeTime')->willReturn('20001111101010Z');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=alreadyWarned,dc=dn',
'pwdpolicysubentry' => array(PPolicyUserPasswordNotifyJobTest::ONE_YEAR_POLICY),
'pwdchangedtime' => array($date->format('YmdHis') . 'Z'),
)));
$pdo = array(); $this->job->expects($this->once())->method('getDBLastPwdChangeTime');
$this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, true); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
} $this->job->expects($this->never())->method('sendMail');
public function testGetWarningTimeInSeconds() { $pdo = array();
$confDays = 7; $this->job->execute(PPolicyUserPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, true);
$policy = array('pwdmaxage' => 365 * 3600 * 24, 'pwdexpirewarning' => 10000); }
$seconds = $this->job->getWarningTimeInSeconds($confDays, $policy); public function testGetWarningTimeInSeconds() {
$confDays = 7;
$policy = array('pwdmaxage' => 365 * 3600 * 24, 'pwdexpirewarning' => 10000);
$this->assertEquals((7*3600*24 + 10000), $seconds); $seconds = $this->job->getWarningTimeInSeconds($confDays, $policy);
$this->assertEquals((7*3600*24 + 10000), $seconds);
$confDays = 0; $confDays = 0;
$policy = array('pwdmaxage' => 365 * 3600 * 24, 'pwdexpirewarning' => 10000); $policy = array('pwdmaxage' => 365 * 3600 * 24, 'pwdexpirewarning' => 10000);
$seconds = $this->job->getWarningTimeInSeconds($confDays, $policy); $seconds = $this->job->getWarningTimeInSeconds($confDays, $policy);
$this->assertEquals(10000, $seconds); $this->assertEquals(10000, $seconds);
$confDays = 7; $confDays = 7;
$policy = array('pwdmaxage' => 365 * 3600 * 24); $policy = array('pwdmaxage' => 365 * 3600 * 24);
$seconds = $this->job->getWarningTimeInSeconds($confDays, $policy); $seconds = $this->job->getWarningTimeInSeconds($confDays, $policy);
$this->assertEquals(7*3600*24, $seconds); $this->assertEquals(7*3600*24, $seconds);
}
} }
} }
?> ?>

View File

@ -21,10 +21,9 @@
*/ */
include_once (dirname ( __FILE__ ) . '/../../../lib/baseModule.inc'); include_once 'lam/lib/baseModule.inc';
include_once (dirname ( __FILE__ ) . '/../../../lib/modules.inc'); include_once 'lam/lib/modules.inc';
include_once (dirname ( __FILE__ ) . '/../../../lib/passwordExpirationJob.inc'); include_once 'lam/lib/modules/sambaSamAccount.inc';
include_once (dirname ( __FILE__ ) . '/../../../lib/modules/sambaSamAccount.inc');
/** /**
* Checks the shadow expire job. * Checks the shadow expire job.

View File

@ -21,145 +21,148 @@
*/ */
include_once (dirname ( __FILE__ ) . '/../../../lib/baseModule.inc'); if (is_readable('lam/lib/passwordExpirationJob.inc')) {
include_once (dirname ( __FILE__ ) . '/../../../lib/modules.inc');
include_once (dirname ( __FILE__ ) . '/../../../lib/passwordExpirationJob.inc');
include_once (dirname ( __FILE__ ) . '/../../../lib/modules/shadowAccount.inc');
/** include_once 'lam/lib/baseModule.inc';
* Checks the shadow expire job. include_once 'lam/lib/modules.inc';
* include_once 'lam/lib/passwordExpirationJob.inc';
* @author Roland Gruber include_once 'lam/lib/modules/shadowAccount.inc';
*
*/
class ShadowAccountPasswordNotifyJobTest extends PHPUnit_Framework_TestCase {
private $job; /**
* Checks the shadow expire job.
*
* @author Roland Gruber
*
*/
class ShadowAccountPasswordNotifyJobTest extends PHPUnit_Framework_TestCase {
const JOB_ID = 'jobID'; private $job;
const WARNING = '14';
private $options = array(); const JOB_ID = 'jobID';
const WARNING = '14';
public function setUp() { private $options = array();
$this->job = $this->getMockBuilder('ShadowAccountPasswordNotifyJob')
->setMethods(array('getDBLastPwdChangeTime', 'setDBLastPwdChangeTime', 'sendMail', 'findUsers', 'getConfigPrefix'))
->getMock();
$this->job->method('getConfigPrefix')->willReturn('test');
$this->job->method('sendMail')->willReturn(true);
$this->options['test_mailNotificationPeriod' . ShadowAccountPasswordNotifyJobTest::JOB_ID][0] = ShadowAccountPasswordNotifyJobTest::WARNING;
}
public function testNoAccounts() { public function setUp() {
$this->job->method('findUsers')->willReturn(array()); $this->job = $this->getMockBuilder('ShadowAccountPasswordNotifyJob')
->setMethods(array('getDBLastPwdChangeTime', 'setDBLastPwdChangeTime', 'sendMail', 'findUsers', 'getConfigPrefix'))
->getMock();
$this->job->method('getConfigPrefix')->willReturn('test');
$this->job->method('sendMail')->willReturn(true);
$this->options['test_mailNotificationPeriod' . ShadowAccountPasswordNotifyJobTest::JOB_ID][0] = ShadowAccountPasswordNotifyJobTest::WARNING;
}
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testNoAccounts() {
$this->job->expects($this->never())->method('sendMail'); $this->job->method('findUsers')->willReturn(array());
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testAccountDoesNotExpire() { $pdo = array();
$this->job->method('findUsers')->willReturn(array(array( $this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
'dn' => 'cn=some,dc=dn', }
'shadowmax' => array('0'),
'shadowlastchange' => array('1')
)));
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testAccountDoesNotExpire() {
$this->job->expects($this->never())->method('sendMail'); $this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('0'),
'shadowlastchange' => array('1')
)));
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testAccountExpired() { $pdo = array();
$this->job->method('findUsers')->willReturn(array(array( $this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
'dn' => 'cn=some,dc=dn', }
'shadowmax' => array('10'),
'shadowlastchange' => array('1')
)));
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testAccountExpired() {
$this->job->expects($this->never())->method('sendMail'); $this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('10'),
'shadowlastchange' => array('1')
)));
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testWarningNotReached() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$lastChangeNow = floor($now->format('U')/3600/24); }
$this->job->method('getDBLastPwdChangeTime')->willReturn($lastChangeNow);
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('300'),
'shadowlastchange' => array($lastChangeNow)
)));
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); public function testWarningNotReached() {
$this->job->expects($this->never())->method('sendMail'); $now = new DateTime('now', getTimeZone());
$lastChangeNow = floor($now->format('U')/3600/24);
$this->job->method('getDBLastPwdChangeTime')->willReturn($lastChangeNow);
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('300'),
'shadowlastchange' => array($lastChangeNow)
)));
$pdo = array(); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('sendMail');
}
public function testAlreadyWarned() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$lastChangeNow = floor($now->format('U')/3600/24); }
$this->job->method('getDBLastPwdChangeTime')->willReturn($lastChangeNow);
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('10'),
'shadowlastchange' => array($lastChangeNow)
)));
$this->job->expects($this->once())->method('getDBLastPwdChangeTime'); public function testAlreadyWarned() {
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); $now = new DateTime('now', getTimeZone());
$this->job->expects($this->never())->method('sendMail'); $lastChangeNow = floor($now->format('U')/3600/24);
$this->job->method('getDBLastPwdChangeTime')->willReturn($lastChangeNow);
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('10'),
'shadowlastchange' => array($lastChangeNow)
)));
$pdo = array(); $this->job->expects($this->once())->method('getDBLastPwdChangeTime');
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->never())->method('setDBLastPwdChangeTime');
} $this->job->expects($this->never())->method('sendMail');
public function testWarning() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$lastChangeNow = floor($now->format('U')/3600/24); }
$this->job->method('getDBLastPwdChangeTime')->willReturn('1');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('10'),
'shadowlastchange' => array($lastChangeNow)
)));
$this->job->expects($this->once())->method('getDBLastPwdChangeTime'); public function testWarning() {
$this->job->expects($this->once())->method('setDBLastPwdChangeTime'); $now = new DateTime('now', getTimeZone());
$this->job->expects($this->once())->method('sendMail'); $lastChangeNow = floor($now->format('U')/3600/24);
$this->job->method('getDBLastPwdChangeTime')->willReturn('1');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('10'),
'shadowlastchange' => array($lastChangeNow)
)));
$pdo = array(); $this->job->expects($this->once())->method('getDBLastPwdChangeTime');
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false); $this->job->expects($this->once())->method('setDBLastPwdChangeTime');
} $this->job->expects($this->once())->method('sendMail');
public function testWarningDryRun() { $pdo = array();
$now = new DateTime('now', getTimeZone()); $this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, false);
$lastChangeNow = floor($now->format('U')/3600/24); }
$this->job->method('getDBLastPwdChangeTime')->willReturn('1');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('10'),
'shadowlastchange' => array($lastChangeNow)
)));
$this->job->expects($this->once())->method('getDBLastPwdChangeTime'); public function testWarningDryRun() {
$this->job->expects($this->never())->method('setDBLastPwdChangeTime'); $now = new DateTime('now', getTimeZone());
$this->job->expects($this->never())->method('sendMail'); $lastChangeNow = floor($now->format('U')/3600/24);
$this->job->method('getDBLastPwdChangeTime')->willReturn('1');
$this->job->method('findUsers')->willReturn(array(array(
'dn' => 'cn=some,dc=dn',
'shadowmax' => array('10'),
'shadowlastchange' => array($lastChangeNow)
)));
$this->job->expects($this->once())->method('getDBLastPwdChangeTime');
$this->job->expects($this->never())->method('setDBLastPwdChangeTime');
$this->job->expects($this->never())->method('sendMail');
$pdo = array();
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, true);
}
$pdo = array();
$this->job->execute(ShadowAccountPasswordNotifyJobTest::JOB_ID, $this->options, $pdo, true);
} }
} }
?> ?>

View File

@ -3,7 +3,7 @@
$Id$ $Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2014 Roland Gruber Copyright (C) 2014 - 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -21,59 +21,63 @@ $Id$
*/ */
include_once (dirname ( __FILE__ ) . '/../../../lib/baseModule.inc'); if (is_readable('lam/lib/modules/sudoRole.inc')) {
include_once (dirname ( __FILE__ ) . '/../../../lib/modules/sudoRole.inc');
/** include_once 'lam/lib/baseModule.inc';
* Checks sudo role functions. include_once 'lam/lib/modules/sudoRole.inc';
*
* @author Roland Gruber
*
*/
class SudoRoleTest extends PHPUnit_Framework_TestCase {
public function testIsValidDate() { /**
$valid = array('22.10.2014', '05.01.2013', '1.3.2014', '10.5.2014', '4.12.2015', * Checks sudo role functions.
'05.01.2013 22:15', '1.3.2014 5:1', '10.5.2014 13:3', '4.12.2015 5:22'); *
foreach ($valid as $testDate) { * @author Roland Gruber
$this->assertTrue(sudoRole::isValidDate($testDate)); *
} */
$invalid = array('10.25.2014', 'abc', '2014-10-12', '10.022014', '10:12', '22.10.2014 12'); class SudoRoleTest extends PHPUnit_Framework_TestCase {
foreach ($invalid as $testDate) {
$this->assertNotTrue(sudoRole::isValidDate($testDate), $testDate);
}
}
public function testEncodeDate() { public function testIsValidDate() {
$dates = array( $valid = array('22.10.2014', '05.01.2013', '1.3.2014', '10.5.2014', '4.12.2015',
'1.2.2014' => '20140201000000Z', '05.01.2013 22:15', '1.3.2014 5:1', '10.5.2014 13:3', '4.12.2015 5:22');
'10.2.2014' => '20140210000000Z', foreach ($valid as $testDate) {
'1.11.2014' => '20141101000000Z', $this->assertTrue(sudoRole::isValidDate($testDate));
'20.12.2014' => '20141220000000Z', }
'1.2.2014 1:2' => '20140201010200Z', $invalid = array('10.25.2014', 'abc', '2014-10-12', '10.022014', '10:12', '22.10.2014 12');
'10.2.2014 1:10' => '20140210011000Z', foreach ($invalid as $testDate) {
'1.11.2014 10:2' => '20141101100200Z', $this->assertNotTrue(sudoRole::isValidDate($testDate), $testDate);
'20.12.2014 10:12' => '20141220101200Z', }
);
foreach ($dates as $input => $output) {
$this->assertEquals($output, sudoRole::encodeDate($input), $input . ' ' . $output);
} }
}
public function testDecodeDate() { public function testEncodeDate() {
$dates = array( $dates = array(
'01.02.2014 00:00' => '20140201000000Z', '1.2.2014' => '20140201000000Z',
'10.02.2014 00:00' => '20140210000000Z', '10.2.2014' => '20140210000000Z',
'01.11.2014 00:00' => '20141101000000Z', '1.11.2014' => '20141101000000Z',
'20.12.2014 00:00' => '20141220000000Z', '20.12.2014' => '20141220000000Z',
'01.02.2014 01:02' => '20140201010200Z', '1.2.2014 1:2' => '20140201010200Z',
'10.02.2014 01:10' => '20140210011000Z', '10.2.2014 1:10' => '20140210011000Z',
'01.11.2014 10:02' => '20141101100200Z', '1.11.2014 10:2' => '20141101100200Z',
'20.12.2014 10:12' => '20141220101200Z', '20.12.2014 10:12' => '20141220101200Z',
); );
foreach ($dates as $output => $input) { foreach ($dates as $input => $output) {
$this->assertEquals($output, sudoRole::decodeDate($input), $input . ' ' . $output); $this->assertEquals($output, sudoRole::encodeDate($input), $input . ' ' . $output);
}
} }
public function testDecodeDate() {
$dates = array(
'01.02.2014 00:00' => '20140201000000Z',
'10.02.2014 00:00' => '20140210000000Z',
'01.11.2014 00:00' => '20141101000000Z',
'20.12.2014 00:00' => '20141220000000Z',
'01.02.2014 01:02' => '20140201010200Z',
'10.02.2014 01:10' => '20140210011000Z',
'01.11.2014 10:02' => '20141101100200Z',
'20.12.2014 10:12' => '20141220101200Z',
);
foreach ($dates as $output => $input) {
$this->assertEquals($output, sudoRole::decodeDate($input), $input . ' ' . $output);
}
}
} }
} }

View File

@ -23,8 +23,8 @@ $Id$
$_SERVER ['REMOTE_ADDR'] = '127.0.0.1'; $_SERVER ['REMOTE_ADDR'] = '127.0.0.1';
include_once (dirname ( __FILE__ ) . '/../utils/configuration.inc'); include_once 'lam/tests/utils/configuration.inc';
include_once (dirname ( __FILE__ ) . '/../../lib/security.inc'); include_once 'lam/lib/security.inc';
/** /**
* Checks password checking functions. * Checks password checking functions.

View File

@ -0,0 +1,48 @@
<?php
/*
$Id$
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2016 Roland Gruber
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
require_once 'lam/lib/types.inc';
/**
* Checks ListAttribute.
*
* @author Roland Gruber
*
*/
class ListAttributeTest extends PHPUnit_Framework_TestCase {
public function testPreTranslated() {
$attr = new \LAM\TYPES\ListAttribute('#uid', 'user');
$this->assertEquals('User name', $attr->getAlias());
$this->assertEquals('uid', $attr->getAttributeName());
}
public function testCustomAlias() {
$attr = new \LAM\TYPES\ListAttribute('uid:My translation', 'user');
$this->assertEquals('My translation', $attr->getAlias());
$this->assertEquals('uid', $attr->getAttributeName());
}
}
?>

14
phpunit.xml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit>
<testsuites>
<testsuite name="AllTests">
<directory>lam/tests</directory>
</testsuite>
</testsuites>
<php>
<includePath>.</includePath>
</php>
<logging>
<log type="coverage-html" target="../code-coverage/html"/>
</logging>
</phpunit>