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, $limit) {
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()) {
59 } elseif ("".bigintval($limit)."" != "".$limit."") {
60 // Invalid amount entered
64 // Register the new URL
65 return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", $limit);
67 // Admin unlocked an email so we can migrate the URL
68 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
73 } elseif (!VALIDATE_URL($url)) {
76 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
77 // URL already found in surfbar!
79 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
84 // Register the new URL
85 return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
87 // Admin function for unlocking URLs
88 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
89 // Is this an admin or invalid array?
91 // Not admin or invalid IDs array
93 } elseif (!is_array($IDs)) {
96 } elseif (count($IDs) == 0) {
101 // Set to true to make AND expression valid if first URL got unlocked
104 // Update the status for all ids
105 foreach ($IDs as $id => $dummy) {
106 // Test all ids through (ignores failed)
107 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
110 // Return total status
113 // Admin function for rejecting URLs
114 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
115 // Is this an admin or invalid array?
117 // Not admin or invalid IDs array
119 } elseif (!is_array($IDs)) {
122 } elseif (count($IDs) == 0) {
127 // Set to true to make AND expression valid if first URL got unlocked
130 // Update the status for all ids
131 foreach ($IDs as $id => $dummy) {
132 // Test all ids through (ignores failed)
133 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
136 // Return total status
140 // -----------------------------------------------------------------------------
142 // -----------------------------------------------------------------------------
144 // Member has added an URL
145 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
148 // Do some pre-checks
152 } elseif (!VALIDATE_URL($url)) {
155 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
156 // URL already found in surfbar!
158 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
161 } elseif ("".bigintval($limit)."" != "".$limit."") {
162 // Invalid amount entered
166 // Register the new URL
167 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", $limit);
169 // Create list of actions depending on status for the user
170 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
171 // Load all actions in an array for given status
172 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
175 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
179 $width = round(100 / count($actionArray));
181 // "Walk" through all actions and create forms
182 foreach ($actionArray as $actionId=>$action) {
183 // Add form for this action
184 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
185 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
186 <input type=\"hidden\" name=\"id\" value=\"%s\" />
187 <input type=\"hidden\" name=\"action\" value=\"%s\" />
188 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
206 // Do the member form request
207 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
208 global $SURFBAR_CACHE;
210 // By default no action is performed
217 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
218 // Important form elements are missing!
220 } elseif (!isset($URLs[$formData['id']])) {
221 // ID not found in cache
223 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
224 // Action not allowed for current URL status
228 // Create the function name for selected action
229 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper(SQL_ESCAPE($formData['action'])));
231 // Is the function there?
232 if (function_exists($functionName)) {
234 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
236 // Extract URL data for call-back
237 $urlData = array($URLs[$formData['id']]);
239 // Action found so execute it
240 $performed = call_user_func_array($functionName, $urlData);
242 // Log invalid request
243 DEBUG_LOG(__FUNCTION__.": action={$formData['action']},id={$formData['id']},function={$functionName}");
249 // Validate if the requested action can be performed on current URL status
250 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
251 global $SURFBAR_CACHE;
253 // Search for the requested action/status combination in database
254 $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
255 array($action, $status), __FILE__, __LINE__);
257 // Is the entry there?
258 $isValid = (SQL_NUMROWS($result) == 1);
260 // Fetch the new status if found
262 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
266 SQL_FREERESULT($result);
272 // -----------------------------------------------------------------------------
274 // -----------------------------------------------------------------------------
277 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
278 // Create the data array for next function call
280 $urlData['id'] => $urlData
283 // Simply change the status here
284 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
286 // Book an URL now (from migration)
287 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
288 // Create the data array for next function call
290 $urlData['id'] => $urlData
293 // Simply change the status here
294 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
297 // -----------------------------------------------------------------------------
299 // -----------------------------------------------------------------------------
301 // Looks up by an URL
302 function SURFBAR_LOOKUP_BY_URL ($url) {
303 // Now lookup that given URL by itself
304 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
307 return (count($urlArray) > 0);
309 // Load URL data by given search term and column
310 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
313 // By default nothing is found
314 $lastUrlData = array();
316 // Is the column an id number?
317 if (($column == "id") || ($column == "userid")) {
318 // Extra secure input
319 $searchTerm = bigintval($searchTerm);
322 // If the column is "id" there can be only one entry
324 if ($column == "id") {
328 // Look up the record
329 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, status, registered, last_locked, lock_reason
330 FROM "._MYSQL_PREFIX."_surfbar_urls
334 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
336 // Is there at least one record?
337 if (SQL_NUMROWS($result) > 0) {
339 while ($dataRow = SQL_FETCHARRAY($result)) {
340 // Shall we group these results?
341 if ($group == "id") {
342 // Add the row by id as index
343 $lastUrlData[$dataRow['id']] = $dataRow;
346 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
352 SQL_FREERESULT($result);
357 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
358 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $limit=0) {
361 // Make sure by the user registered URLs are always pending
362 if ($addMode == "reg") $status = "PENDING";
367 'frametester' => FRAMETESTER($url),
373 // Insert the URL into database
374 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
377 if ($content['insert_id'] == 0) {
378 // INSERT did not insert any data!
382 // Translate status and limit
383 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
384 $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
386 // If in reg-mode we notify admin
387 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
388 // Notify admin even when he as unlocked an email
389 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
393 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
395 // Return the insert id
396 return $content['insert_id'];
398 // Inserts an url by given data array and return the insert id
399 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
401 $uid = bigintval($urlData['uid']);
404 if (empty($uid)) $uid = 0;
406 // Just run the insert query for now
407 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid,url,status,views_max,views_allowed) VALUES(%s,'%s','%s','%s','%s')",
414 ), __FILE__, __LINE__
418 return SQL_INSERTID();
420 // Notify admin(s) with a selected message and content
421 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
422 // Prepare template name
423 $templateName = sprintf("admin_surfbar_%s", $messageType);
425 // Set default subject if following eval() wents wrong
426 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
429 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
430 strtoupper($messageType)
434 // Send the notification out
435 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
437 // Notify the user about the performed action
438 function SURFBAR_NOTIFY_USER ($messageType, $content) {
439 // Skip notification if userid is zero
440 if ($content['uid'] == 0) {
444 // Prepare template name
445 $templateName = sprintf("member_surfbar_%s", $messageType);
447 // Set default subject if following eval() wents wrong
448 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
451 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
452 strtoupper($messageType)
457 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
460 return SEND_EMAIL($content['uid'], $subject, $mailText);
462 // Translates the limit
463 function SURFBAR_TRANSLATE_LIMIT ($limit) {
467 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
470 $return = TRANSLATE_COMMA($limit);
476 // Translate the URL status
477 function SURFBAR_TRANSLATE_STATUS ($status) {
478 // Create constant name
479 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
481 // Set default translated status
482 $statusTranslated = "!".$constantName."!";
484 // Generate eval() command
485 if (defined($constantName)) {
486 $eval = "\$statusTranslated = ".$constantName.";";
491 return $statusTranslated;
494 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
497 // Static values are default
498 $reward = $_CONFIG['surfbar_static_reward'];
500 // Do we have static or dynamic?
501 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
502 // "Calculate" dynamic reward
504 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
506 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
514 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
517 // Static costs is default
518 $costs = $_CONFIG['surfbar_static_costs'];
520 // Do we have static or dynamic?
521 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
522 // "Calculate" dynamic costs
524 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
526 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
533 // "Calculate" dynamic add
534 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
535 // Get min/max values
536 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
537 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
539 // "Calculate" dynamic part and return it
540 return mt_rand($min, $max);
542 // Determine right template name
543 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
544 // Default is the frameset
545 $templateName = "surfbar_frameset";
547 // Any frame set? ;-)
548 if (isset($_GET['frame'])) {
549 // Use the frame as a template name part... ;-)
550 $templateName = sprintf("surfbar_frame_%s",
551 SQL_ESCAPE($_GET['frame'])
556 return $templateName;
558 // Check if the "reload lock" of the current user is full, call this function
559 // before you call SURFBAR_CHECK_RELOAD_LOCK().
560 function SURFBAR_CHECK_RELOAD_FULL() {
561 global $SURFBAR_CACHE, $_CONFIG;
566 // Cache static reload lock
567 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
568 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
570 // Do we have dynamic model?
571 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
572 // "Calculate" dynamic lock
573 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
577 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
578 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
580 array($GLOBALS['userid']), __FILE__, __LINE__
584 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
587 if (is_null($SURFBAR_CACHE['user_locks'])) {
588 // Then fix it to zero!
589 $SURFBAR_CACHE['user_locks'] = 0;
593 SQL_FREERESULT($result);
596 $total = SURFBAR_GET_TOTAL_URLS();
598 // Do we have some URLs in lock? Admins can always surf on own URLs!
599 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
600 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
605 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
606 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId="") {
607 // Determine depleted user account
608 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
610 // Is the exlude userid set?
611 if ($excludeUserId !== "") {
613 $UIDs[] = $excludeUserId;
616 // Get amount from database
617 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
618 FROM "._MYSQL_PREFIX."_surfbar_urls
619 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
620 array($status), __FILE__, __LINE__
624 list($cnt) = SQL_FETCHROW($result);
627 SQL_FREERESULT($result);
632 // Check wether the user is allowed to book more URLs
633 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
636 // Is this admin and userid is zero or does the user has some URLs left to book?
637 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
639 // Get total amount of URLs of given status for current user
640 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
643 // Is the user 0 and user is logged in?
644 if (($uid == 0) && (IS_MEMBER())) {
645 // Then use this userid
646 $uid = $GLOBALS['userid'];
647 } elseif ($uid == 0) {
649 return ($_CONFIG['surfbar_max_order'] + 1);
652 // Default is all URLs
655 // Is the status set?
656 if (is_array($status)) {
657 // Only URLs with these status
658 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
659 } elseif (!empty($status)) {
660 // Only URLs with this status
661 $ADD = sprintf(" AND status='%s'", $status);
662 } elseif (is_array($exclude)) {
663 // Exclude URLs with these status
664 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
665 } elseif (!empty($exclude)) {
666 // Exclude URLs with this status
667 $ADD = sprintf(" AND status != '%s'", $exclude);
670 // Get amount from database
671 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
672 FROM "._MYSQL_PREFIX."_surfbar_urls
673 WHERE userid=%s".$ADD."
675 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
679 list($cnt) = SQL_FETCHROW($result);
682 SQL_FREERESULT($result);
687 // Generate a validation code for the given id number
688 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
689 global $_CONFIG, $SURFBAR_CACHE;
691 // @TODO Invalid salt should be refused
692 $SURFBAR_CACHE['salt'] = "INVALID";
694 // Get code length from config
695 $length = $_CONFIG['code_length'];
698 if ($length == 0) $length = 10;
700 // Generate a code until the length matches
702 while (strlen($valCode) != $length) {
705 // Generate random hashed string
706 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
707 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
710 $SURFBAR_CACHE['salt'] = $salt;
711 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
714 // ... and now the validation code
715 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
716 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
719 // Hash it with md5() and salt it with the random string
720 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
722 // Finally encrypt it PGP-like and return it
723 $valHashedCode = generatePassString($hashedCode);
724 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
725 return $valHashedCode;
727 // Check validation code
728 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
729 global $SURFBAR_CACHE;
732 $urlId = bigintval($urlId);
734 // Now generate the code again
735 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
737 // Return result of checking hashes and salts
738 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
739 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
740 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
742 // Lockdown the userid/id combination (reload lock)
743 function SURFBAR_LOCKDOWN_ID ($urlId) {
744 //* //DEBUG: */ print "LOCK!");
745 ///* //DEBUG: */ return;
746 // Just add it to the database
747 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
748 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
750 // Remove the salt from database
751 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
752 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
754 // Pay points to the user and remove it from the sender
755 function SURFBAR_PAY_POINTS ($urlId) {
756 // Remove it from the URL owner
757 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
758 if (SURFBAR_GET_USERID() > 0) {
759 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
762 // Book it to the user
763 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
764 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
766 // Updates the statistics of current URL/userid
767 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
774 $allowed = SURFBAR_GET_ALLOWED_VIEWS();
776 // Do we have a limit?
778 // Then count views_max down!
779 $ADD .= ",views_max=views_max-1";
783 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
784 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
786 // Update the stats entry
787 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
788 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
790 // Was that update okay?
791 if (SQL_AFFECTEDROWS() == 0) {
792 // No, then insert entry
793 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
794 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
797 // Update total/daily/weekly/monthly counter
798 $_CONFIG['surfbar_total_counter']++;
799 $_CONFIG['surfbar_daily_counter']++;
800 $_CONFIG['surfbar_weekly_counter']++;
801 $_CONFIG['surfbar_monthly_counter']++;
803 // Update config as well
804 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
806 // Update the salt for validation and statistics
807 function SURFBAR_UPDATE_SALT_STATS () {
808 // Update statistics record
809 SURFBAR_UPDATE_INSERT_STATS_RECORD();
811 // Simply store the salt from cache away in database...
812 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
813 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
816 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
819 if (SQL_AFFECTEDROWS() == 0) {
820 // Insert missing entry!
821 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
822 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
826 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
828 // Return if the update was okay
829 return (SQL_AFFECTEDROWS() == 1);
831 // Check if the reload lock is active for given id
832 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
833 //DEBUG_LOG(__FUNCTION__.":id={$urlId}");
835 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
836 FROM "._MYSQL_PREFIX."_surfbar_locks
837 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
838 ORDER BY last_surfed ASC
840 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
844 list($cnt) = SQL_FETCHROW($result);
847 SQL_FREERESULT($result);
850 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
853 // Determine which user hash no more points left
854 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
858 // Do we have a current user id?
860 // Then add this as well
861 $UIDs[] = $GLOBALS['userid'];
863 // Get all userid except logged in one
864 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
865 WHERE userid NOT IN (%s,0) AND status='ACTIVE'
867 ORDER BY userid ASC",
868 array($GLOBALS['userid']), __FILE__, __LINE__);
871 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
872 WHERE status='ACTIVE'
874 ORDER BY userid ASC", __FILE__, __LINE__);
878 while (list($uid) = SQL_FETCHROW($result)) {
880 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
881 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
883 // Shall we add this to ignore?
886 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
892 SQL_FREERESULT($result);
895 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
900 // Determine how many users are Online in surfbar
901 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
904 // Count all users in surfbar modue and return the value
905 $result = SQL_QUERY_ESC("SELECT id
906 FROM "._MYSQL_PREFIX."_surfbar_stats
907 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
909 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
912 $cnt = SQL_NUMROWS($result);
915 SQL_FREERESULT($result);
920 // Determine waiting time for one URL
921 function SURFBAR_DETERMINE_WAIT_TIME () {
924 // Static time is default
925 $time = $_CONFIG['surfbar_static_time'];
927 // Which payment model do we have?
928 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
929 // "Calculate" dynamic time
930 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
936 // Changes the status of an URL from given to other
937 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
940 // Get URL data for status comparison if missing
941 if (count($data) == 0) {
942 $data = SURFBAR_GET_URL_DATA($urlId);
945 // Is the status like prevStatus is saying?
946 if ($data[$urlId]['status'] != $prevStatus) {
947 // No, then abort here
952 // Update the status now
953 // ---------------------- Commented out for debugging member actions! -----------------------
954 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
955 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
956 // ---------------------- Commented out for debugging member actions! -----------------------
959 if (SQL_AFFECTEDROWS() != 1) {
960 // No, something went wrong
964 // Prepare content for notification routines
965 $data[$urlId]['uid'] = $data[$urlId]['userid'];
966 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
967 $data[$urlId]['reward'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
968 $data[$urlId]['costs'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
969 $data[$urlId]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
970 $data[$urlId]['registered'] = MAKE_DATETIME($data[$urlId]['registered'], "2");
971 $newStatus = strtolower($newStatus);
973 // Send admin notification
974 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
976 // Send user notification
977 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
982 // Calculate minimum value for dynamic payment model
983 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
986 // Addon is zero by default
990 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
993 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
996 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
999 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1002 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1004 // Get user's total URLs
1005 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1008 if ($totalUrls > 0) {
1009 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1011 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1017 // Calculate maximum value for dynamic payment model
1018 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1021 // Addon is zero by default
1028 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1031 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1034 $addon += abs($max * $percent * $totalUsers);
1037 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1040 $addon += abs($max * $percent * $totalUrls);
1045 // Calculate dynamic lock
1046 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1049 // Default lock is 30 seconds
1053 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1056 $addon = abs(log($onlineUsers / $addon + 1));
1061 // "Getter" for lock ids array
1062 function SURFBAR_GET_LOCK_IDS () {
1063 // Prepare some arrays
1068 // Get all id from locks within the timestamp
1069 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1071 "._MYSQL_PREFIX."_surfbar_locks
1075 id ASC", array($GLOBALS['userid']),
1076 __FILE__, __LINE__);
1079 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1081 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
1083 // Skip entries that are too old
1084 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1086 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
1088 // Add only if missing or bigger
1089 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1091 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
1099 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
1101 // Ignore these old entries!
1109 SQL_FREERESULT($result);
1114 // "Getter" for maximum random number
1115 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1117 // Count max availabe entries
1118 $result = SQL_QUERY("SELECT sbu.id AS cnt
1119 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1120 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1121 ON sbu.id=sbs.url_id
1122 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1124 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."
1125 GROUP BY sbu.id", __FILE__, __LINE__);
1128 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1131 $maxRand = SQL_NUMROWS($result);
1134 SQL_FREERESULT($result);
1139 // Load all URLs of the current user and return it as an array
1140 function SURFBAR_GET_USER_URLS () {
1145 $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
1146 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1147 WHERE u.userid=%s AND u.status != 'DELETED'
1149 array($GLOBALS['userid']), __FILE__, __LINE__);
1151 // Are there entries?
1152 if (SQL_NUMROWS($result) > 0) {
1154 while ($row = SQL_FETCHARRAY($result)) {
1156 $URLs[$row['id']] = $row;
1161 SQL_FREERESULT($result);
1166 // "Getter" for member action array for given status
1167 function SURFBAR_GET_ACTION_ARRAY ($status) {
1169 $returnArray = array();
1171 // Get all assigned actions
1172 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1173 array($status), __FILE__, __LINE__);
1175 // Some entries there?
1176 if (SQL_NUMROWS($result) > 0) {
1178 while (list($action) = SQL_FETCHROW($result)) {
1179 $returnArray[] = $action;
1184 SQL_FREERESULT($result);
1187 return $returnArray;
1189 // Reload to configured stop page
1190 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1193 // Internal or external?
1194 if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1195 // Reload to internal page
1196 LOAD_URL("surfbar.php?frame=".$page);
1198 // Reload to external page
1199 LOAD_URL($_CONFIG['surfbar_pause_url']);
1203 // Determine next id for surfbar or get data for given id, always call this before you call other
1204 // getters below this function!!!
1205 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1206 global $SURFBAR_CACHE, $_CONFIG;
1208 // Default is no id and no random number
1214 // Get array with lock ids
1215 $USE = SURFBAR_GET_LOCK_IDS();
1217 // Shall we add some URL ids to ignore?
1219 if (count($USE) > 0) {
1221 $ADD = " AND sbu.id NOT IN (";
1222 foreach ($USE as $url_id => $lid) {
1224 $ADD .= $url_id.",";
1227 // Add closing bracket
1228 $ADD = substr($ADD, 0, -1) . ")";
1231 // Determine depleted user account
1232 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1234 // Get maximum randomness factor
1235 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
1237 // If more than one URL can be called generate the random number!
1239 // Generate random number
1240 $randNum = mt_rand(0, ($maxRand - 1));
1243 // And query the database
1244 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
1245 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1246 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1247 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1248 ON sbu.id=sbs.url_id
1249 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1251 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."
1253 ORDER BY l.last_surfed ASC, sbu.id ASC
1255 array($randNum), __FILE__, __LINE__
1258 // Get data from specified id number
1259 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1260 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1261 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1262 ON sbu.id=sbs.url_id
1263 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1265 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))
1267 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1271 // Is there an id number?
1272 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1273 if (SQL_NUMROWS($result) == 1) {
1275 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1276 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1277 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1279 // Determine waiting time
1280 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1282 // Is the last salt there?
1283 if (is_null($SURFBAR_CACHE['last_salt'])) {
1284 // Then repair it wit the static!
1285 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1286 $SURFBAR_CACHE['last_salt'] = "";
1289 // Fix missing last_surfed
1290 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1292 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1293 $SURFBAR_CACHE['last_surfed'] = 0;
1296 // Get base/fixed reward and costs
1297 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1298 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1299 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1301 // Only in dynamic model add the dynamic bonus!
1302 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1303 // Calculate dynamic reward/costs and add it
1304 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1305 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1306 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1310 $nextId = SURFBAR_GET_ID();
1314 SQL_FREERESULT($result);
1317 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1320 // -----------------------------------------------------------------------------
1321 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1322 // $SURFBAR_CACHE ARRAY!
1323 // -----------------------------------------------------------------------------
1324 // Private getter for data elements
1325 function SURFBAR_GET_DATA ($element) {
1326 global $SURFBAR_CACHE;
1327 //DEBUG_LOG(__FUNCTION__.":element={$element}");
1332 // Is the entry there?
1333 if (isset($SURFBAR_CACHE[$element])) {
1335 $data = $SURFBAR_CACHE[$element];
1336 } else { // END - if
1338 print_r($SURFBAR_CACHE);
1339 debug_print_backtrace();
1344 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1347 // Getter for reward from cache
1348 function SURFBAR_GET_REWARD () {
1349 // Get data element and return its contents
1350 return SURFBAR_GET_DATA('reward');
1352 // Getter for costs from cache
1353 function SURFBAR_GET_COSTS () {
1354 // Get data element and return its contents
1355 return SURFBAR_GET_DATA('costs');
1357 // Getter for URL from cache
1358 function SURFBAR_GET_URL () {
1359 // Get data element and return its contents
1360 return SURFBAR_GET_DATA('url');
1362 // Getter for salt from cache
1363 function SURFBAR_GET_SALT () {
1364 // Get data element and return its contents
1365 return SURFBAR_GET_DATA('salt');
1367 // Getter for id from cache
1368 function SURFBAR_GET_ID () {
1369 // Get data element and return its contents
1370 return SURFBAR_GET_DATA('id');
1372 // Getter for userid from cache
1373 function SURFBAR_GET_USERID () {
1374 // Get data element and return its contents
1375 return SURFBAR_GET_DATA('userid');
1377 // Getter for user reload locks
1378 function SURFBAR_GET_USER_RELOAD_LOCK () {
1379 // Get data element and return its contents
1380 return SURFBAR_GET_DATA('user_locks');
1382 // Getter for reload time
1383 function SURFBAR_GET_RELOAD_TIME () {
1384 // Get data element and return its contents
1385 return SURFBAR_GET_DATA('time');
1387 // Getter for allowed views
1388 function SURFBAR_GET_ALLOWED_VIEWS () {
1389 // Get data element and return its contents
1390 return SURFBAR_GET_DATA('views_allowed');