]> git.mxchange.org Git - mailer.git/blob - inc/libs/sponsor_functions.php
More usage of isValidUserId()
[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('sponsor_pass')) &&
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                                         // Check if current selected menu is matching the loaded one
304                                         if ($current == $content2['sub_what']) $content2['sub_title'] = '<strong>' . $content2['sub_title'] . '</strong>';
305
306                                         // Load row template
307                                         $SUB .= loadTemplate('sponsor_what', true, $content2);
308                                 } // END - while
309
310                                 // Prepare data for the main template
311                                 $content['menu'] = $SUB;
312
313                                 // Load menu template
314                                 $OUT .= loadTemplate('sponsor_action', true, $content);
315                         } else {
316                                 // No sub menus active
317                                 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_SUB_MENUS_ACTIVE--}');
318                         }
319
320                         // Free memory
321                         SQL_FREERESULT($result_sub);
322                 } // END - while
323         } else {
324                 // No main menus active
325                 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_MAIN_MENUS_ACTIVE--}');
326         }
327
328         // Free memory
329         SQL_FREERESULT($result_main);
330
331         // Return content
332         return $OUT;
333 }
334
335 //
336 function addSponsorContent ($what) {
337         // Init sponsor content
338         $GLOBALS['sponsor_output'] = '';
339
340         // Generate IFN (Include FileName)
341         $INC = sprintf("inc/modules/sponsor/%s.php", $what);
342         if (isIncludeReadable($INC)) {
343                 // Every sponsor action will output nothing directly. It will be written into $GLOBALS['sponsor_output']!
344                 loadIncludeOnce($INC);
345         } else {
346                 // File not found!
347                 $GLOBALS['sponsor_output'] .= loadTemplate('admin_settings_saved', true, getMaskedMessage('SPONSOR_CONTENT_404', $what));
348         }
349
350         // Return content
351         return $GLOBALS['sponsor_output'];
352 }
353
354 //
355 function updateSponsorLogin () {
356         // Failed by default
357         $login = false;
358
359         // Is sponsor?
360         if (isSponsor()) {
361                 // Update last online timestamp
362                 SQL_QUERY_ESC("UPDATE
363         `{?_MYSQL_PREFIX?}_sponsor_data`
364 SET
365         `last_online`=UNIX_TIMESTAMP()
366 WHERE
367         `id`=%s AND
368         `password`='%s'
369 LIMIT 1",
370                         array(
371                                 bigintval(getSession('sponsor_id')),
372                                 getSession('sponsor_pass')
373                         ), __FUNCTION__, __LINE__);
374
375                 // This update went fine?
376                 $login = (SQL_AFFECTEDROWS() == 1);
377         } // END - if
378
379         // Return status
380         return $login;
381 }
382
383 // Saves sponsor's data
384 function saveSponsorData ($postData, $content) {
385         $EMAIL = false;
386
387         // Unsecure data which we don't want
388         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
389                         'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
390                         'ok', 'pass1', 'pass2');
391
392         // Set default message ("not saved")
393         $message = '{--SPONSOR_ACCOUNT_DATA_NOT_SAVED--}';
394
395         // Check for submitted passwords
396         if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
397                 // Are both passwords the same?
398                 if ($postData['pass1'] == $postData['pass2']) {
399                         // Okay, then set password and remove pass1 and pass2
400                         $postData['password'] = md5($postData['pass1']);
401                 } // END - if
402         } // END - if
403
404         // Remove all (maybe spoofed) unsafe data from array
405         foreach ($UNSAFE as $remove) {
406                 unset($postData[$remove]);
407         } // END - foreach
408
409         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
410         // secure the data
411         $DATA = array();
412
413         // Prepare SQL string
414         $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
415         foreach ($postData as $key => $value) {
416                 // Mmmmm, too less security here???
417                 $sql   .= " `" . secureString($key) . "`='%s',";
418
419                 // We will secure this later inside the SQL_QUERY_ESC() function
420                 $DATA[] = secureString($value);
421         } // END - foreach
422
423         // Check if email has changed
424         if ((!empty($content['email'])) && (!empty($postData['email']))) {
425                 if ($content['email'] != $postData['email']) {
426                         // Change email address
427                         $EMAIL = true;
428
429                         // Okay, has changed then add status with UNCONFIRMED and new hash code
430                         $sql .= " `status`='EMAIL', `hash`='%s',";
431
432                         // Generate hash code
433                         $HASH = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
434                         $DATA[] = $HASH;
435                 } // END - if
436         } // END - if
437
438         // Remove last commata
439         $sql = substr($sql, 0, -1);
440
441         // Add SQL tail data
442         $sql .= " WHERE `id`=%s AND `password`='%s' LIMIT 1";
443         $DATA[] = bigintval(getSession('sponsor_id'));
444         $DATA[] = getSession('sponsor_pass');
445
446         // Saving data was completed... ufff...
447         switch (getWhat()) {
448                 case 'account': // Change account data
449                         if ($EMAIL === true) {
450                                 $message = '{--SPONSOR_ACCOUNT_EMAIL_CHANGED--}';
451                                 $templ   = 'admin_sponsor_change_email';
452                                 $subj    = '{--ADMIN_SPONSOR_ACC_EMAIL_SUBJECT--}';
453                         } else {
454                                 $message = '{--SPONSOR_ACCOUNT_DATA_SAVED--}';
455                                 $templ   = 'admin_sponsor_change_data';
456                                 $subj    = '{--ADMIN_SPONSOR_ACC_DATA_SUBJECT--}';
457                         }
458                         break;
459
460                 case 'settings': // Change settings
461                         // Set message template and subject for admin
462                         $message = '{--SPONSOR_SETTINGS_SAVED--}';
463                         $templ   = 'admin_sponsor_settings';
464                         $subj    = '{--ADMIN_SPONSOR_SETTINGS_SUBJECT--}';
465                         break;
466
467                 default: // Unknown sponsor what value!
468                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
469                         $message = getMaskedMessage('SPONSOR_UNKNOWN_WHAT', getWhat());
470                         $templ   = '';
471                         $subj    = '';
472                         break;
473         } // END - switch
474
475         // Has an entry updated?
476         if (SQL_AFFECTEDROWS() == 1) {
477                 // Template and subject are set?
478                 if (!empty($templ) && !empty($subj)) {
479                         // Run SQL command and check for success
480                         $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
481
482                         // Add all data to content
483                         $content['new_data'] = $postData;
484
485                         // Send email to admins
486                         sendAdminNotification($subj, $templ, $content);
487
488                         // Shall we send mail to the sponsor's new email address?
489                         if ($content['receive_warnings'] == 'Y') {
490                                 /*
491                                  * Okay send email with confirmation link to new address and with no confirmation link
492                                  * to the old address.
493                                  */
494
495                                 // First to old address
496                                 switch (getWhat()) {
497                                         case 'account': // Change account data
498                                                 $email_msg = loadEmailTemplate('sponsor_change_data', $content);
499                                                 sendEmail($content['email'], '{--SPONSOR_ACC_DATA_SUBJECT--}', $email_msg);
500
501                                                 if ($EMAIL === true) {
502                                                         // Add hash code to content array
503                                                         $content['hash'] = $HASH;
504
505                                                         // Second mail goes to the new address
506                                                         $email_msg = loadEmailTemplate('sponsor_change_email', $content);
507                                                         sendEmail($content['email'], '{--SPONSOR_ACC_EMAIL_SUBJECT--}', $email_msg);
508                                                 } // END - if
509                                                 break;
510
511                                         case 'settings': // Change settings
512                                                 // Send email
513                                                 $email_msg = loadEmailTemplate('sponsor_settings', $content);
514                                                 sendEmail($content['email'], '{--SPONSOR_SETTINGS_SUBJECT--}', $email_msg);
515                                                 break;
516                                 } // END - switch
517                         } // END - if
518                 } // END - if
519         } // END - if
520
521         // Return final message
522         return $message;
523 }
524
525 // Create email link to sponsor's account
526 function generateSponsorEmailLink ($email, $mod = 'admin') {
527         // Show contact link only if sponsor is confirmed by default
528         $locked = " AND `status`='CONFIRMED'";
529
530         // But admins shall always see it
531         if (isAdmin()) $locked = '';
532
533         $result = SQL_QUERY_ESC("SELECT
534         `id`
535 FROM
536         `{?_MYSQL_PREFIX?}_sponsor_data`
537 WHERE
538         `email`='%s'" . $locked."
539 LIMIT 1",
540                 array($email), __FUNCTION__, __LINE__);
541         if (SQL_NUMROWS($result) == 1) {
542                 // Load sponsor_id
543                 list($sponsor_id) = SQL_FETCHROW($result);
544
545                 // Rewrite email address to contact link
546                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=sponsor_contct&amp;sponsor_id=' . bigintval($sponsor_id) . '%}';
547         } // END - if
548
549         // Free memory
550         SQL_FREERESULT($result);
551
552         // Return rewritten (?) email address
553         return $email;
554 }
555
556 // Processes a sponsor request and handles it
557 function doProcessSponsorFormRequest ($messageArray = array()) {
558         // Default message
559         $message = '';
560
561         // Handle the request
562         $status = handleSponsorRequest(postRequestArray(), true, $messageArray, true);
563
564         // Check the status of the registration process
565         switch ($status) {
566                 case 'added': // Sponsor successfully added with account status = UNCONFIRMED!
567                         // Check for his id number
568                         $result = SQL_QUERY_ESC("SELECT `id`, `hash` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `email`='%s' LIMIT 1",
569                                 array(postRequestParameter('email')), __FILE__, __LINE__);
570                         if (SQL_NUMROWS($result) == 1) {
571                                 // id found so let's load it for the confirmation email
572                                 list($id, $hash) = SQL_FETCHROW($result);
573
574                                 // Prepare data for the email template
575                                 $content['id']        = $id;
576                                 $content['hash']      = $hash;
577                                 $content['email']     = secureString(postRequestParameter('email'));
578                                 $content['surname']   = secureString(postRequestParameter('surname'));
579                                 $content['family']    = secureString(postRequestParameter('family'));
580                                 $content['timestamp'] = generateDateTime(time(), 0);
581                                 $content['password']  = secureString(postRequestParameter('pass1'));
582
583                                 // Generate email and send it to the new sponsor
584                                 $message = loadEmailTemplate('sponsor_confirm', $content, $id);
585                                 sendEmail(postRequestParameter('email'), '{--SPONSOR_PLEASE_CONFIRM_SUBJECT--}', $message);
586
587                                 // Send mail to admin
588                                 sendAdminNotification('{--ADMIN_NEW_SPONSOR--}', 'admin_sponsor_reg', $content);
589
590                                 // Output message: DONE
591                                 $message = $messageArray['added'];
592                         } else {
593                                 // Sponsor account not found???
594                                 $message = getMaskedMessage('SPONSOR_EMAIL_404', postRequestParameter('email'));
595                         }
596
597                         // Free memory
598                         SQL_FREERESULT($result);
599                         break;
600
601                 default:
602                         logDebugMessage(__FILE__, __LINE__, sprintf("Unknown status %s detected.", $status));
603                         if (!isAdmin()) {
604                                 // Message for testing admin
605                                 $message = getMaskedMessage('ADMIN_SPONSOR_UNKNOWN_STATUS', $status);
606                         } else {
607                                 // Message for the guest
608                                 $message = getMaskedMessage('SPONSOR_UNKNOWN_STATUS', $status);
609                         }
610                         break;
611         }
612
613         // Return message
614         return $message;
615 }
616
617 // Expression call-back function for fetching sponsor data
618 function doExpressionSponsor ($data) {
619         // Use current sponsor_id by default
620         $functionName = 'getSponsorId()';
621
622         // Sponsor-related data, so is there a sponsor_id?
623         if (!empty($data['matches'][4][$data['key']])) {
624                 // Do we have a sponsor_id or $sponsor_id?
625                 if ($data['matches'][4][$data['key']] == '$userid') {
626                         // Use dynamic call
627                         $functionName = "getFetchedSponsorData('id', \$userid, '" . $data['callback'] . "')";
628                 } elseif (!empty($data['matches'][4][$data['key']])) {
629                         // Sponsor data found
630                         $functionName = "getFetchedSponsorData('id', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
631                 }
632         } elseif ((!empty($data['callback'])) && (isSponsorDataValid())) {
633                 // "Call-back" alias column for current logged in sponsor's data
634                 $functionName = "getSponsorData('" . $data['callback'] . "')";
635         }
636
637         // Do we have another function to run (e.g. translations)
638         if (!empty($data['extra_func'])) {
639                 // Surround the original function call with it
640                 $functionName = $data['extra_func'] . '(' . $functionName . ')';
641         } // END - if
642
643         // Generate replacer
644         $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
645
646         // Now replace the code
647         $code = replaceExpressionCode($data, $replacer);
648
649         // Return replaced code
650         return $code;
651 }
652
653 // Fetch sponsor data for given sponsor id
654 function fetchSponsorData ($sponsor_id, $column = 'id') {
655         // If we should look for sponsor_id secure&set it here
656         if ($column == 'id') {
657                 // Secure sponsor_id
658                 $sponsor_id = bigintval($sponsor_id);
659
660                 // Set it here
661                 setCurrentSponsorId($sponsor_id);
662
663                 // Don't look for invalid sponsor_ids...
664                 if (!isValidUserId($sponsor_id)) {
665                         // Invalid, so abort here
666                         debug_report_bug(__FUNCTION__, __LINE__, 'Sponsor id ' . $sponsor_id . ' is invalid.');
667                 } elseif (isSponsorDataValid()) {
668                         // Use cache, so it is fine
669                         return true;
670                 }
671         } elseif (isSponsorDataValid()) {
672                 // Use cache, so it is fine
673                 return true;
674         }
675
676         // By default none was found
677         $found = false;
678
679         // Extra statements
680         $ADD = '';
681
682         // Query for the sponsor
683         $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `%s`='%s' LIMIT 1",
684                 array($column, $sponsor_id), __FUNCTION__, __LINE__);
685
686         // Do we have a record?
687         if (SQL_NUMROWS($result) == 1) {
688                 // Load data from cookies
689                 $data = SQL_FETCHARRAY($result);
690
691                 // Set the sponsor_id for later use
692                 setCurrentSponsorId($data['id']);
693                 $GLOBALS['sponsor_data'][getCurrentSponsorId()] = $data;
694
695                 // Rewrite 'last_failure' if found
696                 if (isset($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'])) {
697                         // Backup the raw one and zero it
698                         $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'] = $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'];
699                         $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = '0';
700
701                         // Is it not zero?
702                         if ($GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
703                                 // Seperate data/time
704                                 $array = explode(' ', $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure_raw']);
705
706                                 // Seperate data and time again
707                                 $array['date'] = explode('-', $array[0]);
708                                 $array['time'] = explode(':', $array[1]);
709
710                                 // Now pass it to mktime()
711                                 $GLOBALS['sponsor_data'][getCurrentSponsorId()]['last_failure'] = mktime(
712                                         $array['time'][0],
713                                         $array['time'][1],
714                                         $array['time'][2],
715                                         $array['date'][1],
716                                         $array['date'][2],
717                                         $array['date'][0]
718                                 );
719                         } // END - if
720                 } // END - if
721
722                 // Found, but valid?
723                 $found = isSponsorDataValid();
724         } // END - if
725
726         // Free memory
727         SQL_FREERESULT($result);
728
729         // Return result
730         return $found;
731 }
732
733 // Wrapper for fetchSponsorData() and getSponsorData() calls
734 function getFetchedSponsorData ($keyColumn, $sponsor_id, $valueColumn) {
735         // Zero ids are not valid
736         if ($sponsor_id == 0) {
737                 // Abort here
738                 debug_report_bug(__FUNCTION__, __LINE__, 'Zero sponsor_id provided');
739         } // END - if
740
741         // Is it cached?
742         if (!isset($GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn])) {
743                 // Default is empty
744                 $data = '';
745
746                 // Can we fetch the sponsor data?
747                 if ((isValidSponsorId($sponsor_id)) && (fetchSponsorData($sponsor_id, $keyColumn))) {
748                         // Now get the data back
749                         $data = getSponsorData($valueColumn);
750                 } // END - if
751
752                 // Cache it
753                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cached:id=' . $sponsor_id . ',keyColumn=' . $keyColumn . ',valueColumn=' . $valueColumn . ',data=' . $data);
754                 $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn] = $data;
755         } // END - if
756
757         // Return it
758         return $GLOBALS['sponsor_data_cache'][$sponsor_id][$keyColumn][$valueColumn];
759 }
760
761 // Checks if the sponsor data is valid, this may indicate that the sponsor has logged
762 // in, but you should use isMember() if you want to find that out.
763 function isSponsorDataValid () {
764         // Sponsor id should not be zero so abort here
765         if (!isCurrentSponsorIdSet()) return false;
766
767         // Is it cached?
768         if (!isset($GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()])) {
769                 // Determine it
770                 $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()] = ((isset($GLOBALS['sponsor_data'][getCurrentSponsorId()])) && (count($GLOBALS['sponsor_data'][getCurrentSponsorId()]) > 1));
771         } // END - if
772
773         // Return the result
774         return $GLOBALS['is_sponsor_data_valid'][getCurrentSponsorId()];
775 }
776
777 // Setter for current sponsor_id
778 function setCurrentSponsorId ($sponsor_id) {
779         // Set sponsor_id
780         $GLOBALS['current_sponsor_id'] = bigintval($sponsor_id);
781
782         // Unset it to re-determine the actual state
783         unset($GLOBALS['is_sponsor_data_valid'][$sponsor_id]);
784 }
785
786 // Getter for current sponsor_id
787 function getCurrentSponsorId () {
788         // Sponsorid must be set before it can be used
789         if (!isCurrentSponsorIdSet()) {
790                 // Not set
791                 debug_report_bug(__FUNCTION__, __LINE__, 'Sponsor id is not set.');
792         } // END - if
793
794         // Return the sponsor_id
795         return $GLOBALS['current_sponsor_id'];
796 }
797
798 // Checks if current sponsor_id is set
799 function isCurrentSponsorIdSet () {
800         return ((isset($GLOBALS['current_sponsor_id'])) && (isValidSponsorId($GLOBALS['current_sponsor_id'])));
801 }
802
803 // Is given sponsor_id valid?
804 function isValidSponsorId ($sponsor_id) {
805         // Do we have cache?
806         if (!isset($GLOBALS['is_valid_sponsor_id'][$sponsor_id])) {
807                 // Check it out
808                 $GLOBALS['is_valid_sponsor_id'][$sponsor_id] = ((!is_null($sponsor_id)) && (!empty($sponsor_id)) && ($sponsor_id > 0));
809         } // END - if
810
811         // Return cache
812         return $GLOBALS['is_valid_sponsor_id'][$sponsor_id];
813 }
814
815 // Getter for sponsor data
816 function getSponsorData ($column) {
817         // Sponsor id should not be zero
818         if (!isValidUserId(getCurrentSponsorId())) {
819                 debug_report_bug(__FUNCTION__, __LINE__, 'Sponsor id is zero.');
820         } // END - if
821
822         // Return the value
823         return $GLOBALS['sponsor_data'][getCurrentSponsorId()][$column];
824 }
825
826 // Determines the country of the given sponsor id
827 function determineSponsorCountry ($sponsor_id) {
828         // Then handle it over
829         $country = getSponsorData('country');
830
831         // Return it
832         return $country;
833 }
834
835 // Destroy sponsor session
836 function destroySponsorSession () {
837         // Remove all user data from session
838         return ((setSession('sponsor_id', '')) && (setSession('sponsor_pass', '')));
839 }
840
841 // [EOF]
842 ?>