diff --git a/credits.txt b/credits.txt index 47d6916..0bf6fba 100644 --- a/credits.txt +++ b/credits.txt @@ -1,18 +1,18 @@ === wpDirAuth Credits === wpDirAuth is made possible by the following contributors: - + + Stephane Daury + Current maintainer + Montreal, QC, Canada + http://stephane.daury.org/ + Paul Gilzow Current maintainer Columbia, MO, USA http://profiles.wordpress.org/users/gilzow/ - - Stephane Daury - Original author - Montreal, QC, Canada - http://stephane.daury.org/ - Todd Beverly + Todd Beverly wpDirAuth QA and patch contributor Rochester, NY, USA See http://wordpress.org/support/topic/129814 diff --git a/readme.txt b/readme.txt index 95d8b13..8d1933e 100644 --- a/readme.txt +++ b/readme.txt @@ -1,229 +1,175 @@ -=== wpDirAuth === -Contributors: gilzow, stephdau, apokalyptik -Tags: login, authentication, directory, ldap, ldaps -Requires at least: 2.2 -Tested up to: 3.4.2 -Stable tag: 1.7.6 - -WordPress directory authentication plugin through LDAP and LDAPS (SSL). - -== Description == - -See - -PLEASE NOTE -Beta testers of the 1.7.X branch prior to version 1.7.5, you will need to -deactivate wpdirauth before you updgrade to this latest version. Once you -have installed and network activated the plugin, it will copy your options -from their previous location to the sitemeta table. You will only need to -do this once. This will also work for anyone who was using the 1.6.X -branch or older and plans on using it in MULTISITE mode. - -Version 1.7.5 brings full MULTISITE support. - -wpDirAuth allows users of central directory (LDAP) servers to login to -authorized WordPress instances without having to register. The plugin creates -a new account for each directory user on first login so that they have full -access to preferences and functions, as any WP user would. - -Activating the plugin will not restrict you to using directory authentication -and you will still be able to both create new WP-only users as well as turn on -public registration in WordPress. You can also assign any privilege levels to -your directory users, and the those users will be referred to their -institutional password policy whenever they would normally able to update -their WP passwords (on the profile screen, in user edit, etc). - -= LDAP/LDAPS = - -Authentication should work with most LDAP enabled directory services, such as -OpenLDAP, Apache Directory, Microsoft Active Directory, Novell eDirectory, -Sun Java System Directory Server, and more. - -wpDirAuth supports LDAP and LDAPS (SSL) connectivity and can force SSL for -WordPress authentication if it is available on the Web server. It also supports -server connection pools, for pseudo load balancing and fault tolerance, or -multiple source directory authentication. - -Because the key used to locate a user's profile in the LDAP server is not -always the same, depending on your LDAP server type and institutional choices, -you can define your own through the wpDirAuth administration tool. - -When logging in as a directory user, the WP "remember me" feature is downgraded -from 6 months for regular WP users to only 1 hour, so that institutional -passwords are not overly endangered when accessing WP from public terminals. - -= Branding & Notifications = - -You can define notifications addressed to your directory users in key WordPress -areas, such as the login screen and the profile edit screen. - -Since these admin-editable values support HTML (admin, coders, beware of xss!), -you can point your directory users to central support information related to -functions such as changing their institutional password, a WordPress usage -related policy, etc. - -There is also a simple and optional terms of services concept, only implemented -for directory users, which will simply record a one-time acceptance date when -agreed upon. Note that agreeing to the TOS has no effect on the user's level of -access in the system, fact which could change in future version if there is a -demand for it, or through direct code contribution to that effect. - - -== Download == - -You can download the latest stable version of wpDirAuth from the WordPress -Plugin Finder at the following locations: - -* Direct download: -* WPPF home: - - -== Installation == - -Installing should be a piece of cake and take fewer than ten minutes, provided -you know your directory server(s) information, and that your blog is allowed to -connect and bind to it/them. - -Please refer to your friendly neighbourhood LDAP sysadmin for more information. - -1. Upload the `wpDirAuth` directory to the `/wp-content/plugins/` directory. -1. Login to your WordPress instance as an admin user. -1. Activate the plugin through the 'Plugins' menu in WordPress. -1. Go to the `Directory Auth.` menu found in the WordPress `Options` section. -1. Enter your directory server(s) information and set your preferences. - -You should now be able to login as a directory user. - - -== Using wpDirAuth == - -Once installed and activated, you will be able to administer your directory -settings through the dedicated plugin configuration tool found under the -`Directory Auth.` menu found in the WordPress `Options` admin section. - -Directory Authenticated users can now be pre-added to your wordpress system -and granted roles by going to the `Add Dir Auth User` menu found in the -Wordpress `Users` admin section. Contextual help for this section is -available for this section within Wordpress' built-in help menu. - -See the inline help found in the tool for more information on the settings. - -There is a secondary activation toggle, so you can install and activate the -plugin, check out the options panel, but not immediately accept directory -authentication, or even simply turn the feature on or off at any time. - - -== Help and Support == - -Please post questions, request for help to the Wordpress plugins forum or -email . Please be sure to include 'wpdirauth' in the -subject line. - -== TO-DO's == - - -== Source and Development == - -wpDirAuth welcomes friendly contributors wanting to lend a hand, be it in -the form of code through SVN patches, user support, platform portability -testing, security consulting, localization help, etc. - -The [current] goal is to keep the plugin self-contained (ie: no 3rd-party lib) -for easier security maintenance, while keeping the code clean and extensible. - -Focus is on security, features, security, and let's not forget, security. -Unit tests will hopefully be developed and constant security audit performed. - -Recurring quality patch contributions will lead to commit privileges to the -project source repository. - -Please post questions/requests for help to the wordpress forums and/or -email - -The project source code is available on the WordPress Plugin Repository: - -* Stable: -* Unstable: -* Historical: - -The Sybversion repository can be browsed and tracked (RSS, etc) through the -WP Plugin Repo source browser at: - -* - -The generated code documentation can be found at: - -* - -The WP Plugin Repo also offers a convenient ticketing system for bug and -task tracking. - -* Existing tickets: -* Open a new ticket: - - -== License == - -[General Public License](http://www.gnu.org/licenses/gpl.html) - -Copyrights are listed in chronological order, by contributions. - -wpDirAuth: WordPress Directory Authentication, original author -Copyright (c) 2007 Stephane Daury - http://stephane.daury.org/ - -wpDirAuth and wpLDAP Patch Contributions -Copyright (c) 2007 PKR Internet, LLC - http://www.pkrinternet.com/ - -wpDirAuth Patch Contributions -Copyright (c) 2007 Todd Beverly - -wpLDAP: WordPress LDAP Authentication -Copyright (c) 2007 Ashay Suresh Manjure - http://ashay.org/ - -wpDirAuth Patch Contribution and current maintainer -Copyright (c) 2010, 2011, 2012 Paul Gilzow - http://gilzow.com/ - -wpDirAuth 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. - -wpDirAuth 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, see . - - -== Project History == - -Originally started from a patched version of wpLDAP (1.02+patch), wpDirAuth has -since then been heavily overhauled and features have been modified and added. -In other words, a classic case of `pimp my lib'` (hopefully for the better). - -* Current: wpDirAuth: -* Original: wpLDAP: -* wpLDAP Patch: - -== Changelog == - -PLEASE NOTE Beta testers of the 1.7.X branch prior to version 1.7.5, you will need to deactivate wpdirauth before you updgrade to this latest version. Once you have installed and network activated the plugin, it will copy your options from their previous location to the sitemeta table. You will only need to do this once. This will also work for anyone who was using the 1.6.X branch or older and plans on using it in MULTISITE mode. - -= 1.7.6 = -Corrected situation where a new authenticated user logging into a child site in a multisite network was added to the parent site, instead of the child site where they initiated the login. Also, somewhere along the way, I reintroduced a bug that when using authentication groups, the plugin would fail to redirect a successfully logged in user. - -= 1.7.5 = -* MULTISITE support, bug fixes, security enhancements - -= 1.6.1 = -* Corrected a bug that would prevent user profiles from successfully being found. Thanks go to jgiangrande for identifying the problem area. - -= 1.6.0 = -* Added `Add Dir Auth User` to Admin User menu. Now able to pre-add Directory Authenticated users and assign roles where previously users would have to log in first, and then have an admin change their role. - -= 1.5.2 = -* Added ability to limit logins to specific AD groups. Fixed a bug that produced an incorrect filter when using a single Authentication Group - -= 1.5.1 = +=== wpDirAuth === +Contributors: gilzow, stephdau, apokalyptik +Tags: login, authentication, directory, ldap, ldaps +Requires at least: 2.2 +Tested up to: 4.5 +Stable tag: 1.7.15 +WordPress directory authentication plugin through LDAP and LDAPS (SSL). +== Description == +Please see changelog below for recent updates/changes. + +wpDirAuth allows users of central directory (LDAP) servers to login to +authorized WordPress instances without having to register. The plugin creates +a new account for each directory user on first login so that they have full +access to preferences and functions, as any WP user would. +Activating the plugin will not restrict you to using directory authentication +and you will still be able to both create new WP-only users as well as turn on +public registration in WordPress. You can also assign any privilege levels to +your directory users, and the those users will be referred to their +institutional password policy whenever they would normally able to update +their WP passwords (on the profile screen, in user edit, etc). + += LDAP/LDAPS = +Authentication should work with most LDAP enabled directory services, such as +OpenLDAP, Apache Directory, Microsoft Active Directory, Novell eDirectory, +Sun Java System Directory Server, and more. +wpDirAuth supports LDAP and LDAPS (SSL) connectivity and can force SSL for +WordPress authentication if it is available on the Web server. It also supports +server connection pools, for pseudo load balancing and fault tolerance, or +multiple source directory authentication. +Because the key used to locate a user's profile in the LDAP server is not +always the same, depending on your LDAP server type and institutional choices, +you can define your own through the wpDirAuth administration tool. +When logging in as a directory user, the WP "remember me" feature is downgraded +from 6 months for regular WP users to only 1 hour, so that institutional +passwords are not overly endangered when accessing WP from public terminals. + += Branding & Notifications = +You can define notifications addressed to your directory users in key WordPress +areas, such as the login screen and the profile edit screen. +Since these admin-editable values support HTML (admin, coders, beware of xss!), +you can point your directory users to central support information related to +functions such as changing their institutional password, a WordPress usage +related policy, etc. +There is also a simple and optional terms of services concept, only implemented +for directory users, which will simply record a one-time acceptance date when +agreed upon. Note that agreeing to the TOS has no effect on the user's level of +access in the system, fact which could change in future version if there is a +demand for it, or through direct code contribution to that effect. + +== Download == +You can download the latest stable version of wpDirAuth from the WordPress +Plugin Finder at the following locations: +* Direct download: +* WPPF home: + +== Installation == +Installing should be a piece of cake and take fewer than ten minutes, provided +you know your directory server(s) information, and that your blog is allowed to +connect and bind to it/them. +Please refer to your friendly neighbourhood LDAP sysadmin for more information. +Or use a LDAP browser (e.g. Apache Directory Studio) to test/research what your +specific connections settings need to be. +1. Upload the `wpDirAuth` directory to the `/wp-content/plugins/` directory. +1. Login to your WordPress instance as an admin user. +1. Activate the plugin through the 'Plugins' menu in WordPress. +1. Go to the `Directory Auth.` menu found in the WordPress `Options` section. +1. Enter your directory server(s) information and set your preferences. +You should now be able to login as a directory user. +== Using wpDirAuth == +Once installed and activated, you will be able to administer your directory +settings through the dedicated plugin configuration tool found under the +`Directory Auth.` menu found in the WordPress `Options` admin section. +Directory Authenticated users can now be pre-added to your wordpress system +and granted roles by going to the `Add Dir Auth User` menu found in the +Wordpress `Users` admin section. Contextual help for this section is +available for this section within Wordpress' built-in help menu. +See the inline help found in the tool for more information on the settings. +There is a secondary activation toggle, so you can install and activate the +plugin, check out the options panel, but not immediately accept directory +authentication, or even simply turn the feature on or off at any time. + +== Help and Support == +Please post questions, request for help to the Wordpress plugins forum or +email . Please be sure to include 'wpdirauth' in the +subject line. + +== TO-DO's == +Tons. The entire codebase could stand refactoring. + +== Source and Development == +wpDirAuth welcomes friendly contributors wanting to lend a hand, be it in +the form of code through SVN patches, user support, platform portability +testing, security consulting, localization help, etc. +The [current] goal is to keep the plugin self-contained (ie: no 3rd-party lib) +for easier security maintenance, while keeping the code clean and extensible. +Focus is on security, features, security, and let's not forget, security. +Unit tests will hopefully be developed and constant security audit performed. +Recurring quality patch contributions will lead to commit privileges to the +project source repository. +Please post questions/requests for help to the wordpress forums and/or +email +The project source code is available on the WordPress Plugin Repository: +* Stable: +* Unstable: +* Historical: +The Sybversion repository can be browsed and tracked (RSS, etc) through the +WP Plugin Repo source browser at: +* +The generated code documentation can be found at: +* +The WP Plugin Repo also offers a convenient ticketing system for bug and +task tracking. +* Existing tickets: +* Open a new ticket: +== License == +[General Public License](http://www.gnu.org/licenses/gpl.html) +Copyrights are listed in chronological order, by contributions. +wpDirAuth: WordPress Directory Authentication, original author +Copyright (c) 2007 Stephane Daury - http://stephane.daury.org/ +wpDirAuth and wpLDAP Patch Contributions +Copyright (c) 2007 PKR Internet, LLC - http://www.pkrinternet.com/ + +wpDirAuth Patch Contributions +Copyright (c) 2007 Todd Beverly +wpLDAP: WordPress LDAP Authentication +Copyright (c) 2007 Ashay Suresh Manjure - http://ashay.org/ +wpDirAuth Patch Contribution and current maintainer +Copyright (c) 2010, 2011, 2012 Paul Gilzow - http://gilzow.com/ +wpDirAuth 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. +wpDirAuth 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, see . +== Project History == +Originally started from a patched version of wpLDAP (1.02+patch), wpDirAuth has +since then been heavily overhauled and features have been modified and added. +In other words, a classic case of `pimp my lib'` (hopefully for the better). +* Current: wpDirAuth: +* Original: wpLDAP: +* wpLDAP Patch: +== Changelog == += 1.7.15 = ++ let's try this again. filter wpdirauth_filterquery will pass THREE parameters: current AD filter, the account filter as set in the wpDirAuth settings and the username of the person attempting to authenticate. Callback function must pass back a valid AD filter. += 1.7.14 = ++ Why no 1.7.13? Because I'm superstitious. ++ Added hookable filter wpdirauth_filterquery. Will pass 2 parameters: the current AD filter and the username of the person attempting to authenticate. Callback function must pass back a valid AD filter. ++ v4.4.2 of wordpress changed some of the roles & caps. Role create_users no longer allows admins who do not posses super-admin privilege in a multisite to see the wpDirAuth add user menu item when in a site. changed the cap to add_users, but will continue to research += 1.7.12 = +missed an instance of split (deprecated php function). += 1.7.11 = +Adding stripslashes_deep because wordpress. += 1.7.10 = +Bug fixes and minor clean-up += 1.7.9 = +* The plugin no longer automatically creates accounts for directory-authenticated users who log into the site. You can enable this behavior in the plugin settings, but it is no longer the default behavior. +* Not sure why but I never set the plugin up to block Directory-Authenticated users from attempting to use the wordpress builtin password reset tool. It can't actually change the password, but it definitely caused confusion among users. wpDirAuth now blocks directory-authenticated users from using the password reset tool. +* Removed a bunch of deprecated function calls. +* Cleaned up some of the debugging messages. += 1.7.6 = +Corrected situation where a new authenticated user logging into a child site in a multisite network was added to the parent site, instead of the child site where they initiated the login. Also, somewhere along the way, I reintroduced a bug that when using authentication groups, the plugin would fail to redirect a successfully logged in user. += 1.7.5 = +* PLEASE NOTE Beta testers of the 1.7.X branch prior to version 1.7.5, you will need to deactivate wpdirauth before you updgrade to this latest version. Once you have installed and network activated the plugin, it will copy your options from their previous location to the sitemeta table. You will only need to do this once. This will also work for anyone who was using the 1.6.X branch or older and plans on using it in MULTISITE mode. +* MULTISITE support, bug fixes, security enhancements += 1.6.1 = +* Corrected a bug that would prevent user profiles from successfully being found. Thanks go to jgiangrande for identifying the problem area. += 1.6.0 = +* Added `Add Dir Auth User` to Admin User menu. Now able to pre-add Directory Authenticated users and assign roles where previously users would have to log in first, and then have an admin change their role. += 1.5.2 = +* Added ability to limit logins to specific AD groups. Fixed a bug that produced an incorrect filter when using a single Authentication Group += 1.5.1 = * Remove default password nag for wpdirauth accounts \ No newline at end of file diff --git a/wpDirAuth.php b/wpDirAuth.php index 822209a..263c7f8 100644 --- a/wpDirAuth.php +++ b/wpDirAuth.php @@ -1,53 +1,53 @@ - * + * * Copyrights are listed in chronological order, by contributions. - * + * * wpDirAuth: WordPress Directory Authentication, original author * Copyright (c) 2007 Stephane Daury - http://stephane.daury.org/ - * + * * wpDirAuth and wpLDAP Patch Contributions * Copyright (c) 2007 PKR Internet, LLC - http://www.pkrinternet.com/ - * + * * wpDirAuth Patch Contributions * Copyright (c) 2007 Todd Beverly - * + * * wpLDAP: WordPress LDAP Authentication * Copyright (c) 2007 Ashay Suresh Manjure - http://ashay.org/ - * + * * wpDirAuth Patch Contribution and current maintainer * Copyright (c) 2010, 2011, 2012 Paul Gilzow - http://gilzow.com/ - * + * * wpDirAuth 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. - * + * * wpDirAuth 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, see http://www.gnu.org/licenses/. - * + * * @todo Always stay on top of security and user input validation while * staying backwards compatible enough until PHP4 support is dropped in * WP (serious patches welcomed, please see code). Note that we do @@ -56,14 +56,14 @@ /* PLUGIN META INFO FOR WORDPRESS LISTINGS -Plugin Name: wpDirAuth-PosixGroup +Plugin Name: wpDirAuth Plugin URI: http://wpdirauth.gilzow.com/ Description: WordPress Directory Authentication (LDAP/LDAPS). Works with most LDAP enabled directory services, such as OpenLDAP, Apache Directory, Microsoft Active Directory, Novell eDirectory, Sun Java System Directory Server, etc. Originally revived and upgraded from a patched version of wpLDAP. -Version: 1.7.6 +Version: 1.7.15 Author: Paul Gilzow Author URI: http://gilzow.com/ */ @@ -71,7 +71,7 @@ Author URI: http://gilzow.com/ /** * wpDirAuth version. */ -define('WPDIRAUTH_VERSION', '1.7.6'); +define('WPDIRAUTH_VERSION', '1.7.15'); /** * wpDirAuth signature. @@ -105,12 +105,12 @@ define('WPDIRAUTH_LDAP_RETURN_KEYS',serialize(array('sn', 'givenname', 'mail'))) define('WPDIRAUTH_EMAIL_NEWUSER_NOTIFY','You have been added to the site %s as %s %s. You may login to the site using your institution\'s %s (%s) and password at the following address: %s'); /** - *My fail-safe method for determing if we are running in multisite mode + *My fail-safe method for determing if we are running in multisite mode */ define('WPDIRAUTH_MULTISITE',(defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE && function_exists('switch_to_blog')) ? TRUE : FALSE); /** - *List of option keys we store in wp_sitemeta/wp_options + *List of option keys we store in wp_sitemeta/wp_options */ define('WPDIRAUTH_OPTIONS', serialize(array( 'dirAuthEnable', @@ -132,20 +132,20 @@ define('WPDIRAUTH_OPTIONS', serialize(array( if (function_exists('wp_authenticate') || function_exists('wp_setcookie') || !function_exists('ldap_connect')) { -/** - * SAFE MODE - */ - + /** + * SAFE MODE + */ + /** * SAFE MODE: wpDirAuth plugin configuration panel. * Processes and outputs the wpDirAuth configuration form, with a conflict message. - * + * * @return void */ function wpDirAuth_safeConflictMessage() { $wpDARef = WPDIRAUTH_SIGNATURE; - + if (!function_exists('ldap_connect')) { $message = <<<________EOS

