Rewrote 'we' word a little, rewrote mail order to use SQL_INSERTID() instead of anoth...
[mailer.git] / inc / libs / sponsor_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 04/23/2005 *
4  * ===================                          Last change: 05/18/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : sponsor_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for the sponsor area                   *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer den Sponsorenbereich             *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 //
44 function handleSponsorRequest ($postData, $update=false, $messageArray = array(), $RET_STATUS=false) {
45         // Init a lot variables
46         $SAVE = true;
47         $UPDATE = false;
48         $skip = false;
49         $ALREADY = false;
50         $ret = 'unused';
51
52         // Skip these entries
53         $SKIPPED = array(
54                 'ok', 'edit', 'terms', 'pay_type'
55         );
56
57         // Save sponsor data
58         $DATA = array(
59                 'keys'   => array(),
60                 'values' => array()
61         );
62
63                 // Check if sponsor already exists
64                 foreach ($postData as $k => $v) {
65                         if (!(array_search($k, $SKIPPED) > -1)) {
66                                 // Check only posted input entries not the submit button
67                                 switch ($k) {
68                                         case 'email':
69                                                 $ALREADY = false;
70                                                 if (!isEmailValid($v)) {
71                                                         // Email address is not valid
72                                                         $SAVE = false;
73                                                 } else {
74                                                         // Add a new sponsor or update his data?
75                                                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE email='%s' LIMIT 1",
76                                                                 array($postData['email']), __FUNCTION__, __LINE__);
77
78                                                         // Is a sponsor alread in the db?
79                                                         if (SQL_NUMROWS($result) == 1) {
80                                                                 // Yes, he is!
81                                                                 if ((getWhat() == 'add_sponsor') || ($update)) {
82                                                                         // Already found
83                                                                         $ALREADY = true;
84                                                                 } else {
85                                                                         // Update his data
86                                                                         $UPDATE = true;
87                                                                 }
88                                                         }
89
90                                                         // Free memory
91                                                         SQL_FREERESULT($result);
92                                                 }
93                                                 break;
94
95                                         case 'pass1':
96                                                 $k = ''; $v = '';
97                                                 break;
98
99                                         case 'pass2':
100                                                 $k = 'password'; $v = md5($v);
101                                                 break;
102
103                                         case 'url':
104                                                 if (!isUrlValid($v)) {
105                                                         // Don't save the URL
106                                                         $SAVE = false;
107                                                 } // END - if
108                                                 break;
109
110                                         default:
111                                                 // Test if there is are time selections
112                                                 convertSelectionsToEpocheTime($postData, $DATA, $k, $skip);
113                                                 break;
114                                 } // END - switch
115
116                                 if ((!empty($k)) && ($skip == false)) {
117                                         // Add data
118                                         array_push($DATA['keys']  , $k);
119                                         array_push($DATA['values'], $v);
120                                 } // END - if
121                         } // END - if
122                 } // END - foreach
123
124                 // Save sponsor?
125                 if ($SAVE === true) {
126                         // Default is no force even when a guest want to abuse this force switch
127                         if ((empty($postData['force'])) || (!isAdmin())) $postData['force'] = '0';
128
129                         // SQL and message string is empty by default
130                         $sql = ''; $message = '';
131
132                         // Update?
133                         if ($UPDATE) {
134                                 // Update his data
135                                 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET ";
136                                 foreach ($DATA['keys'] as $k => $v) {
137                                         $sql .= $v."='%s', ";
138                                 } // END - foreach
139
140                                 // Remove last ", " from SQL string
141                                 $sql = substr($sql, 0, -2)." WHERE `id`=%s LIMIT 1";
142                                 array_push($DATA['values'], bigintval(getRequestElement('id')));
143
144                                 // Generate message
145                                 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_UPDATED--}', 'updated', $messageArray);
146                                 $ret = 'updated';
147                         } elseif (($ALREADY === false) || (($postData['force'] == 1) && (isAdmin()))) {
148                                 // Add new sponsor, first add more data
149                                 array_push($DATA['keys'], 'status');
150                                 if (($update === true) && (isAdmin()) && (getWhat() == 'add_sponsor')) {
151                                         // Only allowed for admin
152                                         array_push($DATA['values'], 'PENDING');
153
154                                         // Add remote IP address as well
155                                         array_push($DATA['keys'], 'remote_addr');
156                                         array_push($DATA['values'], detectRemoteAddr());
157                                 } else {
158                                         // Guest area
159                                         array_push($DATA['values'], 'UNCONFIRMED');
160
161                                         // Generate hash code
162                                         array_push($DATA['keys'], 'hash');
163                                         // @TODO Rewrite this to API function
164                                         array_push($DATA['values'], md5(session_id() . getEncryptSeparator() . $postData['email'] . getEncryptSeparator() . detectRemoteAddr() . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . time()));
165                                         array_push($DATA['keys'], 'remote_addr');
166                                         array_push($DATA['values'], detectRemoteAddr());
167                                 }
168
169                                 // Search the entry
170                                 $key = array_search('force', $DATA['keys']);
171
172                                 // Remove force from both arrays
173                                 unset($DATA['keys'][$key]);
174                                 unset($DATA['values'][$key]);
175
176                                 // Implode all data into strings
177                                 $keyArray   = implode('`,`'  , $DATA['keys']);
178                                 $valueArray = str_repeat("%s', '", count($DATA['values']) - 1);
179
180                                 // Generate string
181                                 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`' . $keyArray . "`) VALUES ('" . $valueArray . "%s')";
182
183                                 // Generate message
184                                 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_ADDED--}', 'added', $messageArray);
185                                 $ret = 'added';
186                         } elseif (($update === true) && (isAdmin())) {
187                                 // Add all data as hidden data
188                                 $OUT = '';
189                                 foreach ($postData as $k => $v) {
190                                         // Do not add 'force' !
191                                         if ($k != 'force') {
192                                                 $OUT .= '<input type="hidden" name="' . secureString($k) . '" value="' . SQL_ESCAPE($v) . '" />';
193                                         } // END - if
194                                 } // END - foreach
195
196                                 // Remember data
197                                 $content['hidden'] = $OUT;
198                                 $content['email']  = $postData['email'];
199
200                                 // Ask for adding a sponsor with same email address
201                                 loadTemplate('admin_add_sponsor_already', false, $content);
202                                 return;
203                         } else {
204                                 // Already added!
205                                 $message = '{%message,SPONSOR_ALREADY_FOUND=' . $postData['email'] . '%}';
206                                 $ret = 'already';
207                         }
208
209                         if (!empty($sql)) {
210                                 // Run SQL command
211                                 $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
212                         } // END - if
213                 } else {
214                         // Error detected
215                         $message = getMessageFromIndexedArray('{--SPONSOR_DATA_NOT_SAVED--}', 'failed', $messageArray);
216                         displayMessage($message);
217                 }
218
219         // Always return the status
220         return $ret;
221 }
222
223 // Translate the account status
224 function translateSponsorStatus ($status) {
225         // Construct constant name
226         $constantName = sprintf("ACCOUNT_STATUS_%s", $status);
227
228         // Is the constant there?
229         if (isMessageIdValid($constantName)) {
230                 // Then use it
231                 $ret = getMessage($constantName);
232         } else {
233                 // Not found
234                 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
235                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
236                 $ret = '{%message,ACCOUNT_STATUS_UNKNOWN=' . $status . '%}';
237         }
238
239         // Return status
240         return $ret;
241 }
242
243 // Search for an email address in the database
244 function isSponsorRegisteredWithEmail ($email) {
245         // Is there already the provided email address in database?
246         $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
247
248         // Return result
249         return $ret;
250 }
251
252 // Wether the current user is a sponsor
253 function isSponsor () {
254         // Failed is default
255         $ret = false;
256
257         // Determine it
258         $ret = (
259                 (isSessionVariableSet('sponsor_id')) &&
260                 (isSessionVariableSet('sponsor_pass')) &&
261                 (fetchSponsorData(getSession('sponsor_id')))
262         );
263
264         // Return status
265         return $ret;
266 }
267
268 //
269 function addSponsorMenu ($current) {
270         $OUT = '';
271         $WHERE = " AND `active`='Y'";
272         if (isAdmin()) $WHERE = '';
273
274         // Load main menu entries
275         $result_main = SQL_QUERY("SELECT
276         `action` AS `main_action`,
277         `title` AS `main_title`
278 FROM
279         `{?_MYSQL_PREFIX?}_sponsor_menu`
280 WHERE
281         (`what`='' OR `what` IS NULL)
282         " . $WHERE . "
283 ORDER BY
284         `sort` ASC", __FUNCTION__, __LINE__);
285         if (!SQL_HASZERONUMS($result_main)) {
286                 // Load every menu and it's sub menus
287                 while ($content = SQL_FETCHARRAY($result_main)) {
288                         // Load sub menus
289                         $result_sub = SQL_QUERY_ESC("SELECT
290         `what` AS `sub_what`,
291         `title` AS `sub_title`
292 FROM
293         `{?_MYSQL_PREFIX?}_sponsor_menu`
294 WHERE
295         `action`='%s' AND
296         `what` != '' AND
297         `what` IS NOT NULL
298         " . $WHERE . "
299 ORDER BY
300         `sort` ASC",
301                         array($content['main_action']), __FUNCTION__, __LINE__);
302                         if (!SQL_HASZERONUMS($result_sub)) {
303                                 // Load sub menus
304                                 $SUB = '';
305                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
306                                         // Check if current selected menu is matching the loaded one
307                                         if ($current == $content2['sub_what']) $content2['sub_title'] = '<strong>' . $content2['sub_title'] . '</strong>';
308
309                                         // Load row template
310                                         $SUB .= loadTemplate('sponsor_what', true, $content2);
311                                 } // END - while
312
313                                 // Prepare data for the main template
314                                 $content['menu'] = $SUB;
315
316                                 // Load menu template
317                                 $OUT .= loadTemplate('sponsor_action', true, $content);
318                         } else {
319                                 // No sub menus active
320                                 $OUT .= displayMessage('{--SPONSOR_NO_SUB_MENUS_ACTIVE--}', true);
321                         }
322
323                         // Free memory
324                         SQL_FREERESULT($result_sub);
325                 } // END - while
326         } else {
327                 // No main menus active
328                 $OUT .= displayMessage('{--SPONSOR_NO_MAIN_MENUS_ACTIVE--}', true);
329         }
330
331         // Free memory
332         SQL_FREERESULT($result_main);
333
334         // Return content
335         return $OUT;
336 }
337
338 //
339 function addSponsorContent ($what) {
340         // Init sponsor content
341         $GLOBALS['sponsor_output'] = '';
342
343         // Generate IFN (Include FileName)
344         $INC = sprintf("inc/modules/sponsor/%s.php", $what);
345         if (isIncludeReadable($INC)) {
346                 // Every sponsor action will output nothing directly. It will be written into $GLOBALS['sponsor_output']!
347                 loadIncludeOnce($INC);
348         } else {
349                 // File not found
350                 $GLOBALS['sponsor_output'] .= displayMessage('{%message,SPONSOR_CONTENT_404=' . $what . '%}', true);
351         }
352
353         // Return content
354         return $GLOBALS['sponsor_output'];
355 }
356
357 //
358 function updateSponsorLogin () {
359         // Failed by default
360         $login = false;
361
362         // Is sponsor?
363         if (isSponsor()) {
364                 // Update last online timestamp
365                 SQL_QUERY_ESC("UPDATE
366         `{?_MYSQL_PREFIX?}_sponsor_data`
367 SET
368         `last_online`=NOW()
369 WHERE
370         `id`=%s AND
371         `password`='%s'
372 LIMIT 1",
373                         array(
374                                 bigintval(getSession('sponsor_id')),
375                                 getSession('sponsor_pass')
376                         ), __FUNCTION__, __LINE__);
377
378                 // This update went fine?
379                 $login = (!SQL_HASZEROAFFECTED());
380         } // END - if
381
382         // Return status
383         return $login;
384 }
385
386 // Saves sponsor's data
387 function saveSponsorData ($postData, $content) {
388         $EMAIL = false;
389
390         // Unsecure data which we don't want
391         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
392                         'points_amount', 'points_used', 'refid', 'hash', 'last_payment', 'last_currency',
393                         'pass_old', 'ok', 'pass1', 'pass2');
394
395         // Set default message ("not saved")
396         $message = '{--SPONSOR_ACCOUNT_DATA_NOT_SAVED--}';
397
398         // Check for submitted passwords
399         if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
400                 // Are both passwords the same?
401                 if ($postData['pass1'] == $postData['pass2']) {
402                         // Okay, then set password and remove pass1 and pass2
403                         $postData['password'] = md5($postData['pass1']);
404                 } // END - if
405         } // END - if
406
407         // Remove all (maybe spoofed) unsafe data from array
408         foreach ($UNSAFE as $remove) {
409                 unset($postData[$remove]);
410         } // END - foreach
411
412         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
413         // secure the data
414         $DATA = array();
415
416         // Prepare SQL string
417         $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
418         foreach ($postData as $key => $value) {
419                 // Mmmmm, too less security here???
420                 $sql   .= " `" . secureString($key) . "`='%s',";
421
422                 // We will secure this later inside the SQL_QUERY_ESC() function
423                 array_push($DATA, secureString($value));
424         } // END - foreach
425
426         // Check if email has changed
427         if ((!empty($content['email'])) && (!empty($postData['email']))) {
428                 if ($content['email'] != $postData['email']) {
429                         // Change email address
430                         $EMAIL = true;
431
432                         // Okay, has changed then add status with UNCONFIRMED and new hash code
433                         $sql .= " `status`='EMAIL',`hash`='%s',";
434
435                         // Generate hash code
436                         // @TODO Rewrite this to API function
437                         $HASH = md5(session_id() . getEncryptSeparator() . $postData['email'] . getEncryptSeparator() . detectRemoteAddr() . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . time());
438                         array_push($DATA, $HASH);
439                 } // END - if
440         } // END - if
441         // Remove last commata
442         $sql = substr($sql, 0, -1);
443
444         // Add last_change
445         $sql .= ',`last_change`=NOW()';
446
447         // Add SQL tail data
448         $sql .= " WHERE `id`=%s AND `password`='%s' LIMIT 1";
449         array_push($DATA, bigintval(getSession('sponsor_id')), getSession('sponsor_pass'));
450
451         // Saving data was completed... ufff...
452         switch (getWhat()) {
453                 case 'account': // Change account data
454                         if ($EMAIL === true) {
455                                 $message = '{--SPONSOR_ACCOUNT_EMAIL_CHANGED--}';
456                                 $templ   = 'admin_sponsor_change_email';
457                                 $subject    = '{--ADMIN_SPONSOR_ACC_EMAIL_SUBJECT--}';
458                         } else {
459                                 $message = '{--SPONSOR_ACCOUNT_DATA_SAVED--}';
460                                 $templ   = 'admin_sponsor_change_data';
461                                 $subject    = '{--ADMIN_SPONSOR_ACC_DATA_SUBJECT--}';
462                         }
463                         break;
464
465                 case 'settings': // Change settings
466                         // Set message template and subject for admin
467                         $message = '{--SPONSOR_SETTINGS_SAVED--}';
468                         $templ   = 'admin_sponsor_settings';
469                         $subject    = '{--ADMIN_SPONSOR_SETTINGS_SUBJECT--}';
470                         break;
471
472                 default: // Unknown sponsor what value!
473                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
474                         $message = '{--SPONSOR_UNKNOWN_WHAT--}';
475                         $templ   = '';
476                         $subject    = '';
477                         break;
478         } // END - switch
479
480         // Has an entry updated?
481         if (!SQL_HASZEROAFFECTED()) {
482                 // Template and subject are set?
483                 if (!empty($templ) && !empty($subject)) {
484                         // Run SQL command and check for success
485                         $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
486
487                         // Add all data to content
488                         $content['new_data'] = $postData;
489
490                         // Send email to admins
491                         sendAdminNotification($subject, $templ, $content);
492
493                         // Shall we send mail to the sponsor's new email address?
494                         if ($content['receive_warnings'] == 'Y') {
495                                 /*
496                                  * Okay send email with confirmation link to new address and with no confirmation link
497                                  * to the old address.
498                                  */
499
500                                 // First to old address
501                                 switch (getWhat()) {
502                                         case 'account': // Change account data
503                                                 $email_msg = loadEmailTemplate('sponsor_change_data', $content);
504                                                 sendEmail($content['email'], '{--SPONSOR_ACC_DATA_SUBJECT--}', $email_msg);
505
506                                                 if ($EMAIL === true) {
507                                                         // Add hash code to content array
508                                                         $content['hash'] = $HASH;
509
510                                                         // Second mail goes to the new address
511                                                         $email_msg = loadEmailTemplate('sponsor_change_email', $content);
512                                                         sendEmail($content['email'], '{--SPONSOR_ACC_EMAIL_SUBJECT--}', $email_msg);
513                                                 } // END - if
514                                                 break;
515
516                                         case 'settings': // Change settings
517                                                 // Send email
518                                                 $email_msg = loadEmailTemplate('sponsor_settings', $content);
519                                                 sendEmail($content['email'], '{--SPONSOR_SETTINGS_SUBJECT--}', $email_msg);
520                                                 break;
521                                 } // END - switch
522                         } // END - if
523                 } // END - if
524         } // END - if
525
526         // Return final message
527         return $message;
528 }
529
530 // Create email link to sponsor's account
531 function generateSponsorEmailLink ($email, $mod = 'admin') {
532         // Show contact link only if sponsor is confirmed by default
533         $locked = " AND `status`='CONFIRMED'";
534
535         // But admins shall always see it
536         if (isAdmin()) $locked = '';
537
538         $result = SQL_QUERY_ESC("SELECT
539         `id`
540 FROM
541         `{?_MYSQL_PREFIX?}_sponsor_data`
542 WHERE
543         '%s' REGEXP `email`
544         " . $locked . "
545 LIMIT 1",
546                 array($email), __FUNCTION__, __LINE__);
547         if (SQL_NUMROWS($result) == 1) {
548                 // Load sponsor_id
549                 list($sponsor_id) = SQL_FETCHROW($result);
550
551                 // Rewrite email address to contact link
552                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=sponsor_contct&amp;sponsor_id=' . bigintval($sponsor_id) . '%}';
553         } // END - if
554
555         // Free memory
556         SQL_FREERESULT($result);
557
558         // Return rewritten (?) email address
559         return $email;
560 }
561
562 // Processes a sponsor request and handles it
563 function doProcessSponsorFormRequest ($messageArray = array()) {
564         // Default message
565         $message = '';
566
567         // Handle the request
568         $status = handleSponsorRequest(postRequestArray(), true, $messageArray, true);
569
570         // Check the status of the registration process
571         switch ($status) {
572                 case 'added': // Sponsor successfully added with account status = UNCONFIRMED!
573                         // Check for his id number
574                         $result = SQL_QUERY_ESC("SELECT `id`, `hash` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE '%s' REGEXP `email` LIMIT 1",
575                                 array(postRequestElement('email')), __FUNCTION__, __LINE__);
576                         if (SQL_NUMROWS($result) == 1) {
577                                 // id found so let's load it for the confirmation email
578                                 list($id, $hash) = SQL_FETCHROW($result);
579
580                                 // Prepare data for the email template
581                                 $content['id']        = $id;
582                                 $content['hash']      = $hash;
583                                 $content['email']     = postRequestElement('email');
584                                 $content['surname']   = postRequestElement('surname');
585                                 $content['family']    = postRequestElement('family');
586                                 $content['timestamp'] = generateDateTime(time(), 0);
587                                 $content['password']  = postRequestElement('pass1');
588
589                                 // Generate email and send it to the new sponsor
590                                 $message = loadEmailTemplate('sponsor_confirm', $content, $id);
591                                 sendEmail(postRequestElement('email'), '{--SPONSOR_PLEASE_CONFIRM_SUBJECT--}', $message);
592
593                                 // Send mail to admin
594                                 sendAdminNotification('{--ADMIN_NEW_SPONSOR--}', 'admin_sponsor_reg', $content);
595
596                                 // Output message: DONE
597                                 $message = $messageArray['added'];
598                         } else {
599                                 // Sponsor account not found???
600                                 $message = '{%message,SPONSOR_EMAIL_404=' . postRequestElement('email') . '%}';
601                         }
602
603                         // Free memory
604                         SQL_FREERESULT($result);
605                         break;
606
607                 default:
608                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
609                         if (!isAdmin()) {
610                                 // Message for testing admin
611                                 $message = '{%message,ADMIN_SPONSOR_UNKNOWN_STATUS=' . $status . '%}';
612                         } else {
613                                 // Message for the guest
614                                 $message = '{%message,SPONSOR_UNKNOWN_STATUS=' . $status . '%}';
615                         }
616                         break;
617         } // END - switch
618
619         // Return message
620         return $message;
621 }
622
623 // Expression call-back function for fetching sponsor data
624 function doExpressionSponsor ($data) {
625         // Use current sponsor_id by default
626         $functionName = 'getSponsorId()';
627
628         // Sponsor-related data, so is there a sponsor_id?
629         if (!empty($data['matches'][4][$data['key']])) {
630                 // Is there a sponsor_id or $sponsor_id?
631                 if ($data['matches'][4][$data['key']] == '$userid') {
632                         // Use dynamic call
633                         $functionName = "getFetchedSponsorData('id', \$userid, '" . $data['callback'] . "')";
634                 } elseif (!empty($data['matches'][4][$data['key']])) {
635                         // Sponsor data found
636                         $functionName = "getFetchedSponsorData('id', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
637                 }
638         } elseif ((!empty($data['callback'])) && (isSponsorDataValid())) {
639                 // "Call-back" alias column for current logged in sponsor's data
640                 $functionName = "getSponsorData('" . $data['callback'] . "')";
641         }
642
643         // Is there another function to run (e.g. translations)
644         if (!empty($data['extra_func'])) {
645                 // Surround the original function call with it
646                 $functionName = $data['extra_func'] . '(' . $functionName . ')';
647         } // END - if
648
649         // Generate replacer
650         $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
651
652         // Now replace the code
653         $code = replaceExpressionCode($data, $replacer);
654
655         // Return replaced code
656         return $code;
657 }
658
659 // Fetch sponsor data for given sponsor id
660 function fetchSponsorData ($sponsor_id, $column = 'id') {
661         // If we should look for sponsor_id secure&set it here
662         if ($column == 'id') {
663                 // Secure sponsor_id
664                 $sponsor_id = bigintval($sponsor_id);
665
666                 // Set it here
667                 setCurrentSponsorId($sponsor_id);
668
669                 // Don't look for invalid sponsor_ids...
670                 if (!isValidUserId($sponsor_id)) {
671                         // Invalid, so abort here
672                         reportBug(__FUNCTION__, __LINE__, 'Sponsor id ' . $sponsor_id . ' is invalid.');
673                 } elseif (isSponsorDataValid()) {
674                         // Use cache, so it is fine
675                         return true;
676                 }
677         } elseif (isSponsorDataValid()) {
678                 // Use cache, so it is fine
679                 return true;
680         }
681
682         // By default none was found
683         $found = false;
684
685         // Extra statements
686         $ADD = '';
687
688         // Query for the sponsor
689         $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `%s`='%s' LIMIT 1",
690                 array($column, $sponsor_id), __FUNCTION__, __LINE__);
691
692         // Is there a record?
693         if (SQL_NUMROWS($result) == 1) {
694                 // Load data from cookies
695                 $data = SQL_FETCHARRAY($result);
696
697                 // Set the sponsor_id for later use
698                 setCurrentSponsorId($data['id']);
699                 $GLOBALS['sponsor_data'][getCurrentSponsorId()] = $data;
700
701                 // Rewrite 'last_failure' if found
702                 if (isset($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'])) {
703                         // Backup the raw one and zero it
704                         $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'] = $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'];
705                         $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = NULL;
706
707                         // Is it not zero?
708                         if (!is_null($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'])) {
709                                 // Seperate data/time
710                                 $array = explode(' ', $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw']);
711
712                                 // Seperate data and time again
713                                 $array['date'] = explode('-', $array[0]);
714                                 $array['time'] = explode(':', $array[1]);
715
716                                 // Now pass it to mktime()
717                                 $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = mktime(
718                                         $array['time'][0],
719                                         $array['time'][1],
720                                         $array['time'][2],
721                                         $array['date'][1],
722                                         $array['date'][2],
723                                         $array['date'][0]
724                                 );
725                         } // END - if
726                 } // END - if
727
728                 // Found, but valid?
729                 $found = isSponsorDataValid();
730         } // END - if
731
732         // Free memory
733         SQL_FREERESULT($result);
734
735         // Return result
736         return $found;
737 }
738
739 // Wrapper for fetchSponsorData() and getSponsorData() calls
740 function getFetchedSponsorData ($keyColumn, $sponsor_id, $valueColumn) {
741         // Zero ids are not valid
742         if ($sponsor_id == 0) {
743                 // Abort here
744                 reportBug(__FUNCTION__, __LINE__, 'Zero sponsor_id provided');
745         } // END - if
746
747         // Is it cached?
748         if (!isset($GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn])) {
749                 // Default is empty
750                 $data = '';
751
752                 // Can we fetch the sponsor data?
753                 if ((isValidSponsorId($sponsor_id)) && (fetchSponsorData($sponsor_id, $keyColumn))) {
754                         // Now get the data back
755                         $data = getSponsorData($valueColumn);
756                 } // END - if
757
758                 // Cache it
759                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cached:id=' . $sponsor_id . ',keyColumn=' . $keyColumn . ',valueColumn=' . $valueColumn . ',data=' . $data);
760                 $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn] = $data;
761         } // END - if
762
763         // Return it
764         return $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn];
765 }
766
767 // Checks if the sponsor data is valid, this may indicate that the sponsor has logged
768 // in, but you should use isMember() if you want to find that out.
769 function isSponsorDataValid () {
770         // Sponsor id should not be zero so abort here
771         if (!isCurrentSponsorIdSet()) return false;
772
773         // Is it cached?
774         if (!isset($GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()])) {
775                 // Determine it
776                 $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()] = ((isset($GLOBALS['sponsor_data'][getCurrentSponsorId()])) && (count($GLOBALS['sponsor_data'][getCurrentSponsorId()]) > 1));
777         } // END - if
778
779         // Return the result
780         return $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()];
781 }
782
783 // Setter for current sponsor_id
784 function setCurrentSponsorId ($sponsor_id) {
785         // Set sponsor_id
786         $GLOBALS['current_sponsor_id'] = bigintval($sponsor_id);
787
788         // Unset it to re-determine the actual state
789         unset($GLOBALS['is_sponsor_data_valid'][$sponsor_id]);
790 }
791
792 // Getter for current sponsor_id
793 function getCurrentSponsorId () {
794         // Sponsorid must be set before it can be used
795         if (!isCurrentSponsorIdSet()) {
796                 // Not set
797                 reportBug(__FUNCTION__, __LINE__, 'Sponsor id is not set.');
798         } // END - if
799
800         // Return the sponsor_id
801         return $GLOBALS['current_sponsor_id'];
802 }
803
804 // Checks if current sponsor_id is set
805 function isCurrentSponsorIdSet () {
806         return ((isset($GLOBALS['current_sponsor_id'])) && (isValidSponsorId($GLOBALS['current_sponsor_id'])));
807 }
808
809 // Is given sponsor_id valid?
810 function isValidSponsorId ($sponsor_id) {
811         // Is there cache?
812         if (!isset($GLOBALS[__FUNCTION__][$sponsor_id])) {
813                 // Check it out
814                 $GLOBALS[__FUNCTION__][$sponsor_id] = ((!is_null($sponsor_id)) && (!empty($sponsor_id)) && ($sponsor_id > 0));
815         } // END - if
816
817         // Return cache
818         return $GLOBALS[__FUNCTION__][$sponsor_id];
819 }
820
821 // Getter for sponsor data
822 function getSponsorData ($column) {
823         // Sponsor id should not be zero
824         if (!isValidUserId(getCurrentSponsorId())) {
825                 reportBug(__FUNCTION__, __LINE__, 'Sponsor id is zero.');
826         } // END - if
827
828         // Return the value
829         return $GLOBALS['sponsor_data'][getCurrentSponsorId()][$column];
830 }
831
832 // Determines the country of the given sponsor id
833 function determineSponsorCountry ($sponsor_id) {
834         // Then handle it over
835         $country = getSponsorData('country');
836
837         // Return it
838         return $country;
839 }
840
841 // Destroy sponsor session
842 function destroySponsorSession () {
843         // Remove all user data from session
844         return (
845                 (setSession('sponsor_id', '')) &&
846                 (setSession('sponsor_pass', '')) &&
847                 (
848                         ((isExtensionActive('theme')) && (setMailerTheme(''))) ||
849                         (!isExtensionActive('theme'))
850                 )
851         );
852 }
853
854 // Getter for sponsor_min_points
855 function getSponsorMinPoints () {
856         // Is there cache?
857         if (!isset($GLOBALS[__FUNCTION__])) {
858                 // Determine it
859                 $GLOBALS[__FUNCTION__] = getConfig('sponsor_min_points');
860         } // END - if
861
862         // Return cache
863         return $GLOBALS[__FUNCTION__];
864 }
865
866 // Getter for sponsor_ref_points
867 function getSponsorRefPoints () {
868         // Is there cache?
869         if (!isset($GLOBALS[__FUNCTION__])) {
870                 // Determine it
871                 $GLOBALS[__FUNCTION__] = getConfig('sponsor_ref_points');
872         } // END - if
873
874         // Return cache
875         return $GLOBALS[__FUNCTION__];
876 }
877
878 // [EOF]
879 ?>