Renamed function so it might be more understandable
[mailer.git] / inc / mysql-manager.php
index 4ff3a8cd7b585d64a49192b0ffef40e0cb46b27d..f7238a64a85a8d71b6d5670f1b29f697dcfe2e94 100644 (file)
@@ -14,8 +14,6 @@
  * $Date::                                                            $ *
  * $Tag:: 0.2.1-FINAL                                                 $ *
  * $Author::                                                          $ *
- * Needs to be in all Files and every File needs "svn propset           *
- * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
@@ -74,8 +72,8 @@ function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
        return $data['title'];
 }
 
-// Add menu description pending on given file name (without path!)
-function addMenuDescription ($accessLevel, $FQFN, $return = false) {
+// Add link into output stream (or return it) for 'You Are Here' navigation
+function addYouAreHereLink ($accessLevel, $FQFN, $return = false) {
        // Use only filename of the FQFN...
        $file = basename($FQFN);
 
@@ -239,7 +237,7 @@ ORDER BY
                        // Do we have some entries?
                        if (!SQL_HASZERONUMS($result_sub)) {
                                // Init counter
-                               $cnt = '0';
+                               $count = '0';
 
                                // Load all sub menus
                                while ($content2 = SQL_FETCHARRAY($result_sub)) {
@@ -262,7 +260,7 @@ ORDER BY
                                                $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&amp;what=' . $content['sub_what'] . '%}" target="_self">';
                                        } else {
                                                // Not found! - open
-                                               $OUT .= '<em style="cursor:help" class="admin_note" title="{%message,MENU_WHAT_404=' . $content['sub_what'] . '%}">';
+                                               $OUT .= '<em style="cursor:help" class="notice" title="{%message,MENU_WHAT_404=' . $content['sub_what'] . '%}">';
                                        }
 
                                        // Menu title
@@ -281,7 +279,7 @@ ORDER BY
                                        }
 
                                        // Cunt it up
-                                       $cnt++;
+                                       $count++;
 
                                        // Rewrite array
                                        $content = array(
@@ -292,7 +290,7 @@ ORDER BY
                                        );
 
                                        // Add regular menu row or bottom row?
-                                       if ($cnt < SQL_NUMROWS($result_sub)) {
+                                       if ($count < SQL_NUMROWS($result_sub)) {
                                                $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
                                        } else {
                                                $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
@@ -370,61 +368,56 @@ function isMember () {
        // @TODO Try to rewrite this to one or more functions
        if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
 
-       // is the cache entry there?
-       if (isset($GLOBALS['is_member'])) {
+       // Is the cache entry there?
+       if (isset($GLOBALS[__FUNCTION__])) {
                // Then return it
-               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS['is_member']) . ')');
-               return $GLOBALS['is_member'];
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
+               return $GLOBALS[__FUNCTION__];
        } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
-               // No member
+               // Destroy any existing user session data
+               destroyMemberSession();
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
+
+               // Abort further processing
                return false;
-       } else {
-               // Get it secured from session
-               setMemberId(getSession('userid'));
-               setCurrentUserId(getMemberId());
-               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . getSession('userid') . ' used from cookie/session.');
        }
 
+       // Get userid secured from session
+       setMemberId(getSession('userid'));
+
+       // ... and set it as currently handled user id
+       setCurrentUserId(getMemberId());
+
        // Init user data array
        initUserData();
 
        // Fix "deleted" cookies first
        fixDeletedCookies(array('userid', 'u_hash'));
 
-       // Are cookies set?
-       if ((isMemberIdSet()) && (isSessionVariableSet('u_hash'))) {
-               // Cookies are set with values, but are they valid?
-               if (fetchUserData(getMemberId()) === true) {
-                       // Validate password by created the difference of it and the secret key
-                       $valPass = encodeHashForCookie(getUserData('password'));
+       // Are cookies set and can the member data be loaded?
+       if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === true)) {
+               // Validate password by created the difference of it and the secret key
+               $valPass = encodeHashForCookie(getUserData('password'));
 
+               // So did we now have valid data and an unlocked user?
+               if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
                        // Transfer last module and online time
                        $GLOBALS['last_online']['module'] = getUserData('last_module');
                        $GLOBALS['last_online']['online'] = getUserData('last_online');
 
-                       // So did we now have valid data and an unlocked user?
-                       if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
-                               // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
-                               $ret = true;
-                       } else {
-                               // Maybe got locked etc.
-                               //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'status=' . getUserData('status') . ',' . $valPass . '(' . strlen($valPass) . ')/' . getSession('u_hash') . '(' . strlen(getSession('u_hash')) . ')/' . getUserData('password') . '(' . strlen(getUserData('password')) . ')');
-                               destroyMemberSession();
-                       }
-               } else {
-                       // Cookie data is invalid!
-                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data invalid or user not found.');
-                       destroyMemberSession();
-               }
-       } else {
-               // Cookie data is invalid!
-               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data not complete.');
+                       // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
+                       $ret = true;
+               } // END - if
+       } // END - if
+
+       // Is $ret still false?
+       if ($ret === false) {
+               // Yes, so destroy the session
                destroyMemberSession();
-       }
+       } // END - if
 
        // Cache status
