Made mails debugable without messing the output, fixes for forced sponsor registratio...
[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                                 } else {
154                                         // Guest area
155                                         $DATA['values'][] = 'UNCONFIRMED';
156
157                                         // Generate hash code
158                                         $DATA['keys'][] = 'hash';
159                                         $DATA['values'][] = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
160                                         $DATA['keys'][] = 'remote_addr';
161                                         $DATA['values'][] = detectRemoteAddr();
162                                 }
163
164                                 // Search the entry
165                                 $key = array_search('force', $DATA['keys']);
166
167                                 // Remove force from both arrays
168                                 unset($DATA['keys'][$key]);
169                                 unset($DATA['values'][$key]);
170
171                                 // Implode all data into strings
172                                 $keyArray   = implode('`, `'  , $DATA['keys']);
173                                 $valueArray = str_repeat("%s', '", count($DATA['values']) - 1);
174
175                                 // Generate string
176                                 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`' . $keyArray . "`) VALUES ('" . $valueArray . "%s')";
177
178                                 // Generate message
179                                 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_ADDED--}', 'added', $messageArray);
180                                 $ret = 'added';
181                         } elseif (($update === true) && (isAdmin())) {
182                                 // Add all data as hidden data
183                                 $OUT = '';
184                                 foreach ($postData as $k => $v) {
185                                         // Do not add 'force' !
186                                         if ($k != 'force') {
187                                                 $OUT .= '<input type="hidden" name="' . secureString($k) . '" value="' . SQL_ESCAPE($v) . '" />';
188                                         } // END - if
189                                 } // END - foreach
190
191                                 // Remember data
192                                 $content['hidden'] = $OUT;
193                                 $content['email']  = $postData['email'];
194
195                                 // Ask for adding a sponsor with same email address
196                                 loadTemplate('admin_add_sponsor_already', false, $content);
197                                 return;
198                         } else {
199                                 // Already added!
200                                 $message = getMaskedMessage('SPONSOR_ALREADY_FOUND', $postData['email']);
201                                 $ret = 'already';
202                         }
203
204                         if (!empty($sql)) {
205                                 // Run SQL command
206                                 $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
207                         } // END - if
208                 } else {
209                         // Error found!
210                         $message = getMessageFromIndexedArray('{--SPONSOR_DATA_NOT_SAVED--}', 'failed', $messageArray);
211                         loadTemplate('admin_settings_saved', false, $message);
212                 }
213
214         // Always return the status
215         return $ret;
216 }
217
218 //
219 function sponsorTranslateUserStatus ($status) {
220         // Construct constant name
221         $constantName = sprintf("ACCOUNT_STATUS_%s", $status);
222
223         // Is the constant there?
224         if (isMessageIdValid($constantName)) {
225                 // Then use it
226                 $ret = getMessage($constantName);
227         } else {
228                 // Not found!
229                 /* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
230                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
231                 $ret = getMaskedMessage('ACCOUNT_STATUS_UNKNOWN_STATUS', $status);
232         }
233
234         // Return status
235         return $ret;
236 }
237
238 // Search for an email address in the database
239 function isSponsorRegisteredWithEmail ($email) {
240         // Do we already have the provided email address in our DB?
241         $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
242
243         // Return result
244         return $ret;
245 }
246
247 // Wether the current user is a sponsor
248 function isSponsor () {
249         // Failed...
250         $ret = false;
251         if ((isSessionVariableSet('sponsor_id')) && (isSessionVariableSet('sponsorpass'))) {
252                 // Check cookies against database records...
253                 $result = SQL_QUERY_ESC("SELECT
254         `id`
255 FROM
256         `{?_MYSQL_PREFIX?}_sponsor_data`
257 WHERE
258         `id`='%s' AND `password`='%s' AND `status`='CONFIRMED'
259 LIMIT 1",
260                         array(
261                                 bigintval(getSession('sponsor_id')),
262                                 getSession('sponsorpass')
263                         ), __FUNCTION__, __LINE__);
264                 if (SQL_NUMROWS($result) == 1) {
265                         // All is fine
266                         $ret = true;
267                 } // END - if
268
269                 // Free memory
270                 SQL_FREERESULT($result);
271         } // END - if
272
273         // Return status
274         return $ret;
275 }
276
277 //
278 function addSponsorMenu ($current) {
279         $OUT = '';
280         $WHERE = " AND `active`='Y'";
281         if (isAdmin()) $WHERE = '';
282
283         // Load main menu entries
284         $result_main = SQL_QUERY("SELECT
285         `action` AS `main_action`, `title` AS `main_title`
286 FROM
287         `{?_MYSQL_PREFIX?}_sponsor_menu`
288 WHERE
289         (`what`='' OR `what` IS NULL)
290         " . $WHERE . "
291 ORDER BY
292         `sort` ASC", __FUNCTION__, __LINE__);
293         if (!SQL_HASZERONUMS($result_main)) {
294                 // Load every menu and it's sub menus
295                 while ($content = SQL_FETCHARRAY($result_main)) {
296                         // Load sub menus
297                         $result_sub = SQL_QUERY_ESC("SELECT
298         `what` AS `sub_what`, `title` AS `sub_title`
299 FROM
300         `{?_MYSQL_PREFIX?}_sponsor_menu`
301 WHERE
302         `action`='%s' AND
303         `what` != '' AND
304         `what` IS NOT NULL
305         " . $WHERE . "
306 ORDER BY
307         `sort` ASC",
308                         array($content['main_action']), __FUNCTION__, __LINE__);
309                         if (!SQL_HASZERONUMS($result_sub)) {
310                                 // Load sub menus
311                                 $SUB = '';
312                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
313                                         // Merge both arrays
314                                         $content = merge_array($content, $content2);
315
316                                         // Check if current selected menu is matching the loaded one
317                                         if ($current == $content['sub_what']) $content['sub_title'] = '<strong>' . $content['sub_title'] . '</strong>';
318
319                                         // Prepare data for the sub template
320                                         $content = array(
321                                                 'what'  => $content['sub_what'],
322                                                 'title' => $content['sub_title']
323                                         );
324
325                                         // Load row template
326                                         $SUB .= loadTemplate('sponsor_what', true, $content);
327                                 }
328
329                                 // Prepare data for the main template
330                                 $content = array(
331                                         'title' => $content['main_title'],
332                                         'menu'  => $SUB
333                                 );
334
335                                 // Load menu template
336                                 $OUT .= loadTemplate('sponsor_action', true, $content);
337                         } else {
338                                 // No sub menus active
339                                 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_SUB_MENUS_ACTIVE--}');
340                         }
341
342                         // Free memory
343                         SQL_FREERESULT($result_sub);
344                 }
345         } else {
346                 // No main menus active
347                 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_MAIN_MENUS_ACTIVE--}');
348         }
349
350         // Free memory
351         SQL_FREERESULT($result_main);
352
353         // Return content
354         return $OUT;
355 }
356
357 //
358 function addSponsorContent ($what) {
359         $OUT = '';
360         $INC = sprintf("inc/modules/sponsor/%s.php", $what);
361         if (isIncludeReadable($INC)) {
362                 // Every sponsor action will output nothing directly. It will be written into $OUT!
363                 loadIncludeOnce($INC);
364         } else {
365                 // File not found!
366                 $OUT .= loadTemplate('admin_settings_saved', true, getMaskedMessage('SPONSOR_CONTENT_404', $what));
367         }
368
369         // Return content
370         return $OUT;
371 }
372
373 //
374 function updateSponsorLogin () {
375         // Failed by default
376         $login = false;
377
378         // Is sponsor?
379         if (isSponsor()) {
380                 // Update last online timestamp
381                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_sponsor_data`
382 SET `last_online`=UNIX_TIMESTAMP()
383 WHERE `id`='%s' AND `password`='%s' LIMIT 1",
384                         array(
385                                 bigintval(getSession('sponsor_id')),
386                                 getSession('sponsorpass')
387                         ), __FUNCTION__, __LINE__);
388
389                 // This update went fine?
390                 $login = (SQL_AFFECTEDROWS() == 1);
391         }
392
393         // Return status
394         return $login;
395 }
396
397 // Saves sponsor's data
398 function saveSponsorData ($postData, $content) {
399         $EMAIL = false;
400
401         // Unsecure data which we don't want
402         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
403                         'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
404                         'ok', 'pass1', 'pass2');
405
406         // Set default message ("not saved")
407         $message = '{--SPONSOR_ACCOUNT_DATA_NOT_SAVED--}';
408
409         // Check for submitted passwords
410         if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
411                 // Are both passwords the same?
412                 if ($postData['pass1'] == $postData['pass2']) {
413                         // Okay, then set password and remove pass1 and pass2
414                         $postData['password'] = md5($postData['pass1']);
415                 } // END - if
416         } // END - if
417
418         // Remove all (maybe spoofed) unsafe data from array
419         foreach ($UNSAFE as $remove) {
420                 unset($postData[$remove]);
421         } // END - foreach
422
423         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
424         // secure the data
425         $DATA = array();
426
427         // Prepare SQL string
428         $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
429         foreach ($postData as $key => $value) {
430                 // Mmmmm, too less security here???
431                 $sql   .= " `" . secureString($key) . "`='%s',";
432
433                 // We will secure this later inside the SQL_QUERY_ESC() function
434                 $DATA[] = secureString($value);
435         } // END - foreach
436
437         // Check if email has changed
438         if ((!empty($content['email'])) && (!empty($postData['email']))) {
439                 if ($content['email'] != $postData['email']) {
440                         // Change email address
441                         $EMAIL = true;
442
443                         // Okay, has changed then add status with UNCONFIRMED and new hash code
444                         $sql .= " `status`='EMAIL', `hash`='%s',";
445
446                         // Generate hash code
447                         $HASH = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
448                         $DATA[] = $HASH;
449                 } // END - if
450         } // END - if
451
452         // Remove last commata
453         $sql = substr($sql, 0, -1);
454
455         // Add SQL tail data
456         $sql .= " WHERE `id`=%s AND `password`='%s' LIMIT 1";
457         $DATA[] = bigintval(getSession('sponsor_id'));
458         $DATA[] = getSession('sponsorpass');
459
460         // Saving data was completed... ufff...
461         switch (getWhat()) {
462                 case 'account': // Change account data
463                         if ($EMAIL === true) {
464                                 $message = '{--SPONSOR_ACCOUNT_EMAIL_CHANGED--}';
465                                 $templ   = 'admin_sponsor_change_email';
466                                 $subj    = '{--ADMIN_SPONSOR_ACC_EMAIL_SUBJECT--}';
467                         } else {
468                                 $message = '{--SPONSOR_ACCOUNT_DATA_SAVED--}';
469                                 $templ   = 'admin_sponsor_change_data';
470                                 $subj    = '{--ADMIN_SPONSOR_ACC_DATA_SUBJECT--}';
471                         }
472                         break;
473
474                 case 'settings': // Change settings
475                         // Set message template and subject for admin
476                         $message = '{--SPONSOR_SETTINGS_SAVED--}';
477                         $templ   = 'admin_sponsor_settings';
478                         $subj    = '{--ADMIN_SPONSOR_SETTINGS_SUBJECT--}';
479                         break;
480
481                 default: // Unknown sponsor what value!
482                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
483                         $message = getMaskedMessage('SPONSOR_UNKNOWN_WHAT', getWhat());
484                         $templ   = '';
485                         $subj    = '';
486                         break;
487         } // END - switch
488
489         // Has an entry updated?
490         if (SQL_AFFECTEDROWS() == 1) {
491                 // Template and subject are set?
492                 if (!empty($templ) && !empty($subj)) {
493                         // Run SQL command and check for success
494                         $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
495
496                         // Add all data to content
497                         $content['new_data'] = $postData;
498
499                         // Send email to admins
500                         sendAdminNotification($subj, $templ, $content);
501
502                         // Shall we send mail to the sponsor's new email address?
503                         if ($content['receive_warnings'] == 'Y') {
504                                 /*
505                                  * Okay send email with confirmation link to new address and with no confirmation link
506                                  * to the old address.
507                                  */
508
509                                 // First to old address
510                                 switch (getWhat()) {
511                                         case 'account': // Change account data
512                                                 $email_msg = loadEmailTemplate('sponsor_change_data', $content);
513                                                 sendEmail($content['email'], '{--SPONSOR_ACC_DATA_SUBJECT--}', $email_msg);
514
515                                                 if ($EMAIL === true) {
516                                                         // Add hash code to content array
517                                                         $content['hash'] = $HASH;
518
519                                                         // Second mail goes to the new address
520                                                         $email_msg = loadEmailTemplate('sponsor_change_email', $content);
521                                                         sendEmail($content['email'], '{--SPONSOR_ACC_EMAIL_SUBJECT--}', $email_msg);
522                                                 } // END - if
523                                                 break;
524
525                                         case 'settings': // Change settings
526                                                 // Send email
527                                                 $email_msg = loadEmailTemplate('sponsor_settings', $content);
528                                                 sendEmail($content['email'], '{--SPONSOR_SETTINGS_SUBJECT--}', $email_msg);
529                                                 break;
530                                 } // END - switch
531                         } // END - if
532                 } // END - if
533         } // END - if
534
535         // Return final message
536         return $message;
537 }
538
539 // Create email link to sponsor's account
540 function generateSponsorEmailLink ($email, $mod = 'admin') {
541         // Show contact link only if sponsor is confirmed by default
542         $locked = " AND `status`='CONFIRMED'";
543
544         // But admins shall always see it
545         if (isAdmin()) $locked = '';
546
547         $result = SQL_QUERY_ESC("SELECT
548         `id`
549 FROM
550         `{?_MYSQL_PREFIX?}_sponsor_data`
551 WHERE
552         `email`='%s'" . $locked."
553 LIMIT 1",
554                 array($email), __FUNCTION__, __LINE__);
555         if (SQL_NUMROWS($result) == 1) {
556                 // Load sponsor_id
557                 list($sponsor_id) = SQL_FETCHROW($result);
558
559                 // Rewrite email address to contact link
560                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=sponsor_contct&amp;sponsor_id=' . bigintval($sponsor_id) . '%}';
561         } // END - if
562
563         // Free memory
564         SQL_FREERESULT($result);
565
566         // Return rewritten (?) email address
567         return $email;
568 }
569
570 // Processes a sponsor request and handles it
571 function doProcessSponsorFormRequest ($messageArray = array()) {
572         // Default message
573         $message = '';
574
575         // Handle the request
576         $status = handleSponsorRequest(postRequestArray(), true, $messageArray, true);
577
578         // Check the status of the registration process
579         switch ($status) {
580                 case 'added': // Sponsor successfully added with account status = UNCONFIRMED!
581                         // Check for his id number
582                         $result = SQL_QUERY_ESC("SELECT `id`, `hash` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `email`='%s' LIMIT 1",
583                                 array(postRequestParameter('email')), __FILE__, __LINE__);
584                         if (SQL_NUMROWS($result) == 1) {
585                                 // id found so let's load it for the confirmation email
586                                 list($id, $hash) = SQL_FETCHROW($result);
587
588                                 // Prepare data for the email template
589                                 $content['id']        = $id;
590                                 $content['hash']      = $hash;
591                                 $content['email']     = secureString(postRequestParameter('email'));
592                                 $content['surname']   = secureString(postRequestParameter('surname'));
593                                 $content['family']    = secureString(postRequestParameter('family'));
594                                 $content['timestamp'] = generateDateTime(time(), 0);
595                                 $content['password']  = secureString(postRequestParameter('pass1'));
596
597                                 // Generate email and send it to the new sponsor
598                                 $message = loadEmailTemplate('sponsor_confirm', $hash);
599                                 sendEmail(postRequestParameter('email'), '{--SPONSOR_PLEASE_CONFIRM_SUBJECT--}', $message);
600
601                                 // Send mail to admin
602                                 sendAdminNotification('{--ADMIN_NEW_SPONSOR--}', 'admin_sponsor_reg', $hash);
603
604                                 // Output message: DONE
605                                 $message = $messageArray['added'];
606                         } else {
607                                 // Sponsor account not found???
608                                 $message = getMaskedMessage('SPONSOR_EMAIL_404', postRequestParameter('email'));
609                         }
610
611                         // Free memory
612                         SQL_FREERESULT($result);
613                         break;
614
615                 default:
616                         logDebugMessage(__FILE__, __LINE__, sprintf("Unknown status %s detected.", $status));
617                         if (!isAdmin()) {
618                                 // Message for testing admin
619                                 $message = getMaskedMessage('ADMIN_SPONSOR_UNKNOWN_STATUS', $status);
620                         } else {
621                                 // Message for the guest
622                                 $message = getMaskedMessage('SPONSOR_UNKNOWN_STATUS', $status);
623                         }
624                         break;
625         }
626
627         // Return message
628         return $message;
629 }
630
631 // [EOF]
632 ?>