Sorry, but your PHP install does not seem to have access to the LDAP features.

@@ -181,30 +181,30 @@ ________EOS;

________EOS; } - + echo <<<________EOS

Directory Authentication Options: Plugin Conflict

$message

$wpDARef

-
+ ________EOS; } - + /** * SAFE MODE: Adds the `Directory Auth.` menu entry in the Wordpress Admin section. * Also activates the wpDirAuth config panel, with a conflict message, as a callback function. - * + * * @uses wpDirAuth_safeConflictMessage */ - function wpDirAuth_safeAddMenu() + function wpDirAuth_safeAddMenu() { if (function_exists('add_options_page')) { add_options_page( 'Directory Authentication Options: Plugin Conflict', '!! Directory Auth. !!', - 9, + 'manage_options', basename(__FILE__), 'wpDirAuth_safeConflictMessage' ); @@ -214,18 +214,18 @@ ________EOS; /** * SAFE MODE: Add custom WordPress actions. - * + * * @uses wpDirAuth_safeAddMenu */ if (function_exists('add_action')) { add_action('admin_menu', 'wpDirAuth_safeAddMenu'); - } + } } else { -/** - * STANDARD MODE - */ - + /** + * STANDARD MODE + */ + /** * Cookie marker. * Generates a random string to be used as salt for the password @@ -236,21 +236,21 @@ else { function wpDirAuth_makeCookieMarker() { $cookieMarker = md5( - $_SERVER['SERVER_SIGNATURE'] - .$_SERVER['HTTP_USER_AGENT'] - .$_SERVER['REMOTE_ADDR'] - ).uniqid(microtime(),true); + $_SERVER['SERVER_SIGNATURE'] + .$_SERVER['HTTP_USER_AGENT'] + .$_SERVER['REMOTE_ADDR'] + ).uniqid(microtime(),true); update_site_option("dirAuthCookieMarker",$cookieMarker); return $cookieMarker; } - - + + /** * LDAP bind test * Tries two different documented method of php-based ldap binding. * Note: passing params by reference, no need for copies (unlike in * wpDirAuth_auth where it is desirable). - * + * * @param object &$connection LDAP connection * @param string &$username LDAP username * @param string &$password LDAP password @@ -259,33 +259,38 @@ else { * */ function wpDirAuth_bindTest(&$connection, &$username, &$password,$baseDn) { - $password = strtr($password, array("\'"=>"'")); + //$password = strtr($password, array("\'"=>"'")); + /** + * Why stripslashes on the password? Because wordpress. + * @see: https://codex.wordpress.org/Function_Reference/stripslashes_deep#Good_Coding_Practice + */ + $password = stripslashes_deep($password); if ( ($isBound = @ldap_bind($connection, $username, $password)) === false ) { // @see http://weblogs.valsania.it/andreav/2008/07/24/wpdirauth-14-patch/ $isBound = @ldap_bind($connection,"uid=$username,$baseDn", $password); } return $isBound; } - + /** - * put your comment there... - * - * @param string $dc name of domain controller to connect to - * @param integer $enableSsl ssl config option - * @return resource - */ + * put your comment there... + * + * @param string $dc name of domain controller to connect to + * @param integer $enableSsl ssl config option + * @return resource + */ function wpDirAuth_establishConnection($dc,$enableSsl){ /** * Only setup protocol value if ldaps is required to help with older AD * @see http://groups.google.com/group/wpdirauth-support/browse_thread/thread/7b744c7ad66a4829 */ $protocol = ($enableSsl) ? 'ldaps://' : ''; - + /** * Scan for and use alternate server port, but only if ssl is disabled. * @see Parameters constraint at http://ca.php.net/ldap_connect */ - + if (strstr($dc, ':')) list($dc, $port) = explode(':', $dc); switch($enableSsl){ @@ -299,11 +304,11 @@ else { $connection = ldap_connect($dc,$port); } else { $connection = ldap_connect($dc); - } - break; + } + break; } - + /** * Copes with W2K3/AD issue. * @see http://bugs.php.net/bug.php?id=30670 @@ -311,34 +316,34 @@ else { if (@ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3)) { @ldap_set_option($connection, LDAP_OPT_REFERRALS, 0); } - + //they want to start TLS if($enableSsl == 2){ if(!ldap_start_tls($connection)){ return new WP_Error('tls_failed_to_start',__('wpDirAuth error: tls failed to start')); } - } - - return $connection; + } + + return $connection; } /** - * put your comment there... - * - * @param array $controllers list of domain controllers to connect to - * @return mixed array of shuffled controllers or WP_Error - */ + * put your comment there... + * + * @param array $controllers list of domain controllers to connect to + * @return mixed array of shuffled controllers or WP_Error + */ function wpDirAuth_shuffleControllers($controllers){ if (count($controllers) > 1) { // shuffle the domain controllers for pseudo load balancing and fault tolerance. shuffle($controllers); } elseif (count($controllers) == 0) { return new WP_Error('no_controllers',__(' wpDirAuth config error: no domain controllers specified.')); - } - - return $controllers; + } + + return $controllers; } - + /** * Custom LDAP authentication module. * The returned keys are in the same format used by WP for @@ -347,7 +352,7 @@ else { * @param string $username LDAP username * @param string $password LDAP password * @return WP_Error object OR array Directory email, last_name and first_name - * + * * @uses WPDIRAUTH_DEFAULT_FILTER * @uses WPDIRAUTH_ERROR_TITLE * @uses wpDirAuth_bindTest @@ -357,10 +362,11 @@ else { */ function wpDirAuth_auth($username, $password) { - global $error, $pwd; - + global $error, $pwd; + $errorTitle = WPDIRAUTH_ERROR_TITLE; - + $isInDirectory = false; + $results = false; $controllers = explode(',', get_site_option('dirAuthControllers')); $baseDn = get_site_option('dirAuthBaseDn'); $preBindUser = get_site_option('dirAuthPreBindUser'); @@ -369,36 +375,38 @@ else { $filter = get_site_option('dirAuthFilter'); $enableSsl = get_site_option('dirAuthEnableSsl'); $boolUseGroups = get_site_option('dirAuthUseGroups'); - + if($boolUseGroups == 1){ $strAuthGroups = get_site_option('dirAuthGroups'); } - + $returnKeys = unserialize(WPDIRAUTH_LDAP_RETURN_KEYS); - + $isBound = $isPreBound = $isLoggedIn = false; - + if ($accountSuffix) $username .= $accountSuffix; - + if (!$filter) $filter = WPDIRAUTH_DEFAULT_FILTER; - + $filterQuery = "($filter=$username)"; - + + $filterQuery = apply_filters('wpdirauth_filterquery',$filterQuery,$filter,$username); + $controllers = wpDirAuth_shuffleControllers($controllers); - + if(is_wp_error($controllers)){ return $controllers; } - - // Connection pool loop - Haha, PooL LooP + + // Connection pool loop - Haha, PooL LooP foreach ($controllers as $dc) { - + $connection = wpDirAuth_establishConnection($dc,$enableSsl); - + if(is_wp_error($connection)){ return $connection; } - + if ($preBindUser && $preBindPassword) { /** * Use case 1: Servers requiring pre-binding with admin defined @@ -444,38 +452,35 @@ else { } } } - + if ( ($preBindUser && $preBindPassword) && ( ! $isPreBound ) ) { return new WP_Error ('no_directory_or_prebinding', $errorTitle - . __(' wpDirAuth config error: No directory server available for authentication, OR pre-binding credentials denied.')); + . __(' wpDirAuth config error: No directory server available for authentication, OR pre-binding credentials denied.')); } - elseif ( ( $isInDirectory ) && ( ! $isBound ) ) { + elseif ( ( $isInDirectory ) && ( ! $isBound ) ) { return new WP_Error ('could_not_bind_as_user', $errorTitle - . __(' Incorrect password.')); - } + . __(' Incorrect password.')); + } elseif ( ! $isBound && ! $isPreBound ) { return new WP_Error ('no_directory_available', $errorTitle - . __(' wpDirAuth config error: No directory server available for authentication.')); + . __(' wpDirAuth config error: No directory server available for authentication.')); } elseif ( ! $isLoggedIn) { /** - * @desc wp-hack was echo'ing out $username verbatim which allowed a XSS vulnerability. Encoded $username before echoing' - */ + * @desc wp-hack was echo'ing out $username verbatim which allowed a XSS vulnerability. Encoded $username before echoing' + */ return new WP_Error ('could_not_authenticate', $errorTitle - . __(' Could not authenticate user. Please check your credentials.') - . " [" . htmlentities($username,ENT_QUOTES,'UTF-8') . "]"); + . __(' Could not authenticate user. Please check your credentials.') + . " [" . htmlentities($username,ENT_QUOTES,'UTF-8') . "]"); + - } else { if($boolUseGroups == 1){ //the user is authenticated, but we want to make sure they are a member of the groups given /** - * We need to get the DN's for each Authentication Group CN that was given to us. - */ - - // 2014-07-06 Nikolai R Kristiansen - // Modified for posixGroup lookup + * We need to get the DN's for each Authentication Group CN that was given to us. + */ $aryAuthGroupsDN = array(); $aryAuthGroups = explode(',',$strAuthGroups); $aryAttribs = array('distinguishedname'); @@ -484,20 +489,18 @@ else { $rscLDAPSearch = ldap_search($connection,$baseDn,$strAuthGroup,$aryAttribs); $arySearchResults = ldap_get_entries($connection,$rscLDAPSearch); if(isset($arySearchResults[0]['dn'])){ - $aryAuthGroupsDN[] = $strAuthGroup; - } + $aryAuthGroupsDN[] = $arySearchResults[0]['dn']; + } } - + if(count($aryAuthGroupsDN) == 0){ return new WP_Error('no_auth_groups_found',$errorTitle.__('No Authentication Groups found based on given group CN')); - } - - // (&(memberUid=nikolark)(cn=dns-aktiv)) - // TODO configurable memberUid and cn - $memberFilterQuery = "(memberUid=$username)"; - $strFilterQuery = '(&'.$memberFilterQuery.'(|'; + } + + + $strFilterQuery = '(&'.$filterQuery.'(|'; foreach($aryAuthGroupsDN as $strAuthGroupDN){ - $strFilterQuery .= "($strAuthGroupDN)"; + $strFilterQuery .= '(memberOf='.$strAuthGroupDN.')'; } $strFilterQuery .= '))'; if(($rscLDAPSearchGroupMember = ldap_search($connection,$baseDn,$strFilterQuery)) !== false){ @@ -507,33 +510,32 @@ else { . __('User authenticated but is not a member of an Authentication Group(s)')); } } - - } - - + + } + + /** * Search for profile, if still needed. - * @see $results in preceding loop: Use case 3 + * $result is set to false by default. reset to a resource or false again in lines 403-437 + * wpDirAuth_retrieveUserDetails() now checks the value of $results before continuing */ - if (!$results){ - return wpDirAuth_retrieveUserDetails($connection,$baseDn,$filterQuery); - } else { - return wpDirAuth_retrieveUserDetails($connection,$baseDn,$filterQuery,$results); - } + + return wpDirAuth_retrieveUserDetails($connection,$baseDn,$filterQuery,$results); + } } - - + + /** * Runs stripslashes, html_entity_decode, then strip_tags with * allowed html if requested. - * + * * No input sashimi for us (hopefully). * * @param string $value Value to `sanitize` * @param boolean $allowed Set to true for WPDIRAUTH_ALLOWED_TAGS * @return string Cleaner value. - * + * * @uses WPDIRAUTH_ALLOWED_TAGS */ function wpDirAuth_sanitize($value, $allowed = false) @@ -541,14 +543,14 @@ else { $allowed = ($allowed) ? WPDIRAUTH_ALLOWED_TAGS : ''; return strip_tags(html_entity_decode(stripslashes($value)), $allowed); } - - + + /** * wpDirAuth plugin configuration panel. * Processes and outputs the wpDirAuth configuration form. - * + * * @return void - * + * * @uses WPDIRAUTH_DEFAULT_FILTER * @uses WPDIRAUTH_DEFAULT_LOGINSCREENMSG * @uses WPDIRAUTH_DEFAULT_CHANGEPASSMSG @@ -559,12 +561,12 @@ else { function wpDirAuth_optionsPanel() { global $userdata; - + $wpDARef = WPDIRAUTH_SIGNATURE; $allowedHTML = htmlentities(WPDIRAUTH_ALLOWED_TAGS); - - $curUserIsDirUser = get_usermeta($userdata->ID, 'wpDirAuthFlag'); - + + $curUserIsDirUser = get_user_meta($userdata->ID, 'wpDirAuthFlag',true); + if ($curUserIsDirUser) { echo <<<____________EOS
@@ -581,11 +583,11 @@ else { using the appropriate WordPress admin tool.

$wpDARef

-
+ ____________EOS; return; } - + if ($_POST) { $enableSsl = 0; //default $boolUseGroups = 0; //default @@ -593,13 +595,14 @@ ____________EOS; $enable = intval($_POST['dirAuthEnable']) == 1 ? 1 : 0; $requireSsl = intval($_POST['dirAuthRequireSsl']) == 1 ? 1 : 0; $TOS = intval($_POST['dirAuthTOS']) == 1 ? 1 : 0; - + $boolAutoRegister = intval($_POST['dirAuthAutoRegistration'])== 1 ? 1 : 0; + _wpdirauth_log($boolAutoRegister,'value for autoregister passed via POST',false,array('line'=>__LINE__,'file'=>__FILE__)); //integers if(intval($_POST['dirAuthEnableSsl']) == 1 || intval($_POST['dirAuthEnableSsl']) == 2){ - $enableSsl = intval($_POST['dirAuthEnableSsl']); + $enableSsl = intval($_POST['dirAuthEnableSsl']); } - - + + // Strings, no HTML $controllers = wpDirAuth_sanitize($_POST['dirAuthControllers']); $baseDn = wpDirAuth_sanitize($_POST['dirAuthBaseDn']); @@ -613,16 +616,22 @@ ____________EOS; $strMarketingSSOID= wpDirAuth_sanitize(($_POST['dirAuthMarketingSSOID'])); if($strAuthGroups != ''){ - $boolUseGroups = 1; - } - + $boolUseGroups = 1; + if(1 == $boolAutoRegister){ + //they are using authgroups, but they also want us to autoregister. sorry, cant do that. + $boolAutoRegister = 0; + } + } + // Have to be allowed to contain some HTML $loginScreenMsg = wpDirAuth_sanitize($_POST['dirAuthLoginScreenMsg'], true); $changePassMsg = wpDirAuth_sanitize($_POST['dirAuthChangePassMsg'], true); - + + _wpdirauth_log($boolAutoRegister,'auto register before saving',false,array('line'=>__LINE__,'file'=>__FILE__)); update_site_option('dirAuthEnable', $enable); update_site_option('dirAuthEnableSsl', $enableSsl); update_site_option('dirAuthRequireSsl', $requireSsl); + update_site_option('dirAuthAutoRegister', $boolAutoRegister); update_site_option('dirAuthControllers', $controllers); update_site_option('dirAuthBaseDn', $baseDn); update_site_option('dirAuthPreBindUser', $preBindUser); @@ -636,33 +645,33 @@ ____________EOS; update_site_option('dirAuthGroups', $strAuthGroups); update_site_option('dirAuthMarketingSSOID', $strMarketingSSOID); - + // Only store/override the value if a new one is being sent a bind user is set. if ( $preBindUser && $preBindPassword && ($preBindPassCheck == $preBindPassword) ) update_site_option('dirAuthPreBindPassword', $preBindPassword); - + // Clear the stored password if the Bind DN is null elseif ( ! $preBindUser) update_site_option('dirAuthPreBindPassword', ''); - + if (get_site_option('dirAuthEnable') && !get_site_option('dirAuthCookieMarker')) wpDirAuth_makeCookieMarker(); - + echo '

Your new settings were saved successfully.

'; - + // Be sure to clear $preBindPassword, not to be displayed onscreen or in source unset($preBindPassword); - } - else { + } else { // Booleans - $enable = intval(get_site_option('dirAuthEnable')) == 1 ? 1 : 0; - $requireSsl = intval(get_site_option('dirAuthRequireSsl')) == 1 ? 1 : 0; - $TOS = intval(get_site_option('dirAuthTOS')) == 1 ? 1 : 0; - $boolUseGroups = intval(get_site_option('dirAuthUseGroups')) == 1 ? 1 : 0; - + $enable = intval(get_site_option('dirAuthEnable')) == 1 ? 1 : 0; + $requireSsl = intval(get_site_option('dirAuthRequireSsl')) == 1 ? 1 : 0; + $TOS = intval(get_site_option('dirAuthTOS')) == 1 ? 1 : 0; + $boolUseGroups = intval(get_site_option('dirAuthUseGroups')) == 1 ? 1 : 0; + $boolAutoRegister= intval(get_site_option('dirAuthAutoRegister'))== 1 ? 1 : 0; + //integers $enableSsl = intval(get_site_option('dirAuthEnableSsl',0)); - + // Strings, no HTML $controllers = wpDirAuth_sanitize(get_site_option('dirAuthControllers')); $baseDn = wpDirAuth_sanitize(get_site_option('dirAuthBaseDn')); @@ -671,8 +680,8 @@ ____________EOS; $filter = wpDirAuth_sanitize(get_site_option('dirAuthFilter')); $institution = wpDirAuth_sanitize(get_site_option('dirAuthInstitution')); $strAuthGroups = wpDirAuth_sanitize((get_site_option('dirAuthGroups'))); - $strMarketingSSOID = wpDirAuth_sanitize((get_site_option('dirAuthMarketingSSOID'))); - + $strMarketingSSOID = wpDirAuth_sanitize((get_site_option('dirAuthMarketingSSOID'))); + // Have to be allowed to contain some HTML $loginScreenMsg = wpDirAuth_sanitize(get_site_option('dirAuthLoginScreenMsg'), true); $changePassMsg = wpDirAuth_sanitize(get_site_option('dirAuthChangePassMsg'), true); @@ -687,31 +696,40 @@ ____________EOS; $loginScreenMsg = htmlspecialchars($loginScreenMsg); $changePassMsg = htmlspecialchars($changePassMsg); $strAuthGroups = htmlspecialchars($strAuthGroups); - + + $tEnable = $fEnable = $tWpSsl = $fWpSsl = $tTOS = $fTOS = ''; + if ($enable) { $tEnable = "checked"; } else { $fEnable = "checked"; } - + $defaultFilter = WPDIRAUTH_DEFAULT_FILTER; if (!$filter) { $filter = $defaultFilter; } - + if (!$institution) { $institution = '[YOUR INSTITUTION]'; } - + if (!$loginScreenMsg) { $loginScreenMsg = sprintf(WPDIRAUTH_DEFAULT_LOGINSCREENMSG, $institution); } - + if (!$changePassMsg) { $changePassMsg = sprintf(WPDIRAUTH_DEFAULT_CHANGEPASSMSG, $institution); } - + + /** + * If they are using authentication groups we will not automaticaly register authed users that dont already have an account + */ + if('' != $strAuthGroups && $boolAutoRegister == 1){ + $boolAutoRegister = 0; + } + /* if ($enableSsl) { $tSsl = "checked"; @@ -733,34 +751,46 @@ ____________EOS; break; case 0: default: - $strNoSSL = $strOptionSelected; + $strNoSSL = $strOptionSelected; break; } - + if ($requireSsl) { $tWpSsl = "checked"; } else { $fWpSsl = "checked"; } - + if ($TOS) { $tTOS = "checked"; } else { $fTOS = "checked"; } - + + $strYesAutoRegister = ''; + $strNoAutoRegister = ''; + if($boolAutoRegister){ + $strYesAutoRegister = 'checked'; + } else { + $strNoAutoRegister = 'checked'; + } + + /** + * @todo seems like we should loop through these yes/nos are something... + */ + $wpDAV = WPDIRAUTH_VERSION; - + echo <<<________EOS

Directory Authentication Options

- WordPress Settings + WordPress Settings
  • @@ -780,6 +810,15 @@ ____________EOS;
    Force the WordPress login screen to require encryption (SSL, https:// URL)?
  • +
  • + +

    If a user authenticates successfully, but does not already have an account for the site, should wpDirAuth automatically create a new user + account for the authenticated user, and assign them to the lowest possible role? Note that this setting has no affect if you are using + Authentication Groups.

    + Yes   + No   + +
@@ -788,10 +827,6 @@ ____________EOS;

  • - - (Defaults to $defaultFilter) + (Defaults to $defaultFilter)
    What LDAP field should we search the username against to locate the user's profile after successful login?
  • @@ -868,7 +903,7 @@ ____________EOS;
    Name of your institution/company. Displayed on the login screen. - +

  • @@ -891,7 +926,7 @@ ____________EOS;
    Displayed wherever user passwords can be changed, for directory users only.
    Note: Some HTML allowed: $allowedHTML - +
  • @@ -910,40 +945,42 @@ ____________EOS;
  • ________EOS; } - + /** * Adds the `Directory Auth.` menu entry in the Wordpress Admin section, and the `Add Directory Authenticated User` to the Users menu * Also activates the wpDirAuth config panel as a callback function. - * + * * @uses wpDirAuth_optionsPanel * @uses wpDirAuth_add_user_panel */ - function wpDirAuth_addMenu() + function wpDirAuth_addMenu() { if (function_exists('add_options_page')) { - add_options_page( + $strWpAdminPage = add_options_page( 'Directory Authentication Options', 'Directory Auth.', - 9, + 'manage_options', basename(__FILE__), 'wpDirAuth_optionsPanel' ); + + //$strWpAdminPanel is here in case we want to add a contextual help panel later } } - - + + /** * Extending WP's login_form. * Enforces the admin defined SSL login preferences and adds a directory * login related message to the standard WP login screen. - * + * * @uses WPDIRAUTH_DEFAULT_LOGINSCREENMSG */ function wpDirAuth_loginFormExtra() { if (get_site_option('dirAuthEnable')) { - + if (isset($_SERVER['SCRIPT_URI']) && preg_match('|^http|',$_SERVER['SCRIPT_URI'])) { $selfURL = $_SERVER['SCRIPT_URI']; } @@ -964,62 +1001,62 @@ ________EOS; : $_SERVER["SCRIPT_NAME"].'?'.$_SERVER['QUERY_STRING']) ); } - + //_log('contents of selfurl: '.$selfURL); - - + + if (get_site_option('dirAuthRequireSsl') && (!preg_match('|^https|',$selfURL))) { $sslURL = str_replace('http://','https://',$selfURL); - + $refreshJS = '" />'; $refreshMeta = ''; $refreshMsg = 'Please access the encrypted version of this page.'; - + if (headers_sent()) { - echo $refreshJS.$refreshMeta.'

    '.$refreshMsg.'

    '; + echo $refreshJS.$refreshMeta.'

    '.$refreshMsg.'

    '; } else { @ob_end_clean(); if (!@header('Location:'.$sslURL)) { echo ''.$refreshJS.$refreshMeta.'' - . ''.$refreshMsg.''; + . ''.$refreshMsg.''; } } - + exit; } - + $dirAuthInstitution = stripslashes(get_site_option('dirAuthInstitution')); if (!$dirAuthInstitution) $dirAuthInstitution = __('Directory'); - + $loginScreenMsg = stripslashes(get_site_option('dirAuthLoginScreenMsg')); if (!$loginScreenMsg) $loginScreenMsg = __(sprintf( WPDIRAUTH_DEFAULT_LOGINSCREENMSG, get_site_option('dirAuthInstitution') )); - + echo '

    '.$loginScreenMsg.'

    '; } } - - + + /** * Extending WP's show_password_fields. * Displays the directory password change message in profile.php and user.php. * * @return boolean Return format as expected by WP's show_password_fields() - * + * * @uses WPDIRAUTH_DEFAULT_CHANGEPASSMSG */ function wpDirAuth_hidePassFields() { global $profileuser, $userdata; - - $editUserIsDirUser = get_usermeta($profileuser->ID, 'wpDirAuthFlag'); - + + $editUserIsDirUser = get_user_meta($profileuser->ID, 'wpDirAuthFlag',true); + if (!$editUserIsDirUser) { return true; } @@ -1032,44 +1069,44 @@ ________EOS; stripslashes(get_site_option('dirAuthInstitution')) )); } - + if (get_site_option('dirAuthTOS')) { // TOS option is ON - if (($TOSDate = get_usermeta($profileuser->ID, 'wpDirAuthTOS')) === '') { + if (($TOSDate = get_user_meta($profileuser->ID, 'wpDirAuthTOS', true)) === '') { if ($userdata->ID == $profileuser->ID) { // Only show TOS acceptance checkbox to the owner of the profile. $message .= '

    ' - . ' ' - . __('Accept terms of services.') - . '

    '; + . ' ' + . __('Accept terms of services.') + . '

    '; } else { // Show generic message to other admins. $message .= '

    ' - . __('User has not yet agreed to the terms of services.') - . '

    '; + . __('User has not yet agreed to the terms of services.') + . '

    '; } } else { // Show TOS acceptance date $message .= '

    ' - . __('Terms of services accepted on') - . ' '.$TOSDate - . '

    '; + . __('Terms of services accepted on') + . ' '.$TOSDate + . '

    '; } } - + echo '

    ' - . __('Directory Password Update') - . '

    ' - . $message - . '

    '; - + . __('Directory Password Update') + . '

    ' + . $message + . '

    '; + return false; } } - - + + /** * Extending WP's profile_update. * Saves the TOS acceptance if sent. @@ -1078,8 +1115,8 @@ ________EOS; * @return boolean Return format as expected by WP's profile_update() */ function wpDirAuth_profileUpdate($userID){ - if (intval($_POST['wpDirAuthTOS']) === 1) { - update_usermeta($userID, 'wpDirAuthTOS', date('Y-m-d H:i:s')); + if (isset($_POST['wpDirAuthTOS']) && intval($_POST['wpDirAuthTOS']) === 1) { + update_user_meta($userID, 'wpDirAuthTOS', date('Y-m-d H:i:s')); } return true; } @@ -1092,10 +1129,10 @@ ________EOS; * @param string $username Login form username. * @param string $password Login form password * @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object. - * + * * @uses wpDirAuth_makeCookieMarker * @uses wpDirAuth_auth - * + * * @see http://codex.wordpress.org/Pluggable_Functions */ function wp_authenticate($username, $password) @@ -1107,43 +1144,44 @@ ________EOS; global $blog_id; $intOriginalBlog = $blog_id; switch_to_blog(1); //switch to the parent blog - $boolRestoreBlog = true; + $boolRestoreBlog = true; } /** - * @desc wp-hack for some reason, this function is being called even when a user just goes to the login page. added the next 3 lines so that - * if the user arrives via $_GET, then we simply tell them to login - */ + * @desc wp-hack for some reason, this function is being called even when a user just goes to the login page. added the next 3 lines so that + * if the user arrives via $_GET, then we simply tell them to login + */ if($_SERVER['REQUEST_METHOD'] != 'POST'){ if($boolRestoreBlog) restore_current_blog(); - return new WP_Error('incorrect_method',__('Please Login')); + return new WP_Error('incorrect_method',__('Please Login')); } - + if (!$username) { if($boolRestoreBlog) restore_current_blog(); return new WP_Error('empty_username', __('Login Error: The username field is empty.')); } - + if (!$password) { if($boolRestoreBlog) restore_current_blog(); return new WP_Error('empty_password', __('Login Error: The password field is empty.')); } - + $enable = get_site_option('dirAuthEnable'); $cookieMarker = get_site_option('dirAuthCookieMarker'); - + $boolAutoRegister= (bool)get_site_option('dirAuthAutoRegister'); + if (!$cookieMarker) { $cookieMarker = wpDirAuth_makeCookieMarker(); } - + /** - * Get the login object. We will use it for first user insertion or when the + * Get the login object. We will use it for first user insertion or when the * directory auth option is not activated. */ - $login = get_userdatabylogin($username); - $loginUserIsDirUser = ($login) ? get_usermeta($login->ID, 'wpDirAuthFlag') : 0; - + $login = get_user_by('login',$username); + $loginUserIsDirUser = (false !== $login) ? get_user_meta($login->ID, 'wpDirAuthFlag',true) : 0; + if (!$enable && $loginUserIsDirUser) { /* * Existing directory user, but directory access has now been disabled. @@ -1158,22 +1196,21 @@ ________EOS; /** * Directory auth == true */ - - if (!$login) { + + if (!$login && $boolAutoRegister) { /** - * No existing account record found, try dir auth + * No existing account record found, autoregister is on, try dir auth */ $userData = wpDirAuth_auth($username,$password); - + if ( !is_wp_error($userData) ) { /** * Passed directory signin, so create a new WP user */ - require_once(ABSPATH . WPINC . '/registration.php'); - + $userLogin = sanitize_user($username); - $userEmail = apply_filters('user_registration_email', $userData['email']); - + $userEmail = apply_filters('user_registration_email', $userData['email']); + if (username_exists($userLogin)) { /* * Username exists. @@ -1184,8 +1221,7 @@ ________EOS; Could not create a new WP user account because the directory username ' . htmlentities($userLogin,ENT_QUOTES,'UTF-8') . ' is already registered on this site.')); - } - elseif (email_exists($userEmail)) { + } elseif (email_exists($userEmail)) { /* * Email exists. */ @@ -1195,38 +1231,35 @@ ________EOS; Could not create a new WP account because the email ' . htmlentities($userEmail,ENT_QUOTES,'UTF-8') . ' is already registered with this site.')); - } - else { + } else { if(defined('WPDIRAUTH_MULTISITE') && WPDIRAUTH_MULTISITE && isset($boolRestoreBlog) && $boolRestoreBlog){ restore_current_blog(); - } - - if ($userID = wp_create_user($userLogin, $password, $userEmail)) { - $userData['ID'] = $userID; - $tmpAr = split('@',$userData['email']); - $userData['nickname'] = str_replace('.','_',$tmpAr[0]); - $userData['display_name'] = $userData['first_name'].' '.$userData['last_name']; - unset($userData['email']); + } - wp_update_user($userData); - update_usermeta($userID, 'wpDirAuthFlag', 1); - wpDirAuth_remove_password_nag($userID); - //if($boolRestoreBlog) restore_current_blog(); - return new WP_User($userID); - } - else { - /* - * Unknown error. - */ - //if($boolRestoreBlog) restore_current_blog(); - do_action( 'wp_login_failed', $username ); - return new WP_Error('creation_unknown_error',__('Directory Login Error: + if ($userID = wp_create_user($userLogin, $password, $userEmail)) { + $userData['ID'] = $userID; + $tmpAr = explode('@',$userData['email']); + $userData['nickname'] = str_replace('.','_',$tmpAr[0]); + $userData['display_name'] = $userData['first_name'].' '.$userData['last_name']; + unset($userData['email']); + + wp_update_user($userData); + update_user_meta($userID, 'wpDirAuthFlag', 1); + wpDirAuth_remove_password_nag($userID); + //if($boolRestoreBlog) restore_current_blog(); + return new WP_User($userID); + } else { + /* + * Unknown error. + */ + //if($boolRestoreBlog) restore_current_blog(); + do_action( 'wp_login_failed', $username ); + return new WP_Error('creation_unknown_error',__('Directory Login Error: Could not create a new user account. Unknown error. [user: ' . htmlentities($userLogin,ENT_QUOTES,'UTF-8') . ', email: ' . htmlentities($userEmail,ENT_QUOTES,'UTF-8') . ']')); - } + } } - } - else { + } else { /* * Did not pass dir auth, and no login present in WP */ @@ -1234,8 +1267,8 @@ ________EOS; do_action( 'wp_login_failed', $username ); return $userData; } - } - else { + } else { + /* * Dealing with an existing WP account */ @@ -1247,10 +1280,9 @@ ________EOS; /* * WP user, password okay. */ - if($boolRestoreBlog) restore_current_blog(); - return new WP_User($login->ID); - } - else { + if($boolRestoreBlog) restore_current_blog(); + return new WP_User($login->ID); + } else { /* * WP user, wrong pass */ @@ -1259,18 +1291,17 @@ ________EOS; return new WP_Error('incorrect_password',__('WordPress Login Error: Incorrect password.')); } - } - else { + } else { /** * Directory user, try ldap binding */ $userData = wpDirAuth_auth($username,$password); - + if ( !is_wp_error($userData) ) { /* * Directory user, password okay. */ - wpDirAuth_remove_password_nag($login->ID); + wpDirAuth_remove_password_nag($login->ID); if($boolRestoreBlog) restore_current_blog(); return new WP_User($login->ID); } @@ -1298,7 +1329,7 @@ ________EOS; return new WP_Error('failed_login',__('WordPress Login Error: Could not authenticate user. Please check your credentials.')); - } + } else { /* * Found an existing WP account. @@ -1309,7 +1340,7 @@ ________EOS; */ if($boolRestoreBlog) restore_current_blog(); return new WP_User($login->ID); - } + } else { /* * WP user, wrong pass @@ -1323,7 +1354,7 @@ ________EOS; } } - + /** * WordPress wp_setcookie overwrite. * Sets the WP session cookies. @@ -1335,32 +1366,34 @@ ________EOS; * @param string $siteurl * @param boolean $remember * @return void - * + * * @uses wpDirAuth_makeCookieMarker - * - * @see http://codex.wordpress.org/Pluggable_Functions + * + * @deprecated + * + * @see http://codex.wordpress.org/Pluggable_Functions */ - function wp_setcookie($username, $password, $already_md5 = false, $home = '', $siteurl = '', $remember = false) + function wpsetauthcookie($intUserId, $remember = false, $boolSecure = true) { global $wpdb; /** * Try to locate the user's record and define if it is an existing directory user */ - $login = get_userdatabylogin($username); + $login = get_user_by('id',$intUserId); //$login = $wpdb->get_row('SELECT ID FROM $wpdb->users WHERE user_login = '$username''); $loginUserIsDirUser = ($login) ? get_usermeta($login->ID, 'wpDirAuthFlag') : 0; - + /** * Get wpsDirAuth options */ $enable = get_site_option('dirAuthEnable'); $cookieMarker = get_site_option('dirAuthCookieMarker'); - + if (!$cookieMarker) { $cookieMarker = wpDirAuth_makeCookieMarker(); } - + /** * Set the password hash cookie */ @@ -1372,7 +1405,7 @@ ________EOS; $password = md5( md5($password) ); // Double hash the password in the cookie. } } - + /** * Updated WP remember me option for directory users to only be * remembered for 1 hour so that institutional passwords are not @@ -1394,7 +1427,7 @@ ________EOS; $cookiepath = COOKIEPATH; else $cookiepath = preg_replace('|https?://[^/]+|i', '', $home . '/' ); - + if ( empty($siteurl) ) { $sitecookiepath = SITECOOKIEPATH; $cookiehash = COOKIEHASH; @@ -1402,10 +1435,10 @@ ________EOS; $sitecookiepath = preg_replace('|https?://[^/]+|i', '', $siteurl . '/' ); $cookiehash = md5($siteurl); } - + setcookie(USER_COOKIE, $username, $expire, $cookiepath, COOKIE_DOMAIN); setcookie(PASS_COOKIE, $password, $expire, $cookiepath, COOKIE_DOMAIN); - + if ( $cookiepath != $sitecookiepath ) { setcookie(USER_COOKIE, $username, $expire, $sitecookiepath, COOKIE_DOMAIN); setcookie(PASS_COOKIE, $password, $expire, $sitecookiepath, COOKIE_DOMAIN); @@ -1414,213 +1447,213 @@ ________EOS; } /** - * Prints data on a variable into a comments block in the source code of a page. Used for debugging purposes only. - * - * @param mixed $mxdVar - * @param string $strMsg - */ + * Prints data on a variable into a comments block in the source code of a page. Used for debugging purposes only. + * + * @param mixed $mxdVar + * @param string $strMsg + */ function wpDirAuthPrintDebug($mxdVar,$strMsg){ echo PHP_EOL,'',PHP_EOL; } - + /** - * Removes the "you're using a default password"" nag for dirauth accounts - * - * @param integer $userID - * @return void - */ + * Removes the "you're using a default password"" nag for dirauth accounts + * + * @param integer $userID + * @return void + */ function wpDirAuth_remove_password_nag($userID){ if(get_user_option('default_password_nag',$userID)){ update_user_option($userID, 'default_password_nag', false, true); } } - + /** - * Retrieves values given in WPDIRAUTH_LDAP_RETURN_KEYS from a valid, bound LDAP connection - * - * @param resource $rscConnection verified LDAP connection resource - * @param string $strBaseDn - * @param string $strFilterQuery - * @param mixed $rscReult if LDAP search was already performed. default null - * @return mixed WP_Error object if there was an error encountered, otherwise an array of user details - * - * @TODO right now it's actually coded such that what is returned is always the same, even if you change the keys in WPDIRAUTH_LDAP_RETURN_KEYS. Rewrite it so - * it will dynamically retrieve the values. idea is that WPDIRAUTH_LDAP_RETURN_KEYS would become an associative array of key names to return => LDAP keys to retrieve. - * WPDIRAUTH_LDAP_RETURN_KEYS = serialize(array( - * 'first_name' =>'givenname', - * 'last_name' =>'sn', - * 'email' =>'mail' - * )); - * of course, we'll need to somehow require at least the email key since we need that one in order to add the user. - */ - function wpDirAuth_retrieveUserDetails($rscConnection,$strBaseDn,$strFilterQuery,$rscResult=NULL){ + * Retrieves values given in WPDIRAUTH_LDAP_RETURN_KEYS from a valid, bound LDAP connection + * + * @param resource $rscConnection verified LDAP connection resource + * @param string $strBaseDn + * @param string $strFilterQuery + * @param mixed $rscReult if LDAP search was already performed. default null + * @return mixed WP_Error object if there was an error encountered, otherwise an array of user details + * + * @TODO right now it's actually coded such that what is returned is always the same, even if you change the keys in WPDIRAUTH_LDAP_RETURN_KEYS. Rewrite it so + * it will dynamically retrieve the values. idea is that WPDIRAUTH_LDAP_RETURN_KEYS would become an associative array of key names to return => LDAP keys to retrieve. + * WPDIRAUTH_LDAP_RETURN_KEYS = serialize(array( + * 'first_name' =>'givenname', + * 'last_name' =>'sn', + * 'email' =>'mail' + * )); + * of course, we'll need to somehow require at least the email key since we need that one in order to add the user. + */ + function wpDirAuth_retrieveUserDetails($rscConnection,$strBaseDn,$strFilterQuery,$rscResult=false){ //now that we have a valid connection and are bound, we need to find the user. - - if(is_null($rscResult)){ - $rscResult = ldap_search($rscConnection,$strBaseDn,$strFilterQuery,unserialize(WPDIRAUTH_LDAP_RETURN_KEYS)); + + if(is_bool($rscResult) && false === $rscResult){ + $rscResult = ldap_search($rscConnection,$strBaseDn,$strFilterQuery,unserialize(WPDIRAUTH_LDAP_RETURN_KEYS)); } - + /** - * At this point, we will no longer use $strFilterQuery EXCEPT in the output of an error message. To ensure we dont introduce an injection point, we will encode any - * html entities that might be present. + * At this point, we will no longer use $strFilterQuery EXCEPT in the output of an error message. To ensure we dont introduce an injection point, we will encode any + * html entities that might be present. */ $strFilterQuery = htmlentities($strFilterQuery,ENT_QUOTES,'UTF-8'); - + if(!$rscResult){ return new WP_Error ('noprofile_search', __('Directory authentication initially succeeded, but no valid profile was found (search procedure).') - ." [$strFilter]"); + ." [$strFilter]"); } else { $aryUserDetails = @ldap_get_entries($rscConnection, $rscResult); - + $intCount = intval($aryUserDetails['count']); if ($intCount < 1) { return new WP_Error ('noprofile_getentries', __('Directory authentication initially succeeded, but no valid profile was found ("get entries" procedure).') - ." [$strFilterQuery]"); + ." [$strFilterQuery]"); } elseif ($intCount > 1) { return new WP_Error ('not_unique', __('Directory authentication initially succeeded, but the username you sent is not a unique profile identifier.') - . " [$strFilterQuery]"); + . " [$strFilterQuery]"); } else { $strEmail = isset($aryUserDetails[0]['mail'][0]) ? $aryUserDetails[0]['mail'][0] : ''; - + $strLastName = isset($aryUserDetails[0]['sn'][0]) ? $aryUserDetails[0]['sn'][0] : ''; - + $strFirstName = isset($aryUserDetails[0]['givenname'][0]) ? $aryUserDetails[0]['givenname'][0] : ''; - + return array( 'email' => $strEmail, 'last_name' => $strLastName, 'first_name' => $strFirstName - ); + ); } - } + } } - + /** - * Handles connecting to LDAP and performing a search for the given SSOID - * - * @param string $strSSOID - * @return mixed WP_Error object on failure, array of user details on success - * @TODO this function shares a LOT with wpDirAuth_auth. see if you cant combine them some more - */ + * Handles connecting to LDAP and performing a search for the given SSOID + * + * @param string $strSSOID + * @return mixed WP_Error object on failure, array of user details on success + * @TODO this function shares a LOT with wpDirAuth_auth. see if you cant combine them some more + */ function wpDirAuth_ConnectAndLookupUser($strSSOID){ $boolFound = false; - + $strBaseDn = get_site_option('dirAuthBaseDn'); $strPreBindUser = get_site_option('dirAuthPreBindUser',''); $strPreBindPassword = get_site_option('dirAuthPreBindPassword',''); $strAccountSuffix = get_site_option('dirAuthAccountSuffix'); $strFilter = get_site_option('dirAuthFilter'); - $intEnableSSL = get_site_option('dirAuthEnableSsl'); - + $intEnableSSL = get_site_option('dirAuthEnableSsl'); + if ($strAccountSuffix) $strSSOID .= $strAccountSuffix; - + if (!$strFilter || empty($strFilter)) $strFilter = WPDIRAUTH_DEFAULT_FILTER; - - $strFilterQuery = "($strFilter=$strSSOID)"; - + + $strFilterQuery = "($strFilter=$strSSOID)"; + $aryControllers = wpDirAuth_shuffleControllers(explode(',', get_site_option('dirAuthControllers'))); - + if(is_wp_error($aryControllers)){ return $aryControllers; //there werent any controllers to connect to } - + /** - * @todo if we get a successful connection, cant we break out of the loop before we go through binding and a search? Or is it possible that one DC in the - * list might not allow anonymous searching and/or the pre-bind user/pass isnt valid on one of them and we need to try the next in the list? - */ + * @todo if we get a successful connection, cant we break out of the loop before we go through binding and a search? Or is it possible that one DC in the + * list might not allow anonymous searching and/or the pre-bind user/pass isnt valid on one of them and we need to try the next in the list? + */ foreach($aryControllers as $strDC){ $rscConnection = wpDirAuth_establishConnection($strDC,$intEnableSSL); if(is_wp_error($rscConnection)){ return $rscConnection; //tls failed to start on the DC } - + if(!wpDirAuth_bindTest($rscConnection,$strPreBindUser,$strPreBindPassword,$strBaseDn)){ return new WP_Error('login_failed',__('Error Connecting to LDAP Server

    ' . 'There was an error connecting to your LDAP server ('. htmlentities($strDC,ENT_QUOTES,'UTF-8').'). Please see the LDAP error message below for troubleshooting:

    ' . ldap_error($rscConnection))); } - + //successfully bound, now we need to get the user details return wpDirAuth_retrieveUserDetails($rscConnection,$strBaseDn,$strFilterQuery); } } - + /** - * Checks to make sure the user doesnt already exist and that the email associated with a SSOID isnt already in use in the blog, and if not, adds the user. - * - * @param string $strSSOID Single Sign On ID - * @param string $strRole Role chosen to give the new user - * @return mixed array of user details on success or WP_Error object on failure - */ + * Checks to make sure the user doesnt already exist and that the email associated with a SSOID isnt already in use in the blog, and if not, adds the user. + * + * @param string $strSSOID Single Sign On ID + * @param string $strRole Role chosen to give the new user + * @return mixed array of user details on success or WP_Error object on failure + */ function wpDirAuth_add_new_user($strSSOID,$strRole,$intBlogID = 0){ /** - * We need to see if the user name already exists. if not, then we need to see if the email address is already in use, if not, then we need to try and look - * up the user. then if we actually found something, then we'll add them into wordpress - */ + * We need to see if the user name already exists. if not, then we need to see if the email address is already in use, if not, then we need to try and look + * up the user. then if we actually found something, then we'll add them into wordpress + */ $strSSOID = sanitize_user($strSSOID); $intBlogID = is_int($intBlogID) ? $intBlogID : (int) $intBlogID; //just to make sure - + if(username_exists($strSSOID)){ echo '

    user already exists

    '; return new WP_Error('username_exists',__('

    Could not create a new Wordpress account because the directory username ' - . htmlentities($strSSOID,ENT_QUOTES,'UTF-8') . ' is already registered on this site.

    ')); + . htmlentities($strSSOID,ENT_QUOTES,'UTF-8') . ' is already registered on this site.

    ')); } - + //we'll have to go ahead and look them up in LDAP in order to check their email address $aryUserDetails = wpDirAuth_ConnectAndLookupUser($strSSOID); if(is_wp_error($aryUserDetails)){ return $aryUserDetails; - } + } $strUserEmail = apply_filters('user_registration_email', $aryUserDetails['email']); - + if(email_exists($strUserEmail)){ echo '

    Email address already exists

    '; - return new WP_Error('email_exists',__('Could not create a new WP account because the email ' + return new WP_Error('email_exists',__('Could not create a new WP account because the email ' . htmlentities($strUserEmail,ENT_QUOTES,'UTF-8') . ' is already registered with this site.')); } - + $aryUserDetails['user_pass'] = mt_rand();//we're going to store a random password in WP since directory users will never use it to log in anyway' $aryUserDetails['user_login'] = $strSSOID; $aryUserDetails['user_email'] = $aryUserDetails['email'] = $strUserEmail; /** - * @TODO ask Stephen why he's replacing .'s with _'s in the user name of the email address. Does nickname not allow spaces? - */ - $tmpAr = split('@',$aryUserDetails['email']); + * @TODO ask Stephen why he's replacing .'s with _'s in the user name of the email address. Does nickname not allow spaces? + */ + $tmpAr = explode('@',$aryUserDetails['email']); $aryUserDetails['nickname'] = str_replace('.','_',$tmpAr[0]); $aryUserDetails['display_name'] = $aryUserDetails['first_name'].' '.$aryUserDetails['last_name']; - $aryUserDetails['role'] = $strRole; - + $aryUserDetails['role'] = $strRole; + /** - * Switch to the blog we want to insert the user into - */ + * Switch to the blog we want to insert the user into + */ if(defined('MULTISITE') && MULTISITE && function_exists('switch_to_blog')) switch_to_blog($intBlogID); $intUserID = wp_insert_user($aryUserDetails); - + if(!is_int($intUserID)){ return new WP_Error('createuser_failed',__('For an unknow reason, WP failed to create a new user.' .' Failure occurred at line ' . __LINE__ . ' in the function ' . __FUNCTION__ . ' in the file ' . basename(__FILE__) . '.')); } - + $aryUserDetails['ID'] = $intUserID; - update_usermeta($intUserID, 'wpDirAuthFlag', 1); + update_user_meta($intUserID, 'wpDirAuthFlag', 1); wpDirAuth_remove_password_nag($intUserID); - + //for situations where an admin is adding a user from a site edit screen /** if($intBlogID != 0){ - add_user_to_blog($intBlogID,$intUserID,$strRole); + add_user_to_blog($intBlogID,$intUserID,$strRole); } */ - + if(defined('MULTISITE') && MULTISITE && function_exists('switch_to_blog')) restore_current_blog(); - return $aryUserDetails; + return $aryUserDetails; } - + /** - * Loops through the WP_Error object and prints out the error messages it contains - * - * @param object $objError - * @return void - */ + * Loops through the WP_Error object and prints out the error messages it contains + * + * @param object $objError + * @return void + */ function wpDirAuth_print_error_messages($objError){ echo PHP_EOL,'
    ',WPDIRAUTH_ERROR_TITLE,'
      ',PHP_EOL; foreach($objError->get_error_messages() as $strErrMsg){ @@ -1628,99 +1661,109 @@ ________EOS; } echo '
    ',PHP_EOL; } - + /** - * Constructs the message to be displayed when a new user has been added successfully - * - * @param string $strSSOID User's Single Sign On ID - * @param integer $strUserID user's wordpress user ID - * @param array Data on the sites and roles that the user has been added to - * @return string - * @uses wpDirAuth_determine_A_or_An - * - */ + * Constructs the message to be displayed when a new user has been added successfully + * + * @param string $strSSOID User's Single Sign On ID + * @param integer $strUserID user's wordpress user ID + * @param array Data on the sites and roles that the user has been added to + * @return string + * @uses wpDirAuth_determine_A_or_An + * + */ function wpDirAuth_construct_success_msg($strSSOID,$strUserID,$arySitesData,$strExtraMsg=''){ //$arySitesData = array('blogname','role','siteurl'); $strMsg = '

    Just created user %s as %s. %s

    '; - + $strSiteMessage = '%s for site %s'; $arySiteMsgParts = array(); foreach($arySitesData as $arySiteData){ - $arySiteMsgParts[] = sprintf($strSiteMessage,$arySiteData['role'],$arySiteData['siteurl'],$arySiteData['blogname']); + $arySiteMsgParts[] = sprintf($strSiteMessage,$arySiteData['role'],$arySiteData['siteurl'],$arySiteData['blogname']); } - + return sprintf($strMsg,$strUserID,$strSSOID,implode($arySiteMsgParts,', '),$strExtraMsg); } - + /** - * Just determines if the word $strWord should be prefaced with 'a' or 'an'. - * Yea, i know it's picky, but I work with editors who complain about this type of stuff all the time =P - * - * @param string $strWord - * @return string - */ + * Just determines if the word $strWord should be prefaced with 'a' or 'an'. + * Yea, i know it's picky, but I work with editors who complain about this type of stuff all the time =P + * + * @param string $strWord + * @return string + */ function wpDirAuth_determine_A_or_An($strWord){ $strAorAn = 'a'; if(in_array(substr($strWord,0,1),array('a','e','i','o','u'))){ $strAorAn .= 'n'; } - - return $strAorAn; + + return $strAorAn; } - + /** - * Adds contextual help to the Add Dir Auth page under the Users menu - * - */ + * Adds contextual help to the Add Dir Auth page under the Users menu + * + */ function wpDirAuth_add_user_contextual_help(){ + _wpdirauth_log(__FUNCTION__,'function called!'); $strMarketingSSOID = get_site_option('dirAuthMarketingSSOID','Username'); - add_contextual_help('users_page_'.basename(__FILE__,'.php'), - '

    ' . __('To add a directory authenticated user from your institution to your site, fill in the form on this screen. If you’re not sure which role to assign, you can use the link below to review the different roles and their capabilities. Here is a basic overview of roles:') . '

    ' . + $objScreen = get_current_screen(); + + + + $strContent = '

    ' . __('To add a directory authenticated user from your institution to your site, fill in the form on this screen. If you’re not sure which role to assign, you can use the link below to review the different roles and their capabilities. Here is a basic overview of roles:') . '

    ' . '
      ' . - '
    • ' . __('Administrators have access to all the administration features.') . '
    • ' . - '
    • ' . __('Editors can publish posts, manage posts as well as manage other people’s posts, etc.') . '
    • ' . - '
    • ' . __('Authors can publish and manage their own posts.') . '
    • ' . - '
    • ' . __('Contributors can write and manage their posts but not publish posts or upload media files.') . '
    • ' . - '
    • ' . __('Subscribers can read comments/comment/receive newsletters, etc.') . '
    • ' . + '
    • ' . __('Administrators have access to all the administration features.') . '
    • ' . + '
    • ' . __('Editors can publish posts, manage posts as well as manage other people’s posts, etc.') . '
    • ' . + '
    • ' . __('Authors can publish and manage their own posts.') . '
    • ' . + '
    • ' . __('Contributors can write and manage their posts but not publish posts or upload media files.') . '
    • ' . + '
    • ' . __('Subscribers can read comments/comment/receive newsletters, etc.') . '
    • ' . '
    ' . '

    ' . __('The user\'s insitutional single-sign-on ID (e.g. ' . $strMarketingSSOID .') will become the user\'s Wordpress username.') . '

    ' . '

    ' . __('New users will receive an email letting them know they’ve been added as a user for your site.') . '

    ' . '

    ' . __('Remember to click the Add User button at the bottom of this screen when you are finished.') . '

    ' . '

    ' . __('For more information:') . '

    ' . - '

    ' . __('Support Forums') . '

    ' - ); + '

    ' . __('Support Forums') . '

    '; + + $objScreen->add_help_tab(array( + 'id'=>'wpdirauth-help', + 'title'=>'wpDirAuth Help', + 'content'=>$strContent + + )); } - + /** - * Processes and outputs the Add Dir Auth user form. - * @return void - */ + * Processes and outputs the Add Dir Auth user form. + * @return void + */ function wpDirAuth_add_user_panel(){ _log('WPDIRAUTH - function ' . __FUNCTION__ . ' activated. '); /** - * Still needed? - */ + * Still needed? + */ global $id; /** - * get_current_screen()->id = site-users-network will let us know if we are on the sites,edit,user tab - */ + * get_current_screen()->id = site-users-network will let us know if we are on the sites,edit,user tab + */ $strScreenID = get_current_screen()->id; /** - * Are we running in a wordpress network and in the network area? - */ - $boolIsNetworkAdminScreen = (is_network_admin() && $strScreenID != 'site-users-network') ? true : false; + * Are we running in a wordpress network and in the network area? + */ + $boolIsNetworkAdminScreen = (is_network_admin() && $strScreenID != 'site-users-network') ? true : false; /** - * How do we refer to their SSOID? - */ + * How do we refer to their SSOID? + */ $strMarketingSSOID = get_site_option('dirAuthMarketingSSOID','Username'); - $strReferer = wpDirAuth_get_referer(); - + $strReferer = wpDirAuth_get_referer(); + /** - * defaults - */ + * defaults + */ $strWpDirAuthSSOID = ''; $strWpDirAuthRole = ''; $boolConfirmationEmail = true; @@ -1729,83 +1772,83 @@ ________EOS; if($boolIsNetworkAdminScreen){ $arySitesData = wpDirAuth_retrieve_multisite_blog_data(); } - + if($_POST){ if(wp_verify_nonce($_POST['_wpnonce_add-da-user'],'add-da-user')){ /** - * We gots a problem.... if they've checked all the boxes and chosen roles but forgot to enter the pawprint (it happens, you did - * it yourself!) then we cant rebuild the list of which sites were checked/not checked later because we're jumping out before - * we get to the point where we build that data. - */ + * We gots a problem.... if they've checked all the boxes and chosen roles but forgot to enter the pawprint (it happens, you did + * it yourself!) then we cant rebuild the list of which sites were checked/not checked later because we're jumping out before + * we get to the point where we build that data. + */ if(isset($_POST['ssoid']) && $_POST['ssoid'] == ''){ $objErrors->add('blank_ssoid',__('

    '.$strMarketingSSOID.' can not be left blank.

    ')); } else { $strWpDirAuthSSOID = wpDirAuth_sanitize($_POST['ssoid']); - + if($boolIsNetworkAdminScreen && $strReferer != 'site-users.php'){ - $arySitesAndRoles = array(); - $aryValidSiteIDs = array_keys($arySitesData); - $aryValidRoles = array_keys(get_editable_roles()); - _log('contents of the post in function ' . __FUNCTION__.' at line ' . __LINE__ . ':'.PHP_EOL.var_export($_POST,true)); + $arySitesAndRoles = array(); + $aryValidSiteIDs = array_keys($arySitesData); + $aryValidRoles = array_keys(get_editable_roles()); + _log('contents of the post in function ' . __FUNCTION__.' at line ' . __LINE__ . ':'.PHP_EOL.var_export($_POST,true)); //we SHOULD have at least one site set. for($i=0;$i0 && $intCountPostSite<3){ if($intCountPostSite == 1 && is_string(current($_POST[$strPostSite]))){ /** - * If the array has only one element, then this site wasnt selected as one we want to add the user to. but we - * need, for simplicity sake, to make the array contain two elements before we do input validation - */ + * If the array has only one element, then this site wasnt selected as one we want to add the user to. but we + * need, for simplicity sake, to make the array contain two elements before we do input validation + */ $_POST[$strPostSite] = array('',current($_POST[$strPostSite])); - /** - * Since we know that the array has two elements, we'll test to make sure the siteid is valid' - */ + /** + * Since we know that the array has two elements, we'll test to make sure the siteid is valid' + */ } elseif(!is_numeric($_POST[$strPostSite][0]) || !in_array($_POST[$strPostSite][0],$aryValidSiteIDs)) { - $_POST[$strPostSite][0] = ''; + $_POST[$strPostSite][0] = ''; } - + /** - * - */ + * + */ if(!in_array($_POST[$strPostSite][1],$aryValidRoles)){ $_POST[$strPostSite][1] = ''; } - + /** - * If we now have non-empty values for both elements, we'll add them to our array to be used for inserting the user into sites - */ + * If we now have non-empty values for both elements, we'll add them to our array to be used for inserting the user into sites + */ if($_POST[$strPostSite][0] != '' && $_POST[$strPostSite][1] != ''){ $arySitesAndRoles[$i] = array('blog_id'=>$_POST[$strPostSite][0],'role'=>$_POST[$strPostSite][1]); } - } + } } } - + $strWpDirAuthRole = (isset($_POST['role']) && in_array($_POST['role'],array_keys(get_editable_roles()))) ? $_POST['role'] : get_site_option('default_role'); $intBlogID = (isset($_POST['id']) && is_numeric($_POST['id'])) ? intval($_POST['id']) : ''; if(isset($_POST['noconfirmation']) && $_POST['noconfirmation'] == 1) $boolConfirmationEmail = false; - + if(!isset($arySitesAndRoles) || !$boolIsNetworkAdminScreen){ $aryUserData = wpDirAuth_add_new_user($strWpDirAuthSSOID,$strWpDirAuthRole,$intBlogID); _log('adding a standard user (' . $strWpDirAuthSSOID .')from either inside a site, or from the edit section of a site'); - _log('user data from newly added user is : ' . PHP_EOL . var_export($aryUserData,true) . PHP_EOL); + _log('user data from newly added user is : ' . PHP_EOL . var_export($aryUserData,true) . PHP_EOL); } elseif(count($arySitesAndRoles)<1) { - $aryUserData = new WP_Error('no_site_role_selected','

    You will need to select at least one site to add this user to.

    '); + $aryUserData = new WP_Error('no_site_role_selected','

    You will need to select at least one site to add this user to.

    '); } else { $aryUserData = wpDirAuth_add_new_user_to_multi_sites($strWpDirAuthSSOID,$arySitesAndRoles); _log('adding a user (' . $strWpDirAuthSSOID .')from the network Add Dir Auth user section'); } - + if(is_wp_error($aryUserData)){ //foreach($objErrors->) - + //$mxdErrors = $aryUserData; $objErrors->add($aryUserData->get_error_code(),$aryUserData->get_error_message(),$aryUserData->get_error_data()); } else { @@ -1813,126 +1856,126 @@ ________EOS; if(isset($arySitesAndRoles) && count($arySitesAndRoles)!=0){ foreach($arySitesAndRoles as $arySiteData){ $arySitesAddedTo[] = array( - 'blogname'=>$arySitesData[$arySiteData['blog_id']], - 'aoran' =>wpDirAuth_determine_A_or_An($arySiteData['role']), - 'role' =>$arySiteData['role'], - 'siteurl' =>get_site_url($arySiteData['blog_id'],'','https') - - ); - } + 'blogname'=>$arySitesData[$arySiteData['blog_id']], + 'aoran' =>wpDirAuth_determine_A_or_An($arySiteData['role']), + 'role' =>$arySiteData['role'], + 'siteurl' =>get_site_url($arySiteData['blog_id'],'','https') + + ); + } } else { $arySitesAddedTo[] = array( - 'blogname' =>get_site_option('blogname'), - 'aoran' =>wpDirAuth_determine_A_or_An($strWpDirAuthRole), - 'role' =>$strWpDirAuthRole, - 'siteurl' =>site_url() - ); - } - - /** + 'blogname' =>get_site_option('blogname'), + 'aoran' =>wpDirAuth_determine_A_or_An($strWpDirAuthRole), + 'role' =>$strWpDirAuthRole, + 'siteurl' =>site_url() + ); + } + + /** * ok, the admin has just successfully added a user to a site from the sites->edit->users tab. Since we cant seem to * redirect them back to the screen automatically, let's give them a link to go back.' */ - if($strReferer == 'site-users.php' && $boolIsNetworkAdminScreen){ - $strReturnToURL = wp_get_referer(); - $strExtraMessage = 'Return to the User tab of the '. $arySitesData[$intBlogID] . ' site.'; - } else { - $strExtraMessage = ''; - } - + if($strReferer == 'site-users.php' && $boolIsNetworkAdminScreen){ + $strReturnToURL = wp_get_referer(); + $strExtraMessage = 'Return to the User tab of the '. $arySitesData[$intBlogID] . ' site.'; + } else { + $strExtraMessage = ''; + } + $strSuccess = wpDirAuth_construct_success_msg($strWpDirAuthSSOID,$aryUserData['ID'],$arySitesAddedTo,$strExtraMessage); - _log('for user ' . $strWpDirAuthSSOID . ', added them to ' . var_export($arySitesAddedTo,true).'.'); - + _log('for user ' . $strWpDirAuthSSOID . ', added them to ' . var_export($arySitesAddedTo,true).'.'); + if($boolConfirmationEmail){ foreach($arySitesAddedTo as $arySiteAddedToData){ $strMsg = sprintf(WPDIRAUTH_EMAIL_NEWUSER_NOTIFY,$arySiteAddedToData['blogname'],$arySiteAddedToData['aoran'],$arySiteAddedToData['role'],$strMarketingSSOID,$strWpDirAuthSSOID,$arySiteAddedToData['siteurl'].'/wp-login.php'); wp_mail($aryUserData['email'],'['.$arySiteAddedToData['blogname'].'] You\'ve been added!',$strMsg); } - } - + } + //reset back to defaults $strWpDirAuthSSOID = ''; $strWpDirAuthRole = ''; $boolConfirmationEmail = true; } - } + } } else { $objErrors->add('invalid-nonce',__('Invalid nonce value')); } - } + } - - -?> + + + ?>

    Add New Directory Authentication User

    -errors) != 0) { - wpDirAuth_print_error_messages($objErrors); - } elseif($strSuccess != ''){ - echo $strSuccess; - } -?>

    + errors) != 0) { + wpDirAuth_print_error_messages($objErrors); + } elseif($strSuccess != ''){ + echo $strSuccess; + } + ?>

    Directory Auth settings page.') ?>

    - +
    > - ',PHP_EOL; } - ?> - - - - - - - - - - - - - + + +
    - - - -
    + + + + + + + + + + $strSiteName){ $boolChecked = false; - + if(isset($arySitesAndRoles[$i])){ - $aryFormSiteData = $arySitesAndRoles[$i]; + $aryFormSiteData = $arySitesAndRoles[$i]; } elseif(isset($_POST['site'.$i])) { - $aryFormSiteData = $_POST['site'.$i]; + $aryFormSiteData = $_POST['site'.$i]; } else { $aryFormSiteData = array(); } - + _log('aryFormSiteData at line ' . __LINE__ . ': ' . var_export($aryFormSiteData,true)); - + /** - * We are working on the assumption that there are either ALWAYS two elements in aryformSiteData or the array is empty. - * If the first element in the array isnt empty, then the current site needs to be checked - */ + * We are working on the assumption that there are either ALWAYS two elements in aryformSiteData or the array is empty. + * If the first element in the array isnt empty, then the current site needs to be checked + */ if(reset($aryFormSiteData) != ''){ $boolChecked = true; } - + /** - * If the last element (eg second, role) isnt empty, then we want to select it from the list - */ + * If the last element (eg second, role) isnt empty, then we want to select it from the list + */ $strRoleSelected = (end($aryFormSiteData) != '') ? current($aryFormSiteData) : ''; - + echo ''; - ++$i; + ++$i; } - - ?> - - - - - - - - - - -
    + + + +
      '.$strSiteName.' @@ -1941,38 +1984,38 @@ ________EOS; echo PHP_EOL,'
    -
    - 'createusersub' ) ); ?> + ?> + + + + + + + + + + + + + + 'createusersub' ) ); ?>
    - -__LINE__,'file'=>__FILE__)); + _wpdirauth_log($intUserID,'contents of user id',false,array('line'=>__LINE__,'file'=>__FILE__)); + $mxdReturn = true; + + $boolDirAuthEnabled = get_site_option('dirAuthEnable'); + _wpdirauth_log($boolDirAuthEnabled,'contents of boolDirAuthEnabled',false,array('line'=>__LINE__,'file'=>__FILE__)); + if(1 == $boolDirAuthEnabled){ + $intDirAuthUser = get_user_meta($intUserID,'wpDirAuthFlag',true); + _wpdirauth_log($intDirAutherUser,'contents of intDirAuthUser',false,array('line'=>__LINE__,'file'=>__FILE__)); + if(1 == $intDirAuthUser){ + + $strPasswordReset = '

    Error: Unable to reset password

    '; + $strPasswordReset .= get_site_option('dirAuthChangePassMsg'); + add_filter('login_message',function(){return '';}); + $mxdReturn = new WP_Error('invalid_username',$strPasswordReset); + } + } + + return $mxdReturn; + } + + function wpDirAuth_cookieExpire($intExpireTime,$intUserID,$boolRemember) + { + //_wpdirauth_log($intUserID,'the user id'); + //_wpdirauth_log($intExpireTime,'the expiration time'); + //_wpdirauth_log($boolRemember,'whether or not to remember the user'); + + if(1 == get_user_meta($intUserID,'wpDirAuthFlag',true)){ + /** + * @todo make this an option in the wpSettings + */ + $intExpireTime = 60 * 60; + _wpdirauth_log($intExpireTime,'user is dirauth user so this is how long will set the cookie for'); + } + + return $intExpireTime; + + } + + /** + * TESTING + */ function wpDirAuth_network_adduser(){ - add_submenu_page('users.php','Add Directory Authenticated User','Add Dir Auth User','add_users','wpDirAuth','wpDirAuth_add_user_panel'); + add_submenu_page('users.php','Add Directory Authenticated User','Add Dir Auth User','add_users','wpDirAuth','wpDirAuth_add_user_panel'); } - + function wpDirAuth_addNetworkMenu(){ - add_submenu_page('settings.php','wpDirAuth Directory Authentication Options','wpDirAuth','manage_options','wpDirAuth_optionsPanel','wpDirAuth_optionsPanel'); + $strWpDirAuthPage = add_submenu_page('settings.php','wpDirAuth Directory Authentication Options','wpDirAuth','manage_options','wpDirAuth_optionsPanel','wpDirAuth_optionsPanel'); + //$strWpDirAuthPage is here in case we want to add a contextual help panel later } - + function wpDirAuth_retrieve_multisite_blog_data(){ global $wpdb; $aryBlogData = array(); @@ -2051,52 +2153,52 @@ ________EOS; $strTableName .= ($intSiteKey != 1) ? $intSiteKey . '_' : ''; $strTableName .= 'options'; /** - * Wonder if I should do wpdb->get_var here instead? - */ + * Wonder if I should do wpdb->get_var here instead? + */ $arySiteData = $wpdb->get_results($wpdb->prepare("SELECT option_value from $strTableName WHERE option_name = 'blogname'"),ARRAY_A); $aryBlogData[$intSiteKey] = (isset($arySiteData[0]['option_value']) && $arySiteData[0]['option_value'] != '') ? $arySiteData[0]['option_value'] : 'Unable to Retrive Blog Name'; } _log('aryBlogData:'.PHP_EOL.var_export($aryBlogData,true).PHP_EOL); return $aryBlogData; } - + /** - * put your comment there... - * - * @param string $strSSOID - * @param array $aryBlogIDsRoles should be a nested array with the sub-array containing the keys 'blog_id' and 'role' - * @return mixed WP_Error or user details upon success. - */ + * put your comment there... + * + * @param string $strSSOID + * @param array $aryBlogIDsRoles should be a nested array with the sub-array containing the keys 'blog_id' and 'role' + * @return mixed WP_Error or user details upon success. + */ function wpDirAuth_add_new_user_to_multi_sites($strSSOID,$aryBlogIDsRoles){ $mxdFirstElement = reset($aryBlogIDsRoles);//reset back to the beginning if(count($aryBlogIDsRoles)<1 || !$mxdFirstElement){ return new WP_Error('blog_id_role_missing',__('

    Could not create a new Wordpress account because data on blog id and role is ' - . 'missing. Function: ' . __FUNCTION__.', line ' . __LINE__.'.

    ')); + . 'missing. Function: ' . __FUNCTION__.', line ' . __LINE__.'.

    ')); } else { - + $aryFirstSite = current($aryBlogIDsRoles); $aryUserData = wpDirAuth_add_new_user($strSSOID,$aryFirstSite['role'],$aryFirstSite['blog_id']); if(is_wp_error($aryUserData)){ return $aryUserData; } else { //we already added for the first site - unset($aryBlogIDsRoles[key($aryBlogIDsRoles)]); + unset($aryBlogIDsRoles[key($aryBlogIDsRoles)]); foreach($aryBlogIDsRoles as $arySiteDetails){ add_user_to_blog($arySiteDetails['blog_id'],$aryUserData['ID'],$arySiteDetails['role']); } - } - + } + return $aryUserData; - } + } } - + function wpDirAuth_get_referer(){ $strReferer = basename(wp_get_referer()); if(strpos($strReferer,'?') !== FALSE){ $aryRefererParts = explode('?',$strReferer); $strReferer = $aryRefererParts[0]; } - + return $strReferer; } } @@ -2106,12 +2208,12 @@ register_activation_hook(__FILE__, 'wpDirAuth_activation'); function wpDirAuth_activation($network_wide){ if($network_wide){ /** - * Prior to v1.7.5, wpDirAuth options were stored in wp_options when + * Prior to v1.7.5, wpDirAuth options were stored in wp_options when * network activated instead of wp_sitemeta. To ensure that users dont * lose their settings when upgrading to 1.7.5 or newer, we'll check - * to see if there are wpDirAuth options in wp_options when network - * activating. If so, we'll copy them over to wp_sitemeta and then - * delete them from wp_options + * to see if there are wpDirAuth options in wp_options when network + * activating. If so, we'll copy them over to wp_sitemeta and then + * delete them from wp_options */ $mxdWpDirAuthEnable = get_option('dirAuthEnable'); if(is_integer($mxdWpDirAuthEnable) && $mxdWpDirAuthEnable !== FALSE){ @@ -2124,64 +2226,67 @@ function wpDirAuth_activation($network_wide){ } if(!function_exists('_log')){ - /** - * For logging debug messages into the debug log. - * - * @param mixed $message - */ - function _log( $message, $boolBackTraced = false ) { - _wpdirauth_log($message,null,$boolBackTraced); - } + /** + * For logging debug messages into the debug log. + * + * @param mixed $message + */ + function _log( $message, $boolBackTraced = false ) { + _wpdirauth_log($message,null,$boolBackTraced); + } } if(!function_exists('_wpdirauth_log')){ - /** - * For logging debug messages into the debug log. - * - * @param mixed $mxdVariable variable we need to debug - * @param $strPrependMessage message to include - * @param boolean $boolBackTraced - * @param array $aryDetails details for doing a mini backtrace instead of the full thing - * - */ - function _wpdirauth_log( $mxdVariable, $strPrependMessage = null, $boolBackTraced = false, $aryDetails = array() ) { - $boolBackTrace = false; - if( WP_DEBUG === true ){ - $strMessage = 'WPDIRAUTH: '; - - if(count($aryDetails) > 0){ - if(isset($aryDetails['line'])){ - $strMessage .= 'At line number ' . $aryDetails['line'] . ' '; - } - - if(isset($aryDetails['func'])){ - $strMessage .= 'inside of function ' . $aryDetails['func'] . ' '; - } - - if(isset($aryDetails['file'])){ - $strMessage .= 'in file ' . $aryDetails['file'] .' '; - } - - $strMessage .= PHP_EOL; - } - - if(!is_null($strPrependMessage)) $strMessage .= $strPrependMessage.' '; - - if( is_array( $mxdVariable ) || is_object( $mxdVariable ) ){ - $strMessage .= PHP_EOL . var_export($mxdVariable,true); - } else { - $strMessage .= $mxdVariable; - } - - if($boolBackTrace && $boolBackTraced){ - $aryBackTrace = debug_backtrace(); - - $strMessage .= PHP_EOL.'Contents of backtrace:'.PHP_EOL.var_export($aryBackTrace,true).PHP_EOL; - } - - error_log($strMessage); - } - } -} + /** + * For logging debug messages into the debug log. + * + * @param mixed $mxdVariable variable we need to debug + * @param $strPrependMessage message to include + * @param boolean $boolBackTraced + * @param array $aryDetails details for doing a mini backtrace instead of the full thing + * + */ + function _wpdirauth_log( $mxdVariable, $strPrependMessage = null, $boolBackTraced = false, $aryDetails = array() ) { + $boolBackTrace = false; + /** + * This is here so I can leave my debugging messages in the code but disable them from logging when out in + * production. + */ + $boolDoLog = false; + if( WP_DEBUG === true && $boolDoLog){ + $strMessage = 'WPDIRAUTH: '; -?> + if(count($aryDetails) > 0){ + if(isset($aryDetails['line'])){ + $strMessage .= 'At line number ' . $aryDetails['line'] . ' '; + } + + if(isset($aryDetails['func'])){ + $strMessage .= 'inside of function ' . $aryDetails['func'] . ' '; + } + + if(isset($aryDetails['file'])){ + $strMessage .= 'in file ' . $aryDetails['file'] .' '; + } + + $strMessage .= PHP_EOL; + } + + if(!is_null($strPrependMessage)) $strMessage .= $strPrependMessage.' '; + + if( is_array( $mxdVariable ) || is_object( $mxdVariable ) ){ + $strMessage .= PHP_EOL . var_export($mxdVariable,true); + } else { + $strMessage .= $mxdVariable; + } + + if($boolBackTrace && $boolBackTraced){ + $aryBackTrace = debug_backtrace(); + + $strMessage .= PHP_EOL.'Contents of backtrace:'.PHP_EOL.var_export($aryBackTrace,true).PHP_EOL; + } + + error_log($strMessage); + } + } +} \ No newline at end of file