More rewrites, and output-mode fixed (we should documentate this)
[mailer.git] / inc / libs / sponsor_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 }
43
44 //
45 function handlSponsorRequest (&$postData, $update=false, $messageArray=array(), $RET_STATUS=false) {
46         // Init a lot variables
47         $SAVE = true;
48         $UPDATE = false;
49         $skip = false;
50         $ALREADY = false;
51         $ret = "unused";
52
53         // Skip these entries
54         $SKIPPED = array(
55                 'ok', 'edit', 'terms', 'pay_type'
56         );
57
58         // Save sponsor data
59         $DATA = array(
60                 'keys'   => array(),
61                 'values' => array()
62         );
63
64                 // Check if sponsor already exists
65                 foreach ($postData as $k => $v) {
66                         if (!(array_search($k, $SKIPPED) > -1)) {
67                                 // Check only posted input entries not the submit button
68                                 switch ($k)
69                                 {
70                                         case 'email':
71                                                 $ALREADY = false;
72                                                 if (!isEmailValid($v)) {
73                                                         // Email address is not valid
74                                                         $SAVE = false;
75                                                 } else {
76                                                         // Do we want to add a new sponsor or update his data?
77                                                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE email='%s' LIMIT 1",
78                                                         array($postData['email']), __FUNCTION__, __LINE__);
79
80                                                         // Is a sponsor alread in the db?
81                                                         if (SQL_NUMROWS($result) == 1) {
82                                                                 // Yes, he is!
83                                                                 if ((getWhat() == 'add_sponsor') || ($update)) {
84                                                                         // Already found!
85                                                                         $ALREADY = true;
86                                                                 } else {
87                                                                         // Update his data
88                                                                         $UPDATE = true;
89                                                                 }
90                                                         }
91
92                                                         // Free memory
93                                                         SQL_FREERESULT($result);
94                                                 }
95                                                 break;
96
97                                         case 'pass1':
98                                                 $k = ''; $v = '';
99                                                 break;
100
101                                         case 'pass2':
102                                                 $k = 'password'; $v = md5($v);
103                                                 break;
104
105                                         case 'url':
106                                                 if (!isUrlValid($v)) $SAVE = false;
107                                                 break;
108
109                                         default:
110                                                 // Test if there is are time selections
111                                                 convertSelectionsToTimestamp($postData, $DATA, $k, $skip);
112                                                 break;
113                                 }
114
115                                 if ((!empty($k)) && ($skip == false)) {
116                                         // Add data
117                                         $DATA['keys'][] = $k; $DATA['values'][] = $v;
118                                 }
119                         }
120                 }
121
122                 // Save sponsor?
123                 if ($SAVE === true) {
124                         // Default is no force even when a guest want to abuse this force switch
125                         if ((empty($postData['force'])) || (!isAdmin())) $postData['force'] = 0;
126
127                         // SQL and message string is empty by default
128                         $sql = ''; $message = '';
129
130                         // Update?
131                         if ($UPDATE) {
132                                 // Update his data
133                                 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET ";
134                                 foreach ($DATA['keys'] as $k => $v) {
135                                         $sql .= $v."='%s', ";
136                                 }
137
138                                 // Remove last ", " from SQL string
139                                 $sql = substr($sql, 0, -2)." WHERE `id`='%s' LIMIT 1";
140                                 $DATA['values'][] = bigintval(getRequestElement('id'));
141
142                                 // Generate message
143                                 $message = getMessageFromIndexedArray(getMessage('ADMIN_SPONSOR_UPDATED'), 'updated', $messageArray);
144                                 $ret = "updated";
145                         } elseif (($ALREADY === false) || (($postData['force'] == 1) && (isAdmin()))) {
146                                 // Add new sponsor, first add more data
147                                 $DATA['keys'][] = 'sponsor_created'; $DATA['values'][] = time();
148                                 $DATA['keys'][] = 'status';
149                                 if (($update === true) && (isAdmin()) && (getWhat() == 'add_sponsor')) {
150                                         // Only allowed for admin
151                                         $DATA['values'][] = 'PENDING';
152                                 } else {
153                                         // Guest area
154                                         $DATA['values'][] = 'UNCONFIRMED';
155
156                                         // Generate hash code
157                                         $DATA['keys'][] = 'hash';
158                                         $DATA['values'][] = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
159                                         $DATA['keys'][] = 'remote_addr';
160                                         $DATA['values'][] = detectRemoteAddr();
161                                 }
162
163                                 // Implode all data into strings
164                                 $KEYS   = implode("`, `"  , $DATA['keys']);
165                                 $valueS = str_repeat("%s', '", count($DATA['values']) - 1);
166
167                                 // Generate string
168                                 $sql = "INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`".$KEYS."`) VALUES ('".$valueS."%s')";
169
170                                 // Generate message
171                                 $message = getMessageFromIndexedArray(getMessage('ADMIN_SPONSOR_ADDED'), "added", $messageArray);
172                                 $ret = 'added';
173                         } elseif (($update === true) && (isAdmin())) {
174                                 // Add all data as hidden data
175                                 $OUT = '';
176                                 foreach ($postData as $k => $v) {
177                                         // Do not add 'force' !
178                                         if ($k != "force") {
179                                                 $OUT .= "<input type=\"hidden\" name=\"".$k."\" value=\"".stripslashes($v)."\" />\n";
180                                         }
181                                 }
182                                 $content['hidden'] = $OUT;
183                                 $content['email']  = $postData['email'];
184
185                                 // Ask for adding a sponsor with same email address
186                                 loadTemplate('admin_add_sponsor_already', false, $content);
187                                 return;
188                         } else {
189                                 // Already added!
190                                 $message = sprintf(getMessage('SPONSOR_ALREADY_FOUND'), $postData['email']);
191                                 $ret = 'already';
192                         }
193
194                         if (!empty($sql)) {
195                                 // Run SQL command
196                                 $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
197                         } // END - if
198
199                         // Output message
200                         if (($update === true) && (isAdmin())) {
201                                 loadTemplate('admin_settings_saved', false, $message);
202                         } // END - if
203                 } else {
204                         // Error found!
205                         $message = getMessageFromIndexedArray(getMessage('SPONSOR_DATA_NOT_SAVED'), 'failed', $messageArray);
206                         loadTemplate('admin_settings_saved', false, $message);
207                 }
208
209                 // Shall we return the status?
210                 if ($RET_STATUS === true) return $ret;
211 }
212
213 //
214 function sponsorTranslateUserStatus ($status) {
215         // Construct constant name
216         $constantName = sprintf("ACCOUNT_%s", $status);
217
218         // Is the constant there?
219         if (defined($constantName)) {
220                 // Then use it
221                 $ret = constant($constantName);
222         } else {
223                 // Not found!
224                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
225                 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
226         }
227         return $ret;
228 }
229
230 // Search for an email address in the database
231 function isSponsorRegisteredWithEmail ($email) {
232         // Do we already have the provided email address in our DB?
233         $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
234
235         // Return result
236         return $ret;
237 }
238
239 // Wether the current user is a sponsor
240 function isSponsor () {
241         // Failed...
242         $ret = false;
243         if ((isSessionVariableSet('sponsorid')) && (isSessionVariableSet('sponsorpass'))) {
244                 // Check cookies against database records...
245                 $result = SQL_QUERY_ESC("SELECT
246         `id`
247 FROM
248         `{?_MYSQL_PREFIX?}_sponsor_data`
249 WHERE
250         `id`='%s' AND `password`='%s' AND `status`='CONFIRMED'
251 LIMIT 1",
252                         array(
253                                 bigintval(getSession('sponsorid')),
254                                 getSession('sponsorpass')
255                         ), __FUNCTION__, __LINE__);
256                 if (SQL_NUMROWS($result) == 1) {
257                         // All is fine
258                         $ret = true;
259                 } // END - if
260
261                 // Free memory
262                 SQL_FREERESULT($result);
263         } // END - if
264
265         // Return status
266         return $ret;
267 }
268
269 //
270 function addSponsorMenu ($current) {
271         $OUT = '';
272         $WHERE = " AND active='Y'";
273         if (isAdmin()) $WHERE = '';
274
275         // Load main menu entries
276         $result_main = SQL_QUERY("SELECT action AS main_action, title AS main_title FROM `{?_MYSQL_PREFIX?}_sponsor_menu`
277 WHERE (`what`='' OR `what` IS NULL) ".$WHERE."
278 ORDER BY `sort`", __FUNCTION__, __LINE__);
279         if (SQL_NUMROWS($result_main) > 0) {
280                 // Load every menu and it's sub menus
281                 while ($content = SQL_FETCHARRAY($result_main)) {
282                         // Load sub menus
283                         $result_sub = SQL_QUERY_ESC("SELECT what AS sub_what, title AS sub_title FROM `{?_MYSQL_PREFIX?}_sponsor_menu`
284 WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$WHERE."
285 ORDER BY `sort`",
286                         array($content['main_action']), __FUNCTION__, __LINE__);
287                         if (SQL_NUMROWS($result_sub) > 0) {
288                                 // Load sub menus
289                                 $SUB = '';
290                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
291                                         // Merge both arrays
292                                         $content = merge_array($content, $content2);
293
294                                         // Check if current selected menu is matching the loaded one
295                                         if ($current == $content['sub_what']) $content['sub_title'] = "<strong>".$content['sub_title']."</strong>";
296
297                                         // Prepare data for the sub template
298                                         $content = array(
299                                                 'what'  => $content['sub_what'],
300                                                 'title' => $content['sub_title']
301                                         );
302
303                                         // Load row template
304                                         $SUB .= loadTemplate('sponsor_what', true, $content);
305                                 }
306
307                                 // Prepare data for the main template
308                                 $content = array(
309                                         'title' => $content['main_title'],
310                                         'menu'  => $SUB
311                                 );
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, getMessage('SPONSOR_NO_SUB_MENUS_ACTIVE'));
318                         }
319
320                         // Free memory
321                         SQL_FREERESULT($result_sub);
322                 }
323         } else {
324                 // No main menus active
325                 $OUT .= loadTemplate('admin_settings_saved', true, getMessage('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         $OUT = '';
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 $OUT!
341                 loadIncludeOnce($INC);
342         } else {
343                 // File not found!
344                 $OUT .= loadTemplate('admin_settings_saved', true, sprintf(getMessage('SPONSOR_CONTENT_404'), $what));
345         }
346
347         // Return content
348         return $OUT;
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 `{?_MYSQL_PREFIX?}_sponsor_data`
360 SET `last_online`=UNIX_TIMESTAMP()
361 WHERE `id`='%s' AND `password`='%s' LIMIT 1",
362                         array(
363                                 bigintval(getSession('sponsorid')),
364                                 getSession('sponsorpass')
365                         ), __FUNCTION__, __LINE__);
366
367                 // This update went fine?
368                 $login = (SQL_AFFECTEDROWS() == 1);
369         }
370
371         // Return status
372         return $login;
373 }
374
375 // Saves sponsor's data
376 function saveSponsorData ($postData, $content) {
377         $EMAIL = false;
378
379         // Unsecure data which we don't want
380         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
381                         'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
382                         'ok', 'pass1', 'pass2');
383
384         // Set default message ("not saved")
385         $message = getMessage('SPONSOR_ACCOUNT_DATA_NOT_SAVED');
386
387         // Check for submitted passwords
388         if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
389                 // Are both passwords the same?
390                 if ($postData['pass1'] == $postData['pass2']) {
391                         // Okay, then set password and remove pass1 and pass2
392                         $postData['password'] = md5($postData['pass1']);
393                 } // END - if
394         } // END - if
395
396         // Remove all (maybe spoofed) unsafe data from array
397         foreach ($UNSAFE as $remove) {
398                 unset($postData[$remove]);
399         } // END - foreach
400
401         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
402         // secure the data
403         $DATA = array();
404
405         // Prepare SQL string
406         $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
407         foreach ($postData as $key => $value) {
408                 // Mmmmm, too less security here???
409                 $sql   .= " `".secureString($key)."`='%s',";
410
411                 // We will secure this later inside the SQL_QUERY_ESC() function
412                 $DATA[] = secureString($value);
413         } // END - foreach
414
415         // Check if email has changed
416         if ((!empty($content['email'])) && (!empty($postData['email']))) {
417                 if ($content['email'] != $postData['email']) {
418                         // Change email address
419                         $EMAIL = true;
420
421                         // Okay, has changed then add status with UNCONFIRMED and new hash code
422                         $sql .= " `status`='EMAIL', `hash`='%s',";
423
424                         // Generate hash code
425                         $HASH = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
426                         $DATA[] = $HASH;
427                 } // END - if
428         } // END - if
429
430         // Remove last commata
431         $sql = substr($sql, 0, -1);
432
433         // Add SQL tail data
434         $sql .= " WHERE `id`='%s' AND password='%s' LIMIT 1";
435         $DATA[] = bigintval(getSession('sponsorid'));
436         $DATA[] = getSession('sponsorpass');
437
438         // Saving data was completed... ufff...
439         switch (getWhat())
440         {
441                 case 'account': // Change account data
442                         if ($EMAIL === true) {
443                                 $message   = getMessage('SPONSOR_ACCOUNT_EMAIL_CHANGED');
444                                 $templ = 'admin_sponsor_change_email';
445                                 $subj  = getMessage('ADMIN_SPONSOR_ACC_EMAIL_SUBJ');
446                         } else {
447                                 $message   = getMessage('SPONSOR_ACCOUNT_DATA_SAVED');
448                                 $templ = 'admin_sponsor_change_data';
449                                 $subj  = getMessage('ADMIN_SPONSOR_ACC_DATA_SUBJ');
450                         }
451                         break;
452
453                 case 'settings': // Change settings
454                         // Translate some data
455                         $content['receive']  = translateYesNo($content['receive_warnings']);
456                         $content['interval'] = createFancyTime($content['warning_interval']);
457
458                         // Set message template and subject for admin
459                         $message   = getMessage('SPONSOR_SETTINGS_SAVED');
460                         $templ = 'admin_sponsor_settings';
461                         $subj  = getMessage('ADMIN_SPONSOR_SETTINGS_SUBJ');
462                         break;
463
464                 default: // Unknown sponsor what value!
465                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
466                         $message = sprintf(getMessage('SPONSOR_UNKNOWN_WHAT'), getWhat());
467                         $templ = ''; $subj = '';
468                         break;
469         }
470
471         if (SQL_AFFECTEDROWS() == 1) {
472                 if (!empty($templ) && !empty($subj)) {
473                         // Run SQL command and check for success
474                         $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
475
476                         // Add all data to content
477                         $content['new_data'] = $postData;
478
479                         // Change some data
480                         if (isset($content['gender']))             $content['gender']                  = translateGender($content['gender']);
481                         if (isset($content['new_data']['gender'])) $content['new_data']['gender']      = translateGender($content['new_data']['gender']);
482                         if (isset($content['receive_warnings']))   $content['new_data']['receive']     = translateYesNo($content['new_data']['receive_warnings']);
483                         if (isset($content['warning_interval']))   $content['new_data']['interval']    = createFancyTime($content['new_data']['warning_interval']);
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                                 // Okay send email with confirmation link to new address and with no confirmation link
491                                 // to the old address
492
493                                 // First to old address
494                                 switch (getWhat())
495                                 {
496                                         case 'account': // Change account data
497                                                 $email_msg = loadEmailTemplate('sponsor_change_data', $content);
498                                                 sendEmail($content['email'], getMessage('SPONSOR_ACC_DATA_SUBJ'), $email_msg);
499
500                                                 if ($EMAIL === true) {
501                                                         // Add hash code to content array
502                                                         $content['hash'] = $HASH;
503
504                                                         // Second mail goes to the new address
505                                                         $email_msg = loadEmailTemplate('sponsor_change_email', $content);
506                                                         sendEmail($content['email'], getMessage('SPONSOR_ACC_EMAIL_SUBJ'), $email_msg);
507                                                 }
508                                                 break;
509
510                                         case 'settings': // Change settings
511                                                 // Send email
512                                                 $email_msg = loadEmailTemplate('sponsor_settings', $content);
513                                                 sendEmail($content['email'], getMessage('SPONSOR_SETTINGS_SUBJ'), $email_msg);
514                                                 break;
515                                 }
516                         } // END - if
517                 } // END - if
518         } // END - if
519
520         // Return final message
521         return $message;
522 }
523
524 // [EOF]
525 ?>