Failed SQL queries are now also reported in bug mails, SQL queries improved (more...
[mailer.git] / inc / libs / admins_functions.php
index b3336935e27449487b33c5bb36461f32893aa28c..8c692aa43b70c0b986b5edc1c4b3f814cd50479f 100644 (file)
@@ -18,6 +18,7 @@
  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
  * For more information visit: http://www.mxchange.org                  *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -169,44 +170,46 @@ function adminsChangeAdminAccount ($postData, $element = '') {
 
                        // Admin account saved
                        $message = getMessage('ADMIN_ACCOUNT_SAVED');
-               } elseif ($postData['pass1'][$id] == $postData['pass2'][$id]) {
-                       // Save only when both passwords are the same (also when they are empty)
-                       $add = ''; $cache_update = 1;
-
-                       // Generate hash
-                       $hash = generateHash($postData['pass1'][$id]);
-
-                       // Save password when set
-                       if (!empty($postData['pass1'][$id])) $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
-
-                       // Get admin's id
-                       $adminId = getCurrentAdminId();
-                       $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
-
-                       // Rewrite cookie when it's own account
-                       if ($adminId == $id) {
-                               // Set timeout cookie
-                               setSession('admin_last', time());
-
-                               if ($login != getSession('admin_login')) {
-                                       // Update login cookie
-                                       setSession('admin_login', $login);
-
-                                       // Update password cookie as well?
-                                       if (!empty($add)) setSession('admin_md5', $hash);
-                               } elseif (generateHash($postData['pass1'][$id], $salt) != getSession('admin_md5')) {
-                                       // Update password cookie
-                                       setSession('admin_md5', $hash);
-                               }
-                       } // END - if
-
-                       // Get default ACL from admin to check if we can allow him to change the default ACL
-                       $default = getAdminDefaultAcl(getCurrentAdminId());
-
-                       // Update admin account
-                       if ($default == 'allow') {
-                               // Allow changing default ACL
-                               SQL_QUERY_ESC("UPDATE
+               } elseif ((isset($postData['pass1'])) && (isset($postData['pass2']))) {
+                       // Update only if both passwords match
+                       if (($postData['pass1'][$id] == $postData['pass2'][$id])) {
+                               // Save only when both passwords are the same (also when they are empty)
+                               $add = ''; $cache_update = 1;
+
+                               // Generate hash
+                               $hash = generateHash($postData['pass1'][$id]);
+
+                               // Save password when set
+                               if (!empty($postData['pass1'][$id])) $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
+
+                               // Get admin's id
+                               $adminId = getCurrentAdminId();
+                               $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
+
+                               // Rewrite cookie when it's own account
+                               if ($adminId == $id) {
+                                       // Set timeout cookie
+                                       setSession('admin_last', time());
+
+                                       if ($login != getSession('admin_login')) {
+                                               // Update login cookie
+                                               setSession('admin_login', $login);
+
+                                               // Update password cookie as well?
+                                               if (!empty($add)) setSession('admin_md5', $hash);
+                                       } elseif (generateHash($postData['pass1'][$id], $salt) != getSession('admin_md5')) {
+                                               // Update password cookie
+                                               setSession('admin_md5', $hash);
+                                       }
+                               } // END - if
+
+                               // Get default ACL from admin to check if we can allow him to change the default ACL
+                               $default = getAdminDefaultAcl(getCurrentAdminId());
+
+                               // Update admin account
+                               if ($default == 'allow') {
+                                       // Allow changing default ACL
+                                       SQL_QUERY_ESC("UPDATE
        `{?_MYSQL_PREFIX?}_admins`
 SET
        `login`='%s'".$add.",
@@ -216,16 +219,16 @@ SET
 WHERE
        `id`=%s
 LIMIT 1",
-                               array(
-                                       $login,
-                                       $postData['email'][$id],
-                                       $postData['mode'][$id],
-                                       $postData['la_mode'][$id],
-                                       $id
-                               ), __FUNCTION__, __LINE__);
-                       } else {
-                               // Do not allow it here
-                               SQL_QUERY_ESC("UPDATE
+                                       array(
+                                               $login,
+                                               $postData['email'][$id],
+                                               $postData['mode'][$id],
+                                               $postData['la_mode'][$id],
+                                               $id
+                                       ), __FUNCTION__, __LINE__);
+                               } else {
+                                       // Do not allow it here
+                                       SQL_QUERY_ESC("UPDATE
        `{?_MYSQL_PREFIX?}_admins`
 SET
        `login`='%s'".$add.",
@@ -234,19 +237,42 @@ SET
 WHERE
        `id`=%s
 LIMIT 1",
-                               array(
-                                       $login,
-                                       $postData['email'][$id],
-                                       $postData['la_mode'][$id],
-                                       $id
-                               ), __FUNCTION__, __LINE__);
-                       }
+                                       array(
+                                               $login,
+                                               $postData['email'][$id],
+                                               $postData['la_mode'][$id],
+                                               $id
+                                       ), __FUNCTION__, __LINE__);
+                               }
 
-                       // Admin account saved
-                       $message = getMessage('ADMIN_ACCOUNT_SAVED');
+                               // Admin account saved
+                               $message = getMessage('ADMIN_ACCOUNT_SAVED');
+                       } else {
+                               // Passwords did not match
+                               $message = getMessage('ADMINS_ERROR_PASS_MISMATCH');
+                       }
                } else {
-                       // Passwords did not match
-                       $message = getMessage('ADMINS_ERROR_PASS_MISMATCH');
+                       // Update whole array
+                       $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_admins` SET ';
+                       foreach ($postData as $entry => $value) {
+                               // Skip login/id entry
+                               if (in_array($entry, array('login', 'id'))) continue;
+
+                               // Do we have a non-string (e.g. number, NOW() or back-tick at the beginning?
+                               if ((bigintval($value[$id], true, false) === $value[$id]) || ($value[$id] == 'NOW()') || (substr($value[$id], 0, 1) == '`'))  {
+                                       // No need for ticks (')
+                                       $SQL .= '`' . $entry . '`=' . $value[$id] . ',';
+                               } else {
+                                       // Strings need ticks (') around them
+                                       $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "',";
+                               }
+                       } // END - foreach
+
+                       // Remove last tick and finish query
+                       $SQL = substr($SQL, 0, -1) . ' WHERE `id`=%s LIMIT 1';
+
+                       // Run it
+                       SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
                }
        } // END - foreach
 
