e62d6835f0f7660b37a47a36306a4836e2eb3dbf
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/31/2008 *
4  * ===================                          Last change: 08/31/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : surfbar_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for surfbar                            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die Surfbar                      *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
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                  *
23  *                                                                      *
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.                                  *
28  *                                                                      *
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.                         *
33  *                                                                      *
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,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 }
44
45 // -----------------------------------------------------------------------------
46 //                               Admin functions
47 // -----------------------------------------------------------------------------
48 //
49 // Admin has added an URL with given user id and so on
50 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
51         // Do some pre-checks
52         if (!isAdmin()) {
53                 // Not an admin
54                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
55                 return false;
56         } elseif (!isUrlValid($url)) {
57                 // URL invalid
58                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid URL.", $url, $limit, $reload));
59                 return false;
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));
63                 return false;
64         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
65                 // No more allowed!
66                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : No more URLs allowed.", $url, $limit, $reload));
67                 return false;
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));
71                 return false;
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));
75                 return false;
76         }
77
78         // Register the new URL
79         return SURFBAR_REGISTER_URL($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
80 }
81
82 // Admin unlocked an email so we can migrate the URL
83 function SURFBAR_ADMIN_MIGRATE_URL ($url, $userid) {
84         // Do some pre-checks
85         if (!isAdmin()) {
86                 // Not an admin
87                 return false;
88         } elseif (!isUrlValid($url)) {
89                 // URL invalid
90                 return false;
91         } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
92                 // URL already found in surfbar!
93                 return false;
94         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
95                 // No more allowed!
96                 return false;
97         }
98
99         // Register the new URL
100         return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
101 }
102
103 // Admin function for unlocking URLs
104 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
105         // Is this an admin or invalid array?
106         if (!isAdmin()) {
107                 // Not admin or invalid ids array
108                 return false;
109         } elseif (!is_array($IDs)) {
110                 // No array
111                 return false;
112         } elseif (count($IDs) == 0) {
113                 // Empty array
114                 return false;
115         }
116
117         // Set to true to make AND expression valid if first URL got unlocked
118         $done = true;
119
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')));
124         } // END - if
125
126         // Return total status
127         return $done;
128 }
129
130 // Admin function for rejecting URLs
131 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
132         // Is this an admin or invalid array?
133         if (!isAdmin()) {
134                 // Not admin or invalid ids array
135                 return false;
136         } elseif (!is_array($IDs)) {
137                 // No array
138                 return false;
139         } elseif (count($IDs) == 0) {
140                 // Empty array
141                 return false;
142         }
143
144         // Set to true to make AND expression valid if first URL got unlocked
145         $done = true;
146
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')));
151         } // END - if
152
153         // Return total status
154         return $done;
155 }
156
157 //
158 // -----------------------------------------------------------------------------
159 //                               Member functions
160 // -----------------------------------------------------------------------------
161 //
162 // Member has added an URL
163 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
164         // Do some pre-checks
165         if (!isMember()) {
166                 // Not a member
167                 return false;
168         } elseif ((!isUrlValid($url)) && (!isAdmin())) {
169                 // URL invalid
170                 return false;
171         } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
172                 // URL already found in surfbar!
173                 return false;
174         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
175                 // No more allowed!
176                 return false;
177         } elseif (''.($limit + 0).'' != ''.$limit.'') {
178                 // Invalid amount entered
179                 return false;
180         }
181
182         // Register the new URL
183         return SURFBAR_REGISTER_URL($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
184 }
185
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);
190
191         // Init HTML code
192         $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
193 <tr>\n";
194
195         // Calculate width
196         $width = round(100 / count($actionArray));
197
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(
202                         'width'    => $width,
203                         'id'       => bigintval($urlId),
204                         'action'   => strtolower($action),
205                         'title'    => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE--}',
206                         'submit'   => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT--}',
207                 ));
208         } // END - foreach
209
210         // Close table
211         $OUT .= "</tr>
212 </table>\n";
213
214         // Return code
215         return $OUT;
216 }
217
218 // Do the member form request
219 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
220         // By default no action is performed
221         $performed = false;
222
223         // Is this a member?
224         if (!isMember()) {
225                 // No member!
226                 return false;
227         } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
228                 // Important form elements are missing!
229                 return false;
230         } elseif (!isset($URLs[$formData['id']])) {
231                 // id not found in cache
232                 return false;
233         } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
234                 // Action not allowed for current URL status
235                 return false;
236         }
237
238         // Secure action
239         $action = secureString($formData['action']);
240
241         // Has it changed?
242         if ($action != $formData['action']) {
243                 // Invalid data in action found
244                 return false;
245         } // END - if
246
247         // Create the function name for selected action
248         $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
249
250         // Is the function there?
251         if (function_exists($functionName)) {
252                 // Add new status
253                 $URLs[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
254
255                 // Extract URL data for call-back
256                 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
257
258                 // Action found so execute it
259                 $performed = call_user_func_array($functionName, $urlData);
260         } else {
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));
264         }
265
266         // Return status
267         return $performed;
268 }
269
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__);
275
276         // Is the entry there?
277         $isValid = (SQL_NUMROWS($result) == 1);
278
279         // Fetch the new status if found
280         if ($isValid) {
281                 // Load new status
282                 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
283         } // END - if
284
285         // Free result
286         SQL_FREERESULT($result);
287
288         // Return status
289         return $isValid;
290 }
291
292 //
293 // -----------------------------------------------------------------------------
294 //                               Member actions
295 // -----------------------------------------------------------------------------
296 //
297 // Retreat a booked URL
298 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
299         // Create the data array for next function call
300         $data = array(
301         $urlData['id'] => $urlData
302         );
303
304         // Simply change the status here
305         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
306 }
307
308 // Book an URL now (from migration)
309 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
310         // Create the data array for next function call
311         $data = array(
312         $urlData['id'] => $urlData
313         );
314
315         // Simply change the status here
316         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
317 }
318
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);
325         } // END - if
326
327         // Display form
328         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
329 }
330
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);
337         } // END - if
338
339         // Display form
340         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
341 }
342
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));
346 }
347
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'];
354
355         // Return status change
356         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
357 }
358
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));
362 }
363
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);
372
373         // Is the lock reason empty?
374         if (empty($urlData['lock_reason'])) {
375                 // Fix it to three dashes
376                 $urlData['lock_reason'] = '---';
377         } // END - if
378
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';
385
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';
392                 } // END - if
393         } // END - if
394
395         // Load the form and display it
396         loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
397
398         // All fine by default ... ;-)
399         return true;
400 }
401
402 // Execute choosen action
403 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
404         // By default nothing is executed
405         $executed = false;
406
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';
411         } // END - if
412
413         // Construct function name
414         $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
415
416         // Is 'userid' set and not 'userid' ?
417         if ((!isset($urlData['userid'])) && (isset($urlData['userid']))) {
418                 // Auto-fix this
419                 $urlData['userid'] = $urlData['userid'];
420         } // END - if
421
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));
428                 } // END - if
429         } else {
430                 // Not found!
431                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
432         }
433
434         // Return status
435         return $executed;
436 }
437 // "Execute edit" function: Update changed data
438 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
439         // Default is nothing done
440         $status = false;
441
442         // Has the URL or limit changed?
443         if (true) {
444                 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
445                 // Run the query
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__);
448
449                 // All fine
450                 $status = true;
451         } // END - if
452
453         // Return status
454         return $status;
455 }
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)
459         return true;
460 }
461 //
462 // -----------------------------------------------------------------------------
463 //                           Self-maintenance functions
464 // -----------------------------------------------------------------------------
465 //
466 // Main function
467 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
468         // Handle URLs which limit has depleted so we can stop them
469         SURFBAR_HANDLE_DEPLETED_VIEWS();
470
471         // Handle low-points amounts
472         SURFBAR_HANDLE_LOW_POINTS();
473 }
474 // Handle URLs which limit has depleted
475 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
476         // Get all URLs
477         $urlArray = SURFBAR_GET_URL_DATA(0, 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
478
479         // Do we have some entries?
480         if (count($urlArray) > 0) {
481                 // Then handle all!
482                 foreach ($urlArray as $id => $urlData) {
483                         // Backup data
484                         $data = $urlData;
485
486                         // Rewrite array for next call
487                         $urlData[$id] = $data;
488
489                         // Handle the status
490                         SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
491                 } // END - foreach
492         } // END - if
493 }
494
495 // Alert users which have URLs booked and are low on points amount
496 function SURFBAR_HANDLE_LOW_POINTS () {
497         // Get all userids
498         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
499
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')) {
504                         // Prepare content
505                         $content = array(
506                                 'userid'      => $userid,
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'))
511                         );
512
513                         // Notify this user
514                         SURFBAR_NOTIFY_USER('low_points', $content);
515
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__);
519                 } // END - if
520         } // END - foreach
521 }
522
523 //
524 // -----------------------------------------------------------------------------
525 //                               Generic functions
526 // -----------------------------------------------------------------------------
527 //
528
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)));
533
534         // Was it found?
535         return (count($urlArray) > 0);
536 }
537
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();
542
543         // Is the column an id number?
544         if (($column == 'id') || ($column == 'userid')) {
545                 // Extra secure input
546                 $searchTerm = bigintval($searchTerm);
547         } // END - if
548
549         // If the column is 'id' there can be only one entry
550         $limit = '';
551         if ($column == 'id') {
552                 $limit = "LIMIT 1";
553         } // END - if
554
555         // Look up the record
556         $result = SQL_QUERY_ESC("SELECT
557         `id`, `userid`, `url`,
558         `views_total`, `views_max`, `views_allowed`, `status`,
559         UNIX_TIMESTAMP(`registered`) AS `registered`, UNIX_TIMESTAMP(`last_locked`) AS `last_locked`, `lock_reason`,
560         `views_max`, `views_allowed`, `fixed_reload`
561 FROM
562         `{?_MYSQL_PREFIX?}_surfbar_urls`
563 WHERE
564         `%s`='%s'".$add."
565 ORDER BY
566         `%s` %s
567 %s",
568                 array(
569                         $column,
570                         $searchTerm,
571                         $order,
572                         $sort,
573                         $limit
574                 ), __FUNCTION__, __LINE__);
575
576         // Is there at least one record?
577         if (SQL_NUMROWS($result) > 0) {
578                 // Then load all!
579                 while ($dataRow = SQL_FETCHARRAY($result)) {
580                         // Shall we group these results?
581                         if ($group == 'id') {
582                                 // Add the row by id as index
583                                 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
584                         } else {
585                                 // Group entries
586                                 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
587                         }
588                 } // END - while
589         } // END - if
590
591         // Free the result
592         SQL_FREERESULT($result);
593
594         // Return the result
595         return $GLOBALS['last_url_data'];
596 }
597
598 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
599 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
600         // Make sure by the user registered URLs are always pending
601         if ($addMode == 'reg') {
602                 $status = 'PENDING';
603         } // END - if
604
605         // Prepare content
606         $content = merge_array($extraFields, array(
607                 'url'         => $url,
608                 'frametester' => generateFrametesterUrl($url),
609                 'userid'         => $userid,
610                 'status'      => $status,
611         ));
612
613         // Is limit/reload set?
614         if (!isset($config['limit'])) {
615                 $content['limit']  = '0';
616         } // END - if
617         if (!isset($config['reload'])) {
618                 $content['reload'] = '0';
619         } // END - if
620
621         // Insert the URL into database
622         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
623
624         // Is this id valid?
625         if ($content['insert_id'] == '0') {
626                 // INSERT did not insert any data!
627                 return false;
628         } // END - if
629
630         // Translate status and limit
631         $content['limit'] = translateSurfbarLimit($content['limit']);
632
633         // If in reg-mode we notify admin
634         if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
635                 // Notify admin even when he as unlocked an email
636                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
637         } // END - if
638
639         // Send mail to user
640         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
641
642         // Return the insert id
643         return $content['insert_id'];
644 }
645
646 // Inserts an url by given data array and return the insert id
647 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
648         // Get userid
649         $userid = bigintval($urlData['userid']);
650
651         // Is the id set?
652         if (empty($userid)) $userid = '0';
653
654         // Just run the insert query for now
655         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)",
656                 array(
657                         $userid,
658                         $urlData['url'],
659                         $urlData['status'],
660                         $urlData['limit'],
661                         $urlData['limit'],
662                         $urlData['reload']
663                 ), __FUNCTION__, __LINE__
664         );
665
666         // Return insert id
667         return SQL_INSERTID();
668 }
669
670 // Notify admin(s) with a selected message and content
671 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
672         // Prepare template name
673         $templateName = sprintf("admin_surfbar_%s", $messageType);
674
675         // Prepare subject
676         $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
677                 strtoupper($messageType)
678         ));
679
680         // Is the subject line there?
681         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
682                 // Set default subject if following eval() wents wrong
683                 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
684         } // END - if
685
686         // Translate some data if present
687         if (isset($content['status']))        $content['status']        = translateSurfbarUrlStatus($content['status']);
688         if (isset($content['registered']))    $content['registered']    = generateDateTime($content['registered'], 2);
689         if (isset($content['last_locked']))   $content['last_locked']   = generateDateTime($content['last_locked'], 2);
690         if (isset($content['views_total']))   $content['views_total']   = translateComma($content['views_total']);
691         if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
692         if (isset($content['views_max']))     $content['views_max']     = translateComma($content['views_max']);
693
694         // Send the notification out
695         return sendAdminNotification($subject, $templateName, $content, $content['userid']);
696 }
697
698 // Notify the user about the performed action
699 function SURFBAR_NOTIFY_USER ($messageType, $content) {
700         // Skip notification if userid is zero
701         if ($content['userid'] == '0') {
702                 return false;
703         } // END - if
704
705         // Prepare template name
706         $templateName = sprintf("member_surfbar_%s", $messageType);
707
708         // Prepare subject
709         $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
710         strtoupper($messageType)
711         ));
712
713         // Is the subject line there?
714         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
715                 // Set default subject if following eval() wents wrong
716                 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
717         } // END - if
718
719         // Translate some data if present
720         if (isset($content['status']))        $content['status']        = translateSurfbarUrlStatus($content['status']);
721         if (isset($content['registered']))    $content['registered']    = generateDateTime($content['registered'], 2);
722         if (isset($content['last_locked']))   $content['last_locked']   = generateDateTime($content['last_locked'], 2);
723         if (isset($content['views_total']))   $content['views_total']   = translateComma($content['views_total']);
724         if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
725         if (isset($content['views_max']))     $content['views_max']     = translateComma($content['views_max']);
726
727         // Load template
728         $mailText = loadEmailTemplate($templateName, $content, $content['userid']);
729
730         // Send the email
731         return sendEmail($content['userid'], $subject, $mailText);
732 }
733
734 // Translates the limit
735 function translateSurfbarLimit ($limit) {
736         // Is this zero?
737         if ($limit == '0') {
738                 // Unlimited!
739                 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
740         } else {
741                 // Translate comma
742                 $return = translateComma($limit);
743         }
744
745         // Return value
746         return $return;
747 }
748
749 // Translate the URL status
750 function translateSurfbarUrlStatus ($status) {
751         // Create constant name
752         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
753
754         // Get message
755         $statusTranslated = getMessage($constantName);
756
757         // Return result
758         return $statusTranslated;
759 }
760
761 // Determine reward
762 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
763         // Static values are default
764         $reward = getConfig('surfbar_static_reward');
765
766         // Do we have static or dynamic?
767         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
768                 // "Calculate" dynamic reward
769                 if ($onlyMin) {
770                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
771                 } else {
772                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
773                 }
774         } // END - if
775
776         // Return reward
777         return $reward;
778 }
779
780 // Determine costs
781 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
782         // Static costs is default
783         $costs  = getConfig('surfbar_static_costs');
784
785         // Do we have static or dynamic?
786         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
787                 // "Calculate" dynamic costs
788                 if ($onlyMin) {
789                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
790                 } else {
791                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
792                 }
793         } // END - if
794
795         // Return costs
796         return $costs;
797 }
798
799 // "Calculate" dynamic add
800 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
801         // Get min/max values
802         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
803         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
804
805         // "Calculate" dynamic part and return it
806         return mt_rand($min, $max);
807 }
808
809 // Determine right template name
810 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
811         // Default is the frameset
812         $templateName = "surfbar_frameset";
813
814         // Any frame set? ;-)
815         if (isGetRequestParameterSet('frame')) {
816                 // Use the frame as a template name part... ;-)
817                 $templateName = sprintf("surfbar_frame_%s",
818                 getRequestParameter('frame')
819                 );
820         } // END - if
821
822         // Return result
823         return $templateName;
824 }
825
826 // Check if the "reload lock" of the current user is full, call this function
827 // before you call SURFBAR_CHECK_RELOAD_LOCK().
828 function SURFBAR_CHECK_RELOAD_FULL() {
829         // Default is full!
830         $isFull = true;
831
832         // Cache static reload lock
833         $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
834         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
835
836         // Do we have dynamic model?
837         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
838                 // "Calculate" dynamic lock
839                 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
840         } // END - if
841
842         // Ask the database
843         $result = SQL_QUERY_ESC("SELECT
844         COUNT(l.id) AS cnt
845 FROM
846         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
847 INNER JOIN
848         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
849 ON
850         u.id=l.url_id
851 WHERE
852         l.userid=%s AND
853         (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.last_surfed) AND
854         (
855                 ((UNIX_TIMESTAMP(l.last_surfed) - u.fixed_reload) < 0 AND u.fixed_reload > 0) OR
856                 u.fixed_reload = '0'
857         )
858 LIMIT 1",
859                 array(getMemberId()), __FUNCTION__, __LINE__
860         );
861
862         // Fetch row
863         list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
864
865         // Is it null?
866         if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
867                 // Then fix it to zero!
868                 $GLOBALS['surfbar_cache']['user_locks'] = '0';
869         } // END - if
870
871         // Free result
872         SQL_FREERESULT($result);
873
874         // Get total URLs
875         $total = SURFBAR_GET_TOTAL_URLS();
876
877         // Do we have some URLs in lock? Admins can always surf on own URLs!
878         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
879         $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
880
881         // Return result
882         return $isFull;
883 }
884
885 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
886 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
887         // Determine depleted user account
888         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
889
890         // If we dont get any user ids back, there are no URLs
891         if (count($userids['userid']) == 0) {
892                 // No user ids found, no URLs!
893                 return 0;
894         } // END - if
895
896         // Is the exlude userid set?
897         if ($excludeUserId > 0) {
898                 // Then add it
899                 $userids['userid'][$excludeUserId] = $excludeUserId;
900         } // END - if
901
902         // Get amount from database
903         $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
904 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
905 WHERE `userid` NOT IN (".implode(', ', $userids['userid']).") AND `status`='%s'",
906                 array($status), __FUNCTION__, __LINE__
907         );
908
909         // Fetch row
910         list($cnt) = SQL_FETCHROW($result);
911
912         // Free result
913         SQL_FREERESULT($result);
914
915         // Return result
916         return $cnt;
917 }
918
919 // Check wether the user is allowed to book more URLs
920 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
921         // Is this admin and userid is zero or does the user has some URLs left to book?
922         return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getConfig('surfbar_max_order')));
923 }
924
925 // Get total amount of URLs of given status for current user
926 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '',$exclude = '') {
927         // Is the user 0 and user is logged in?
928         if (($userid == '0') && (isMember())) {
929                 // Then use this userid
930                 $userid = getMemberId();
931         } elseif ($userid == '0') {
932                 // Error!
933                 return (getConfig('surfbar_max_order') + 1);
934         }
935
936         // Default is all URLs
937         $add = '';
938
939         // Is the status set?
940         if (is_array($status)) {
941                 // Only URLs with these status
942                 $add = sprintf(" AND `status` IN('%s')", implode("','", $status));
943         } elseif (!empty($status)) {
944                 // Only URLs with this status
945                 $add = sprintf(" AND `status`='%s'", $status);
946         } elseif (is_array($exclude)) {
947                 // Exclude URLs with these status
948                 $add = sprintf(" AND `status` NOT IN('%s')", implode("','", $exclude));
949         } elseif (!empty($exclude)) {
950                 // Exclude URLs with this status
951                 $add = sprintf(" AND `status` != '%s'", $exclude);
952         }
953
954         // Get amount from database
955         $cnt = countSumTotalData($userid, 'surfbar_urls', 'id', 'userid', true, $add);
956
957         // Return result
958         return $cnt;
959 }
960
961 // Generate a validation code for the given id number
962 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
963         // @TODO Invalid salt should be refused
964         $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
965
966         // Get code length from config
967         $length = getConfig('code_length');
968
969         // Fix length to 10
970         if ($length == '0') $length = 10;
971
972         // Generate a code until the length matches
973         $valCode = '';
974         while (strlen($valCode) != $length) {
975                 // Is the salt set?
976                 if (empty($salt)) {
977                         // Generate random hashed string
978                         $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
979                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
980                 } else {
981                         // Use this as salt!
982                         $GLOBALS['surfbar_cache']['salt'] = $salt;
983                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
984                 }
985
986                 // ... and now the validation code
987                 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getMemberId());
988                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
989         } // END - while
990
991         // Hash it with md5() and salt it with the random string
992         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
993
994         // Finally encrypt it PGP-like and return it
995         $valHashedCode = encodeHashForCookie($hashedCode);
996
997         // Return hashed value
998         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
999         return $valHashedCode;
1000 }
1001
1002 // Check validation code
1003 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
1004         // Secure id number
1005         $urlId = bigintval($urlId);
1006
1007         // Now generate the code again
1008         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1009
1010         // Return result of checking hashes and salts
1011         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
1012         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('last_salt').'+++', false);
1013         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
1014 }
1015
1016 // Lockdown the userid/id combination (reload lock)
1017 function SURFBAR_LOCKDOWN_ID ($urlId) {
1018         //* DEBUG: */ outputHtml('LOCK!');
1019         ///* DEBUG: */ return;
1020         // Just add it to the database
1021         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`userid`, `url_id`) VALUES (%s, %s)",
1022                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1023
1024         // Remove the salt from database
1025         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1026                 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1027 }
1028
1029 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1030 function SURFBAR_PAY_POINTS () {
1031         // Remove it from the URL owner
1032         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1033         if (SURFBAR_GET_USERID() > 0) {
1034                 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1035         } // END - if
1036
1037         // Book it to the user
1038         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1039         addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getMemberId(), SURFBAR_GET_DATA('reward'));
1040 }
1041
1042 // Updates the statistics of current URL/userid
1043 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1044         // Init add
1045         $add = '';
1046
1047         // Get allowed views
1048         $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1049
1050         // Do we have a limit?
1051         if ($allowed > 0) {
1052                 // Then count views_max down!
1053                 $add .= ", `views_max`=`views_max`-1";
1054         } // END - if
1055
1056         // Update URL stats
1057         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `views_total`=`views_total`+1".$add." WHERE `id`=%s LIMIT 1",
1058                 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1059
1060         // Update the stats entry
1061         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `count`=`count`+1 WHERE `userid`=%s AND `url_id`=%s LIMIT 1",
1062                 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1063
1064         // Was that update okay?
1065         if (SQL_AFFECTEDROWS() < 1) {
1066                 // No, then insert entry
1067                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1068                 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1069         } // END - if
1070
1071         // Update total/daily/weekly/monthly counter
1072         incrementConfigEntry('surfbar_total_counter');
1073         incrementConfigEntry('surfbar_daily_counter');
1074         incrementConfigEntry('surfbar_weekly_counter');
1075         incrementConfigEntry('surfbar_monthly_counter');
1076
1077         // Update config as well
1078         updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1079 }
1080
1081 // Update the salt for validation and statistics
1082 function SURFBAR_UPDATE_SALT_STATS () {
1083         // Update statistics record
1084         SURFBAR_UPDATE_INSERT_STATS_RECORD();
1085
1086         // Simply store the salt from cache away in database...
1087         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `last_salt`='%s' WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1088                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getMemberId()), __FUNCTION__, __LINE__);
1089
1090         // Debug message
1091         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1092
1093         // Was that okay?
1094         if (SQL_AFFECTEDROWS() < 1) {
1095                 // Insert missing entry!
1096                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`url_id`, `userid`, `last_salt`) VALUES (%s, %s, '%s')",
1097                         array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1098         } // END - if
1099
1100         // Debug message
1101         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1102
1103         // Return if the update was okay
1104         return (SQL_AFFECTEDROWS() == 1);
1105 }
1106
1107 // Check if the reload lock is active for given id
1108 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1109         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1110         // Ask the database
1111         $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1112 FROM
1113         `{?_MYSQL_PREFIX?}_surfbar_locks`
1114 WHERE
1115         `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1116 ORDER BY
1117         `last_surfed` ASC
1118 LIMIT 1",
1119                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1120         );
1121
1122         // Fetch counter
1123         list($cnt) = SQL_FETCHROW($result);
1124
1125         // Free result
1126         SQL_FREERESULT($result);
1127
1128         // Return check
1129         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1130         return ($cnt == 1);
1131 }
1132
1133 // Determine which user hash no more points left
1134 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1135         // Init array
1136         $userids = array(
1137                 'userid'      => array(),
1138                 'points'   => array(),
1139                 'notified' => array(),
1140         );
1141
1142         // Do we have a current user id?
1143         if ((isMember()) && ($limit == '0')) {
1144                 // Then add this as well
1145                 $userids['userid'][getMemberId()]      = getMemberId();
1146                 $userids['points'][getMemberId()]   = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
1147                 $userids['notified'][getMemberId()] = '0';
1148
1149                 // Get all userid except logged in one
1150                 $result = SQL_QUERY_ESC("SELECT
1151         u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1152 FROM
1153         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1154 INNER JOIN
1155         `{?_MYSQL_PREFIX?}_user_data` AS d
1156 ON
1157         u.userid=d.userid
1158 WHERE
1159         u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1160 GROUP BY
1161         u.userid
1162 ORDER BY
1163         u.userid ASC",
1164                         array(getMemberId()), __FUNCTION__, __LINE__);
1165         } else {
1166                 // Get all userid
1167                 $result = SQL_QUERY("SELECT
1168         u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1169 FROM
1170         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1171 INNER JOIN
1172         `{?_MYSQL_PREFIX?}_user_data` AS d
1173 ON
1174         u.userid=d.userid
1175 WHERE
1176         u.`status`='ACTIVE'
1177 GROUP BY
1178         u.userid
1179 ORDER BY
1180         u.userid ASC", __FUNCTION__, __LINE__);
1181         }
1182
1183         // Load all userid
1184         while ($content = SQL_FETCHARRAY($result)) {
1185                 // Get total points
1186                 $points = countSumTotalData($content['userid'], 'user_points', 'points') - countSumTotalData($content['userid'], 'user_data', 'used_points');
1187                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']},points={$points}", false);
1188
1189                 // Shall we add this to ignore?
1190                 if ($points <= $limit) {
1191                         // Ignore this one!
1192                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']} has depleted points amount!", false);
1193                         $userids['userid'][$content['userid']]      = $content['userid'];
1194                         $userids['points'][$content['userid']]   = $points;
1195                         $userids['notified'][$content['userid']] = $content['notified'];
1196                 } // END - if
1197         } // END - while
1198
1199         // Free result
1200         SQL_FREERESULT($result);
1201
1202         // Debug message
1203         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($userids)." (with own userid=".getMemberId().')', false);
1204
1205         // Return result
1206         return $userids;
1207 }
1208
1209 // Determine how many users are Online in surfbar
1210 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1211         // Count all users in surfbar modue and return the value
1212         $result = SQL_QUERY("SELECT
1213         `id`
1214 FROM
1215         `{?_MYSQL_PREFIX?}_surfbar_stats`
1216 WHERE
1217         (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`last_surfed`)) <= {?online_timeout?}
1218 GROUP BY
1219         `userid` ASC", __FUNCTION__, __LINE__);
1220
1221         // Fetch count
1222         $cnt = SQL_NUMROWS($result);
1223
1224         // Free result
1225         SQL_FREERESULT($result);
1226
1227         // Return result
1228         return $cnt;
1229 }
1230
1231 // Determine waiting time for one URL
1232 function SURFBAR_DETERMINE_WAIT_TIME () {
1233         // Get fixed reload lock
1234         $fixed = SURFBAR_GET_FIXED_RELOAD();
1235
1236         // Is the fixed reload time set?
1237         if ($fixed > 0) {
1238                 // Return it
1239                 return $fixed;
1240         } // END - if
1241
1242         // Static time is default
1243         $time = getConfig('surfbar_static_time');
1244
1245         // Which payment model do we have?
1246         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1247                 // "Calculate" dynamic time
1248                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1249         } // END - if
1250
1251         // Return value
1252         return $time;
1253 }
1254
1255 // Changes the status of an URL from given to other
1256 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1257         // Make new status always lower-case
1258         $newStatus = strtolower($newStatus);
1259
1260         // Get URL data for status comparison if missing
1261         if ((!is_array($data)) || (count($data) == 0)) {
1262                 // Fetch missing URL data
1263                 $data = SURFBAR_GET_URL_DATA($urlId);
1264         } // END - if
1265
1266         // Is the new status set?
1267         if ((!is_string($newStatus)) || (empty($newStatus))) {
1268                 // Abort here, but fine!
1269                 return true;
1270         } // END - if
1271
1272         // Is the status like prevStatus is saying?
1273         if ($data[$urlId]['status'] != $prevStatus) {
1274                 // No, then abort here
1275                 return false;
1276         } // END - if
1277
1278
1279         // Update the status now
1280         // ---------- Comment out for debugging/developing member actions! ---------
1281         //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1282         //      array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1283         // ---------- Comment out for debugging/developing member actions! ---------
1284
1285         // Was that fine?
1286         // ---------- Comment out for debugging/developing member actions! ---------
1287         //if (SQL_AFFECTEDROWS() != 1) {
1288         //      // No, something went wrong
1289         //      return false;
1290         //} // END - if
1291         // ---------- Comment out for debugging/developing member actions! ---------
1292
1293         // Prepare content for notification routines
1294         $data[$urlId]['userid']         = $data[$urlId]['userid'];
1295         $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1296         $data[$urlId]['reward']      = translateComma(getConfig('surfbar_static_reward'));
1297         $data[$urlId]['costs']       = translateComma(getConfig('surfbar_static_costs'));
1298
1299         // Do some dirty fixing here:
1300         if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1301                 // Fix for template change
1302                 $newStatus = 'continued';
1303         } // END - if
1304
1305         // Send admin notification
1306         SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1307
1308         // Send user notification
1309         SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1310
1311         // All done!
1312         return true;
1313 }
1314
1315 // Calculate minimum value for dynamic payment model
1316 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1317         // Addon is zero by default
1318         $addon = '0';
1319
1320         // Percentage part
1321         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1322
1323         // Get total users
1324         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1325
1326         // Get online users
1327         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1328
1329         // Calculate addon
1330         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1331
1332         // Get total URLs
1333         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1334
1335         // Get user's total URLs
1336         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1337
1338         // Calculate addon
1339         if ($totalUrls > 0) {
1340                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1341         } else {
1342                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1343         }
1344
1345         // Return addon
1346         return $addon;
1347 }
1348
1349 // Calculate maximum value for dynamic payment model
1350 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1351         // Addon is zero by default
1352         $addon = '0';
1353
1354         // Maximum value
1355         $max = log(2);
1356
1357         // Percentage part
1358         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1359
1360         // Get total users
1361         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1362
1363         // Calculate addon
1364         $addon += abs($max * $percent * $totalUsers);
1365
1366         // Get total URLs
1367         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1368
1369         // Calculate addon
1370         $addon += abs($max * $percent * $totalUrls);
1371
1372         // Return addon
1373         return $addon;
1374 }
1375
1376 // Calculate dynamic lock
1377 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1378         // Default lock is 30 seconds
1379         $addon = 30;
1380
1381         // Get online users
1382         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1383
1384         // Calculate lock
1385         $addon = abs(log($onlineUsers / $addon + 1));
1386
1387         // Return value
1388         return $addon;
1389 }
1390
1391 // "Getter" for lock ids array
1392 function SURFBAR_GET_LOCK_IDS () {
1393         // Prepare some arrays
1394         $IDs = array();
1395         $USE = array();
1396         $ignored = array();
1397
1398         // Get all id from locks within the timestamp
1399         $result = SQL_QUERY_ESC("SELECT `id`, `url_id`, UNIX_TIMESTAMP(`last_surfed`) AS last_surfed
1400 FROM
1401         `{?_MYSQL_PREFIX?}_surfbar_locks`
1402 WHERE
1403         `userid`=%s
1404 ORDER BY
1405         `id` ASC", array(getMemberId()),
1406         __FUNCTION__, __LINE__);
1407
1408         // Load all entries
1409         while ($content = SQL_FETCHARRAY($result)) {
1410                 // Debug message
1411                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1412
1413                 // Skip entries that are too old
1414                 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1415                         // Debug message
1416                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1417
1418                         // Add only if missing or bigger
1419                         if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1420                                 // Debug message
1421                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1422
1423                                 // Add this id
1424                                 $IDs[$content['url_id']] = $content['last_surfed'];
1425                                 $USE[$content['url_id']] = $content['id'];
1426                         } // END - if
1427                 } else {
1428                         // Debug message
1429                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1430
1431                         // Ignore these old entries!
1432                         $ignored[] = $content['url_id'];
1433                         unset($IDs[$content['url_id']]);
1434                         unset($USE[$content['url_id']]);
1435                 }
1436         } // END - while
1437
1438         // Free result
1439         SQL_FREERESULT($result);
1440
1441         // Return array
1442         return $USE;
1443 }
1444
1445 // "Getter" for maximum random number
1446 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1447         // Count max availabe entries
1448         $result = SQL_QUERY("SELECT sbu.id AS cnt
1449 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1450 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1451 ON sbu.id=sbs.url_id
1452 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1453 ON sbu.id=l.url_id
1454 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."
1455 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1456
1457         // Log last query
1458         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1459
1460         // Fetch max rand
1461         $maxRand = SQL_NUMROWS($result);
1462
1463         // Free result
1464         SQL_FREERESULT($result);
1465
1466         // Return value
1467         return $maxRand;
1468 }
1469
1470 // Load all URLs of the current user and return it as an array
1471 function SURFBAR_GET_USER_URLS () {
1472         // Init array
1473         $URLs = array();
1474
1475         // Begin the query
1476         $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
1477 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1478 WHERE u.userid=%s AND u.status != 'DELETED'
1479 ORDER BY u.id ASC",
1480         array(getMemberId()), __FUNCTION__, __LINE__);
1481
1482         // Are there entries?
1483         if (SQL_NUMROWS($result) > 0) {
1484                 // Load all rows
1485                 while ($row = SQL_FETCHARRAY($result)) {
1486                         // Add the row
1487                         $URLs[$row['id']] = $row;
1488                 } // END - while
1489         } // END - if
1490
1491         // Free result
1492         SQL_FREERESULT($result);
1493
1494         // Return the array
1495         return $URLs;
1496 }
1497
1498 // "Getter" for member action array for given status
1499 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1500         // Init array
1501         $returnArray = array();
1502
1503         // Get all assigned actions
1504         $result = SQL_QUERY_ESC("SELECT action FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1505         array($status), __FUNCTION__, __LINE__);
1506
1507         // Some entries there?
1508         if (SQL_NUMROWS($result) > 0) {
1509                 // Load all actions
1510                 // @TODO This can be somehow rewritten
1511                 while ($content = SQL_FETCHARRAY($result)) {
1512                         $returnArray[] = $content['action'];
1513                 } // END - if
1514         } // END - if
1515
1516         // Free result
1517         SQL_FREERESULT($result);
1518
1519         // Return result
1520         return $returnArray;
1521 }
1522
1523 // Reload to configured stop page
1524 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1525         // Internal or external?
1526         if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1527                 // Reload to internal page
1528                 redirectToUrl('surfbar.php?frame=' . $page);
1529         } else {
1530                 // Reload to external page
1531                 redirectToConfiguredUrl('surfbar_pause_url');
1532         }
1533 }
1534
1535 // Determine next id for surfbar or get data for given id, always call this before you call other
1536 // getters below this function!!!
1537 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1538         // Default is no id and no random number
1539         $nextId = '0';
1540         $randNum = '0';
1541
1542         // Is the id set?
1543         if ($urlId == '0') {
1544                 // Get array with lock ids
1545                 $USE = SURFBAR_GET_LOCK_IDS();
1546
1547                 // Shall we add some URL ids to ignore?
1548                 $add = '';
1549                 if (count($USE) > 0) {
1550                         // Ignore some!
1551                         $add = " AND sbu.id NOT IN (";
1552                         foreach ($USE as $url_id => $lid) {
1553                                 // Add URL id
1554                                 $add .= $url_id.',';
1555                         } // END - foreach
1556
1557                         // Add closing bracket
1558                         $add = substr($add, 0, -1) . ')';
1559                 } // END - if
1560
1561                 // Determine depleted user account
1562                 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1563
1564                 // Get maximum randomness factor
1565                 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['userid'], $add);
1566
1567                 // If more than one URL can be called generate the random number!
1568                 if ($maxRand > 1) {
1569                         // Generate random number
1570                         $randNum = mt_rand(0, ($maxRand - 1));
1571                 } // END - if
1572
1573                 // And query the database
1574                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1575                 $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
1576 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1577 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1578 ON sbu.id=sbs.url_id
1579 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1580 ON sbu.id=l.url_id
1581 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."
1582 GROUP BY sbu.id
1583 ORDER BY l.last_surfed ASC, sbu.id ASC
1584 LIMIT %s,1",
1585                         array($randNum), __FUNCTION__, __LINE__
1586                 );
1587         } else {
1588                 // Get data from specified id number
1589                 $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
1590 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1591 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1592 ON sbu.id=sbs.url_id
1593 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1594 ON sbu.id=l.url_id
1595 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))
1596 LIMIT 1",
1597                         array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1598                 );
1599         }
1600
1601         // Is there an id number?
1602         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1603         if (SQL_NUMROWS($result) == 1) {
1604                 // Load/cache data
1605                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1606                 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1607                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1608
1609                 // Determine waiting time
1610                 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1611
1612                 // Is the last salt there?
1613                 if (is_null($GLOBALS['surfbar_cache']['last_salt'])) {
1614                         // Then repair it wit the static!
1615                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1616                         $GLOBALS['surfbar_cache']['last_salt'] = '';
1617                 } // END - if
1618
1619                 // Fix missing last_surfed
1620                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1621                         // Fix it here
1622                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1623                         $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1624                 } // END - if
1625
1626                 // Get base/fixed reward and costs
1627                 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1628                 $GLOBALS['surfbar_cache']['costs']  = SURFBAR_DETERMINE_COSTS();
1629                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1630
1631                 // Only in dynamic model add the dynamic bonus!
1632                 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1633                         // Calculate dynamic reward/costs and add it
1634                         $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1635                         $GLOBALS['surfbar_cache']['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1636                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1637                 } // END - if
1638
1639                 // Now get the id
1640                 $nextId = SURFBAR_GET_ID();
1641         } // END - if
1642
1643         // Free result
1644         SQL_FREERESULT($result);
1645
1646         // Return result
1647         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1648         return $nextId;
1649 }
1650
1651 // -----------------------------------------------------------------------------
1652 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1653 // THE $GLOBALS['surfbar_cache'] ARRAY!
1654 // -----------------------------------------------------------------------------
1655
1656 // Initializes the surfbar
1657 function SURFBAR_INIT () {
1658         // Init cache array
1659         $GLOBALS['surfbar_cache'] = array();
1660 }
1661
1662 // Private getter for data elements
1663 function SURFBAR_GET_DATA ($element) {
1664         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1665
1666         // Default is null
1667         $data = null;
1668
1669         // Is the entry there?
1670         if (isset($GLOBALS['surfbar_cache'][$element])) {
1671                 // Then take it
1672                 $data = $GLOBALS['surfbar_cache'][$element];
1673         } else { // END - if
1674                 print("<pre>");
1675                 print_r($GLOBALS['surfbar_cache']);
1676                 print("</pre>");
1677                 debug_report_bug();
1678         }
1679
1680         // Return result
1681         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1682         return $data;
1683 }
1684
1685 // Getter for reward from cache
1686 function SURFBAR_GET_REWARD () {
1687         // Get data element and return its contents
1688         return SURFBAR_GET_DATA('reward');
1689 }
1690
1691 // Getter for costs from cache
1692 function SURFBAR_GET_COSTS () {
1693         // Get data element and return its contents
1694         return SURFBAR_GET_DATA('costs');
1695 }
1696
1697 // Getter for URL from cache
1698 function SURFBAR_GET_URL () {
1699         // Get data element and return its contents
1700         return SURFBAR_GET_DATA('url');
1701 }
1702
1703 // Getter for salt from cache
1704 function SURFBAR_GET_SALT () {
1705         // Get data element and return its contents
1706         return SURFBAR_GET_DATA('salt');
1707 }
1708
1709 // Getter for id from cache
1710 function SURFBAR_GET_ID () {
1711         // Get data element and return its contents
1712         return SURFBAR_GET_DATA('id');
1713 }
1714
1715 // Getter for userid from cache
1716 function SURFBAR_GET_USERID () {
1717         // Get data element and return its contents
1718         return SURFBAR_GET_DATA('userid');
1719 }
1720
1721 // Getter for user reload locks
1722 function SURFBAR_GET_USER_LOCKS () {
1723         // Get data element and return its contents
1724         return SURFBAR_GET_DATA('user_locks');
1725 }
1726
1727 // Getter for reload time
1728 function SURFBAR_GET_RELOAD_TIME () {
1729         // Get data element and return its contents
1730         return SURFBAR_GET_DATA('time');
1731 }
1732
1733 // Getter for allowed views
1734 function SURFBAR_GET_VIEWS_ALLOWED () {
1735         // Get data element and return its contents
1736         return SURFBAR_GET_DATA('views_allowed');
1737 }
1738
1739 // Getter for fixed reload
1740 function SURFBAR_GET_FIXED_RELOAD () {
1741         // Get data element and return its contents
1742         return SURFBAR_GET_DATA('fixed_reload');
1743 }
1744
1745 // Getter for surf lock
1746 function SURFBAR_GET_SURF_LOCK () {
1747         // Get data element and return its contents
1748         return SURFBAR_GET_DATA('surf_lock');
1749 }
1750
1751 // Getter for new status
1752 function SURFBAR_GET_NEW_STATUS () {
1753         // Get data element and return its contents
1754         return SURFBAR_GET_DATA('new_status');
1755 }
1756
1757 // [EOF]
1758 ?>