But only when it is not empty
[mailer.git] / inc / referral-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/12/2011 *
4  * ===================                          Last change: 07/12/2011 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : referral-functions.php                           *
8  * -------------------------------------------------------------------- *
9  * Short description : All referral system functions                    *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle zum Referral-System gehoerenden Funktionen  *
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 - 2013 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 // Initializes the referral system
44 function initReferralSystem () {
45         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' Referral system initialized!');
46         $GLOBALS['ref_level']  = NULL;
47         $GLOBALS['ref_system'] = TRUE;
48 }
49
50 // Getter fro ref level percents
51 function getReferralLevelPercents ($level) {
52         // Default is zero
53         $data['percents'] = '0';
54
55         // Is there cache?
56         if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
57                 // First look for level
58                 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
59                 if ($key !== FALSE) {
60                         // Entry found
61                         $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
62
63                         // Count cache hit
64                         incrementStatsEntry('cache_hits');
65                 } // END - if
66         } elseif (!isExtensionActive('cache')) {
67                 // Get referral data
68                 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`=%s LIMIT 1",
69                         array(bigintval($level)), __FUNCTION__, __LINE__);
70
71                 // Entry found?
72                 if (SQL_NUMROWS($result_level) == 1) {
73                         // Get percents
74                         $data = SQL_FETCHARRAY($result_level);
75                 } // END - if
76
77                 // Free result
78                 SQL_FREERESULT($result_level);
79         }
80
81         // Return percent
82         return $data['percents'];
83 }
84
85 /**
86  * Dynamic Referral and points system, can also send mails!
87  *
88  * subject       = Subject line, write in lower-case letters and underscore is allowed
89  * userid        = Referral id wich should receive...
90  * points        = ... xxx points
91  * refid         = inc/modules/guest/what-confirm.php need this
92  */
93 function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NULL) {
94         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',refid=' . convertNullToZero($refid) . ' - ENTERED!');
95         // By default nothing has been added
96         $added = FALSE;
97
98         // Determine payment method and notification
99         $paymentMethod = strtoupper(getPaymentMethodFromSubject($subject));
100         $sendNotify    = isPaymentRecipientNotificationEnabled($subject);
101
102         // When $userid is NULL add points to jackpot
103         if ((!isValidId($userid)) && ($paymentMethod == 'DIRECT') && (isExtensionActive('jackpot'))) {
104                 // Add points to jackpot only in DIRECT mode
105                 return addPointsToJackpot($points);
106         } // END - if
107
108         // Set userid as current
109         setCurrentUserId($userid);
110
111         // Check user account
112         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify));
113         if (fetchUserData($userid)) {
114                 // Determine whether the user has some mails to click before he/she gets the points
115                 $isLocked = ifUserPointsLocked($userid);
116
117                 // Detect database column
118                 $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $isLocked);
119
120                 // Get percents
121                 $percents = getReferralLevelPercents($GLOBALS['ref_level']);
122                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ',percents=' . $percents . ',mode=' . $paymentMethod . ',pointsColumn=' . $pointsColumn . ',isLocked=' . intval($isLocked) . ',refid=' . getUserData('refid'));
123
124                 // Some percents found?
125                 if ($percents > 0) {
126                         // Calculate new points
127                         $ref_points = $points * $percents / 100;
128
129                         // Pay refback here if level > 0 and in ref-mode
130                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',paymentMethod=' . $paymentMethod);
131                         if (($userid != $refid) && (substr($subject, 0, 8) != 'refback:') &&($paymentMethod == 'REFERRAL') && (isValidId(getUserData('refid'))) && (isExtensionActive('refback'))) {
132                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - BEFORE!');
133                                 $ref_points = addRefbackPoints($userid, getUserData('refid'), $points, $ref_points);
134                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - AFTER!');
135                         } // END - if
136
137                         // Update points...
138                         if (is_null($GLOBALS['ref_level'])) {
139                                 // Level NULL (self)
140                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth` IS NULL LIMIT 1",
141                                         array(
142                                                 $pointsColumn,
143                                                 $pointsColumn,
144                                                 $ref_points,
145                                                 bigintval($userid)
146                                         ), __FUNCTION__, __LINE__);
147                         } else {
148                                 // Level 1+
149                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`=%s LIMIT 1",
150                                         array(
151                                                 $pointsColumn,
152                                                 $pointsColumn,
153                                                 $ref_points,
154                                                 bigintval($userid),
155                                                 bigintval($GLOBALS['ref_level'])
156                                         ), __FUNCTION__, __LINE__);
157                         }
158                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'pointsColumn='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.convertNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - UPDATE! ('.SQL_AFFECTEDROWS().')');
159
160                         // No entry updated?
161                         if (SQL_HASZEROAFFECTED()) {
162                                 // First ref in this level! :-)
163                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`, `ref_depth`, `%s`) VALUES (%s, %s, %s)",
164                                         array(
165                                                 $pointsColumn,
166                                                 bigintval($userid),
167                                                 convertZeroToNull($GLOBALS['ref_level']),
168                                                 $ref_points
169                                         ), __FUNCTION__, __LINE__);
170                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.convertNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - INSERTED! ('.SQL_AFFECTEDROWS().')');
171                         } // END - if
172
173                         // Check affected rows
174                         $added = (SQL_AFFECTEDROWS() == 1);
175                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added=' . intval($added) . ' - BEFORE FILTER');
176
177                         // Prepare data for the filter
178                         $filterData = array(
179                                 'subject'     => $subject,
180                                 'userid'      => $userid,
181                                 'points'      => $points,
182                                 'ref_points'  => $ref_points,
183                                 'column'      => $pointsColumn,
184                                 'notify'      => $sendNotify,
185                                 'refid'       => $refid,
186                                 'locked'      => $isLocked,
187                                 'points_mode' => 'add',
188                                 'add_mode'    => $paymentMethod,
189                                 'added'       => $added
190                         );
191
192                         // Filter it now
193                         $filterData = runFilterChain('post_add_points', $filterData);
194
195                         // Extract $added
196                         $added = $filterData['added'];
197                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added=' . intval($added) . ' - AFTER FILTER');
198
199                         // Debug message
200                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . $refid . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify) . ',isLocked=' . intval($isLocked));
201
202                         // Send "referral confirmed" mails out?
203                         if ((isValidUserid($refid)) && ($refid != $userid) && ($sendNotify === TRUE)) {
204                                 // Calculate the referral's points and percents
205                                 $percentsReferral = getReferralLevelPercents($GLOBALS['ref_level'] + 1);
206
207                                 // Calculate new points
208                                 $ref_points = $ref_points * $percentsReferral / 100;
209
210                                 // Prepare content
211                                 $content = array(
212                                         'userid'         => bigintval($userid),
213                                         'refid'          => $refid,
214                                         'level'          => bigintval($GLOBALS['ref_level'] + 1),
215                                         'percents'       => $percentsReferral,
216                                         'points'         => ($paymentMethod == 'REFERRAL' ? $ref_points : '0'),
217                                         'payment_method' => $paymentMethod,
218                                         'subject'        => $subject,
219                                 );
220
221                                 // Load email template
222                                 $message = loadEmailTemplate('guest_user_confirmed_referral', $content, bigintval($userid));
223
224                                 // Send email
225                                 sendEmail($userid, '{--THANKS_REFERRAL_ONE_SUBJECT--}', $message);
226                         } // END - if
227
228                         // Points updated, maybe I shall send him an email?
229                         if (($sendNotify === TRUE) && ($isLocked === FALSE)) {
230                                 // "Explode" subject
231                                 $subjectArray = explode(':', $subject);
232                                 $subjectUserid = (isset($subjectArray[1])) ? $subjectArray[1] : '0';
233
234                                 // Generic delivery of mails, so prepare data
235                                 $content = array(
236                                         'userid'         => $userid,
237                                         'percents'       => $percents,
238                                         'level'          => bigintval($GLOBALS['ref_level']),
239                                         'points'         => $ref_points,
240                                         'column'         => $pointsColumn,
241                                         'subject'        => $subjectArray[0],
242                                         'subject_userid' => $subjectUserid,
243                                         'payment_method' => $paymentMethod,
244                                 );
245
246                                 // Load email template
247                                 $message = loadEmailTemplate('member_' . $subjectArray[0] . '_' . strtolower($paymentMethod), $content, $userid);
248
249                                 // Send email
250                                 sendEmail($userid, '{%message,MEMBER_' . $paymentMethod . '_' . strtoupper($subjectArray[0]) . '_SUBJECT=' . $subjectUserid . '%}', $message);
251
252                                 // Also send admin notification
253                                 sendAdminNotification(
254                                         // Subject
255                                         '{%message,ADMIN_' . $paymentMethod . '_' . strtoupper($subjectArray[0]) . '_SUBJECT=' . $subjectUserid . '%}',
256                                         // Template name
257                                         'admin_' . $subjectArray[0] . '_' . strtolower($paymentMethod),
258                                         // Template content (data array)
259                                         $content,
260                                         // User id
261                                         $userid
262                                 );
263                         } // END - if
264
265                         // Increase referral level, if payment method is 'REFERRAL'
266                         if ($paymentMethod == 'REFERRAL') {
267                                 // Increase it
268                                 $GLOBALS['ref_level']++;
269                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level increased, ref_level=' . convertNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
270                         } elseif (isDebugModeEnabled()) {
271                                 // Not increasing referral level, DIRECT payment method
272                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level *NOT* increased, ref_level=' . convertNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
273                         }
274
275                         // Remove any :x
276                         $subject = removeDoubleDotFromSubject($subject);
277
278                         // Maybe there's another ref?
279                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'points=' . $points . ',refid(var|data)=' . convertNullToZero($refid) . '|' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod . ',subject=' . $subject . ',ref_level=' . $GLOBALS['ref_level']);
280                         if (($paymentMethod == 'REFERRAL') && (isValidId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid)) {
281                                 // Is _ref there?
282                                 if (substr($subject, -4, 4) == '_ref') {
283                                         // Then remove it, no double _ref suffix!
284                                         $subject = substr($subject, 0, -4);
285                                 } // END - if
286
287                                 // Then let's credit him here...
288                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',ref_points=' . $ref_points . ',added[' . gettype($added) . ']=' . intval($added) . ',ref_level=' . $GLOBALS['ref_level'] . ' - ADVANCE!');
289                                 $added = ($added && addPointsThroughReferralSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, getFetchedUserData('userid', getUserData('refid'), 'refid')));
290                         } // END - if
291                 } // END - if
292         } // END - if
293
294         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',sendNotify=' . intval($sendNotify) . ',refid=' . convertNullToZero($refid) . ',paymentMethod=' . $paymentMethod . ' - EXIT!');
295         return $added;
296 }
297
298 // Updates the referral counter
299 function updateReferralCounter ($userid) {
300         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
301         // Init referral id
302         $refid = NULL;
303
304         // Check for his referral
305         if (fetchUserData($userid)) {
306                 // Get it
307                 $refid = getUserData('refid');
308                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertZeroToNull($refid) . ' - FETCHED!');
309         } // END - if
310
311         // Init entries
312         if (empty($GLOBALS['cache_array']['ref_level'][$userid])) {
313                 $GLOBALS['cache_array']['ref_level'][$userid] = NULL;
314         } // END - if
315         if (empty($GLOBALS['cache_array']['ref_level'][$refid])) {
316                 $GLOBALS['cache_array']['ref_level'][$refid] = NULL;
317         } // END - if
318
319         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertZeroToNull($refid));
320
321         // When he has a referral...
322         if ((isValidId($refid)) && ($refid != $userid)) {
323                 // Move to next referral level and count his counter one up
324                 $GLOBALS['cache_array']['ref_level'][$refid] = $GLOBALS['cache_array']['ref_level'][$userid] + 1;
325                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid(' . $refid . ')=' . $GLOBALS['cache_array']['ref_level'][$refid] . ' - ADVANCED!');
326
327                 // Update counter
328                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`=%s LIMIT 1",
329                         array(
330                                 bigintval($refid),
331                                 bigintval($GLOBALS['cache_array']['ref_level'][$refid])
332                         ), __FUNCTION__, __LINE__);
333
334                 // When no entry was updated then we have to create it here
335                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . $refid . ',level=' . $GLOBALS['cache_array']['ref_level'][$refid] . ',updated=' . SQL_AFFECTEDROWS());
336                 if (SQL_HASZEROAFFECTED()) {
337                         // First count!
338                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
339                                 array(
340                                         bigintval($refid),
341                                         convertZeroToNull($GLOBALS['cache_array']['ref_level'][$refid])
342                                 ), __FUNCTION__, __LINE__);
343                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . $refid . ',level=' . $GLOBALS['cache_array']['ref_level'][$refid] . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS());
344                 } // END - if
345
346                 // Advance to next level
347                 updateReferralCounter($refid);
348         } elseif ((($refid == $userid) || (!isValidId($refid))) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
349                 // Remove cache here
350                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . convertZeroToNull($refid) . ' - CACHE!');
351                 rebuildCache('refsystem', 'refsystem');
352         }
353
354         // Update the referral table
355         updateReferralTable($userid);
356
357         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertZeroToNull($refid) . ',level=' . convertZeroToNull($GLOBALS['cache_array']['ref_level'][$refid]) . ' - EXIT!');
358 }
359
360 // Subtract points from database and mediadata cache
361 function subtractPoints ($subject, $userid, $points) {
362         // Add points to used points
363         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
364                 array(
365                         $points,
366                         bigintval($userid)
367                 ), __FUNCTION__, __LINE__);
368
369         // Prepare filter data
370         $filterData = array(
371                 'subject'     => $subject,
372                 'userid'      => $userid,
373                 'points'      => $points,
374                 'points_mode' => 'sub',
375                 'column'      => 'used_points',
376                 'added'       => (!SQL_HASZEROAFFECTED())
377         );
378
379         // Insert booking record
380         $filterData = runFilterChain('post_sub_points', $filterData);
381
382         // Return result
383         return $filterData['added'];
384 }
385 // "Getter" for array for user refs and points in given level
386 function getUserReferralPoints ($userid, $level) {
387         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - ENTERED!');
388         // Default is no refs and no nickname
389         $refs = array();
390
391         // Get refs from database
392         $result = SQL_QUERY_ESC('SELECT
393         `ur`.`id`,
394         `ur`.`refid`,
395         `ud`.`status`,
396         `ud`.`last_online`,
397         `ud`.`mails_confirmed`,
398         `ud`.`emails_received`,
399         `ud`.`subid`
400 FROM
401         `{?_MYSQL_PREFIX?}_user_refs` AS `ur`
402 LEFT JOIN
403         `{?_MYSQL_PREFIX?}_user_points` AS `up`
404 ON
405         `ur`.`refid`=`up`.`userid` AND
406         (`ur`.`level`=0 OR `ur`.`level` IS NULL)
407 LEFT JOIN
408         `{?_MYSQL_PREFIX?}_user_data` AS `ud`
409 ON
410         `ur`.`refid`=`ud`.`userid`
411 WHERE
412         `ur`.`userid`=%s AND
413         `ur`.`level`=%s
414 ORDER BY
415         `ur`.`refid` ASC',
416                 array(
417                         bigintval($userid),
418                         bigintval($level)
419                 ), __FUNCTION__, __LINE__);
420
421         // Are there some entries?
422         if (!SQL_HASZERONUMS($result)) {
423                 // Fetch all entries
424                 while ($row = SQL_FETCHARRAY($result)) {
425                         // Init click rate with zero
426                         $row['click_rate'] = '0';
427
428                         // Is at least one mail received?
429                         if ($row['emails_received'] > 0) {
430                                 // Calculate click rate
431                                 $row['click_rate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
432                         } // END - if
433
434                         // Activity is 'active' by default because if ext-autopurge is not installed
435                         $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
436
437                         // Is autopurge installed and the user inactive?
438                         if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online']))  {
439                                 // Inactive user!
440                                 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
441                         } // END - if
442
443                         // Remove some entries
444                         unset($row['mails_confirmed']);
445                         unset($row['emails_received']);
446                         unset($row['last_online']);
447
448                         // Add row
449                         $refs[$row['id']] = $row;
450                 } // END - while
451         } // END - if
452
453         // Free result
454         SQL_FREERESULT($result);
455
456         // Return result
457         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - EXIT!');
458         return $refs;
459 }
460
461 // Get points data for given subject
462 function getPointsDataArrayFromSubject ($subject) {
463         // Extension ext-sql_patches must be up-to-date
464         if (isExtensionInstalledAndOlder('sql_patches', '0.8.2')) {
465                 // Please update ext-sql_patches
466                 reportBug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
467         } elseif (substr($subject, -8, 8) == '_ref_ref') {
468                 // Please report ALL finiding
469                 reportBug(__FUNCTION__, __LINE__, 'subject=' . $subject . ' contains invalid double-suffix _ref.');
470         }
471
472         // Remove any double-dot from it
473         $subject = removeDoubleDotFromSubject($subject);
474
475         // If we have cache, shortcut it here
476         if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
477                 // Count cache hit
478                 incrementStatsEntry('cache_hits');
479
480                 // Return it
481                 return $GLOBALS['cache_array']['points_data'][$subject];
482         } // END - if
483
484         // Now checkout the entry in database table
485         $result = SQL_QUERY_ESC("SELECT `id`, `subject`, `column_name`, `locked_mode`, `payment_method`, `notify_recipient` FROM `{?_MYSQL_PREFIX?}_points_data` WHERE `subject`='%s' LIMIT 1",
486                 array($subject), __FUNCTION__, __LINE__);
487
488         // Is there an entry?
489         if (SQL_NUMROWS($result) == 1) {
490                 // Then load it
491                 $pointsData = SQL_FETCHARRAY($result);
492
493                 // Add all entries to our cache array
494                 foreach ($pointsData as $key => $value) {
495                         $GLOBALS['cache_array']['points_data'][$subject][$key] = $value;
496                 } // END - foreach
497         } else {
498                 // Register this automatically
499                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`, `column_name`, `locked_mode`, `payment_method`, `notify_recipient`) VALUES ('%s','points','LOCKED','REFERRAL','N')",
500                         array($subject), __FUNCTION__, __LINE__);
501
502                 // Re-request it
503                 return getPointsDataArrayFromSubject($subject);
504         }
505
506         // Free result
507         SQL_FREERESULT($result);
508
509         // Return it
510         return $GLOBALS['cache_array']['points_data'][$subject];
511 }
512
513 // Determines the right points column name for given subject and 'locked'
514 function getPointsColumnNameFromSubjectLocked ($subject, $isLocked) {
515         // Get the points_data entry
516         $pointsData = getPointsDataArrayFromSubject($subject);
517
518         // Regular points by default
519         $columnName = $pointsData['column_name'];
520
521         // Are the points locked?
522         if (($isLocked === TRUE) && ($pointsData['locked_mode'] == 'LOCKED')) {
523                 // Locked points, so prefix it
524                 $columnName = 'locked_' . $pointsData['column_name'];
525         } // END - if
526
527         // Return the result
528         return $columnName;
529 }
530
531 // Determines the payment method for given extension and 'locked'
532 function getPaymentMethodFromSubject ($subject) {
533         // Get the points_data entry
534         $pointsData = getPointsDataArrayFromSubject($subject);
535
536         // Regular points by default
537         $paymentMethod = $pointsData['payment_method'];
538
539         // Return the result
540         return $paymentMethod;
541 }
542
543 // Checks whether notification of points recipient is enabled
544 function isPaymentRecipientNotificationEnabled ($subject) {
545         // Get the points_data entry
546         $pointsData = getPointsDataArrayFromSubject($subject);
547
548         // Is it enabled?
549         $isEnabled = ($pointsData['notify_recipient'] == 'Y');
550
551         // Return the result
552         return $isEnabled;
553 }
554
555 // Update "referral table"
556 function updateReferralTable ($userid) {
557         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
558         // Load all referrals
559         loadReferralTable($userid);
560
561         // Add missing level > 1
562         addMissingReferralLevels($userid);
563
564         // The last step is to flush all userid's entries to the database
565         flushReferralTableToDatabase($userid);
566
567         // Rebuild cache
568         rebuildCache('refsystem', 'refsystem');
569
570         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
571 }
572
573 // Loads all referrals for given userid
574 function loadReferralTable ($userid) {
575         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
576         // Init array
577         $GLOBALS['referral_refid'][$userid] = array();
578
579         // Get all level entries from the refsystem table
580         $GLOBALS['referral_result'][$userid] = SQL_QUERY_ESC('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
581                 array($userid), __FUNCTION__, __LINE__);
582
583         // Are there entries?
584         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL_NUMROWS()=' . SQL_NUMROWS($GLOBALS['referral_result'][$userid]));
585         if (SQL_NUMROWS($GLOBALS['referral_result'][$userid]) > 0) {
586                 // Then walk through all levels
587                 while (list($level) = SQL_FETCHROW($GLOBALS['referral_result'][$userid])) {
588                         // Init array
589                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
590                         $GLOBALS['referral_refid'][$userid][$level] = array();
591
592                         // Level is = 1?
593                         if ($level == 1) {
594                                 // Load all referrals of this user
595                                 $GLOBALS['referral_result_refs'][$userid] = SQL_QUERY_ESC('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
596                                         array($userid), __FUNCTION__, __LINE__);
597
598                                 // Are there entries?
599                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',SQL_NUMROWS()=' . SQL_NUMROWS($GLOBALS['referral_result_refs'][$userid]));
600                                 if (SQL_NUMROWS($GLOBALS['referral_result_refs'][$userid]) > 0) {
601                                         // Then again walk through all
602                                         while (list($refid) = SQL_FETCHROW($GLOBALS['referral_result_refs'][$userid])) {
603                                                 // Add this refid
604                                                 array_push($GLOBALS['referral_refid'][$userid][$level], $refid);
605                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid . ' - ADDED!');
606
607                                                 // Load the refid's array as well
608                                                 loadReferralTable($refid);
609                                         } // END - while
610                                 } // END - if
611
612                                 // Free result
613                                 SQL_FREERESULT($GLOBALS['referral_result_refs'][$userid]);
614                         } // END - if
615                 } // END - while
616         } // END - if
617
618         // Free result
619         SQL_FREERESULT($GLOBALS['referral_result'][$userid]);
620         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
621 }
622
623 // Adds missing referral levels to the array
624 function addMissingReferralLevels ($userid) {
625         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
626         // If the array is gone, you have called this function without calling loadReferralTable()
627         if (!isset($GLOBALS['referral_refid'][$userid])) {
628                 // Please fix your code
629                 reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
630         } // END - if
631         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
632
633         // Sort the array reversed
634         krsort($GLOBALS['referral_refid']);
635
636         // Now walk through the array, first levels
637         foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
638                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
639                 // Next are the users
640                 foreach ($levelArray as $refid) {
641                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
642                         // Does the refid have an array?
643                         if (isset($GLOBALS['referral_refid'][$refid])) {
644                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',count()=' . count($GLOBALS['referral_refid'][$refid]));
645                                 // Add also this user's (maybe) missing levels
646                                 addMissingReferralLevels($refid);
647
648                                 // Okay, then walk through here, too
649                                 foreach ($GLOBALS['referral_refid'][$refid] as $refLevel => $refArray) {
650                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',count()=' . count($refArray));
651                                         // Also walk through this one
652                                         foreach ($refArray as $refRefid) {
653                                                 // Calculate new level
654                                                 $newLevel = $level + $refLevel;
655                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',refRefid=' . $refRefid . ',newLevel=' . $newLevel);
656                                                 // Is the refRefid not in?
657                                                 if ((!isset($GLOBALS['referral_refid'][$userid][$newLevel])) || (!in_array($refRefid, $GLOBALS['referral_refid'][$userid][$newLevel]))) {
658                                                         // Then we must add this ref's refid to the userid's next level
659                                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',newLevel=' . $newLevel . ',refRefid=' . $refRefid . ' - ADDED!');
660                                                         array_push($GLOBALS['referral_refid'][$userid][$newLevel], $refRefid);
661
662                                                         // Add also this user's (maybe) missing levels
663                                                         addMissingReferralLevels($refRefid);
664                                                 } // END - if
665                                         } // END - foreach
666                                 } // END - foreach
667                         } // END - foreach
668                 } // END - foreach
669         } // END - foreach
670         //die('<pre>'.print_r($GLOBALS['referral_refid'][$userid],TRUE).'</pre>');
671         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
672 }
673
674 // Flush all entries for given userid to database
675 function flushReferralTableToDatabase ($userid) {
676         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
677         // If the array is gone, you have called this function without calling loadReferralTable()
678         if (!isset($GLOBALS['referral_refid'][$userid])) {
679                 // Please fix your code
680                 reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
681         } // END - if
682         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
683
684         // If no entries are there, skip this whole step
685         if (count($GLOBALS['referral_refid'][$userid]) == 0) {
686                 // No entries found
687                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ABORTING...');
688                 return;
689         } // END - if
690
691         // Prepare SQL
692         $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`, `level`, `refid`) VALUES ';
693         $executeSql = FALSE;
694
695         // Now walk through the array, first levels
696         foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
697                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
698                 // Next are the users
699                 foreach ($levelArray as $refid) {
700                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
701                         // Query the user_refs table
702                         $count = countSumTotalData(bigintval($userid), 'user_refs', 'id', 'userid', TRUE, ' AND `level`=' . bigintval($level) . ' AND `refid`=' . bigintval($refid));
703
704                         // Is there no entry?
705                         if ($count == 0) {
706                                 // Then add it to the SQL
707                                 $SQL .= '(' . $userid . ',' . $level . ',' . $refid . '),';
708
709                                 // Some has been added, so execute the query
710                                 $executeSql = TRUE;
711                         } // END - if
712                 } // END - foreach
713         } // END - foreach
714
715         // Remove last comma from SQL
716         $SQL = substr($SQL, 0, -1);
717
718         // And run it
719         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL=' . $SQL);
720         if ($executeSql === TRUE) {
721                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
722         } // END - if
723
724         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
725 }
726
727 // Generator (somewhat getter) for points_data, locked_mode
728 function generatePointsLockedModeOptions ($lockedMode = NULL) {
729         // Is this cached?
730         if (!isset($GLOBALS[__FUNCTION__][$lockedMode])) {
731                 // Generate output and cache it
732                 $GLOBALS[__FUNCTION__][$lockedMode] = generateOptions(
733                         '/ARRAY/',
734                         array(
735                                 'LOCKED',
736                                 'UNLOCKED'
737                         ),
738                         array(),
739                         $lockedMode,
740                         '', '',
741                         array(),
742                         'translatePointsLockedMode'
743                 );
744         } // END - if
745
746         // Return content
747         return $GLOBALS[__FUNCTION__][$lockedMode];
748 }
749
750 // Generator (somewhat getter) for points_data, payment_method
751 function generatePointsPaymentMethodOptions ($paymentMethod = NULL) {
752         // Is this cached?
753         if (!isset($GLOBALS[__FUNCTION__][$paymentMethod])) {
754                 // Generate output and cache it
755                 $GLOBALS[__FUNCTION__][$paymentMethod] = generateOptions(
756                         '/ARRAY/',
757                         array(
758                                 'DIRECT',
759                                 'REFERRAL'
760                         ),
761                         array(),
762                         $paymentMethod,
763                         '', '',
764                         array(),
765                         'translatePointsPaymentMethod'
766                 );
767         } // END - if
768
769         // Return content
770         return $GLOBALS[__FUNCTION__][$paymentMethod];
771 }
772
773 // Generator (somewhat getter) for points_data, notify_recipient
774 function generatePointsNotifyRecipientOptions ($notifyRecipient = NULL) {
775         // Is this cached?
776         if (!isset($GLOBALS[__FUNCTION__][$notifyRecipient])) {
777                 // Generate output and cache it
778                 $GLOBALS[__FUNCTION__][$notifyRecipient] = generateOptions(
779                         '/ARRAY/',
780                         array(
781                                 'Y',
782                                 'N'
783                         ),
784                         array(),
785                         $notifyRecipient,
786                         '', '',
787                         array(),
788                         'translatePointsNotifyRecipient'
789                 );
790         } // END - if
791
792         // Return content
793         return $GLOBALS[__FUNCTION__][$notifyRecipient];
794 }
795
796 // Setter for referral id (no bigintval, or nicknames will fail!)
797 function setReferralId ($refid) {
798         $GLOBALS['__refid'] = $refid;
799 }
800
801 // Checks if 'refid' is valid
802 function isReferralIdValid () {
803         return ((isset($GLOBALS['__refid'])) && (getReferralId() !== NULL) && (getReferralId() > 0));
804 }
805
806 // Getter for referral id
807 function getReferralId () {
808         return $GLOBALS['__refid'];
809 }
810
811 // Determines referral id and sets it
812 function determineReferralId () {
813         // Is it already detected?
814         if (isReferralIdValid()) {
815                 // Do not determine it, just return it
816                 return getReferralId();
817         } elseif ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
818                 // Skip this in non-html-mode and outside ref.php
819                 return FALSE;
820         }
821
822         // Check if refid is set
823         if (isReferralIdValid()) {
824                 // This is fine...
825                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from GLOBALS (' . getReferralId() . ')');
826         } elseif (isPostRequestElementSet('refid')) {
827                 // Get referral id from POST element refid
828                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from POST data (' . postRequestElement('refid') . ')');
829                 setReferralId(secureString(postRequestElement('refid')));
830         } elseif (isGetRequestElementSet('refid')) {
831                 // Get referral id from GET parameter refid
832                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from GET data (' . getRequestElement('refid') . ')');
833                 setReferralId(getRequestElement('refid'));
834         } elseif (isGetRequestElementSet('ref')) {
835                 // Set refid=ref (the referral link uses such variable)
836                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using ref from GET data (' . getRequestElement('ref') . ')');
837                 setReferralId(getRequestElement('ref'));
838         } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
839                 // The variable user comes from  click.php
840                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using user from GET data (' . getRequestElement('user') . ')');
841                 setReferralId(bigintval(getRequestElement('user')));
842         } elseif ((isSessionVariableSet('refid')) && (isValidId(getSession('refid')))) {
843                 // Set session refid as global
844                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from SESSION data (' . getSession('refid') . ')');
845                 setReferralId(bigintval(getSession('refid')));
846         } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (isRandomReferralIdEnabled())) {
847                 // Select a random user which has confirmed enougth mails
848                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Checking random referral id');
849                 setReferralId(determineRandomReferralId());
850         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidId(getDefRefid()))) {
851                 // Set default refid as refid in URL
852                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using default refid (' . getDefRefid() . ')');
853                 setReferralId(getDefRefid());
854         } else {
855                 // No default id when ext-sql_patches is not installed or none set
856                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using NULL as refid');
857                 setReferralId(NULL);
858         }
859
860         // Set cookie when default refid > 0
861         if ((!isSessionVariableSet('refid')) || (!isValidId(getReferralId())) || ((!isValidId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidId(getDefRefid())))) {
862                 // Default is not found
863                 $found = FALSE;
864
865                 // Is there nickname or userid set?
866                 if ((isExtensionActive('nickname')) && (isNicknameUsed(getReferralId()))) {
867                         // Nickname in URL, so load the id
868                         $found = fetchUserData(getReferralId(), 'nickname');
869
870                         // If we found it, use the userid as referral id
871                         if ($found === TRUE) {
872                                 // Set the userid as 'refid'
873                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from user account by nickname (' . getUserData('userid') . ')');
874                                 setReferralId(getUserData('userid'));
875                         } // END - if
876                 } elseif (isValidId(getReferralId())) {
877                         // Direct userid entered
878                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using direct userid (' . getReferralId() . ')');
879                         $found = fetchUserData(getReferralId());
880                 }
881
882                 // Is the record valid?
883                 if ((($found === FALSE) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
884                         // No, then reset referral id
885                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using default refid (' . getDefRefid() . ')');
886                         setReferralId(getDefRefid());
887                 } // END - if
888
889                 // Set cookie
890                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Saving refid to session (' . getReferralId() . ') #1');
891                 setSession('refid', getReferralId());
892         } elseif ((!isReferralIdValid()) || (!fetchUserData(getReferralId()))) {
893                 // Not valid!
894                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not valid referral id (' . getReferralId() . '), setting NULL in session');
895                 setReferralId(NULL);
896                 setSession('refid', NULL);
897         } else {
898                 // Set it from GLOBALS array in session
899                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Saving refid to session (' . getReferralId() . ') #2');
900                 setSession('refid', getReferralId());
901         }
902
903         // Run post validation filter chain
904         runFilterChain('post_refid_validation');
905
906         // Return determined refid
907         return getReferralId();
908 }
909
910 // [EOF]
911 ?>