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 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
45 // -----------------------------------------------------------------------------
47 // -----------------------------------------------------------------------------
49 // Admin has added an URL with given user id and so on
50 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
54 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
56 } elseif (!isUrlValid($url)) {
58 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid URL.", $url, $limit, $reload));
60 } elseif (SURFBAR_LOOKUP_BY_URL($url, '0')) {
61 // URL already found in surfbar!
62 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Already added.", $url, $limit, $reload));
64 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
66 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : No more URLs allowed.", $url, $limit, $reload));
68 } elseif ('' . ($limit + 0) . '' != '' . $limit . '') {
69 // Invalid limit entered
70 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid limit entered.", $url, $limit, $reload));
72 } elseif ('' . ($reload + 0) . '' != '' . $reload . '') {
73 // Invalid amount entered
74 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid reload entered.", $url, $limit, $reload));
78 // Register the new URL
79 return SURFBAR_REGISTER_URL($url, '0', 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
82 // Admin unlocked an email so we can migrate the URL
83 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
88 } elseif (!isUrlValid($url)) {
91 } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
92 // URL already found in surfbar!
94 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
99 // Register the new URL
100 return SURFBAR_REGISTER_URL($url, $uid, 'MIGRATED', 'migrate');
103 // Admin function for unlocking URLs
104 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
105 // Is this an admin or invalid array?
107 // Not admin or invalid IDs array
109 } elseif (!is_array($IDs)) {
112 } elseif (count($IDs) == 0) {
117 // Set to true to make AND expression valid if first URL got unlocked
120 // Update the status for all ids
121 foreach ($IDs as $id => $dummy) {
122 // Test all ids through (ignores failed)
123 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
126 // Return total status
130 // Admin function for rejecting URLs
131 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
132 // Is this an admin or invalid array?
134 // Not admin or invalid IDs array
136 } elseif (!is_array($IDs)) {
139 } elseif (count($IDs) == 0) {
144 // Set to true to make AND expression valid if first URL got unlocked
147 // Update the status for all ids
148 foreach ($IDs as $id => $dummy) {
149 // Test all ids through (ignores failed)
150 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
153 // Return total status
158 // -----------------------------------------------------------------------------
160 // -----------------------------------------------------------------------------
162 // Member has added an URL
163 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
164 // Do some pre-checks
168 } elseif ((!isUrlValid($url)) && (!IS_ADMIN())) {
171 } elseif (SURFBAR_LOOKUP_BY_URL($url, getUserId())) {
172 // URL already found in surfbar!
174 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getUserId())) {
177 } elseif (''.($limit + 0).'' != ''.$limit.'') {
178 // Invalid amount entered
182 // Register the new URL
183 return SURFBAR_REGISTER_URL($url, getUserId(), 'PENDING', 'reg', array('limit' => $limit));
186 // Create list of actions depending on status for the user
187 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
188 // Load all actions in an array for given status
189 $actionArray = SURFBAR_getModeAction_ARRAY($status);
192 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
196 $width = round(100 / count($actionArray));
198 // "Walk" through all actions and create forms
199 foreach ($actionArray as $actionId => $action) {
200 // Add form for this action
201 $OUT .= LOAD_TEMPLATE('member_surfbar_list_form', true, array(
203 'id' => bigintval($urlId),
204 'action' => strtolower($action),
205 'title' => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE--}',
206 'submit' => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT--}',
218 // Do the member form request
219 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
220 // By default no action is performed
227 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
228 // Important form elements are missing!
230 } elseif (!isset($URLs[$formData['id']])) {
231 // ID not found in cache
233 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
234 // Action not allowed for current URL status
239 $action = SQL_ESCAPE(htmlentities(strip_tags($formData['action']), ENT_QUOTES));
242 if ($action != $formData['action']) {
243 // Invalid data in action found
247 // Create the function name for selected action
248 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
250 // Is the function there?
251 if (function_exists($functionName)) {
253 $URLs[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
255 // Extract URL data for call-back
256 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
258 // Action found so execute it
259 $performed = call_user_func_array($functionName, $urlData);
261 // Log invalid request
262 DEBUG_LOG(__FUNCTION__, __LINE__, "action={$formData['action']},id={$formData['id']},function={$functionName}");
263 addFatalMessage(__FUNCTION__, __LINE__, "Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
270 // Validate if the requested action can be performed on current URL status
271 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
272 // Search for the requested action/status combination in database
273 $result = SQL_QUERY_ESC("SELECT new_status FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
274 array($action, $status), __FUNCTION__, __LINE__);
276 // Is the entry there?
277 $isValid = (SQL_NUMROWS($result) == 1);
279 // Fetch the new status if found
282 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
286 SQL_FREERESULT($result);
293 // -----------------------------------------------------------------------------
295 // -----------------------------------------------------------------------------
297 // Retreat a booked URL
298 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
299 // Create the data array for next function call
301 $urlData['id'] => $urlData
304 // Simply change the status here
305 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
308 // Book an URL now (from migration)
309 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
310 // Create the data array for next function call
312 $urlData['id'] => $urlData
315 // Simply change the status here
316 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
319 // Show edit form or do the changes
320 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
321 // Is the "execute" flag there?
322 if (isset($urlData['edit']['execute'])) {
323 // Execute the changes
324 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
328 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
331 // Show delete form or do the changes
332 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
333 // Is the "execute" flag there?
334 if (isset($urlData['delete']['execute'])) {
335 // Execute the changes
336 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
340 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
343 // Pause active banner
344 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
345 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
348 // Unpause stopped banner
349 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
350 // Fix missing entry for template
351 $urlData['edit'] = $urlData['unpause'];
352 $urlData['edit']['url'] = $urlData['url'];
353 $urlData['edit']['limit'] = $urlData['views_max'];
355 // Return status change
356 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
359 // Resubmit locked URL
360 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
361 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
364 // Display selected "action form"
365 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
366 // Translate some data
367 $urlData['registered'] = generateDateTime($urlData['registered'], '2');
368 $urlData['views_total'] = translateComma($urlData['views_total']);
369 $urlData['views_max'] = translateComma($urlData['views_max']);
370 $urlData['views_allowed'] = translateComma($urlData['views_allowed']);
371 $urlData['last_locked'] = generateDateTime($urlData['last_locked'], '2');
373 // Is the lock reason empty?
374 if (empty($urlData['lock_reason'])) {
375 // Fix it to three dashes
376 $urlData['lock_reason'] = '---';
379 // Include fields only for action 'edit'
380 if ($action == 'edit') {
381 // Default is not limited
382 $urlData['limited_yes'] = '';
383 $urlData['limited_no'] = ' checked="checked"';
384 $urlData['limited'] = 'false';
386 // Is this URL limited?
387 if ($urlData['views_max'] > 0) {
388 // Then rewrite form data
389 $urlData['limited_yes'] = ' checked="checked"';
390 $urlData['limited_no'] = '';
391 $urlData['limited'] = 'true';
395 // Load the form and display it
396 LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
398 // All fine by default ... ;-)
402 // Execute choosen action
403 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
404 // By default nothing is executed
407 // Is limitation "no" and "limit" is > 0?
408 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] == 'N') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
409 // Set it to unlimited
410 $urlData[$action]['limit'] = 0;
413 // Construct function name
414 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
416 // Is 'userid' set and not 'uid' ?
417 if ((!isset($urlData['uid'])) && (isset($urlData['userid']))) {
419 $urlData['uid'] = $urlData['userid'];
422 // Is that function there?
423 if (function_exists($functionName)) {
424 // Execute the function
425 if (call_user_func_array($functionName, array($urlData)) == true) {
426 // Update status as well
427 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
431 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
437 // "Execute edit" function: Update changed data
438 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
439 // Default is nothing done
442 // Translate URLs for testing
443 $url1 = COMPILE_CODE($urlData['url']);
444 $url2 = COMPILE_CODE($urlData['edit']['url']);
446 // Has the URL or limit changed?
448 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
450 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET url='%s', views_allowed=%s, views_max=%s WHERE `id`=%s AND `status`='%s' LIMIT 1",
451 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
460 // "Execute delete" function: Does nothing...
461 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
462 // Nothing special to do (see above function for such "special actions" to perform)
466 // -----------------------------------------------------------------------------
467 // Self-maintenance functions
468 // -----------------------------------------------------------------------------
471 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
472 // Handle URLs which limit has depleted so we can stop them
473 SURFBAR_HANDLE_DEPLETED_VIEWS();
475 // Handle low-points amounts
476 SURFBAR_HANDLE_LOW_POINTS();
478 // Handle URLs which limit has depleted
479 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
481 $urlArray = SURFBAR_GET_URL_DATA('0', 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
483 // Do we have some entries?
484 if (count($urlArray) > 0) {
486 foreach ($urlArray as $id => $urlData) {
490 // Rewrite array for next call
491 $urlData[$id] = $data;
494 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
499 // Alert users which have URLs booked and are low on points amount
500 function SURFBAR_HANDLE_LOW_POINTS () {
502 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
504 // "Walk" through all URLs
505 foreach ($UIDs['uid'] as $uid => $dummy) {
506 // Is the last notification far enougth away to notify again?
507 if ((time() - $UIDs['notified'][$uid]) >= getConfig('surfbar_low_interval')) {
511 'low' => translateComma(getConfig('surfbar_warn_low_points')),
512 'points' => translateComma($UIDs['points'][$uid]),
513 'notified' => generateDateTime($UIDs['notified'][$uid]),
514 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
518 SURFBAR_NOTIFY_USER('low_points', $content);
520 // Update last notified
521 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET surfbar_low_notified=NOW() WHERE `userid`=%s LIMIT 1",
522 array($uid), __FUNCTION__, __LINE__);
528 // -----------------------------------------------------------------------------
530 // -----------------------------------------------------------------------------
533 // Looks up by an URL
534 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
535 // Now lookup that given URL by itself
536 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'id', 'ASC', 'id', sprintf(" AND `userid`=%s", bigintval($uid)));
539 return (count($urlArray) > 0);
542 // Load URL data by given search term and column
543 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'id', $order = 'id', $sort = 'ASC', $group = 'id', $add = '') {
544 // By default nothing is found
545 $GLOBALS['last_url_data'] = array();
547 // Is the column an id number?
548 if (($column == 'id') || ($column == 'userid')) {
549 // Extra secure input
550 $searchTerm = bigintval($searchTerm);
553 // If the column is 'id' there can be only one entry
555 if ($column == 'id') {
559 // Look up the record
560 $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, views_max, views_allowed, status, registered, last_locked, lock_reason, views_max, views_allowed, fixed_reload
561 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
562 WHERE %s='%s'".$add."
565 array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
567 // Is there at least one record?
568 if (SQL_NUMROWS($result) > 0) {
570 while ($dataRow = SQL_FETCHARRAY($result)) {
571 // Shall we group these results?
572 if ($group == 'id') {
573 // Add the row by id as index
574 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
577 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
583 SQL_FREERESULT($result);
586 return $GLOBALS['last_url_data'];
589 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
590 function SURFBAR_REGISTER_URL ($url, $uid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
591 // Make sure by the user registered URLs are always pending
592 if ($addMode == 'reg') {
597 $content = merge_array($extraFields, array(
599 'frametester' => FRAMETESTER($url),
604 // Is limit/reload set?
605 if (!isset($config['limit'])) {
606 $content['limit'] = 0;
608 if (!isset($config['reload'])) {
609 $content['reload'] = 0;
612 // Insert the URL into database
613 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
616 if ($content['insert_id'] == 0) {
617 // INSERT did not insert any data!
621 // Translate status and limit
622 $content['limit'] = surfbarTranslateLimit($content['limit']);
624 // If in reg-mode we notify admin
625 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
626 // Notify admin even when he as unlocked an email
627 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
631 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
633 // Return the insert id
634 return $content['insert_id'];
637 // Inserts an url by given data array and return the insert id
638 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
640 $uid = bigintval($urlData['uid']);
643 if (empty($uid)) $uid = 0;
645 // Just run the insert query for now
646 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_urls` (userid,url,status,views_max,views_allowed,fixed_reload) VALUES (%s,'%s','%s',%s,%s,%s)",
654 ), __FUNCTION__, __LINE__
658 return SQL_INSERTID();
661 // Notify admin(s) with a selected message and content
662 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
663 // Prepare template name
664 $templateName = sprintf("admin_surfbar_%s", $messageType);
667 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
668 strtoupper($messageType)
671 // Is the subject line there?
672 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
673 // Set default subject if following eval() wents wrong
674 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
677 // Translate some data if present
678 if (isset($content['status'])) $content['status'] = surfbarTranslateUserStatus($content['status']);
679 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], '2');
680 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], '2');
681 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
682 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
683 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
685 // Send the notification out
686 return sendAdminNotification($subject, $templateName, $content, $content['uid']);
689 // Notify the user about the performed action
690 function SURFBAR_NOTIFY_USER ($messageType, $content) {
691 // Skip notification if userid is zero
692 if ($content['uid'] == 0) {
696 // Prepare template name
697 $templateName = sprintf("member_surfbar_%s", $messageType);
700 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
701 strtoupper($messageType)
704 // Is the subject line there?
705 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
706 // Set default subject if following eval() wents wrong
707 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
710 // Translate some data if present
711 if (isset($content['status'])) $content['status'] = surfbarTranslateUserStatus($content['status']);
712 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], '2');
713 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], '2');
714 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
715 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
716 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
719 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
722 return sendEmail($content['uid'], $subject, $mailText);
725 // Translates the limit
726 function surfbarTranslateLimit ($limit) {
730 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
733 $return = translateComma($limit);
740 // Translate the URL status
741 function surfbarTranslateUserStatus ($status) {
742 // Create constant name
743 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
745 // Set default translated status
746 $statusTranslated = '!'.$constantName.'!';
748 // Is the constant there?
749 if (defined($constantName)) {
750 // Then get it's value
751 $statusTranslated = constant($constantName);
755 return $statusTranslated;
759 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
760 // Static values are default
761 $reward = getConfig('surfbar_static_reward');
763 // Do we have static or dynamic?
764 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
765 // "Calculate" dynamic reward
767 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
769 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
778 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
779 // Static costs is default
780 $costs = getConfig('surfbar_static_costs');
782 // Do we have static or dynamic?
783 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
784 // "Calculate" dynamic costs
786 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
788 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
796 // "Calculate" dynamic add
797 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
798 // Get min/max values
799 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
800 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
802 // "Calculate" dynamic part and return it
803 return mt_rand($min, $max);
806 // Determine right template name
807 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
808 // Default is the frameset
809 $templateName = "surfbar_frameset";
811 // Any frame set? ;-)
812 if (REQUEST_ISSET_GET('frame')) {
813 // Use the frame as a template name part... ;-)
814 $templateName = sprintf("surfbar_frame_%s",
820 return $templateName;
823 // Check if the "reload lock" of the current user is full, call this function
824 // before you call SURFBAR_CHECK_RELOAD_LOCK().
825 function SURFBAR_CHECK_RELOAD_FULL() {
829 // Cache static reload lock
830 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
831 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".getConfig('surfbar_static_lock')."", false);
833 // Do we have dynamic model?
834 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
835 // "Calculate" dynamic lock
836 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
840 $result = SQL_QUERY_ESC("SELECT
843 `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
845 `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
849 l.userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.last_surfed) AND (((UNIX_TIMESTAMP(l.last_surfed) - u.fixed_reload) < 0 AND u.fixed_reload > 0) OR u.fixed_reload = 0)
851 array(getUserId()), __FUNCTION__, __LINE__
855 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
858 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
859 // Then fix it to zero!
860 $GLOBALS['surfbar_cache']['user_locks'] = 0;
864 SQL_FREERESULT($result);
867 $total = SURFBAR_GET_TOTAL_URLS();
869 // Do we have some URLs in lock? Admins can always surf on own URLs!
870 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
871 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
877 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
878 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = 0) {
879 // Determine depleted user account
880 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
882 // Is the exlude userid set?
883 if ($excludeUserId > 0) {
885 $UIDs['uid'][$excludeUserId] = $excludeUserId;
888 // Get amount from database
889 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
890 FROM `{!_MYSQL_PREFIX!}_surfbar_urls`
891 WHERE userid NOT IN (".implode(',', $UIDs['uid']).") AND `status`='%s'",
892 array($status), __FUNCTION__, __LINE__
896 list($cnt) = SQL_FETCHROW($result);
899 SQL_FREERESULT($result);
905 // Check wether the user is allowed to book more URLs
906 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
907 // Is this admin and userid is zero or does the user has some URLs left to book?
908 return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, '', array("REJECTED")) < getConfig('surfbar_max_order')));
911 // Get total amount of URLs of given status for current user
912 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status = '',$exclude = '') {
913 // Is the user 0 and user is logged in?
914 if (($uid == 0) && (IS_MEMBER())) {
915 // Then use this userid
917 } elseif ($uid == 0) {
919 return (getConfig('surfbar_max_order') + 1);
922 // Default is all URLs
925 // Is the status set?
926 if (is_array($status)) {
927 // Only URLs with these status
928 $add = sprintf(" AND `status` IN('%s')", implode("','", $status));
929 } elseif (!empty($status)) {
930 // Only URLs with this status
931 $add = sprintf(" AND `status`='%s'", $status);
932 } elseif (is_array($exclude)) {
933 // Exclude URLs with these status
934 $add = sprintf(" AND `status` NOT IN('%s')", implode("','", $exclude));
935 } elseif (!empty($exclude)) {
936 // Exclude URLs with this status
937 $add = sprintf(" AND `status` != '%s'", $exclude);
940 // Get amount from database
941 $cnt = GET_TOTAL_DATA($uid, 'surfbar_urls', 'id', 'userid', true, $add);
947 // Generate a validation code for the given id number
948 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
949 // @TODO Invalid salt should be refused
950 $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
952 // Get code length from config
953 $length = getConfig('code_length');
956 if ($length == 0) $length = 10;
958 // Generate a code until the length matches
960 while (strlen($valCode) != $length) {
963 // Generate random hashed string
964 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
965 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
968 $GLOBALS['surfbar_cache']['salt'] = $salt;
969 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
972 // ... and now the validation code
973 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getUserId());
974 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
977 // Hash it with md5() and salt it with the random string
978 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
980 // Finally encrypt it PGP-like and return it
981 $valHashedCode = generatePassString($hashedCode);
983 // Return hashed value
984 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
985 return $valHashedCode;
988 // Check validation code
989 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
991 $urlId = bigintval($urlId);
993 // Now generate the code again
994 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
996 // Return result of checking hashes and salts
997 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
998 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt.'|'.SURFBAR_GET_DATA('last_salt')."+++", false);
999 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
1002 // Lockdown the userid/id combination (reload lock)
1003 function SURFBAR_LOCKDOWN_ID ($urlId) {
1004 //* DEBUG: */ OUTPUT_HTML("LOCK!");
1005 ///* DEBUG: */ return;
1006 // Just add it to the database
1007 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_locks` (`userid`, `url_id`) VALUES (%s, %s)",
1008 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1010 // Remove the salt from database
1011 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_surfbar_salts` WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1012 array(bigintval($urlId), getUserId()), __FUNCTION__, __LINE__);
1015 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1016 function SURFBAR_PAY_POINTS () {
1017 // Remove it from the URL owner
1018 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
1019 if (SURFBAR_GET_USERID() > 0) {
1020 SUB_POINTS(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1023 // Book it to the user
1024 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".getUserId().",reward=".SURFBAR_GET_REWARD()."", false);
1025 ADD_POINTS_REFSYSTEM(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getUserId(), SURFBAR_GET_DATA('reward'));
1028 // Updates the statistics of current URL/userid
1029 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1033 // Get allowed views
1034 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1036 // Do we have a limit?
1038 // Then count views_max down!
1039 $add .= ", `views_max`=`views_max`-1";
1043 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `views_total`=`views_total`+1".$add." WHERE `id`=%s LIMIT 1",
1044 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1046 // Update the stats entry
1047 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_stats` SET `count`=`count`+1 WHERE `userid`=%s AND `url_id`=%s LIMIT 1",
1048 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1050 // Was that update okay?
1051 if (SQL_AFFECTEDROWS() < 1) {
1052 // No, then insert entry
1053 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1054 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1057 // Update total/daily/weekly/monthly counter
1058 incrementConfigEntry('surfbar_total_counter');
1059 incrementConfigEntry('surfbar_daily_counter');
1060 incrementConfigEntry('surfbar_weekly_counter');
1061 incrementConfigEntry('surfbar_monthly_counter');
1063 // Update config as well
1064 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1067 // Update the salt for validation and statistics
1068 function SURFBAR_UPDATE_SALT_STATS () {
1069 // Update statistics record
1070 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1072 // Simply store the salt from cache away in database...
1073 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_salts` SET `last_salt`='%s' WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1074 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getUserId()), __FUNCTION__, __LINE__);
1077 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".getUserId()."", false);
1080 if (SQL_AFFECTEDROWS() < 1) {
1081 // Insert missing entry!
1082 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_surfbar_salts` (`url_id`, `userid`, `last_salt`) VALUES (%s, %s, '%s')",
1083 array(SURFBAR_GET_ID(), getUserId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1087 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
1089 // Return if the update was okay
1090 return (SQL_AFFECTEDROWS() == 1);
1093 // Check if the reload lock is active for given id
1094 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1095 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
1097 $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1099 `{!_MYSQL_PREFIX!}_surfbar_locks`
1101 `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1105 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1109 list($cnt) = SQL_FETCHROW($result);
1112 SQL_FREERESULT($result);
1115 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_SURF_LOCK()."", false);
1119 // Determine which user hash no more points left
1120 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1124 'points' => array(),
1125 'notified' => array(),
1128 // Do we have a current user id?
1129 if ((IS_MEMBER()) && ($limit == 0)) {
1130 // Then add this as well
1131 $UIDs['uid'][getUserId()] = getUserId();
1132 $UIDs['points'][getUserId()] = GET_TOTAL_DATA(getUserId(), 'user_points', 'points') - GET_TOTAL_DATA(getUserId(), 'user_data', 'used_points');
1133 $UIDs['notified'][getUserId()] = 0;
1135 // Get all userid except logged in one
1136 $result = SQL_QUERY_ESC("SELECT
1137 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1139 `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1141 `{!_MYSQL_PREFIX!}_user_data` AS d
1145 u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1150 array(getUserId()), __FUNCTION__, __LINE__);
1153 $result = SQL_QUERY("SELECT
1154 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1156 `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1158 `{!_MYSQL_PREFIX!}_user_data` AS d
1166 u.userid ASC", __FUNCTION__, __LINE__);
1170 while ($content = SQL_FETCHARRAY($result)) {
1172 $points = GET_TOTAL_DATA($content['userid'], 'user_points', 'points') - GET_TOTAL_DATA($content['userid'], 'user_data', 'used_points');
1173 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']},points={$points}", false);
1175 // Shall we add this to ignore?
1176 if ($points <= $limit) {
1178 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$content['userid']} has depleted points amount!", false);
1179 $UIDs['uid'][$content['userid']] = $content['userid'];
1180 $UIDs['points'][$content['userid']] = $points;
1181 $UIDs['notified'][$content['userid']] = $content['notified'];
1186 SQL_FREERESULT($result);
1189 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".getUserId().')', false);
1195 // Determine how many users are Online in surfbar
1196 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1197 // Count all users in surfbar modue and return the value
1198 $result = SQL_QUERY_ESC("SELECT id
1199 FROM `{!_MYSQL_PREFIX!}_surfbar_stats`
1200 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1202 array(getConfig('online_timeout')), __FUNCTION__, __LINE__);
1205 $cnt = SQL_NUMROWS($result);
1208 SQL_FREERESULT($result);
1214 // Determine waiting time for one URL
1215 function SURFBAR_DETERMINE_WAIT_TIME () {
1216 // Get fixed reload lock
1217 $fixed = SURFBAR_GET_FIXED_RELOAD();
1219 // Is the fixed reload time set?
1225 // Static time is default
1226 $time = getConfig('surfbar_static_time');
1228 // Which payment model do we have?
1229 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1230 // "Calculate" dynamic time
1231 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1238 // Changes the status of an URL from given to other
1239 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1240 // Make new status always lower-case
1241 $newStatus = strtolower($newStatus);
1243 // Get URL data for status comparison if missing
1244 if ((!is_array($data)) || (count($data) == 0)) {
1245 // Fetch missing URL data
1246 $data = SURFBAR_GET_URL_DATA($urlId);
1249 // Is the new status set?
1250 if ((!is_string($newStatus)) || (empty($newStatus))) {
1251 // Abort here, but fine!
1255 // Is the status like prevStatus is saying?
1256 if ($data[$urlId]['status'] != $prevStatus) {
1257 // No, then abort here
1262 // Update the status now
1263 // ---------- Comment out for debugging/developing member actions! ---------
1264 //SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1265 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1266 // ---------- Comment out for debugging/developing member actions! ---------
1269 // ---------- Comment out for debugging/developing member actions! ---------
1270 //if (SQL_AFFECTEDROWS() != 1) {
1271 // // No, something went wrong
1274 // ---------- Comment out for debugging/developing member actions! ---------
1276 // Prepare content for notification routines
1277 $data[$urlId]['uid'] = $data[$urlId]['userid'];
1278 $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1279 $data[$urlId]['reward'] = translateComma(getConfig('surfbar_static_reward'));
1280 $data[$urlId]['costs'] = translateComma(getConfig('surfbar_static_costs'));
1282 // Do some dirty fixing here:
1283 if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1284 // Fix for template change
1285 $newStatus = 'continued';
1288 // Send admin notification
1289 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1291 // Send user notification
1292 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1298 // Calculate minimum value for dynamic payment model
1299 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1300 // Addon is zero by default
1304 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1307 $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1310 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1313 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1316 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1318 // Get user's total URLs
1319 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1322 if ($totalUrls > 0) {
1323 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1325 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1332 // Calculate maximum value for dynamic payment model
1333 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1334 // Addon is zero by default
1341 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1344 $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true);
1347 $addon += abs($max * $percent * $totalUsers);
1350 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', '0');
1353 $addon += abs($max * $percent * $totalUrls);
1359 // Calculate dynamic lock
1360 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1361 // Default lock is 30 seconds
1365 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1368 $addon = abs(log($onlineUsers / $addon + 1));
1374 // "Getter" for lock ids array
1375 function SURFBAR_GET_LOCK_IDS () {
1376 // Prepare some arrays
1381 // Get all id from locks within the timestamp
1382 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1384 {!_MYSQL_PREFIX!}_surfbar_locks
1388 id ASC", array(getUserId()),
1389 __FUNCTION__, __LINE__);
1392 while ($content = SQL_FETCHARRAY($result)) {
1394 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$content['id']},url={$content['url_id']},rest=".(time() - $last).'/'.SURFBAR_GET_SURF_LOCK()."", false);
1396 // Skip entries that are too old
1397 if (($last > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1399 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1401 // Add only if missing or bigger
1402 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $last)) {
1404 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1407 $IDs[$content['url_id']] = $last;
1408 $USE[$content['url_id']] = $content['id'];
1412 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$content['id']},url={$content['url_id']},last={$last}", false);
1414 // Ignore these old entries!
1415 $ignored[] = $content['url_id'];
1416 unset($IDs[$content['url_id']]);
1417 unset($USE[$content['url_id']]);
1422 SQL_FREERESULT($result);
1428 // "Getter" for maximum random number
1429 function SURFBAR_GET_MAX_RANDOM ($UIDs, $add) {
1430 // Count max availabe entries
1431 $result = SQL_QUERY("SELECT sbu.id AS cnt
1432 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1433 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1434 ON sbu.id=sbs.url_id
1435 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1437 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."
1438 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1441 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1444 $maxRand = SQL_NUMROWS($result);
1447 SQL_FREERESULT($result);
1453 // Load all URLs of the current user and return it as an array
1454 function SURFBAR_GET_USER_URLS () {
1459 $result = SQL_QUERY_ESC("SELECT u.id, u.userid, u.url, u.views_total, u.views_max, u.views_allowed, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
1460 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS u
1461 WHERE u.userid=%s AND u.status != 'DELETED'
1463 array(getUserId()), __FUNCTION__, __LINE__);
1465 // Are there entries?
1466 if (SQL_NUMROWS($result) > 0) {
1468 while ($row = SQL_FETCHARRAY($result)) {
1470 $URLs[$row['id']] = $row;
1475 SQL_FREERESULT($result);
1481 // "Getter" for member action array for given status
1482 function SURFBAR_getModeAction_ARRAY ($status) {
1484 $returnArray = array();
1486 // Get all assigned actions
1487 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1488 array($status), __FUNCTION__, __LINE__);
1490 // Some entries there?
1491 if (SQL_NUMROWS($result) > 0) {
1493 // @TODO This can be somehow rewritten
1494 while ($content = SQL_FETCHARRAY($result)) {
1495 $returnArray[] = $content['action'];
1500 SQL_FREERESULT($result);
1503 return $returnArray;
1506 // Reload to configured stop page
1507 function SURFBAR_RELOAD_TO_STOP_PAGE ($page="stop") {
1508 // Internal or external?
1509 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1510 // Reload to internal page
1511 redirectToUrl('surfbar.php?frame=' . $page);
1513 // Reload to external page
1514 redirectToConfiguredUrl('surfbar_pause_url');
1518 // Determine next id for surfbar or get data for given id, always call this before you call other
1519 // getters below this function!!!
1520 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1521 // Default is no id and no random number
1527 // Get array with lock ids
1528 $USE = SURFBAR_GET_LOCK_IDS();
1530 // Shall we add some URL ids to ignore?
1532 if (count($USE) > 0) {
1534 $add = " AND sbu.id NOT IN (";
1535 foreach ($USE as $url_id => $lid) {
1537 $add .= $url_id.',';
1540 // Add closing bracket
1541 $add = substr($add, 0, -1) . ')';
1544 // Determine depleted user account
1545 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1547 // Get maximum randomness factor
1548 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $add);
1550 // If more than one URL can be called generate the random number!
1552 // Generate random number
1553 $randNum = mt_rand(0, ($maxRand - 1));
1556 // And query the database
1557 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_SURF_LOCK()."", false);
1558 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed, sbu.fixed_reload
1559 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1560 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1561 ON sbu.id=sbs.url_id
1562 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1564 WHERE sbu.userid NOT IN (".implode(',', $UIDs['uid']).") AND sbu.`status`='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$add."
1566 ORDER BY l.last_surfed ASC, sbu.id ASC
1568 array($randNum), __FUNCTION__, __LINE__
1571 // Get data from specified id number
1572 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed, sbu.fixed_reload
1573 FROM `{!_MYSQL_PREFIX!}_surfbar_urls` AS sbu
1574 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_salts` AS sbs
1575 ON sbu.id=sbs.url_id
1576 LEFT JOIN `{!_MYSQL_PREFIX!}_surfbar_locks` AS l
1578 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))
1580 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1584 // Is there an id number?
1585 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".getConfig('db_last_query')."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1586 if (SQL_NUMROWS($result) == 1) {
1588 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['surfbar_cache']).") - BEFORE", false);
1589 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1590 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($GLOBALS['surfbar_cache']).") - AFTER", false);
1592 // Determine waiting time
1593 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1595 // Is the last salt there?
1596 if (is_null($GLOBALS['surfbar_cache']['last_salt'])) {
1597 // Then repair it wit the static!
1598 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1599 $GLOBALS['surfbar_cache']['last_salt'] = '';
1602 // Fix missing last_surfed
1603 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1605 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1606 $GLOBALS['surfbar_cache']['last_surfed'] = 0;
1609 // Get base/fixed reward and costs
1610 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1611 $GLOBALS['surfbar_cache']['costs'] = SURFBAR_DETERMINE_COSTS();
1612 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1614 // Only in dynamic model add the dynamic bonus!
1615 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1616 // Calculate dynamic reward/costs and add it
1617 $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1618 $GLOBALS['surfbar_cache']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1619 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1623 $nextId = SURFBAR_GET_ID();
1627 SQL_FREERESULT($result);
1630 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1634 // -----------------------------------------------------------------------------
1635 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1636 // THE $GLOBALS['surfbar_cache'] ARRAY!
1637 // -----------------------------------------------------------------------------
1639 // Initializes the surfbar
1640 function SURFBAR_INIT () {
1642 $GLOBALS['surfbar_cache'] = array();
1645 // Private getter for data elements
1646 function SURFBAR_GET_DATA ($element) {
1647 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1652 // Is the entry there?
1653 if (isset($GLOBALS['surfbar_cache'][$element])) {
1655 $data = $GLOBALS['surfbar_cache'][$element];
1656 } else { // END - if
1658 print_r($GLOBALS['surfbar_cache']);
1664 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1668 // Getter for reward from cache
1669 function SURFBAR_GET_REWARD () {
1670 // Get data element and return its contents
1671 return SURFBAR_GET_DATA('reward');
1674 // Getter for costs from cache
1675 function SURFBAR_GET_COSTS () {
1676 // Get data element and return its contents
1677 return SURFBAR_GET_DATA('costs');
1680 // Getter for URL from cache
1681 function SURFBAR_GET_URL () {
1682 // Get data element and return its contents
1683 return SURFBAR_GET_DATA('url');
1686 // Getter for salt from cache
1687 function SURFBAR_GET_SALT () {
1688 // Get data element and return its contents
1689 return SURFBAR_GET_DATA('salt');
1692 // Getter for id from cache
1693 function SURFBAR_GET_ID () {
1694 // Get data element and return its contents
1695 return SURFBAR_GET_DATA('id');
1698 // Getter for userid from cache
1699 function SURFBAR_GET_USERID () {
1700 // Get data element and return its contents
1701 return SURFBAR_GET_DATA('userid');
1704 // Getter for user reload locks
1705 function SURFBAR_GET_USER_LOCKS () {
1706 // Get data element and return its contents
1707 return SURFBAR_GET_DATA('user_locks');
1710 // Getter for reload time
1711 function SURFBAR_GET_RELOAD_TIME () {
1712 // Get data element and return its contents
1713 return SURFBAR_GET_DATA('time');
1716 // Getter for allowed views
1717 function SURFBAR_GET_VIEWS_ALLOWED () {
1718 // Get data element and return its contents
1719 return SURFBAR_GET_DATA('views_allowed');
1722 // Getter for fixed reload
1723 function SURFBAR_GET_FIXED_RELOAD () {
1724 // Get data element and return its contents
1725 return SURFBAR_GET_DATA('fixed_reload');
1728 // Getter for surf lock
1729 function SURFBAR_GET_SURF_LOCK () {
1730 // Get data element and return its contents
1731 return SURFBAR_GET_DATA('surf_lock');
1734 // Getter for new status
1735 function SURFBAR_GET_NEW_STATUS () {
1736 // Get data element and return its contents
1737 return SURFBAR_GET_DATA('new_status');