f2b006ccda75b3f62ad88b5531924acaabd9249c
[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 (!defined('__SECURITY')) {
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()) {
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_MEMBER()) {
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($GLOBALS['userid'])) {
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         return 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         // Skip notification if userid is zero
261         if ($content['uid'] == 0) {
262                 return false;
263         } // END - if
264
265         // Prepare template name
266         $templateName = sprintf("member_surfbar_%s", $messageType);
267
268         // Prepare subject
269         $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
270                 strtoupper($messageType)
271         );
272         eval($eval);
273
274         // Load template
275         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
276
277         // Send the email
278         return SEND_EMAIL($content['uid'], $subject, $mailText);
279 }
280 // Translate the URL status
281 function SURFBAR_TRANSLATE_STATUS ($status) {
282         // Create constant name
283         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
284
285         // Set default translated status
286         $statusTranslated = "!".$constantName."!";
287
288         // Generate eval() command
289         if (defined($constantName)) {
290                 $eval = "\$statusTranslated = ".$constantName.";";
291                 eval($eval);
292         } // END - if
293
294         // Return result
295         return $statusTranslated;
296 }
297 // Determine reward
298 function SURFBAR_DETERMINE_REWARD () {
299         global $_CONFIG;
300
301         // Do we have static or dynamic?
302         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
303                 // Static model, so choose static values
304                 $reward = $_CONFIG['surfbar_static_reward'];
305         } else {
306                 // Dynamic model, so calculate values
307                 die("DYNAMIC payment model not yet supported!");
308         }
309
310         // Return reward
311         return $reward;
312 }
313 // Determine costs
314 function SURFBAR_DETERMINE_COSTS () {
315         global $_CONFIG;
316
317         // Do we have static or dynamic?
318         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
319                 $costs  = $_CONFIG['surfbar_static_costs'];
320         } else {
321                 // Dynamic model, so calculate values
322                 die("DYNAMIC payment model not yet supported!");
323         }
324
325         // Return costs
326         return $costs;
327 }
328 // Determine right template name
329 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
330         // Default is the frameset
331         $templateName = "surfbar_frameset";
332
333         // Any frame set? ;-)
334         if (isset($_GET['frame'])) {
335                 // Use the frame as a template name part... ;-)
336                 $templateName = sprintf("surfbar_frame_%s",
337                         SQL_ESCAPE($_GET['frame'])
338                 );
339         } // END - if
340
341         // Return result
342         return $templateName;
343 }
344 // Check if the "reload lock" of the current user is full, call this function
345 // before you call SURFBAR_CHECK_RELOAD_LOCK().
346 function SURFBAR_CHECK_RELOAD_FULL() {
347         global $SURFBAR_CACHE, $_CONFIG;
348
349         // Default is full!
350         $isFull = true;
351
352         // Do we have static or dynamic mode?
353         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
354                 // Cache static reload lock
355                 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
356                 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
357
358                 // Ask the database
359                 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
360 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
361 LIMIT 1",
362                         array($GLOBALS['userid']), __FILE__, __LINE__
363                 );
364
365                 // Fetch row
366                 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
367
368                 // Is it null?
369                 if (is_null($SURFBAR_CACHE['user_locks'])) {
370                         // Then fix it to zero!
371                         $SURFBAR_CACHE['user_locks'] = 0;
372                 } // END - if
373
374                 // Free result
375                 SQL_FREERESULT($result);
376
377                 // Get total URLs
378                 $total = SURFBAR_GET_TOTAL_URLS();
379
380                 // Do we have some URLs in lock? Admins can always surf on own URLs!
381                 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
382                 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
383         } else {
384                 // Dynamic model...
385                 die("DYNAMIC not yet implemented!");
386         }
387
388         // Return result
389         return $isFull;
390 }
391 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
392 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
393         // Determine depleted user account
394         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
395
396         // Get amount from database
397         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
398 FROM "._MYSQL_PREFIX."_surfbar_urls
399 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
400                 array($status), __FILE__, __LINE__
401         );
402
403         // Fetch row
404         list($cnt) = SQL_FETCHROW($result);
405
406         // Free result
407         SQL_FREERESULT($result);
408
409         // Return result
410         return $cnt;
411 }
412 // Check wether the user is allowed to book more URLs
413 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
414         global $_CONFIG;
415
416         // Is this admin and userid is zero or does the user has some URLs left to book?
417         return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid) < $_CONFIG['surfbar_max_order']));
418 }
419 // Get total amount of URLs of given status for current user
420 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0) {
421         global $_CONFIG;
422
423         // Is the user 0 and user is logged in?
424         if (($uid == 0) && (IS_MEMBER())) {
425                 // Then use this userid
426                 $uid = $GLOBALS['userid'];
427         } elseif ($uid == 0) {
428                 // Error!
429                 return ($_CONFIG['surfbar_max_order'] + 1);
430         }
431
432         // Get amount from database
433         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
434 FROM "._MYSQL_PREFIX."_surfbar_urls
435 WHERE userid=%s
436 LIMIT %s",
437                 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
438         );
439
440         // Fetch row
441         list($cnt) = SQL_FETCHROW($result);
442
443         // Free result
444         SQL_FREERESULT($result);
445
446         // Return result
447         return $cnt;
448 }
449 // Generate a validation code for the given id number
450 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
451         global $_CONFIG, $SURFBAR_CACHE;
452
453         // @TODO Invalid salt should be refused
454         $SURFBAR_CACHE['salt'] = "INVALID";
455
456         // Get code length from config
457         $length = $_CONFIG['code_length'];
458
459         // Fix length to 10
460         if ($length == 0) $length = 10;
461
462         // Generate a code until the length matches
463         $valCode = "";
464         while (strlen($valCode) != $length) {
465                 // Is the salt set?
466                 if (empty($salt)) {
467                         // Generate random hashed string
468                         $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
469                         //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
470                 } else {
471                         // Use this as salt!
472                         $SURFBAR_CACHE['salt'] = $salt;
473                         //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
474                 }
475
476                 // ... and now the validation code
477                 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
478                 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
479         } // END - while
480
481         // Hash it with md5() and salt it with the random string
482         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
483
484         // Finally encrypt it PGP-like and return it
485         $valHashedCode = generatePassString($hashedCode);
486         //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
487         return $valHashedCode;
488 }
489 // Check validation code
490 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
491         global $SURFBAR_CACHE;
492
493         // Secure id number
494         $id = bigintval($id);
495
496         // Now generate the code again
497         $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
498
499         // Return result of checking hashes and salts
500         //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
501         //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
502         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
503 }
504 // Lockdown the userid/id combination (reload lock)
505 function SURFBAR_LOCKDOWN_ID ($id) {
506         //* //DEBUG: */ print "LOCK!");
507         ///* //DEBUG: */ return;
508         // Just add it to the database
509         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
510                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
511
512         // Remove the salt from database
513         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
514                 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
515 }
516 // Pay points to the user and remove it from the sender
517 function SURFBAR_PAY_POINTS ($id) {
518         // Remove it from the URL owner
519         //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
520         if (SURFBAR_GET_USERID() > 0) {
521                 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
522         } // END - if
523
524         // Book it to the user
525         //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
526         ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
527 }
528 // Updates the statistics of current URL/userid
529 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
530         global $_CONFIG;
531
532         // Update views_total
533         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
534                 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
535
536         // Update the stats entry
537         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
538                 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
539
540         // Was that update okay?
541         if (SQL_AFFECTEDROWS() == 0) {
542                 // No, then insert entry
543                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
544                         array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
545         } // END - if
546
547         // Update total/daily/weekly/monthly counter
548         $_CONFIG['surfbar_total_counter']++;
549         $_CONFIG['surfbar_daily_counter']++;
550         $_CONFIG['surfbar_weekly_counter']++;
551         $_CONFIG['surfbar_monthly_counter']++;
552
553         // Update config as well
554         UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
555 }
556 // Update the salt for validation and statistics
557 function SURFBAR_UPDATE_SALT_STATS () {
558         // Update statistics record
559         SURFBAR_UPDATE_INSERT_STATS_RECORD();
560
561         // Simply store the salt from cache away in database...
562         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
563                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
564
565         // Debug message
566         //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
567
568         // Was that okay?
569         if (SQL_AFFECTEDROWS() == 0) {
570                 // Insert missing entry!
571                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
572                         array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
573         } // END - if
574
575         // Debug message
576         //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
577
578         // Return if the update was okay
579         return (SQL_AFFECTEDROWS() == 1);
580 }
581 // Check if the reload lock is active for given id
582 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
583         //DEBUG_LOG(__FUNCTION__.":id={$id}");
584         // Ask the database
585         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
586 FROM "._MYSQL_PREFIX."_surfbar_locks
587 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
588 ORDER BY last_surfed ASC
589 LIMIT 1",
590                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
591         );
592
593         // Fetch counter
594         list($cnt) = SQL_FETCHROW($result);
595
596         // Free result
597         SQL_FREERESULT($result);
598
599         // Return check
600         //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
601         return ($cnt == 1);
602 }
603 // Determine which user hash no more points left
604 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
605         // Init array
606         $UIDs = array();
607
608         // Do we have a current user id?
609         if (IS_MEMBER()) {
610                 // Then add this as well
611                 $UIDs[] = $GLOBALS['userid'];
612
613                 // Get all userid except logged in one
614                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
615 WHERE userid NOT IN (%s,0) AND status='CONFIRMED'
616 GROUP BY userid
617 ORDER BY userid ASC",
618                         array($GLOBALS['userid']), __FILE__, __LINE__);
619         } else {
620                 // Get all userid
621                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
622 WHERE status='CONFIRMED'
623 GROUP BY userid
624 ORDER BY userid ASC", __FILE__, __LINE__);
625         }
626
627         // Load all userid
628         while (list($uid) = SQL_FETCHROW($result)) {
629                 // Get total points
630                 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
631                 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
632
633                 // Shall we add this to ignore?
634                 if ($points <= 0) {
635                         // Ignore this one!
636                         //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
637                         $UIDs[] = $uid;
638                 } // END - if
639         } // END - while
640
641         // Free result
642         SQL_FREERESULT($result);
643
644         // Debug message
645         //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
646
647         // Return result
648         return $UIDs;
649 }
650 // Determine how many users are Online in surfbar
651 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
652         global $_CONFIG;
653
654         // Count all users in surfbar modue and return the value
655         $result = SQL_QUERY_ESC("SELECT id
656 FROM "._MYSQL_PREFIX."_surfbar_stats
657 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
658 GROUP BY userid",
659                 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
660
661         // Fetch count
662         $cnt = SQL_NUMROWS($result);
663
664         // Free result
665         SQL_FREERESULT($result);
666
667         // Return result
668         return $cnt;
669 }
670 // Determine waiting time for one URL 
671 function SURFBAR_DETERMINE_WAIT_TIME () {
672         global $_CONFIG;
673
674         // Init time
675         $time = 0;
676
677         // Which payment model do we have?
678         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
679                 // Static model
680                 $time = $_CONFIG['surfbar_static_time'];
681         } else {
682                 // Dynamic
683                 die("DYNAMIC payment model not yet finished!");
684         }
685
686         // Return value
687         return $time;
688 }
689 // Changes the status of an URL from given to other
690 function SURFBAR_CHANGE_STATUS ($id, $prevStatus, $newStatus) {
691         // Get URL data for status comparison
692         $data = SURFBAR_GET_URL_DATA($id);
693
694         // Is the status like prevStatus is saying?
695         if ($data[$id]['status'] != $prevStatus) {
696                 // No, then abort here
697                 return false;
698         } // END - if
699
700         // Update the status now
701         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
702                 array($newStatus, bigintval($id)), __FILE__, __LINE__);
703
704         // Was that fine?
705         if (SQL_AFFECTEDROWS() != 1) {
706                 // No, something went wrong
707                 return false;
708         } // END - if
709
710         // Prepare content for notification routines
711         $data[$id]['uid']         = $data[$id]['userid'];
712         $data[$id]['frametester'] = FRAMETESTER($data[$id]['url']);
713         $data[$id]['reward']      = TRANSLATE_COMMA($data[$id]['reward']);
714         $data[$id]['costs']       = TRANSLATE_COMMA($data[$id]['costs']);
715         $data[$id]['status']      = SURFBAR_TRANSLATE_STATUS($newStatus);
716         $data[$id]['registered']  = MAKE_DATETIME($data[$id]['registered'], "2");
717         $newStatus = strtolower($newStatus);
718
719         // Send admin notification
720         SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$id]);
721
722         // Send user notification
723         SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$id]);
724
725         // All done!
726         return true;
727 }
728 // Calculate minimum value for dynamic payment model
729 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
730         global $_CONFIG;
731
732         // Addon is zero by default
733         $addon = 0;
734
735         // Percentage part
736         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
737
738         // Get total users
739         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
740
741         // Get online users
742         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
743
744         // Calculate addon
745         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
746
747         // Get total URLs
748         $totalUrls = SURFBAR_GET_TOTAL_URLS();
749
750         // Get user's total URLs
751         $userUrls = SURFBAR_GET_TOTAL_USER_URLS();
752
753         // Calculate addon
754         $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
755
756         // Return addon
757         return $addon;
758 }
759 // Calculate maximum value for dynamic payment model
760 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
761         global $_CONFIG;
762
763         // Addon is zero by default
764         $addon = 0;
765
766         // Maximum value
767         $max = log(2);
768
769         // Percentage part
770         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
771
772         // Get total users
773         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
774
775         // Calculate addon
776         $addon += abs($max * $percent * $totalUsers);
777
778         // Get total URLs
779         $totalUrls = SURFBAR_GET_TOTAL_URLS();
780
781         // Calculate addon
782         $addon += abs($max * $percent * $totalUrls);
783
784         // Return addon
785         return $addon;
786 }
787 // Calculate dynamic lock
788 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
789         global $_CONFIG;
790
791         // Default lock is 30 seconds
792         $addon = 30;
793
794         // Get online users
795         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
796
797         // Calculate lock
798         $addon = abs(log($onlineUsers / $addon +1));
799
800         // Return value
801         return $addon;
802 }
803 // "Getter" for lock ids array
804 function SURFBAR_GET_LOCK_IDS () {
805         // Prepare some arrays
806         $IDs = array();
807         $USE = array();
808         $ignored = array();
809
810         // Get all id from locks within the timestamp
811         $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
812 FROM
813         "._MYSQL_PREFIX."_surfbar_locks
814 WHERE
815         userid=%s
816 ORDER BY
817         id ASC", array($GLOBALS['userid']),
818                 __FILE__, __LINE__);
819
820         // Load all entries
821         while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
822                 // Debug message
823                 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
824
825                 // Skip entries that are too old
826                 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
827                         // Debug message
828                         //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
829
830                         // Add only if missing or bigger
831                         if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
832                                 // Debug message
833                                 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
834
835                                 // Add this ID
836                                 $IDs[$url] = $last;
837                                 $USE[$url] = $lid;
838                         } // END - if
839                 } else {
840                         // Debug message
841                         //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
842
843                         // Ignore these old entries!
844                         $ignored[] = $url;
845                         unset($IDs[$url]);
846                         unset($USE[$url]);
847                 }
848         } // END - while
849
850         // Free result
851         SQL_FREERESULT($result);
852
853         // Return array
854         return $USE;
855 }
856 // "Getter" for maximum random number
857 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
858         global $_CONFIG;
859         // Count max availabe entries
860         $result = SQL_QUERY("SELECT sbu.id AS cnt
861 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
862 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
863 ON sbu.id=sbs.url_id
864 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
865 ON sbu.id=l.url_id
866 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
867 GROUP BY sbu.id", __FILE__, __LINE__);
868
869         // Log last query
870         //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
871
872         // Fetch max rand
873         $maxRand = SQL_NUMROWS($result);
874
875         // Free result
876         SQL_FREERESULT($result);
877
878         // Return value
879         return $maxRand;
880 }
881 // Determine next id for surfbar or get data for given id, always call this before you call other
882 // getters below this function!!!
883 function SURFBAR_DETERMINE_NEXT_ID ($id = 0) {
884         global $SURFBAR_CACHE, $_CONFIG;
885
886         // Default is no id and no random number
887         $nextId = 0;
888         $randNum = 0;
889
890         // Is the ID set?
891         if ($id == 0) {
892                 // Get array with lock ids
893                 $USE = SURFBAR_GET_LOCK_IDS();
894
895                 // Shall we add some URL ids to ignore?
896                 $ADD = "";
897                 if (count($USE) > 0) {
898                         // Ignore some!
899                         $ADD = " AND sbu.id NOT IN (";
900                         foreach ($USE as $url_id => $lid) {
901                                 // Add URL id
902                                 $ADD .= $url_id.",";
903                         } // END - foreach
904
905                         // Add closing bracket
906                         $ADD = substr($ADD, 0, -1) . ")";
907                 } // END - if
908
909                 // Determine depleted user account
910                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
911
912                 // Get maximum randomness factor
913                 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
914
915                 // If more than one URL can be called generate the random number!
916                 if ($maxRand > 1) {
917                         // Generate random number
918                         $randNum = mt_rand(0, ($maxRand - 1));
919                 } // END - if
920
921                 // And query the database
922                 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
923                 $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
924 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
925 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
926 ON sbu.id=sbs.url_id
927 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
928 ON sbu.id=l.url_id
929 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
930 GROUP BY sbu.id
931 ORDER BY l.last_surfed ASC, sbu.id ASC
932 LIMIT %s,1",
933                         array($randNum), __FILE__, __LINE__
934                 );
935         } else {
936                 // Get data from specified id number
937                 $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
938 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
939 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
940 ON sbu.id=sbs.url_id
941 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
942 ON sbu.id=l.url_id
943 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
944 LIMIT 1",
945                         array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
946                 );
947         }
948
949         // Is there an id number?
950         //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
951         if (SQL_NUMROWS($result) == 1) {
952                 // Load/cache data
953                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
954                 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
955                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
956
957                 // Determine waiting time
958                 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
959
960                 // Is the last salt there?
961                 if (is_null($SURFBAR_CACHE['last_salt'])) {
962                         // Then repair it wit the static!
963                         //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
964                         $SURFBAR_CACHE['last_salt'] = "";
965                 } // END - if
966
967                 // Fix missing last_surfed
968                 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
969                         // Fix it here
970                         //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
971                         $SURFBAR_CACHE['last_surfed'] = 0;
972                 } // END - if
973
974                 // Get base/fixed reward and costs
975                 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
976                 $SURFBAR_CACHE['costs']  = SURFBAR_DETERMINE_COSTS();
977                 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
978
979                 // Only in dynamic model add the dynamic bonus!
980                 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
981                         // Calculate dynamic reward/costs and add it
982                         $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
983                         $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
984                         //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
985                 } // END - if
986
987                 // Now get the id
988                 $nextId = SURFBAR_GET_ID();
989         } // END - if
990
991         // Free result
992         SQL_FREERESULT($result);
993
994         // Return result
995         //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
996         return $nextId;
997 }
998 // -----------------------------------------------------------------------------
999 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1000 // $SURFBAR_CACHE ARRAY!
1001 // -----------------------------------------------------------------------------
1002 // Private getter for data elements
1003 function SURFBAR_GET_DATA ($element) {
1004         global $SURFBAR_CACHE;
1005         //DEBUG_LOG(__FUNCTION__.":element={$element}");
1006
1007         // Default is null
1008         $data = null;
1009
1010         // Is the entry there?
1011         if (isset($SURFBAR_CACHE[$element])) {
1012                 // Then take it
1013                 $data = $SURFBAR_CACHE[$element];
1014         } else { // END - if
1015                 print("<pre>");
1016                 print_r($SURFBAR_CACHE);
1017                 debug_print_backtrace();
1018                 die("</pre>");
1019         }
1020
1021         // Return result
1022         //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1023         return $data;
1024 }
1025 // Getter for reward from cache
1026 function SURFBAR_GET_REWARD () {
1027         // Get data element and return its contents
1028         return SURFBAR_GET_DATA('reward');
1029 }
1030 // Getter for costs from cache
1031 function SURFBAR_GET_COSTS () {
1032         // Get data element and return its contents
1033         return SURFBAR_GET_DATA('costs');
1034 }
1035 // Getter for URL from cache
1036 function SURFBAR_GET_URL () {
1037         // Get data element and return its contents
1038         return SURFBAR_GET_DATA('url');
1039 }
1040 // Getter for salt from cache
1041 function SURFBAR_GET_SALT () {
1042         // Get data element and return its contents
1043         return SURFBAR_GET_DATA('salt');
1044 }
1045 // Getter for id from cache
1046 function SURFBAR_GET_ID () {
1047         // Get data element and return its contents
1048         return SURFBAR_GET_DATA('id');
1049 }
1050 // Getter for userid from cache
1051 function SURFBAR_GET_USERID () {
1052         // Get data element and return its contents
1053         return SURFBAR_GET_DATA('userid');
1054 }
1055 // Getter for user reload locks
1056 function SURFBAR_GET_USER_RELOAD_LOCK () {
1057         // Get data element and return its contents
1058         return SURFBAR_GET_DATA('user_locks');
1059 }
1060 // Getter for reload time
1061 function SURFBAR_GET_RELOAD_TIME () {
1062         // Get data element and return its contents
1063         return SURFBAR_GET_DATA('time');
1064 }
1065 //
1066 ?>