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