7106e7972c8cc9010fabe908129045f6c2d4f9a2
[mailer.git] / inc / libs / refback_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 09/28/2008 *
4  * ===============                              Last change: 09/28/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : refback_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for refback extension                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer Refback-Erweiterung              *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
42         require($INC);
43 }
44
45 // Payback refback for refid and reduce it for current user
46 function ADD_REFBACK_POINTS ($uid, $ref, $points, $ref_points) {
47         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
48         // Back ref depths
49         $GLOBALS['cache_array']['depth'][$uid][$ref] = $GLOBALS['ref_level'];
50
51         // Init points
52         $return = $points;
53
54         // Get all ref levels
55         $result_refs = SQL_QUERY("SELECT level, percents FROM `{!_MYSQL_PREFIX!}_refdepths` WHERE level > 0 ORDER BY level ASC",
56         __FUNCTION__, __LINE__);
57
58         // "Walk" through all level
59         while ($content = SQL_FETCHARRAY($result_refs)) {
60                 // Reset ref depths
61                 unset($GLOBALS['ref_level']);
62
63                 // "Walk" through all refids
64                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref},level={$content['level']},points={$points}<br />\n";
65                 foreach (GET_REFBACK_USERID_ARRAY($uid, $content['level']) as $refid) {
66                         // Skip level zero or if both are the same
67                         if ($uid == $refid) continue;
68
69                         // Get refback percents
70                         $percents = GET_REFBACK_PERCENTS($uid, $refid);
71                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref},refid={$refid},points={$points},percents={$percents}<br />\n";
72
73                         // Some percents given?
74                         if ($percents > 0) {
75                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):points={$points},perc={$content['percents']},percents={$percents},level={$content['level']}<br />\n";
76                                 // Calculate points for refback
77                                 $refback = $points * ($content['percents'] / 100) * ($percents / 100);
78
79                                 // Update refback table ("refid" and "uid" must be exchanged!)
80                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_refs` SET points=points+%s WHERE userid=%s AND refid=%s LIMIT 1",
81                                 array($refback, $refid, $uid), __FUNCTION__, __LINE__);
82                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):refback={$refback},uid={$uid},refid={$refid} - UPDATE! (".SQL_AFFECTEDROWS().")<br />\n";
83
84                                 // Add points again, but only directly
85                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):refback={$refback}<br />\n";
86                                 ADD_POINTS_REFSYSTEM_DIRECT(sprintf("refback:%s", $refid), $uid, $refback);
87
88                                 // Reduce points if refid is found
89                                 if ($refid == $ref) {
90                                         // Reduce¬†points here!
91                                         $return = $points * ($content['percents'] / 100) - $refback;
92                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):points={$return} - REDUCED<br />\n";
93                                 } // END - if
94                         } // END - if
95                 } // END foreach
96         } // END - while
97
98         // Free result
99         SQL_FREERESULT($result_refs);
100
101         // Restore ref depth
102         $GLOBALS['ref_level'] = $GLOBALS['cache_array']['depth'][$uid][$ref];
103
104         // Return them
105         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
106         return $return;
107 }
108
109 // "Getter" for refback percents
110 function GET_REFBACK_PERCENTS ($uid, $ref) {
111         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
112         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref}<br />\n";
113         // Skip identical ids
114         if ($uid == $ref) return 0;
115
116         // Default is zero
117         $percents = 0;
118
119         // Get percents from database
120         $result = SQL_QUERY_ESC("SELECT refback FROM `{!_MYSQL_PREFIX!}_user_refs` WHERE userid=%s AND refid=%s LIMIT 1",
121         array($ref, $uid), __FUNCTION__, __LINE__);
122
123         // Entry found? (Should be!)
124         if (SQL_NUMROWS($result) == 1) {
125                 // Fetch percents
126                 list($percents) = SQL_FETCHROW($result);
127                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):percents={$percents}<br />\n";
128         } else {
129                 // Debug log
130                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): NO ENTRY FOUND! :-(<br />\n";
131                 DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},ref={$ref} - No entry found! :-(");
132         }
133
134         // Free result
135         SQL_FREERESULT($result);
136
137         // Return percents
138         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
139         return $percents;
140 }
141
142 // "Getter" for userid array which will return only one entry
143 function GET_REFBACK_USERID_ARRAY ($rid, $level) {
144         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
145         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):rid={$rid},level={$level}<br />\n";
146         // Init userids
147         $userIds = array();
148
149         // Look for all
150         $result = SQL_QUERY_ESC("SELECT userid
151 FROM `{!_MYSQL_PREFIX!}_user_refs`
152 WHERE refid=%s AND level=%s
153 ORDER BY userid ASC",
154         array($rid,$level), __FUNCTION__, __LINE__);
155
156         // Entries found?
157         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result)."<br />\n";
158         if (SQL_NUMROWS($result) > 0) {
159                 // Add all
160                 while ($content = SQL_FETCHARRAY($result)) {
161                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):rid={$rid},level={$level},userid={$content['userid']}<br />\n";
162                         $userIds[] = $content['userid'];
163                 } // END - while
164         } // END - if
165
166         // Free result
167         SQL_FREERESULT($result);
168
169         // Return array
170         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):rid={$rid},count()=".count($userIds)."<br />\n";
171         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
172         return $userIds;
173 }
174
175 // Update "refback table"
176 function updateRefbackTable ($uid) {
177         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
178         // Make it sure referal level zero (member him-/herself) is at least selected
179         if (empty($GLOBALS['cache_array']['back_level'])) $GLOBALS['cache_array']['back_level'] = 1;
180         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['back_level']}<br />\n";
181
182         // Init refid
183         $GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']] = 0;
184         $old = 0; $minus = 0;
185
186         // Check for his referal
187         $result_refid = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_data` WHERE refid=%s ORDER BY userid ASC",
188         array(bigintval($uid)), __FUNCTION__, __LINE__);
189
190         // When no entry was updated then we have to create it here
191         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found=".SQL_NUMROWS($result_refid)."<br />\n";
192         if (SQL_NUMROWS($result_refid) > 0) {
193                 // Load all refids
194                 while (list($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]) = SQL_FETCHROW($result_refid)) {
195                         // Remmber userid
196                         $GLOBALS['cache_array']['up_userid'][$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]] = $uid;
197
198                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]}<br />\n";
199                         // Refid set?
200                         if (($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']] > 0) && ($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']] != $uid) && (isset($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]))) {
201                                 // New userid?
202                                 if ((isset($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']-1])) && (isset($GLOBALS['cache_array']['up_userid'][$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']-1]]))) {
203                                         // New userid!
204                                         $old = $uid;
205                                         $uid = $GLOBALS['cache_array']['up_userid'][$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']-1]];
206                                         $minus = 1;
207                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},old={$old},level={$GLOBALS['cache_array']['back_level']},ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]} - NEW UID!<br />\n";
208                                 } // END - if
209
210                                 // Check existence
211                                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_user_refs` WHERE userid=%s AND level='%s' AND refid=%s LIMIT 1",
212                                 array(bigintval($uid), $GLOBALS['cache_array']['back_level'], bigintval($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']])), __FUNCTION__, __LINE__);
213
214                                 // Do we have no entry?
215                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['back_level']},ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]},minus={$minus},numRows=".SQL_NUMROWS($result)." - FOUND!<br />\n";
216                                 if (SQL_NUMROWS($result) == 0) {
217                                         // Insert this level
218                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['back_level']},ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]} - ADD!<br />\n";
219                                         SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_refs` (userid,level,refid) VALUES (%s,%s,%s)",
220                                         array(bigintval($uid), $GLOBALS['cache_array']['back_level'], bigintval($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']])), __FUNCTION__, __LINE__);
221
222                                         // Move to next referal level and count his counter one up!
223                                         $GLOBALS['cache_array']['back_level']++; updateRefbackTable($GLOBALS['cache_array']['up_refid'][($GLOBALS['cache_array']['back_level'] - 1)]);
224                                 } // END - if
225
226                                 // Do we have another level here?
227                                 if ((($GLOBALS['cache_array']['back_level']-$minus) > 0) && ($old > 0)) {
228                                         // Restore old one
229                                         $uid = $old;
230
231                                         // Shall we add this as well?
232                                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_user_refs` WHERE userid=%s AND level='%s' AND refid=%s LIMIT 1",
233                                         array(bigintval($uid), ($GLOBALS['cache_array']['back_level']-$minus), bigintval($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']])), __FUNCTION__, __LINE__);
234
235                                         // Do we have no entry?
236                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level=".($GLOBALS['cache_array']['back_level']-$minus).",ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]},numRows=".SQL_NUMROWS($result)." - BACK!<br />\n";
237                                         if (SQL_NUMROWS($result) == 0) {
238                                                 // Insert this level
239                                                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_refs` (userid,level,refid) VALUES (%s,%s,%s)",
240                                                 array(bigintval($uid), ($GLOBALS['cache_array']['back_level']-$minus), bigintval($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']])), __FUNCTION__, __LINE__);
241                                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level=".($GLOBALS['cache_array']['back_level']-$minus).",ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]} - RETURNED!<br />\n";
242                                         } // END - if
243                                 } // END - if
244                         } // END - if
245                 } // END - while
246
247                 // Free memory
248                 SQL_FREERESULT($result_refid);
249         } // END - if
250
251         // When he has a referal...
252         if ((($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']] == $uid) || ($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']] == 0)) && (GET_EXT_VERSION('cache') >= '0.1.2') && (!isset($GLOBALS['cache_array']['back_cached']))) {
253                 // Remove cache here
254                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']]} - CACHE!<br />\n";
255                 if ($GLOBALS['cache_instance']->loadCacheFile('refback')) $GLOBALS['cache_instance']->destroyCacheFile();
256                 $GLOBALS['cache_array']['back_cached'] = 1;
257         } // END - if
258
259         // "Walk" back here
260         $GLOBALS['cache_array']['back_level']--;
261         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['back_level']} - LEVEL!<br />\n";
262
263         // Fix empty refid
264         if (!isset($GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']-1])) $GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']-1] = 0;
265         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['back_level']},ref={$GLOBALS['cache_array']['up_refid'][$GLOBALS['cache_array']['back_level']-1]} - BACK!<br />\n";
266         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
267 }
268
269 // "Getter" for array for user refs in given level
270 function GET_USER_REFS ($uid, $level) {
271         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
272         // Default is no refs and no nickname
273         $add = '';
274         $refs = array();
275
276         // Do we have nickname extension installed?
277         if (EXT_IS_ACTIVE('nickname')) {
278                 $add = ", d.nickname";
279         } // END - if
280
281         // Get refs from database
282         $result = SQL_QUERY_ESC("SELECT r.id, r.refid, r.refback, r.points, d.status".$add."
283 FROM `{!_MYSQL_PREFIX!}_user_refs` AS r
284 LEFT JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
285 ON r.refid=d.userid
286 WHERE r.userid=%s AND r.level=%s
287 ORDER BY r.refid ASC",
288         array(bigintval($uid), bigintval($level)), __FUNCTION__, __LINE__);
289
290         // Are there some entries?
291         if (SQL_NUMROWS($result) > 0) {
292                 // Fetch all entries
293                 while ($row = SQL_FETCHARRAY($result)) {
294                         // Add row
295                         $refs[$row['id']] = $row;
296                 } // END - while
297         } // END - if
298
299         // Free result
300         SQL_FREERESULT($result);
301
302         // Return result
303         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
304         return $refs;
305 }
306
307 // "Getter" for refback entry
308 function GET_USER_REF_ENTRY ($id) {
309         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
310         // Default data is nothing
311         $data = array();
312
313         // Secure id number
314         $id = bigintval($id);
315
316         // Get entry from database
317         $result = SQL_QUERY_ESC("SELECT id, refid, refback, level FROM `{!_MYSQL_PREFIX!}_user_refs` WHERE `id`=%s AND `userid`=%s LIMIT 1",
318         array($id, getUserId()), __FUNCTION__, __LINE__);
319
320         // Is there an entry?
321         if (SQL_NUMROWS($result) == 1) {
322                 // Fetch data
323                 $data = SQL_FETCHARRAY($result);
324         } // END - if
325
326         // Free result
327         SQL_FREERESULT($result);
328
329         // Return entry
330         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
331         return $data;
332 }
333
334 // Update refback percents (but with some sanity-checks!
335 function REFBACK_CHANGE_MEMBER_PERCENTS ($id, $percents) {
336         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
337         // Default status is failed
338         $status['message'] = getMessage('MEMBER_REFBACK_ERROR_GENERAL');
339
340         // Do some sanity-checks
341         if (!IS_MEMBER()) {
342                 // No member!
343                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_NO_MEMBER');
344                 return $status;
345         } elseif ("".$id."" != ''.($id + 0)."") {
346                 // No number!
347                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_INVALID_ID_NUMBER');
348                 return $status;
349         } elseif (($percents < 0) || ($percents > 100)) {
350                 // Percentage is not valid!
351                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_INVALID_PERCENTAGE');
352                 return $status;
353         }
354
355         // Get ref entry
356         $dummy = GET_USER_REF_ENTRY($id);
357
358         // Is this valid?
359         if (count($dummy) == 0) {
360                 // ID does not belong to user!
361                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_ID_MISMATCH');
362                 return $status;
363         } // END - if
364
365         // Revert german commata
366         $percents = convertCommaToDot($percents);
367
368         // Update entry
369         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_refs` SET refback='%s' WHERE `id`=%s AND `userid`=%s LIMIT 1",
370         array($percents, $id, getUserId()), __FUNCTION__, __LINE__);
371
372         // Entry updated?
373         if (SQL_AFFECTEDROWS() < 1) {
374                 // Entry not updated!
375                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_NOT_UPDATED');
376                 return $status;
377         } // END - if
378
379         // Prepare email content
380         $content = array(
381                 'percents' => translateComma($percents),
382                 'refid'    => $dummy['refid'],
383                 'level'    => $dummy['level']
384         );
385
386         // Load member email template
387         $mail = LOAD_EMAIL_TEMPLATE("member_refback", $content, getUserId());
388
389         // Send email to user
390         sendEmail($dummy['refid'], getMessage('MEMBER_REFBACK_SUBJECT'), $mail);
391
392         // Send admin notification
393         sendAdminNotification(getMessage('ADMIN_REFBACK_SUBJECT'), "admin_refback", $content, getUserId());
394
395         // All fine!
396         $status['ok'] = true;
397
398         // Return status array
399         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
400         return $status;
401 }
402 //
403 ?>