Rewrote 'we' word a little, rewrote mail order to use SQL_INSERTID() instead of anoth...
[mailer.git] / inc / libs / sponsor_functions.php
index 4f2fd8fa348a89e073e73ef414dbc2d7a20035e9..3e5909476677b783bf26173550e8b80e698556aa 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /************************************************************************
- * MXChange v0.2.1                                    Start: 04/23/2005 *
- * ===============                              Last change: 05/18/2008 *
+ * Mailer v0.2.1-FINAL                                Start: 04/23/2005 *
+ * ===================                          Last change: 05/18/2008 *
  *                                                                      *
  * -------------------------------------------------------------------- *
  * File              : sponsor_functions.php                            *
  * -------------------------------------------------------------------- *
  * Kurzbeschreibung  : Funktionen fuer den Sponsorenbereich             *
  * -------------------------------------------------------------------- *
- *                                                                      *
+ * $Revision::                                                        $ *
+ * $Date::                                                            $ *
+ * $Tag:: 0.2.1-FINAL                                                 $ *
+ * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
- * Copyright (c) 2003 - 2008 by Roland Haeder                           *
- * For more information visit: http://www.mxchange.org                  *
+ * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
+ * For more information visit: http://mxchange.org                      *
  *                                                                      *
- * This program is free software. You can redistribute it and/or modify *
+ * This program is free software; you can redistribute it and/or modify *
  * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 2 of the License.       *
+ * the Free Software Foundation; either version 2 of the License, or    *
+ * (at your option) any later version.                                  *
  *                                                                      *
  * This program is distributed in the hope that it will be useful,      *
  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
 
 // Some security stuff...
 if (!defined('__SECURITY')) {
-       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
-       require($INC);
-}
+       die();
+} // END - if
 
 //
-function SPONSOR_HANDLE_SPONSOR (&$POST, $NO_UPDATE=false, $MSGs=array(), $RET_STATUS=false) {
+function handleSponsorRequest ($postData, $update=false, $messageArray = array(), $RET_STATUS=false) {
        // Init a lot variables
        $SAVE = true;
        $UPDATE = false;
        $skip = false;
        $ALREADY = false;
-       $ret = "unused";
+       $ret = 'unused';
 
        // Skip these entries
        $SKIPPED = array(
@@ -56,276 +60,272 @@ function SPONSOR_HANDLE_SPONSOR (&$POST, $NO_UPDATE=false, $MSGs=array(), $RET_S
                'values' => array()
        );
 
-       // Check if sponsor already exists
-       foreach ($POST as $k => $v) {
-               if (!(array_search($k, $SKIPPED) > -1)) {
-                       // Check only posted input entries not the submit button
-                       switch ($k)
-                       {
-                       case "email":
-                               $ALREADY = false;
-                               if (!VALIDATE_EMAIL($v)) {
-                                       // Email address is not valid
-                                       $SAVE = false;
-                               } else {
-                                       // Do we want to add a new sponsor or update his data?
-                                       $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_sponsor_data` WHERE email='%s' LIMIT 1",
-                                               array($POST['email']), __FUNCTION__, __LINE__);
-
-                                       // Is a sponsor alread in the db?
-                                       if (SQL_NUMROWS($result) == 1) {
-                                               // Yes, he is!
-                                               if (($GLOBALS['what'] == "add_sponsor") || ($NO_UPDATE)) {
-                                                       // Already found!
-                                                       $ALREADY = true;
+               // Check if sponsor already exists
+               foreach ($postData as $k => $v) {
+                       if (!(array_search($k, $SKIPPED) > -1)) {
+                               // Check only posted input entries not the submit button
+                               switch ($k) {
+                                       case 'email':
+                                               $ALREADY = false;
+                                               if (!isEmailValid($v)) {
+                                                       // Email address is not valid
+                                                       $SAVE = false;
                                                } else {
-                                                       // Update his data
-                                                       $UPDATE = true;
+                                                       // Add a new sponsor or update his data?
+                                                       $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE email='%s' LIMIT 1",
+                                                               array($postData['email']), __FUNCTION__, __LINE__);
+
+                                                       // Is a sponsor alread in the db?
+                                                       if (SQL_NUMROWS($result) == 1) {
+                                                               // Yes, he is!
+                                                               if ((getWhat() == 'add_sponsor') || ($update)) {
+                                                                       // Already found
+                                                                       $ALREADY = true;
+                                                               } else {
+                                                                       // Update his data
+                                                                       $UPDATE = true;
+                                                               }
+                                                       }
+
+                                                       // Free memory
+                                                       SQL_FREERESULT($result);
                                                }
-                                       }
-
-                                       // Free memory
-                                       SQL_FREERESULT($result);
+                                               break;
+
+                                       case 'pass1':
+                                               $k = ''; $v = '';
+                                               break;
+
+                                       case 'pass2':
+                                               $k = 'password'; $v = md5($v);
+                                               break;
+
+                                       case 'url':
+                                               if (!isUrlValid($v)) {
+                                                       // Don't save the URL
+                                                       $SAVE = false;
+                                               } // END - if
+                                               break;
+
+                                       default:
+                                               // Test if there is are time selections
+                                               convertSelectionsToEpocheTime($postData, $DATA, $k, $skip);
+                                               break;
+                               } // END - switch
+
+                               if ((!empty($k)) && ($skip == false)) {
+                                       // Add data
+                                       array_push($DATA['keys']  , $k);
+                                       array_push($DATA['values'], $v);
+                               } // END - if
+                       } // END - if
+               } // END - foreach
+
+               // Save sponsor?
+               if ($SAVE === true) {
+                       // Default is no force even when a guest want to abuse this force switch
+                       if ((empty($postData['force'])) || (!isAdmin())) $postData['force'] = '0';
+
+                       // SQL and message string is empty by default
+                       $sql = ''; $message = '';
+
+                       // Update?
+                       if ($UPDATE) {
+                               // Update his data
+                               $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET ";
+                               foreach ($DATA['keys'] as $k => $v) {
+                                       $sql .= $v."='%s', ";
+                               } // END - foreach
+
+                               // Remove last ", " from SQL string
+                               $sql = substr($sql, 0, -2)." WHERE `id`=%s LIMIT 1";
+                               array_push($DATA['values'], bigintval(getRequestElement('id')));
+
+                               // Generate message
+                               $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_UPDATED--}', 'updated', $messageArray);
+                               $ret = 'updated';
+                       } elseif (($ALREADY === false) || (($postData['force'] == 1) && (isAdmin()))) {
+                               // Add new sponsor, first add more data
+                               array_push($DATA['keys'], 'status');
+                               if (($update === true) && (isAdmin()) && (getWhat() == 'add_sponsor')) {
+                                       // Only allowed for admin
+                                       array_push($DATA['values'], 'PENDING');
+
+                                       // Add remote IP address as well
+                                       array_push($DATA['keys'], 'remote_addr');
+                                       array_push($DATA['values'], detectRemoteAddr());
+                               } else {
+                                       // Guest area
+                                       array_push($DATA['values'], 'UNCONFIRMED');
+
+                                       // Generate hash code
+                                       array_push($DATA['keys'], 'hash');
+                                       // @TODO Rewrite this to API function
+                                       array_push($DATA['values'], md5(session_id() . getEncryptSeparator() . $postData['email'] . getEncryptSeparator() . detectRemoteAddr() . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . time()));
+                                       array_push($DATA['keys'], 'remote_addr');
+                                       array_push($DATA['values'], detectRemoteAddr());
                                }
-                               break;
-
-                       case "pass1":
-                               $k = ""; $v = "";
-                               break;
-
-                       case "pass2":
-                               $k = "password"; $v = md5($v);
-                               break;
-
-                       case "url":
-                               if (!VALIDATE_URL($v)) $SAVE = false;
-                               break;
-
-                       default:
-                               // Test if there is are time selections
-                               CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $k, $skip);
-                               break;
-                       }
-
-                       if ((!empty($k)) && ($skip == false)) {
-                               // Add data
-                               $DATA['keys'][] = $k; $DATA['values'][] = $v;
-                       }
-               }
-       }
-
-       // Save sponsor?
-       if ($SAVE) {
-               // Default is no force even when a guest want to abuse this force switch
-               if ((empty($POST['force'])) || (!IS_ADMIN())) $POST['force'] = 0;
-
-               // SQL and message string is empty by default
-               $sql = ""; $MSG = "";
-
-               // Update?
-               if ($UPDATE) {
-                       // Update his data
-                       $sql = "UPDATE `{!_MYSQL_PREFIX!}_sponsor_data` SET ";
-                       foreach ($DATA['keys'] as $k => $v) {
-                               $sql .= $v."='%s', ";
-                       }
 
-                       // Remove last ", " from SQL string
-                       $sql = substr($sql, 0, -2)." WHERE id='%s' LIMIT 1";
-                       $DATA['values'][] = bigintval(REQUEST_GET('id'));
-
-                       // Generate message
-                       $MSG = SPONSOR_GET_MESSAGE(ADMIN_SPONSOR_UPDATED, "updated", $MSGs);
-                       $ret = "updated";
-               } elseif ((!$ALREADY) || (($POST['force'] == "1") && (IS_ADMIN()))) {
-                       // Add new sponsor, first add more data
-                       $DATA['keys'][] = "sponsor_created"; $DATA['values'][] = time();
-                       $DATA['keys'][] = "status";
-                       if ((!$NO_UPDATE) && (IS_ADMIN()) && ($GLOBALS['what'] == "add_sponsor")) {
-                               // Only allowed for admin
-                               $DATA['values'][] = "PENDING";
+                               // Search the entry
+                               $key = array_search('force', $DATA['keys']);
+
+                               // Remove force from both arrays
+                               unset($DATA['keys'][$key]);
+                               unset($DATA['values'][$key]);
+
+                               // Implode all data into strings
+                               $keyArray   = implode('`,`'  , $DATA['keys']);
+                               $valueArray = str_repeat("%s', '", count($DATA['values']) - 1);
+
+                               // Generate string
+                               $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`' . $keyArray . "`) VALUES ('" . $valueArray . "%s')";
+
+                               // Generate message
+                               $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_ADDED--}', 'added', $messageArray);
+                               $ret = 'added';
+                       } elseif (($update === true) && (isAdmin())) {
+                               // Add all data as hidden data
+                               $OUT = '';
+                               foreach ($postData as $k => $v) {
+                                       // Do not add 'force' !
+                                       if ($k != 'force') {
+                                               $OUT .= '<input type="hidden" name="' . secureString($k) . '" value="' . SQL_ESCAPE($v) . '" />';
+                                       } // END - if
+                               } // END - foreach
+
+                               // Remember data
+                               $content['hidden'] = $OUT;
+                               $content['email']  = $postData['email'];
+
+                               // Ask for adding a sponsor with same email address
+                               loadTemplate('admin_add_sponsor_already', false, $content);
+                               return;
                        } else {
-                               // Guest area
-                               $DATA['values'][] = "UNCONFIRMED";
-
-                               // Generate hash code
-                               $DATA['keys'][] = "hash";
-                               $DATA['values'][] = md5(session_id().":".$POST['email'].":".GET_REMOTE_ADDR().":".GET_USER_AGENT().":".time());
-                               $DATA['keys'][] = "remote_addr";
-                               $DATA['values'][] = GET_REMOTE_ADDR();
+                               // Already added!
+                               $message = '{%message,SPONSOR_ALREADY_FOUND=' . $postData['email'] . '%}';
+                               $ret = 'already';
                        }
 
-                       // Implode all data into strings
-                       $KEYS   = implode(", "  , $DATA['keys']);
-                       $VALUES = str_repeat("%s', '", count($DATA['values']) - 1);
-
-                       // Generate string
-                       $sql = "INSERT INTO `{!_MYSQL_PREFIX!}_sponsor_data` (".$KEYS.") VALUES ('".$VALUES."%s')";
-
-                       // Generate message
-                       $MSG = SPONSOR_GET_MESSAGE(getMessage('ADMIN_SPONSOR_ADDED'), "added", $MSGs);
-                       $ret = "added";
-               } elseif ((!$NO_UPDATE) && (IS_ADMIN())) {
-                       // Add all data as hidden data
-                       $OUT = "";
-                       foreach ($POST as $k => $v) {
-                               // Do not add 'force' !
-                               if ($k != "force") {
-                                       $OUT .= "<input type=\"hidden\" name=\"".$k."\" value=\"".stripslashes($v)."\" />\n";
-                               }
-                       }
-                       define('__HIDDEN_DATA', $OUT);
-                       define('__EMAIL'      , $POST['email']);
-
-                       // Ask for adding a sponsor with same email address
-                       LOAD_TEMPLATE("admin_add_sponsor_already");
-                       return;
+                       if (!empty($sql)) {
+                               // Run SQL command
+                               $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
+                       } // END - if
                } else {
-                       // Already added!
-                       $MSG = sprintf(getMessage('SPONSOR_ALREADY_FOUND', $POST['email']));
-                       $ret = "already";
-               }
-
-               if (!empty($sql)) {
-                       // Run SQL command
-                       $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
+                       // Error detected
+                       $message = getMessageFromIndexedArray('{--SPONSOR_DATA_NOT_SAVED--}', 'failed', $messageArray);
+                       displayMessage($message);
                }
 
-               // Output message
-               if ((!$NO_UPDATE) && (IS_ADMIN())) {
-                       LOAD_TEMPLATE("admin_settings_saved", false, $MSG);
-               }
-       } else {
-               // Error found!
-               $MSG = SPONSOR_GET_MESSAGE(getMessage('SPONSOR_DATA_NOT_SAVED'), "failed", $MSGs);
-               LOAD_TEMPLATE("admin_settings_saved", false, $MSG);
-       }
-
-       // Shall we return the status?
-       if ($RET_STATUS) return $ret;
+       // Always return the status
+       return $ret;
 }
-//
-function SPONSOR_TRANSLATE_STATUS ($status) {
+
+// Translate the account status
+function translateSponsorStatus ($status) {
        // Construct constant name
-       $constantName = sprintf("ACCOUNT_%s", $status);
+       $constantName = sprintf("ACCOUNT_STATUS_%s", $status);
 
        // Is the constant there?
-       if (defined($constantName)) {
+       if (isMessageIdValid($constantName)) {
                // Then use it
-               $ret = constant($constantName);
+               $ret = getMessage($constantName);
        } else {
-               // Not found!
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
-               $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
+               // Not found
+               //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
+               logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
+               $ret = '{%message,ACCOUNT_STATUS_UNKNOWN=' . $status . '%}';
        }
-       return $ret;
-}
-// Search for an email address in the database
-function SPONSOR_FOUND_EMAIL_DB ($email) {
-       // Do we already have the provided email address in our DB?
-       $ret = (GET_TOTAL_DATA($email, "sponsor_data", "id", "email", true) == 1);
 
-       // Return result
+       // Return status
        return $ret;
 }
-//
-function SPONSOR_GET_MESSAGE ($msg, $pos, $array) {
-       // Check if the requested message was found in array
-       if (isset($array[$pos])) {
-               // ... if yes then use it!
-               $ret = $array[$pos];
-       } else {
-               // ... else use default message
-               $ret = $msg;
-       }
+
+// Search for an email address in the database
+function isSponsorRegisteredWithEmail ($email) {
+       // Is there already the provided email address in database?
+       $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
 
        // Return result
        return $ret;
 }
 
-//
-function IS_SPONSOR () {
-       // Failed...
+// Wether the current user is a sponsor
+function isSponsor () {
+       // Failed is default
        $ret = false;
-       if ((isSessionVariableSet('sponsorid')) && (isSessionVariableSet('sponsorpass'))) {
-               // Check cookies against database records...
-               $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_sponsor_data`
-WHERE id='%s' AND password='%s' AND `status`='CONFIRMED' LIMIT 1",
-                       array(bigintval(get_session('sponsorid')), get_session('sponsorpass')), __FUNCTION__, __LINE__);
-               if (SQL_NUMROWS($result) == 1) {
-                       // All is fine
-                       $ret = true;
-               }
 
-               // Free memory
-               SQL_FREERESULT($result);
-       }
+       // Determine it
+       $ret = (
+               (isSessionVariableSet('sponsor_id')) &&
+               (isSessionVariableSet('sponsor_pass')) &&
+               (fetchSponsorData(getSession('sponsor_id')))
+       );
 
        // Return status
        return $ret;
 }
+
 //
-function GENERATE_SPONSOR_MENU($current)
-{
-       $OUT = "";
-       $WHERE = " AND active='Y'";
-       if (IS_ADMIN()) $WHERE = "";
+function addSponsorMenu ($current) {
+       $OUT = '';
+       $WHERE = " AND `active`='Y'";
+       if (isAdmin()) $WHERE = '';
 
        // Load main menu entries
-       $result_main = SQL_QUERY("SELECT action, title FROM `{!_MYSQL_PREFIX!}_sponsor_menu`
-WHERE (what='' OR `what` IS NULL) ".$WHERE."
-ORDER BY `sort`", __FUNCTION__, __LINE__);
-       if (SQL_NUMROWS($result_main) > 0)
-       {
+       $result_main = SQL_QUERY("SELECT
+       `action` AS `main_action`,
+       `title` AS `main_title`
+FROM
+       `{?_MYSQL_PREFIX?}_sponsor_menu`
+WHERE
+       (`what`='' OR `what` IS NULL)
+       " . $WHERE . "
+ORDER BY
+       `sort` ASC", __FUNCTION__, __LINE__);
+       if (!SQL_HASZERONUMS($result_main)) {
                // Load every menu and it's sub menus
-               while (list($action, $title_main) = SQL_FETCHROW($result_main))
-               {
+               while ($content = SQL_FETCHARRAY($result_main)) {
                        // Load sub menus
-                       $result_sub = SQL_QUERY_ESC("SELECT what, title FROM `{!_MYSQL_PREFIX!}_sponsor_menu`
-WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$WHERE."
-ORDER BY `sort`", array($action), __FUNCTION__, __LINE__);
-                       if (SQL_NUMROWS($result_sub) > 0)
-                       {
+                       $result_sub = SQL_QUERY_ESC("SELECT
+       `what` AS `sub_what`,
+       `title` AS `sub_title`
+FROM
+       `{?_MYSQL_PREFIX?}_sponsor_menu`
+WHERE
+       `action`='%s' AND
+       `what` != '' AND
+       `what` IS NOT NULL
+       " . $WHERE . "
+ORDER BY
+       `sort` ASC",
+                       array($content['main_action']), __FUNCTION__, __LINE__);
+                       if (!SQL_HASZERONUMS($result_sub)) {
                                // Load sub menus
-                               $SUB = "";
-                               while (list($what, $title_sub) = SQL_FETCHROW($result_sub))
-                               {
+                               $SUB = '';
+                               while ($content2 = SQL_FETCHARRAY($result_sub)) {
                                        // Check if current selected menu is matching the loaded one
-                                       if ($current == $what) $title_sub = "<strong>".$title_sub."</strong>";
-
-                                       // Prepare data for the sub template
-                                       $content = array(
-                                               'what'  => $what,
-                                               'title' => $title_sub
-                                       );
+                                       if ($current == $content2['sub_what']) $content2['sub_title'] = '<strong>' . $content2['sub_title'] . '</strong>';
 
                                        // Load row template
-                                       $SUB .= LOAD_TEMPLATE("sponsor_what", true, $content);
-                               }
+                                       $SUB .= loadTemplate('sponsor_what', true, $content2);
+                               } // END - while
 
                                // Prepare data for the main template
-                               $content = array(
-                                       'title' => $title_main,
-                                       'menu'  => $SUB
-                               );
+                               $content['menu'] = $SUB;
 
                                // Load menu template
-                               $OUT .= LOAD_TEMPLATE("sponsor_action", true, $content);
-                       }
-                        else
-                       {
+                               $OUT .= loadTemplate('sponsor_action', true, $content);
+                       } else {
                                // No sub menus active
-                               $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_NO_SUB_MENUS_ACTIVE);
+                               $OUT .= displayMessage('{--SPONSOR_NO_SUB_MENUS_ACTIVE--}', true);
                        }
 
                        // Free memory
                        SQL_FREERESULT($result_sub);
-               }
-       }
-        else
-       {
+               } // END - while
+       } else {
                // No main menus active
-               $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_NO_MAIN_MENUS_ACTIVE);
+               $OUT .= displayMessage('{--SPONSOR_NO_MAIN_MENUS_ACTIVE--}', true);
        }
 
        // Free memory
@@ -334,194 +334,546 @@ ORDER BY `sort`", array($action), __FUNCTION__, __LINE__);
        // Return content
        return $OUT;
 }
+
 //
-function GENERATE_SPONSOR_CONTENT($what)
-{
-       $OUT = "";
+function addSponsorContent ($what) {
+       // Init sponsor content
+       $GLOBALS['sponsor_output'] = '';
+
+       // Generate IFN (Include FileName)
        $INC = sprintf("inc/modules/sponsor/%s.php", $what);
-       if (INCLUDE_READABLE($INC)) {
-               // Every sponsor action will output nothing directly. It will be written into $OUT!
-               LOAD_INC_ONCE($INC);
+       if (isIncludeReadable($INC)) {
+               // Every sponsor action will output nothing directly. It will be written into $GLOBALS['sponsor_output']!
+               loadIncludeOnce($INC);
        } else {
-               // File not found!
-               $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_CONTENT_404_1.$what.SPONSOR_CONTENT_404_2);
+               // File not found
+               $GLOBALS['sponsor_output'] .= displayMessage('{%message,SPONSOR_CONTENT_404=' . $what . '%}', true);
        }
 
        // Return content
-       return $OUT;
+       return $GLOBALS['sponsor_output'];
 }
+
 //
-function UPDATE_SPONSOR_LOGIN () {
+function updateSponsorLogin () {
        // Failed by default
        $login = false;
 
        // Is sponsor?
-       if (IS_SPONSOR()) {
+       if (isSponsor()) {
                // Update last online timestamp
-               SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_sponsor_data`
-SET last_online=UNIX_TIMESTAMP()
-WHERE id='%s' AND password='%s' LIMIT 1",
-                       array(bigintval(get_session('sponsorid')), get_session('sponsorpass')), __FUNCTION__, __LINE__);
+               SQL_QUERY_ESC("UPDATE
+       `{?_MYSQL_PREFIX?}_sponsor_data`
+SET
+       `last_online`=NOW()
+WHERE
+       `id`=%s AND
+       `password`='%s'
+LIMIT 1",
+                       array(
+                               bigintval(getSession('sponsor_id')),
+                               getSession('sponsor_pass')
+                       ), __FUNCTION__, __LINE__);
 
                // This update went fine?
-               $login = (SQL_AFFECTEDROWS() == 1);
-       }
+               $login = (!SQL_HASZEROAFFECTED());
+       } // END - if
 
        // Return status
        return $login;
 }
-//
-function SPONSOR_SAVE_DATA ($POST, $content) {
+
+// Saves sponsor's data
+function saveSponsorData ($postData, $content) {
        $EMAIL = false;
 
        // Unsecure data which we don't want
        $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
-                       'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
-                       'ok', 'pass1', 'pass2');
+                       'points_amount', 'points_used', 'refid', 'hash', 'last_payment', 'last_currency',
+                       'pass_old', 'ok', 'pass1', 'pass2');
 
        // Set default message ("not saved")
-       $MSG = SPONSOR_ACCOUNT_DATA_NOT_SAVED;
+       $message = '{--SPONSOR_ACCOUNT_DATA_NOT_SAVED--}';
 
        // Check for submitted passwords
-       if ((!empty($POST['pass1'])) && (!empty($POST['pass2']))) {
+       if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
                // Are both passwords the same?
-               if ($POST['pass1'] == $POST['pass2']) {
+               if ($postData['pass1'] == $postData['pass2']) {
                        // Okay, then set password and remove pass1 and pass2
-                       $POST['password'] = md5($POST['pass1']);
-               }
-       }
+                       $postData['password'] = md5($postData['pass1']);
+               } // END - if
+       } // END - if
 
        // Remove all (maybe spoofed) unsafe data from array
        foreach ($UNSAFE as $remove) {
-               unset($POST[$remove]);
-       }
+               unset($postData[$remove]);
+       } // END - foreach
 
        // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
        // secure the data
        $DATA = array();
 
        // Prepare SQL string
-       $sql = "UPDATE `{!_MYSQL_PREFIX!}_sponsor_data` SET";
-       foreach ($POST as $key => $value) {
+       $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
+       foreach ($postData as $key => $value) {
                // Mmmmm, too less security here???
-               $sql   .= " ".strip_tags($key)."='%s',";
+               $sql   .= " `" . secureString($key) . "`='%s',";
 
                // We will secure this later inside the SQL_QUERY_ESC() function
-               $DATA[] = strip_tags($value);
-
-               // Compile {SLASH} and so on for the email templates
-               $POST[$key] = COMPILE_CODE($value);
-       }
+               array_push($DATA, secureString($value));
+       } // END - foreach
 
        // Check if email has changed
-       if ((!empty($content['email'])) && (!empty($POST['email']))) {
-               if ($content['email'] != $POST['email']) {
+       if ((!empty($content['email'])) && (!empty($postData['email']))) {
+               if ($content['email'] != $postData['email']) {
                        // Change email address
                        $EMAIL = true;
 
                        // Okay, has changed then add status with UNCONFIRMED and new hash code
-                       $sql .= " `status`='EMAIL', hash='%s',";
+                       $sql .= " `status`='EMAIL',`hash`='%s',";
 
                        // Generate hash code
-                       $HASH = md5(session_id().":".$POST['email'].":".GET_REMOTE_ADDR().":".GET_USER_AGENT().":".time());
-                       $DATA[] = $HASH;
-               }
-       }
-
+                       // @TODO Rewrite this to API function
+                       $HASH = md5(session_id() . getEncryptSeparator() . $postData['email'] . getEncryptSeparator() . detectRemoteAddr() . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . time());
+                       array_push($DATA, $HASH);
+               } // END - if
+       } // END - if
        // Remove last commata
        $sql = substr($sql, 0, -1);
 
+       // Add last_change
+       $sql .= ',`last_change`=NOW()';
+
        // Add SQL tail data
-       $sql .= " WHERE id='%s' AND password='%s' LIMIT 1";
-       $DATA[] = bigintval(get_session('sponsorid'));
-       $DATA[] = get_session('sponsorpass');
+       $sql .= " WHERE `id`=%s AND `password`='%s' LIMIT 1";
+       array_push($DATA, bigintval(getSession('sponsor_id')), getSession('sponsor_pass'));
 
        // Saving data was completed... ufff...
-       switch ($GLOBALS['what'])
-       {
-       case "account": // Change account data
-               if ($EMAIL === true) {
-                       $MSG   = getMessage('SPONSOR_ACCOUNT_EMAIL_CHANGED');
-                       $templ = "admin_sponsor_change_email";
-                       $subj  = getMessage('ADMIN_SPONSOR_ACC_EMAIL_SUBJ');
-               } else {
-                       $MSG   = getMessage('SPONSOR_ACCOUNT_DATA_SAVED');
-                       $templ = "admin_sponsor_change_data";
-                       $subj  = getMessage('ADMIN_SPONSOR_ACC_DATA_SUBJ');
-               }
-               break;
-
-       case "settings": // Change settings
-               // Translate some data
-               $content['receive']  = TRANSLATE_YESNO($content['receive_warnings']);
-               $content['interval'] = CREATE_FANCY_TIME($content['warning_interval']);
-
-               // Set message template and subject for admin
-               $MSG   = getMessage('SPONSOR_SETTINGS_SAVED');
-               $templ = "admin_sponsor_settings";
-               $subj  = getMessage('ADMIN_SPONSOR_SETTINGS_SUBJ');
-               break;
-
-       default: // Unknown sponsor what value!
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", $GLOBALS['what']));
-               $MSG = sprintf(getMessage('SPONSOR_UNKNOWN_WHAT'), $GLOBALS['what']);
-               $templ = ""; $subj = "";
-               break;
-       }
-
-       if (SQL_AFFECTEDROWS() == 1) {
-               if (!empty($templ) && !empty($subj)) {
+       switch (getWhat()) {
+               case 'account': // Change account data
+                       if ($EMAIL === true) {
+                               $message = '{--SPONSOR_ACCOUNT_EMAIL_CHANGED--}';
+                               $templ   = 'admin_sponsor_change_email';
+                               $subject    = '{--ADMIN_SPONSOR_ACC_EMAIL_SUBJECT--}';
+                       } else {
+                               $message = '{--SPONSOR_ACCOUNT_DATA_SAVED--}';
+                               $templ   = 'admin_sponsor_change_data';
+                               $subject    = '{--ADMIN_SPONSOR_ACC_DATA_SUBJECT--}';
+                       }
+                       break;
+
+               case 'settings': // Change settings
+                       // Set message template and subject for admin
+                       $message = '{--SPONSOR_SETTINGS_SAVED--}';
+                       $templ   = 'admin_sponsor_settings';
+                       $subject    = '{--ADMIN_SPONSOR_SETTINGS_SUBJECT--}';
+                       break;
+
+               default: // Unknown sponsor what value!
+                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
+                       $message = '{--SPONSOR_UNKNOWN_WHAT--}';
+                       $templ   = '';
+                       $subject    = '';
+                       break;
+       } // END - switch
+
+       // Has an entry updated?
+       if (!SQL_HASZEROAFFECTED()) {
+               // Template and subject are set?
+               if (!empty($templ) && !empty($subject)) {
                        // Run SQL command and check for success
                        $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
 
                        // Add all data to content
-                       global $DATA;
-                       $DATA = $POST;
-
-                       // Change some data
-                       if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
-                       if (isset($DATA['gender']))    $DATA['gender']    = TRANSLATE_GENDER($DATA['gender']);
-                       if (isset($content['receive_warnings'])) $DATA['receive']     = TRANSLATE_YESNO($POST['receive_warnings']);
-                       if (isset($content['warning_interval'])) $DATA['interval']    = CREATE_FANCY_TIME($POST['warning_interval']);
+                       $content['new_data'] = $postData;
 
                        // Send email to admins
-                       SEND_ADMIN_NOTIFICATION($subj, $templ, $content);
+                       sendAdminNotification($subject, $templ, $content);
 
                        // Shall we send mail to the sponsor's new email address?
-                       if ($content['receive_warnings'] == "Y") {
-                               // Okay send email with confirmation link to new address and with no confirmation link
-                               // to the old address
+                       if ($content['receive_warnings'] == 'Y') {
+                               /*
+                                * Okay send email with confirmation link to new address and with no confirmation link
+                                * to the old address.
+                                */
 
                                // First to old address
