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