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