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);
281 // -----------------------------------------------------------------------------
283 // -----------------------------------------------------------------------------
285 // Looks up by an URL
286 function SURFBAR_LOOKUP_BY_URL ($url) {
287 // Now lookup that given URL by itself
288 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
291 return (count($urlArray) > 0);
293 // Load URL data by given search term and column
294 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
297 // By default nothing is found
298 $lastUrlData = array();
300 // Is the column an id number?
301 if (($column == "id") || ($column == "userid")) {
302 // Extra secure input
303 $searchTerm = bigintval($searchTerm);
306 // If the column is "id" there can be only one entry
308 if ($column == "id") {
312 // Look up the record
313 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, status, registered, last_locked, lock_reason
314 FROM "._MYSQL_PREFIX."_surfbar_urls
318 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
320 // Is there at least one record?
321 if (SQL_NUMROWS($result) > 0) {
323 while ($dataRow = SQL_FETCHARRAY($result)) {
324 // Shall we group these results?
325 if ($group == "id") {
326 // Add the row by id as index
327 $lastUrlData[$dataRow['id']] = $dataRow;
330 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
336 SQL_FREERESULT($result);
341 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
342 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg") {
345 // Make sure by the user registered URLs are always pending
346 if ($addMode == "reg") $status = "PENDING";
351 'frametester' => FRAMETESTER($url),
356 // Insert the URL into database
357 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
359 // Translate status, reward and costs
360 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
362 // If in reg-mode we notify admin
363 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
364 // Notify admin even when he as unlocked an email
365 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
369 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
371 // Return the insert id
372 return $content['insert_id'];
374 // Inserts an url by given data array and return the insert id
375 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
377 $uid = bigintval($urlData['uid']);
380 if (empty($uid)) $uid = 0;
382 // Just run the insert query for now
383 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, status) VALUES(%s, '%s', '%s')",
388 ), __FILE__, __LINE__
392 return SQL_INSERTID();
394 // Notify admin(s) with a selected message and content
395 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
396 // Prepare template name
397 $templateName = sprintf("admin_surfbar_%s", $messageType);
399 // Set default subject if following eval() wents wrong
400 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
403 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
404 strtoupper($messageType)
408 // Send the notification out
409 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
411 // Notify the user about the performed action
412 function SURFBAR_NOTIFY_USER ($messageType, $content) {
413 // Skip notification if userid is zero
414 if ($content['uid'] == 0) {
418 // Prepare template name
419 $templateName = sprintf("member_surfbar_%s", $messageType);
421 // Set default subject if following eval() wents wrong
422 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
425 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
426 strtoupper($messageType)
431 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
434 return SEND_EMAIL($content['uid'], $subject, $mailText);
436 // Translate the URL status
437 function SURFBAR_TRANSLATE_STATUS ($status) {
438 // Create constant name
439 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
441 // Set default translated status
442 $statusTranslated = "!".$constantName."!";
444 // Generate eval() command
445 if (defined($constantName)) {
446 $eval = "\$statusTranslated = ".$constantName.";";
451 return $statusTranslated;
454 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
457 // Static values are default
458 $reward = $_CONFIG['surfbar_static_reward'];
460 // Do we have static or dynamic?
461 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
462 // "Calculate" dynamic reward
464 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
466 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
474 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
477 // Static costs is default
478 $costs = $_CONFIG['surfbar_static_costs'];
480 // Do we have static or dynamic?
481 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
482 // "Calculate" dynamic costs
484 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
486 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
493 // "Calculate" dynamic add
494 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
495 // Get min/max values
496 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
497 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
499 // "Calculate" dynamic part and return it
500 return mt_rand($min, $max);
502 // Determine right template name
503 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
504 // Default is the frameset
505 $templateName = "surfbar_frameset";
507 // Any frame set? ;-)
508 if (isset($_GET['frame'])) {
509 // Use the frame as a template name part... ;-)
510 $templateName = sprintf("surfbar_frame_%s",
511 SQL_ESCAPE($_GET['frame'])
516 return $templateName;
518 // Check if the "reload lock" of the current user is full, call this function
519 // before you call SURFBAR_CHECK_RELOAD_LOCK().
520 function SURFBAR_CHECK_RELOAD_FULL() {
521 global $SURFBAR_CACHE, $_CONFIG;
526 // Cache static reload lock
527 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
528 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
530 // Do we have dynamic model?
531 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
532 // "Calculate" dynamic lock
533 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
537 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
538 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
540 array($GLOBALS['userid']), __FILE__, __LINE__
544 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
547 if (is_null($SURFBAR_CACHE['user_locks'])) {
548 // Then fix it to zero!
549 $SURFBAR_CACHE['user_locks'] = 0;
553 SQL_FREERESULT($result);
556 $total = SURFBAR_GET_TOTAL_URLS();
558 // Do we have some URLs in lock? Admins can always surf on own URLs!
559 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
560 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
565 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
566 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId="") {
567 // Determine depleted user account
568 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
570 // Is the exlude userid set?
571 if ($excludeUserId !== "") {
573 $UIDs[] = $excludeUserId;
576 // Get amount from database
577 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
578 FROM "._MYSQL_PREFIX."_surfbar_urls
579 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
580 array($status), __FILE__, __LINE__
584 list($cnt) = SQL_FETCHROW($result);
587 SQL_FREERESULT($result);
592 // Check wether the user is allowed to book more URLs
593 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
596 // Is this admin and userid is zero or does the user has some URLs left to book?
597 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
599 // Get total amount of URLs of given status for current user
600 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
603 // Is the user 0 and user is logged in?
604 if (($uid == 0) && (IS_MEMBER())) {
605 // Then use this userid
606 $uid = $GLOBALS['userid'];
607 } elseif ($uid == 0) {
609 return ($_CONFIG['surfbar_max_order'] + 1);
612 // Default is all URLs
615 // Is the status set?
616 if (is_array($status)) {
617 // Only URLs with these status
618 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
619 } elseif (!empty($status)) {
620 // Only URLs with this status
621 $ADD = sprintf(" AND status='%s'", $status);
622 } elseif (is_array($exclude)) {
623 // Exclude URLs with these status
624 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
625 } elseif (!empty($exclude)) {
626 // Exclude URLs with this status
627 $ADD = sprintf(" AND status != '%s'", $exclude);
630 // Get amount from database
631 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
632 FROM "._MYSQL_PREFIX."_surfbar_urls
633 WHERE userid=%s".$ADD."
635 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
639 list($cnt) = SQL_FETCHROW($result);
642 SQL_FREERESULT($result);
647 // Generate a validation code for the given id number
648 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
649 global $_CONFIG, $SURFBAR_CACHE;
651 // @TODO Invalid salt should be refused
652 $SURFBAR_CACHE['salt'] = "INVALID";
654 // Get code length from config
655 $length = $_CONFIG['code_length'];
658 if ($length == 0) $length = 10;
660 // Generate a code until the length matches
662 while (strlen($valCode) != $length) {
665 // Generate random hashed string
666 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
667 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
670 $SURFBAR_CACHE['salt'] = $salt;
671 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
674 // ... and now the validation code
675 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
676 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
679 // Hash it with md5() and salt it with the random string
680 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
682 // Finally encrypt it PGP-like and return it
683 $valHashedCode = generatePassString($hashedCode);
684 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
685 return $valHashedCode;
687 // Check validation code
688 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
689 global $SURFBAR_CACHE;
692 $urlId = bigintval($urlId);
694 // Now generate the code again
695 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
697 // Return result of checking hashes and salts
698 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
699 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
700 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
702 // Lockdown the userid/id combination (reload lock)
703 function SURFBAR_LOCKDOWN_ID ($urlId) {
704 //* //DEBUG: */ print "LOCK!");
705 ///* //DEBUG: */ return;
706 // Just add it to the database
707 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
708 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
710 // Remove the salt from database
711 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
712 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
714 // Pay points to the user and remove it from the sender
715 function SURFBAR_PAY_POINTS ($urlId) {
716 // Remove it from the URL owner
717 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
718 if (SURFBAR_GET_USERID() > 0) {
719 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
722 // Book it to the user
723 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
724 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
726 // Updates the statistics of current URL/userid
727 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
730 // Update views_total
731 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
732 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
734 // Update the stats entry
735 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
736 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
738 // Was that update okay?
739 if (SQL_AFFECTEDROWS() == 0) {
740 // No, then insert entry
741 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
742 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
745 // Update total/daily/weekly/monthly counter
746 $_CONFIG['surfbar_total_counter']++;
747 $_CONFIG['surfbar_daily_counter']++;
748 $_CONFIG['surfbar_weekly_counter']++;
749 $_CONFIG['surfbar_monthly_counter']++;
751 // Update config as well
752 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
754 // Update the salt for validation and statistics
755 function SURFBAR_UPDATE_SALT_STATS () {
756 // Update statistics record
757 SURFBAR_UPDATE_INSERT_STATS_RECORD();
759 // Simply store the salt from cache away in database...
760 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
761 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
764 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
767 if (SQL_AFFECTEDROWS() == 0) {
768 // Insert missing entry!
769 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
770 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
774 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
776 // Return if the update was okay
777 return (SQL_AFFECTEDROWS() == 1);
779 // Check if the reload lock is active for given id
780 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
781 //DEBUG_LOG(__FUNCTION__.":id={$urlId}");
783 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
784 FROM "._MYSQL_PREFIX."_surfbar_locks
785 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
786 ORDER BY last_surfed ASC
788 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
792 list($cnt) = SQL_FETCHROW($result);
795 SQL_FREERESULT($result);
798 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
801 // Determine which user hash no more points left
802 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
806 // Do we have a current user id?
808 // Then add this as well
809 $UIDs[] = $GLOBALS['userid'];
811 // Get all userid except logged in one
812 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
813 WHERE userid NOT IN (%s,0) AND status='ACTIVE'
815 ORDER BY userid ASC",
816 array($GLOBALS['userid']), __FILE__, __LINE__);
819 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
820 WHERE status='ACTIVE'
822 ORDER BY userid ASC", __FILE__, __LINE__);
826 while (list($uid) = SQL_FETCHROW($result)) {
828 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
829 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
831 // Shall we add this to ignore?
834 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
840 SQL_FREERESULT($result);
843 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
848 // Determine how many users are Online in surfbar
849 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
852 // Count all users in surfbar modue and return the value
853 $result = SQL_QUERY_ESC("SELECT id
854 FROM "._MYSQL_PREFIX."_surfbar_stats
855 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
857 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
860 $cnt = SQL_NUMROWS($result);
863 SQL_FREERESULT($result);
868 // Determine waiting time for one URL
869 function SURFBAR_DETERMINE_WAIT_TIME () {
872 // Static time is default
873 $time = $_CONFIG['surfbar_static_time'];
875 // Which payment model do we have?
876 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
877 // "Calculate" dynamic time
878 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
884 // Changes the status of an URL from given to other
885 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
888 // Get URL data for status comparison if missing
889 if (count($data) == 0) {
890 $data = SURFBAR_GET_URL_DATA($urlId);
893 // Is the status like prevStatus is saying?
894 if ($data[$urlId]['status'] != $prevStatus) {
895 // No, then abort here
900 // Update the status now
901 // ---------------------- Commented out for debugging member actions! -----------------------
902 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
903 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
904 // ---------------------- Commented out for debugging member actions! -----------------------
907 if (SQL_AFFECTEDROWS() != 1) {
908 // No, something went wrong
912 // Prepare content for notification routines
913 $data[$urlId]['uid'] = $data[$urlId]['userid'];
914 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
915 $data[$urlId]['reward'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
916 $data[$urlId]['costs'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
917 $data[$urlId]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
918 $data[$urlId]['registered'] = MAKE_DATETIME($data[$urlId]['registered'], "2");
919 $newStatus = strtolower($newStatus);
921 // Send admin notification
922 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
924 // Send user notification
925 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
930 // Calculate minimum value for dynamic payment model
931 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
934 // Addon is zero by default
938 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
941 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
944 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
947 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
950 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
952 // Get user's total URLs
953 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
956 if ($totalUrls > 0) {
957 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
959 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
965 // Calculate maximum value for dynamic payment model
966 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
969 // Addon is zero by default
976 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
979 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
982 $addon += abs($max * $percent * $totalUsers);
985 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
988 $addon += abs($max * $percent * $totalUrls);
993 // Calculate dynamic lock
994 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
997 // Default lock is 30 seconds
1001 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1004 $addon = abs(log($onlineUsers / $addon + 1));
1009 // "Getter" for lock ids array
1010 function SURFBAR_GET_LOCK_IDS () {
1011 // Prepare some arrays
1016 // Get all id from locks within the timestamp
1017 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1019 "._MYSQL_PREFIX."_surfbar_locks
1023 id ASC", array($GLOBALS['userid']),
1024 __FILE__, __LINE__);
1027 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1029 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
1031 // Skip entries that are too old
1032 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1034 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
1036 // Add only if missing or bigger
1037 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1039 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
1047 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
1049 // Ignore these old entries!
1057 SQL_FREERESULT($result);
1062 // "Getter" for maximum random number
1063 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1065 // Count max availabe entries
1066 $result = SQL_QUERY("SELECT sbu.id AS cnt
1067 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1068 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1069 ON sbu.id=sbs.url_id
1070 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1072 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."
1073 GROUP BY sbu.id", __FILE__, __LINE__);
1076 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1079 $maxRand = SQL_NUMROWS($result);
1082 SQL_FREERESULT($result);
1087 // Load all URLs of the current user and return it as an array
1088 function SURFBAR_GET_USER_URLS () {
1093 $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
1094 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1095 WHERE u.userid=%s AND u.status != 'DELETED'
1097 array($GLOBALS['userid']), __FILE__, __LINE__);
1099 // Are there entries?
1100 if (SQL_NUMROWS($result) > 0) {
1102 while ($row = SQL_FETCHARRAY($result)) {
1104 $URLs[$row['id']] = $row;
1109 SQL_FREERESULT($result);
1114 // "Getter" for member action array for given status
1115 function SURFBAR_GET_ACTION_ARRAY ($status) {
1117 $returnArray = array();
1119 // Get all assigned actions
1120 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1121 array($status), __FILE__, __LINE__);
1123 // Some entries there?
1124 if (SQL_NUMROWS($result) > 0) {
1126 while (list($action) = SQL_FETCHROW($result)) {
1127 $returnArray[] = $action;
1132 SQL_FREERESULT($result);
1135 return $returnArray;
1137 // Reload to configured stop page
1138 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1141 // Internal or external?
1142 if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1143 // Reload to internal page
1144 LOAD_URL("surfbar.php?frame=".$page);
1146 // Reload to external page
1147 LOAD_URL($_CONFIG['surfbar_pause_url']);
1151 // Determine next id for surfbar or get data for given id, always call this before you call other
1152 // getters below this function!!!
1153 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1154 global $SURFBAR_CACHE, $_CONFIG;
1156 // Default is no id and no random number
1162 // Get array with lock ids
1163 $USE = SURFBAR_GET_LOCK_IDS();
1165 // Shall we add some URL ids to ignore?
1167 if (count($USE) > 0) {
1169 $ADD = " AND sbu.id NOT IN (";
1170 foreach ($USE as $url_id => $lid) {
1172 $ADD .= $url_id.",";
1175 // Add closing bracket
1176 $ADD = substr($ADD, 0, -1) . ")";
1179 // Determine depleted user account
1180 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1182 // Get maximum randomness factor
1183 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
1185 // If more than one URL can be called generate the random number!
1187 // Generate random number
1188 $randNum = mt_rand(0, ($maxRand - 1));
1191 // And query the database
1192 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
1193 $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
1194 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1195 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1196 ON sbu.id=sbs.url_id
1197 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1199 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."
1201 ORDER BY l.last_surfed ASC, sbu.id ASC
1203 array($randNum), __FILE__, __LINE__
1206 // Get data from specified id number
1207 $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
1208 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1209 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1210 ON sbu.id=sbs.url_id
1211 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1213 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))
1215 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1219 // Is there an id number?
1220 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1221 if (SQL_NUMROWS($result) == 1) {
1223 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1224 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1225 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1227 // Determine waiting time
1228 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1230 // Is the last salt there?
1231 if (is_null($SURFBAR_CACHE['last_salt'])) {
1232 // Then repair it wit the static!
1233 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1234 $SURFBAR_CACHE['last_salt'] = "";
1237 // Fix missing last_surfed
1238 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1240 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1241 $SURFBAR_CACHE['last_surfed'] = 0;
1244 // Get base/fixed reward and costs
1245 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1246 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1247 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1249 // Only in dynamic model add the dynamic bonus!
1250 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1251 // Calculate dynamic reward/costs and add it
1252 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1253 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1254 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1258 $nextId = SURFBAR_GET_ID();
1262 SQL_FREERESULT($result);
1265 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1268 // -----------------------------------------------------------------------------
1269 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1270 // $SURFBAR_CACHE ARRAY!
1271 // -----------------------------------------------------------------------------
1272 // Private getter for data elements
1273 function SURFBAR_GET_DATA ($element) {
1274 global $SURFBAR_CACHE;
1275 //DEBUG_LOG(__FUNCTION__.":element={$element}");
1280 // Is the entry there?
1281 if (isset($SURFBAR_CACHE[$element])) {
1283 $data = $SURFBAR_CACHE[$element];
1284 } else { // END - if
1286 print_r($SURFBAR_CACHE);
1287 debug_print_backtrace();
1292 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1295 // Getter for reward from cache
1296 function SURFBAR_GET_REWARD () {
1297 // Get data element and return its contents
1298 return SURFBAR_GET_DATA('reward');
1300 // Getter for costs from cache
1301 function SURFBAR_GET_COSTS () {
1302 // Get data element and return its contents
1303 return SURFBAR_GET_DATA('costs');
1305 // Getter for URL from cache
1306 function SURFBAR_GET_URL () {
1307 // Get data element and return its contents
1308 return SURFBAR_GET_DATA('url');
1310 // Getter for salt from cache
1311 function SURFBAR_GET_SALT () {
1312 // Get data element and return its contents
1313 return SURFBAR_GET_DATA('salt');
1315 // Getter for id from cache
1316 function SURFBAR_GET_ID () {
1317 // Get data element and return its contents
1318 return SURFBAR_GET_DATA('id');
1320 // Getter for userid from cache
1321 function SURFBAR_GET_USERID () {
1322 // Get data element and return its contents
1323 return SURFBAR_GET_DATA('userid');
1325 // Getter for user reload locks
1326 function SURFBAR_GET_USER_RELOAD_LOCK () {
1327 // Get data element and return its contents
1328 return SURFBAR_GET_DATA('user_locks');
1330 // Getter for reload time
1331 function SURFBAR_GET_RELOAD_TIME () {
1332 // Get data element and return its contents
1333 return SURFBAR_GET_DATA('time');