Renamed ifSqlHasZeroNums() to ifSqlHasZeroNumRows() and improved some queries.
[mailer.git] / inc / modules / admin / what-list_user.php
index feabe013ac560fd0fe361374202e5f2fd315cd4d..295b8144062ad50bd112d7035216d732c4b57d0d 100644 (file)
@@ -16,7 +16,7 @@
  * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2015 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -44,29 +44,26 @@ if ((!defined('__SECURITY')) || (!isAdmin())) {
 addYouAreHereLink('admin', __FILE__);
 
 // Init variables
-$MORE = '';
+$moreColumns = '';
 
 // Add lock reason?
 if (isExtensionInstalledAndNewer('user', '0.3.5')) {
        // Add them...
-       $MORE .= ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
+       $moreColumns .= ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
 } // END - if
 
 // Is the extension 'country' installed?
 if (isExtensionActive('country')) {
        // Add country code
-       $MORE .= ',`country_code`';
-} else {
-       // Add direct value
-       $MORE .= ',`country`';
-}
+       $moreColumns .= ',`country_code`';
+} // END - if
 
 // Init unset data
 if (!isGetRequestElementSet('letter')) { setGetRequestElement('letter', '');       }
 if (!isGetRequestElementSet('sortby')) { setGetRequestElement('sortby', 'userid'); }
 if (!isGetRequestElementSet('page'))   { setGetRequestElement('page'  , 1);        }
 
