Huge rewrite of default parameters, ext-network continued:
[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 - 2009 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         die();
42 }
43
44 // Payback refback for refid and reduce it for current user
45 function addRefbackPoints ($userid, $ref, $points, $ref_points) {
46         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
47         // Back ref depths
48         $GLOBALS['refback_depth'][$userid][$ref] = $GLOBALS['ref_level'];
49
50         // Init points
51         $return = $points;
52
53         // Get all ref levels
54         $result_refs = SQL_QUERY("SELECT `level`, `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level` > 0 ORDER BY `level` ASC",
55                 __FUNCTION__, __LINE__);
56
57         // "Walk" through all level
58         while ($content = SQL_FETCHARRAY($result_refs)) {
59                 // Reset ref depths
60                 // @TODO Try to rewrite the following unset()
61                 unset($GLOBALS['ref_level']);
62
63                 // "Walk" through all refids
64                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref},level={$content['level']},points={$points}<br />");
65                 foreach (getArrayFromRefbackLevel($userid, $content['level']) as $refid) {
66                         // Skip level zero or if both are the same
67                         if ($userid == $refid) continue;
68
69                         // Get refback percents
70                         $percents = getRefbackPercents($userid, $refid);
71                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref},refid={$refid},points={$points},percents={$percents}<br />");
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 />");
76                                 // Calculate points for refback
77                                 $refback = $points * ($content['percents'] / 100) * ($percents / 100);
78
79                                 // Update refback table ("refid" and "userid" 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, $userid), __FUNCTION__, __LINE__);
82                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):refback={$refback},userid={$userid},refid={$refid} - UPDATE! (".SQL_AFFECTEDROWS().")<br />");
83
84                                 // Add points again, but only directly
85                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):refback={$refback}<br />");
86                                 addPointsDirectly(sprintf("refback:%s", $refid), $userid, $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 />");
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['refback_depth'][$userid][$ref];
103
104         // Return them
105         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
106         return $return;
107 }
108
109 // "Getter" for refback percents
110 function getRefbackPercents ($userid, $ref) {
111         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
112         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref}<br />");
113         // Skip identical ids
114         if ($userid == $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, $userid), __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 />");
128         } else {
129                 // Debug log
130                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): NO ENTRY FOUND! :-(<br />");
131                 logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},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 />");
139         return $percents;
140 }
141
142 // "Getter" for userid array which will return only one entry
143 function getArrayFromRefbackLevel ($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 />");
146         // Init userids
147         $userIds = array();
148
149         // Look for all
150         $result = SQL_QUERY_ESC("SELECT
151         `userid`
152 FROM
153         `{?_MYSQL_PREFIX?}_user_refs`
154 WHERE
155         `refid`=%s AND `level`=%s
156 ORDER BY
157         `userid` ASC",
158                 array($rid, $level), __FUNCTION__, __LINE__);
159
160         // Entries found?
161         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result)."<br />");
162         if (SQL_NUMROWS($result) > 0) {
163                 // Add all
164                 while ($content = SQL_FETCHARRAY($result)) {
165                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):rid={$rid},level={$level},userid={$content['userid']}<br />");
166                         $userIds[] = $content['userid'];
167                 } // END - while
168         } // END - if
169
170         // Free result
171         SQL_FREERESULT($result);
172
173         // Return array
174         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):rid={$rid},count()=".count($userIds)."<br />");
175         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
176         return $userIds;
177 }
178
179 // Update "refback table"
180 function updateRefbackTable ($userid) {
181         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
182         // Make it sure referal level zero (member him-/herself) is at least selected
183         if (empty($GLOBALS['refback_level'])) $GLOBALS['refback_level'] = 1;
184         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['refback_level']}<br />");
185
186         // Init refid
187         $GLOBALS['refback_refid'][$GLOBALS['refback_level']] = '0';
188         $old = '0'; $minus = '0';
189
190         // Check for his referal
191         $result_refid = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC",
192                 array(bigintval($userid)), __FUNCTION__, __LINE__);
193
194         // When no entry was updated then we have to create it here
195         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found=".SQL_NUMROWS($result_refid)."<br />");
196         if (SQL_NUMROWS($result_refid) > 0) {
197                 // Load all refids
198                 while (list($GLOBALS['refback_refid'][$GLOBALS['refback_level']]) = SQL_FETCHROW($result_refid)) {
199                         // Remmber userid
200                         $GLOBALS['refback_userid'][$GLOBALS['refback_refid'][$GLOBALS['refback_level']]] = $userid;
201
202                         // Refid set?
203                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']]}<br />");
204                         if (($GLOBALS['refback_refid'][$GLOBALS['refback_level']] > 0) && ($GLOBALS['refback_refid'][$GLOBALS['refback_level']] != $userid) && (isset($GLOBALS['refback_refid'][$GLOBALS['refback_level']]))) {
205                                 // New userid?
206                                 if ((isset($GLOBALS['refback_refid'][$GLOBALS['refback_level']-1])) && (isset($GLOBALS['refback_userid'][$GLOBALS['refback_refid'][$GLOBALS['refback_level']-1]]))) {
207                                         // New userid!
208                                         $old = $userid;
209                                         $userid = $GLOBALS['refback_userid'][$GLOBALS['refback_refid'][$GLOBALS['refback_level']-1]];
210                                         $minus = 1;
211                                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},old={$old},level={$GLOBALS['refback_level']},ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']]} - NEW UID!<br />");
212                                 } // END - if
213
214                                 // Check existence
215                                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `userid`=%s AND `level`='%s' AND `refid`=%s LIMIT 1",
216                                         array(bigintval($userid), $GLOBALS['refback_level'], bigintval($GLOBALS['refback_refid'][$GLOBALS['refback_level']])), __FUNCTION__, __LINE__);
217
218                                 // Do we have no entry?
219                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['refback_level']},ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']]},minus={$minus},numRows=".SQL_NUMROWS($result)." - FOUND!<br />");
220                                 if (SQL_NUMROWS($result) == '0') {
221                                         // Insert this level
222                                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['refback_level']},ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']]} - ADD!<br />");
223                                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`,`level`,`refid`) VALUES (%s,%s,%s)",
224                                                 array(bigintval($userid), $GLOBALS['refback_level'], bigintval($GLOBALS['refback_refid'][$GLOBALS['refback_level']])), __FUNCTION__, __LINE__);
225
226                                         // Move to next referal level and count his counter one up!
227                                         $GLOBALS['refback_level']++; updateRefbackTable($GLOBALS['refback_refid'][($GLOBALS['refback_level'] - 1)]);
228                                 } // END - if
229
230                                 // Do we have another level here?
231                                 if ((($GLOBALS['refback_level']-$minus) > 0) && ($old > 0)) {
232                                         // Restore old one
233                                         $userid = $old;
234
235                                         // Shall we add this as well?
236                                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `userid`=%s AND `level`='%s' AND `refid`=%s LIMIT 1",
237                                                 array(bigintval($userid), ($GLOBALS['refback_level']-$minus), bigintval($GLOBALS['refback_refid'][$GLOBALS['refback_level']])), __FUNCTION__, __LINE__);
238
239                                         // Do we have no entry?
240                                         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level=".($GLOBALS['refback_level']-$minus).",ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']]},numRows=".SQL_NUMROWS($result)." - BACK!<br />");
241                                         if (SQL_NUMROWS($result) == '0') {
242                                                 // Insert this level
243                                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`,`level`,`refid`) VALUES (%s,%s,%s)",
244                                                         array(bigintval($userid), ($GLOBALS['refback_level']-$minus), bigintval($GLOBALS['refback_refid'][$GLOBALS['refback_level']])), __FUNCTION__, __LINE__);
245                                                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level=".($GLOBALS['refback_level']-$minus).",ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']]} - RETURNED!<br />");
246                                         } // END - if
247                                 } // END - if
248                         } // END - if
249                 } // END - while
250
251                 // Free memory
252                 SQL_FREERESULT($result_refid);
253         } // END - if
254
255         // When he has a referal...
256         if ((($GLOBALS['refback_refid'][$GLOBALS['refback_level']] == $userid) || ($GLOBALS['refback_refid'][$GLOBALS['refback_level']] == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2')) && (!isset($GLOBALS['refback_cached']))) {
257                 // Remove cache here
258                 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']]} - CACHE!<br />");
259                 if ($GLOBALS['cache_instance']->loadCacheFile('refback')) $GLOBALS['cache_instance']->removeCacheFile();
260                 $GLOBALS['refback_cached'] = 1;
261         } // END - if
262
263         // "Walk" back here
264         $GLOBALS['refback_level']--;
265         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['refback_level']} - LEVEL!<br />");
266
267         // Fix empty refid
268         if (!isset($GLOBALS['refback_refid'][$GLOBALS['refback_level']-1])) $GLOBALS['refback_refid'][$GLOBALS['refback_level']-1] = '0';
269         //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},level={$GLOBALS['refback_level']},ref={$GLOBALS['refback_refid'][$GLOBALS['refback_level']-1]} - BACK!<br />");
270         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
271 }
272
273 // "Getter" for array for user refs in given level
274 function getArrayFromRefbackUserRefs ($userid, $level) {
275         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
276         // Default is no refs and no nickname
277         $add = '';
278         $refs = array();
279
280         // Do we have nickname extension installed?
281         if (isExtensionActive('nickname')) {
282                 $add = ", d.nickname";
283         } // END - if
284
285         // Get refs from database
286         $result = SQL_QUERY_ESC("SELECT
287         r.id,
288         r.refid,
289         r.refback,
290         r.points,
291         d.status".$add."
292 FROM
293         `{?_MYSQL_PREFIX?}_user_refs` AS r
294 LEFT JOIN
295         `{?_MYSQL_PREFIX?}_user_data` AS d
296 ON
297         r.refid=d.userid
298 WHERE
299         r.userid=%s AND r.level=%s
300 ORDER BY
301         r.refid ASC",
302                 array(bigintval($userid), bigintval($level)), __FUNCTION__, __LINE__);
303
304         // Are there some entries?
305         if (SQL_NUMROWS($result) > 0) {
306                 // Fetch all entries
307                 while ($row = SQL_FETCHARRAY($result)) {
308                         // Add row
309                         $refs[$row['id']] = $row;
310                 } // END - while
311         } // END - if
312
313         // Free result
314         SQL_FREERESULT($result);
315
316         // Return result
317         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
318         return $refs;
319 }
320
321 // "Getter" for refback entry
322 function getArrayFromUserRefbackData ($id) {
323         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
324         // Default data is nothing
325         $data = array();
326
327         // Secure id number
328         $id = bigintval($id);
329
330         // Get entry from database
331         $result = SQL_QUERY_ESC("SELECT `id`, `refid`, `refback`, `level` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `id`=%s AND `userid`=%s LIMIT 1",
332                 array($id, getMemberId()), __FUNCTION__, __LINE__);
333
334         // Is there an entry?
335         if (SQL_NUMROWS($result) == 1) {
336                 // Fetch data
337                 $data = SQL_FETCHARRAY($result);
338         } // END - if
339
340         // Free result
341         SQL_FREERESULT($result);
342
343         // Return entry
344         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
345         return $data;
346 }
347
348 // Update refback percents (but with some sanity-checks!
349 function updateMemberRefbackPercents ($id, $percents) {
350         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
351         // Default status is failed
352         $status['message'] = getMessage('MEMBER_REFBACK_ERROR_GENERAL');
353
354         // Do some sanity-checks
355         if (!isMember()) {
356                 // No member!
357                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_NO_MEMBER');
358                 return $status;
359         } elseif (''.$id.'' != ''.($id + 0).'') {
360                 // No number!
361                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_INVALID_ID_NUMBER');
362                 return $status;
363         } elseif (($percents < 0) || ($percents > 100)) {
364                 // Percentage is not valid!
365                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_INVALID_PERCENTAGE');
366                 return $status;
367         }
368
369         // Get ref entry
370         $dummy = getArrayFromUserRefbackData($id);
371
372         // Is this valid?
373         if (count($dummy) == '0') {
374                 // id does not belong to user!
375                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_ID_MISMATCH');
376                 return $status;
377         } // END - if
378
379         // Revert german commata
380         $percents = convertCommaToDot($percents);
381
382         // Update entry
383         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_refs` SET `refback`='%s' WHERE `id`=%s AND `userid`=%s LIMIT 1",
384                 array($percents, $id, getMemberId()), __FUNCTION__, __LINE__);
385
386         // Entry updated?
387         if (SQL_AFFECTEDROWS() < 1) {
388                 // Entry not updated!
389                 $status['message'] = getMessage('MEMBER_REFBACK_ERROR_NOT_UPDATED');
390                 return $status;
391         } // END - if
392
393         // Prepare email content
394         $content = array(
395                 'percents' => translateComma($percents),
396                 'refid'    => $dummy['refid'],
397                 'level'    => $dummy['level']
398         );
399
400         // Load member email template
401         $mail = loadEmailTemplate('member_refback', $content, getMemberId());
402
403         // Send email to user
404         sendEmail($dummy['refid'], getMessage('MEMBER_REFBACK_SUBJECT'), $mail);
405
406         // Send admin notification
407         sendAdminNotification(getMessage('ADMIN_REFBACK_SUBJECT'), 'admin_refback', $content, getMemberId());
408
409         // All fine!
410         $status['ok'] = true;
411
412         // Return status array
413         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
414         return $status;
415 }
416 //
417 ?>