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