2 /************************************************************************
3 * Mailer v0.2.1-FINAL 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 - 2009 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')) {
44 // -----------------------------------------------------------------------------
46 // -----------------------------------------------------------------------------
48 // Admin has added an URL with given user id and so on
49 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
53 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
55 } elseif (!isUrlValid($url)) {
57 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid URL.", $url, $limit, $reload));
59 } elseif (SURFBAR_LOOKUP_BY_URL($url, 0)) {
60 // URL already found in surfbar!
61 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Already added.", $url, $limit, $reload));
63 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
65 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : No more URLs allowed.", $url, $limit, $reload));
67 } elseif ('' . ($limit + 0) . '' != '' . $limit . '') {
68 // Invalid limit entered
69 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid limit entered.", $url, $limit, $reload));
71 } elseif ('' . ($reload + 0) . '' != '' . $reload . '') {
72 // Invalid amount entered
73 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid reload entered.", $url, $limit, $reload));
77 // Register the new URL
78 return SURFBAR_REGISTER_URL($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
81 // Admin unlocked an email so we can migrate the URL
82 function SURFBAR_ADMIN_MIGRATE_URL ($url, $userid) {
87 } elseif (!isUrlValid($url)) {
90 } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
91 // URL already found in surfbar!
93 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
98 // Register the new URL
99 return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
102 // Admin function for unlocking URLs
103 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
104 // Is this an admin or invalid array?
106 // Not admin or invalid ids array
108 } elseif (!is_array($IDs)) {
111 } elseif (count($IDs) == '0') {
116 // Set to true to make AND expression valid if first URL got unlocked
119 // Update the status for all ids
120 foreach ($IDs as $id => $dummy) {
121 // Test all ids through (ignores failed)
122 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
125 // Return total status
129 // Admin function for rejecting URLs
130 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
131 // Is this an admin or invalid array?
133 // Not admin or invalid ids array
135 } elseif (!is_array($IDs)) {
138 } elseif (count($IDs) == '0') {
143 // Set to true to make AND expression valid if first URL got unlocked
146 // Update the status for all ids
147 foreach ($IDs as $id => $dummy) {
148 // Test all ids through (ignores failed)
149 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
152 // Return total status
157 // -----------------------------------------------------------------------------
159 // -----------------------------------------------------------------------------
161 // Member has added an URL
162 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
163 // Do some pre-checks
167 } elseif ((!isUrlValid($url)) && (!isAdmin())) {
170 } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
171 // URL already found in surfbar!
173 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
176 } elseif (''.($limit + 0).'' != ''.$limit.'') {
177 // Invalid amount entered
181 // Register the new URL
182 return SURFBAR_REGISTER_URL($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
185 // Create list of actions depending on status for the user
186 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
187 // Load all actions in an array for given status
188 $actionArray = SURFBAR_GET_ARRAY_FROM_STATUS($status);
191 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
195 $width = round(100 / count($actionArray));
197 // "Walk" through all actions and create forms
198 foreach ($actionArray as $actionId => $action) {
199 // Add form for this action
200 $OUT .= loadTemplate('member_surfbar_list_form', true, array(
202 'id' => bigintval($urlId),
203 'action' => strtolower($action),
204 'title' => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE--}',
205 'submit' => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT--}',
217 // Do the member form request
218 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
219 // By default no action is performed
226 } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
227 // Important form elements are missing!
229 } elseif (!isset($URLs[$formData['id']])) {
230 // id not found in cache
232 } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
233 // Action not allowed for current URL status
238 $action = secureString($formData['action']);
241 if ($action != $formData['action']) {
242 // Invalid data in action found
246 // Create the function name for selected action
247 $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
249 // Is the function there?
250 if (function_exists($functionName)) {
252 $URLs[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
254 // Extract URL data for call-back
255 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
257 // Action found so execute it
258 $performed = call_user_func_array($functionName, $urlData);
260 // Log invalid request
261 logDebugMessage(__FUNCTION__, __LINE__, "action={$formData['action']},id={$formData['id']},function={$functionName}");
262 addFatalMessage(__FUNCTION__, __LINE__, "Invalid member action! action=%s,id=%s,function=%s", array($formData['action'], $formData['id'], $functionName));
269 // Validate if the requested action can be performed on current URL status
270 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
271 // Search for the requested action/status combination in database
272 $result = SQL_QUERY_ESC("SELECT new_status FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `action`='%s' AND `status`='%s' LIMIT 1",
273 array($action, $status), __FUNCTION__, __LINE__);
275 // Is the entry there?
276 $isValid = (SQL_NUMROWS($result) == 1);
278 // Fetch the new status if found
281 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
285 SQL_FREERESULT($result);
292 // -----------------------------------------------------------------------------
294 // -----------------------------------------------------------------------------
296 // Retreat a booked URL
297 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
298 // Create the data array for next function call
300 $urlData['id'] => $urlData
303 // Simply change the status here
304 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
307 // Book an URL now (from migration)
308 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
309 // Create the data array for next function call
311 $urlData['id'] => $urlData
314 // Simply change the status here
315 return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
318 // Show edit form or do the changes
319 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
320 // Is the "execute" flag there?
321 if (isset($urlData['edit']['execute'])) {
322 // Execute the changes
323 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
327 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
330 // Show delete form or do the changes
331 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
332 // Is the "execute" flag there?
333 if (isset($urlData['delete']['execute'])) {
334 // Execute the changes
335 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
339 return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
342 // Pause active banner
343 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
344 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
347 // Unpause stopped banner
348 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
349 // Fix missing entry for template
350 $urlData['edit'] = $urlData['unpause'];
351 $urlData['edit']['url'] = $urlData['url'];
352 $urlData['edit']['limit'] = $urlData['views_max'];
354 // Return status change
355 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
358 // Resubmit locked URL
359 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
360 return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
363 // Display selected "action form"
364 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
365 // Translate some data
366 $urlData['registered'] = generateDateTime($urlData['registered'], 2);
367 $urlData['views_total'] = translateComma($urlData['views_total']);
368 $urlData['views_max'] = translateComma($urlData['views_max']);
369 $urlData['views_allowed'] = translateComma($urlData['views_allowed']);
370 $urlData['last_locked'] = generateDateTime($urlData['last_locked'], 2);
372 // Is the lock reason empty?
373 if (empty($urlData['lock_reason'])) {
374 // Fix it to three dashes
375 $urlData['lock_reason'] = '---';
378 // Include fields only for action 'edit'
379 if ($action == 'edit') {
380 // Default is not limited
381 $urlData['limited_y'] = '';
382 $urlData['limited_n'] = ' checked="checked"';
383 $urlData['limited'] = 'false';
385 // Is this URL limited?
386 if ($urlData['views_max'] > 0) {
387 // Then rewrite form data
388 $urlData['limited_y'] = ' checked="checked"';
389 $urlData['limited_n'] = '';
390 $urlData['limited'] = 'true';
394 // Load the form and display it
395 loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
397 // All fine by default ... ;-)
401 // Execute choosen action
402 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
403 // By default nothing is executed
406 // Is limitation "no" and "limit" is > 0?
407 if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
408 // Set it to unlimited
409 $urlData[$action]['limit'] = '0';
412 // Construct function name
413 $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
415 // Is 'userid' set and not 'userid' ?
416 if ((!isset($urlData['userid'])) && (isset($urlData['userid']))) {
418 $urlData['userid'] = $urlData['userid'];
421 // Is that function there?
422 if (function_exists($functionName)) {
423 // Execute the function
424 if (call_user_func_array($functionName, array($urlData)) == true) {
425 // Update status as well
426 $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
430 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
436 // "Execute edit" function: Update changed data
437 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
438 // Default is nothing done
441 // Has the URL or limit changed?
443 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
445 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",
446 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
455 // "Execute delete" function: Does nothing...
456 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
457 // Nothing special to do (see above function for such "special actions" to perform)
461 // -----------------------------------------------------------------------------
462 // Self-maintenance functions
463 // -----------------------------------------------------------------------------
466 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
467 // Handle URLs which limit has depleted so we can stop them
468 SURFBAR_HANDLE_DEPLETED_VIEWS();
470 // Handle low-points amounts
471 SURFBAR_HANDLE_LOW_POINTS();
473 // Handle URLs which limit has depleted
474 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
476 $urlArray = SURFBAR_GET_URL_DATA(0, 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
478 // Do we have some entries?
479 if (count($urlArray) > 0) {
481 foreach ($urlArray as $id => $urlData) {
485 // Rewrite array for next call
486 $urlData[$id] = $data;
489 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
494 // Alert users which have URLs booked and are low on points amount
495 function SURFBAR_HANDLE_LOW_POINTS () {
497 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
499 // "Walk" through all URLs
500 foreach ($UIDs['userid'] as $userid => $dummy) {
501 // Is the last notification far enougth away to notify again?
502 if ((time() - $UIDs['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
506 'low' => translateComma(getConfig('surfbar_warn_low_points')),
507 'points' => translateComma($UIDs['points'][$userid]),
508 'notified' => generateDateTime($UIDs['notified'][$userid]),
509 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
513 SURFBAR_NOTIFY_USER('low_points', $content);
515 // Update last notified
516 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET surfbar_low_notified=NOW() WHERE `userid`=%s LIMIT 1",
517 array($userid), __FUNCTION__, __LINE__);
523 // -----------------------------------------------------------------------------
525 // -----------------------------------------------------------------------------
528 // Looks up by an URL
529 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
530 // Now lookup that given URL by itself
531 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'id', 'ASC', 'id', sprintf(" AND `userid`=%s", bigintval($userid)));
534 return (count($urlArray) > 0);
537 // Load URL data by given search term and column
538 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'id', $order = 'id', $sort = 'ASC', $group = 'id', $add = '') {
539 // By default nothing is found
540 $GLOBALS['last_url_data'] = array();
542 // Is the column an id number?
543 if (($column == 'id') || ($column == 'userid')) {
544 // Extra secure input
545 $searchTerm = bigintval($searchTerm);
548 // If the column is 'id' there can be only one entry
550 if ($column == 'id') {
554 // Look up the record
555 $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
556 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
557 WHERE %s='%s'".$add."
560 array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
562 // Is there at least one record?
563 if (SQL_NUMROWS($result) > 0) {
565 while ($dataRow = SQL_FETCHARRAY($result)) {
566 // Shall we group these results?
567 if ($group == 'id') {
568 // Add the row by id as index
569 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
572 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
578 SQL_FREERESULT($result);
581 return $GLOBALS['last_url_data'];
584 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
585 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
586 // Make sure by the user registered URLs are always pending
587 if ($addMode == 'reg') {
592 $content = merge_array($extraFields, array(
594 'frametester' => generateFrametesterUrl($url),
599 // Is limit/reload set?
600 if (!isset($config['limit'])) {
601 $content['limit'] = '0';
603 if (!isset($config['reload'])) {
604 $content['reload'] = '0';
607 // Insert the URL into database
608 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
611 if ($content['insert_id'] == '0') {
612 // INSERT did not insert any data!
616 // Translate status and limit
617 $content['limit'] = translateSurfbarLimit($content['limit']);
619 // If in reg-mode we notify admin
620 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
621 // Notify admin even when he as unlocked an email
622 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
626 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
628 // Return the insert id
629 return $content['insert_id'];
632 // Inserts an url by given data array and return the insert id
633 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
635 $userid = bigintval($urlData['userid']);
638 if (empty($userid)) $userid = '0';
640 // Just run the insert query for now
641 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)",
649 ), __FUNCTION__, __LINE__
653 return SQL_INSERTID();
656 // Notify admin(s) with a selected message and content
657 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
658 // Prepare template name
659 $templateName = sprintf("admin_surfbar_%s", $messageType);
662 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
663 strtoupper($messageType)
666 // Is the subject line there?
667 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
668 // Set default subject if following eval() wents wrong
669 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
672 // Translate some data if present
673 if (isset($content['status'])) $content['status'] = translateSurfbarUrlStatus($content['status']);
674 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], 2);
675 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], 2);
676 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
677 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
678 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
680 // Send the notification out
681 return sendAdminNotification($subject, $templateName, $content, $content['userid']);
684 // Notify the user about the performed action
685 function SURFBAR_NOTIFY_USER ($messageType, $content) {
686 // Skip notification if userid is zero
687 if ($content['userid'] == '0') {
691 // Prepare template name
692 $templateName = sprintf("member_surfbar_%s", $messageType);
695 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
696 strtoupper($messageType)
699 // Is the subject line there?
700 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
701 // Set default subject if following eval() wents wrong
702 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
705 // Translate some data if present
706 if (isset($content['status'])) $content['status'] = translateSurfbarUrlStatus($content['status']);
707 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], 2);
708 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], 2);
709 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
710 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
711 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
714 $mailText = loadEmailTemplate($templateName, $content, $content['userid']);
717 return sendEmail($content['userid'], $subject, $mailText);
720 // Translates the limit
721 function translateSurfbarLimit ($limit) {
725 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
728 $return = translateComma($limit);
735 // Translate the URL status
736 function translateSurfbarUrlStatus ($status) {
737 // Create constant name
738 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
741 $statusTranslated = getMessage($constantName);
744 return $statusTranslated;
748 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
749 // Static values are default
750 $reward = getConfig('surfbar_static_reward');
752 // Do we have static or dynamic?
753 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
754 // "Calculate" dynamic reward
756 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
758 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
767 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
768 // Static costs is default
769 $costs = getConfig('surfbar_static_costs');
771 // Do we have static or dynamic?
772 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
773 // "Calculate" dynamic costs
775 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
777 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
785 // "Calculate" dynamic add
786 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
787 // Get min/max values
788 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
789 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
791 // "Calculate" dynamic part and return it
792 return mt_rand($min, $max);
795 // Determine right template name
796 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
797 // Default is the frameset
798 $templateName = "surfbar_frameset";
800 // Any frame set? ;-)
801 if (isGetRequestElementSet('frame')) {
802 // Use the frame as a template name part... ;-)
803 $templateName = sprintf("surfbar_frame_%s",
804 getRequestElement('frame')
809 return $templateName;
812 // Check if the "reload lock" of the current user is full, call this function
813 // before you call SURFBAR_CHECK_RELOAD_LOCK().
814 function SURFBAR_CHECK_RELOAD_FULL() {
818 // Cache static reload lock
819 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
820 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
822 // Do we have dynamic model?
823 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
824 // "Calculate" dynamic lock
825 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
829 $result = SQL_QUERY_ESC("SELECT
832 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
834 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
838 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')
840 array(getMemberId()), __FUNCTION__, __LINE__
844 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
847 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
848 // Then fix it to zero!
849 $GLOBALS['surfbar_cache']['user_locks'] = '0';
853 SQL_FREERESULT($result);
856 $total = SURFBAR_GET_TOTAL_URLS();
858 // Do we have some URLs in lock? Admins can always surf on own URLs!
859 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
860 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
866 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
867 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
868 // Determine depleted user account
869 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
871 // If we dont get any user ids back, there are no URLs
872 if (count($UIDs['userid']) == '0') {
873 // No user ids found, no URLs!
877 // Is the exlude userid set?
878 if ($excludeUserId > 0) {
880 $UIDs['userid'][$excludeUserId] = $excludeUserId;
883 // Get amount from database
884 $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
885 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
886 WHERE `userid` NOT IN (".implode(', ', $UIDs['userid']).") AND `status`='%s'",
887 array($status), __FUNCTION__, __LINE__
891 list($cnt) = SQL_FETCHROW($result);
894 SQL_FREERESULT($result);
900 // Check wether the user is allowed to book more URLs
901 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
902 // Is this admin and userid is zero or does the user has some URLs left to book?
903 return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getConfig('surfbar_max_order')));
906 // Get total amount of URLs of given status for current user
907 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '',$exclude = '') {
908 // Is the user 0 and user is logged in?
909 if (($userid == '0') && (isMember())) {
910 // Then use this userid
911 $userid = getMemberId();
912 } elseif ($userid == '0') {
914 return (getConfig('surfbar_max_order') + 1);
917 // Default is all URLs
920 // Is the status set?
921 if (is_array($status)) {
922 // Only URLs with these status
923 $add = sprintf(" AND `status` IN('%s')", implode("','", $status));
924 } elseif (!empty($status)) {
925 // Only URLs with this status
926 $add = sprintf(" AND `status`='%s'", $status);
927 } elseif (is_array($exclude)) {
928 // Exclude URLs with these status
929 $add = sprintf(" AND `status` NOT IN('%s')", implode("','", $exclude));
930 } elseif (!empty($exclude)) {
931 // Exclude URLs with this status
932 $add = sprintf(" AND `status` != '%s'", $exclude);
935 // Get amount from database
936 $cnt = countSumTotalData($userid, 'surfbar_urls', 'id', 'userid', true, $add);
942 // Generate a validation code for the given id number
943 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
944 // @TODO Invalid salt should be refused
945 $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
947 // Get code length from config
948 $length = getConfig('code_length');
951 if ($length == '0') $length = 10;
953 // Generate a code until the length matches
955 while (strlen($valCode) != $length) {
958 // Generate random hashed string
959 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
960 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
963 $GLOBALS['surfbar_cache']['salt'] = $salt;
964 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
967 // ... and now the validation code
968 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getMemberId());
969 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
972 // Hash it with md5() and salt it with the random string
973 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
975 // Finally encrypt it PGP-like and return it
976 $valHashedCode = generatePassString($hashedCode);
978 // Return hashed value
979 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
980 return $valHashedCode;
983 // Check validation code
984 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
986 $urlId = bigintval($urlId);
988 // Now generate the code again
989 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
991 // Return result of checking hashes and salts
992 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
993 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('last_salt').'+++', false);
994 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
997 // Lockdown the userid/id combination (reload lock)
998 function SURFBAR_LOCKDOWN_ID ($urlId) {
999 //* DEBUG: */ outputHtml('LOCK!');
1000 ///* DEBUG: */ return;
1001 // Just add it to the database
1002 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`userid`, `url_id`) VALUES (%s, %s)",
1003 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1005 // Remove the salt from database
1006 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1007 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1010 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1011 function SURFBAR_PAY_POINTS () {
1012 // Remove it from the URL owner
1013 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1014 if (SURFBAR_GET_USERID() > 0) {
1015 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1018 // Book it to the user
1019 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1020 addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getMemberId(), SURFBAR_GET_DATA('reward'));
1023 // Updates the statistics of current URL/userid
1024 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1028 // Get allowed views
1029 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1031 // Do we have a limit?
1033 // Then count views_max down!
1034 $add .= ", `views_max`=`views_max`-1";
1038 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `views_total`=`views_total`+1".$add." WHERE `id`=%s LIMIT 1",
1039 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1041 // Update the stats entry
1042 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `count`=`count`+1 WHERE `userid`=%s AND `url_id`=%s LIMIT 1",
1043 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1045 // Was that update okay?
1046 if (SQL_AFFECTEDROWS() < 1) {
1047 // No, then insert entry
1048 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1049 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1052 // Update total/daily/weekly/monthly counter
1053 incrementConfigEntry('surfbar_total_counter');
1054 incrementConfigEntry('surfbar_daily_counter');
1055 incrementConfigEntry('surfbar_weekly_counter');
1056 incrementConfigEntry('surfbar_monthly_counter');
1058 // Update config as well
1059 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1062 // Update the salt for validation and statistics
1063 function SURFBAR_UPDATE_SALT_STATS () {
1064 // Update statistics record
1065 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1067 // Simply store the salt from cache away in database...
1068 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `last_salt`='%s' WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1069 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getMemberId()), __FUNCTION__, __LINE__);
1072 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1075 if (SQL_AFFECTEDROWS() < 1) {
1076 // Insert missing entry!
1077 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`url_id`, `userid`, `last_salt`) VALUES (%s, %s, '%s')",
1078 array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1082 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1084 // Return if the update was okay
1085 return (SQL_AFFECTEDROWS() == 1);
1088 // Check if the reload lock is active for given id
1089 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1090 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1092 $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1094 `{?_MYSQL_PREFIX?}_surfbar_locks`
1096 `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1100 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1104 list($cnt) = SQL_FETCHROW($result);
1107 SQL_FREERESULT($result);
1110 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1114 // Determine which user hash no more points left
1115 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1118 'userid' => array(),
1119 'points' => array(),
1120 'notified' => array(),
1123 // Do we have a current user id?
1124 if ((isMember()) && ($limit == '0')) {
1125 // Then add this as well
1126 $UIDs['userid'][getMemberId()] = getMemberId();
1127 $UIDs['points'][getMemberId()] = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
1128 $UIDs['notified'][getMemberId()] = '0';
1130 // Get all userid except logged in one
1131 $result = SQL_QUERY_ESC("SELECT
1132 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1134 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1136 `{?_MYSQL_PREFIX?}_user_data` AS d
1140 u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1145 array(getMemberId()), __FUNCTION__, __LINE__);
1148 $result = SQL_QUERY("SELECT
1149 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1151 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1153 `{?_MYSQL_PREFIX?}_user_data` AS d
1161 u.userid ASC", __FUNCTION__, __LINE__);
1165 while ($content = SQL_FETCHARRAY($result)) {
1167 $points = countSumTotalData($content['userid'], 'user_points', 'points') - countSumTotalData($content['userid'], 'user_data', 'used_points');
1168 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']},points={$points}", false);
1170 // Shall we add this to ignore?
1171 if ($points <= $limit) {
1173 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']} has depleted points amount!", false);
1174 $UIDs['userid'][$content['userid']] = $content['userid'];
1175 $UIDs['points'][$content['userid']] = $points;
1176 $UIDs['notified'][$content['userid']] = $content['notified'];
1181 SQL_FREERESULT($result);
1184 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".getMemberId().')', false);
1190 // Determine how many users are Online in surfbar
1191 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1192 // Count all users in surfbar modue and return the value
1193 $result = SQL_QUERY("SELECT
1196 `{?_MYSQL_PREFIX?}_surfbar_stats`
1198 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`last_surfed`)) <= {?online_timeout?}
1200 `userid` ASC", __FUNCTION__, __LINE__);
1203 $cnt = SQL_NUMROWS($result);
1206 SQL_FREERESULT($result);
1212 // Determine waiting time for one URL
1213 function SURFBAR_DETERMINE_WAIT_TIME () {
1214 // Get fixed reload lock
1215 $fixed = SURFBAR_GET_FIXED_RELOAD();
1217 // Is the fixed reload time set?
1223 // Static time is default
1224 $time = getConfig('surfbar_static_time');
1226 // Which payment model do we have?
1227 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1228 // "Calculate" dynamic time
1229 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1236 // Changes the status of an URL from given to other
1237 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1238 // Make new status always lower-case
1239 $newStatus = strtolower($newStatus);
1241 // Get URL data for status comparison if missing
1242 if ((!is_array($data)) || (count($data) == '0')) {
1243 // Fetch missing URL data
1244 $data = SURFBAR_GET_URL_DATA($urlId);
1247 // Is the new status set?
1248 if ((!is_string($newStatus)) || (empty($newStatus))) {
1249 // Abort here, but fine!
1253 // Is the status like prevStatus is saying?
1254 if ($data[$urlId]['status'] != $prevStatus) {
1255 // No, then abort here
1260 // Update the status now
1261 // ---------- Comment out for debugging/developing member actions! ---------
1262 //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1263 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1264 // ---------- Comment out for debugging/developing member actions! ---------
1267 // ---------- Comment out for debugging/developing member actions! ---------
1268 //if (SQL_AFFECTEDROWS() != 1) {
1269 // // No, something went wrong
1272 // ---------- Comment out for debugging/developing member actions! ---------
1274 // Prepare content for notification routines
1275 $data[$urlId]['userid'] = $data[$urlId]['userid'];
1276 $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1277 $data[$urlId]['reward'] = translateComma(getConfig('surfbar_static_reward'));
1278 $data[$urlId]['costs'] = translateComma(getConfig('surfbar_static_costs'));
1280 // Do some dirty fixing here:
1281 if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1282 // Fix for template change
1283 $newStatus = 'continued';
1286 // Send admin notification
1287 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1289 // Send user notification
1290 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1296 // Calculate minimum value for dynamic payment model
1297 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1298 // Addon is zero by default
1302 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1305 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1308 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1311 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1314 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1316 // Get user's total URLs
1317 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1320 if ($totalUrls > 0) {
1321 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1323 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1330 // Calculate maximum value for dynamic payment model
1331 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1332 // Addon is zero by default
1339 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1342 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1345 $addon += abs($max * $percent * $totalUsers);
1348 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1351 $addon += abs($max * $percent * $totalUrls);
1357 // Calculate dynamic lock
1358 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1359 // Default lock is 30 seconds
1363 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1366 $addon = abs(log($onlineUsers / $addon + 1));
1372 // "Getter" for lock ids array
1373 function SURFBAR_GET_LOCK_IDS () {
1374 // Prepare some arrays
1379 // Get all id from locks within the timestamp
1380 $result = SQL_QUERY_ESC("SELECT `id`, `url_id`, UNIX_TIMESTAMP(`last_surfed`) AS last_surfed
1382 `{?_MYSQL_PREFIX?}_surfbar_locks`
1386 `id` ASC", array(getMemberId()),
1387 __FUNCTION__, __LINE__);
1390 while ($content = SQL_FETCHARRAY($result)) {
1392 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1394 // Skip entries that are too old
1395 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1397 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1399 // Add only if missing or bigger
1400 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1402 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1405 $IDs[$content['url_id']] = $content['last_surfed'];
1406 $USE[$content['url_id']] = $content['id'];
1410 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1412 // Ignore these old entries!
1413 $ignored[] = $content['url_id'];
1414 unset($IDs[$content['url_id']]);
1415 unset($USE[$content['url_id']]);
1420 SQL_FREERESULT($result);
1426 // "Getter" for maximum random number
1427 function SURFBAR_GET_MAX_RANDOM ($UIDs, $add) {
1428 // Count max availabe entries
1429 $result = SQL_QUERY("SELECT sbu.id AS cnt
1430 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1431 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1432 ON sbu.id=sbs.url_id
1433 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1435 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."
1436 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1439 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1442 $maxRand = SQL_NUMROWS($result);
1445 SQL_FREERESULT($result);
1451 // Load all URLs of the current user and return it as an array
1452 function SURFBAR_GET_USER_URLS () {
1457 $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
1458 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1459 WHERE u.userid=%s AND u.status != 'DELETED'
1461 array(getMemberId()), __FUNCTION__, __LINE__);
1463 // Are there entries?
1464 if (SQL_NUMROWS($result) > 0) {
1466 while ($row = SQL_FETCHARRAY($result)) {
1468 $URLs[$row['id']] = $row;
1473 SQL_FREERESULT($result);
1479 // "Getter" for member action array for given status
1480 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1482 $returnArray = array();
1484 // Get all assigned actions
1485 $result = SQL_QUERY_ESC("SELECT action FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1486 array($status), __FUNCTION__, __LINE__);
1488 // Some entries there?
1489 if (SQL_NUMROWS($result) > 0) {
1491 // @TODO This can be somehow rewritten
1492 while ($content = SQL_FETCHARRAY($result)) {
1493 $returnArray[] = $content['action'];
1498 SQL_FREERESULT($result);
1501 return $returnArray;
1504 // Reload to configured stop page
1505 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1506 // Internal or external?
1507 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1508 // Reload to internal page
1509 redirectToUrl('surfbar.php?frame=' . $page);
1511 // Reload to external page
1512 redirectToConfiguredUrl('surfbar_pause_url');
1516 // Determine next id for surfbar or get data for given id, always call this before you call other
1517 // getters below this function!!!
1518 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1519 // Default is no id and no random number
1524 if ($urlId == '0') {
1525 // Get array with lock ids
1526 $USE = SURFBAR_GET_LOCK_IDS();
1528 // Shall we add some URL ids to ignore?
1530 if (count($USE) > 0) {
1532 $add = " AND sbu.id NOT IN (";
1533 foreach ($USE as $url_id => $lid) {
1535 $add .= $url_id.',';
1538 // Add closing bracket
1539 $add = substr($add, 0, -1) . ')';
1542 // Determine depleted user account
1543 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1545 // Get maximum randomness factor
1546 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['userid'], $add);
1548 // If more than one URL can be called generate the random number!
1550 // Generate random number
1551 $randNum = mt_rand(0, ($maxRand - 1));
1554 // And query the database
1555 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1556 $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
1557 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1558 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1559 ON sbu.id=sbs.url_id
1560 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1562 WHERE sbu.userid NOT IN (".implode(',', $UIDs['userid']).") AND sbu.`status`='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$add."
1564 ORDER BY l.last_surfed ASC, sbu.id ASC
1566 array($randNum), __FUNCTION__, __LINE__
1569 // Get data from specified id number
1570 $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
1571 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1572 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1573 ON sbu.id=sbs.url_id
1574 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1576 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))
1578 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1582 // Is there an id number?
1583 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1584 if (SQL_NUMROWS($result) == 1) {
1586 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1587 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1588 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1590 // Determine waiting time
1591 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1593 // Is the last salt there?
1594 if (is_null($GLOBALS['surfbar_cache']['last_salt'])) {
1595 // Then repair it wit the static!
1596 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1597 $GLOBALS['surfbar_cache']['last_salt'] = '';
1600 // Fix missing last_surfed
1601 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1603 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1604 $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1607 // Get base/fixed reward and costs
1608 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1609 $GLOBALS['surfbar_cache']['costs'] = SURFBAR_DETERMINE_COSTS();
1610 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1612 // Only in dynamic model add the dynamic bonus!
1613 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1614 // Calculate dynamic reward/costs and add it
1615 $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1616 $GLOBALS['surfbar_cache']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1617 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1621 $nextId = SURFBAR_GET_ID();
1625 SQL_FREERESULT($result);
1628 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1632 // -----------------------------------------------------------------------------
1633 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1634 // THE $GLOBALS['surfbar_cache'] ARRAY!
1635 // -----------------------------------------------------------------------------
1637 // Initializes the surfbar
1638 function SURFBAR_INIT () {
1640 $GLOBALS['surfbar_cache'] = array();
1643 // Private getter for data elements
1644 function SURFBAR_GET_DATA ($element) {
1645 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1650 // Is the entry there?
1651 if (isset($GLOBALS['surfbar_cache'][$element])) {
1653 $data = $GLOBALS['surfbar_cache'][$element];
1654 } else { // END - if
1656 print_r($GLOBALS['surfbar_cache']);
1662 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1666 // Getter for reward from cache
1667 function SURFBAR_GET_REWARD () {
1668 // Get data element and return its contents
1669 return SURFBAR_GET_DATA('reward');
1672 // Getter for costs from cache
1673 function SURFBAR_GET_COSTS () {
1674 // Get data element and return its contents
1675 return SURFBAR_GET_DATA('costs');
1678 // Getter for URL from cache
1679 function SURFBAR_GET_URL () {
1680 // Get data element and return its contents
1681 return SURFBAR_GET_DATA('url');
1684 // Getter for salt from cache
1685 function SURFBAR_GET_SALT () {
1686 // Get data element and return its contents
1687 return SURFBAR_GET_DATA('salt');
1690 // Getter for id from cache
1691 function SURFBAR_GET_ID () {
1692 // Get data element and return its contents
1693 return SURFBAR_GET_DATA('id');
1696 // Getter for userid from cache
1697 function SURFBAR_GET_USERID () {
1698 // Get data element and return its contents
1699 return SURFBAR_GET_DATA('userid');
1702 // Getter for user reload locks
1703 function SURFBAR_GET_USER_LOCKS () {
1704 // Get data element and return its contents
1705 return SURFBAR_GET_DATA('user_locks');
1708 // Getter for reload time
1709 function SURFBAR_GET_RELOAD_TIME () {
1710 // Get data element and return its contents
1711 return SURFBAR_GET_DATA('time');
1714 // Getter for allowed views
1715 function SURFBAR_GET_VIEWS_ALLOWED () {
1716 // Get data element and return its contents
1717 return SURFBAR_GET_DATA('views_allowed');
1720 // Getter for fixed reload
1721 function SURFBAR_GET_FIXED_RELOAD () {
1722 // Get data element and return its contents
1723 return SURFBAR_GET_DATA('fixed_reload');
1726 // Getter for surf lock
1727 function SURFBAR_GET_SURF_LOCK () {
1728 // Get data element and return its contents
1729 return SURFBAR_GET_DATA('surf_lock');
1732 // Getter for new status
1733 function SURFBAR_GET_NEW_STATUS () {
1734 // Get data element and return its contents
1735 return SURFBAR_GET_DATA('new_status');