mailer project continued:
[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 - 2012 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         // Do we have 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 ((!isValidUserId($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') && (isValidUserId(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, '{--THANX_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 ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($paymentMethod == 'REFERRAL')) {
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         $ref = NULL;
303
304         // Check for his referral
305         if (fetchUserData($userid)) {
306                 // Get it
307                 $ref = getUserData('refid');
308                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . convertZeroToNull($ref) . ' - 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'][$ref])) {
316                 $GLOBALS['cache_array']['ref_level'][$ref] = NULL;
317         } // END - if
318
319         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . convertZeroToNull($ref));
320
321         // When he has a referral...
322         if (($ref > 0) && ($ref != $userid)) {
323                 // Move to next referral level and count his counter one up
324                 $GLOBALS['cache_array']['ref_level'][$ref] = $GLOBALS['cache_array']['ref_level'][$userid] + 1;
325                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref(' . $ref . ')=' . $GLOBALS['cache_array']['ref_level'][$ref] . ' - 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($ref),
331                                 bigintval($GLOBALS['cache_array']['ref_level'][$ref])
332                         ), __FUNCTION__, __LINE__);
333
334                 // When no entry was updated then we have to create it here
335                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . $ref . ',level=' . $GLOBALS['cache_array']['ref_level'][$ref] . ',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($ref),
341                                         convertZeroToNull($GLOBALS['cache_array']['ref_level'][$ref])
342                                 ), __FUNCTION__, __LINE__);
343                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . $ref . ',level=' . $GLOBALS['cache_array']['ref_level'][$ref] . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS());
344                 } // END - if
345
346                 // Advance to next level
347                 updateReferralCounter($ref);
348         } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
349                 // Remove cache here
350                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . convertZeroToNull($ref) . ' - CACHE!');
351                 rebuildCache('refsystem', 'refsystem');
352         }
353
354         // Update the referral table
355         updateReferralTable($userid);
356
357         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . convertZeroToNull($ref) . ',level=' . convertZeroToNull($GLOBALS['cache_array']['ref_level'][$ref]) . ' - 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                 'added'       => (!SQL_HASZEROAFFECTED())
376         );
377
378         // Insert booking record
379         $filterData = runFilterChain('post_sub_points', $filterData);
380
381         // Return result
382         return $filterData['added'];
383 }
384 // "Getter" for array for user refs and points in given level
385 function getUserReferralPoints ($userid, $level) {
386         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - ENTERED!');
387         // Default is no refs and no nickname
388         $refs = array();
389
390         // Get refs from database
391         $result = SQL_QUERY_ESC("SELECT
392         ur.`id`, ur.`refid`, ud.`status`, ud.`last_online`, ud.`mails_confirmed`, ud.`emails_received`
393 FROM
394         `{?_MYSQL_PREFIX?}_user_refs` AS `ur`
395 LEFT JOIN
396         `{?_MYSQL_PREFIX?}_user_points` AS `up`
397 ON
398         ur.`refid`=up.`userid` AND
399         (ur.`level`=0 OR ur.`level` IS NULL)
400 LEFT JOIN
401         `{?_MYSQL_PREFIX?}_user_data` AS `ud`
402 ON
403         ur.`refid`=ud.`userid`
404 WHERE
405         ur.`userid`=%s AND
406         ur.`level`=%s
407 ORDER BY
408         ur.`refid` ASC",
409                 array(
410                         bigintval($userid),
411                         bigintval($level)
412                 ), __FUNCTION__, __LINE__);
413
414         // Are there some entries?
415         if (!SQL_HASZERONUMS($result)) {
416                 // Fetch all entries
417                 while ($row = SQL_FETCHARRAY($result)) {
418                         // Init click rate with zero
419                         $row['click_rate'] = '0';
420
421                         // Is at least one mail received?
422                         if ($row['emails_received'] > 0) {
423                                 // Calculate click rate
424                                 $row['click_rate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
425                         } // END - if
426
427                         // Activity is 'active' by default because if ext-autopurge is not installed
428                         $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
429
430                         // Is autopurge installed and the user inactive?
431                         if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online']))  {
432                                 // Inactive user!
433                                 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
434                         } // END - if
435
436                         // Remove some entries
437                         unset($row['mails_confirmed']);
438                         unset($row['emails_received']);
439                         unset($row['last_online']);
440
441                         // Add row
442                         $refs[$row['id']] = $row;
443                 } // END - while
444         } // END - if
445
446         // Free result
447         SQL_FREERESULT($result);
448
449         // Return result
450         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - EXIT!');
451         return $refs;
452 }
453
454 // Get points data for given subject
455 function getPointsDataArrayFromSubject ($subject) {
456         // Extension ext-sql_patches must be up-to-date
457         if (isExtensionInstalledAndOlder('sql_patches', '0.8.2')) {
458                 // Please update ext-sql_patches
459                 reportBug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
460         } elseif (substr($subject, -8, 8) == '_ref_ref') {
461                 // Please report ALL finiding
462                 reportBug(__FUNCTION__, __LINE__, 'subject=' . $subject . ' contains invalid double-suffix _ref.');
463         }
464
465         // Remove any double-dot from it
466         $subject = removeDoubleDotFromSubject($subject);
467
468         // If we have cache, shortcut it here
469         if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
470                 // Count cache hit
471                 incrementStatsEntry('cache_hits');
472
473                 // Return it
474                 return $GLOBALS['cache_array']['points_data'][$subject];
475         } // END - if
476
477         // Now checkout the entry in database table
478         $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",
479                 array($subject), __FUNCTION__, __LINE__);
480
481         // Do we have an entry?
482         if (SQL_NUMROWS($result) == 1) {
483                 // Then load it
484                 $pointsData = SQL_FETCHARRAY($result);
485
486                 // Add all entries to our cache array
487                 foreach ($pointsData as $key => $value) {
488                         $GLOBALS['cache_array']['points_data'][$subject][$key] = $value;
489                 } // END - foreach
490         } else {
491                 // Register this automatically
492                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`,`column_name`,`locked_mode`,`payment_method`,`notify_recipient`) VALUES ('%s','points','LOCKED','REFERRAL','N')",
493                         array($subject), __FUNCTION__, __LINE__);
494
495                 // Re-request it
496                 return getPointsDataArrayFromSubject($subject);
497         }
498
499         // Free result
500         SQL_FREERESULT($result);
501
502         // Return it
503         return $GLOBALS['cache_array']['points_data'][$subject];
504 }
505
506 // Determines the right points column name for given subject and 'locked'
507 function getPointsColumnNameFromSubjectLocked ($subject, $isLocked) {
508         // Get the points_data entry
509         $pointsData = getPointsDataArrayFromSubject($subject);
510
511         // Regular points by default
512         $columnName = $pointsData['column_name'];
513
514         // Are the points locked?
515         if (($isLocked === true) && ($pointsData['locked_mode'] == 'LOCKED')) {
516                 // Locked points, so prefix it
517                 $columnName = 'locked_' . $pointsData['column_name'];
518         } // END - if
519
520         // Return the result
521         return $columnName;
522 }
523
524 // Determines the payment method for given extension and 'locked'
525 function getPaymentMethodFromSubject ($subject) {
526         // Get the points_data entry
527         $pointsData = getPointsDataArrayFromSubject($subject);
528
529         // Regular points by default
530         $paymentMethod = $pointsData['payment_method'];
531
532         // Return the result
533         return $paymentMethod;
534 }
535
536 // Checks whether notification of points recipient is enabled
537 function isPaymentRecipientNotificationEnabled ($subject) {
538         // Get the points_data entry
539         $pointsData = getPointsDataArrayFromSubject($subject);
540
541         // Is it enabled?
542         $isEnabled = ($pointsData['notify_recipient'] == 'Y');
543
544         // Return the result
545         return $isEnabled;
546 }
547
548 // Update "referral table"
549 function updateReferralTable ($userid) {
550         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
551         // Load all referrals
552         loadReferralTable($userid);
553
554         // Add missing level > 1
555         addMissingReferralLevels($userid);
556
557         // The last step is to flush all userid's entries to the database
558         flushReferralTableToDatabase($userid);
559
560         // Rebuild cache
561         rebuildCache('refsystem', 'refsystem');
562
563         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
564 }
565
566 // Loads all referrals for given userid
567 function loadReferralTable ($userid) {
568         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
569         // Init array
570         $GLOBALS['referral_refid'][$userid] = array();
571
572         // Get all level entries from the refsystem table
573         $GLOBALS['referral_result'][$userid] = SQL_QUERY_ESC('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
574                 array($userid), __FUNCTION__, __LINE__);
575
576         // Do we have entries?
577         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL_NUMROWS()=' . SQL_NUMROWS($GLOBALS['referral_result'][$userid]));
578         if (SQL_NUMROWS($GLOBALS['referral_result'][$userid]) > 0) {
579                 // Then walk through all levels
580                 while (list($level) = SQL_FETCHROW($GLOBALS['referral_result'][$userid])) {
581                         // Init array
582                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
583                         $GLOBALS['referral_refid'][$userid][$level] = array();
584
585                         // Level is = 1?
586                         if ($level == 1) {
587                                 // Load all referrals of this user
588                                 $GLOBALS['referral_result_refs'][$userid] = SQL_QUERY_ESC('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
589                                         array($userid), __FUNCTION__, __LINE__);
590
591                                 // Do we have entries?
592                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',SQL_NUMROWS()=' . SQL_NUMROWS($GLOBALS['referral_result_refs'][$userid]));
593                                 if (SQL_NUMROWS($GLOBALS['referral_result_refs'][$userid]) > 0) {
594                                         // Then again walk through all
595                                         while (list($refid) = SQL_FETCHROW($GLOBALS['referral_result_refs'][$userid])) {
596                                                 // Add this refid
597                                                 array_push($GLOBALS['referral_refid'][$userid][$level], $refid);
598                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid . ' - ADDED!');
599
600                                                 // Load the refid's array as well
601                                                 loadReferralTable($refid);
602                                         } // END - while
603                                 } // END - if
604
605                                 // Free result
606                                 SQL_FREERESULT($GLOBALS['referral_result_refs'][$userid]);
607                         } // END - if
608                 } // END - while
609         } // END - if
610
611         // Free result
612         SQL_FREERESULT($GLOBALS['referral_result'][$userid]);
613         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
614 }
615
616 // Adds missing referral levels to the array
617 function addMissingReferralLevels ($userid) {
618         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
619         // If the array is gone, you have called this function without calling loadReferralTable()
620         if (!isset($GLOBALS['referral_refid'][$userid])) {
621                 // Please fix your code
622                 reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
623         } // END - if
624         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
625
626         // Sort the array reversed
627         krsort($GLOBALS['referral_refid']);
628
629         // Now walk through the array, first levels
630         foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
631                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
632                 // Next are the users
633                 foreach ($levelArray as $refid) {
634                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
635                         // Does the refid have an array?
636                         if (isset($GLOBALS['referral_refid'][$refid])) {
637                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',count()=' . count($GLOBALS['referral_refid'][$refid]));
638                                 // Add also this user's (maybe) missing levels
639                                 addMissingReferralLevels($refid);
640
641                                 // Okay, then walk through here, too
642                                 foreach ($GLOBALS['referral_refid'][$refid] as $refLevel => $refArray) {
643                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',count()=' . count($refArray));
644                                         // Also walk through this one
645                                         foreach ($refArray as $refRefid) {
646                                                 // Calculate new level
647                                                 $newLevel =  $level + $refLevel;
648                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',refRefid=' . $refRefid . ',newLevel=' . $newLevel);
649                                                 // Is the refRefid not in?
650                                                 if ((!isset($GLOBALS['referral_refid'][$userid][$newLevel])) || (!in_array($refRefid, $GLOBALS['referral_refid'][$userid][$newLevel]))) {
651                                                         // Then we must add this ref's refid to the userid's next level
652                                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',newLevel=' . $newLevel . ',refRefid=' . $refRefid . ' - ADDED!');
653                                                         array_push($GLOBALS['referral_refid'][$userid][$newLevel], $refRefid);
654
655                                                         // Add also this user's (maybe) missing levels
656                                                         addMissingReferralLevels($refRefid);
657                                                 } // END - if
658                                         } // END - foreach
659                                 } // END - foreach
660                         } // END - foreach
661                 } // END - foreach
662         } // END - foreach
663         //die('<pre>'.print_r($GLOBALS['referral_refid'][$userid],true).'</pre>');
664         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
665 }
666
667 // Flush all entries for given userid to database
668 function flushReferralTableToDatabase ($userid) {
669         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
670         // If the array is gone, you have called this function without calling loadReferralTable()
671         if (!isset($GLOBALS['referral_refid'][$userid])) {
672                 // Please fix your code
673                 reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
674         } // END - if
675         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
676
677         // If no entries are there, skip this whole step
678         if (count($GLOBALS['referral_refid'][$userid]) == 0) {
679                 // No entries found
680                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ABORTING...');
681                 return;
682         } // END - if
683
684         // Prepare SQL
685         $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`,`level`,`refid`) VALUES ';
686         $executeSql = false;
687
688         // Now walk through the array, first levels
689         foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
690                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
691                 // Next are the users
692                 foreach ($levelArray as $refid) {
693                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
694                         // Query the user_refs table
695                         list($count) = SQL_FETCHROW(SQL_QUERY_ESC('SELECT COUNT(`id`) AS `count` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `userid`=%s AND `level`=%s AND `refid`=%s LIMIT 1',
696                                 array(
697                                         $userid,
698                                         $level,
699                                         $refid
700                                 ), __FUNCTION__, __LINE__));
701
702                         // Do we have no entry?
703                         if ($count == 0) {
704                                 // Then add it to the SQL
705                                 $SQL .= '(' . $userid . ',' . $level . ',' . $refid . '),';
706
707                                 // Some has been added, so execute the query
708                                 $executeSql = true;
709                         } // END - if
710                 } // END - foreach
711         } // END - foreach
712
713         // Remove last comma from SQL
714         $SQL = substr($SQL, 0, -1);
715
716         // And run it
717         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL=' . $SQL);
718         if ($executeSql === true) {
719                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
720         } // END - if
721
722         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
723 }
724
725 // Generator (somewhat getter) for points_data, locked_mode
726 function generatePointsLockedModeOptions ($lockedMode =  NULL) {
727         // Is this cached?
728         if (!isset($GLOBALS[__FUNCTION__][$lockedMode])) {
729                 // Generate output and cache it
730                 $GLOBALS[__FUNCTION__][$lockedMode] = generateOptions(
731                         '/ARRAY/',
732                         array(
733                                 'LOCKED',
734                                 'UNLOCKED'
735                         ),
736                         array(),
737                         $lockedMode,
738                         '', '',
739                         array(),
740                         'translatePointsLockedMode'
741                 );
742         } // END - if
743
744         // Return content
745         return $GLOBALS[__FUNCTION__][$lockedMode];
746 }
747
748 // Generator (somewhat getter) for points_data, payment_method
749 function generatePointsPaymentMethodOptions ($paymentMethod =  NULL) {
750         // Is this cached?
751         if (!isset($GLOBALS[__FUNCTION__][$paymentMethod])) {
752                 // Generate output and cache it
753                 $GLOBALS[__FUNCTION__][$paymentMethod] = generateOptions(
754                         '/ARRAY/',
755                         array(
756                                 'DIRECT',
757                                 'REFERRAL'
758                         ),
759                         array(),
760                         $paymentMethod,
761                         '', '',
762                         array(),
763                         'translatePointsPaymentMethod'
764                 );
765         } // END - if
766
767         // Return content
768         return $GLOBALS[__FUNCTION__][$paymentMethod];
769 }
770
771 // Generator (somewhat getter) for points_data, notify_recipient
772 function generatePointsNotifyRecipientOptions ($notifyRecipient =  NULL) {
773         // Is this cached?
774         if (!isset($GLOBALS[__FUNCTION__][$notifyRecipient])) {
775                 // Generate output and cache it
776                 $GLOBALS[__FUNCTION__][$notifyRecipient] = generateOptions(
777                         '/ARRAY/',
778                         array(
779                                 'Y',
780                                 'N'
781                         ),
782                         array(),
783                         $notifyRecipient,
784                         '', '',
785                         array(),
786                         'translatePointsNotifyRecipient'
787                 );
788         } // END - if
789
790         // Return content
791         return $GLOBALS[__FUNCTION__][$notifyRecipient];
792 }
793
794 // Setter for referral id (no bigintval, or nicknames will fail!)
795 function setReferralId ($refid) {
796         $GLOBALS['__refid'] = $refid;
797 }
798
799 // Checks if 'refid' is valid
800 function isReferralIdValid () {
801         return ((isset($GLOBALS['__refid'])) && (getReferralId() !== NULL) && (getReferralId() > 0));
802 }
803
804 // Getter for referral id
805 function getReferralId () {
806         return $GLOBALS['__refid'];
807 }
808
809 // [EOF]
810 ?>