-       $GLOBALS['is_member'] = $ret;
+       $GLOBALS[__FUNCTION__] = $ret;
 
        // Return status
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
@@ -540,9 +533,9 @@ function isAdmin () {
        } // END - if
 
        // Do we have cache?
-       if (!isset($GLOBALS['is_admin'][$adminId])) {
+       if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
                // Init it with failed
-               $GLOBALS['is_admin'][$adminId] = false;
+               $GLOBALS[__FUNCTION__][$adminId] = false;
 
                // Search in array for entry
                if (isset($GLOBALS['admin_hash'])) {
@@ -568,12 +561,12 @@ function isAdmin () {
                if (!empty($valPass)) {
                        // Check if password is valid
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
-                       $GLOBALS['is_admin'][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
+                       $GLOBALS[__FUNCTION__][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
                } // END - if
        } // END - if
 
        // Return result of comparision
-       return $GLOBALS['is_admin'][$adminId];
+       return $GLOBALS[__FUNCTION__][$adminId];
 }
 
 // Generates a list of "max receiveable emails per day"
@@ -695,10 +688,10 @@ function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
        // Should we look for affected rows (only update) or found rows?
        if ($updateEntry === true) {
                // Check updated/affected rows
-               $ret = (SQL_AFFECTEDROWS() == 1);
+               $ret = (!SQL_HASZEROAFFECTED());
        } else {
                // Check found rows
-               $ret = (SQL_NUMROWS($result) == 1);
+               $ret = (!SQL_HASZERONUMS($result));
        }
 
        // Free memory
@@ -824,7 +817,7 @@ function getPaymentTitlePrice ($pid, $full=false) {
                if ($full === false) {
                        $ret = $data['mail_title'];
                } else {
-                       $ret = $data['mail_title'] . ' / ' . translateComma($data['price']) . ' {?POINTS?}';
+                       $ret = $data['mail_title'] . ' / {%pipe,translateComma=' . $data['price'] . '%} {?POINTS?}';
                }
        }
 
@@ -988,7 +981,7 @@ function getReferalLevelPercents ($level) {
  * Dynamic referal system, can also send mails!
  *
  * subject     = Subject line, write in lower-case letters and underscore is allowed
- * userid         = Referal id wich should receive...
+ * userid      = Referal id wich should receive...
  * points      = ... xxx points
  * sendNotify  = shall I send the referal an email or not?
  * refid       = inc/modules/guest/what-confirm.php need this
@@ -997,6 +990,9 @@ function getReferalLevelPercents ($level) {
  *               for default value will cause no referal will get points ever!!!)
  */
 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $refid = '0', $add_mode = 'ref') {
+       // By default nothing has been added
+       $added = false;
+
        //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">' . __FUNCTION__ . ' - ENTRY</font> ------------------------<ul><li>');
        // Convert mode to lower-case
        $add_mode = strtolower($add_mode);
@@ -1019,15 +1015,20 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
                //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): Referal level increased. DEPTH='.$GLOBALS['ref_level']);
        }
 
-       // Default is 'normal' points
-       $data = 'points';
-
-       // Which points, locked or normal?
-       if ($locked === true) $data = 'locked_points';
-
        // Check user account
        //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points);
        if (fetchUserData($userid)) {
+               // Determine wether the user has some mails to click before he/she gets the points
+               $locked = ifUserPointsLocked($userid);
+
+               // Default is 'normal' points
+               $data = 'points';
+
+               // Which points, locked or normal?
+               if ($locked === true) {
+                       $data = 'locked_points';
+               } // END - if
+
                // This is the user and his ref
                $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
 
@@ -1054,16 +1055,16 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
                        //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):data='.$data.',ref_points='.$ref_points.',userid='.$userid.',depth='.$GLOBALS['ref_level'].',mode='.$add_mode.' - UPDATE! ('.SQL_AFFECTEDROWS().')');
 
                        // No entry updated?
-                       if (SQL_AFFECTEDROWS() < 1) {
+                       if (SQL_HASZEROAFFECTED()) {
                                // First ref in this level! :-)
                                SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,%s,%s)",
                                        array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
                                //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):data='.$data.',ref_points='.$ref_points.',userid='.$userid.',depth='.$GLOBALS['ref_level'].',mode='.$add_mode.' - INSERTED! ('.SQL_AFFECTEDROWS().')');
                        } // END - if
 
-                       // Determine wether the user has some mails to click before he/she gets the points
-                       $locked = false;
-                       if ((getUserData('ref_payout') > 0) && (!isDirectPaymentAllowed())) $locked = true;
+                       // Check affected rows
+                       $added = SQL_AFFECTEDROWS();
+                       //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):added='.intval($added));
 
                        // Prepare data for the filter
                        $filterData = array(
@@ -1075,10 +1076,15 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
                                'locked'   => $locked,
                                'mode'     => 'add',
                                'sub_mode' => $add_mode,
+                               'added'    => $added
                        );
 
                        // Filter it now
-                       runFilterChain('add_points', $filterData);
+                       $filterData = runFilterChain('add_points', $filterData);
+
+                       // Extract $added
+                       $added = $filterData['added'];
+                       //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):added='.intval($added));
 
                        // Points updated, maybe I shall send him an email?
                        if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
@@ -1094,10 +1100,10 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
 
                                // Send email
                                sendEmail($userid, '{--THANX_REFERAL_ONE_SUBJECT--}', $message);
-                       } elseif (($sendNotify === true) && (getUserData('refid') == '0') && ($locked === false) && ($add_mode == 'direct')) {
+                       } elseif (($sendNotify === true) && (!isValidUserId(getUserData('refid'))) && ($locked === false) && ($add_mode == 'direct')) {
                                // Prepare content
                                $content = array(
-                                       'text'   => '{--REASON_DIRECT_PAYMENT--}',
+                                       'reason' => '{--REASON_DIRECT_PAYMENT--}',
                                        'points' => $ref_points
                                );
 
@@ -1116,12 +1122,13 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
                        if ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
                                // Then let's credit him here...
                                //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',ref='.getUserData('refid').',points='.$points.' - ADVANCE!');
-                               addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'));
+                               $added = ($added && addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid')));
                        } // END - if
                } // END - if
        } // END - if
 
-       //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.' - EXIT</font> ------------------------<br />');
+       //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.': added=' . intval($added) . ' - EXIT</font> ------------------------<br />');
+       return $added;
 }
 
 // Updates the referal counter
@@ -1136,10 +1143,13 @@ function updateReferalCounter ($userid) {
 
        // When no entry was updated then we have to create it here
        //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):updated=' . SQL_AFFECTEDROWS());
-       if (SQL_AFFECTEDROWS() < 1) {
+       if (SQL_HASZEROAFFECTED()) {
                // First count!
                SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
-                       array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
+                       array(
+                               bigintval($userid),
+                               $GLOBALS['cache_array']['ref_level'][$userid]
+                       ), __FUNCTION__, __LINE__);
                //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid);
        } // END - if
 
@@ -1464,18 +1474,16 @@ function generateOptionList ($table, $id, $name, $default = '', $special = '', $
 // Activate exchange
 function FILTER_ACTIVATE_EXCHANGE () {
        // Is the extension 'user' there?
-       if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == '0')) {
+       if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
                // Silently abort here
                return false;
        } // END - if
 
        // Check total amount of users
-       if (getTotalConfirmedUser() >= getConfig('activate_xchange')) {
+       if (getTotalConfirmedUser() >= getActivateXchange()) {
                // Activate System
-               setSqlsArray(array(
-                       "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
-                       "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
-               ));
+               addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1");
+               addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
 
                // Run SQLs
                runFilterChain('run_sqls');
@@ -1599,11 +1607,15 @@ function subtractPoints ($subject, $userid, $points) {
                'subject' => $subject,
                'userid'  => $userid,
                'points'  => $points,
-               'mode'    => 'sub'
+               'mode'    => 'sub',
+               'added'   => (!SQL_HASZEROAFFECTED())
        );
 
        // Insert booking record
-       runFilterChain('sub_points', $filterData);
+       $filterData = runFilterChain('sub_points', $filterData);
+
+       // Return result
+       return $filterData['added'];
 }
 
 // "Getter" for total available receivers
@@ -1671,7 +1683,7 @@ function generateCategoryOptionsList ($mode) {
                } // END - foreach
        } else {
                // No cateogries are defined yet
-               $OUT = '<option class="member_failed">{--MEMBER_NO_CATEGORIES--}</option>';
+               $OUT = '<option class="notice">{--MEMBER_NO_CATEGORIES--}</option>';
        }
 
        // Return HTML code