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