2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/31/2008 *
4 * =============== Last change: 08/31/2008 *
6 * -------------------------------------------------------------------- *
7 * File : surfbar_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for surfbar *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer die Surfbar *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
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. *
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. *
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, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
40 // -----------------------------------------------------------------------------
42 // -----------------------------------------------------------------------------
44 // Admin has added an URL with given user id and so on
45 function SURFBAR_ADMIN_ADD_URL ($url) {
50 } elseif (!VALIDATE_URL($url)) {
53 } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
54 // URL already found in surfbar!
56 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
61 // Do we have fixed or dynamic payment model?
62 $reward = SURFBAR_DETERMINE_REWARD();
63 $costs = SURFBAR_DETERMINE_COSTS();
65 // Register the new URL
66 return SURFBAR_REGISTER_URL($url, "0", $reward, $costs, "0", "CONFIRMED", "unlock");
68 // Admin function for unlocking URLs
69 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
70 // Is this an admin or invalid array?
72 // Not admin or invalid IDs array
74 } elseif (!is_array($IDs)) {
77 } elseif (count($IDs) == 0) {
82 // Set to true to make AND expression valid if first URL got unlocked
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")));
91 // Return total status
95 // -----------------------------------------------------------------------------
97 // -----------------------------------------------------------------------------
99 // Member has added an URL
100 function SURFBAR_MEMBER_ADD_URL ($url) {
103 // Do some pre-checks
107 } elseif (!VALIDATE_URL($url)) {
110 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
111 // URL already found in surfbar!
113 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
118 // Do we have fixed or dynamic payment model?
119 $reward = SURFBAR_DETERMINE_REWARD();
120 $costs = SURFBAR_DETERMINE_COSTS();
122 // Register the new URL
123 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], $reward, $costs);
125 // Create list of actions depending on status for the user
126 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
127 // Load all actions in an array for given status
128 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
131 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
135 $width = round(100 / count($actionArray));
137 // "Walk" through all actions and create forms
138 foreach ($actionArray as $actionId=>$action) {
139 // Add form for this action
140 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
141 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
142 <input type=\"hidden\" name=\"id\" value=\"%s\" />
143 <input type=\"hidden\" name=\"action\" value=\"%s\" />
144 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
162 // Do the member form request
163 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
170 /* DEBUG: */ die("<pre>".print_r($formData, true)."</pre><pre>".print_r($URLs, true)."</pre>");
173 // -----------------------------------------------------------------------------
175 // -----------------------------------------------------------------------------
177 // Looks up by an URL
178 function SURFBAR_LOOKUP_BY_URL ($url) {
179 // Now lookup that given URL by itself
180 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
183 return (count($urlArray) > 0);
185 // Load URL data by given search term and column
186 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
189 // By default nothing is found
190 $lastUrlData = array();
192 // Is the column an id number?
193 if (($column == "id") || ($column == "userid")) {
194 // Extra secure input
195 $searchTerm = bigintval($searchTerm);
198 // If the column is "id" there can be only one entry
200 if ($column == "id") {
204 // Look up the record
205 $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
206 FROM "._MYSQL_PREFIX."_surfbar_urls
210 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
212 // Is there at least one record?
213 if (SQL_NUMROWS($result) > 0) {
215 while ($dataRow = SQL_FETCHARRAY($result)) {
216 // Shall we group these results?
217 if ($group == "id") {
218 // Add the row by id as index
219 $lastUrlData[$dataRow['id']] = $dataRow;
222 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
228 SQL_FREERESULT($result);
233 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
234 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $costs, $paymentId=0, $status="PENDING", $addMode="reg") {
237 // Make sure by the user registered URLs are always pending
238 if ($addMode == "reg") $status = "PENDING";
243 'frametester' => FRAMETESTER($url),
250 // Insert the URL into database
251 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
253 // Translate status, reward and costs
254 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
255 $content['reward'] = TRANSLATE_COMMA($content['reward']);
256 $content['costs'] = TRANSLATE_COMMA($content['costs']);
258 // If in reg-mode we notify admin
259 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
260 // Notify admin even when he as unlocked an email
261 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
265 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
267 // Return the insert id
268 return $content['insert_id'];
270 // Inserts an url by given data array and return the insert id
271 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
273 $uid = bigintval($urlData['uid']);
276 if (empty($uid)) $uid = 0;
278 // Just run the insert query for now
279 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, status) VALUES('%s', '%s', %s, %s, '%s')",
283 (float)$urlData['reward'],
284 (float)$urlData['costs'],
286 ), __FILE__, __LINE__
290 return SQL_INSERTID();
292 // Notify admin(s) with a selected message and content
293 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
294 // Prepare template name
295 $templateName = sprintf("admin_surfbar_%s", $messageType);
298 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
299 strtoupper($messageType)
303 // Send the notification out
304 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
306 // Notify the user about the performed action
307 function SURFBAR_NOTIFY_USER ($messageType, $content) {
308 // Skip notification if userid is zero
309 if ($content['uid'] == 0) {
313 // Prepare template name
314 $templateName = sprintf("member_surfbar_%s", $messageType);
317 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
318 strtoupper($messageType)
323 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
326 return SEND_EMAIL($content['uid'], $subject, $mailText);
328 // Translate the URL status
329 function SURFBAR_TRANSLATE_STATUS ($status) {
330 // Create constant name
331 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
333 // Set default translated status
334 $statusTranslated = "!".$constantName."!";
336 // Generate eval() command
337 if (defined($constantName)) {
338 $eval = "\$statusTranslated = ".$constantName.";";
343 return $statusTranslated;
346 function SURFBAR_DETERMINE_REWARD () {
349 // Static values are default
350 $reward = $_CONFIG['surfbar_static_reward'];
352 // Do we have static or dynamic?
353 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
354 // "Calculate" dynamic reward
355 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
361 // "Calculate" dynamic add
362 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
363 // Get min/max values
364 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
365 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
367 // "Calculate" dynamic part and return it
368 return mt_rand($min, $max);
371 function SURFBAR_DETERMINE_COSTS () {
374 // Static costs is default
375 $costs = $_CONFIG['surfbar_static_costs'];
377 // Do we have static or dynamic?
378 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
379 // "Calculate" dynamic costs
380 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
386 // Determine right template name
387 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
388 // Default is the frameset
389 $templateName = "surfbar_frameset";
391 // Any frame set? ;-)
392 if (isset($_GET['frame'])) {
393 // Use the frame as a template name part... ;-)
394 $templateName = sprintf("surfbar_frame_%s",
395 SQL_ESCAPE($_GET['frame'])
400 return $templateName;
402 // Check if the "reload lock" of the current user is full, call this function
403 // before you call SURFBAR_CHECK_RELOAD_LOCK().
404 function SURFBAR_CHECK_RELOAD_FULL() {
405 global $SURFBAR_CACHE, $_CONFIG;
410 // Cache static reload lock
411 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
412 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
414 // Do we have dynamic model?
415 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
416 // "Calculate" dynamic lock
417 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
421 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
422 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
424 array($GLOBALS['userid']), __FILE__, __LINE__
428 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
431 if (is_null($SURFBAR_CACHE['user_locks'])) {
432 // Then fix it to zero!
433 $SURFBAR_CACHE['user_locks'] = 0;
437 SQL_FREERESULT($result);
440 $total = SURFBAR_GET_TOTAL_URLS();
442 // Do we have some URLs in lock? Admins can always surf on own URLs!
443 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
444 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
449 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
450 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED", $excludeUserId="") {
451 // Determine depleted user account
452 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
454 // Is the exlude userid set?
455 if ($excludeUserId !== "") {
457 $UIDs[] = $excludeUserId;
460 // Get amount from database
461 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
462 FROM "._MYSQL_PREFIX."_surfbar_urls
463 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
464 array($status), __FILE__, __LINE__
468 list($cnt) = SQL_FETCHROW($result);
471 SQL_FREERESULT($result);
476 // Check wether the user is allowed to book more URLs
477 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
480 // Is this admin and userid is zero or does the user has some URLs left to book?
481 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
483 // Get total amount of URLs of given status for current user
484 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
487 // Is the user 0 and user is logged in?
488 if (($uid == 0) && (IS_MEMBER())) {
489 // Then use this userid
490 $uid = $GLOBALS['userid'];
491 } elseif ($uid == 0) {
493 return ($_CONFIG['surfbar_max_order'] + 1);
496 // Default is all URLs
499 // Is the status set?
500 if (is_array($status)) {
501 // Only URLs with these status
502 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
503 } elseif (!empty($status)) {
504 // Only URLs with this status
505 $ADD = sprintf(" AND status='%s'", $status);
506 } elseif (is_array($exclude)) {
507 // Exclude URLs with these status
508 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
509 } elseif (!empty($exclude)) {
510 // Exclude URLs with this status
511 $ADD = sprintf(" AND status != '%s'", $exclude);
514 // Get amount from database
515 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
516 FROM "._MYSQL_PREFIX."_surfbar_urls
517 WHERE userid=%s".$ADD."
519 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
523 list($cnt) = SQL_FETCHROW($result);
526 SQL_FREERESULT($result);
531 // Generate a validation code for the given id number
532 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
533 global $_CONFIG, $SURFBAR_CACHE;
535 // @TODO Invalid salt should be refused
536 $SURFBAR_CACHE['salt'] = "INVALID";
538 // Get code length from config
539 $length = $_CONFIG['code_length'];
542 if ($length == 0) $length = 10;
544 // Generate a code until the length matches
546 while (strlen($valCode) != $length) {
549 // Generate random hashed string
550 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
551 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
554 $SURFBAR_CACHE['salt'] = $salt;
555 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
558 // ... and now the validation code
559 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
560 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
563 // Hash it with md5() and salt it with the random string
564 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
566 // Finally encrypt it PGP-like and return it
567 $valHashedCode = generatePassString($hashedCode);
568 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
569 return $valHashedCode;
571 // Check validation code
572 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
573 global $SURFBAR_CACHE;
576 $urlId = bigintval($urlId);
578 // Now generate the code again
579 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
581 // Return result of checking hashes and salts
582 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
583 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
584 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
586 // Lockdown the userid/id combination (reload lock)
587 function SURFBAR_LOCKDOWN_ID ($urlId) {
588 //* //DEBUG: */ print "LOCK!");
589 ///* //DEBUG: */ return;
590 // Just add it to the database
591 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
592 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
594 // Remove the salt from database
595 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
596 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
598 // Pay points to the user and remove it from the sender
599 function SURFBAR_PAY_POINTS ($urlId) {
600 // Remove it from the URL owner
601 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
602 if (SURFBAR_GET_USERID() > 0) {
603 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
606 // Book it to the user
607 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
608 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
610 // Updates the statistics of current URL/userid
611 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
614 // Update views_total
615 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
616 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
618 // Update the stats entry
619 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
620 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
622 // Was that update okay?
623 if (SQL_AFFECTEDROWS() == 0) {
624 // No, then insert entry
625 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
626 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
629 // Update total/daily/weekly/monthly counter
630 $_CONFIG['surfbar_total_counter']++;
631 $_CONFIG['surfbar_daily_counter']++;
632 $_CONFIG['surfbar_weekly_counter']++;
633 $_CONFIG['surfbar_monthly_counter']++;
635 // Update config as well
636 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
638 // Update the salt for validation and statistics
639 function SURFBAR_UPDATE_SALT_STATS () {
640 // Update statistics record
641 SURFBAR_UPDATE_INSERT_STATS_RECORD();
643 // Simply store the salt from cache away in database...
644 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
645 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
648 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
651 if (SQL_AFFECTEDROWS() == 0) {
652 // Insert missing entry!
653 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
654 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
658 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
660 // Return if the update was okay
661 return (SQL_AFFECTEDROWS() == 1);
663 // Check if the reload lock is active for given id
664 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
665 //DEBUG_LOG(__FUNCTION__.":id={$urlId}");
667 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
668 FROM "._MYSQL_PREFIX."_surfbar_locks
669 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
670 ORDER BY last_surfed ASC
672 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
676 list($cnt) = SQL_FETCHROW($result);
679 SQL_FREERESULT($result);
682 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
685 // Determine which user hash no more points left
686 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
690 // Do we have a current user id?
692 // Then add this as well
693 $UIDs[] = $GLOBALS['userid'];
695 // Get all userid except logged in one
696 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
697 WHERE userid NOT IN (%s,0) AND status='CONFIRMED'
699 ORDER BY userid ASC",
700 array($GLOBALS['userid']), __FILE__, __LINE__);
703 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
704 WHERE status='CONFIRMED'
706 ORDER BY userid ASC", __FILE__, __LINE__);
710 while (list($uid) = SQL_FETCHROW($result)) {
712 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
713 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
715 // Shall we add this to ignore?
718 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
724 SQL_FREERESULT($result);
727 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
732 // Determine how many users are Online in surfbar
733 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
736 // Count all users in surfbar modue and return the value
737 $result = SQL_QUERY_ESC("SELECT id
738 FROM "._MYSQL_PREFIX."_surfbar_stats
739 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
741 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
744 $cnt = SQL_NUMROWS($result);
747 SQL_FREERESULT($result);
752 // Determine waiting time for one URL
753 function SURFBAR_DETERMINE_WAIT_TIME () {
756 // Static time is default
757 $time = $_CONFIG['surfbar_static_time'];
759 // Which payment model do we have?
760 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
761 // "Calculate" dynamic time
762 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
768 // Changes the status of an URL from given to other
769 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus) {
770 // Get URL data for status comparison
771 $data = SURFBAR_GET_URL_DATA($urlId);
773 // Is the status like prevStatus is saying?
774 if ($data[$urlId]['status'] != $prevStatus) {
775 // No, then abort here
779 // Update the status now
780 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
781 array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
784 if (SQL_AFFECTEDROWS() != 1) {
785 // No, something went wrong
789 // Prepare content for notification routines
790 $data[$urlId]['uid'] = $data[$urlId]['userid'];
791 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
792 $data[$urlId]['reward'] = TRANSLATE_COMMA($data[$urlId]['reward']);
793 $data[$urlId]['costs'] = TRANSLATE_COMMA($data[$urlId]['costs']);
794 $data[$urlId]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
795 $data[$urlId]['registered'] = MAKE_DATETIME($data[$urlId]['registered'], "2");
796 $newStatus = strtolower($newStatus);
798 // Send admin notification
799 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
801 // Send user notification
802 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
807 // Calculate minimum value for dynamic payment model
808 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
811 // Addon is zero by default
815 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
818 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
821 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
824 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
827 $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
829 // Get user's total URLs
830 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "CONFIRMED");
833 if ($totalUrls > 0) {
834 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
836 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
842 // Calculate maximum value for dynamic payment model
843 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
846 // Addon is zero by default
853 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
856 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
859 $addon += abs($max * $percent * $totalUsers);
862 $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
865 $addon += abs($max * $percent * $totalUrls);
870 // Calculate dynamic lock
871 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
874 // Default lock is 30 seconds
878 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
881 $addon = abs(log($onlineUsers / $addon + 1));
886 // "Getter" for lock ids array
887 function SURFBAR_GET_LOCK_IDS () {
888 // Prepare some arrays
893 // Get all id from locks within the timestamp
894 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
896 "._MYSQL_PREFIX."_surfbar_locks
900 id ASC", array($GLOBALS['userid']),
904 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
906 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
908 // Skip entries that are too old
909 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
911 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
913 // Add only if missing or bigger
914 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
916 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
924 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
926 // Ignore these old entries!
934 SQL_FREERESULT($result);
939 // "Getter" for maximum random number
940 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
942 // Count max availabe entries
943 $result = SQL_QUERY("SELECT sbu.id AS cnt
944 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
945 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
947 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
949 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
950 GROUP BY sbu.id", __FILE__, __LINE__);
953 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
956 $maxRand = SQL_NUMROWS($result);
959 SQL_FREERESULT($result);
964 // Load all URLs of the current user and return it as an array
965 function SURFBAR_GET_USER_URLS () {
970 $result = SQL_QUERY_ESC("SELECT u.id, u.url, u.views_total, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
971 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
972 WHERE u.userid=%s AND u.status != 'DELETED'
974 array($GLOBALS['userid']), __FILE__, __LINE__);
976 // Are there entries?
977 if (SQL_NUMROWS($result) > 0) {
979 while ($row = SQL_FETCHARRAY($result)) {
981 $URLs[$row['id']] = $row;
986 SQL_FREERESULT($result);
991 // "Getter" for member action array for given status
992 function SURFBAR_GET_ACTION_ARRAY ($status) {
994 $returnArray = array();
996 // Get all assigned actions
997 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
998 array($status), __FILE__, __LINE__);
1000 // Some entries there?
1001 if (SQL_NUMROWS($result) > 0) {
1003 while (list($action) = SQL_FETCHROW($result)) {
1004 $returnArray[] = $action;
1009 SQL_FREERESULT($result);
1012 return $returnArray;
1014 // Determine next id for surfbar or get data for given id, always call this before you call other
1015 // getters below this function!!!
1016 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1017 global $SURFBAR_CACHE, $_CONFIG;
1019 // Default is no id and no random number
1025 // Get array with lock ids
1026 $USE = SURFBAR_GET_LOCK_IDS();
1028 // Shall we add some URL ids to ignore?
1030 if (count($USE) > 0) {
1032 $ADD = " AND sbu.id NOT IN (";
1033 foreach ($USE as $url_id => $lid) {
1035 $ADD .= $url_id.",";
1038 // Add closing bracket
1039 $ADD = substr($ADD, 0, -1) . ")";
1042 // Determine depleted user account
1043 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1045 // Get maximum randomness factor
1046 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
1048 // If more than one URL can be called generate the random number!
1050 // Generate random number
1051 $randNum = mt_rand(0, ($maxRand - 1));
1054 // And query the database
1055 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
1056 $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
1057 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1058 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1059 ON sbu.id=sbs.url_id
1060 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1062 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
1064 ORDER BY l.last_surfed ASC, sbu.id ASC
1066 array($randNum), __FILE__, __LINE__
1069 // Get data from specified id number
1070 $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
1071 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1072 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1073 ON sbu.id=sbs.url_id
1074 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1076 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
1078 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1082 // Is there an id number?
1083 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1084 if (SQL_NUMROWS($result) == 1) {
1086 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1087 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1088 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1090 // Determine waiting time
1091 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1093 // Is the last salt there?
1094 if (is_null($SURFBAR_CACHE['last_salt'])) {
1095 // Then repair it wit the static!
1096 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1097 $SURFBAR_CACHE['last_salt'] = "";
1100 // Fix missing last_surfed
1101 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1103 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1104 $SURFBAR_CACHE['last_surfed'] = 0;
1107 // Get base/fixed reward and costs
1108 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1109 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1110 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1112 // Only in dynamic model add the dynamic bonus!
1113 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1114 // Calculate dynamic reward/costs and add it
1115 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1116 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1117 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1121 $nextId = SURFBAR_GET_ID();
1125 SQL_FREERESULT($result);
1128 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1131 // -----------------------------------------------------------------------------
1132 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1133 // $SURFBAR_CACHE ARRAY!
1134 // -----------------------------------------------------------------------------
1135 // Private getter for data elements
1136 function SURFBAR_GET_DATA ($element) {
1137 global $SURFBAR_CACHE;
1138 //DEBUG_LOG(__FUNCTION__.":element={$element}");
1143 // Is the entry there?
1144 if (isset($SURFBAR_CACHE[$element])) {
1146 $data = $SURFBAR_CACHE[$element];
1147 } else { // END - if
1149 print_r($SURFBAR_CACHE);
1150 debug_print_backtrace();
1155 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1158 // Getter for reward from cache
1159 function SURFBAR_GET_REWARD () {
1160 // Get data element and return its contents
1161 return SURFBAR_GET_DATA('reward');
1163 // Getter for costs from cache
1164 function SURFBAR_GET_COSTS () {
1165 // Get data element and return its contents
1166 return SURFBAR_GET_DATA('costs');
1168 // Getter for URL from cache
1169 function SURFBAR_GET_URL () {
1170 // Get data element and return its contents
1171 return SURFBAR_GET_DATA('url');
1173 // Getter for salt from cache
1174 function SURFBAR_GET_SALT () {
1175 // Get data element and return its contents
1176 return SURFBAR_GET_DATA('salt');
1178 // Getter for id from cache
1179 function SURFBAR_GET_ID () {
1180 // Get data element and return its contents
1181 return SURFBAR_GET_DATA('id');
1183 // Getter for userid from cache
1184 function SURFBAR_GET_USERID () {
1185 // Get data element and return its contents
1186 return SURFBAR_GET_DATA('userid');
1188 // Getter for user reload locks
1189 function SURFBAR_GET_USER_RELOAD_LOCK () {
1190 // Get data element and return its contents
1191 return SURFBAR_GET_DATA('user_locks');
1193 // Getter for reload time
1194 function SURFBAR_GET_RELOAD_TIME () {
1195 // Get data element and return its contents
1196 return SURFBAR_GET_DATA('time');