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 // Register the new URL
62 return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock");
64 // Admin unlocked an email so we can migrate the URL
65 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
70 } elseif (!VALIDATE_URL($url)) {
73 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
74 // URL already found in surfbar!
76 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
81 // Register the new URL
82 return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
84 // Admin function for unlocking URLs
85 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
86 // Is this an admin or invalid array?
88 // Not admin or invalid IDs array
90 } elseif (!is_array($IDs)) {
93 } elseif (count($IDs) == 0) {
98 // Set to true to make AND expression valid if first URL got unlocked
101 // Update the status for all ids
102 foreach ($IDs as $id => $dummy) {
103 // Test all ids through (ignores failed)
104 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
107 // Return total status
110 // Admin function for rejecting URLs
111 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
112 // Is this an admin or invalid array?
114 // Not admin or invalid IDs array
116 } elseif (!is_array($IDs)) {
119 } elseif (count($IDs) == 0) {
124 // Set to true to make AND expression valid if first URL got unlocked
127 // Update the status for all ids
128 foreach ($IDs as $id => $dummy) {
129 // Test all ids through (ignores failed)
130 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
133 // Return total status
137 // -----------------------------------------------------------------------------
139 // -----------------------------------------------------------------------------
141 // Member has added an URL
142 function SURFBAR_MEMBER_ADD_URL ($url) {
145 // Do some pre-checks
149 } elseif (!VALIDATE_URL($url)) {
152 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
153 // URL already found in surfbar!
155 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
160 // Register the new URL
161 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid']);
163 // Create list of actions depending on status for the user
164 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
165 // Load all actions in an array for given status
166 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
169 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
173 $width = round(100 / count($actionArray));
175 // "Walk" through all actions and create forms
176 foreach ($actionArray as $actionId=>$action) {
177 // Add form for this action
178 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
179 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
180 <input type=\"hidden\" name=\"id\" value=\"%s\" />
181 <input type=\"hidden\" name=\"action\" value=\"%s\" />
182 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
200 // Do the member form request
201 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
202 global $SURFBAR_CACHE;
204 // By default no action is performed
211 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
212 // Important form elements are missing!
214 } elseif (!isset($URLs[$formData['id']])) {
215 // ID not found in cache
217 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
218 // Action not allowed for current URL status
222 // Create the function name for selected action
223 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper(SQL_ESCAPE($formData['action'])));
225 // Is the function there?
226 if (function_exists($functionName)) {
228 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
230 // Extract URL data for call-back
231 $urlData = array($URLs[$formData['id']]);
233 // Action found so execute it
234 $performed = call_user_func_array($functionName, $urlData);
236 // Log invalid request
237 DEBUG_LOG(__FUNCTION__.": action={$formData['action']},id={$formData['id']},function={$functionName}");
243 // Validate if the requested action can be performed on current URL status
244 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
245 global $SURFBAR_CACHE;
247 // Search for the requested action/status combination in database
248 $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
249 array($action, $status), __FILE__, __LINE__);
251 // Is the entry there?
252 $isValid = (SQL_NUMROWS($result) == 1);
254 // Fetch the new status if found
256 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
260 SQL_FREERESULT($result);
266 // -----------------------------------------------------------------------------
268 // -----------------------------------------------------------------------------
271 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
272 // Create the data array for next function call
274 $urlData['id'] => $urlData
277 // Simply change the status here
278 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
280 // Book an URL now (from migration)
281 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
282 // Create the data array for next function call
284 $urlData['id'] => $urlData
287 // Simply change the status here
288 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
291 // -----------------------------------------------------------------------------
293 // -----------------------------------------------------------------------------
295 // Looks up by an URL
296 function SURFBAR_LOOKUP_BY_URL ($url) {
297 // Now lookup that given URL by itself
298 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
301 return (count($urlArray) > 0);
303 // Load URL data by given search term and column
304 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
307 // By default nothing is found
308 $lastUrlData = array();
310 // Is the column an id number?
311 if (($column == "id") || ($column == "userid")) {
312 // Extra secure input
313 $searchTerm = bigintval($searchTerm);
316 // If the column is "id" there can be only one entry
318 if ($column == "id") {
322 // Look up the record
323 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, status, registered, last_locked, lock_reason
324 FROM "._MYSQL_PREFIX."_surfbar_urls
328 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
330 // Is there at least one record?
331 if (SQL_NUMROWS($result) > 0) {
333 while ($dataRow = SQL_FETCHARRAY($result)) {
334 // Shall we group these results?
335 if ($group == "id") {
336 // Add the row by id as index
337 $lastUrlData[$dataRow['id']] = $dataRow;
340 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
346 SQL_FREERESULT($result);
351 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
352 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg") {
355 // Make sure by the user registered URLs are always pending
356 if ($addMode == "reg") $status = "PENDING";
361 'frametester' => FRAMETESTER($url),
366 // Insert the URL into database
367 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
369 // Translate status, reward and costs
370 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
372 // If in reg-mode we notify admin
373 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
374 // Notify admin even when he as unlocked an email
375 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
379 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
381 // Return the insert id
382 return $content['insert_id'];
384 // Inserts an url by given data array and return the insert id
385 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
387 $uid = bigintval($urlData['uid']);
390 if (empty($uid)) $uid = 0;
392 // Just run the insert query for now
393 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, status) VALUES(%s, '%s', '%s')",
398 ), __FILE__, __LINE__
402 return SQL_INSERTID();
404 // Notify admin(s) with a selected message and content
405 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
406 // Prepare template name
407 $templateName = sprintf("admin_surfbar_%s", $messageType);
409 // Set default subject if following eval() wents wrong
410 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
413 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
414 strtoupper($messageType)
418 // Send the notification out
419 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
421 // Notify the user about the performed action
422 function SURFBAR_NOTIFY_USER ($messageType, $content) {
423 // Skip notification if userid is zero
424 if ($content['uid'] == 0) {
428 // Prepare template name
429 $templateName = sprintf("member_surfbar_%s", $messageType);
431 // Set default subject if following eval() wents wrong
432 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
435 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
436 strtoupper($messageType)
441 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
444 return SEND_EMAIL($content['uid'], $subject, $mailText);
446 // Translate the URL status
447 function SURFBAR_TRANSLATE_STATUS ($status) {
448 // Create constant name
449 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
451 // Set default translated status
452 $statusTranslated = "!".$constantName."!";
454 // Generate eval() command
455 if (defined($constantName)) {
456 $eval = "\$statusTranslated = ".$constantName.";";
461 return $statusTranslated;
464 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
467 // Static values are default
468 $reward = $_CONFIG['surfbar_static_reward'];
470 // Do we have static or dynamic?
471 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
472 // "Calculate" dynamic reward
474 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
476 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
484 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
487 // Static costs is default
488 $costs = $_CONFIG['surfbar_static_costs'];
490 // Do we have static or dynamic?
491 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
492 // "Calculate" dynamic costs
494 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
496 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
503 // "Calculate" dynamic add
504 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
505 // Get min/max values
506 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
507 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
509 // "Calculate" dynamic part and return it
510 return mt_rand($min, $max);
512 // Determine right template name
513 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
514 // Default is the frameset
515 $templateName = "surfbar_frameset";
517 // Any frame set? ;-)
518 if (isset($_GET['frame'])) {
519 // Use the frame as a template name part... ;-)
520 $templateName = sprintf("surfbar_frame_%s",
521 SQL_ESCAPE($_GET['frame'])
526 return $templateName;
528 // Check if the "reload lock" of the current user is full, call this function
529 // before you call SURFBAR_CHECK_RELOAD_LOCK().
530 function SURFBAR_CHECK_RELOAD_FULL() {
531 global $SURFBAR_CACHE, $_CONFIG;
536 // Cache static reload lock
537 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
538 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
540 // Do we have dynamic model?
541 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
542 // "Calculate" dynamic lock
543 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
547 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
548 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
550 array($GLOBALS['userid']), __FILE__, __LINE__
554 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
557 if (is_null($SURFBAR_CACHE['user_locks'])) {
558 // Then fix it to zero!
559 $SURFBAR_CACHE['user_locks'] = 0;
563 SQL_FREERESULT($result);
566 $total = SURFBAR_GET_TOTAL_URLS();
568 // Do we have some URLs in lock? Admins can always surf on own URLs!
569 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
570 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
575 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
576 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId="") {
577 // Determine depleted user account
578 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
580 // Is the exlude userid set?
581 if ($excludeUserId !== "") {
583 $UIDs[] = $excludeUserId;
586 // Get amount from database
587 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
588 FROM "._MYSQL_PREFIX."_surfbar_urls
589 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
590 array($status), __FILE__, __LINE__
594 list($cnt) = SQL_FETCHROW($result);
597 SQL_FREERESULT($result);
602 // Check wether the user is allowed to book more URLs
603 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
606 // Is this admin and userid is zero or does the user has some URLs left to book?
607 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
609 // Get total amount of URLs of given status for current user
610 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
613 // Is the user 0 and user is logged in?
614 if (($uid == 0) && (IS_MEMBER())) {
615 // Then use this userid
616 $uid = $GLOBALS['userid'];
617 } elseif ($uid == 0) {
619 return ($_CONFIG['surfbar_max_order'] + 1);
622 // Default is all URLs
625 // Is the status set?
626 if (is_array($status)) {
627 // Only URLs with these status
628 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
629 } elseif (!empty($status)) {
630 // Only URLs with this status
631 $ADD = sprintf(" AND status='%s'", $status);
632 } elseif (is_array($exclude)) {
633 // Exclude URLs with these status
634 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
635 } elseif (!empty($exclude)) {
636 // Exclude URLs with this status
637 $ADD = sprintf(" AND status != '%s'", $exclude);
640 // Get amount from database
641 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
642 FROM "._MYSQL_PREFIX."_surfbar_urls
643 WHERE userid=%s".$ADD."
645 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
649 list($cnt) = SQL_FETCHROW($result);
652 SQL_FREERESULT($result);
657 // Generate a validation code for the given id number
658 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
659 global $_CONFIG, $SURFBAR_CACHE;
661 // @TODO Invalid salt should be refused
662 $SURFBAR_CACHE['salt'] = "INVALID";
664 // Get code length from config
665 $length = $_CONFIG['code_length'];
668 if ($length == 0) $length = 10;
670 // Generate a code until the length matches
672 while (strlen($valCode) != $length) {
675 // Generate random hashed string
676 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
677 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
680 $SURFBAR_CACHE['salt'] = $salt;
681 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
684 // ... and now the validation code
685 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
686 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
689 // Hash it with md5() and salt it with the random string
690 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
692 // Finally encrypt it PGP-like and return it
693 $valHashedCode = generatePassString($hashedCode);
694 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
695 return $valHashedCode;
697 // Check validation code
698 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
699 global $SURFBAR_CACHE;
702 $urlId = bigintval($urlId);
704 // Now generate the code again
705 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
707 // Return result of checking hashes and salts
708 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
709 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
710 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
712 // Lockdown the userid/id combination (reload lock)
713 function SURFBAR_LOCKDOWN_ID ($urlId) {
714 //* //DEBUG: */ print "LOCK!");
715 ///* //DEBUG: */ return;
716 // Just add it to the database
717 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
718 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
720 // Remove the salt from database
721 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
722 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
724 // Pay points to the user and remove it from the sender
725 function SURFBAR_PAY_POINTS ($urlId) {
726 // Remove it from the URL owner
727 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
728 if (SURFBAR_GET_USERID() > 0) {
729 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
732 // Book it to the user
733 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
734 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
736 // Updates the statistics of current URL/userid
737 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
740 // Update views_total
741 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
742 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
744 // Update the stats entry
745 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
746 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
748 // Was that update okay?
749 if (SQL_AFFECTEDROWS() == 0) {
750 // No, then insert entry
751 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
752 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
755 // Update total/daily/weekly/monthly counter
756 $_CONFIG['surfbar_total_counter']++;
757 $_CONFIG['surfbar_daily_counter']++;
758 $_CONFIG['surfbar_weekly_counter']++;
759 $_CONFIG['surfbar_monthly_counter']++;
761 // Update config as well
762 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
764 // Update the salt for validation and statistics
765 function SURFBAR_UPDATE_SALT_STATS () {
766 // Update statistics record
767 SURFBAR_UPDATE_INSERT_STATS_RECORD();
769 // Simply store the salt from cache away in database...
770 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
771 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
774 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
777 if (SQL_AFFECTEDROWS() == 0) {
778 // Insert missing entry!
779 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
780 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
784 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
786 // Return if the update was okay
787 return (SQL_AFFECTEDROWS() == 1);
789 // Check if the reload lock is active for given id
790 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
791 //DEBUG_LOG(__FUNCTION__.":id={$urlId}");
793 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
794 FROM "._MYSQL_PREFIX."_surfbar_locks
795 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
796 ORDER BY last_surfed ASC
798 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
802 list($cnt) = SQL_FETCHROW($result);
805 SQL_FREERESULT($result);
808 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
811 // Determine which user hash no more points left
812 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
816 // Do we have a current user id?
818 // Then add this as well
819 $UIDs[] = $GLOBALS['userid'];
821 // Get all userid except logged in one
822 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
823 WHERE userid NOT IN (%s,0) AND status='ACTIVE'
825 ORDER BY userid ASC",
826 array($GLOBALS['userid']), __FILE__, __LINE__);
829 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
830 WHERE status='ACTIVE'
832 ORDER BY userid ASC", __FILE__, __LINE__);
836 while (list($uid) = SQL_FETCHROW($result)) {
838 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
839 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
841 // Shall we add this to ignore?
844 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
850 SQL_FREERESULT($result);
853 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
858 // Determine how many users are Online in surfbar
859 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
862 // Count all users in surfbar modue and return the value
863 $result = SQL_QUERY_ESC("SELECT id
864 FROM "._MYSQL_PREFIX."_surfbar_stats
865 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
867 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
870 $cnt = SQL_NUMROWS($result);
873 SQL_FREERESULT($result);
878 // Determine waiting time for one URL
879 function SURFBAR_DETERMINE_WAIT_TIME () {
882 // Static time is default
883 $time = $_CONFIG['surfbar_static_time'];
885 // Which payment model do we have?
886 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
887 // "Calculate" dynamic time
888 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
894 // Changes the status of an URL from given to other
895 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
898 // Get URL data for status comparison if missing
899 if (count($data) == 0) {
900 $data = SURFBAR_GET_URL_DATA($urlId);
903 // Is the status like prevStatus is saying?
904 if ($data[$urlId]['status'] != $prevStatus) {
905 // No, then abort here
910 // Update the status now
911 // ---------------------- Commented out for debugging member actions! -----------------------
912 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
913 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
914 // ---------------------- Commented out for debugging member actions! -----------------------
917 if (SQL_AFFECTEDROWS() != 1) {
918 // No, something went wrong
922 // Prepare content for notification routines
923 $data[$urlId]['uid'] = $data[$urlId]['userid'];
924 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
925 $data[$urlId]['reward'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
926 $data[$urlId]['costs'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
927 $data[$urlId]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
928 $data[$urlId]['registered'] = MAKE_DATETIME($data[$urlId]['registered'], "2");
929 $newStatus = strtolower($newStatus);
931 // Send admin notification
932 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
934 // Send user notification
935 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
940 // Calculate minimum value for dynamic payment model
941 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
944 // Addon is zero by default
948 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
951 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
954 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
957 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
960 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
962 // Get user's total URLs
963 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
966 if ($totalUrls > 0) {
967 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
969 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
975 // Calculate maximum value for dynamic payment model
976 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
979 // Addon is zero by default
986 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
989 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
992 $addon += abs($max * $percent * $totalUsers);
995 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
998 $addon += abs($max * $percent * $totalUrls);
1003 // Calculate dynamic lock
1004 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1007 // Default lock is 30 seconds
1011 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1014 $addon = abs(log($onlineUsers / $addon + 1));
1019 // "Getter" for lock ids array
1020 function SURFBAR_GET_LOCK_IDS () {
1021 // Prepare some arrays
1026 // Get all id from locks within the timestamp
1027 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1029 "._MYSQL_PREFIX."_surfbar_locks
1033 id ASC", array($GLOBALS['userid']),
1034 __FILE__, __LINE__);
1037 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1039 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
1041 // Skip entries that are too old
1042 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1044 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
1046 // Add only if missing or bigger
1047 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1049 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
1057 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
1059 // Ignore these old entries!
1067 SQL_FREERESULT($result);
1072 // "Getter" for maximum random number
1073 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1075 // Count max availabe entries
1076 $result = SQL_QUERY("SELECT sbu.id AS cnt
1077 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1078 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1079 ON sbu.id=sbs.url_id
1080 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1082 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0)) AND sbu.status='ACTIVE'".$ADD."
1083 GROUP BY sbu.id", __FILE__, __LINE__);
1086 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1089 $maxRand = SQL_NUMROWS($result);
1092 SQL_FREERESULT($result);
1097 // Load all URLs of the current user and return it as an array
1098 function SURFBAR_GET_USER_URLS () {
1103 $result = SQL_QUERY_ESC("SELECT u.id, u.userid, 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
1104 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1105 WHERE u.userid=%s AND u.status != 'DELETED'
1107 array($GLOBALS['userid']), __FILE__, __LINE__);
1109 // Are there entries?
1110 if (SQL_NUMROWS($result) > 0) {
1112 while ($row = SQL_FETCHARRAY($result)) {
1114 $URLs[$row['id']] = $row;
1119 SQL_FREERESULT($result);
1124 // "Getter" for member action array for given status
1125 function SURFBAR_GET_ACTION_ARRAY ($status) {
1127 $returnArray = array();
1129 // Get all assigned actions
1130 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1131 array($status), __FILE__, __LINE__);
1133 // Some entries there?
1134 if (SQL_NUMROWS($result) > 0) {
1136 while (list($action) = SQL_FETCHROW($result)) {
1137 $returnArray[] = $action;
1142 SQL_FREERESULT($result);
1145 return $returnArray;
1147 // Reload to configured stop page
1148 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1151 // Internal or external?
1152 if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1153 // Reload to internal page
1154 LOAD_URL("surfbar.php?frame=".$page);
1156 // Reload to external page
1157 LOAD_URL($_CONFIG['surfbar_pause_url']);
1161 // Determine next id for surfbar or get data for given id, always call this before you call other
1162 // getters below this function!!!
1163 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1164 global $SURFBAR_CACHE, $_CONFIG;
1166 // Default is no id and no random number
1172 // Get array with lock ids
1173 $USE = SURFBAR_GET_LOCK_IDS();
1175 // Shall we add some URL ids to ignore?
1177 if (count($USE) > 0) {
1179 $ADD = " AND sbu.id NOT IN (";
1180 foreach ($USE as $url_id => $lid) {
1182 $ADD .= $url_id.",";
1185 // Add closing bracket
1186 $ADD = substr($ADD, 0, -1) . ")";
1189 // Determine depleted user account
1190 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1192 // Get maximum randomness factor
1193 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
1195 // If more than one URL can be called generate the random number!
1197 // Generate random number
1198 $randNum = mt_rand(0, ($maxRand - 1));
1201 // And query the database
1202 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
1203 $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
1204 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1205 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1206 ON sbu.id=sbs.url_id
1207 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1209 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$ADD."
1211 ORDER BY l.last_surfed ASC, sbu.id ASC
1213 array($randNum), __FILE__, __LINE__
1216 // Get data from specified id number
1217 $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
1218 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1219 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1220 ON sbu.id=sbs.url_id
1221 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1223 WHERE sbu.userid != %s AND sbu.status='ACTIVE' AND sbu.id=%s AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))
1225 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1229 // Is there an id number?
1230 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1231 if (SQL_NUMROWS($result) == 1) {
1233 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1234 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1235 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1237 // Determine waiting time
1238 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1240 // Is the last salt there?
1241 if (is_null($SURFBAR_CACHE['last_salt'])) {
1242 // Then repair it wit the static!
1243 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1244 $SURFBAR_CACHE['last_salt'] = "";
1247 // Fix missing last_surfed
1248 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1250 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1251 $SURFBAR_CACHE['last_surfed'] = 0;
1254 // Get base/fixed reward and costs
1255 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1256 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1257 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1259 // Only in dynamic model add the dynamic bonus!
1260 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1261 // Calculate dynamic reward/costs and add it
1262 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1263 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1264 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1268 $nextId = SURFBAR_GET_ID();
1272 SQL_FREERESULT($result);
1275 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1278 // -----------------------------------------------------------------------------
1279 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1280 // $SURFBAR_CACHE ARRAY!
1281 // -----------------------------------------------------------------------------
1282 // Private getter for data elements
1283 function SURFBAR_GET_DATA ($element) {
1284 global $SURFBAR_CACHE;
1285 //DEBUG_LOG(__FUNCTION__.":element={$element}");
1290 // Is the entry there?
1291 if (isset($SURFBAR_CACHE[$element])) {
1293 $data = $SURFBAR_CACHE[$element];
1294 } else { // END - if
1296 print_r($SURFBAR_CACHE);
1297 debug_print_backtrace();
1302 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1305 // Getter for reward from cache
1306 function SURFBAR_GET_REWARD () {
1307 // Get data element and return its contents
1308 return SURFBAR_GET_DATA('reward');
1310 // Getter for costs from cache
1311 function SURFBAR_GET_COSTS () {
1312 // Get data element and return its contents
1313 return SURFBAR_GET_DATA('costs');
1315 // Getter for URL from cache
1316 function SURFBAR_GET_URL () {
1317 // Get data element and return its contents
1318 return SURFBAR_GET_DATA('url');
1320 // Getter for salt from cache
1321 function SURFBAR_GET_SALT () {
1322 // Get data element and return its contents
1323 return SURFBAR_GET_DATA('salt');
1325 // Getter for id from cache
1326 function SURFBAR_GET_ID () {
1327 // Get data element and return its contents
1328 return SURFBAR_GET_DATA('id');
1330 // Getter for userid from cache
1331 function SURFBAR_GET_USERID () {
1332 // Get data element and return its contents
1333 return SURFBAR_GET_DATA('userid');
1335 // Getter for user reload locks
1336 function SURFBAR_GET_USER_RELOAD_LOCK () {
1337 // Get data element and return its contents
1338 return SURFBAR_GET_DATA('user_locks');
1340 // Getter for reload time
1341 function SURFBAR_GET_RELOAD_TIME () {
1342 // Get data element and return its contents
1343 return SURFBAR_GET_DATA('time');