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 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
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 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
56 } elseif (!isUrlValid($url)) {
58 logDebugMessage(__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 logDebugMessage(__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 logDebugMessage(__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 logDebugMessage(__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 logDebugMessage(__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, $userid) {
88 } elseif (!isUrlValid($url)) {
91 } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
92 // URL already found in surfbar!
94 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
99 // Register the new URL
100 return SURFBAR_REGISTER_URL($url, $userid, '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)) && (!isAdmin())) {
171 } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
172 // URL already found in surfbar!
174 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
177 } elseif (''.($limit + 0).'' != ''.$limit.'') {
178 // Invalid amount entered
182 // Register the new URL
183 return SURFBAR_REGISTER_URL($url, getMemberId(), '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_GET_ARRAY_FROM_STATUS($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 .= loadTemplate('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 = secureString($formData['action']);
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 logDebugMessage(__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_y'] = '';
383 $urlData['limited_n'] = ' 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_y'] = ' checked="checked"';
390 $urlData['limited_n'] = '';
391 $urlData['limited'] = 'true';
395 // Load the form and display it
396 loadTemplate(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'] != 'Y') && ((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 'userid' ?
417 if ((!isset($urlData['userid'])) && (isset($urlData['userid']))) {
419 $urlData['userid'] = $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 // Has the URL or limit changed?
444 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
446 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",
447 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
456 // "Execute delete" function: Does nothing...
457 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
458 // Nothing special to do (see above function for such "special actions" to perform)
462 // -----------------------------------------------------------------------------
463 // Self-maintenance functions
464 // -----------------------------------------------------------------------------
467 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
468 // Handle URLs which limit has depleted so we can stop them
469 SURFBAR_HANDLE_DEPLETED_VIEWS();
471 // Handle low-points amounts
472 SURFBAR_HANDLE_LOW_POINTS();
474 // Handle URLs which limit has depleted
475 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
477 $urlArray = SURFBAR_GET_URL_DATA(0, 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
479 // Do we have some entries?
480 if (count($urlArray) > 0) {
482 foreach ($urlArray as $id => $urlData) {
486 // Rewrite array for next call
487 $urlData[$id] = $data;
490 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
495 // Alert users which have URLs booked and are low on points amount
496 function SURFBAR_HANDLE_LOW_POINTS () {
498 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
500 // "Walk" through all URLs
501 foreach ($userids['userid'] as $userid => $dummy) {
502 // Is the last notification far enougth away to notify again?
503 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
507 'low' => translateComma(getConfig('surfbar_warn_low_points')),
508 'points' => translateComma($userids['points'][$userid]),
509 'notified' => generateDateTime($userids['notified'][$userid]),
510 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
514 SURFBAR_NOTIFY_USER('low_points', $content);
516 // Update last notified
517 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET surfbar_low_notified=NOW() WHERE `userid`=%s LIMIT 1",
518 array($userid), __FUNCTION__, __LINE__);
524 // -----------------------------------------------------------------------------
526 // -----------------------------------------------------------------------------
529 // Looks up by an URL
530 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
531 // Now lookup that given URL by itself
532 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'id', 'ASC', 'id', sprintf(" AND `userid`=%s", bigintval($userid)));
535 return (count($urlArray) > 0);
538 // Load URL data by given search term and column
539 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'id', $order = 'id', $sort = 'ASC', $group = 'id', $add = '') {
540 // By default nothing is found
541 $GLOBALS['last_url_data'] = array();
543 // Is the column an id number?
544 if (($column == 'id') || ($column == 'userid')) {
545 // Extra secure input
546 $searchTerm = bigintval($searchTerm);
549 // If the column is 'id' there can be only one entry
551 if ($column == 'id') {
555 // Look up the record
556 $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
557 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
558 WHERE %s='%s'".$add."
561 array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
563 // Is there at least one record?
564 if (SQL_NUMROWS($result) > 0) {
566 while ($dataRow = SQL_FETCHARRAY($result)) {
567 // Shall we group these results?
568 if ($group == 'id') {
569 // Add the row by id as index
570 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
573 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
579 SQL_FREERESULT($result);
582 return $GLOBALS['last_url_data'];
585 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
586 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
587 // Make sure by the user registered URLs are always pending
588 if ($addMode == 'reg') {
593 $content = merge_array($extraFields, array(
595 'frametester' => generateFrametesterUrl($url),
600 // Is limit/reload set?
601 if (!isset($config['limit'])) {
602 $content['limit'] = '0';
604 if (!isset($config['reload'])) {
605 $content['reload'] = '0';
608 // Insert the URL into database
609 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
612 if ($content['insert_id'] == '0') {
613 // INSERT did not insert any data!
617 // Translate status and limit
618 $content['limit'] = translateSurfbarLimit($content['limit']);
620 // If in reg-mode we notify admin
621 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
622 // Notify admin even when he as unlocked an email
623 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
627 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
629 // Return the insert id
630 return $content['insert_id'];
633 // Inserts an url by given data array and return the insert id
634 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
636 $userid = bigintval($urlData['userid']);
639 if (empty($userid)) $userid = '0';
641 // Just run the insert query for now
642 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)",
650 ), __FUNCTION__, __LINE__
654 return SQL_INSERTID();
657 // Notify admin(s) with a selected message and content
658 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
659 // Prepare template name
660 $templateName = sprintf("admin_surfbar_%s", $messageType);
663 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
664 strtoupper($messageType)
667 // Is the subject line there?
668 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
669 // Set default subject if following eval() wents wrong
670 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
673 // Translate some data if present
674 if (isset($content['status'])) $content['status'] = translateSurfbarUrlStatus($content['status']);
675 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], 2);
676 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], 2);
677 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
678 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
679 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
681 // Send the notification out
682 return sendAdminNotification($subject, $templateName, $content, $content['userid']);
685 // Notify the user about the performed action
686 function SURFBAR_NOTIFY_USER ($messageType, $content) {
687 // Skip notification if userid is zero
688 if ($content['userid'] == '0') {
692 // Prepare template name
693 $templateName = sprintf("member_surfbar_%s", $messageType);
696 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
697 strtoupper($messageType)
700 // Is the subject line there?
701 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
702 // Set default subject if following eval() wents wrong
703 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
706 // Translate some data if present
707 if (isset($content['status'])) $content['status'] = translateSurfbarUrlStatus($content['status']);
708 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], 2);
709 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], 2);
710 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
711 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
712 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
715 $mailText = loadEmailTemplate($templateName, $content, $content['userid']);
718 return sendEmail($content['userid'], $subject, $mailText);
721 // Translates the limit
722 function translateSurfbarLimit ($limit) {
726 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
729 $return = translateComma($limit);
736 // Translate the URL status
737 function translateSurfbarUrlStatus ($status) {
738 // Create constant name
739 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
742 $statusTranslated = getMessage($constantName);
745 return $statusTranslated;
749 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
750 // Static values are default
751 $reward = getConfig('surfbar_static_reward');
753 // Do we have static or dynamic?
754 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
755 // "Calculate" dynamic reward
757 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
759 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
768 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
769 // Static costs is default
770 $costs = getConfig('surfbar_static_costs');
772 // Do we have static or dynamic?
773 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
774 // "Calculate" dynamic costs
776 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
778 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
786 // "Calculate" dynamic add
787 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
788 // Get min/max values
789 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
790 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
792 // "Calculate" dynamic part and return it
793 return mt_rand($min, $max);
796 // Determine right template name
797 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
798 // Default is the frameset
799 $templateName = "surfbar_frameset";
801 // Any frame set? ;-)
802 if (isGetRequestParameterSet('frame')) {
803 // Use the frame as a template name part... ;-)
804 $templateName = sprintf("surfbar_frame_%s",
805 getRequestParameter('frame')
810 return $templateName;
813 // Check if the "reload lock" of the current user is full, call this function
814 // before you call SURFBAR_CHECK_RELOAD_LOCK().
815 function SURFBAR_CHECK_RELOAD_FULL() {
819 // Cache static reload lock
820 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
821 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
823 // Do we have dynamic model?
824 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
825 // "Calculate" dynamic lock
826 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
830 $result = SQL_QUERY_ESC("SELECT
833 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
835 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
840 (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.last_surfed) AND
842 ((UNIX_TIMESTAMP(l.last_surfed) - u.fixed_reload) < 0 AND u.fixed_reload > 0) OR
846 array(getMemberId()), __FUNCTION__, __LINE__
850 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
853 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
854 // Then fix it to zero!
855 $GLOBALS['surfbar_cache']['user_locks'] = '0';
859 SQL_FREERESULT($result);
862 $total = SURFBAR_GET_TOTAL_URLS();
864 // Do we have some URLs in lock? Admins can always surf on own URLs!
865 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
866 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
872 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
873 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
874 // Determine depleted user account
875 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
877 // If we dont get any user ids back, there are no URLs
878 if (count($userids['userid']) == '0') {
879 // No user ids found, no URLs!
883 // Is the exlude userid set?
884 if ($excludeUserId > 0) {
886 $userids['userid'][$excludeUserId] = $excludeUserId;
889 // Get amount from database
890 $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
891 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
892 WHERE `userid` NOT IN (".implode(', ', $userids['userid']).") AND `status`='%s'",
893 array($status), __FUNCTION__, __LINE__
897 list($cnt) = SQL_FETCHROW($result);
900 SQL_FREERESULT($result);
906 // Check wether the user is allowed to book more URLs
907 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
908 // Is this admin and userid is zero or does the user has some URLs left to book?
909 return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getConfig('surfbar_max_order')));
912 // Get total amount of URLs of given status for current user
913 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '',$exclude = '') {
914 // Is the user 0 and user is logged in?
915 if (($userid == '0') && (isMember())) {
916 // Then use this userid
917 $userid = getMemberId();
918 } elseif ($userid == '0') {
920 return (getConfig('surfbar_max_order') + 1);
923 // Default is all URLs
926 // Is the status set?
927 if (is_array($status)) {
928 // Only URLs with these status
929 $add = sprintf(" AND `status` IN('%s')", implode("','", $status));
930 } elseif (!empty($status)) {
931 // Only URLs with this status
932 $add = sprintf(" AND `status`='%s'", $status);
933 } elseif (is_array($exclude)) {
934 // Exclude URLs with these status
935 $add = sprintf(" AND `status` NOT IN('%s')", implode("','", $exclude));
936 } elseif (!empty($exclude)) {
937 // Exclude URLs with this status
938 $add = sprintf(" AND `status` != '%s'", $exclude);
941 // Get amount from database
942 $cnt = countSumTotalData($userid, 'surfbar_urls', 'id', 'userid', true, $add);
948 // Generate a validation code for the given id number
949 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
950 // @TODO Invalid salt should be refused
951 $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
953 // Get code length from config
954 $length = getConfig('code_length');
957 if ($length == '0') $length = 10;
959 // Generate a code until the length matches
961 while (strlen($valCode) != $length) {
964 // Generate random hashed string
965 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
966 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
969 $GLOBALS['surfbar_cache']['salt'] = $salt;
970 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
973 // ... and now the validation code
974 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getMemberId());
975 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
978 // Hash it with md5() and salt it with the random string
979 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
981 // Finally encrypt it PGP-like and return it
982 $valHashedCode = encodeHashForCookie($hashedCode);
984 // Return hashed value
985 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
986 return $valHashedCode;
989 // Check validation code
990 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
992 $urlId = bigintval($urlId);
994 // Now generate the code again
995 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
997 // Return result of checking hashes and salts
998 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
999 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('last_salt').'+++', false);
1000 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
1003 // Lockdown the userid/id combination (reload lock)
1004 function SURFBAR_LOCKDOWN_ID ($urlId) {
1005 //* DEBUG: */ outputHtml('LOCK!');
1006 ///* DEBUG: */ return;
1007 // Just add it to the database
1008 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`userid`, `url_id`) VALUES (%s, %s)",
1009 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1011 // Remove the salt from database
1012 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1013 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1016 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1017 function SURFBAR_PAY_POINTS () {
1018 // Remove it from the URL owner
1019 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1020 if (SURFBAR_GET_USERID() > 0) {
1021 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1024 // Book it to the user
1025 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1026 addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getMemberId(), SURFBAR_GET_DATA('reward'));
1029 // Updates the statistics of current URL/userid
1030 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1034 // Get allowed views
1035 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1037 // Do we have a limit?
1039 // Then count views_max down!
1040 $add .= ", `views_max`=`views_max`-1";
1044 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `views_total`=`views_total`+1".$add." WHERE `id`=%s LIMIT 1",
1045 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1047 // Update the stats entry
1048 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `count`=`count`+1 WHERE `userid`=%s AND `url_id`=%s LIMIT 1",
1049 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1051 // Was that update okay?
1052 if (SQL_AFFECTEDROWS() < 1) {
1053 // No, then insert entry
1054 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1055 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1058 // Update total/daily/weekly/monthly counter
1059 incrementConfigEntry('surfbar_total_counter');
1060 incrementConfigEntry('surfbar_daily_counter');
1061 incrementConfigEntry('surfbar_weekly_counter');
1062 incrementConfigEntry('surfbar_monthly_counter');
1064 // Update config as well
1065 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1068 // Update the salt for validation and statistics
1069 function SURFBAR_UPDATE_SALT_STATS () {
1070 // Update statistics record
1071 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1073 // Simply store the salt from cache away in database...
1074 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `last_salt`='%s' WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1075 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getMemberId()), __FUNCTION__, __LINE__);
1078 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1081 if (SQL_AFFECTEDROWS() < 1) {
1082 // Insert missing entry!
1083 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`url_id`, `userid`, `last_salt`) VALUES (%s, %s, '%s')",
1084 array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1088 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1090 // Return if the update was okay
1091 return (SQL_AFFECTEDROWS() == 1);
1094 // Check if the reload lock is active for given id
1095 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1096 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1098 $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1100 `{?_MYSQL_PREFIX?}_surfbar_locks`
1102 `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1106 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1110 list($cnt) = SQL_FETCHROW($result);
1113 SQL_FREERESULT($result);
1116 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1120 // Determine which user hash no more points left
1121 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1124 'userid' => array(),
1125 'points' => array(),
1126 'notified' => array(),
1129 // Do we have a current user id?
1130 if ((isMember()) && ($limit == '0')) {
1131 // Then add this as well
1132 $userids['userid'][getMemberId()] = getMemberId();
1133 $userids['points'][getMemberId()] = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
1134 $userids['notified'][getMemberId()] = '0';
1136 // Get all userid except logged in one
1137 $result = SQL_QUERY_ESC("SELECT
1138 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1140 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1142 `{?_MYSQL_PREFIX?}_user_data` AS d
1146 u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1151 array(getMemberId()), __FUNCTION__, __LINE__);
1154 $result = SQL_QUERY("SELECT
1155 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1157 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1159 `{?_MYSQL_PREFIX?}_user_data` AS d
1167 u.userid ASC", __FUNCTION__, __LINE__);
1171 while ($content = SQL_FETCHARRAY($result)) {
1173 $points = countSumTotalData($content['userid'], 'user_points', 'points') - countSumTotalData($content['userid'], 'user_data', 'used_points');
1174 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']},points={$points}", false);
1176 // Shall we add this to ignore?
1177 if ($points <= $limit) {
1179 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']} has depleted points amount!", false);
1180 $userids['userid'][$content['userid']] = $content['userid'];
1181 $userids['points'][$content['userid']] = $points;
1182 $userids['notified'][$content['userid']] = $content['notified'];
1187 SQL_FREERESULT($result);
1190 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($userids)." (with own userid=".getMemberId().')', false);
1196 // Determine how many users are Online in surfbar
1197 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1198 // Count all users in surfbar modue and return the value
1199 $result = SQL_QUERY("SELECT
1202 `{?_MYSQL_PREFIX?}_surfbar_stats`
1204 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`last_surfed`)) <= {?online_timeout?}
1206 `userid` ASC", __FUNCTION__, __LINE__);
1209 $cnt = SQL_NUMROWS($result);
1212 SQL_FREERESULT($result);
1218 // Determine waiting time for one URL
1219 function SURFBAR_DETERMINE_WAIT_TIME () {
1220 // Get fixed reload lock
1221 $fixed = SURFBAR_GET_FIXED_RELOAD();
1223 // Is the fixed reload time set?
1229 // Static time is default
1230 $time = getConfig('surfbar_static_time');
1232 // Which payment model do we have?
1233 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1234 // "Calculate" dynamic time
1235 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1242 // Changes the status of an URL from given to other
1243 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1244 // Make new status always lower-case
1245 $newStatus = strtolower($newStatus);
1247 // Get URL data for status comparison if missing
1248 if ((!is_array($data)) || (count($data) == '0')) {
1249 // Fetch missing URL data
1250 $data = SURFBAR_GET_URL_DATA($urlId);
1253 // Is the new status set?
1254 if ((!is_string($newStatus)) || (empty($newStatus))) {
1255 // Abort here, but fine!
1259 // Is the status like prevStatus is saying?
1260 if ($data[$urlId]['status'] != $prevStatus) {
1261 // No, then abort here
1266 // Update the status now
1267 // ---------- Comment out for debugging/developing member actions! ---------
1268 //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1269 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1270 // ---------- Comment out for debugging/developing member actions! ---------
1273 // ---------- Comment out for debugging/developing member actions! ---------
1274 //if (SQL_AFFECTEDROWS() != 1) {
1275 // // No, something went wrong
1278 // ---------- Comment out for debugging/developing member actions! ---------
1280 // Prepare content for notification routines
1281 $data[$urlId]['userid'] = $data[$urlId]['userid'];
1282 $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1283 $data[$urlId]['reward'] = translateComma(getConfig('surfbar_static_reward'));
1284 $data[$urlId]['costs'] = translateComma(getConfig('surfbar_static_costs'));
1286 // Do some dirty fixing here:
1287 if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1288 // Fix for template change
1289 $newStatus = 'continued';
1292 // Send admin notification
1293 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1295 // Send user notification
1296 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1302 // Calculate minimum value for dynamic payment model
1303 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1304 // Addon is zero by default
1308 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1311 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1314 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1317 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1320 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1322 // Get user's total URLs
1323 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1326 if ($totalUrls > 0) {
1327 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1329 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1336 // Calculate maximum value for dynamic payment model
1337 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1338 // Addon is zero by default
1345 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1348 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1351 $addon += abs($max * $percent * $totalUsers);
1354 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1357 $addon += abs($max * $percent * $totalUrls);
1363 // Calculate dynamic lock
1364 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1365 // Default lock is 30 seconds
1369 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1372 $addon = abs(log($onlineUsers / $addon + 1));
1378 // "Getter" for lock ids array
1379 function SURFBAR_GET_LOCK_IDS () {
1380 // Prepare some arrays
1385 // Get all id from locks within the timestamp
1386 $result = SQL_QUERY_ESC("SELECT `id`, `url_id`, UNIX_TIMESTAMP(`last_surfed`) AS last_surfed
1388 `{?_MYSQL_PREFIX?}_surfbar_locks`
1392 `id` ASC", array(getMemberId()),
1393 __FUNCTION__, __LINE__);
1396 while ($content = SQL_FETCHARRAY($result)) {
1398 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1400 // Skip entries that are too old
1401 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1405 // Add only if missing or bigger
1406 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1408 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1411 $IDs[$content['url_id']] = $content['last_surfed'];
1412 $USE[$content['url_id']] = $content['id'];
1416 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1418 // Ignore these old entries!
1419 $ignored[] = $content['url_id'];
1420 unset($IDs[$content['url_id']]);
1421 unset($USE[$content['url_id']]);
1426 SQL_FREERESULT($result);
1432 // "Getter" for maximum random number
1433 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1434 // Count max availabe entries
1435 $result = SQL_QUERY("SELECT sbu.id AS cnt
1436 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1437 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1438 ON sbu.id=sbs.url_id
1439 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1441 WHERE sbu.userid NOT IN (".implode(',', $userids).") AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0)) AND sbu.`status`='ACTIVE'".$add."
1442 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1445 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1448 $maxRand = SQL_NUMROWS($result);
1451 SQL_FREERESULT($result);
1457 // Load all URLs of the current user and return it as an array
1458 function SURFBAR_GET_USER_URLS () {
1463 $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
1464 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1465 WHERE u.userid=%s AND u.status != 'DELETED'
1467 array(getMemberId()), __FUNCTION__, __LINE__);
1469 // Are there entries?
1470 if (SQL_NUMROWS($result) > 0) {
1472 while ($row = SQL_FETCHARRAY($result)) {
1474 $URLs[$row['id']] = $row;
1479 SQL_FREERESULT($result);
1485 // "Getter" for member action array for given status
1486 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1488 $returnArray = array();
1490 // Get all assigned actions
1491 $result = SQL_QUERY_ESC("SELECT action FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1492 array($status), __FUNCTION__, __LINE__);
1494 // Some entries there?
1495 if (SQL_NUMROWS($result) > 0) {
1497 // @TODO This can be somehow rewritten
1498 while ($content = SQL_FETCHARRAY($result)) {
1499 $returnArray[] = $content['action'];
1504 SQL_FREERESULT($result);
1507 return $returnArray;
1510 // Reload to configured stop page
1511 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1512 // Internal or external?
1513 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1514 // Reload to internal page
1515 redirectToUrl('surfbar.php?frame=' . $page);
1517 // Reload to external page
1518 redirectToConfiguredUrl('surfbar_pause_url');
1522 // Determine next id for surfbar or get data for given id, always call this before you call other
1523 // getters below this function!!!
1524 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1525 // Default is no id and no random number
1530 if ($urlId == '0') {
1531 // Get array with lock ids
1532 $USE = SURFBAR_GET_LOCK_IDS();
1534 // Shall we add some URL ids to ignore?
1536 if (count($USE) > 0) {
1538 $add = " AND sbu.id NOT IN (";
1539 foreach ($USE as $url_id => $lid) {
1541 $add .= $url_id.',';
1544 // Add closing bracket
1545 $add = substr($add, 0, -1) . ')';
1548 // Determine depleted user account
1549 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1551 // Get maximum randomness factor
1552 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['userid'], $add);
1554 // If more than one URL can be called generate the random number!
1556 // Generate random number
1557 $randNum = mt_rand(0, ($maxRand - 1));
1560 // And query the database
1561 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1562 $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
1563 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1564 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1565 ON sbu.id=sbs.url_id
1566 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1568 WHERE sbu.userid NOT IN (".implode(',', $userids['userid']).") AND sbu.`status`='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$add."
1570 ORDER BY l.last_surfed ASC, sbu.id ASC
1572 array($randNum), __FUNCTION__, __LINE__
1575 // Get data from specified id number
1576 $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
1577 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1578 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1579 ON sbu.id=sbs.url_id
1580 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1582 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))
1584 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1588 // Is there an id number?
1589 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1590 if (SQL_NUMROWS($result) == 1) {
1592 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1593 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1594 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1596 // Determine waiting time
1597 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1599 // Is the last salt there?
1600 if (is_null($GLOBALS['surfbar_cache']['last_salt'])) {
1601 // Then repair it wit the static!
1602 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1603 $GLOBALS['surfbar_cache']['last_salt'] = '';
1606 // Fix missing last_surfed
1607 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1609 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1610 $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1613 // Get base/fixed reward and costs
1614 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1615 $GLOBALS['surfbar_cache']['costs'] = SURFBAR_DETERMINE_COSTS();
1616 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1618 // Only in dynamic model add the dynamic bonus!
1619 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1620 // Calculate dynamic reward/costs and add it
1621 $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1622 $GLOBALS['surfbar_cache']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1623 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1627 $nextId = SURFBAR_GET_ID();
1631 SQL_FREERESULT($result);
1634 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1638 // -----------------------------------------------------------------------------
1639 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1640 // THE $GLOBALS['surfbar_cache'] ARRAY!
1641 // -----------------------------------------------------------------------------
1643 // Initializes the surfbar
1644 function SURFBAR_INIT () {
1646 $GLOBALS['surfbar_cache'] = array();
1649 // Private getter for data elements
1650 function SURFBAR_GET_DATA ($element) {
1651 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1656 // Is the entry there?
1657 if (isset($GLOBALS['surfbar_cache'][$element])) {
1659 $data = $GLOBALS['surfbar_cache'][$element];
1660 } else { // END - if
1662 print_r($GLOBALS['surfbar_cache']);
1668 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1672 // Getter for reward from cache
1673 function SURFBAR_GET_REWARD () {
1674 // Get data element and return its contents
1675 return SURFBAR_GET_DATA('reward');
1678 // Getter for costs from cache
1679 function SURFBAR_GET_COSTS () {
1680 // Get data element and return its contents
1681 return SURFBAR_GET_DATA('costs');
1684 // Getter for URL from cache
1685 function SURFBAR_GET_URL () {
1686 // Get data element and return its contents
1687 return SURFBAR_GET_DATA('url');
1690 // Getter for salt from cache
1691 function SURFBAR_GET_SALT () {
1692 // Get data element and return its contents
1693 return SURFBAR_GET_DATA('salt');
1696 // Getter for id from cache
1697 function SURFBAR_GET_ID () {
1698 // Get data element and return its contents
1699 return SURFBAR_GET_DATA('id');
1702 // Getter for userid from cache
1703 function SURFBAR_GET_USERID () {
1704 // Get data element and return its contents
1705 return SURFBAR_GET_DATA('userid');
1708 // Getter for user reload locks
1709 function SURFBAR_GET_USER_LOCKS () {
1710 // Get data element and return its contents
1711 return SURFBAR_GET_DATA('user_locks');
1714 // Getter for reload time
1715 function SURFBAR_GET_RELOAD_TIME () {
1716 // Get data element and return its contents
1717 return SURFBAR_GET_DATA('time');
1720 // Getter for allowed views
1721 function SURFBAR_GET_VIEWS_ALLOWED () {
1722 // Get data element and return its contents
1723 return SURFBAR_GET_DATA('views_allowed');
1726 // Getter for fixed reload
1727 function SURFBAR_GET_FIXED_RELOAD () {
1728 // Get data element and return its contents
1729 return SURFBAR_GET_DATA('fixed_reload');
1732 // Getter for surf lock
1733 function SURFBAR_GET_SURF_LOCK () {
1734 // Get data element and return its contents
1735 return SURFBAR_GET_DATA('surf_lock');
1738 // Getter for new status
1739 function SURFBAR_GET_NEW_STATUS () {
1740 // Get data element and return its contents
1741 return SURFBAR_GET_DATA('new_status');