2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 04/23/2005 *
4 * =================== Last change: 05/18/2008 *
6 * -------------------------------------------------------------------- *
7 * File : sponsor_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for the sponsor area *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer den Sponsorenbereich *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
46 function handleSponsorRequest ($postData, $update=false, $messageArray=array(), $RET_STATUS=false) {
47 // Init a lot variables
56 'ok', 'edit', 'terms', 'pay_type'
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
73 if (!isEmailValid($v)) {
74 // Email address is not valid
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__);
81 // Is a sponsor alread in the db?
82 if (SQL_NUMROWS($result) == 1) {
84 if ((getWhat() == 'add_sponsor') || ($update)) {
94 SQL_FREERESULT($result);
103 $k = 'password'; $v = md5($v);
107 if (!isUrlValid($v)) $SAVE = false;
111 // Test if there is are time selections
112 convertSelectionsToTimestamp($postData, $DATA, $k, $skip);
116 if ((!empty($k)) && ($skip == false)) {
118 $DATA['keys'][] = $k; $DATA['values'][] = $v;
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';
128 // SQL and message string is empty by default
129 $sql = ''; $message = '';
134 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET ";
135 foreach ($DATA['keys'] as $k => $v) {
136 $sql .= $v."='%s', ";
139 // Remove last ", " from SQL string
140 $sql = substr($sql, 0, -2)." WHERE `id`='%s' LIMIT 1";
141 $DATA['values'][] = bigintval(getRequestParameter('id'));
144 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_UPDATED--}', 'updated', $messageArray);
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';
155 $DATA['values'][] = 'UNCONFIRMED';
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();
164 // Implode all data into strings
165 $keyArray = implode('`, `' , $DATA['keys']);
166 $valueArray = str_repeat("%s', '", count($DATA['values']) - 1);
169 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`' . $keyArray . "`) VALUES ('" . $valueArray . "%s')";
172 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_ADDED--}', 'added', $messageArray);
174 } elseif (($update === true) && (isAdmin())) {
175 // Add all data as hidden data
177 foreach ($postData as $k => $v) {
178 // Do not add 'force' !
180 $OUT .= '<input type="hidden" name="' . secureString($k) . '" value="' . SQL_ESCAPE($v) . '" />';
185 $content['hidden'] = $OUT;
186 $content['email'] = $postData['email'];
188 // Ask for adding a sponsor with same email address
189 loadTemplate('admin_add_sponsor_already', false, $content);
193 $message = getMaskedMessage('SPONSOR_ALREADY_FOUND', $postData['email']);
199 $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
203 if (($update === true) && (isAdmin())) {
204 loadTemplate('admin_settings_saved', false, $message);
208 $message = getMessageFromIndexedArray('{--SPONSOR_DATA_NOT_SAVED--}', 'failed', $messageArray);
209 loadTemplate('admin_settings_saved', false, $message);
212 // Shall we return the status?
213 if ($RET_STATUS === true) return $ret;
217 function sponsorTranslateUserStatus ($status) {
218 // Construct constant name
219 $constantName = sprintf("ACCOUNT_STATUS_%s", $status);
221 // Is the constant there?
222 if (isMessageIdValid($constantName)) {
224 $ret = getMessage($constantName);
227 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
228 $ret = getMaskedMessage('ACCOUNT_STATUS_UNKNOWN_STATUS', $status);
233 // Search for an email address in the database
234 function isSponsorRegisteredWithEmail ($email) {
235 // Do we already have the provided email address in our DB?
236 $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
242 // Wether the current user is a sponsor
243 function isSponsor () {
246 if ((isSessionVariableSet('sponsor_id')) && (isSessionVariableSet('sponsorpass'))) {
247 // Check cookies against database records...
248 $result = SQL_QUERY_ESC("SELECT
251 `{?_MYSQL_PREFIX?}_sponsor_data`
253 `id`='%s' AND `password`='%s' AND `status`='CONFIRMED'
256 bigintval(getSession('sponsor_id')),
257 getSession('sponsorpass')
258 ), __FUNCTION__, __LINE__);
259 if (SQL_NUMROWS($result) == 1) {
265 SQL_FREERESULT($result);
273 function addSponsorMenu ($current) {
275 $WHERE = " AND `active`='Y'";
276 if (isAdmin()) $WHERE = '';
278 // Load main menu entries
279 $result_main = SQL_QUERY("SELECT
280 `action` AS `main_action`, `title` AS `main_title`
282 `{?_MYSQL_PREFIX?}_sponsor_menu`
284 (`what`='' OR `what` IS NULL)
287 `sort` ASC", __FUNCTION__, __LINE__);
288 if (!SQL_HASZERONUMS($result_main)) {
289 // Load every menu and it's sub menus
290 while ($content = SQL_FETCHARRAY($result_main)) {
292 $result_sub = SQL_QUERY_ESC("SELECT
293 `what` AS `sub_what`, `title` AS `sub_title`
295 `{?_MYSQL_PREFIX?}_sponsor_menu`
303 array($content['main_action']), __FUNCTION__, __LINE__);
304 if (!SQL_HASZERONUMS($result_sub)) {
307 while ($content2 = SQL_FETCHARRAY($result_sub)) {
309 $content = merge_array($content, $content2);
311 // Check if current selected menu is matching the loaded one
312 if ($current == $content['sub_what']) $content['sub_title'] = '<strong>' . $content['sub_title'] . '</strong>';
314 // Prepare data for the sub template
316 'what' => $content['sub_what'],
317 'title' => $content['sub_title']
321 $SUB .= loadTemplate('sponsor_what', true, $content);
324 // Prepare data for the main template
326 'title' => $content['main_title'],
330 // Load menu template
331 $OUT .= loadTemplate('sponsor_action', true, $content);
333 // No sub menus active
334 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_SUB_MENUS_ACTIVE--}');
338 SQL_FREERESULT($result_sub);
341 // No main menus active
342 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_MAIN_MENUS_ACTIVE--}');
346 SQL_FREERESULT($result_main);
353 function addSponsorContent ($what) {
355 $INC = sprintf("inc/modules/sponsor/%s.php", $what);
356 if (isIncludeReadable($INC)) {
357 // Every sponsor action will output nothing directly. It will be written into $OUT!
358 loadIncludeOnce($INC);
361 $OUT .= loadTemplate('admin_settings_saved', true, getMaskedMessage('SPONSOR_CONTENT_404', $what));
369 function updateSponsorLogin () {
375 // Update last online timestamp
376 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_sponsor_data`
377 SET `last_online`=UNIX_TIMESTAMP()
378 WHERE `id`='%s' AND `password`='%s' LIMIT 1",
380 bigintval(getSession('sponsor_id')),
381 getSession('sponsorpass')
382 ), __FUNCTION__, __LINE__);
384 // This update went fine?
385 $login = (SQL_AFFECTEDROWS() == 1);
392 // Saves sponsor's data
393 function saveSponsorData ($postData, $content) {
396 // Unsecure data which we don't want
397 $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
398 'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
399 'ok', 'pass1', 'pass2');
401 // Set default message ("not saved")
402 $message = '{--SPONSOR_ACCOUNT_DATA_NOT_SAVED--}';
404 // Check for submitted passwords
405 if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
406 // Are both passwords the same?
407 if ($postData['pass1'] == $postData['pass2']) {
408 // Okay, then set password and remove pass1 and pass2
409 $postData['password'] = md5($postData['pass1']);
413 // Remove all (maybe spoofed) unsafe data from array
414 foreach ($UNSAFE as $remove) {
415 unset($postData[$remove]);
418 // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
422 // Prepare SQL string
423 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
424 foreach ($postData as $key => $value) {
425 // Mmmmm, too less security here???
426 $sql .= " `" . secureString($key) . "`='%s',";
428 // We will secure this later inside the SQL_QUERY_ESC() function
429 $DATA[] = secureString($value);
432 // Check if email has changed
433 if ((!empty($content['email'])) && (!empty($postData['email']))) {
434 if ($content['email'] != $postData['email']) {
435 // Change email address
438 // Okay, has changed then add status with UNCONFIRMED and new hash code
439 $sql .= " `status`='EMAIL', `hash`='%s',";
441 // Generate hash code
442 $HASH = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
447 // Remove last commata
448 $sql = substr($sql, 0, -1);
451 $sql .= " WHERE `id`=%s AND `password`='%s' LIMIT 1";
452 $DATA[] = bigintval(getSession('sponsor_id'));
453 $DATA[] = getSession('sponsorpass');
455 // Saving data was completed... ufff...
457 case 'account': // Change account data
458 if ($EMAIL === true) {
459 $message = '{--SPONSOR_ACCOUNT_EMAIL_CHANGED--}';
460 $templ = 'admin_sponsor_change_email';
461 $subj = '{--ADMIN_SPONSOR_ACC_EMAIL_SUBJECT--}';
463 $message = '{--SPONSOR_ACCOUNT_DATA_SAVED--}';
464 $templ = 'admin_sponsor_change_data';
465 $subj = '{--ADMIN_SPONSOR_ACC_DATA_SUBJECT--}';
469 case 'settings': // Change settings
470 // Set message template and subject for admin
471 $message = '{--SPONSOR_SETTINGS_SAVED--}';
472 $templ = 'admin_sponsor_settings';
473 $subj = '{--ADMIN_SPONSOR_SETTINGS_SUBJECT--}';
476 default: // Unknown sponsor what value!
477 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
478 $message = getMaskedMessage('SPONSOR_UNKNOWN_WHAT', getWhat());
484 // Has an entry updated?
485 if (SQL_AFFECTEDROWS() == 1) {
486 // Template and subject are set?
487 if (!empty($templ) && !empty($subj)) {
488 // Run SQL command and check for success
489 $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
491 // Add all data to content
492 $content['new_data'] = $postData;
494 // Send email to admins
495 sendAdminNotification($subj, $templ, $content);
497 // Shall we send mail to the sponsor's new email address?
498 if ($content['receive_warnings'] == 'Y') {
500 * Okay send email with confirmation link to new address and with no confirmation link
501 * to the old address.
504 // First to old address
506 case 'account': // Change account data
507 $email_msg = loadEmailTemplate('sponsor_change_data', $content);
508 sendEmail($content['email'], '{--SPONSOR_ACC_DATA_SUBJECT--}', $email_msg);
510 if ($EMAIL === true) {
511 // Add hash code to content array
512 $content['hash'] = $HASH;
514 // Second mail goes to the new address
515 $email_msg = loadEmailTemplate('sponsor_change_email', $content);
516 sendEmail($content['email'], '{--SPONSOR_ACC_EMAIL_SUBJECT--}', $email_msg);
520 case 'settings': // Change settings
522 $email_msg = loadEmailTemplate('sponsor_settings', $content);
523 sendEmail($content['email'], '{--SPONSOR_SETTINGS_SUBJECT--}', $email_msg);
530 // Return final message
534 // Create email link to sponsor's account
535 function generateSponsorEmailLink ($email, $mod = 'admin') {
536 // Show contact link only if sponsor is confirmed by default
537 $locked = " AND `status`='CONFIRMED'";
539 // But admins shall always see it
540 if (isAdmin()) $locked = '';
542 $result = SQL_QUERY_ESC("SELECT
545 `{?_MYSQL_PREFIX?}_sponsor_data`
547 `email`='%s'" . $locked."
549 array($email), __FUNCTION__, __LINE__);
550 if (SQL_NUMROWS($result) == 1) {
552 list($sponsor_id) = SQL_FETCHROW($result);
554 // Rewrite email address to contact link
555 $email = '{%url=modules.php?module=' . $mod . '&what=sponsor_contct&sponsor_id=' . bigintval($sponsor_id) . '%}';
559 SQL_FREERESULT($result);
561 // Return rewritten (?) email address
565 // Processes a sponsor request and handles it
566 function doProcessSponsorFormRequest ($messageArray = array()) {
570 // Handle the request
571 $status = handleSponsorRequest(postRequestArray(), true, $messageArray, true);
573 // Check the status of the registration process
575 case 'added': // Sponsor successfully added with account status = UNCONFIRMED!
576 // Check for his id number
577 $result = SQL_QUERY_ESC("SELECT `id`, `hash` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `email`='%s' LIMIT 1",
578 array(postRequestParameter('email')), __FILE__, __LINE__);
579 if (SQL_NUMROWS($result) == 1) {
580 // id found so let's load it for the confirmation email
581 list($id, $hash) = SQL_FETCHROW($result);
583 // Prepare data for the email template
584 $content['id'] = $id;
585 $content['hash'] = $hash;
586 $content['email'] = secureString(postRequestParameter('email'));
587 $content['surname'] = secureString(postRequestParameter('surname'));
588 $content['family'] = secureString(postRequestParameter('family'));
589 $content['timestamp'] = generateDateTime(time(), 0);
590 $content['password'] = secureString(postRequestParameter('pass1'));
592 // Generate email and send it to the new sponsor
593 $message = loadEmailTemplate('sponsor_confirm', $hash);
594 sendEmail(postRequestParameter('email'), '{--SPONSOR_PLEASE_CONFIRM_SUBJECT--}', $message);
596 // Send mail to admin
597 sendAdminNotification('{--ADMIN_NEW_SPONSOR--}', 'admin_sponsor_reg', $hash);
599 // Output message: DONE
600 $message = $messageArray['added'];
602 // Sponsor account not found???
603 $message = getMaskedMessage('SPONSOR_EMAIL_404', postRequestParameter('email'));
607 SQL_FREERESULT($result);
611 logDebugMessage(__FILE__, __LINE__, sprintf("Unknown status %s detected.", $status));
613 // Message for testing admin
614 $message = getMaskedMessage('ADMIN_SPONSOR_UNKNOWN_STATUS', $status);
616 // Message for the guest
617 $message = getMaskedMessage('SPONSOR_UNKNOWN_STATUS', $status);