-                               switch ($GLOBALS['what'])
-                               {
-                               case "account": // Change account data
-                                       $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_data", $content);
-                                       SEND_EMAIL($content['email'], getMessage('SPONSOR_ACC_DATA_SUBJ'), $email_msg);
-
-                                       if ($EMAIL === true) {
-                                               // Add hash code to content array
-                                               $content['hash'] = $HASH;
-
-                                               // Second mail goes to the new address
-                                               $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_email", $content);
-                                               SEND_EMAIL($content['email'], getMessage('SPONSOR_ACC_EMAIL_SUBJ'), $email_msg);
-                                       }
-                                       break;
-
-                               case "settings": // Change settings
-                                       // Send email
-                                       $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_settings", $content);
-                                       SEND_EMAIL($content['email'], getMessage('SPONSOR_SETTINGS_SUBJ'), $email_msg);
-                                       break;
-                               }
+                               switch (getWhat()) {
+                                       case 'account': // Change account data
+                                               $email_msg = loadEmailTemplate('sponsor_change_data', $content);
+                                               sendEmail($content['email'], '{--SPONSOR_ACC_DATA_SUBJECT--}', $email_msg);
+
+                                               if ($EMAIL === true) {
+                                                       // Add hash code to content array
+                                                       $content['hash'] = $HASH;
+
+                                                       // Second mail goes to the new address
+                                                       $email_msg = loadEmailTemplate('sponsor_change_email', $content);
+                                                       sendEmail($content['email'], '{--SPONSOR_ACC_EMAIL_SUBJECT--}', $email_msg);
+                                               } // END - if
+                                               break;
+
+                                       case 'settings': // Change settings
+                                               // Send email
+                                               $email_msg = loadEmailTemplate('sponsor_settings', $content);
+                                               sendEmail($content['email'], '{--SPONSOR_SETTINGS_SUBJECT--}', $email_msg);
+                                               break;
+                               } // END - switch
+                       } // END - if
+               } // END - if
+       } // END - if
+
+       // Return final message
+       return $message;
+}
+
+// Create email link to sponsor's account
+function generateSponsorEmailLink ($email, $mod = 'admin') {
+       // Show contact link only if sponsor is confirmed by default
+       $locked = " AND `status`='CONFIRMED'";
+
+       // But admins shall always see it
+       if (isAdmin()) $locked = '';
+
+       $result = SQL_QUERY_ESC("SELECT
+       `id`
+FROM
+       `{?_MYSQL_PREFIX?}_sponsor_data`
+WHERE
+       '%s' REGEXP `email`
+       " . $locked . "
+LIMIT 1",
+               array($email), __FUNCTION__, __LINE__);
+       if (SQL_NUMROWS($result) == 1) {
+               // Load sponsor_id
+               list($sponsor_id) = SQL_FETCHROW($result);
+
+               // Rewrite email address to contact link
+               $email = '{%url=modules.php?module=' . $mod . '&amp;what=sponsor_contct&amp;sponsor_id=' . bigintval($sponsor_id) . '%}';
+       } // END - if
+
+       // Free memory
+       SQL_FREERESULT($result);
+
+       // Return rewritten (?) email address
+       return $email;
+}
+
+// Processes a sponsor request and handles it
+function doProcessSponsorFormRequest ($messageArray = array()) {
+       // Default message
+       $message = '';
+
+       // Handle the request
+       $status = handleSponsorRequest(postRequestArray(), true, $messageArray, true);
+
+       // Check the status of the registration process
+       switch ($status) {
+               case 'added': // Sponsor successfully added with account status = UNCONFIRMED!
+                       // Check for his id number
+                       $result = SQL_QUERY_ESC("SELECT `id`, `hash` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE '%s' REGEXP `email` LIMIT 1",
+                               array(postRequestElement('email')), __FUNCTION__, __LINE__);
+                       if (SQL_NUMROWS($result) == 1) {
+                               // id found so let's load it for the confirmation email
+                               list($id, $hash) = SQL_FETCHROW($result);
+
+                               // Prepare data for the email template
+                               $content['id']        = $id;
+                               $content['hash']      = $hash;
+                               $content['email']     = postRequestElement('email');
+                               $content['surname']   = postRequestElement('surname');
+                               $content['family']    = postRequestElement('family');
+                               $content['timestamp'] = generateDateTime(time(), 0);
+                               $content['password']  = postRequestElement('pass1');
+
+                               // Generate email and send it to the new sponsor
+                               $message = loadEmailTemplate('sponsor_confirm', $content, $id);
+                               sendEmail(postRequestElement('email'), '{--SPONSOR_PLEASE_CONFIRM_SUBJECT--}', $message);
+
+                               // Send mail to admin
+                               sendAdminNotification('{--ADMIN_NEW_SPONSOR--}', 'admin_sponsor_reg', $content);
+
+                               // Output message: DONE
+                               $message = $messageArray['added'];
+                       } else {
+                               // Sponsor account not found???
+                               $message = '{%message,SPONSOR_EMAIL_404=' . postRequestElement('email') . '%}';
+                       }
+
+                       // Free memory
+                       SQL_FREERESULT($result);
+                       break;
+
+               default:
+                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
+                       if (!isAdmin()) {
+                               // Message for testing admin
+                               $message = '{%message,ADMIN_SPONSOR_UNKNOWN_STATUS=' . $status . '%}';
+                       } else {
+                               // Message for the guest
+                               $message = '{%message,SPONSOR_UNKNOWN_STATUS=' . $status . '%}';
                        }
+                       break;
+       } // END - switch
+
+       // Return message
+       return $message;
+}
+
+// Expression call-back function for fetching sponsor data
+function doExpressionSponsor ($data) {
+       // Use current sponsor_id by default
+       $functionName = 'getSponsorId()';
+
+       // Sponsor-related data, so is there a sponsor_id?
+       if (!empty($data['matches'][4][$data['key']])) {
+               // Is there a sponsor_id or $sponsor_id?
+               if ($data['matches'][4][$data['key']] == '$userid') {
+                       // Use dynamic call
+                       $functionName = "getFetchedSponsorData('id', \$userid, '" . $data['callback'] . "')";
+               } elseif (!empty($data['matches'][4][$data['key']])) {
+                       // Sponsor data found
+                       $functionName = "getFetchedSponsorData('id', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
                }
+       } elseif ((!empty($data['callback'])) && (isSponsorDataValid())) {
+               // "Call-back" alias column for current logged in sponsor's data
+               $functionName = "getSponsorData('" . $data['callback'] . "')";
        }
 
-       // Return final message
-       return $MSG;
+       // Is there another function to run (e.g. translations)
+       if (!empty($data['extra_func'])) {
+               // Surround the original function call with it
+               $functionName = $data['extra_func'] . '(' . $functionName . ')';
+       } // END - if
+
+       // Generate replacer
+       $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
+
+       // Now replace the code
+       $code = replaceExpressionCode($data, $replacer);
+
+       // Return replaced code
+       return $code;
 }
 