@@ -393,20 +419,8 @@ function adminsListAdminAccounts() {
        loadTemplate('admin_list_admins', false, $OUT);
 }
 
-// Filter for adding extra data to the query
-function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
-       // Is the admins extension updated? (should be!)
-       if (getExtensionVersion('admins') >= '0.3.0') $add .= ', `default_acl` AS def_acl';
-       if (getExtensionVersion('admins') >= '0.6.7') $add .= ', `la_mode`';
-       if (getExtensionVersion('admins') >= '0.7.2') $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
-       if (getExtensionVersion('admins') >= '0.7.3') $add .= ', `expert_settings`, `expert_warning`';
-
-       // Return it
-       return $add;
-}
-
 // Sends out mail to all administrators
-// IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
+// IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
 function sendAdminsEmails ($subj, $template, $content, $userid) {
        // Trim template name
        $template = trim($template);
@@ -417,7 +431,7 @@ function sendAdminsEmails ($subj, $template, $content, $userid) {
        // Check which admin shall receive this mail
        $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
                array($template), __FUNCTION__, __LINE__);
-       if (SQL_NUMROWS($result) == '0') {
+       if (SQL_HASZERONUMS($result)) {
                // Create new entry (to all admins)
                SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
                        array($template), __FUNCTION__, __LINE__);
@@ -449,7 +463,7 @@ function sendAdminsEmails ($subj, $template, $content, $userid) {
                                        $userid
                                ));
                        }
-               } elseif ($adminId == '0') {
+               } elseif (($adminId == '0') || (empty($adminId))) {
                        // Select all email adresses
                        $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC",
                                __FUNCTION__, __LINE__);
@@ -543,5 +557,154 @@ function getAminsExpertWarning () {
        return $data['expert_warning'];
 }
 