-// Set base URL
+// Set base HTML
 $base = '[<a href="{%url=modules.php?module=admin';
 
 if (isGetRequestElementSet('userid')) {
@@ -74,31 +71,54 @@ if (isGetRequestElementSet('userid')) {
        $userid = bigintval(getRequestElement('userid'));
 
        // Does the account exists?
-       $result_user = SQL_QUERY_ESC("SELECT
-       `userid`,`country`,`email`,`birth_day`,`birth_month`,`birth_year`,`last_online`,`used_points`,`emails_sent`,`joined`,`last_update`,`last_profile_sent`,`notified`,`emails_received`,`mails_confirmed`".$MORE."
+       $result_user = sqlQueryEscaped('SELECT
+       `userid`,
+       `country`,
+       `email`,
+       `birth_day`,
+       `birth_month`,
+       `birth_year`,
+       `last_online`,
+       `used_points`,
+       `emails_sent`,
+       `joined`,
+       `last_update`,
+       `last_profile_sent`,
+       `notified`,
+       `emails_received`,
+       `mails_confirmed`
+       ' . $moreColumns . '
 FROM
        `{?_MYSQL_PREFIX?}_user_data`
 WHERE
        `userid`=%s
-LIMIT 1",
+LIMIT 1',
                array($userid), __FILE__, __LINE__);
 
        // User found?
-       if (SQL_NUMROWS($result_user) == 1) {
+       if (sqlNumRows($result_user) == 1) {
                // Account found
-               $content  = SQL_FETCHARRAY($result_user);
+               $content  = sqlFetchArray($result_user);
 
                // Get count/sum of refs, selected categories, unconfirmed mails
+               // @TODO Refacture these old link generation to functions
                $content['refs']  = countSumTotalData($userid, 'refsystem', 'counter');
-               $content['cats']  = countSumTotalData($userid, 'user_cats', 'id', 'userid', true);
+               $content['cats']  = countSumTotalData($userid, 'user_cats', 'id', 'userid', TRUE);
                $content['links'] = getTotalUnconfirmedMails($userid);
 
                // Add links to the numbers
-               if ($content['links'] > 0) $content['links'] = $base . '&amp;what=list_links&amp;userid=' . $userid . '%}">' . $content['links'] . '</a>]';
-               if ($content['refs']  > 0) $content['refs']  = $base . '&amp;what=list_refs&amp;userid=' . $userid . '%}">{%pipe,translateComma=' . $content['refs'] . '%}</a>]';
-               if ($content['cats']  > 0) $content['cats']  = $base . '&amp;what=list_cats&amp;userid=' . $userid . '%}">{%pipe,translateComma=' . $content['cats'] . '%}</a>]';
+               if ($content['links'] > 0) {
+                       $content['links'] = $base . '&amp;what=list_links&amp;userid=' . $userid . '%}">' . $content['links'] . '</a>]';
+               } // END - if
+               if ($content['refs']  > 0) {
+                       $content['refs']  = $base . '&amp;what=list_refs&amp;userid=' . $userid . '%}">{%pipe,translateComma=' . $content['refs'] . '%}</a>]';
+               } // END - if
+               if ($content['cats']  > 0) {
+                       $content['cats']  = $base . '&amp;what=list_user_cats&amp;userid=' . $userid . '%}">{%pipe,translateComma=' . $content['cats'] . '%}</a>]';
+               } // END - if
 
                // Calculate timestamp for birthday
+               // @TODO Refacture birth_foo to avoid uni* timetstamps as older members cannot be greeded correctly
                $stamp = mktime(0, 0, 0, $content['birth_month'], $content['birth_day'], $content['birth_year']);
 
                // Is this above zero?
@@ -116,7 +136,6 @@ LIMIT 1",
                $content['joined']            = generateDateTime($content['joined'], '2');
                $content['last_update']       = generateDateTime($content['last_update'], '2');
                $content['last_profile_sent'] = generateDateTime($content['last_profile_sent'], '2');
-               $content['total_points']      = getTotalPoints($content['userid']);
                $content['locked_points']     = countSumTotalData($content['userid'], 'user_points', 'locked_points') + countSumTotalData($content['userid'], 'user_points', 'locked_order_points');
 
                // Prepare array for filter
@@ -138,10 +157,7 @@ LIMIT 1",
                } // END - if
 
                // Clickrate
-               $content['click_rate'] = '0';
-               if ($content['emails_received'] > 0) {
-                       $content['click_rate'] = ($content['mails_confirmed'] / $content['emails_received'] * 100);
-               } // END - if
+               $content['click_rate'] = calculatePercentageRate($content['mails_confirmed'], $content['emails_received']);
 
                // Is the extension 'country' installed?
                if (isExtensionActive('country')) {
@@ -156,14 +172,14 @@ LIMIT 1",
                $content['userid'] = $userid;
 
                // Load user-details template
-               loadTemplate('admin_user_details', false, $content);
+               loadTemplate('admin_user_details', FALSE, $content);
        } else {
                // Account does not exist!
                displayMessage('{%message,ADMIN_MEMBER_404=' . $userid . '%}');
        }
 
        // Free the result
-       SQL_FREERESULT($result_user);
+       sqlFreeResult($result_user);
 } else {
        $whereStatement = '';
        if (isGetRequestElementSet('letter')) {
@@ -176,14 +192,17 @@ LIMIT 1",
                // Is a WHERE statement already there?
                if (!empty($whereStatement)) {
                        // Then append the status column
-                       $whereStatement .= sprintf(" AND `status`='%s'", SQL_ESCAPE(secureString(strtoupper(getRequestElement('status')))));
+                       $whereStatement .= sprintf(" AND `status`='%s'", sqlEscapeString(strtoupper(getRequestElement('status'))));
                } else {
                        // Start a new one
-                       $whereStatement = sprintf(" WHERE `status`='%s'", SQL_ESCAPE(secureString(strtoupper(getRequestElement('status')))));
+                       $whereStatement = sprintf(" WHERE `status`='%s'", sqlEscapeString(strtoupper(getRequestElement('status'))));
                }
-       } elseif (isGetRequestElementSet('mode')) {
+
+               // Exclude other users
+               $whereStatement = runFilterChain('user_exclusion_sql', ' ' . $whereStatement);
+       } elseif (isGetRequestElementSet('do')) {
                // Choose what we need to list
-               switch (getRequestElement('mode')) {
+               switch (getRequestElement('do')) {
                        case 'norefs': // Users w/o refs
                                if (!empty($whereStatement)) {
                                        // Add AND statement
@@ -204,41 +223,63 @@ LIMIT 1",
                                }
                                break;
 
+                       case 'testers': // Test accounts
+                               // Add statement through filter
+                               $whereStatement = runFilterChain('user_inclusion_sql', $whereStatement);
+                               break;
+
                        default: // Invalid list mode
-                               debug_report_bug(__FILE__, __LINE__, sprintf("Invalid list mode %s detected.", getRequestElement('mode')));
+                               reportBug(__FILE__, __LINE__, sprintf('Invalid do %s detected.', sqlEscapeString(getRequestElement('do'))));
                                break;
                } // END - switch
+
+               // If it is not 'testers', add exclusion SQL
+               if (getRequestElement('do') != 'testers') {
+                       // Exclude tester users
+                       $whereStatement = runFilterChain('user_exclusion_sql', ' ' . $whereStatement);
+               } // END - if
        } // END - if
 
        // Generate master query string
-       $sql = sprintf("SELECT `userid`,`email`,`emails_sent`,`mails_confirmed`,`emails_received`" . $MORE . " FROM `{?_MYSQL_PREFIX?}_user_data`" . $whereStatement . " ORDER BY `%s` ASC",
+       $sql = sprintf('SELECT
+       `userid`,
+       `email`,
+       `emails_sent`,
+       `mails_confirmed`,
+       `emails_received`
+       ' . $moreColumns . '
+FROM
+       `{?_MYSQL_PREFIX?}_user_data`
+' . $whereStatement . '
+ORDER BY
+       `%s` ASC',
                getRequestElement('sortby')
        );
 
        // Prepare SQL and run it
-       $result_master = SQL_QUERY($sql, __FILE__, __LINE__);
+       $result_master = sqlQuery($sql, __FILE__, __LINE__);
 
-       // Calculate page count (0.5 fixes a bug with page count)
-       if (getConfig('user_limit') == '0') {
+       // Is the user limit zero?
+       if (getUserLimit() == '0') {
+               // Then set it to default ...
                setConfigEntry('user_limit', 100);
+
+               // ... but output warning
                displayMessage('{--EXTENSION_WARNING_USER_LIMIT--}');
        } // END - if
 
-       // Activate the extension please!
-       $numPages = round(SQL_NUMROWS($result_master) / getConfig('user_limit') + 0.5);
+       // Calculate page count (0.5 fixes a bug with page count)
+       $numPages = round(sqlNumRows($result_master) / getUserLimit() + 0.5);
 
        if (!isGetRequestElementSet('page'))   setGetRequestElement('page'  , 1);
-       if (!isGetRequestElementSet('offset')) setGetRequestElement('offset', getConfig('user_limit'));
+       if (!isGetRequestElementSet('offset')) setGetRequestElement('offset', getUserLimit());
 
        // Add limitation to SQL string and run him again
        $sql .= ' LIMIT ' . (getRequestElement('offset') * getRequestElement('page') - getRequestElement('offset')) . ', ' . getRequestElement('offset');
-       $result = SQL_QUERY($sql, __FILE__, __LINE__);
+       $result = sqlQuery($sql, __FILE__, __LINE__);
 
        // Are there some entries?
-       if (!SQL_HASZERONUMS($result_master)) {
-               // We have some (new?) registrations!
-               $templateContent['user_count'] = getTotalConfirmedUser();
-
+       if (!ifSqlHasZeroNumRows($result_master)) {
                // Sorting links and number of pages
                $templateContent['sort_links'] = addSortLinks(getRequestElement('letter'), getRequestElement('sortby'));
                $templateContent['num_pages'] = $numPages;
@@ -253,7 +294,7 @@ LIMIT 1",
 
                // Load all users
                $OUT = '';
-               while ($content = SQL_FETCHARRAY($result)) {
+               while ($content = sqlFetchArray($result)) {
                        // Merge more data in
                        $content = merge_array($content, $templateContent);
 
@@ -269,17 +310,36 @@ LIMIT 1",
                        } // END - if
 
                        // Click rate
-                       $content['click_rate'] = '0';
-                       if ($content['emails_received'] > 0) {
-                               $content['click_rate'] = $content['mails_confirmed'] / $content['emails_received'] * 100;
-                       } // END - if
+                       $content['click_rate'] = calculatePercentageRate($content['mails_confirmed'], $content['emails_received']);
 
                        // Transfer data to array
                        $content['email']          = '[<a href="' . generateEmailLink($content['email'], 'user_data') . '">' . $content['email'] . '</a>]';
                        $content['lock_timestamp'] = generateDateTime($content['lock_timestamp'], '2');
-                       $content['refs']           = countSumTotalData($content['userid'], 'user_refs', 'id', 'userid', true);
-                       $content['own_points']     = countSumTotalData($content['userid'], 'user_points', 'points') + countSumTotalData($content['userid'], 'user_points', 'order_points');
-                       $content['locked_points']  = countSumTotalData($content['userid'], 'user_points', 'locked_points') + countSumTotalData($content['userid'], 'user_points', 'locked_order_points');
+                       $content['refs']           = countSumTotalData($content['userid'], 'user_refs', 'id', 'userid', TRUE);
+
+                       // Prepare array for filter
+                       $data = array(
+                               'userid' => $content['userid'],
+                               'points' => 0
+                       );
+
+                       // Run the filter chain
+                       $data = runFilterChain('get_own_points', $data);
+
+                       // Copy points
+                       $content['own_points'] = $data['points'];
+
+                       // Prepare array for filter again
+                       $data = array(
+                               'userid' => $content['userid'],
+                               'points' => 0
+                       );
+
+                       // Run the filter chain
+                       $data = runFilterChain('get_locked_points', $data);
+
+                       // Copy points
+                       $content['locked_points']  = $data['points'];
 
                        // If we have at least one referral, make it clickable to referral list
                        if ($content['refs'] > 0) {
@@ -297,14 +357,14 @@ LIMIT 1",
                        }
 
                        // Load row template and switch colors
-                       $OUT .= loadTemplate('admin_list_user_row', true, $content);
+                       $OUT .= loadTemplate('admin_list_user_row', TRUE, $content);
                } // END - while
 
                // Free memory
-               SQL_FREERESULT($result);
+               sqlFreeResult($result);
 
                // Free some memory
-               SQL_FREERESULT($result_master);
+               sqlFreeResult($result_master);
 
                // Remember all rows
                $content['rows'] = $OUT;
@@ -313,14 +373,14 @@ LIMIT 1",
                $content = merge_array($content, $templateContent);
 
                // Load main template
-               loadTemplate('admin_list_user', false, $content);
+               loadTemplate('admin_list_user', FALSE, $content);
        } else {
                // No one as registered so far! :-(
                displayMessage('{--ADMIN_NO_NONE_REGISTERED--}');
        }
 
        // Free memory
-       SQL_FREERESULT($result_master);
+       sqlFreeResult($result_master);
 }
 
 // [EOF]