A lot has been rewritten, ext-teams added, ext-forced continued:
[mailer.git] / inc / referal-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              : referal-functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : All referal system functions                     *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle zum Referal-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 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.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 referal system
44 function initReferalSystem () {
45         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' Referal system initialized!');
46         $GLOBALS['ref_level']  = NULL;
47         $GLOBALS['ref_system'] = true;
48 }
49
50 // Getter fro ref level percents
51 function getReferalLevelPercents ($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 referal 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 referal and points system, can also send mails!
87  *
88  * subject       = Subject line, write in lower-case letters and underscore is allowed
89  * userid        = Referal id wich should receive...
90  * points        = ... xxx points
91  * refid         = inc/modules/guest/what-confirm.php need this
92  */
93 function addPointsThroughReferalSystem ($subject, $userid, $points, $refid = NULL) {
94         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',refid=' . makeNullToZero($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__, 'userid=' . $userid . ',points=' . $points . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify));
113         if (fetchUserData($userid)) {
114                 // Determine wether the user has some mails to click before he/she gets the points
115                 $locked = ifUserPointsLocked($userid);
116
117                 // Detect database column
118                 $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $locked);
119
120                 // Get percents
121                 $per = getReferalLevelPercents($GLOBALS['ref_level']);
122                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',points=' . $points . ',depth=' . makeNullToZero($GLOBALS['ref_level']) . ',per=' . $per . ',mode=' . $paymentMethod . ',pointsColumn=' . $pointsColumn . ',locked=' . intval($locked) . ',refid=' . getUserData('refid'));
123
124                 // Some percents found?
125                 if ($per > 0) {
126                         // Calculate new points
127                         $ref_points = $points * $per / 100;
128
129                         // Pay refback here if level > 0 and in ref-mode
130                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . makeNullToZero(getUserData('refid')) . ',points=' . $points . ',paymentMethod=' . $paymentMethod);
131                         if (($userid != $refid) && ($paymentMethod == 'REFERAL') && (isValidUserId(getUserData('refid'))) && (isExtensionActive('refback'))) {
132                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . makeNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . makeNullToZero($GLOBALS['ref_level']) . ' - BEFORE!');
133                                 $ref_points = addRefbackPoints($userid, getUserData('refid'), $points, $ref_points);
134                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . makeNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . makeNullToZero($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='.makeNullToZero($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                                                 makeZeroToNull($GLOBALS['ref_level']),
168                                                 $ref_points
169                                         ), __FUNCTION__, __LINE__);
170                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.makeNullToZero($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'     => $locked,
187                                 '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                         // Points updated, maybe I shall send him an email?
200                         if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
201                                 // Prepare content
202                                 $content = array(
203                                         'percents' => $per,
204                                         'level'    => bigintval($GLOBALS['ref_level']),
205                                         'points'   => $ref_points,
206                                 );
207
208                                 // Load email template
209                                 $message = loadEmailTemplate('guest_user_confirmed_referal', $content, bigintval($userid));
210
211                                 // Send email
212                                 sendEmail($userid, '{--THANX_REFERAL_ONE_SUBJECT--}', $message);
213                         } elseif (($sendNotify === true) && (!isValidUserId(getUserData('refid'))) && ($locked === false) && ($paymentMethod == 'DIRECT')) {
214                                 // Prepare content
215                                 $content = array(
216                                         'reason'  => '{--REASON_DIRECT_PAYMENT--}',
217                                         'subject' => $subject,
218                                         'points'  => $ref_points
219                                 );
220
221                                 // Load message
222                                 $message = loadEmailTemplate('member_add_points', $content, $userid);
223
224                                 // And sent it away
225                                 sendEmail($userid, '{--DIRECT_PAYMENT_SUBJECT--}', $message);
226                                 if (!isGetRequestParameterSet('mid')) {
227                                         // Output message to admin
228                                         displayMessage('{--ADMIN_POINTS_ADDED--}');
229                                 } // END - if
230                         }
231
232                         // Increase referal level, if payment method is REFERAL
233                         if ($paymentMethod == 'REFERAL') {
234                                 // Increase it
235                                 $GLOBALS['ref_level']++;
236                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referal level increased, ref_level=' . makeNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . makeNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
237                         } elseif (isDebugModeEnabled()) {
238                                 // Not increasing referal level, DIRECT payment method
239                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referal level *NOT* increased, ref_level=' . makeNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . makeNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
240                         }
241
242                         // Maybe there's another ref?
243                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'points=' . $points . ',refid(var|data)=' . makeNullToZero($refid) . '|' . makeNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
244                         if ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($paymentMethod == 'REFERAL')) {
245                                 // Then let's credit him here...
246                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . makeNullToZero(getUserData('refid')) . ',points=' . $points . ',ref_points=' . $ref_points . ',added[' . gettype($added) . ']=' . intval($added) . ' - ADVANCE!');
247                                 $added = ($added && addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, getFetchedUserData('userid', getUserData('refid'), 'refid')));
248                         } // END - if
249                 } // END - if
250         } // END - if
251
252         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',sendNotify=' . intval($sendNotify) . ',refid=' . makeNullToZero($refid) . ',paymentMethod=' . $paymentMethod . ' - EXIT!');
253         return $added;
254 }
255
256 // Updates the referal counter
257 function updateReferalCounter ($userid) {
258         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
259         // Init referal id
260         $ref = NULL;
261
262         // Check for his referal
263         if (fetchUserData($userid)) {
264                 // Get it
265                 $ref = getUserData('refid');
266                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . makeZeroToNull($ref) . ' - FETCHED!');
267         } // END - if
268
269         // Init entries
270         if (empty($GLOBALS['cache_array']['ref_level'][$userid])) {
271                 $GLOBALS['cache_array']['ref_level'][$userid] = NULL;
272         } // END - if
273         if (empty($GLOBALS['cache_array']['ref_level'][$ref])) {
274                 $GLOBALS['cache_array']['ref_level'][$ref] = NULL;
275         } // END - if
276
277         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . makeZeroToNull($ref));
278
279         // When he has a referal...
280         if (($ref > 0) && ($ref != $userid)) {
281                 // Move to next referal level and count his counter one up
282                 $GLOBALS['cache_array']['ref_level'][$ref] = $GLOBALS['cache_array']['ref_level'][$userid] + 1;
283                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref(' . $ref . ')=' . $GLOBALS['cache_array']['ref_level'][$ref] . ' - ADVANCED!');
284
285                 // Update counter
286                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`=%s LIMIT 1",
287                         array(
288                                 bigintval($ref),
289                                 bigintval($GLOBALS['cache_array']['ref_level'][$ref])
290                         ), __FUNCTION__, __LINE__);
291
292                 // When no entry was updated then we have to create it here
293                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . $ref . ',level=' . $GLOBALS['cache_array']['ref_level'][$ref] . ',updated=' . SQL_AFFECTEDROWS());
294                 if (SQL_HASZEROAFFECTED()) {
295                         // First count!
296                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`,`level`,`counter`) VALUES (%s,%s,1)",
297                                 array(
298                                         bigintval($ref),
299                                         makeZeroToNull($GLOBALS['cache_array']['ref_level'][$ref])
300                                 ), __FUNCTION__, __LINE__);
301                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . $ref . ',level=' . $GLOBALS['cache_array']['ref_level'][$ref] . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS());
302                 } // END - if
303
304                 // Advance to next level
305                 updateReferalCounter($ref);
306         } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
307                 // Remove cache here
308                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . makeZeroToNull($ref) . ' - CACHE!');
309                 rebuildCache('refsystem', 'refsystem');
310         }
311
312         // Update the referal table
313         updateReferalTable($userid);
314
315         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . makeZeroToNull($ref) . ',level=' . makeZeroToNull($GLOBALS['cache_array']['ref_level'][$ref]) . ' - EXIT!');
316 }
317
318 // Subtract points from database and mediadata cache
319 function subtractPoints ($subject, $userid, $points) {
320         // Add points to used points
321         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
322                 array(
323                         $points,
324                         bigintval($userid)
325                 ), __FUNCTION__, __LINE__);
326
327         // Prepare filter data
328         $filterData = array(
329                 'subject' => $subject,
330                 'userid'  => $userid,
331                 'points'  => $points,
332                 'mode'    => 'sub',
333                 'added'   => (!SQL_HASZEROAFFECTED())
334         );
335
336         // Insert booking record
337         $filterData = runFilterChain('post_sub_points', $filterData);
338
339         // Return result
340         return $filterData['added'];
341 }
342 // "Getter" for array for user refs and points in given level
343 function getUserReferalPoints ($userid, $level) {
344         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - ENTERED!');
345         // Default is no refs and no nickname
346         $refs = array();
347
348         // Get refs from database
349         $result = SQL_QUERY_ESC("SELECT
350         ur.`id`, ur.`refid`, ud.`status`, ud.`last_online`, ud.`mails_confirmed`, ud.`emails_received`
351 FROM
352         `{?_MYSQL_PREFIX?}_user_refs` AS `ur`
353 LEFT JOIN
354         `{?_MYSQL_PREFIX?}_user_points` AS `up`
355 ON
356         ur.`refid`=up.`userid` AND
357         (ur.`level`=0 OR ur.`level` IS NULL)
358 LEFT JOIN
359         `{?_MYSQL_PREFIX?}_user_data` AS `ud`
360 ON
361         ur.`refid`=ud.`userid`
362 WHERE
363         ur.`userid`=%s AND
364         ur.`level`=%s
365 ORDER BY
366         ur.`refid` ASC",
367                 array(
368                         bigintval($userid),
369                         bigintval($level)
370                 ), __FUNCTION__, __LINE__);
371
372         // Are there some entries?
373         if (!SQL_HASZERONUMS($result)) {
374                 // Fetch all entries
375                 while ($row = SQL_FETCHARRAY($result)) {
376                         // Get total points of this user
377                         $row['points'] = getTotalPoints($row['refid']);
378
379                         // Get unconfirmed mails
380                         $row['unconfirmed'] = getTotalUnconfirmedMails($row['refid']);
381
382                         // Init click rate with zero
383                         $row['click_rate'] = '0';
384
385                         // Is at least one mail received?
386                         if ($row['emails_received'] > 0) {
387                                 // Calculate click rate
388                                 $row['click_rate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
389                         } // END - if
390
391                         // Activity is 'active' by default because if autopurge is not installed
392                         $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
393
394                         // Is autopurge installed and the user inactive?
395                         if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online']))  {
396                                 // Inactive user!
397                                 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
398                         } // END - if
399
400                         // Remove some entries
401                         unset($row['mails_confirmed']);
402                         unset($row['emails_received']);
403                         unset($row['last_online']);
404
405                         // Add row
406                         $refs[$row['id']] = $row;
407                 } // END - while
408         } // END - if
409
410         // Free result
411         SQL_FREERESULT($result);
412
413         // Return result
414         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - EXIT!');
415         return $refs;
416 }
417
418 // Get points data for given subject
419 function getPointsDataArrayFromSubject ($subject) {
420         // Extension ext-sql_patches must be up-to-date
421         if (isExtensionInstalledAndOlder('sql_patches', '0.8.2')) {
422                 // Please update ext-sql_patches
423                 debug_report_bug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
424         } // END - if
425
426         // Remove any double-dot from it
427         $subjectArray = explode(':', $subject);
428         $subject = $subjectArray[0];
429         unset($subjectArray);
430
431         // If we have cache, shortcut it here
432         if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
433                 // Return it
434                 return $GLOBALS['cache_array']['points_data'][$subject];
435         } // END - if
436
437         // Now checkout the entry in database table
438         $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",
439                 array($subject), __FUNCTION__, __LINE__);
440
441         // Do we have an entry?
442         if (SQL_NUMROWS($result) == 1) {
443                 // Then load it
444                 $pointsData = SQL_FETCHARRAY($result);
445
446                 // Add all entries to our cache array
447                 foreach ($pointsData as $key=>$value) {
448                         $GLOBALS['cache_array']['points_data'][$subject][$key] = $value;
449                 } // END - foreach
450         } else {
451                 // Register this automatically
452                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`,`column_name`,`locked_mode`,`payment_method`,`notify_recipient`) VALUES ('%s','points','LOCKED','REFERAL','N')",
453                         array($subject), __FUNCTION__, __LINE__);
454
455                 // Re-request it
456                 return getPointsDataArrayFromSubject($subject);
457         }
458
459         // Free result
460         SQL_FREERESULT($result);
461
462         // Return it
463         return $GLOBALS['cache_array']['points_data'][$subject];
464 }
465
466 // Determines the right points column name for given subject and 'locked'
467 function getPointsColumnNameFromSubjectLocked ($subject, $isLocked) {
468         // Get the points_data entry
469         $pointsData = getPointsDataArrayFromSubject($subject);
470
471         // Regular points by default
472         $columnName = $pointsData['column_name'];
473
474         // Are the points locked?
475         if (($isLocked === true) && ($pointsData['locked_mode'] == 'LOCKED')) {
476                 // Locked points, so prefix it
477                 $columnName = 'locked_' . $pointsData['column_name'];
478         } // END - if
479
480         // Return the result
481         return $columnName;
482 }
483
484 // Determines the payment method for given extension and 'locked'
485 function getPaymentMethodFromSubject ($subject) {
486         // Get the points_data entry
487         $pointsData = getPointsDataArrayFromSubject($subject);
488
489         // Regular points by default
490         $paymentMethod = $pointsData['payment_method'];
491
492         // Return the result
493         return $paymentMethod;
494 }
495
496 // Checks wether notification of points recipient is enabled
497 function isPaymentRecipientNotificationEnabled ($subject) {
498         // Get the points_data entry
499         $pointsData = getPointsDataArrayFromSubject($subject);
500
501         // Is it enabled?
502         $isEnabled = ($pointsData['notify_recipient'] == 'Y');
503
504         // Return the result
505         return $isEnabled;
506 }
507
508 // Update "referal table"
509 function updateReferalTable ($userid) {
510         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
511         // Load all referals
512         loadReferalTable($userid);
513
514         // Add missing level > 1
515         addMissingReferalLevels($userid);
516
517         // The last step is to flush all userid's entries to the database
518         flushReferalTableToDatabase($userid);
519
520         // Rebuild cache
521         rebuildCache('refsystem', 'refsystem');
522
523         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
524 }
525
526 // Loads all referals for given userid
527 function loadReferalTable ($userid) {
528         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
529         // Init array
530         $GLOBALS['referal_refid'][$userid] = array();
531
532         // Get all level entries from the refsystem table
533         $result = SQL_QUERY_ESC('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
534                 array($userid), __FUNCTION__, __LINE__);
535
536         // Do we have entries?
537         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL_NUMROWS()=' . SQL_NUMROWS($result));
538         if (SQL_NUMROWS($result) > 0) {
539                 // Then walk through all levels
540                 while (list($level) = SQL_FETCHROW($result)) {
541                         // Init array
542                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
543                         $GLOBALS['referal_refid'][$userid][$level] = array();
544
545                         // Level is = 1?
546                         if ($level == 1) {
547                                 // Load all referals of this user
548                                 $result_refs = SQL_QUERY_ESC('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
549                                         array($userid), __FUNCTION__, __LINE__);
550
551                                 // Do we have entries?
552                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',SQL_NUMROWS()=' . SQL_NUMROWS($result_refs));
553                                 if (SQL_NUMROWS($result_refs) > 0) {
554                                         // Then again walk through all
555                                         while (list($refid) = SQL_FETCHROW($result_refs)) {
556                                                 // Add this refid
557                                                 $GLOBALS['referal_refid'][$userid][$level][] = $refid;
558                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
559                                                 // Load the refid's array as well
560                                                 loadReferalTable($refid);
561                                         } // END - while
562                                 } // END - if
563
564                                 // Free result
565                                 SQL_FREERESULT($result_refs);
566                         } // END - if
567                 } // END - while
568         } // END - if
569
570         // Free result
571         SQL_FREERESULT($result);
572         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
573 }
574
575 // Adds missing referal levels to the array
576 function addMissingReferalLevels ($userid) {
577         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
578         // If the array is gone, you have called this function without calling loadReferalTable()
579         if (!isset($GLOBALS['referal_refid'][$userid])) {
580                 // Please fix your code
581                 debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferalTable() before! userid=' . $userid);
582         } // END - if
583         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referal_refid'][$userid]));
584
585         // Now walk through the array, first levels
586         foreach ($GLOBALS['referal_refid'][$userid] as $level=>$levelArray) {
587                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
588                 // Next are the users
589                 foreach ($levelArray as $refid) {
590                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
591                         // Does the refid have an array?
592                         if (isset($GLOBALS['referal_refid'][$refid])) {
593                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . makeNullToZero($refid) . ',count()=' . count($GLOBALS['referal_refid'][$refid]));
594                                 // Okay, then walk through here, too
595                                 foreach ($GLOBALS['referal_refid'][$refid] as $refLevel=>$refArray) {
596                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . makeNullToZero($refid) . ',refLevel=' . $refLevel . ',count()=' . count($refArray));
597                                         // Also walk through this one
598                                         foreach ($refArray as $refRefid) {
599                                                 // Calculate new level
600                                                 $newLevel =  $level + $refLevel;
601                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . makeNullToZero($refid) . ',refLevel=' . $refLevel . ',refRefid=' . $refRefid . ',newLevel=' . $newLevel);
602                                                 // Is the refRefid not in?
603                                                 if ((!isset($GLOBALS['referal_refid'][$userid][$newLevel])) || (!in_array($refRefid, $GLOBALS['referal_refid'][$userid][$newLevel]))) {
604                                                         // Then we must add this ref's refid to the userid's next level
605                                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',newLevel=' . $newLevel . ',refRefid=' . $refRefid . ' - ADDED!');
606                                                         $GLOBALS['referal_refid'][$userid][$newLevel][] = $refRefid;
607                                                 } // END - if
608                                         } // END - foreach
609                                 } // END - foreach
610                         } // END - foreach
611                 } // END - foreach
612         } // END - foreach
613         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
614 }
615
616 // Flush all entries for given userid to database
617 function flushReferalTableToDatabase ($userid) {
618         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
619         // If the array is gone, you have called this function without calling loadReferalTable()
620         if (!isset($GLOBALS['referal_refid'][$userid])) {
621                 // Please fix your code
622                 debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferalTable() before! userid=' . $userid);
623         } // END - if
624         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referal_refid'][$userid]));
625
626         // If no entries are there, skip this whole step
627         if (count($GLOBALS['referal_refid'][$userid]) == 0) {
628                 // No entries found
629                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ABORTING...');
630                 return;
631         } // END - if
632
633         // Prepare SQL
634         $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`,`level`,`refid`) VALUES ';
635         $executeSql = false;
636
637         // Now walk through the array, first levels
638         foreach ($GLOBALS['referal_refid'][$userid] as $level=>$levelArray) {
639                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
640                 // Next are the users
641                 foreach ($levelArray as $refid) {
642                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
643                         // Query the user_refs table
644                         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',
645                                 array(
646                                         $userid,
647                                         $level,
648                                         $refid
649                                 ), __FUNCTION__, __LINE__));
650
651                         // Do we have no entry?
652                         if ($count == 0) {
653                                 // Then add it to the SQL
654                                 $SQL .= '(' . $userid . ',' . $level . ',' . $refid . '),';
655
656                                 // Some has been added, so execute the query
657                                 $executeSql = true;
658                         } // END - if
659                 } // END - foreach
660         } // END - foreach
661
662         // Remove last comma from SQL
663         $SQL = substr($SQL, 0, -1);
664
665         // And run it
666         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL=' . $SQL);
667         if ($executeSql === true) {
668                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
669         } // END - if
670
671         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
672 }
673
674 // [EOF]
675 ?>