]> git.mxchange.org Git - mailer.git/blob - inc/libs/sponsor_functions.php
Configuration of advertisement networks prepared, CSS cleaned up, HTML rewritten:
[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                                         case 'email':
71                                                 $ALREADY = false;
72                                                 if (!isEmailValid($v)) {
73                                                         // Email address is not valid
74                                                         $SAVE = false;
75                                                 } else {
76                                                         // Do we want to add a new sponsor or update his data?
77                                                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE email='%s' LIMIT 1",
78                                                         array($postData['email']), __FUNCTION__, __LINE__);
79
80                                                         // Is a sponsor alread in the db?
81                                                         if (SQL_NUMROWS($result) == 1) {
82                                                                 // Yes, he is!
83                                                                 if ((getWhat() == 'add_sponsor') || ($update)) {
84                                                                         // Already found!
85                                                                         $ALREADY = true;
86                                                                 } else {
87                                                                         // Update his data
88                                                                         $UPDATE = true;
89                                                                 }
90                                                         }
91
92                                                         // Free memory
93                                                         SQL_FREERESULT($result);
94                                                 }
95                                                 break;
96
97                                         case 'pass1':
98                                                 $k = ''; $v = '';
99                                                 break;
100
101                                         case 'pass2':
102                                                 $k = 'password'; $v = md5($v);
103                                                 break;
104
105                                         case 'url':
106                                                 if (!isUrlValid($v)) $SAVE = false;
107                                                 break;
108
109                                         default:
110                                                 // Test if there is are time selections
111                                                 convertSelectionsToTimestamp($postData, $DATA, $k, $skip);
112                                                 break;
113                                 } // END - switch
114
115                                 if ((!empty($k)) && ($skip == false)) {
116                                         // Add data
117                                         $DATA['keys'][] = $k; $DATA['values'][] = $v;
118                                 } // END - if
119                         } // END - if
120                 } // END - foreach
121
122                 // Save sponsor?
123                 if ($SAVE === true) {
124                         // Default is no force even when a guest want to abuse this force switch
125                         if ((empty($postData['force'])) || (!isAdmin())) $postData['force'] = '0';
126
127                         // SQL and message string is empty by default
128                         $sql = ''; $message = '';
129
130                         // Update?
131                         if ($UPDATE) {
132                                 // Update his data
133                                 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET ";
134                                 foreach ($DATA['keys'] as $k => $v) {
135                                         $sql .= $v."='%s', ";
136                                 } // END - foreach
137
138                                 // Remove last ", " from SQL string
139                                 $sql = substr($sql, 0, -2)." WHERE `id`=%s LIMIT 1";
140                                 $DATA['values'][] = bigintval(getRequestParameter('id'));
141
142                                 // Generate message
143                                 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_UPDATED--}', 'updated', $messageArray);
144                                 $ret = 'updated';
145                         } elseif (($ALREADY === false) || (($postData['force'] == 1) && (isAdmin()))) {
146                                 // Add new sponsor, first add more data
147                                 $DATA['keys'][] = 'status';
148                                 if (($update === true) && (isAdmin()) && (getWhat() == 'add_sponsor')) {
149                                         // Only allowed for admin
150                                         $DATA['values'][] = 'PENDING';
151
152                                         // Add remote IP address as well
153                                         $DATA['keys'][] = 'remote_addr';
154                                         $DATA['values'][] = detectRemoteAddr();
155                                 } else {
156                                         // Guest area
157                                         $DATA['values'][] = 'UNCONFIRMED';
158
159                                         // Generate hash code
160                                         $DATA['keys'][] = 'hash';
161                                         // @TODO Rewrite this to API function
162                                         $DATA['values'][] = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
163                                         $DATA['keys'][] = 'remote_addr';
164                                         $DATA['values'][] = detectRemoteAddr();
165                                 }
166
167                                 // Search the entry
168                                 $key = array_search('force', $DATA['keys']);
169
170                                 // Remove force from both arrays
171                                 unset($DATA['keys'][$key]);
172                                 unset($DATA['values'][$key]);
173
174                                 // Implode all data into strings
175                                 $keyArray   = implode('`, `'  , $DATA['keys']);
176                                 $valueArray = str_repeat("%s', '", count($DATA['values']) - 1);
177
178                                 // Generate string
179                                 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`' . $keyArray . "`) VALUES ('" . $valueArray . "%s')";
180
181                                 // Generate message
182                                 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_ADDED--}', 'added', $messageArray);
183                                 $ret = 'added';
184                         } elseif (($update === true) && (isAdmin())) {
185                                 // Add all data as hidden data
186                                 $OUT = '';
187                                 foreach ($postData as $k => $v) {
188                                         // Do not add 'force' !
189                                         if ($k != 'force') {
190                                                 $OUT .= '<input type="hidden" name="' . secureString($k) . '" value="' . SQL_ESCAPE($v) . '" />';
191                                         } // END - if
192                                 } // END - foreach
193
194                                 // Remember data
195                                 $content['hidden'] = $OUT;
196                                 $content['email']  = $postData['email'];
197
198                                 // Ask for adding a sponsor with same email address
199                                 loadTemplate('admin_add_sponsor_already', false, $content);
200                                 return;
201                         } else {
202                                 // Already added!
203                                 $message = getMaskedMessage('SPONSOR_ALREADY_FOUND', $postData['email']);
204                                 $ret = 'already';
205                         }
206
207                         if (!empty($sql)) {
208                                 // Run SQL command
209                                 $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
210                         } // END - if
211                 } else {
212                         // Error found!
213                         $message = getMessageFromIndexedArray('{--SPONSOR_DATA_NOT_SAVED--}', 'failed', $messageArray);
214                         loadTemplate('admin_settings_saved', false, $message);
215                 }
216
217         // Always return the status
218         return $ret;
219 }
220
221 //
222 function sponsorTranslateUserStatus ($status) {
223         // Construct constant name
224         $constantName = sprintf("ACCOUNT_STATUS_%s", $status);
225
226         // Is the constant there?
227         if (isMessageIdValid($constantName)) {
228                 // Then use it
229                 $ret = getMessage($constantName);
230         } else {
231                 // Not found!
232                 /* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
233                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
234                 $ret = getMaskedMessage('ACCOUNT_STATUS_UNKNOWN_STATUS', $status);
235         }
236
237         // Return status
238         return $ret;
239 }
240
241 // Search for an email address in the database
242 function isSponsorRegisteredWithEmail ($email) {
243         // Do we already have the provided email address in our DB?
244         $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
245
246         // Return result
247         return $ret;
248 }
249
250 // Wether the current user is a sponsor
251 function isSponsor () {
252         // Failed is default
253         $ret = false;
254
255         // Determine it
256         $ret = (
257                 (isSessionVariableSet('sponsor_id')) &&
258                 (isSessionVariableSet('sponsor_pass')) &&
259                 (fetchSponsorData(getSession('sponsor_id')))
260         );
261
262         // Return status
263         return $ret;
264 }
265
266 //
267 function addSponsorMenu ($current) {
268         $OUT = '';
269         $WHERE = " AND `active`='Y'";
270         if (isAdmin()) $WHERE = '';
271
272         // Load main menu entries
273         $result_main = SQL_QUERY("SELECT
274         `action` AS `main_action`, `title` AS `main_title`
275 FROM
276         `{?_MYSQL_PREFIX?}_sponsor_menu`
277 WHERE
278         (`what`='' OR `what` IS NULL)
279         " . $WHERE . "
280 ORDER BY
281         `sort` ASC", __FUNCTION__, __LINE__);
282         if (!SQL_HASZERONUMS($result_main)) {
283                 // Load every menu and it's sub menus
284                 while ($content = SQL_FETCHARRAY($result_main)) {
285                         // Load sub menus
286                         $result_sub = SQL_QUERY_ESC("SELECT
287         `what` AS `sub_what`, `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 .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_SUB_MENUS_ACTIVE--}');
317                         }
318
319                         // Free memory
320                         SQL_FREERESULT($result_sub);
321                 } // END - while
322         } else {
323                 // No main menus active
324                 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_MAIN_MENUS_ACTIVE--}');
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'] .= loadTemplate('admin_settings_saved', true, getMaskedMessage('SPONSOR_CONTENT_404', $what));
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_AFFECTEDROWS() == 1);
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_pay', 'last_curr', 'pass_old',
389                         '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() . ':' . $postData['email'] . ':' . detectRemoteAddr() . ':' . detectUserAgent() . ':' . 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 = getMaskedMessage('SPONSOR_UNKNOWN_WHAT', getWhat());
472                         $templ   = '';
473                         $subj    = '';
474                         break;
475         } // END - switch
476
477         // Has an entry updated?
478         if (SQL_AFFECTEDROWS() == 1) {
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         `email`='%s'" . $locked."
541 LIMIT 1",
542                 array($email), __FUNCTION__, __LINE__);
543         if (SQL_NUMROWS($result) == 1) {
544                 // Load sponsor_id
545                 list($sponsor_id) = SQL_FETCHROW($result);
546
547                 // Rewrite email address to contact link
548                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=sponsor_contct&amp;sponsor_id=' . bigintval($sponsor_id) . '%}';
549         } // END - if
550
551         // Free memory
552         SQL_FREERESULT($result);
553
554         // Return rewritten (?) email address
555         return $email;
556 }
557
558 // Processes a sponsor request and handles it
559 function doProcessSponsorFormRequest ($messageArray = array()) {
560         // Default message
561         $message = '';
562
563         // Handle the request
564         $status = handleSponsorRequest(postRequestArray(), true, $messageArray, true);
565
566         // Check the status of the registration process
567         switch ($status) {
568                 case 'added': // Sponsor successfully added with account status = UNCONFIRMED!
569                         // Check for his id number
570                         $result = SQL_QUERY_ESC("SELECT `id`, `hash` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `email`='%s' LIMIT 1",
571                                 array(postRequestParameter('email')), __FUNCTION__, __LINE__);
572                         if (SQL_NUMROWS($result) == 1) {
573                                 // id found so let's load it for the confirmation email
574                                 list($id, $hash) = SQL_FETCHROW($result);
575
576                                 // Prepare data for the email template
577                                 $content['id']        = $id;
578                                 $content['hash']      = $hash;
579                                 $content['email']     = secureString(postRequestParameter('email'));
580                                 $content['surname']   = secureString(postRequestParameter('surname'));
581                                 $content['family']    = secureString(postRequestParameter('family'));
582                                 $content['timestamp'] = generateDateTime(time(), 0);
583                                 $content['password']  = secureString(postRequestParameter('pass1'));
584
585                                 // Generate email and send it to the new sponsor
586                                 $message = loadEmailTemplate('sponsor_confirm', $content, $id);
587                                 sendEmail(postRequestParameter('email'), '{--SPONSOR_PLEASE_CONFIRM_SUBJECT--}', $message);
588
589                                 // Send mail to admin
590                                 sendAdminNotification('{--ADMIN_NEW_SPONSOR--}', 'admin_sponsor_reg', $content);
591
592                                 // Output message: DONE
593                                 $message = $messageArray['added'];
594                         } else {
595                                 // Sponsor account not found???
596                                 $message = getMaskedMessage('SPONSOR_EMAIL_404', postRequestParameter('email'));
597                         }
598
599                         // Free memory
600                         SQL_FREERESULT($result);
601                         break;
602
603                 default:
604                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
605                         if (!isAdmin()) {
606                                 // Message for testing admin
607                                 $message = getMaskedMessage('ADMIN_SPONSOR_UNKNOWN_STATUS', $status);
608                         } else {
609                                 // Message for the guest
610                                 $message = getMaskedMessage('SPONSOR_UNKNOWN_STATUS', $status);
611                         }
612                         break;
613         }
614
615         // Return message
616         return $message;
617 }
618
619 // Expression call-back function for fetching sponsor data
620 function doExpressionSponsor ($data) {
621         // Use current sponsor_id by default
622         $functionName = 'getSponsorId()';
623
624         // Sponsor-related data, so is there a sponsor_id?
625         if (!empty($data['matches'][4][$data['key']])) {
626                 // Do we have a sponsor_id or $sponsor_id?
627                 if ($data['matches'][4][$data['key']] == '$userid') {
628                         // Use dynamic call
629                         $functionName = "getFetchedSponsorData('id', \$userid, '" . $data['callback'] . "')";
630                 } elseif (!empty($data['matches'][4][$data['key']])) {
631                         // Sponsor data found
632                         $functionName = "getFetchedSponsorData('id', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
633                 }
634         } elseif ((!empty($data['callback'])) && (isSponsorDataValid())) {
635                 // "Call-back" alias column for current logged in sponsor's data
636                 $functionName = "getSponsorData('" . $data['callback'] . "')";
637         }
638
639         // Do we have another function to run (e.g. translations)
640         if (!empty($data['extra_func'])) {
641                 // Surround the original function call with it
642                 $functionName = $data['extra_func'] . '(' . $functionName . ')';
643         } // END - if
644
645         // Generate replacer
646         $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
647
648         // Now replace the code
649         $code = replaceExpressionCode($data, $replacer);
650
651         // Return replaced code
652         return $code;
653 }
654
655 // Fetch sponsor data for given sponsor id
656 function fetchSponsorData ($sponsor_id, $column = 'id') {
657         // If we should look for sponsor_id secure&set it here
658         if ($column == 'id') {
659                 // Secure sponsor_id
660                 $sponsor_id = bigintval($sponsor_id);
661
662                 // Set it here
663                 setCurrentSponsorId($sponsor_id);
664
665                 // Don't look for invalid sponsor_ids...
666                 if (!isValidUserId($sponsor_id)) {
667                         // Invalid, so abort here
668                         debug_report_bug(__FUNCTION__, __LINE__, 'Sponsor id ' . $sponsor_id . ' is invalid.');
669                 } elseif (isSponsorDataValid()) {
670                         // Use cache, so it is fine
671                         return true;
672                 }
673         } elseif (isSponsorDataValid()) {
674                 // Use cache, so it is fine
675                 return true;
676         }
677
678         // By default none was found
679         $found = false;
680
681         // Extra statements
682         $ADD = '';
683
684         // Query for the sponsor
685         $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `%s`='%s' LIMIT 1",
686                 array($column, $sponsor_id), __FUNCTION__, __LINE__);
687
688         // Do we have a record?
689         if (SQL_NUMROWS($result) == 1) {
690                 // Load data from cookies
691                 $data = SQL_FETCHARRAY($result);
692
693                 // Set the sponsor_id for later use
694                 setCurrentSponsorId($data['id']);
695                 $GLOBALS['sponsor_data'][getCurrentSponsorId()] = $data;
696
697                 // Rewrite 'last_failure' if found
698                 if (isset($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'])) {
699                         // Backup the raw one and zero it
700                         $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'] = $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'];
701                         $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = '0';
702
703                         // Is it not zero?
704                         if ($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
705                                 // Seperate data/time
706                                 $array = explode(' ', $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw']);
707
708                                 // Seperate data and time again
709                                 $array['date'] = explode('-', $array[0]);
710                                 $array['time'] = explode(':', $array[1]);
711
712                                 // Now pass it to mktime()
713                                 $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = mktime(
714                                         $array['time'][0],
715                                         $array['time'][1],
716                                         $array['time'][2],
717                                         $array['date'][1],
718                                         $array['date'][2],
719                                         $array['date'][0]
720                                 );
721                         } // END - if
722                 } // END - if
723
724                 // Found, but valid?
725                 $found = isSponsorDataValid();
726         } // END - if
727
728         // Free memory
729         SQL_FREERESULT($result);
730
731         // Return result
732         return $found;
733 }
734
735 // Wrapper for fetchSponsorData() and getSponsorData() calls
736 function getFetchedSponsorData ($keyColumn, $sponsor_id, $valueColumn) {
737         // Zero ids are not valid
738         if ($sponsor_id == 0) {
739                 // Abort here
740                 debug_report_bug(__FUNCTION__, __LINE__, 'Zero sponsor_id provided');
741         } // END - if
742
743         // Is it cached?
744         if (!isset($GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn])) {
745                 // Default is empty
746                 $data = '';
747
748                 // Can we fetch the sponsor data?
749                 if ((isValidSponsorId($sponsor_id)) && (fetchSponsorData($sponsor_id, $keyColumn))) {
750                         // Now get the data back
751                         $data = getSponsorData($valueColumn);
752                 } // END - if
753
754                 // Cache it
755                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cached:id=' . $sponsor_id . ',keyColumn=' . $keyColumn . ',valueColumn=' . $valueColumn . ',data=' . $data);
756                 $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn] = $data;
757         } // END - if
758
759         // Return it
760         return $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn];
761 }
762
763 // Checks if the sponsor data is valid, this may indicate that the sponsor has logged
764 // in, but you should use isMember() if you want to find that out.
765 function isSponsorDataValid () {
766         // Sponsor id should not be zero so abort here
767         if (!isCurrentSponsorIdSet()) return false;
768
769         // Is it cached?
770         if (!isset($GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()])) {
771                 // Determine it
772                 $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()] = ((isset($GLOBALS['sponsor_data'][getCurrentSponsorId()])) && (count($GLOBALS['sponsor_data'][getCurrentSponsorId()]) > 1));
773         } // END - if
774
775         // Return the result
776         return $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()];
777 }
778
779 // Setter for current sponsor_id
780 function setCurrentSponsorId ($sponsor_id) {
781         // Set sponsor_id
782         $GLOBALS['current_sponsor_id'] = bigintval($sponsor_id);
783
784         // Unset it to re-determine the actual state
785         unset($GLOBALS['is_sponsor_data_valid'][$sponsor_id]);
786 }
787
788 // Getter for current sponsor_id
789 function getCurrentSponsorId () {
790         // Sponsorid must be set before it can be used
791         if (!isCurrentSponsorIdSet()) {
792                 // Not set
793                 debug_report_bug(__FUNCTION__, __LINE__, 'Sponsor id is not set.');
794         } // END - if
795
796         // Return the sponsor_id
797         return $GLOBALS['current_sponsor_id'];
798 }
799
800 // Checks if current sponsor_id is set
801 function isCurrentSponsorIdSet () {
802         return ((isset($GLOBALS['current_sponsor_id'])) && (isValidSponsorId($GLOBALS['current_sponsor_id'])));
803 }
804
805 // Is given sponsor_id valid?
806 function isValidSponsorId ($sponsor_id) {
807         // Do we have cache?
808         if (!isset($GLOBALS[__FUNCTION__][$sponsor_id])) {
809                 // Check it out
810                 $GLOBALS[__FUNCTION__][$sponsor_id] = ((!is_null($sponsor_id)) && (!empty($sponsor_id)) && ($sponsor_id > 0));
811         } // END - if
812
813         // Return cache
814         return $GLOBALS[__FUNCTION__][$sponsor_id];
815 }
816
817 // Getter for sponsor data
818 function getSponsorData ($column) {
819         // Sponsor id should not be zero
820         if (!isValidUserId(getCurrentSponsorId())) {
821                 debug_report_bug(__FUNCTION__, __LINE__, 'Sponsor id is zero.');
822         } // END - if
823
824         // Return the value
825         return $GLOBALS['sponsor_data'][getCurrentSponsorId()][$column];
826 }
827
828 // Determines the country of the given sponsor id
829 function determineSponsorCountry ($sponsor_id) {
830         // Then handle it over
831         $country = getSponsorData('country');
832
833         // Return it
834         return $country;
835 }
836
837 // Destroy sponsor session
838 function destroySponsorSession () {
839         // Remove all user data from session
840         return ((setSession('sponsor_id', '')) && (setSession('sponsor_pass', '')));
841 }
842
843 // Getter for sponsor_min_points
844 function getSponsorMinPoints () {
845         // Do we have cache?
846         if (!isset($GLOBALS[__FUNCTION__])) {
847                 // Determine it
848                 $GLOBALS[__FUNCTION__] = getConfig('sponsor_min_points');
849         } // END - if
850
851         // Return cache
852         return $GLOBALS[__FUNCTION__];
853 }
854
855 // Getter for sponsor_ref_points
856 function getSponsorRefPoints () {
857         // Do we have cache?
858         if (!isset($GLOBALS[__FUNCTION__])) {
859                 // Determine it
860                 $GLOBALS[__FUNCTION__] = getConfig('sponsor_ref_points');
861         } // END - if
862
863         // Return cache
864         return $GLOBALS[__FUNCTION__];
865 }
866
867 // [EOF]
868 ?>