2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/31/2008 *
4 * =============== Last change: 08/31/2008 *
6 * -------------------------------------------------------------------- *
7 * File : surfbar_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for surfbar *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer die Surfbar *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
40 // -----------------------------------------------------------------------------
42 // -----------------------------------------------------------------------------
44 // Admin has added an URL with given user id and so on
45 function SURFBAR_ADMIN_ADD_URL ($url) {
50 } elseif (!VALIDATE_URL($url)) {
53 } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
54 // URL already found in surfbar!
56 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
61 // Do we have fixed or dynamic payment model?
62 $reward = SURFBAR_DETERMINE_REWARD();
63 $costs = SURFBAR_DETERMINE_COSTS();
65 // Register the new URL
66 return SURFBAR_REGISTER_URL($url, "0", $reward, $costs, "0", "CONFIRMED", "unlock");
68 // Admin function for unlocking URLs
69 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
70 // Is this an admin or invalid array?
72 // Not admin or invalid IDs array
74 } elseif (!is_array($IDs)) {
77 } elseif (count($IDs) == 0) {
82 // Set to true to make AND expression valid if first URL got unlocked
85 // Update the status for all ids
86 foreach ($IDs as $id => $dummy) {
87 // Test all ids through (ignores failed)
88 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "CONFIRMED")));
91 // Return total status
95 // -----------------------------------------------------------------------------
97 // -----------------------------------------------------------------------------
99 // Member has added an URL
100 function SURFBAR_MEMBER_ADD_URL ($url) {
103 // Do some pre-checks
107 } elseif (!VALIDATE_URL($url)) {
110 } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
111 // URL already found in surfbar!
113 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
118 // Do we have fixed or dynamic payment model?
119 $reward = SURFBAR_DETERMINE_REWARD();
120 $costs = SURFBAR_DETERMINE_COSTS();
122 // Register the new URL
123 return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], $reward, $costs);
125 // -----------------------------------------------------------------------------
127 // -----------------------------------------------------------------------------
129 // Looks up by an URL
130 function SURFBAR_LOOKUP_BY_URL ($url) {
131 // Now lookup that given URL by itself
132 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
135 return (count($urlArray) > 0);
137 // Load URL data by given search term and column
138 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
141 // By default nothing is found
142 $lastUrlData = array();
144 // Is the column an id number?
145 if (($column == "id") || ($column == "userid")) {
146 // Extra secure input
147 $searchTerm = bigintval($searchTerm);
150 // If the column is "id" there can be only one entry
152 if ($column == "id") {
156 // Look up the record
157 $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
158 FROM "._MYSQL_PREFIX."_surfbar_urls
162 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
164 // Is there at least one record?
165 if (SQL_NUMROWS($result) > 0) {
167 while ($dataRow = SQL_FETCHARRAY($result)) {
168 // Shall we group these results?
169 if ($group == "id") {
170 // Add the row by id as index
171 $lastUrlData[$dataRow['id']] = $dataRow;
174 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
180 SQL_FREERESULT($result);
185 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
186 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $costs, $paymentId=0, $status="PENDING", $addMode="reg") {
189 // Make sure by the user registered URLs are always pending
190 if ($addMode == "reg") $status = "PENDING";
195 'frametester' => FRAMETESTER($url),
202 // Insert the URL into database
203 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
205 // Translate status, reward and costs
206 $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
207 $content['reward'] = TRANSLATE_COMMA($content['reward']);
208 $content['costs'] = TRANSLATE_COMMA($content['costs']);
210 // If in reg-mode we notify admin
211 if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
212 // Notify admin even when he as unlocked an email
213 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
217 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
219 // Return the insert id
220 return $content['insert_id'];
222 // Inserts an url by given data array and return the insert id
223 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
225 $uid = bigintval($urlData['uid']);
228 if (empty($uid)) $uid = 0;
230 // Just run the insert query for now
231 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, status) VALUES('%s', '%s', %s, %s, '%s')",
235 (float)$urlData['reward'],
236 (float)$urlData['costs'],
238 ), __FILE__, __LINE__
242 return SQL_INSERTID();
244 // Notify admin(s) with a selected message and content
245 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
246 // Prepare template name
247 $templateName = sprintf("admin_surfbar_%s", $messageType);
250 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
251 strtoupper($messageType)
255 // Send the notification out
256 return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
258 // Notify the user about the performed action
259 function SURFBAR_NOTIFY_USER ($messageType, $content) {
260 // Skip notification if userid is zero
261 if ($content['uid'] == 0) {
265 // Prepare template name
266 $templateName = sprintf("member_surfbar_%s", $messageType);
269 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
270 strtoupper($messageType)
275 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
278 return SEND_EMAIL($content['uid'], $subject, $mailText);
280 // Translate the URL status
281 function SURFBAR_TRANSLATE_STATUS ($status) {
282 // Create constant name
283 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
285 // Set default translated status
286 $statusTranslated = "!".$constantName."!";
288 // Generate eval() command
289 if (defined($constantName)) {
290 $eval = "\$statusTranslated = ".$constantName.";";
295 return $statusTranslated;
298 function SURFBAR_DETERMINE_REWARD () {
301 // Static values are default
302 $reward = $_CONFIG['surfbar_static_reward'];
304 // Do we have static or dynamic?
305 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
306 // "Calculate" dynamic reward
307 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
313 // "Calculate" dynamic add
314 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
315 // Get min/max values
316 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
317 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
319 // "Calculate" dynamic part and return it
320 return mt_rand($min, $max);
323 function SURFBAR_DETERMINE_COSTS () {
326 // Static costs is default
327 $costs = $_CONFIG['surfbar_static_costs'];
329 // Do we have static or dynamic?
330 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
331 // "Calculate" dynamic costs
332 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
338 // Determine right template name
339 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
340 // Default is the frameset
341 $templateName = "surfbar_frameset";
343 // Any frame set? ;-)
344 if (isset($_GET['frame'])) {
345 // Use the frame as a template name part... ;-)
346 $templateName = sprintf("surfbar_frame_%s",
347 SQL_ESCAPE($_GET['frame'])
352 return $templateName;
354 // Check if the "reload lock" of the current user is full, call this function
355 // before you call SURFBAR_CHECK_RELOAD_LOCK().
356 function SURFBAR_CHECK_RELOAD_FULL() {
357 global $SURFBAR_CACHE, $_CONFIG;
362 // Cache static reload lock
363 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
364 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
366 // Do we have dynamic model?
367 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
368 // "Calculate" dynamic lock
369 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
373 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
374 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
376 array($GLOBALS['userid']), __FILE__, __LINE__
380 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
383 if (is_null($SURFBAR_CACHE['user_locks'])) {
384 // Then fix it to zero!
385 $SURFBAR_CACHE['user_locks'] = 0;
389 SQL_FREERESULT($result);
392 $total = SURFBAR_GET_TOTAL_URLS();
394 // Do we have some URLs in lock? Admins can always surf on own URLs!
395 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
396 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
401 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
402 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED", $excludeUserId="") {
403 // Determine depleted user account
404 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
406 // Is the exlude userid set?
407 if ($excludeUserId !== "") {
409 $UIDs[] = $excludeUserId;
412 // Get amount from database
413 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
414 FROM "._MYSQL_PREFIX."_surfbar_urls
415 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
416 array($status), __FILE__, __LINE__
420 list($cnt) = SQL_FETCHROW($result);
423 SQL_FREERESULT($result);
428 // Check wether the user is allowed to book more URLs
429 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
432 // Is this admin and userid is zero or does the user has some URLs left to book?
433 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
435 // Get total amount of URLs of given status for current user
436 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
439 // Is the user 0 and user is logged in?
440 if (($uid == 0) && (IS_MEMBER())) {
441 // Then use this userid
442 $uid = $GLOBALS['userid'];
443 } elseif ($uid == 0) {
445 return ($_CONFIG['surfbar_max_order'] + 1);
448 // Default is all URLs
451 // Is the status set?
452 if (is_array($status)) {
453 // Only URLs with these status
454 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
455 } elseif (!empty($status)) {
456 // Only URLs with this status
457 $ADD = sprintf(" AND status='%s'", $status);
458 } elseif (is_array($exclude)) {
459 // Exclude URLs with these status
460 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
461 } elseif (!empty($exclude)) {
462 // Exclude URLs with this status
463 $ADD = sprintf(" AND status != '%s'", $exclude);
466 // Get amount from database
467 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
468 FROM "._MYSQL_PREFIX."_surfbar_urls
469 WHERE userid=%s".$ADD."
471 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
475 list($cnt) = SQL_FETCHROW($result);
478 SQL_FREERESULT($result);
483 // Generate a validation code for the given id number
484 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
485 global $_CONFIG, $SURFBAR_CACHE;
487 // @TODO Invalid salt should be refused
488 $SURFBAR_CACHE['salt'] = "INVALID";
490 // Get code length from config
491 $length = $_CONFIG['code_length'];
494 if ($length == 0) $length = 10;
496 // Generate a code until the length matches
498 while (strlen($valCode) != $length) {
501 // Generate random hashed string
502 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
503 //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
506 $SURFBAR_CACHE['salt'] = $salt;
507 //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
510 // ... and now the validation code
511 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
512 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
515 // Hash it with md5() and salt it with the random string
516 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
518 // Finally encrypt it PGP-like and return it
519 $valHashedCode = generatePassString($hashedCode);
520 //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
521 return $valHashedCode;
523 // Check validation code
524 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
525 global $SURFBAR_CACHE;
528 $id = bigintval($id);
530 // Now generate the code again
531 $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
533 // Return result of checking hashes and salts
534 //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
535 //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
536 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
538 // Lockdown the userid/id combination (reload lock)
539 function SURFBAR_LOCKDOWN_ID ($id) {
540 //* //DEBUG: */ print "LOCK!");
541 ///* //DEBUG: */ return;
542 // Just add it to the database
543 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
544 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
546 // Remove the salt from database
547 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
548 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
550 // Pay points to the user and remove it from the sender
551 function SURFBAR_PAY_POINTS ($id) {
552 // Remove it from the URL owner
553 //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
554 if (SURFBAR_GET_USERID() > 0) {
555 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
558 // Book it to the user
559 //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
560 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
562 // Updates the statistics of current URL/userid
563 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
566 // Update views_total
567 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
568 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
570 // Update the stats entry
571 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
572 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
574 // Was that update okay?
575 if (SQL_AFFECTEDROWS() == 0) {
576 // No, then insert entry
577 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
578 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
581 // Update total/daily/weekly/monthly counter
582 $_CONFIG['surfbar_total_counter']++;
583 $_CONFIG['surfbar_daily_counter']++;
584 $_CONFIG['surfbar_weekly_counter']++;
585 $_CONFIG['surfbar_monthly_counter']++;
587 // Update config as well
588 UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
590 // Update the salt for validation and statistics
591 function SURFBAR_UPDATE_SALT_STATS () {
592 // Update statistics record
593 SURFBAR_UPDATE_INSERT_STATS_RECORD();
595 // Simply store the salt from cache away in database...
596 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
597 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
600 //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
603 if (SQL_AFFECTEDROWS() == 0) {
604 // Insert missing entry!
605 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
606 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
610 //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
612 // Return if the update was okay
613 return (SQL_AFFECTEDROWS() == 1);
615 // Check if the reload lock is active for given id
616 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
617 //DEBUG_LOG(__FUNCTION__.":id={$id}");
619 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
620 FROM "._MYSQL_PREFIX."_surfbar_locks
621 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
622 ORDER BY last_surfed ASC
624 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
628 list($cnt) = SQL_FETCHROW($result);
631 SQL_FREERESULT($result);
634 //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
637 // Determine which user hash no more points left
638 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
642 // Do we have a current user id?
644 // Then add this as well
645 $UIDs[] = $GLOBALS['userid'];
647 // Get all userid except logged in one
648 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
649 WHERE userid NOT IN (%s,0) AND status='CONFIRMED'
651 ORDER BY userid ASC",
652 array($GLOBALS['userid']), __FILE__, __LINE__);
655 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
656 WHERE status='CONFIRMED'
658 ORDER BY userid ASC", __FILE__, __LINE__);
662 while (list($uid) = SQL_FETCHROW($result)) {
664 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
665 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
667 // Shall we add this to ignore?
670 //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
676 SQL_FREERESULT($result);
679 //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
684 // Determine how many users are Online in surfbar
685 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
688 // Count all users in surfbar modue and return the value
689 $result = SQL_QUERY_ESC("SELECT id
690 FROM "._MYSQL_PREFIX."_surfbar_stats
691 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
693 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
696 $cnt = SQL_NUMROWS($result);
699 SQL_FREERESULT($result);
704 // Determine waiting time for one URL
705 function SURFBAR_DETERMINE_WAIT_TIME () {
708 // Static time is default
709 $time = $_CONFIG['surfbar_static_time'];
711 // Which payment model do we have?
712 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
713 // "Calculate" dynamic time
714 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
720 // Changes the status of an URL from given to other
721 function SURFBAR_CHANGE_STATUS ($id, $prevStatus, $newStatus) {
722 // Get URL data for status comparison
723 $data = SURFBAR_GET_URL_DATA($id);
725 // Is the status like prevStatus is saying?
726 if ($data[$id]['status'] != $prevStatus) {
727 // No, then abort here
731 // Update the status now
732 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
733 array($newStatus, bigintval($id)), __FILE__, __LINE__);
736 if (SQL_AFFECTEDROWS() != 1) {
737 // No, something went wrong
741 // Prepare content for notification routines
742 $data[$id]['uid'] = $data[$id]['userid'];
743 $data[$id]['frametester'] = FRAMETESTER($data[$id]['url']);
744 $data[$id]['reward'] = TRANSLATE_COMMA($data[$id]['reward']);
745 $data[$id]['costs'] = TRANSLATE_COMMA($data[$id]['costs']);
746 $data[$id]['status'] = SURFBAR_TRANSLATE_STATUS($newStatus);
747 $data[$id]['registered'] = MAKE_DATETIME($data[$id]['registered'], "2");
748 $newStatus = strtolower($newStatus);
750 // Send admin notification
751 SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$id]);
753 // Send user notification
754 SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$id]);
759 // Calculate minimum value for dynamic payment model
760 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
763 // Addon is zero by default
767 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
770 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
773 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
776 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
779 $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
781 // Get user's total URLs
782 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "CONFIRMED");
785 if ($totalUrls > 0) {
786 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
788 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
794 // Calculate maximum value for dynamic payment model
795 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
798 // Addon is zero by default
805 $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
808 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
811 $addon += abs($max * $percent * $totalUsers);
814 $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
817 $addon += abs($max * $percent * $totalUrls);
822 // Calculate dynamic lock
823 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
826 // Default lock is 30 seconds
830 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
833 $addon = abs(log($onlineUsers / $addon + 1));
838 // "Getter" for lock ids array
839 function SURFBAR_GET_LOCK_IDS () {
840 // Prepare some arrays
845 // Get all id from locks within the timestamp
846 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
848 "._MYSQL_PREFIX."_surfbar_locks
852 id ASC", array($GLOBALS['userid']),
856 while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
858 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
860 // Skip entries that are too old
861 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
863 //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
865 // Add only if missing or bigger
866 if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
868 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
876 //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
878 // Ignore these old entries!
886 SQL_FREERESULT($result);
891 // "Getter" for maximum random number
892 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
894 // Count max availabe entries
895 $result = SQL_QUERY("SELECT sbu.id AS cnt
896 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
897 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
899 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
901 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
902 GROUP BY sbu.id", __FILE__, __LINE__);
905 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
908 $maxRand = SQL_NUMROWS($result);
911 SQL_FREERESULT($result);
916 // Load all URLs of the current user and return it as an array
917 function SURFBAR_GET_USER_URLS () {
922 $result = SQL_QUERY_ESC("SELECT u.id, u.url, u.views_total, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
923 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
924 WHERE u.userid=%s AND u.status != 'DELETED'
926 array($GLOBALS['userid']), __FILE__, __LINE__);
928 // Are there entries?
929 if (SQL_NUMROWS($result) > 0) {
931 while ($row = SQL_FETCHARRAY($result)) {
933 $URLs[$row['id']] = $row;
938 SQL_FREERESULT($result);
943 // "Getter" for member action array for given status
944 function SURFBAR_GET_ACTION_ARRAY ($status) {
946 $returnArray = array();
948 // Get all assigned actions
949 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
950 array($status), __FILE__, __LINE__);
952 // Some entries there?
953 if (SQL_NUMROWS($result) > 0) {
955 while (list($action) = SQL_FETCHROW($result)) {
956 $returnArray[] = $action;
961 SQL_FREERESULT($result);
966 // Create list of actions depending on status for the user
967 function SURFBAR_MEMBER_ACTIONS ($id, $status) {
968 // Load all actions in an array for given status
969 $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
974 // "Walk" through all actions and create forms
975 foreach ($actionArray as $action) {
976 // Add form for this action
977 $OUT .= sprintf("<form action=\"".URL."/modules.php?module=login&what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
978 <input type=\"submit\" name=\"%s\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
988 // Determine next id for surfbar or get data for given id, always call this before you call other
989 // getters below this function!!!
990 function SURFBAR_DETERMINE_NEXT_ID ($id = 0) {
991 global $SURFBAR_CACHE, $_CONFIG;
993 // Default is no id and no random number
999 // Get array with lock ids
1000 $USE = SURFBAR_GET_LOCK_IDS();
1002 // Shall we add some URL ids to ignore?
1004 if (count($USE) > 0) {
1006 $ADD = " AND sbu.id NOT IN (";
1007 foreach ($USE as $url_id => $lid) {
1009 $ADD .= $url_id.",";
1012 // Add closing bracket
1013 $ADD = substr($ADD, 0, -1) . ")";
1016 // Determine depleted user account
1017 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1019 // Get maximum randomness factor
1020 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
1022 // If more than one URL can be called generate the random number!
1024 // Generate random number
1025 $randNum = mt_rand(0, ($maxRand - 1));
1028 // And query the database
1029 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
1030 $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
1031 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1032 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1033 ON sbu.id=sbs.url_id
1034 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1036 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
1038 ORDER BY l.last_surfed ASC, sbu.id ASC
1040 array($randNum), __FILE__, __LINE__
1043 // Get data from specified id number
1044 $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
1045 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1046 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1047 ON sbu.id=sbs.url_id
1048 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1050 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
1052 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
1056 // Is there an id number?
1057 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1058 if (SQL_NUMROWS($result) == 1) {
1060 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1061 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1062 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1064 // Determine waiting time
1065 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1067 // Is the last salt there?
1068 if (is_null($SURFBAR_CACHE['last_salt'])) {
1069 // Then repair it wit the static!
1070 //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1071 $SURFBAR_CACHE['last_salt'] = "";
1074 // Fix missing last_surfed
1075 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1077 //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1078 $SURFBAR_CACHE['last_surfed'] = 0;
1081 // Get base/fixed reward and costs
1082 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1083 $SURFBAR_CACHE['costs'] = SURFBAR_DETERMINE_COSTS();
1084 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1086 // Only in dynamic model add the dynamic bonus!
1087 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1088 // Calculate dynamic reward/costs and add it
1089 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1090 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1091 //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1095 $nextId = SURFBAR_GET_ID();
1099 SQL_FREERESULT($result);
1102 //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1105 // -----------------------------------------------------------------------------
1106 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1107 // $SURFBAR_CACHE ARRAY!
1108 // -----------------------------------------------------------------------------
1109 // Private getter for data elements
1110 function SURFBAR_GET_DATA ($element) {
1111 global $SURFBAR_CACHE;
1112 //DEBUG_LOG(__FUNCTION__.":element={$element}");
1117 // Is the entry there?
1118 if (isset($SURFBAR_CACHE[$element])) {
1120 $data = $SURFBAR_CACHE[$element];
1121 } else { // END - if
1123 print_r($SURFBAR_CACHE);
1124 debug_print_backtrace();
1129 //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1132 // Getter for reward from cache
1133 function SURFBAR_GET_REWARD () {
1134 // Get data element and return its contents
1135 return SURFBAR_GET_DATA('reward');
1137 // Getter for costs from cache
1138 function SURFBAR_GET_COSTS () {
1139 // Get data element and return its contents
1140 return SURFBAR_GET_DATA('costs');
1142 // Getter for URL from cache
1143 function SURFBAR_GET_URL () {
1144 // Get data element and return its contents
1145 return SURFBAR_GET_DATA('url');
1147 // Getter for salt from cache
1148 function SURFBAR_GET_SALT () {
1149 // Get data element and return its contents
1150 return SURFBAR_GET_DATA('salt');
1152 // Getter for id from cache
1153 function SURFBAR_GET_ID () {
1154 // Get data element and return its contents
1155 return SURFBAR_GET_DATA('id');
1157 // Getter for userid from cache
1158 function SURFBAR_GET_USERID () {
1159 // Get data element and return its contents
1160 return SURFBAR_GET_DATA('userid');
1162 // Getter for user reload locks
1163 function SURFBAR_GET_USER_RELOAD_LOCK () {
1164 // Get data element and return its contents
1165 return SURFBAR_GET_DATA('user_locks');
1167 // Getter for reload time
1168 function SURFBAR_GET_RELOAD_TIME () {
1169 // Get data element and return its contents
1170 return SURFBAR_GET_DATA('time');