2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/31/2008 *
4 * =============== Last change: 08/31/2008 *
6 * -------------------------------------------------------------------- *
7 * File : surfbar_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for surfbar *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer die Surfbar *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 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, getUserId())) {
171 // URL already found in surfbar!
173 } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getUserId())) {
176 } elseif (''.($limit + 0).'' != ''.$limit.'') {
177 // Invalid amount entered
181 // Register the new URL
182 return SURFBAR_REGISTER_URL($url, getUserId(), '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 = SQL_ESCAPE(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 // Translate URLs for testing
442 $url1 = compileCode($urlData['url']);
443 $url2 = compileCode($urlData['edit']['url']);
445 // Has the URL or limit changed?
447 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
449 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",
450 array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
459 // "Execute delete" function: Does nothing...
460 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
461 // Nothing special to do (see above function for such "special actions" to perform)
465 // -----------------------------------------------------------------------------
466 // Self-maintenance functions
467 // -----------------------------------------------------------------------------
470 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
471 // Handle URLs which limit has depleted so we can stop them
472 SURFBAR_HANDLE_DEPLETED_VIEWS();
474 // Handle low-points amounts
475 SURFBAR_HANDLE_LOW_POINTS();
477 // Handle URLs which limit has depleted
478 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
480 $urlArray = SURFBAR_GET_URL_DATA(0, 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
482 // Do we have some entries?
483 if (count($urlArray) > 0) {
485 foreach ($urlArray as $id => $urlData) {
489 // Rewrite array for next call
490 $urlData[$id] = $data;
493 SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
498 // Alert users which have URLs booked and are low on points amount
499 function SURFBAR_HANDLE_LOW_POINTS () {
501 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
503 // "Walk" through all URLs
504 foreach ($UIDs['userid'] as $userid => $dummy) {
505 // Is the last notification far enougth away to notify again?
506 if ((time() - $UIDs['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
510 'low' => translateComma(getConfig('surfbar_warn_low_points')),
511 'points' => translateComma($UIDs['points'][$userid]),
512 'notified' => generateDateTime($UIDs['notified'][$userid]),
513 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
517 SURFBAR_NOTIFY_USER('low_points', $content);
519 // Update last notified
520 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET surfbar_low_notified=NOW() WHERE `userid`=%s LIMIT 1",
521 array($userid), __FUNCTION__, __LINE__);
527 // -----------------------------------------------------------------------------
529 // -----------------------------------------------------------------------------
532 // Looks up by an URL
533 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
534 // Now lookup that given URL by itself
535 $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'id', 'ASC', 'id', sprintf(" AND `userid`=%s", bigintval($userid)));
538 return (count($urlArray) > 0);
541 // Load URL data by given search term and column
542 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'id', $order = 'id', $sort = 'ASC', $group = 'id', $add = '') {
543 // By default nothing is found
544 $GLOBALS['last_url_data'] = array();
546 // Is the column an id number?
547 if (($column == 'id') || ($column == 'userid')) {
548 // Extra secure input
549 $searchTerm = bigintval($searchTerm);
552 // If the column is 'id' there can be only one entry
554 if ($column == 'id') {
558 // Look up the record
559 $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
560 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
561 WHERE %s='%s'".$add."
564 array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
566 // Is there at least one record?
567 if (SQL_NUMROWS($result) > 0) {
569 while ($dataRow = SQL_FETCHARRAY($result)) {
570 // Shall we group these results?
571 if ($group == 'id') {
572 // Add the row by id as index
573 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
576 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
582 SQL_FREERESULT($result);
585 return $GLOBALS['last_url_data'];
588 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
589 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
590 // Make sure by the user registered URLs are always pending
591 if ($addMode == 'reg') {
596 $content = merge_array($extraFields, array(
598 'frametester' => generateFrametesterUrl($url),
603 // Is limit/reload set?
604 if (!isset($config['limit'])) {
605 $content['limit'] = 0;
607 if (!isset($config['reload'])) {
608 $content['reload'] = 0;
611 // Insert the URL into database
612 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
615 if ($content['insert_id'] == 0) {
616 // INSERT did not insert any data!
620 // Translate status and limit
621 $content['limit'] = translateSurfbarLimit($content['limit']);
623 // If in reg-mode we notify admin
624 if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
625 // Notify admin even when he as unlocked an email
626 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
630 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
632 // Return the insert id
633 return $content['insert_id'];
636 // Inserts an url by given data array and return the insert id
637 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
639 $userid = bigintval($urlData['userid']);
642 if (empty($userid)) $userid = 0;
644 // Just run the insert query for now
645 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)",
653 ), __FUNCTION__, __LINE__
657 return SQL_INSERTID();
660 // Notify admin(s) with a selected message and content
661 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
662 // Prepare template name
663 $templateName = sprintf("admin_surfbar_%s", $messageType);
666 $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
667 strtoupper($messageType)
670 // Is the subject line there?
671 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
672 // Set default subject if following eval() wents wrong
673 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
676 // Translate some data if present
677 if (isset($content['status'])) $content['status'] = translateSurfbarUrlStatus($content['status']);
678 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], 2);
679 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], 2);
680 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
681 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
682 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
684 // Send the notification out
685 return sendAdminNotification($subject, $templateName, $content, $content['userid']);
688 // Notify the user about the performed action
689 function SURFBAR_NOTIFY_USER ($messageType, $content) {
690 // Skip notification if userid is zero
691 if ($content['userid'] == 0) {
695 // Prepare template name
696 $templateName = sprintf("member_surfbar_%s", $messageType);
699 $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
700 strtoupper($messageType)
703 // Is the subject line there?
704 if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
705 // Set default subject if following eval() wents wrong
706 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
709 // Translate some data if present
710 if (isset($content['status'])) $content['status'] = translateSurfbarUrlStatus($content['status']);
711 if (isset($content['registered'])) $content['registered'] = generateDateTime($content['registered'], 2);
712 if (isset($content['last_locked'])) $content['last_locked'] = generateDateTime($content['last_locked'], 2);
713 if (isset($content['views_total'])) $content['views_total'] = translateComma($content['views_total']);
714 if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
715 if (isset($content['views_max'])) $content['views_max'] = translateComma($content['views_max']);
718 $mailText = loadEmailTemplate($templateName, $content, $content['userid']);
721 return sendEmail($content['userid'], $subject, $mailText);
724 // Translates the limit
725 function translateSurfbarLimit ($limit) {
729 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
732 $return = translateComma($limit);
739 // Translate the URL status
740 function translateSurfbarUrlStatus ($status) {
741 // Create constant name
742 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
744 // Set default translated status
745 $statusTranslated = '!'.$constantName.'!';
747 // Is the constant there?
748 if (defined($constantName)) {
749 // Then get it's value
750 $statusTranslated = constant($constantName);
754 return $statusTranslated;
758 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
759 // Static values are default
760 $reward = getConfig('surfbar_static_reward');
762 // Do we have static or dynamic?
763 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
764 // "Calculate" dynamic reward
766 $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
768 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
777 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
778 // Static costs is default
779 $costs = getConfig('surfbar_static_costs');
781 // Do we have static or dynamic?
782 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
783 // "Calculate" dynamic costs
785 $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
787 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
795 // "Calculate" dynamic add
796 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
797 // Get min/max values
798 $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
799 $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
801 // "Calculate" dynamic part and return it
802 return mt_rand($min, $max);
805 // Determine right template name
806 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
807 // Default is the frameset
808 $templateName = "surfbar_frameset";
810 // Any frame set? ;-)
811 if (isGetRequestElementSet('frame')) {
812 // Use the frame as a template name part... ;-)
813 $templateName = sprintf("surfbar_frame_%s",
814 getRequestElement('frame')
819 return $templateName;
822 // Check if the "reload lock" of the current user is full, call this function
823 // before you call SURFBAR_CHECK_RELOAD_LOCK().
824 function SURFBAR_CHECK_RELOAD_FULL() {
828 // Cache static reload lock
829 $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
830 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
832 // Do we have dynamic model?
833 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
834 // "Calculate" dynamic lock
835 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
839 $result = SQL_QUERY_ESC("SELECT
842 `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
844 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
848 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)
850 array(getUserId()), __FUNCTION__, __LINE__
854 list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
857 if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
858 // Then fix it to zero!
859 $GLOBALS['surfbar_cache']['user_locks'] = 0;
863 SQL_FREERESULT($result);
866 $total = SURFBAR_GET_TOTAL_URLS();
868 // Do we have some URLs in lock? Admins can always surf on own URLs!
869 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
870 $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
876 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
877 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = 0) {
878 // Determine depleted user account
879 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
881 // If we dont get any user ids back, there are no URLs
882 if (count($UIDs['userid']) == 0) {
883 // No user ids found, no URLs!
887 // Is the exlude userid set?
888 if ($excludeUserId > 0) {
890 $UIDs['userid'][$excludeUserId] = $excludeUserId;
893 // Get amount from database
894 $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
895 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
896 WHERE `userid` NOT IN (".implode(', ', $UIDs['userid']).") AND `status`='%s'",
897 array($status), __FUNCTION__, __LINE__
901 list($cnt) = SQL_FETCHROW($result);
904 SQL_FREERESULT($result);
910 // Check wether the user is allowed to book more URLs
911 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid=0) {
912 // Is this admin and userid is zero or does the user has some URLs left to book?
913 return ((($userid == 0) && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array("REJECTED")) < getConfig('surfbar_max_order')));
916 // Get total amount of URLs of given status for current user
917 function SURFBAR_GET_TOTAL_USER_URLS ($userid=0, $status = '',$exclude = '') {
918 // Is the user 0 and user is logged in?
919 if (($userid == 0) && (isMember())) {
920 // Then use this userid
921 $userid = getUserId();
922 } elseif ($userid == 0) {
924 return (getConfig('surfbar_max_order') + 1);
927 // Default is all URLs
930 // Is the status set?
931 if (is_array($status)) {
932 // Only URLs with these status
933 $add = sprintf(" AND `status` IN('%s')", implode("','", $status));
934 } elseif (!empty($status)) {
935 // Only URLs with this status
936 $add = sprintf(" AND `status`='%s'", $status);
937 } elseif (is_array($exclude)) {
938 // Exclude URLs with these status
939 $add = sprintf(" AND `status` NOT IN('%s')", implode("','", $exclude));
940 } elseif (!empty($exclude)) {
941 // Exclude URLs with this status
942 $add = sprintf(" AND `status` != '%s'", $exclude);
945 // Get amount from database
946 $cnt = countSumTotalData($userid, 'surfbar_urls', 'id', 'userid', true, $add);
952 // Generate a validation code for the given id number
953 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
954 // @TODO Invalid salt should be refused
955 $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
957 // Get code length from config
958 $length = getConfig('code_length');
961 if ($length == 0) $length = 10;
963 // Generate a code until the length matches
965 while (strlen($valCode) != $length) {
968 // Generate random hashed string
969 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
970 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
973 $GLOBALS['surfbar_cache']['salt'] = $salt;
974 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
977 // ... and now the validation code
978 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getUserId());
979 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
982 // Hash it with md5() and salt it with the random string
983 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
985 // Finally encrypt it PGP-like and return it
986 $valHashedCode = generatePassString($hashedCode);
988 // Return hashed value
989 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
990 return $valHashedCode;
993 // Check validation code
994 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
996 $urlId = bigintval($urlId);
998 // Now generate the code again
999 $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1001 // Return result of checking hashes and salts
1002 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
1003 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('last_salt').'+++', false);
1004 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
1007 // Lockdown the userid/id combination (reload lock)
1008 function SURFBAR_LOCKDOWN_ID ($urlId) {
1009 //* DEBUG: */ outputHtml('LOCK!');
1010 ///* DEBUG: */ return;
1011 // Just add it to the database
1012 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`userid`, `url_id`) VALUES (%s, %s)",
1013 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1015 // Remove the salt from database
1016 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1017 array(bigintval($urlId), getUserId()), __FUNCTION__, __LINE__);
1020 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1021 function SURFBAR_PAY_POINTS () {
1022 // Remove it from the URL owner
1023 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1024 if (SURFBAR_GET_USERID() > 0) {
1025 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1028 // Book it to the user
1029 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getUserId().',reward='.SURFBAR_GET_REWARD().'', false);
1030 addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getUserId(), SURFBAR_GET_DATA('reward'));
1033 // Updates the statistics of current URL/userid
1034 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1038 // Get allowed views
1039 $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1041 // Do we have a limit?
1043 // Then count views_max down!
1044 $add .= ", `views_max`=`views_max`-1";
1048 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `views_total`=`views_total`+1".$add." WHERE `id`=%s LIMIT 1",
1049 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1051 // Update the stats entry
1052 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `count`=`count`+1 WHERE `userid`=%s AND `url_id`=%s LIMIT 1",
1053 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1055 // Was that update okay?
1056 if (SQL_AFFECTEDROWS() < 1) {
1057 // No, then insert entry
1058 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1059 array(getUserId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1062 // Update total/daily/weekly/monthly counter
1063 incrementConfigEntry('surfbar_total_counter');
1064 incrementConfigEntry('surfbar_daily_counter');
1065 incrementConfigEntry('surfbar_weekly_counter');
1066 incrementConfigEntry('surfbar_monthly_counter');
1068 // Update config as well
1069 updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1072 // Update the salt for validation and statistics
1073 function SURFBAR_UPDATE_SALT_STATS () {
1074 // Update statistics record
1075 SURFBAR_UPDATE_INSERT_STATS_RECORD();
1077 // Simply store the salt from cache away in database...
1078 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `last_salt`='%s' WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1079 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getUserId()), __FUNCTION__, __LINE__);
1082 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getUserId().'', false);
1085 if (SQL_AFFECTEDROWS() < 1) {
1086 // Insert missing entry!
1087 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`url_id`, `userid`, `last_salt`) VALUES (%s, %s, '%s')",
1088 array(SURFBAR_GET_ID(), getUserId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1092 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1094 // Return if the update was okay
1095 return (SQL_AFFECTEDROWS() == 1);
1098 // Check if the reload lock is active for given id
1099 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1100 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1102 $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1104 `{?_MYSQL_PREFIX?}_surfbar_locks`
1106 `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1110 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1114 list($cnt) = SQL_FETCHROW($result);
1117 SQL_FREERESULT($result);
1120 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1124 // Determine which user hash no more points left
1125 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1128 'userid' => array(),
1129 'points' => array(),
1130 'notified' => array(),
1133 // Do we have a current user id?
1134 if ((isMember()) && ($limit == 0)) {
1135 // Then add this as well
1136 $UIDs['userid'][getUserId()] = getUserId();
1137 $UIDs['points'][getUserId()] = countSumTotalData(getUserId(), 'user_points', 'points') - countSumTotalData(getUserId(), 'user_data', 'used_points');
1138 $UIDs['notified'][getUserId()] = 0;
1140 // Get all userid except logged in one
1141 $result = SQL_QUERY_ESC("SELECT
1142 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1144 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1146 `{?_MYSQL_PREFIX?}_user_data` AS d
1150 u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1155 array(getUserId()), __FUNCTION__, __LINE__);
1158 $result = SQL_QUERY("SELECT
1159 u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1161 `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1163 `{?_MYSQL_PREFIX?}_user_data` AS d
1171 u.userid ASC", __FUNCTION__, __LINE__);
1175 while ($content = SQL_FETCHARRAY($result)) {
1177 $points = countSumTotalData($content['userid'], 'user_points', 'points') - countSumTotalData($content['userid'], 'user_data', 'used_points');
1178 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']},points={$points}", false);
1180 // Shall we add this to ignore?
1181 if ($points <= $limit) {
1183 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']} has depleted points amount!", false);
1184 $UIDs['userid'][$content['userid']] = $content['userid'];
1185 $UIDs['points'][$content['userid']] = $points;
1186 $UIDs['notified'][$content['userid']] = $content['notified'];
1191 SQL_FREERESULT($result);
1194 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".getUserId().')', false);
1200 // Determine how many users are Online in surfbar
1201 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1202 // Count all users in surfbar modue and return the value
1203 $result = SQL_QUERY("SELECT
1206 `{?_MYSQL_PREFIX?}_surfbar_stats`
1208 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`last_surfed`)) <= {?online_timeout?}
1210 `userid` ASC", __FUNCTION__, __LINE__);
1213 $cnt = SQL_NUMROWS($result);
1216 SQL_FREERESULT($result);
1222 // Determine waiting time for one URL
1223 function SURFBAR_DETERMINE_WAIT_TIME () {
1224 // Get fixed reload lock
1225 $fixed = SURFBAR_GET_FIXED_RELOAD();
1227 // Is the fixed reload time set?
1233 // Static time is default
1234 $time = getConfig('surfbar_static_time');
1236 // Which payment model do we have?
1237 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1238 // "Calculate" dynamic time
1239 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1246 // Changes the status of an URL from given to other
1247 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1248 // Make new status always lower-case
1249 $newStatus = strtolower($newStatus);
1251 // Get URL data for status comparison if missing
1252 if ((!is_array($data)) || (count($data) == 0)) {
1253 // Fetch missing URL data
1254 $data = SURFBAR_GET_URL_DATA($urlId);
1257 // Is the new status set?
1258 if ((!is_string($newStatus)) || (empty($newStatus))) {
1259 // Abort here, but fine!
1263 // Is the status like prevStatus is saying?
1264 if ($data[$urlId]['status'] != $prevStatus) {
1265 // No, then abort here
1270 // Update the status now
1271 // ---------- Comment out for debugging/developing member actions! ---------
1272 //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1273 // array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1274 // ---------- Comment out for debugging/developing member actions! ---------
1277 // ---------- Comment out for debugging/developing member actions! ---------
1278 //if (SQL_AFFECTEDROWS() != 1) {
1279 // // No, something went wrong
1282 // ---------- Comment out for debugging/developing member actions! ---------
1284 // Prepare content for notification routines
1285 $data[$urlId]['userid'] = $data[$urlId]['userid'];
1286 $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1287 $data[$urlId]['reward'] = translateComma(getConfig('surfbar_static_reward'));
1288 $data[$urlId]['costs'] = translateComma(getConfig('surfbar_static_costs'));
1290 // Do some dirty fixing here:
1291 if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1292 // Fix for template change
1293 $newStatus = 'continued';
1296 // Send admin notification
1297 SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1299 // Send user notification
1300 SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1306 // Calculate minimum value for dynamic payment model
1307 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1308 // Addon is zero by default
1312 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1315 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1318 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1321 $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1324 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1326 // Get user's total URLs
1327 $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1330 if ($totalUrls > 0) {
1331 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1333 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1340 // Calculate maximum value for dynamic payment model
1341 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1342 // Addon is zero by default
1349 $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1352 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1355 $addon += abs($max * $percent * $totalUsers);
1358 $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1361 $addon += abs($max * $percent * $totalUrls);
1367 // Calculate dynamic lock
1368 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1369 // Default lock is 30 seconds
1373 $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1376 $addon = abs(log($onlineUsers / $addon + 1));
1382 // "Getter" for lock ids array
1383 function SURFBAR_GET_LOCK_IDS () {
1384 // Prepare some arrays
1389 // Get all id from locks within the timestamp
1390 $result = SQL_QUERY_ESC("SELECT `id`, `url_id`, UNIX_TIMESTAMP(`last_surfed`) AS last_surfed
1392 `{?_MYSQL_PREFIX?}_surfbar_locks`
1396 `id` ASC", array(getUserId()),
1397 __FUNCTION__, __LINE__);
1400 while ($content = SQL_FETCHARRAY($result)) {
1402 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1404 // Skip entries that are too old
1405 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1407 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1409 // Add only if missing or bigger
1410 if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1412 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1415 $IDs[$content['url_id']] = $content['last_surfed'];
1416 $USE[$content['url_id']] = $content['id'];
1420 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1422 // Ignore these old entries!
1423 $ignored[] = $content['url_id'];
1424 unset($IDs[$content['url_id']]);
1425 unset($USE[$content['url_id']]);
1430 SQL_FREERESULT($result);
1436 // "Getter" for maximum random number
1437 function SURFBAR_GET_MAX_RANDOM ($UIDs, $add) {
1438 // Count max availabe entries
1439 $result = SQL_QUERY("SELECT sbu.id AS cnt
1440 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1441 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1442 ON sbu.id=sbs.url_id
1443 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1445 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."
1446 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1452 $maxRand = SQL_NUMROWS($result);
1455 SQL_FREERESULT($result);
1461 // Load all URLs of the current user and return it as an array
1462 function SURFBAR_GET_USER_URLS () {
1467 $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
1468 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1469 WHERE u.userid=%s AND u.status != 'DELETED'
1471 array(getUserId()), __FUNCTION__, __LINE__);
1473 // Are there entries?
1474 if (SQL_NUMROWS($result) > 0) {
1476 while ($row = SQL_FETCHARRAY($result)) {
1478 $URLs[$row['id']] = $row;
1483 SQL_FREERESULT($result);
1489 // "Getter" for member action array for given status
1490 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1492 $returnArray = array();
1494 // Get all assigned actions
1495 $result = SQL_QUERY_ESC("SELECT action FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1496 array($status), __FUNCTION__, __LINE__);
1498 // Some entries there?
1499 if (SQL_NUMROWS($result) > 0) {
1501 // @TODO This can be somehow rewritten
1502 while ($content = SQL_FETCHARRAY($result)) {
1503 $returnArray[] = $content['action'];
1508 SQL_FREERESULT($result);
1511 return $returnArray;
1514 // Reload to configured stop page
1515 function SURFBAR_RELOAD_TO_STOP_PAGE ($page="stop") {
1516 // Internal or external?
1517 if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1518 // Reload to internal page
1519 redirectToUrl('surfbar.php?frame=' . $page);
1521 // Reload to external page
1522 redirectToConfiguredUrl('surfbar_pause_url');
1526 // Determine next id for surfbar or get data for given id, always call this before you call other
1527 // getters below this function!!!
1528 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1529 // Default is no id and no random number
1535 // Get array with lock ids
1536 $USE = SURFBAR_GET_LOCK_IDS();
1538 // Shall we add some URL ids to ignore?
1540 if (count($USE) > 0) {
1542 $add = " AND sbu.id NOT IN (";
1543 foreach ($USE as $url_id => $lid) {
1545 $add .= $url_id.',';
1548 // Add closing bracket
1549 $add = substr($add, 0, -1) . ')';
1552 // Determine depleted user account
1553 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1555 // Get maximum randomness factor
1556 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['userid'], $add);
1558 // If more than one URL can be called generate the random number!
1560 // Generate random number
1561 $randNum = mt_rand(0, ($maxRand - 1));
1564 // And query the database
1565 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1566 $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
1567 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1568 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1569 ON sbu.id=sbs.url_id
1570 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1572 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."
1574 ORDER BY l.last_surfed ASC, sbu.id ASC
1576 array($randNum), __FUNCTION__, __LINE__
1579 // Get data from specified id number
1580 $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
1581 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1582 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1583 ON sbu.id=sbs.url_id
1584 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1586 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))
1588 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1592 // Is there an id number?
1593 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1594 if (SQL_NUMROWS($result) == 1) {
1596 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1597 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1598 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1600 // Determine waiting time
1601 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1603 // Is the last salt there?
1604 if (is_null($GLOBALS['surfbar_cache']['last_salt'])) {
1605 // Then repair it wit the static!
1606 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1607 $GLOBALS['surfbar_cache']['last_salt'] = '';
1610 // Fix missing last_surfed
1611 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1613 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1614 $GLOBALS['surfbar_cache']['last_surfed'] = 0;
1617 // Get base/fixed reward and costs
1618 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1619 $GLOBALS['surfbar_cache']['costs'] = SURFBAR_DETERMINE_COSTS();
1620 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1622 // Only in dynamic model add the dynamic bonus!
1623 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1624 // Calculate dynamic reward/costs and add it
1625 $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1626 $GLOBALS['surfbar_cache']['costs'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1627 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1631 $nextId = SURFBAR_GET_ID();
1635 SQL_FREERESULT($result);
1638 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1642 // -----------------------------------------------------------------------------
1643 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1644 // THE $GLOBALS['surfbar_cache'] ARRAY!
1645 // -----------------------------------------------------------------------------
1647 // Initializes the surfbar
1648 function SURFBAR_INIT () {
1650 $GLOBALS['surfbar_cache'] = array();
1653 // Private getter for data elements
1654 function SURFBAR_GET_DATA ($element) {
1655 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1660 // Is the entry there?
1661 if (isset($GLOBALS['surfbar_cache'][$element])) {
1663 $data = $GLOBALS['surfbar_cache'][$element];
1664 } else { // END - if
1666 print_r($GLOBALS['surfbar_cache']);
1672 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1676 // Getter for reward from cache
1677 function SURFBAR_GET_REWARD () {
1678 // Get data element and return its contents
1679 return SURFBAR_GET_DATA('reward');
1682 // Getter for costs from cache
1683 function SURFBAR_GET_COSTS () {
1684 // Get data element and return its contents
1685 return SURFBAR_GET_DATA('costs');
1688 // Getter for URL from cache
1689 function SURFBAR_GET_URL () {
1690 // Get data element and return its contents
1691 return SURFBAR_GET_DATA('url');
1694 // Getter for salt from cache
1695 function SURFBAR_GET_SALT () {
1696 // Get data element and return its contents
1697 return SURFBAR_GET_DATA('salt');
1700 // Getter for id from cache
1701 function SURFBAR_GET_ID () {
1702 // Get data element and return its contents
1703 return SURFBAR_GET_DATA('id');
1706 // Getter for userid from cache
1707 function SURFBAR_GET_USERID () {
1708 // Get data element and return its contents
1709 return SURFBAR_GET_DATA('userid');
1712 // Getter for user reload locks
1713 function SURFBAR_GET_USER_LOCKS () {
1714 // Get data element and return its contents
1715 return SURFBAR_GET_DATA('user_locks');
1718 // Getter for reload time
1719 function SURFBAR_GET_RELOAD_TIME () {
1720 // Get data element and return its contents
1721 return SURFBAR_GET_DATA('time');
1724 // Getter for allowed views
1725 function SURFBAR_GET_VIEWS_ALLOWED () {
1726 // Get data element and return its contents
1727 return SURFBAR_GET_DATA('views_allowed');
1730 // Getter for fixed reload
1731 function SURFBAR_GET_FIXED_RELOAD () {
1732 // Get data element and return its contents
1733 return SURFBAR_GET_DATA('fixed_reload');
1736 // Getter for surf lock
1737 function SURFBAR_GET_SURF_LOCK () {
1738 // Get data element and return its contents
1739 return SURFBAR_GET_DATA('surf_lock');
1742 // Getter for new status
1743 function SURFBAR_GET_NEW_STATUS () {
1744 // Get data element and return its contents
1745 return SURFBAR_GET_DATA('new_status');