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", "0", "ACTIVE", "unlock");
64 // Admin function for unlocking URLs
65 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
66 // Is this an admin or invalid array?
68 // Not admin or invalid IDs array
70 } elseif (!is_array($IDs)) {
73 } elseif (count($IDs) == 0) {
78 // Set to true to make AND expression valid if first URL got unlocked
81 // Update the status for all ids
82 foreach ($IDs as $id => $dummy) {
83 // Test all ids through (ignores failed)
84 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
87 // Return total status
90 // Admin function for rejecting URLs
91 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
92 // Is this an admin or invalid array?
94 // Not admin or invalid IDs array
96 } elseif (!is_array($IDs)) {
99 } elseif (count($IDs) == 0) {
104 // Set to true to make AND expression valid if first URL got unlocked
107 // Update the status for all ids
108 foreach ($IDs as $id => $dummy) {
109 // Test all ids through (ignores failed)
110 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
113 // Return total status
117 // -----------------------------------------------------------------------------
119 // -----------------------------------------------------------------------------
121 // Member has added an URL
122 function SURFBAR_MEMBER_ADD_URL ($url) {
125 // Do some pre-checks
129 } elseif (!VALIDATE_URL($url)) {
132 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
133 // URL already found in surfbar!
135 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
140 // Register the new URL
141 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid']);
143 // Create list of actions depending on status for the user
144 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
145 // Load all actions in an array for given status
146 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
149 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
153 $width = round(100 / count($actionArray));
155 // "Walk" through all actions and create forms
156 foreach ($actionArray as $actionId=>$action) {
157 // Add form for this action
158 $OUT .= sprintf(" <td align=\"center\" width=\"%d%%\">
159 <form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
160 <input type=\"hidden\" name=\"id\" value=\"%s\" />
161 <input type=\"hidden\" name=\"action\" value=\"%s\" />
162 <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
180 // Do the member form request
181 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
182 global $SURFBAR_CACHE;
184 // By default no action is performed
191 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
192 // Important form elements are missing!
194 } elseif (!isset($URLs[$formData['id']])) {
195 // ID not found in cache
197 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
198 // Action not allowed for current URL status
202 // Create the function name for selected action
203 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper(SQL_ESCAPE($formData['action'])));
205 // Is the function there?
206 if (function_exists($functionName)) {
208 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
210 // Extract URL data for call-back
211 $urlData = array($URLs[$formData['id']]);
213 // Action found so execute it
214 $performed = call_user_func_array($functionName, $urlData);
216 // Log invalid request
217 DEBUG_LOG(__FUNCTION__.": action={$formData['action']},id={$formData['id']},function={$functionName}");
223 // Validate if the requested action can be performed on current URL status
224 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
225 global $SURFBAR_CACHE;
227 // Search for the requested action/status combination in database
228 $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
229 array($action, $status), __FILE__, __LINE__);
231 // Is the entry there?
232 $isValid = (SQL_NUMROWS($result) == 1);
234 // Fetch the new status if found
236 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
240 SQL_FREERESULT($result);
246 // -----------------------------------------------------------------------------
248 // -----------------------------------------------------------------------------
251 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
252 // Create the data array for next function call
254 $urlData['id'] => $urlData
257 // Simply change the status here
258 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
261 // -----------------------------------------------------------------------------
263 // -----------------------------------------------------------------------------
265 // Looks up by an URL
266 function SURFBAR_LOOKUP_BY_URL ($url) {
267 // Now lookup that given URL by itself
268 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
271 return (count($urlArray) > 0);
273 // Load URL data by given search term and column
274 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
277 // By default nothing is found
278 $lastUrlData = array();
280 // Is the column an id number?
281 if (($column == "id") || ($column == "userid")) {
282 // Extra secure input
283 $searchTerm = bigintval($searchTerm);
286 // If the column is "id" there can be only one entry
288 if ($column == "id") {
292 // Look up the record
293 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, status, registered, last_locked, lock_reason
294 FROM "._MYSQL_PREFIX."_surfbar_urls
298 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
300 // Is there at least one record?
301 if (SQL_NUMROWS($result) > 0) {
303 while ($dataRow = SQL_FETCHARRAY($result)) {
304 // Shall we group these results?
305 if ($group == "id") {
306 // Add the row by id as index
307 $lastUrlData[$dataRow['id']] = $dataRow;
310 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
316 SQL_FREERESULT($result);
321 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
322 function SURFBAR_REGISTER_URL ($url, $uid, $paymentId=0, $status="PENDING", $addMode="reg") {
325 // Make sure by the user registered URLs are always pending
326 if ($addMode == "reg") $status = "PENDING";
331 'frametester' => FRAMETESTER($url),
336 // Insert the URL into database
337 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
339 // Translate status, reward and costs
340 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
342 // If in reg-mode we notify admin
343 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
344 // Notify admin even when he as unlocked an email
345 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
349 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
351 // Return the insert id
352 return $content['insert_id'];
354 // Inserts an url by given data array and return the insert id
355 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
357 $uid = bigintval($urlData['uid']);
360 if (empty($uid)) $uid = 0;
362 // Just run the insert query for now
363 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, status) VALUES(%s, '%s', '%s')",
368 ), __FILE__, __LINE__
372 return SQL_INSERTID();
374 // Notify admin(s) with a selected message and content
375 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
376 // Prepare template name
377 $templateName = sprintf("admin_surfbar_%s", $messageType);
379 // Set default subject if following eval() wents wrong
380 $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
383 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
384 strtoupper($messageType)
388 // Send the notification out
389 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
391 // Notify the user about the performed action
392 function SURFBAR_NOTIFY_USER ($messageType, $content) {
393 // Skip notification if userid is zero
394 if ($content['uid'] == 0) {
398 // Prepare template name
399 $templateName = sprintf("member_surfbar_%s", $messageType);
401 // Set default subject if following eval() wents wrong
402 $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
405 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
406 strtoupper($messageType)
411 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
414 return SEND_EMAIL($content['uid'], $subject, $mailText);
416 // Translate the URL status
417 function SURFBAR_TRANSLATE_STATUS ($status) {
418 // Create constant name
419 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
421 // Set default translated status
422 $statusTranslated = "!".$constantName."!";
424 // Generate eval() command
425 if (defined($constantName)) {
426 $eval = "\$statusTranslated = ".$constantName.";";
431 return $statusTranslated;
434 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
437 // Static values are default
438 $reward = $_CONFIG['surfbar_static_reward'];
440 // Do we have static or dynamic?
441 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
442 // "Calculate" dynamic reward
444 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
446 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
454 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
457 // Static costs is default
458 $costs = $_CONFIG['surfbar_static_costs'];
460 // Do we have static or dynamic?
461 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
462 // "Calculate" dynamic costs
464 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
466 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
473 // "Calculate" dynamic add
474 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
475 // Get min/max values
476 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
477 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
479 // "Calculate" dynamic part and return it
480 return mt_rand($min, $max);
482 // Determine right template name
483 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
484 // Default is the frameset
485 $templateName = "surfbar_frameset";
487 // Any frame set? ;-)
488 if (isset($_GET['frame'])) {
489 // Use the frame as a template name part... ;-)
490 $templateName = sprintf("surfbar_frame_%s",
491 SQL_ESCAPE($_GET['frame'])
496 return $templateName;
498 // Check if the "reload lock" of the current user is full, call this function
499 // before you call SURFBAR_CHECK_RELOAD_LOCK().
500 function SURFBAR_CHECK_RELOAD_FULL() {
501 global $SURFBAR_CACHE, $_CONFIG;
506 // Cache static reload lock
507 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
508 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
510 // Do we have dynamic model?
511 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
512 // "Calculate" dynamic lock
513 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
517 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
518 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
520 array($GLOBALS['userid']), __FILE__, __LINE__
524 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
527 if (is_null($SURFBAR_CACHE['user_locks'])) {
528 // Then fix it to zero!
529 $SURFBAR_CACHE['user_locks'] = 0;
533 SQL_FREERESULT($result);
536 $total = SURFBAR_GET_TOTAL_URLS();
538 // Do we have some URLs in lock? Admins can always surf on own URLs!
539 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
540 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
545 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
546 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId="") {
547 // Determine depleted user account
548 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
550 // Is the exlude userid set?
551 if ($excludeUserId !== "") {
553 $UIDs[] = $excludeUserId;
556 // Get amount from database
557 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
558 FROM "._MYSQL_PREFIX."_surfbar_urls
559 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
560 array($status), __FILE__, __LINE__
564 list($cnt) = SQL_FETCHROW($result);
567 SQL_FREERESULT($result);
572 // Check wether the user is allowed to book more URLs
573 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
576 // Is this admin and userid is zero or does the user has some URLs left to book?
577 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
579 // Get total amount of URLs of given status for current user
580 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
583 // Is the user 0 and user is logged in?
584 if (($uid == 0) && (IS_MEMBER())) {
585 // Then use this userid
586 $uid = $GLOBALS['userid'];
587 } elseif ($uid == 0) {
589 return ($_CONFIG['surfbar_max_order'] + 1);
592 // Default is all URLs
595 // Is the status set?
596 if (is_array($status)) {
597 // Only URLs with these status
598 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
599 } elseif (!empty($status)) {
600 // Only URLs with this status
601 $ADD = sprintf(" AND status='%s'", $status);
602 } elseif (is_array($exclude)) {
603 // Exclude URLs with these status
604 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
605 } elseif (!empty($exclude)) {
606 // Exclude URLs with this status
607 $ADD = sprintf(" AND status != '%s'", $exclude);
610 // Get amount from database
611 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
612 FROM "._MYSQL_PREFIX."_surfbar_urls
613 WHERE userid=%s".$ADD."
615 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
619 list($cnt) = SQL_FETCHROW($result);
622 SQL_FREERESULT($result);
627 // Generate a validation code for the given id number
628 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
629 global $_CONFIG, $SURFBAR_CACHE;
631 // @TODO Invalid salt should be refused
632 $SURFBAR_CACHE['salt'] = "INVALID";
634 // Get code length from config
635 $length = $_CONFIG['code_length'];
638 if ($length == 0) $length = 10;
640 // Generate a code until the length matches
642 while (strlen($valCode) != $length) {
645 // Generate random hashed string
646 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
647 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
650 $SURFBAR_CACHE['salt'] = $salt;
651 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
654 // ... and now the validation code
655 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
656 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
659 // Hash it with md5() and salt it with the random string
660 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
662 // Finally encrypt it PGP-like and return it
663 $valHashedCode = generatePassString($hashedCode);
664 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
665 return $valHashedCode;
667 // Check validation code
668 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
669 global $SURFBAR_CACHE;
672 $urlId = bigintval($urlId);
674 // Now generate the code again
675 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
677 // Return result of checking hashes and salts
678 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
679 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
680 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
682 // Lockdown the userid/id combination (reload lock)
683 function SURFBAR_LOCKDOWN_ID ($urlId) {
684 //* //DEBUG: */ print "LOCK!");
685 ///* //DEBUG: */ return;
686 // Just add it to the database
687 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
688 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
690 // Remove the salt from database
691 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
692 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
694 // Pay points to the user and remove it from the sender
695 function SURFBAR_PAY_POINTS ($urlId) {
696 // Remove it from the URL owner
697 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
698 if (SURFBAR_GET_USERID() > 0) {
699 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
702 // Book it to the user
703 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
704 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
706 // Updates the statistics of current URL/userid
707 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
710 // Update views_total
711 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
712 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
714 // Update the stats entry
715 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
716 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
718 // Was that update okay?
719 if (SQL_AFFECTEDROWS() == 0) {
720 // No, then insert entry
721 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
722 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
725 // Update total/daily/weekly/monthly counter
726 $_CONFIG['surfbar_total_counter']++;
727 $_CONFIG['surfbar_daily_counter']++;
728 $_CONFIG['surfbar_weekly_counter']++;
729 $_CONFIG['surfbar_monthly_counter']++;
731 // Update config as well
732 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
734 // Update the salt for validation and statistics
735 function SURFBAR_UPDATE_SALT_STATS () {
736 // Update statistics record
737 SURFBAR_UPDATE_INSERT_STATS_RECORD();
739 // Simply store the salt from cache away in database...
740 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
741 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
744 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
747 if (SQL_AFFECTEDROWS() == 0) {
748 // Insert missing entry!
749 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
750 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
754 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
756 // Return if the update was okay
757 return (SQL_AFFECTEDROWS() == 1);
759 // Check if the reload lock is active for given id
760 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
761 //DEBUG_LOG(__FUNCTION__.":id={$urlId}");
763 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
764 FROM "._MYSQL_PREFIX."_surfbar_locks
765 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
766 ORDER BY last_surfed ASC
768 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
772 list($cnt) = SQL_FETCHROW($result);
775 SQL_FREERESULT($result);
778 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
781 // Determine which user hash no more points left
782 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
786 // Do we have a current user id?
788 // Then add this as well
789 $UIDs[] = $GLOBALS['userid'];
791 // Get all userid except logged in one
792 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
793 WHERE userid NOT IN (%s,0) AND status='ACTIVE'
795 ORDER BY userid ASC",
796 array($GLOBALS['userid']), __FILE__, __LINE__);
799 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
800 WHERE status='ACTIVE'
802 ORDER BY userid ASC", __FILE__, __LINE__);
806 while (list($uid) = SQL_FETCHROW($result)) {
808 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
809 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
811 // Shall we add this to ignore?
814 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
820 SQL_FREERESULT($result);
823 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
828 // Determine how many users are Online in surfbar
829 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
832 // Count all users in surfbar modue and return the value
833 $result = SQL_QUERY_ESC("SELECT id
834 FROM "._MYSQL_PREFIX."_surfbar_stats
835 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
837 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
840 $cnt = SQL_NUMROWS($result);
843 SQL_FREERESULT($result);
848 // Determine waiting time for one URL
849 function SURFBAR_DETERMINE_WAIT_TIME () {
852 // Static time is default
853 $time = $_CONFIG['surfbar_static_time'];
855 // Which payment model do we have?
856 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
857 // "Calculate" dynamic time
858 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
864 // Changes the status of an URL from given to other
865 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
868 // Get URL data for status comparison if missing
869 if (count($data) == 0) {
870 $data = SURFBAR_GET_URL_DATA($urlId);
873 // Is the status like prevStatus is saying?
874 if ($data[$urlId]['status'] != $prevStatus) {
875 // No, then abort here
880 // Update the status now
881 // ---------------------- Commented out for debugging member actions! -----------------------
882 //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
883 // array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
884 // ---------------------- Commented out for debugging member actions! -----------------------
887 if (SQL_AFFECTEDROWS() != 1) {
888 // No, something went wrong
892 // Prepare content for notification routines
893 $data[$urlId]['uid'] = $data[$urlId]['userid'];
894 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
895 $data[$urlId]['reward'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
896 $data[$urlId]['costs'] = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
897 $data[$urlId]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
898 $data[$urlId]['registered'] = MAKE_DATETIME($data[$urlId]['registered'], "2");
899 $newStatus = strtolower($newStatus);
901 // Send admin notification
902 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
904 // Send user notification
905 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
910 // Calculate minimum value for dynamic payment model
911 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
914 // Addon is zero by default
918 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
921 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
924 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
927 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
930 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
932 // Get user's total URLs
933 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
936 if ($totalUrls > 0) {
937 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
939 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
945 // Calculate maximum value for dynamic payment model
946 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
949 // Addon is zero by default
956 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
959 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
962 $addon += abs($max * $percent * $totalUsers);
965 $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
968 $addon += abs($max * $percent * $totalUrls);
973 // Calculate dynamic lock
974 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
977 // Default lock is 30 seconds
981 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
984 $addon = abs(log($onlineUsers / $addon + 1));
989 // "Getter" for lock ids array
990 function SURFBAR_GET_LOCK_IDS () {
991 // Prepare some arrays
996 // Get all id from locks within the timestamp
997 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
999 "._MYSQL_PREFIX."_surfbar_locks
1003 id ASC", array($GLOBALS['userid']),
1004 __FILE__, __LINE__);
1007 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1009 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
1011 // Skip entries that are too old
1012 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1014 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
1016 // Add only if missing or bigger
1017 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1019 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
1027 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
1029 // Ignore these old entries!
1037 SQL_FREERESULT($result);
1042 // "Getter" for maximum random number
1043 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1045 // Count max availabe entries
1046 $result = SQL_QUERY("SELECT sbu.id AS cnt
1047 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1048 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1049 ON sbu.id=sbs.url_id
1050 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1052 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='ACTIVE'".$ADD."
1053 GROUP BY sbu.id", __FILE__, __LINE__);
1056 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1059 $maxRand = SQL_NUMROWS($result);
1062 SQL_FREERESULT($result);
1067 // Load all URLs of the current user and return it as an array
1068 function SURFBAR_GET_USER_URLS () {
1073 $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
1074 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1075 WHERE u.userid=%s AND u.status != 'DELETED'
1077 array($GLOBALS['userid']), __FILE__, __LINE__);
1079 // Are there entries?
1080 if (SQL_NUMROWS($result) > 0) {
1082 while ($row = SQL_FETCHARRAY($result)) {
1084 $URLs[$row['id']] = $row;
1089 SQL_FREERESULT($result);
1094 // "Getter" for member action array for given status
1095 function SURFBAR_GET_ACTION_ARRAY ($status) {
1097 $returnArray = array();
1099 // Get all assigned actions
1100 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1101 array($status), __FILE__, __LINE__);
1103 // Some entries there?
1104 if (SQL_NUMROWS($result) > 0) {
1106 while (list($action) = SQL_FETCHROW($result)) {
1107 $returnArray[] = $action;
1112 SQL_FREERESULT($result);
1115 return $returnArray;
1117 // Determine next id for surfbar or get data for given id, always call this before you call other
1118 // getters below this function!!!
1119 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1120 global $SURFBAR_CACHE, $_CONFIG;
1122 // Default is no id and no random number
1128 // Get array with lock ids
1129 $USE = SURFBAR_GET_LOCK_IDS();
1131 // Shall we add some URL ids to ignore?
1133 if (count($USE) > 0) {
1135 $ADD = " AND sbu.id NOT IN (";
1136 foreach ($USE as $url_id => $lid) {
1138 $ADD .= $url_id.",";
1141 // Add closing bracket
1142 $ADD = substr($ADD, 0, -1) . ")";
1145 // Determine depleted user account
1146 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1148 // Get maximum randomness factor
1149 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
1151 // If more than one URL can be called generate the random number!
1153 // Generate random number
1154 $randNum = mt_rand(0, ($maxRand - 1));
1157 // And query the database
1158 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
1159 $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
1160 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1161 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1162 ON sbu.id=sbs.url_id
1163 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1165 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='ACTIVE'".$ADD."
1167 ORDER BY l.last_surfed ASC, sbu.id ASC
1169 array($randNum), __FILE__, __LINE__
1172 // Get data from specified id number
1173 $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
1174 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1175 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1176 ON sbu.id=sbs.url_id
1177 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1179 WHERE sbu.userid != %s AND sbu.status='ACTIVE' AND sbu.id=%s
1181 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1185 // Is there an id number?
1186 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1187 if (SQL_NUMROWS($result) == 1) {
1189 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1190 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1191 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1193 // Determine waiting time
1194 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1196 // Is the last salt there?
1197 if (is_null($SURFBAR_CACHE['last_salt'])) {
1198 // Then repair it wit the static!
1199 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1200 $SURFBAR_CACHE['last_salt'] = "";
1203 // Fix missing last_surfed
1204 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1206 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1207 $SURFBAR_CACHE['last_surfed'] = 0;
1210 // Get base/fixed reward and costs
1211 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1212 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1213 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1215 // Only in dynamic model add the dynamic bonus!
1216 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1217 // Calculate dynamic reward/costs and add it
1218 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1219 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1220 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1224 $nextId = SURFBAR_GET_ID();
1228 SQL_FREERESULT($result);
1231 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1234 // -----------------------------------------------------------------------------
1235 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1236 // $SURFBAR_CACHE ARRAY!
1237 // -----------------------------------------------------------------------------
1238 // Private getter for data elements
1239 function SURFBAR_GET_DATA ($element) {
1240 global $SURFBAR_CACHE;
1241 //DEBUG_LOG(__FUNCTION__.":element={$element}");
1246 // Is the entry there?
1247 if (isset($SURFBAR_CACHE[$element])) {
1249 $data = $SURFBAR_CACHE[$element];
1250 } else { // END - if
1252 print_r($SURFBAR_CACHE);
1253 debug_print_backtrace();
1258 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1261 // Getter for reward from cache
1262 function SURFBAR_GET_REWARD () {
1263 // Get data element and return its contents
1264 return SURFBAR_GET_DATA('reward');
1266 // Getter for costs from cache
1267 function SURFBAR_GET_COSTS () {
1268 // Get data element and return its contents
1269 return SURFBAR_GET_DATA('costs');
1271 // Getter for URL from cache
1272 function SURFBAR_GET_URL () {
1273 // Get data element and return its contents
1274 return SURFBAR_GET_DATA('url');
1276 // Getter for salt from cache
1277 function SURFBAR_GET_SALT () {
1278 // Get data element and return its contents
1279 return SURFBAR_GET_DATA('salt');
1281 // Getter for id from cache
1282 function SURFBAR_GET_ID () {
1283 // Get data element and return its contents
1284 return SURFBAR_GET_DATA('id');
1286 // Getter for userid from cache
1287 function SURFBAR_GET_USERID () {
1288 // Get data element and return its contents
1289 return SURFBAR_GET_DATA('userid');
1291 // Getter for user reload locks
1292 function SURFBAR_GET_USER_RELOAD_LOCK () {
1293 // Get data element and return its contents
1294 return SURFBAR_GET_DATA('user_locks');
1296 // Getter for reload time
1297 function SURFBAR_GET_RELOAD_TIME () {
1298 // Get data element and return its contents
1299 return SURFBAR_GET_DATA('time');