+// Get login_failures number from administrator's login name
+function getAdminLoginFailures ($adminLogin) {
+       // Admin login should not be empty
+       if (empty($adminLogin)) {
+               debug_report_bug('adminLogin is empty.');
+       } // END - if
+
+       // By default no admin is found
+       $data['login_failures'] = '-1';
+
+       // Check cache
+       if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminLogin])) {
+               // Use it if found to save SQL queries
+               $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminLogin];
+
+               // Update cache hits
+               incrementStatsEntry('cache_hits');
+       } elseif (!isExtensionActive('cache')) {
+               // Load from database
+               $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
+                       array($adminLogin), __FUNCTION__, __LINE__);
+
+               // Do we have an entry?
+               if (SQL_NUMROWS($result) == 1) {
+                       // Get it
+                       $data = SQL_FETCHARRAY($result);
+               } // END - if
+
+               // Free result
+               SQL_FREERESULT($result);
+       }
+
+       // Return the login_failures
+       return $data['login_failures'];
+}
+
+// Get last_failure number from administrator's login name
+function getAdminLastFailure ($adminLogin) {
+       // Admin login should not be empty
+       if (empty($adminLogin)) {
+               debug_report_bug('adminLogin is empty.');
+       } // END - if
+
+       // By default no admin is found
+       $data['last_failure'] = '-1';
+
+       // Check cache
+       if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminLogin])) {
+               // Use it if found to save SQL queries
+               $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminLogin];
+
+               // Update cache hits
+               incrementStatsEntry('cache_hits');
+       } elseif (!isExtensionActive('cache')) {
+               // Load from database
+               $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
+                       array($adminLogin), __FUNCTION__, __LINE__);
+
+               // Do we have an entry?
+               if (SQL_NUMROWS($result) == 1) {
+                       // Get it
+                       $data = SQL_FETCHARRAY($result);
+               } // END - if
+
+               // Free result
+               SQL_FREERESULT($result);
+       }
+
+       // Return the last_failure
+       return $data['last_failure'];
+}
+
+//*****************************************************************************
+//                     Below only filter functions
+//*****************************************************************************
+
+// Filter for adding extra data to the query
+function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
+       // Is the admins extension updated? (should be!)
+       if (getExtensionVersion('admins') >= '0.3.0') $add .= ', `default_acl` AS def_acl';
+       if (getExtensionVersion('admins') >= '0.6.7') $add .= ', `la_mode`';
+       if (getExtensionVersion('admins') >= '0.7.2') $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
+       if (getExtensionVersion('admins') >= '0.7.3') $add .= ', `expert_settings`, `expert_warning`';
+
+       // Return it
+       return $add;
+}
+
+// Reset the login failures
+function FILTER_RESET_ADMINS_LOGIN_FAILURES ($data) {
+       // Store it in session
+       setSession('mxchange_admin_failures'    , getAdminLoginFailures($data['login']));
+       setSession('mxchange_admin_last_failure', getAdminLastFailure($data['login']));
+
+       // Prepare update data
+       $postData['login'][getCurrentAdminId()]          = $data['login'];
+       $postData['login_failures'][getCurrentAdminId()] = '0';
+       $postData['last_failure'][getCurrentAdminId()]   = '0000-00-00 00:00:00';
+
+       // Change it in the admin
+       adminsChangeAdminAccount($postData);
+
+       // Always make sure the cache is destroyed
+       rebuildCache('admin');
+
+       // Return the data for further processing
+       return $data;
+}
+
+// Count the login failure
+function FILTER_COUNT_ADMINS_LOGIN_FAILURE ($data) {
+       // Prepare update data
+       $postData['login'][getCurrentAdminId()]          = $data['login'];
+       $postData['login_failures'][getCurrentAdminId()] = '`login_failures`+1';
+       $postData['last_failure'][getCurrentAdminId()]   = 'NOW()';
+
+       // Change it in the admin
+       adminsChangeAdminAccount($postData);
+
+       // Always make sure the cache is destroyed
+       rebuildCache('admin');
+
+       // Return the data for further processing
+       return $data;
+}
+
+// Rehashes the given plain admin password and stores it the database
+function FILTER_REHASH_ADMINS_PASSWORD ($data) {
+       // Generate new hash
+       $newHash = generateHash($data['plain_pass']);
+
+       // Prepare update data
+       $postData['login'][getCurrentAdminId()]    = $data['login'];
+       $postData['password'][getCurrentAdminId()] = $newHash;
+
+       // Change it in the admin
+       adminsChangeAdminAccount($postData);
+
+       // Update cookie/session and data array
+       setSession('admin_md5', encodeHashForCookie($newHash));
+       $data['pass_hash'] = $newHash;
+
+       // Always make sure the cache is destroyed
+       rebuildCache('admin');
+
+       // Return the data for further processing
+       return $data;
+}
+
 // [EOF]
 ?>