-//
+// Fetch sponsor data for given sponsor id
+function fetchSponsorData ($sponsor_id, $column = 'id') {
+       // If we should look for sponsor_id secure&set it here
+       if ($column == 'id') {
+               // Secure sponsor_id
+               $sponsor_id = bigintval($sponsor_id);
+
+               // Set it here
+               setCurrentSponsorId($sponsor_id);
+
+               // Don't look for invalid sponsor_ids...
+               if (!isValidUserId($sponsor_id)) {
+                       // Invalid, so abort here
+                       reportBug(__FUNCTION__, __LINE__, 'Sponsor id ' . $sponsor_id . ' is invalid.');
+               } elseif (isSponsorDataValid()) {
+                       // Use cache, so it is fine
+                       return true;
+               }
+       } elseif (isSponsorDataValid()) {
+               // Use cache, so it is fine
+               return true;
+       }
+
+       // By default none was found
+       $found = false;
+
+       // Extra statements
+       $ADD = '';
+
+       // Query for the sponsor
+       $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `%s`='%s' LIMIT 1",
+               array($column, $sponsor_id), __FUNCTION__, __LINE__);
+
+       // Is there a record?
+       if (SQL_NUMROWS($result) == 1) {
+               // Load data from cookies
+               $data = SQL_FETCHARRAY($result);
+
+               // Set the sponsor_id for later use
+               setCurrentSponsorId($data['id']);
+               $GLOBALS['sponsor_data'][getCurrentSponsorId()] = $data;
+
+               // Rewrite 'last_failure' if found
+               if (isset($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'])) {
+                       // Backup the raw one and zero it
+                       $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'] = $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'];
+                       $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = NULL;
+
+                       // Is it not zero?
+                       if (!is_null($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'])) {
+                               // Seperate data/time
+                               $array = explode(' ', $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw']);
+
+                               // Seperate data and time again
+                               $array['date'] = explode('-', $array[0]);
+                               $array['time'] = explode(':', $array[1]);
+
+                               // Now pass it to mktime()
+                               $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = mktime(
+                                       $array['time'][0],
+                                       $array['time'][1],
+                                       $array['time'][2],
+                                       $array['date'][1],
+                                       $array['date'][2],
+                                       $array['date'][0]
+                               );
+                       } // END - if
+               } // END - if
+
+               // Found, but valid?
+               $found = isSponsorDataValid();
+       } // END - if
+
+       // Free memory
+       SQL_FREERESULT($result);
+
+       // Return result
+       return $found;
+}
+
+// Wrapper for fetchSponsorData() and getSponsorData() calls
+function getFetchedSponsorData ($keyColumn, $sponsor_id, $valueColumn) {
+       // Zero ids are not valid
+       if ($sponsor_id == 0) {
+               // Abort here
+               reportBug(__FUNCTION__, __LINE__, 'Zero sponsor_id provided');
+       } // END - if
+
+       // Is it cached?
+       if (!isset($GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn])) {
+               // Default is empty
+               $data = '';
+
+               // Can we fetch the sponsor data?
+               if ((isValidSponsorId($sponsor_id)) && (fetchSponsorData($sponsor_id, $keyColumn))) {
+                       // Now get the data back
+                       $data = getSponsorData($valueColumn);
+               } // END - if
+
+               // Cache it
+               /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cached:id=' . $sponsor_id . ',keyColumn=' . $keyColumn . ',valueColumn=' . $valueColumn . ',data=' . $data);
+               $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn] = $data;
+       } // END - if
+
+       // Return it
+       return $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn];
+}
+
+// Checks if the sponsor data is valid, this may indicate that the sponsor has logged
+// in, but you should use isMember() if you want to find that out.
+function isSponsorDataValid () {
+       // Sponsor id should not be zero so abort here
+       if (!isCurrentSponsorIdSet()) return false;
+
+       // Is it cached?
+       if (!isset($GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()])) {
+               // Determine it
+               $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()] = ((isset($GLOBALS['sponsor_data'][getCurrentSponsorId()])) && (count($GLOBALS['sponsor_data'][getCurrentSponsorId()]) > 1));
+       } // END - if
+
+       // Return the result
+       return $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()];
+}
+
+// Setter for current sponsor_id
+function setCurrentSponsorId ($sponsor_id) {
+       // Set sponsor_id
+       $GLOBALS['current_sponsor_id'] = bigintval($sponsor_id);
+
+       // Unset it to re-determine the actual state
+       unset($GLOBALS['is_sponsor_data_valid'][$sponsor_id]);
+}
+
+// Getter for current sponsor_id
+function getCurrentSponsorId () {
+       // Sponsorid must be set before it can be used
+       if (!isCurrentSponsorIdSet()) {
+               // Not set
+               reportBug(__FUNCTION__, __LINE__, 'Sponsor id is not set.');
+       } // END - if
+
+       // Return the sponsor_id
+       return $GLOBALS['current_sponsor_id'];
+}
+
+// Checks if current sponsor_id is set
+function isCurrentSponsorIdSet () {
+       return ((isset($GLOBALS['current_sponsor_id'])) && (isValidSponsorId($GLOBALS['current_sponsor_id'])));
+}
+
+// Is given sponsor_id valid?
+function isValidSponsorId ($sponsor_id) {
+       // Is there cache?
+       if (!isset($GLOBALS[__FUNCTION__][$sponsor_id])) {
+               // Check it out
+               $GLOBALS[__FUNCTION__][$sponsor_id] = ((!is_null($sponsor_id)) && (!empty($sponsor_id)) && ($sponsor_id > 0));
+       } // END - if
+
+       // Return cache
+       return $GLOBALS[__FUNCTION__][$sponsor_id];
+}
+
+// Getter for sponsor data
+function getSponsorData ($column) {
+       // Sponsor id should not be zero
+       if (!isValidUserId(getCurrentSponsorId())) {
+               reportBug(__FUNCTION__, __LINE__, 'Sponsor id is zero.');
+       } // END - if
+
+       // Return the value
+       return $GLOBALS['sponsor_data'][getCurrentSponsorId()][$column];
+}
+
+// Determines the country of the given sponsor id
+function determineSponsorCountry ($sponsor_id) {
+       // Then handle it over
+       $country = getSponsorData('country');
+
+       // Return it
+       return $country;
+}
+
+// Destroy sponsor session
+function destroySponsorSession () {
+       // Remove all user data from session
+       return (
+               (setSession('sponsor_id', '')) &&
+               (setSession('sponsor_pass', '')) &&
+               (
+                       ((isExtensionActive('theme')) && (setMailerTheme(''))) ||
+                       (!isExtensionActive('theme'))
+               )
+       );
+}
+
+// Getter for sponsor_min_points
+function getSponsorMinPoints () {
+       // Is there cache?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // Determine it
+               $GLOBALS[__FUNCTION__] = getConfig('sponsor_min_points');
+       } // END - if
+
+       // Return cache
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Getter for sponsor_ref_points
+function getSponsorRefPoints () {
+       // Is there cache?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // Determine it
+               $GLOBALS[__FUNCTION__] = getConfig('sponsor_ref_points');
+       } // END - if
+
+       // Return cache
+       return $GLOBALS[__FUNCTION__];
+}
+
+// [EOF]
 ?>