A lot texts rewritten and exclamation signs removed
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
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.                                  *
27  *                                                                      *
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.                         *
32  *                                                                      *
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,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 }
43
44 // -----------------------------------------------------------------------------
45 //                               Admin functions
46 // -----------------------------------------------------------------------------
47 //
48 // Admin has added an URL with given user id and so on
49 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
50         // Do some pre-checks
51         if (!isAdmin()) {
52                 // Not an admin
53                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Not admin.", $url, $limit, $reload));
54                 return false;
55         } elseif (!isUrlValid($url)) {
56                 // URL invalid
57                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : Invalid URL.", $url, $limit, $reload));
58                 return false;
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));
62                 return false;
63         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
64                 // No more allowed!
65                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s : No more URLs allowed.", $url, $limit, $reload));
66                 return false;
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));
70                 return false;
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));
74                 return false;
75         }
76
77         // Register the new URL
78         return SURFBAR_REGISTER_URL($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
79 }
80
81 // Admin unlocked an email so we can migrate the URL
82 function SURFBAR_ADMIN_MIGRATE_URL ($url, $userid) {
83         // Do some pre-checks
84         if (!isAdmin()) {
85                 // Not an admin
86                 return false;
87         } elseif (!isUrlValid($url)) {
88                 // URL invalid
89                 return false;
90         } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
91                 // URL already found in surfbar!
92                 return false;
93         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
94                 // No more allowed!
95                 return false;
96         }
97
98         // Register the new URL
99         return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
100 }
101
102 // Admin function for unlocking URLs
103 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
104         // Is this an admin or invalid array?
105         if (!isAdmin()) {
106                 // Not admin or invalid ids array
107                 return false;
108         } elseif (!is_array($IDs)) {
109                 // No array
110                 return false;
111         } elseif (count($IDs) == 0) {
112                 // Empty array
113                 return false;
114         }
115
116         // Set to true to make AND expression valid if first URL got unlocked
117         $done = true;
118
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')));
123         } // END - if
124
125         // Return total status
126         return $done;
127 }
128
129 // Admin function for rejecting URLs
130 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
131         // Is this an admin or invalid array?
132         if (!isAdmin()) {
133                 // Not admin or invalid ids array
134                 return false;
135         } elseif (!is_array($IDs)) {
136                 // No array
137                 return false;
138         } elseif (count($IDs) == 0) {
139                 // Empty array
140                 return false;
141         }
142
143         // Set to true to make AND expression valid if first URL got unlocked
144         $done = true;
145
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')));
150         } // END - if
151
152         // Return total status
153         return $done;
154 }
155
156 //
157 // -----------------------------------------------------------------------------
158 //                               Member functions
159 // -----------------------------------------------------------------------------
160 //
161 // Member has added an URL
162 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
163         // Do some pre-checks
164         if (!isMember()) {
165                 // Not a member
166                 return false;
167         } elseif ((!isUrlValid($url)) && (!isAdmin())) {
168                 // URL invalid
169                 return false;
170         } elseif (SURFBAR_LOOKUP_BY_URL($url, getUserId())) {
171                 // URL already found in surfbar!
172                 return false;
173         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getUserId())) {
174                 // No more allowed!
175                 return false;
176         } elseif (''.($limit + 0).'' != ''.$limit.'') {
177                 // Invalid amount entered
178                 return false;
179         }
180
181         // Register the new URL
182         return SURFBAR_REGISTER_URL($url, getUserId(), 'PENDING', 'reg', array('limit' => $limit));
183 }
184
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);
189
190         // Init HTML code
191         $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
192 <tr>\n";
193
194         // Calculate width
195         $width = round(100 / count($actionArray));
196
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(
201                         'width'    => $width,
202                         'id'       => bigintval($urlId),
203                         'action'   => strtolower($action),
204                         'title'    => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE--}',
205                         'submit'   => '{--MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT--}',
206                 ));
207         } // END - foreach
208
209         // Close table
210         $OUT .= "</tr>
211 </table>\n";
212
213         // Return code
214         return $OUT;
215 }
216
217 // Do the member form request
218 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
219         // By default no action is performed
220         $performed = false;
221
222         // Is this a member?
223         if (!isMember()) {
224                 // No member!
225                 return false;
226         } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
227                 // Important form elements are missing!
228                 return false;
229         } elseif (!isset($URLs[$formData['id']])) {
230                 // id not found in cache
231                 return false;
232         } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
233                 // Action not allowed for current URL status
234                 return false;
235         }
236
237         // Secure action
238         $action = SQL_ESCAPE(secureString($formData['action']));
239
240         // Has it changed?
241         if ($action != $formData['action']) {
242                 // Invalid data in action found
243                 return false;
244         } // END - if
245
246         // Create the function name for selected action
247         $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
248
249         // Is the function there?
250         if (function_exists($functionName)) {
251                 // Add new status
252                 $URLs[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
253
254                 // Extract URL data for call-back
255                 $urlData = array(merge_array($URLs[$formData['id']], array($action => $formData)));
256
257                 // Action found so execute it
258                 $performed = call_user_func_array($functionName, $urlData);
259         } else {
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));
263         }
264
265         // Return status
266         return $performed;
267 }
268
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__);
274
275         // Is the entry there?
276         $isValid = (SQL_NUMROWS($result) == 1);
277
278         // Fetch the new status if found
279         if ($isValid) {
280                 // Load new status
281                 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
282         } // END - if
283
284         // Free result
285         SQL_FREERESULT($result);
286
287         // Return status
288         return $isValid;
289 }
290
291 //
292 // -----------------------------------------------------------------------------
293 //                               Member actions
294 // -----------------------------------------------------------------------------
295 //
296 // Retreat a booked URL
297 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
298         // Create the data array for next function call
299         $data = array(
300         $urlData['id'] => $urlData
301         );
302
303         // Simply change the status here
304         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
305 }
306
307 // Book an URL now (from migration)
308 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
309         // Create the data array for next function call
310         $data = array(
311         $urlData['id'] => $urlData
312         );
313
314         // Simply change the status here
315         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
316 }
317
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);
324         } // END - if
325
326         // Display form
327         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
328 }
329
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);
336         } // END - if
337
338         // Display form
339         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
340 }
341
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));
345 }
346
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'];
353
354         // Return status change
355         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['status'], $urlData['new_status'], array($urlData['id'] => $urlData));
356 }
357
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));
361 }
362
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);
371
372         // Is the lock reason empty?
373         if (empty($urlData['lock_reason'])) {
374                 // Fix it to three dashes
375                 $urlData['lock_reason'] = '---';
376         } // END - if
377
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';
384
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';
391                 } // END - if
392         } // END - if
393
394         // Load the form and display it
395         loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
396
397         // All fine by default ... ;-)
398         return true;
399 }
400
401 // Execute choosen action
402 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
403         // By default nothing is executed
404         $executed = false;
405
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;
410         } // END - if
411
412         // Construct function name
413         $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
414
415         // Is 'userid' set and not 'userid' ?
416         if ((!isset($urlData['userid'])) && (isset($urlData['userid']))) {
417                 // Auto-fix this
418                 $urlData['userid'] = $urlData['userid'];
419         } // END - if
420
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));
427                 } // END - if
428         } else {
429                 // Not found!
430                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('MEMBER_SURFBAR_EXECUTE_ACTION_404'), $functionName);
431         }
432
433         // Return status
434         return $executed;
435 }
436 // "Execute edit" function: Update changed data
437 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
438         // Default is nothing done
439         $status = false;
440
441         // Translate URLs for testing
442         $url1 = compileCode($urlData['url']);
443         $url2 = compileCode($urlData['edit']['url']);
444
445         // Has the URL or limit changed?
446         if (true) {
447                 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
448                 // Run the query
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__);
451
452                 // All fine
453                 $status = true;
454         }
455
456         // Return status
457         return $status;
458 }
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)
462         return true;
463 }
464 //
465 // -----------------------------------------------------------------------------
466 //                           Self-maintenance functions
467 // -----------------------------------------------------------------------------
468 //
469 // Main function
470 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
471         // Handle URLs which limit has depleted so we can stop them
472         SURFBAR_HANDLE_DEPLETED_VIEWS();
473
474         // Handle low-points amounts
475         SURFBAR_HANDLE_LOW_POINTS();
476 }
477 // Handle URLs which limit has depleted
478 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
479         // Get all URLs
480         $urlArray = SURFBAR_GET_URL_DATA(0, 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
481
482         // Do we have some entries?
483         if (count($urlArray) > 0) {
484                 // Then handle all!
485                 foreach ($urlArray as $id => $urlData) {
486                         // Backup data
487                         $data = $urlData;
488
489                         // Rewrite array for next call
490                         $urlData[$id] = $data;
491
492                         // Handle the status
493                         SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
494                 } // END - foreach
495         } // END - if
496 }
497
498 // Alert users which have URLs booked and are low on points amount
499 function SURFBAR_HANDLE_LOW_POINTS () {
500         // Get all userids
501         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
502
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')) {
507                         // Prepare content
508                         $content = array(
509                                 'userid'      => $userid,
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'))
514                         );
515
516                         // Notify this user
517                         SURFBAR_NOTIFY_USER('low_points', $content);
518
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__);
522                 } // END - if
523         } // END - foreach
524 }
525
526 //
527 // -----------------------------------------------------------------------------
528 //                               Generic functions
529 // -----------------------------------------------------------------------------
530 //
531
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)));
536
537         // Was it found?
538         return (count($urlArray) > 0);
539 }
540
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();
545
546         // Is the column an id number?
547         if (($column == 'id') || ($column == 'userid')) {
548                 // Extra secure input
549                 $searchTerm = bigintval($searchTerm);
550         } // END - if
551
552         // If the column is 'id' there can be only one entry
553         $limit = '';
554         if ($column == 'id') {
555                 $limit = "LIMIT 1";
556         } // END - if
557
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."
562 ORDER BY %s %s
563 %s",
564         array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
565
566         // Is there at least one record?
567         if (SQL_NUMROWS($result) > 0) {
568                 // Then load all!
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;
574                         } else {
575                                 // Group entries
576                                 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
577                         }
578                 } // END - while
579         } // END - if
580
581         // Free the result
582         SQL_FREERESULT($result);
583
584         // Return the result
585         return $GLOBALS['last_url_data'];
586 }
587
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') {
592                 $status = 'PENDING';
593         } // END - if
594
595         // Prepare content
596         $content = merge_array($extraFields, array(
597                 'url'         => $url,
598                 'frametester' => generateFrametesterUrl($url),
599                 'userid'         => $userid,
600                 'status'      => $status,
601         ));
602
603         // Is limit/reload set?
604         if (!isset($config['limit'])) {
605                 $content['limit']  = 0;
606         } // END - if
607         if (!isset($config['reload'])) {
608                 $content['reload'] = 0;
609         } // END - if
610
611         // Insert the URL into database
612         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
613
614         // Is this id valid?
615         if ($content['insert_id'] == 0) {
616                 // INSERT did not insert any data!
617                 return false;
618         } // END - if
619
620         // Translate status and limit
621         $content['limit'] = translateSurfbarLimit($content['limit']);
622
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);
627         } // END - if
628
629         // Send mail to user
630         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
631
632         // Return the insert id
633         return $content['insert_id'];
634 }
635
636 // Inserts an url by given data array and return the insert id
637 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
638         // Get userid
639         $userid = bigintval($urlData['userid']);
640
641         // Is the id set?
642         if (empty($userid)) $userid = 0;
643
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)",
646         array(
647         $userid,
648         $urlData['url'],
649         $urlData['status'],
650         $urlData['limit'],
651         $urlData['limit'],
652         $urlData['reload']
653         ), __FUNCTION__, __LINE__
654         );
655
656         // Return insert id
657         return SQL_INSERTID();
658 }
659
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);
664
665         // Prepare subject
666         $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
667                 strtoupper($messageType)
668         ));
669
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');
674         } // END - if
675
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']);
683
684         // Send the notification out
685         return sendAdminNotification($subject, $templateName, $content, $content['userid']);
686 }
687
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) {
692                 return false;
693         } // END - if
694
695         // Prepare template name
696         $templateName = sprintf("member_surfbar_%s", $messageType);
697
698         // Prepare subject
699         $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
700         strtoupper($messageType)
701         ));
702
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');
707         } // END - if
708
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']);
716
717         // Load template
718         $mailText = loadEmailTemplate($templateName, $content, $content['userid']);
719
720         // Send the email
721         return sendEmail($content['userid'], $subject, $mailText);
722 }
723
724 // Translates the limit
725 function translateSurfbarLimit ($limit) {
726         // Is this zero?
727         if ($limit == 0) {
728                 // Unlimited!
729                 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
730         } else {
731                 // Translate comma
732                 $return = translateComma($limit);
733         }
734
735         // Return value
736         return $return;
737 }
738
739 // Translate the URL status
740 function translateSurfbarUrlStatus ($status) {
741         // Create constant name
742         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
743
744         // Set default translated status
745         $statusTranslated = '!'.$constantName.'!';
746
747         // Is the constant there?
748         if (defined($constantName)) {
749                 // Then get it's value
750                 $statusTranslated = constant($constantName);
751         } // END - if
752
753         // Return result
754         return $statusTranslated;
755 }
756
757 // Determine reward
758 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
759         // Static values are default
760         $reward = getConfig('surfbar_static_reward');
761
762         // Do we have static or dynamic?
763         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
764                 // "Calculate" dynamic reward
765                 if ($onlyMin) {
766                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
767                 } else {
768                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
769                 }
770         } // END - if
771
772         // Return reward
773         return $reward;
774 }
775
776 // Determine costs
777 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
778         // Static costs is default
779         $costs  = getConfig('surfbar_static_costs');
780
781         // Do we have static or dynamic?
782         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
783                 // "Calculate" dynamic costs
784                 if ($onlyMin) {
785                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
786                 } else {
787                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
788                 }
789         } // END - if
790
791         // Return costs
792         return $costs;
793 }
794
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();
800
801         // "Calculate" dynamic part and return it
802         return mt_rand($min, $max);
803 }
804
805 // Determine right template name
806 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
807         // Default is the frameset
808         $templateName = "surfbar_frameset";
809
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')
815                 );
816         } // END - if
817
818         // Return result
819         return $templateName;
820 }
821
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() {
825         // Default is full!
826         $isFull = true;
827
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);
831
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();
836         } // END - if
837
838         // Ask the database
839         $result = SQL_QUERY_ESC("SELECT
840         COUNT(l.id) AS cnt
841 FROM
842         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
843 INNER JOIN
844         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
845 ON
846         u.id=l.url_id
847 WHERE
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)
849 LIMIT 1",
850                 array(getUserId()), __FUNCTION__, __LINE__
851         );
852
853         // Fetch row
854         list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
855
856         // Is it null?
857         if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
858                 // Then fix it to zero!
859                 $GLOBALS['surfbar_cache']['user_locks'] = 0;
860         } // END - if
861
862         // Free result
863         SQL_FREERESULT($result);
864
865         // Get total URLs
866         $total = SURFBAR_GET_TOTAL_URLS();
867
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));
871
872         // Return result
873         return $isFull;
874 }
875
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();
880
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!
884                 return 0;
885         } // END - if
886
887         // Is the exlude userid set?
888         if ($excludeUserId > 0) {
889                 // Then add it
890                 $UIDs['userid'][$excludeUserId] = $excludeUserId;
891         } // END - if
892
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__
898         );
899
900         // Fetch row
901         list($cnt) = SQL_FETCHROW($result);
902
903         // Free result
904         SQL_FREERESULT($result);
905
906         // Return result
907         return $cnt;
908 }
909
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')));
914 }
915
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) {
923                 // Error!
924                 return (getConfig('surfbar_max_order') + 1);
925         }
926
927         // Default is all URLs
928         $add = '';
929
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);
943         }
944
945         // Get amount from database
946         $cnt = countSumTotalData($userid, 'surfbar_urls', 'id', 'userid', true, $add);
947
948         // Return result
949         return $cnt;
950 }
951
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';
956
957         // Get code length from config
958         $length = getConfig('code_length');
959
960         // Fix length to 10
961         if ($length == 0) $length = 10;
962
963         // Generate a code until the length matches
964         $valCode = '';
965         while (strlen($valCode) != $length) {
966                 // Is the salt set?
967                 if (empty($salt)) {
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);
971                 } else {
972                         // Use this as salt!
973                         $GLOBALS['surfbar_cache']['salt'] = $salt;
974                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
975                 }
976
977                 // ... and now the validation code
978                 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getUserId());
979                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
980         } // END - while
981
982         // Hash it with md5() and salt it with the random string
983         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
984
985         // Finally encrypt it PGP-like and return it
986         $valHashedCode = generatePassString($hashedCode);
987
988         // Return hashed value
989         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
990         return $valHashedCode;
991 }
992
993 // Check validation code
994 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
995         // Secure id number
996         $urlId = bigintval($urlId);
997
998         // Now generate the code again
999         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1000
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')));
1005 }
1006
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__);
1014
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__);
1018 }
1019
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());
1026         } // END - if
1027
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'));
1031 }
1032
1033 // Updates the statistics of current URL/userid
1034 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1035         // Init add
1036         $add = '';
1037
1038         // Get allowed views
1039         $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1040
1041         // Do we have a limit?
1042         if ($allowed > 0) {
1043                 // Then count views_max down!
1044                 $add .= ", `views_max`=`views_max`-1";
1045         } // END - if
1046
1047         // Update URL stats
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__);
1050
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__);
1054
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__);
1060         } // END - if
1061
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');
1067
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), '+');
1070 }
1071
1072 // Update the salt for validation and statistics
1073 function SURFBAR_UPDATE_SALT_STATS () {
1074         // Update statistics record
1075         SURFBAR_UPDATE_INSERT_STATS_RECORD();
1076
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__);
1080
1081         // Debug message
1082         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getUserId().'', false);
1083
1084         // Was that okay?
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__);
1089         } // END - if
1090
1091         // Debug message
1092         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1093
1094         // Return if the update was okay
1095         return (SQL_AFFECTEDROWS() == 1);
1096 }
1097
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);
1101         // Ask the database
1102         $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1103 FROM
1104         `{?_MYSQL_PREFIX?}_surfbar_locks`
1105 WHERE
1106         `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1107 ORDER BY
1108         `last_surfed` ASC
1109 LIMIT 1",
1110                 array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1111         );
1112
1113         // Fetch counter
1114         list($cnt) = SQL_FETCHROW($result);
1115
1116         // Free result
1117         SQL_FREERESULT($result);
1118
1119         // Return check
1120         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1121         return ($cnt == 1);
1122 }
1123
1124 // Determine which user hash no more points left
1125 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1126         // Init array
1127         $UIDs = array(
1128                 'userid'      => array(),
1129                 'points'   => array(),
1130                 'notified' => array(),
1131         );
1132
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;
1139
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
1143 FROM
1144         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1145 INNER JOIN
1146         `{?_MYSQL_PREFIX?}_user_data` AS d
1147 ON
1148         u.userid=d.userid
1149 WHERE
1150         u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1151 GROUP BY
1152         u.userid
1153 ORDER BY
1154         u.userid ASC",
1155                         array(getUserId()), __FUNCTION__, __LINE__);
1156         } else {
1157                 // Get all userid
1158                 $result = SQL_QUERY("SELECT
1159         u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1160 FROM
1161         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1162 INNER JOIN
1163         `{?_MYSQL_PREFIX?}_user_data` AS d
1164 ON
1165         u.userid=d.userid
1166 WHERE
1167         u.`status`='ACTIVE'
1168 GROUP BY
1169         u.userid
1170 ORDER BY
1171         u.userid ASC", __FUNCTION__, __LINE__);
1172         }
1173
1174         // Load all userid
1175         while ($content = SQL_FETCHARRAY($result)) {
1176                 // Get total points
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);
1179
1180                 // Shall we add this to ignore?
1181                 if ($points <= $limit) {
1182                         // Ignore this one!
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'];
1187                 } // END - if
1188         } // END - while
1189
1190         // Free result
1191         SQL_FREERESULT($result);
1192
1193         // Debug message
1194         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".getUserId().')', false);
1195
1196         // Return result
1197         return $UIDs;
1198 }
1199
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
1204         `id`
1205 FROM
1206         `{?_MYSQL_PREFIX?}_surfbar_stats`
1207 WHERE
1208         (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`last_surfed`)) <= {?online_timeout?}
1209 GROUP BY
1210         `userid` ASC", __FUNCTION__, __LINE__);
1211
1212         // Fetch count
1213         $cnt = SQL_NUMROWS($result);
1214
1215         // Free result
1216         SQL_FREERESULT($result);
1217
1218         // Return result
1219         return $cnt;
1220 }
1221
1222 // Determine waiting time for one URL
1223 function SURFBAR_DETERMINE_WAIT_TIME () {
1224         // Get fixed reload lock
1225         $fixed = SURFBAR_GET_FIXED_RELOAD();
1226
1227         // Is the fixed reload time set?
1228         if ($fixed > 0) {
1229                 // Return it
1230                 return $fixed;
1231         } // END - if
1232
1233         // Static time is default
1234         $time = getConfig('surfbar_static_time');
1235
1236         // Which payment model do we have?
1237         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1238                 // "Calculate" dynamic time
1239                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1240         } // END - if
1241
1242         // Return value
1243         return $time;
1244 }
1245
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);
1250
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);
1255         } // END - if
1256
1257         // Is the new status set?
1258         if ((!is_string($newStatus)) || (empty($newStatus))) {
1259                 // Abort here, but fine!
1260                 return true;
1261         } // END - if
1262
1263         // Is the status like prevStatus is saying?
1264         if ($data[$urlId]['status'] != $prevStatus) {
1265                 // No, then abort here
1266                 return false;
1267         } // END - if
1268
1269
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! ---------
1275
1276         // Was that fine?
1277         // ---------- Comment out for debugging/developing member actions! ---------
1278         //if (SQL_AFFECTEDROWS() != 1) {
1279         //      // No, something went wrong
1280         //      return false;
1281         //} // END - if
1282         // ---------- Comment out for debugging/developing member actions! ---------
1283
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'));
1289
1290         // Do some dirty fixing here:
1291         if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1292                 // Fix for template change
1293                 $newStatus = 'continued';
1294         } // END - if
1295
1296         // Send admin notification
1297         SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1298
1299         // Send user notification
1300         SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1301
1302         // All done!
1303         return true;
1304 }
1305
1306 // Calculate minimum value for dynamic payment model
1307 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1308         // Addon is zero by default
1309         $addon = 0;
1310
1311         // Percentage part
1312         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1313
1314         // Get total users
1315         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1316
1317         // Get online users
1318         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1319
1320         // Calculate addon
1321         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1322
1323         // Get total URLs
1324         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1325
1326         // Get user's total URLs
1327         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1328
1329         // Calculate addon
1330         if ($totalUrls > 0) {
1331                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1332         } else {
1333                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1334         }
1335
1336         // Return addon
1337         return $addon;
1338 }
1339
1340 // Calculate maximum value for dynamic payment model
1341 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1342         // Addon is zero by default
1343         $addon = 0;
1344
1345         // Maximum value
1346         $max = log(2);
1347
1348         // Percentage part
1349         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1350
1351         // Get total users
1352         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1353
1354         // Calculate addon
1355         $addon += abs($max * $percent * $totalUsers);
1356
1357         // Get total URLs
1358         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1359
1360         // Calculate addon
1361         $addon += abs($max * $percent * $totalUrls);
1362
1363         // Return addon
1364         return $addon;
1365 }
1366
1367 // Calculate dynamic lock
1368 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1369         // Default lock is 30 seconds
1370         $addon = 30;
1371
1372         // Get online users
1373         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1374
1375         // Calculate lock
1376         $addon = abs(log($onlineUsers / $addon + 1));
1377
1378         // Return value
1379         return $addon;
1380 }
1381
1382 // "Getter" for lock ids array
1383 function SURFBAR_GET_LOCK_IDS () {
1384         // Prepare some arrays
1385         $IDs = array();
1386         $USE = array();
1387         $ignored = array();
1388
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
1391 FROM
1392         `{?_MYSQL_PREFIX?}_surfbar_locks`
1393 WHERE
1394         `userid`=%s
1395 ORDER BY
1396         `id` ASC", array(getUserId()),
1397         __FUNCTION__, __LINE__);
1398
1399         // Load all entries
1400         while ($content = SQL_FETCHARRAY($result)) {
1401                 // Debug message
1402                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1403
1404                 // Skip entries that are too old
1405                 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1406                         // Debug message
1407                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1408
1409                         // Add only if missing or bigger
1410                         if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1411                                 // Debug message
1412                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1413
1414                                 // Add this id
1415                                 $IDs[$content['url_id']] = $content['last_surfed'];
1416                                 $USE[$content['url_id']] = $content['id'];
1417                         } // END - if
1418                 } else {
1419                         // Debug message
1420                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1421
1422                         // Ignore these old entries!
1423                         $ignored[] = $content['url_id'];
1424                         unset($IDs[$content['url_id']]);
1425                         unset($USE[$content['url_id']]);
1426                 }
1427         } // END - while
1428
1429         // Free result
1430         SQL_FREERESULT($result);
1431
1432         // Return array
1433         return $USE;
1434 }
1435
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
1444 ON sbu.id=l.url_id
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__);
1447
1448         // Log last query
1449         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1450
1451         // Fetch max rand
1452         $maxRand = SQL_NUMROWS($result);
1453
1454         // Free result
1455         SQL_FREERESULT($result);
1456
1457         // Return value
1458         return $maxRand;
1459 }
1460
1461 // Load all URLs of the current user and return it as an array
1462 function SURFBAR_GET_USER_URLS () {
1463         // Init array
1464         $URLs = array();
1465
1466         // Begin the query
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'
1470 ORDER BY u.id ASC",
1471         array(getUserId()), __FUNCTION__, __LINE__);
1472
1473         // Are there entries?
1474         if (SQL_NUMROWS($result) > 0) {
1475                 // Load all rows
1476                 while ($row = SQL_FETCHARRAY($result)) {
1477                         // Add the row
1478                         $URLs[$row['id']] = $row;
1479                 } // END - while
1480         } // END - if
1481
1482         // Free result
1483         SQL_FREERESULT($result);
1484
1485         // Return the array
1486         return $URLs;
1487 }
1488
1489 // "Getter" for member action array for given status
1490 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1491         // Init array
1492         $returnArray = array();
1493
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__);
1497
1498         // Some entries there?
1499         if (SQL_NUMROWS($result) > 0) {
1500                 // Load all actions
1501                 // @TODO This can be somehow rewritten
1502                 while ($content = SQL_FETCHARRAY($result)) {
1503                         $returnArray[] = $content['action'];
1504                 } // END - if
1505         } // END - if
1506
1507         // Free result
1508         SQL_FREERESULT($result);
1509
1510         // Return result
1511         return $returnArray;
1512 }
1513
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);
1520         } else {
1521                 // Reload to external page
1522                 redirectToConfiguredUrl('surfbar_pause_url');
1523         }
1524 }
1525
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
1530         $nextId = 0;
1531         $randNum = 0;
1532
1533         // Is the id set?
1534         if ($urlId == 0) {
1535                 // Get array with lock ids
1536                 $USE = SURFBAR_GET_LOCK_IDS();
1537
1538                 // Shall we add some URL ids to ignore?
1539                 $add = '';
1540                 if (count($USE) > 0) {
1541                         // Ignore some!
1542                         $add = " AND sbu.id NOT IN (";
1543                         foreach ($USE as $url_id => $lid) {
1544                                 // Add URL id
1545                                 $add .= $url_id.',';
1546                         } // END - foreach
1547
1548                         // Add closing bracket
1549                         $add = substr($add, 0, -1) . ')';
1550                 } // END - if
1551
1552                 // Determine depleted user account
1553                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1554
1555                 // Get maximum randomness factor
1556                 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['userid'], $add);
1557
1558                 // If more than one URL can be called generate the random number!
1559                 if ($maxRand > 1) {
1560                         // Generate random number
1561                         $randNum = mt_rand(0, ($maxRand - 1));
1562                 } // END - if
1563
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
1571 ON sbu.id=l.url_id
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."
1573 GROUP BY sbu.id
1574 ORDER BY l.last_surfed ASC, sbu.id ASC
1575 LIMIT %s,1",
1576                         array($randNum), __FUNCTION__, __LINE__
1577                 );
1578         } else {
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
1585 ON sbu.id=l.url_id
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))
1587 LIMIT 1",
1588                         array(getUserId(), bigintval($urlId)), __FUNCTION__, __LINE__
1589                 );
1590         }
1591
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) {
1595                 // Load/cache data
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);
1599
1600                 // Determine waiting time
1601                 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1602
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'] = '';
1608                 } // END - if
1609
1610                 // Fix missing last_surfed
1611                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1612                         // Fix it here
1613                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1614                         $GLOBALS['surfbar_cache']['last_surfed'] = 0;
1615                 } // END - if
1616
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);
1621
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);
1628                 } // END - if
1629
1630                 // Now get the id
1631                 $nextId = SURFBAR_GET_ID();
1632         } // END - if
1633
1634         // Free result
1635         SQL_FREERESULT($result);
1636
1637         // Return result
1638         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1639         return $nextId;
1640 }
1641
1642 // -----------------------------------------------------------------------------
1643 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1644 // THE $GLOBALS['surfbar_cache'] ARRAY!
1645 // -----------------------------------------------------------------------------
1646
1647 // Initializes the surfbar
1648 function SURFBAR_INIT () {
1649         // Init cache array
1650         $GLOBALS['surfbar_cache'] = array();
1651 }
1652
1653 // Private getter for data elements
1654 function SURFBAR_GET_DATA ($element) {
1655         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1656
1657         // Default is null
1658         $data = null;
1659
1660         // Is the entry there?
1661         if (isset($GLOBALS['surfbar_cache'][$element])) {
1662                 // Then take it
1663                 $data = $GLOBALS['surfbar_cache'][$element];
1664         } else { // END - if
1665                 print("<pre>");
1666                 print_r($GLOBALS['surfbar_cache']);
1667                 print("</pre>");
1668                 debug_report_bug();
1669         }
1670
1671         // Return result
1672         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1673         return $data;
1674 }
1675
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');
1680 }
1681
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');
1686 }
1687
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');
1692 }
1693
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');
1698 }
1699
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');
1704 }
1705
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');
1710 }
1711
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');
1716 }
1717
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');
1722 }
1723
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');
1728 }
1729
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');
1734 }
1735
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');
1740 }
1741
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');
1746 }
1747
1748 // [EOF]
1749 ?>