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