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