4c931566ad8da8f87688334143e513372de0896a
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 08/31/2008 *
4  * ===============                              Last change: 08/31/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : surfbar_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for surfbar                            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die Surfbar                      *
12  * -------------------------------------------------------------------- *
13  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // Admin has added an URL with given user id
41 function SURFBAR_ADMIN_ADD_URL ($url, $uid, $reward, $costs, $paymentId) {
42         // Do some pre-checks
43         if (!IS_ADMIN()) {
44                 // Not an admin
45                 return false;
46         } elseif (!VALIDATE_URL($url)) {
47                 // URL invalid
48                 return false;
49         } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
50                 // URL already found in surfbar!
51                 return false;
52         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
53                 // No more allowed!
54                 return false;
55         }
56
57         // Register the new URL
58         return SURFBAR_REGISTER_URL($url, $uid, $reward, $costs, $paymentId, "CONFIRMED", "unlock");
59 }
60 // Member has added an URL
61 function SURFBAR_MEMBER_ADD_URL ($url) {
62         global $_CONFIG;
63
64         // Do some pre-checks
65         if (!IS_LOGGED_IN()) {
66                 // Not a member
67                 return false;
68         } elseif (!VALIDATE_URL($url)) {
69                 // URL invalid
70                 return false;
71         } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
72                 // URL already found in surfbar!
73                 return false;
74         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
75                 // No more allowed!
76                 return false;
77         }
78
79         // Do we have fixed or dynamic payment model?
80         $reward = SURFBAR_DETERMINE_REWARD();
81         $costs  = SURFBAR_DETERMINE_COSTS();
82
83         // Register the new URL
84         return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], $reward, $costs);
85 }
86 // Looks up by an URL
87 function SURFBAR_LOOKUP_BY_URL ($url) {
88         // Now lookup that given URL by itself
89         $urlArray = SURFBAR_GET_URL_DATA($url, "url");
90
91         // Was it found?
92         return (count($urlArray) > 0);
93 }
94 // Load URL data by given search term and column
95 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
96         global $lastUrlData;
97
98         // By default nothing is found
99         $lastUrlData = array();
100
101         // Is the column an id number?
102         if (($column == "id") || ($column == "userid")) {
103                 // Extra secure input
104                 $searchTerm = bigintval($searchTerm);
105         } // END - if
106
107         // Look up the record
108         $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
109 FROM "._MYSQL_PREFIX."_surfbar_urls
110 WHERE %s='%s'
111 ORDER BY %s %s",
112                 array($column, $searchTerm, $order, $sort), __FILE__, __LINE__);
113
114         // Is there at least one record?
115         if (SQL_NUMROWS($result) > 0) {
116                 // Then load all!
117                 while ($dataRow = SQL_FETCHARRAY($result)) {
118                         // Shall we group these results?
119                         if ($group == "id") {
120                                 // Add the row by id as index
121                                 $lastUrlData[$dataRow['id']] = $dataRow;
122                         } else {
123                                 // Group entries
124                                 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
125                         }
126                 } // END - while
127         } // END - if
128
129         // Free the result
130         SQL_FREERESULT($result);
131
132         // Return the result
133         return $lastUrlData;
134 }
135 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
136 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $costs, $paymentId=0, $status="PENDING", $addMode="reg") {
137         global $_CONFIG;
138
139         // Make sure by the user registered URLs are always pending
140         if ($addMode == "reg") $status = "PENDING";
141
142         // Prepare content
143         $content = array(
144                 'url'         => $url,
145                 'frametester' => FRAMETESTER($url),
146                 'uid'         => $uid,
147                 'reward'      => $reward,
148                 'costs'       => $costs,
149                 'payment_id'  => $paymentId,
150                 'status'      => $status
151         );
152
153         // Insert the URL into database
154         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
155
156         // Translate status, reward and costs
157         $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
158         $content['reward'] = TRANSLATE_COMMA($content['reward']);
159         $content['costs']  = TRANSLATE_COMMA($content['costs']);
160
161         // If in reg-mode we notify admin
162         if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
163                 // Notify admin even when he as unlocked an email
164                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
165         } // END - if
166
167         // Send mail to user
168         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
169
170         // Return the insert id
171         return $content['insert_id'];
172 }
173 // Inserts an url by given data array and return the insert id
174 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
175         // Just run the insert query for now
176         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, payment_id, status) VALUES(%s, '%s', %s, %s, %d, '%s')",
177                 array(
178                         bigintval($urlData['uid']),
179                         $urlData['url'],
180                         (float)$urlData['reward'],
181                         (float)$urlData['costs'],
182                         bigintval($urlData['payment_id']),
183                         $urlData['status']
184                 ), __FILE__, __LINE__
185         );
186
187         // Return insert id
188         return SQL_INSERTID();
189 }
190 // Notify admin(s) with a selected message and content
191 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
192         // Prepare template name
193         $templateName = sprintf("admin_surfbar_%s", $messageType);
194
195         // Prepare subject
196         $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
197                 strtoupper($messageType)
198         );
199         eval($eval);
200
201         // Send the notification out
202         SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
203 }
204 // Notify the user about the performed action
205 function SURFBAR_NOTIFY_USER ($messageType, $content) {
206         // Prepare template name
207         $templateName = sprintf("member_surfbar_%s", $messageType);
208
209         // Prepare subject
210         $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
211                 strtoupper($messageType)
212         );
213         eval($eval);
214
215         // Load template
216         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
217
218         // Send the email
219         SEND_EMAIL($content['uid'], $subject, $mailText);
220 }
221 // Translate the URL status
222 function SURFBAR_TRANSLATE_STATUS ($status) {
223         // Create constant name
224         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
225
226         // Set default translated status
227         $statusTranslated = "!".$constantName."!";
228
229         // Generate eval() command
230         if (defined($constantName)) {
231                 $eval = "\$statusTranslated = ".$constantName.";";
232                 eval($eval);
233         } // END - if
234
235         // Return result
236         return $statusTranslated;
237 }
238 // Determine reward
239 function SURFBAR_DETERMINE_REWARD () {
240         global $_CONFIG;
241
242         // Do we have static or dynamic?
243         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
244                 // Static model, so choose static values
245                 $reward = $_CONFIG['surfbar_static_reward'];
246         } else {
247                 // Dynamic model, so calculate values
248                 die("DYNAMIC payment model not yet supported!");
249         }
250
251         // Return reward
252         return $reward;
253 }
254 // Determine costs
255 function SURFBAR_DETERMINE_COSTS () {
256         global $_CONFIG;
257
258         // Do we have static or dynamic?
259         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
260                 $costs  = $_CONFIG['surfbar_static_costs'];
261         } else {
262                 // Dynamic model, so calculate values
263                 die("DYNAMIC payment model not yet supported!");
264         }
265
266         // Return costs
267         return $costs;
268 }
269 // Determine right template name
270 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
271         // Default is the frameset
272         $templateName = "surfbar_frameset";
273
274         // Any frame set? ;-)
275         if (isset($_GET['frame'])) {
276                 // Use the frame as a template name part... ;-)
277                 $templateName = sprintf("surfbar_frame_%s",
278                         SQL_ESCAPE($_GET['frame'])
279                 );
280         } // END - if
281
282         // Return result
283         return $templateName;
284 }
285 // Check if the "reload lock" of the current user is full, call this function
286 // before you call SURFBAR_CHECK_RELOAD_LOCK().
287 function SURFBAR_CHECK_RELOAD_FULL() {
288         global $SURFBAR_CACHE, $_CONFIG;
289
290         // Default is full!
291         $isFull = true;
292
293         // Do we have static or dynamic mode?
294         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
295                 // Cache static reload lock
296                 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
297                 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
298
299                 // Ask the database
300                 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
301 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
302 LIMIT 1",
303                         array($GLOBALS['userid']), __FILE__, __LINE__
304                 );
305
306                 // Fetch row
307                 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
308
309                 // Is it null?
310                 if (is_null($SURFBAR_CACHE['user_locks'])) {
311                         // Then fix it to zero!
312                         $SURFBAR_CACHE['user_locks'] = 0;
313                 } // END - if
314
315                 // Free result
316                 SQL_FREERESULT($result);
317
318                 // Get total URLs
319                 $total = SURFBAR_GET_TOTAL_URLS();
320
321                 // Do we have some URLs in lock? Admins can always surf on own URLs!
322                 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
323                 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
324         } else {
325                 // Dynamic model...
326                 die("DYNAMIC not yet implemented!");
327         }
328
329         // Return result
330         return $isFull;
331 }
332 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
333 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
334         // Determine depleted user account
335         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
336
337         // Get amount from database
338         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
339 FROM "._MYSQL_PREFIX."_surfbar_urls
340 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
341                 array($status), __FILE__, __LINE__
342         );
343
344         // Fetch row
345         list($cnt) = SQL_FETCHROW($result);
346
347         // Free result
348         SQL_FREERESULT($result);
349
350         // Return result
351         return $cnt;
352 }
353 // Check wether the user is allowed to book more URLs
354 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
355         global $_CONFIG;
356
357         // Simply check it out
358         return (SURFBAR_GET_TOTAL_USER_URLS($uid) < $_CONFIG['surfbar_max_order']);
359 }
360 // Get total amount of URLs of given status for current user
361 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0) {
362         global $_CONFIG;
363
364         // Is the user 0 and user is logged in?
365         if (($uid == 0) && (IS_LOGGED_IN())) {
366                 // Then use this userid
367                 $uid = $GLOBALS['userid'];
368         } elseif ($uid == 0) {
369                 // Error!
370                 return ($_CONFIG['surfbar_max_order'] + 1);
371         }
372
373         // Get amount from database
374         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
375 FROM "._MYSQL_PREFIX."_surfbar_urls
376 WHERE userid=%s
377 LIMIT %s",
378                 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
379         );
380
381         // Fetch row
382         list($cnt) = SQL_FETCHROW($result);
383
384         // Free result
385         SQL_FREERESULT($result);
386
387         // Return result
388         return $cnt;
389 }
390 // Generate a validation code for the given id number
391 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
392         global $_CONFIG, $SURFBAR_CACHE;
393
394         // Generate a code until the length matches
395         $valCode = "";
396         while (strlen($valCode) != $_CONFIG['code_length']) {
397                 // Is the salt set?
398                 if (empty($salt)) {
399                         // Generate random hashed string
400                         $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
401                         //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
402                 } else {
403                         // Use this as salt!
404                         $SURFBAR_CACHE['salt'] = $salt;
405                         //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
406                 }
407
408                 // ... and now the validation code
409                 $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
410                 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
411         } // END - while
412
413         // Hash it with md5() and salt it with the random string
414         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
415
416         // Finally encrypt it PGP-like and return it
417         $valHashedCode = generatePassString($hashedCode);
418         //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
419         return $valHashedCode;
420 }
421 // Check validation code
422 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
423         global $SURFBAR_CACHE;
424
425         // Secure id number
426         $id = bigintval($id);
427
428         // Now generate the code again
429         $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
430
431         // Return result of checking hashes and salts
432         //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
433         //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
434         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
435 }
436 // Lockdown the userid/id combination (reload lock)
437 function SURFBAR_LOCKDOWN_ID ($id) {
438         //* DEBUG: */ print "LOCK!");
439         ///* DEBUG: */ return;
440         // Just add it to the database
441         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
442                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
443
444         // Remove the salt from database
445         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
446                 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
447 }
448 // Pay points to the user and remove it from the sender
449 function SURFBAR_PAY_POINTS ($id) {
450         global $SURFBAR_CACHE, $_CONFIG;
451
452         // Re-configure ref-system to surfbar levels
453         $_CONFIG['db_percents'] = "percent";
454         $_CONFIG['db_table']    = "surfbar_reflevels";
455
456         // Remove it from the URL owner
457         //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
458         SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
459
460         // Book it to the user
461         //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
462         ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
463 }
464 // Updates the statistics of current URL/userid
465 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
466         global $_CONFIG;
467
468         // Update views_total
469         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
470                 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
471
472         // Update the stats entry
473         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
474                 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
475
476         // Was that update okay?
477         if (SQL_AFFECTEDROWS() == 0) {
478                 // No, then insert entry
479                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
480                         array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
481         } // END - if
482
483         // Update total/daily/weekly/monthly counter
484         $_CONFIG['surfbar_total_counter']++;
485         $_CONFIG['surfbar_daily_counter']++;
486         $_CONFIG['surfbar_weekly_counter']++;
487         $_CONFIG['surfbar_monthly_counter']++;
488
489         // Update config as well
490         UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
491 }
492 // Update the salt for validation and statistics
493 function SURFBAR_UPDATE_SALT_STATS () {
494         // Update statistics record
495         SURFBAR_UPDATE_INSERT_STATS_RECORD();
496
497         // Simply store the salt from cache away in database...
498         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
499                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
500
501         // Debug message
502         //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
503
504         // Was that okay?
505         if (SQL_AFFECTEDROWS() == 0) {
506                 // Insert missing entry!
507                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
508                         array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
509         } // END - if
510
511         // Debug message
512         //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
513
514         // Return if the update was okay
515         return (SQL_AFFECTEDROWS() == 1);
516 }
517 // Check if the reload lock is active for given id
518 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
519         //DEBUG_LOG(__FUNCTION__.":id={$id}");
520         // Ask the database
521         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
522 FROM "._MYSQL_PREFIX."_surfbar_locks
523 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
524 ORDER BY last_surfed ASC
525 LIMIT 1",
526                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
527         );
528
529         // Fetch counter
530         list($cnt) = SQL_FETCHROW($result);
531
532         // Free result
533         SQL_FREERESULT($result);
534
535         // Return check
536         //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
537         return ($cnt == 1);
538 }
539 // Determine which user hash no more points left
540 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
541         // Init array
542         $UIDs = array();
543
544         // Do we have a current user id?
545         if (IS_LOGGED_IN()) {
546                 // Then add this as well
547                 $UIDs[] = $GLOBALS['userid'];
548
549                 // Get all userid except logged in one
550                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
551 WHERE userid != %s AND status='CONFIRMED'
552 GROUP BY userid
553 ORDER BY userid ASC",
554                         array($GLOBALS['userid']), __FILE__, __LINE__);
555         } else {
556                 // Get all userid
557                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
558 WHERE status='CONFIRMED'
559 GROUP BY userid
560 ORDER BY userid ASC", __FILE__, __LINE__);
561         }
562
563         // Load all userid
564         while (list($uid) = SQL_FETCHROW($result)) {
565                 // Get total points
566                 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
567                 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
568
569                 // Shall we add this to ignore?
570                 if ($points <= 0) {
571                         // Ignore this one!
572                         //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
573                         $UIDs[] = $uid;
574                 } // END - if
575         } // END - while
576
577         // Free result
578         SQL_FREERESULT($result);
579
580         // Debug message
581         //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
582
583         // Return result
584         return $UIDs;
585 }
586 // Determine how many users are Online in surfbar
587 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
588         global $_CONFIG;
589
590         // Count all users in surfbar modue and return the value
591         $result = SQL_QUERY_ESC("SELECT COUNT(id) FROM "._MYSQL_PREFIX."_surfbar_stats WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) >= %s",
592                 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
593
594         // Fetch count
595         list($cnt) = SQL_FETCHROW($result);
596
597         // Free result
598         SQL_FREERESULT($result);
599
600         // Return result
601         return $cnt;
602 }
603 // Determine next id for surfbar view, always call this before you call other
604 // getters below this function!!!
605 function SURFBAR_GET_NEXT_ID ($id = 0) {
606         global $SURFBAR_CACHE, $_CONFIG;
607
608         // Default is no id!
609         $nextId = 0; $randNum = 0;
610
611         // Is the ID set?
612         if ($id == 0) {
613                 // Prepare some arrays
614                 $IDs = array();
615                 $USE = array();
616                 $ignored = array();
617
618                 // Get all id from locks within the timestamp
619                 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed)
620 FROM
621         "._MYSQL_PREFIX."_surfbar_locks
622 WHERE
623         userid=%s
624 ORDER BY
625         id ASC", array($GLOBALS['userid']),
626                         __FILE__, __LINE__);
627
628                 // Load all entries
629                 while (list($id, $url, $last) = SQL_FETCHROW($result)) {
630                         //DEBUG_LOG(__FUNCTION__.":next - id={$id},url={$url},last={$last}");
631                         // Skip entries that are too old
632                         if (($last < (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
633                                 //DEBUG_LOG(__FUNCTION__.":okay - id={$id},url={$url},last={$last}");
634                                 // Add only if missing or bigger
635                                 if ((!isset($IDs[$url])) || ($IDs[$url] <= $last)) {
636                                         // Add this ID
637                                         //DEBUG_LOG(__FUNCTION__.":ADD - id={$id},url={$url},last={$last}");
638                                         $IDs[$url] = $last;
639                                         $USE[$url] = $id;
640                                 } // END - if
641                         } else {
642                                 // Ignore these old entries!
643                                 //DEBUG_LOG(__FUNCTION__.":ignore - id={$id},url={$url},last={$last}");
644                                 $ignored[] = $url;
645                                 unset($IDs[$url]);
646                                 unset($USE[$url]);
647                         }
648                 } // END - while
649
650                 // Free result
651                 SQL_FREERESULT($result);
652
653                 // Shall we add some ids?
654                 $ADD = "";
655                 if (count($USE) > 0) {
656                         $ADD = " AND l.id IN (".implode(",", $USE).")";
657                 } // END - if
658
659                 // Determine depleted user account
660                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
661
662                 // Count max availabe entries
663                 $result = SQL_QUERY("SELECT sbu.id AS cnt
664 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
665 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
666 ON sbu.payment_id=p.id
667 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
668 ON sbu.id=sbs.url_id
669 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
670 ON sbu.id=l.url_id
671 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
672 GROUP BY sbu.id", __FILE__, __LINE__);
673
674                 // Log last query
675                 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
676
677                 // Fetch max rand
678                 $maxRand = SQL_NUMROWS($result);
679
680                 // Free result
681                 SQL_FREERESULT($result);
682
683                 // If more than one URL can be called generate the random number!
684                 if ($maxRand > 1) {
685                         // Generate random number
686                         $randNum = mt_rand(0, $maxRand);
687                 } // END - if
688
689                 // And query the database
690                 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
691                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, p.time, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
692 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
693 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
694 ON sbu.payment_id=p.id
695 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
696 ON sbu.id=sbs.url_id
697 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
698 ON sbu.id=l.url_id
699 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
700 GROUP BY sbu.id
701 ORDER BY l.last_surfed ASC, sbu.id ASC
702 LIMIT %s,1",
703                         array($randNum), __FILE__, __LINE__
704                 );
705         } else {
706                 // Get data from specified id number
707                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, p.time, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
708 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
709 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
710 ON sbu.payment_id=p.id
711 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
712 ON sbu.id=sbs.url_id
713 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
714 ON sbu.id=l.url_id
715 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
716 LIMIT 1",
717                         array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
718                 );
719         }
720
721         // Is there an id number?
722         //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
723         if (SQL_NUMROWS($result) == 1) {
724                 // Load/cache data
725                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
726                 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
727                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
728
729                 // Is the time there?
730                 if (is_null($SURFBAR_CACHE['time'])) {
731                         // Then repair it wit the static!
732                         //DEBUG_LOG(__FUNCTION__.":time - STATIC!");
733                         $SURFBAR_CACHE['time'] = $_CONFIG['surfbar_static_time'];
734                 } // END - if
735
736                 // Is the last salt there?
737                 if (is_null($SURFBAR_CACHE['last_salt'])) {
738                         // Then repair it wit the static!
739                         //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
740                         $SURFBAR_CACHE['last_salt'] = "";
741                 } // END - if
742
743                 // Fix missing last_surfed
744                 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
745                         // Fix it here
746                         //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
747                         $SURFBAR_CACHE['last_surfed'] = "0";
748                 } // END - if
749
750                 // Get base/fixed reward and costs
751                 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
752                 $SURFBAR_CACHE['costs']  = SURFBAR_DETERMINE_COSTS();
753                 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
754
755                 // Only in dynamic model add the dynamic bonus!
756                 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
757                         // Calculate dynamic reward/costs and add it
758                         $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
759                         $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
760                         //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
761                 } // END - if
762
763                 // Now get the id
764                 $nextId = SURFBAR_GET_ID();
765         } // END - if
766
767         // Free result
768         SQL_FREERESULT($result);
769
770         // Return result
771         //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
772         return $nextId;
773 }
774 // ----------------------------------------------------------------------------
775 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
776 // $SURFBAR_CACHE ARRAY!
777 // ----------------------------------------------------------------------------
778 // Private getter for data elements
779 function SURFBAR_GET_DATA ($element) {
780         global $SURFBAR_CACHE;
781         //DEBUG_LOG(__FUNCTION__.":element={$element}");
782
783         // Default is null
784         $data = null;
785
786         // Is the entry there?
787         if (isset($SURFBAR_CACHE[$element])) {
788                 // Then take it
789                 $data = $SURFBAR_CACHE[$element];
790         } else { // END - if
791                 print("<pre>");
792                 print_r($SURFBAR_CACHE);
793                 debug_print_backtrace();
794                 die("</pre>");
795         }
796
797         // Return result
798         //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
799         return $data;
800 }
801 // Getter for reward from cache
802 function SURFBAR_GET_REWARD () {
803         // Get data element and return its contents
804         return SURFBAR_GET_DATA('reward');
805 }
806 // Getter for costs from cache
807 function SURFBAR_GET_COSTS () {
808         // Get data element and return its contents
809         return SURFBAR_GET_DATA('costs');
810 }
811 // Getter for URL from cache
812 function SURFBAR_GET_URL () {
813         // Get data element and return its contents
814         return SURFBAR_GET_DATA('url');
815 }
816 // Getter for salt from cache
817 function SURFBAR_GET_SALT () {
818         // Get data element and return its contents
819         return SURFBAR_GET_DATA('salt');
820 }
821 // Getter for id from cache
822 function SURFBAR_GET_ID () {
823         // Get data element and return its contents
824         return SURFBAR_GET_DATA('id');
825 }
826 // Getter for userid from cache
827 function SURFBAR_GET_USERID () {
828         // Get data element and return its contents
829         return SURFBAR_GET_DATA('userid');
830 }
831 // Getter for user reload locks
832 function SURFBAR_GET_USER_RELOAD_LOCK () {
833         // Get data element and return its contents
834         return SURFBAR_GET_DATA('user_locks');
835 }
836 // Getter for reload time
837 function SURFBAR_GET_RELOAD_TIME () {
838         // Get data element and return its contents
839         return SURFBAR_GET_DATA('time');
840 }
841 //
842 ?>