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