fooRequestElementBar() functions renamed, adding of request parameters added:
[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  * 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, getMemberId())) {
171                 // URL already found in surfbar!
172                 return false;
173         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
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, getMemberId(), '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 = 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         // Has the URL or limit changed?
442         if (true) {
443                 //if (($urlData['views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
444                 // Run the query
445                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET url='%s', views_allowed=%s, views_max=%s WHERE `id`=%s AND `status`='%s' LIMIT 1",
446                         array($urlData['url'], $urlData['edit']['limit'], $urlData['edit']['limit'], $urlData['id'], $urlData['status']), __FUNCTION__, __LINE__);
447
448                 // All fine
449                 $status = true;
450         } // END - if
451
452         // Return status
453         return $status;
454 }
455 // "Execute delete" function: Does nothing...
456 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
457         // Nothing special to do (see above function for such "special actions" to perform)
458         return true;
459 }
460 //
461 // -----------------------------------------------------------------------------
462 //                           Self-maintenance functions
463 // -----------------------------------------------------------------------------
464 //
465 // Main function
466 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
467         // Handle URLs which limit has depleted so we can stop them
468         SURFBAR_HANDLE_DEPLETED_VIEWS();
469
470         // Handle low-points amounts
471         SURFBAR_HANDLE_LOW_POINTS();
472 }
473 // Handle URLs which limit has depleted
474 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
475         // Get all URLs
476         $urlArray = SURFBAR_GET_URL_DATA(0, 'views_max', 'id', 'ASC', 'id', " AND views_allowed>0 AND `status`='ACTIVE'");
477
478         // Do we have some entries?
479         if (count($urlArray) > 0) {
480                 // Then handle all!
481                 foreach ($urlArray as $id => $urlData) {
482                         // Backup data
483                         $data = $urlData;
484
485                         // Rewrite array for next call
486                         $urlData[$id] = $data;
487
488                         // Handle the status
489                         SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
490                 } // END - foreach
491         } // END - if
492 }
493
494 // Alert users which have URLs booked and are low on points amount
495 function SURFBAR_HANDLE_LOW_POINTS () {
496         // Get all userids
497         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
498
499         // "Walk" through all URLs
500         foreach ($userids['userid'] as $userid => $dummy) {
501                 // Is the last notification far enougth away to notify again?
502                 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
503                         // Prepare content
504                         $content = array(
505                                 'userid'      => $userid,
506                                 'low'      => translateComma(getConfig('surfbar_warn_low_points')),
507                                 'points'   => translateComma($userids['points'][$userid]),
508                                 'notified' => generateDateTime($userids['notified'][$userid]),
509                                 'interval' => createFancyTime(getConfig('surfbar_low_interval'))
510                         );
511
512                         // Notify this user
513                         SURFBAR_NOTIFY_USER('low_points', $content);
514
515                         // Update last notified
516                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET surfbar_low_notified=NOW() WHERE `userid`=%s LIMIT 1",
517                         array($userid), __FUNCTION__, __LINE__);
518                 } // END - if
519         } // END - foreach
520 }
521
522 //
523 // -----------------------------------------------------------------------------
524 //                               Generic functions
525 // -----------------------------------------------------------------------------
526 //
527
528 // Looks up by an URL
529 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
530         // Now lookup that given URL by itself
531         $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'id', 'ASC', 'id', sprintf(" AND `userid`=%s", bigintval($userid)));
532
533         // Was it found?
534         return (count($urlArray) > 0);
535 }
536
537 // Load URL data by given search term and column
538 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'id', $order = 'id', $sort = 'ASC', $group = 'id', $add = '') {
539         // By default nothing is found
540         $GLOBALS['last_url_data'] = array();
541
542         // Is the column an id number?
543         if (($column == 'id') || ($column == 'userid')) {
544                 // Extra secure input
545                 $searchTerm = bigintval($searchTerm);
546         } // END - if
547
548         // If the column is 'id' there can be only one entry
549         $limit = '';
550         if ($column == 'id') {
551                 $limit = "LIMIT 1";
552         } // END - if
553
554         // Look up the record
555         $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, views_max, views_allowed, status, registered, last_locked, lock_reason, views_max, views_allowed, fixed_reload
556 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
557 WHERE %s='%s'".$add."
558 ORDER BY %s %s
559 %s",
560         array($column, $searchTerm, $order, $sort, $limit), __FUNCTION__, __LINE__);
561
562         // Is there at least one record?
563         if (SQL_NUMROWS($result) > 0) {
564                 // Then load all!
565                 while ($dataRow = SQL_FETCHARRAY($result)) {
566                         // Shall we group these results?
567                         if ($group == 'id') {
568                                 // Add the row by id as index
569                                 $GLOBALS['last_url_data'][$dataRow['id']] = $dataRow;
570                         } else {
571                                 // Group entries
572                                 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['id']] = $dataRow;
573                         }
574                 } // END - while
575         } // END - if
576
577         // Free the result
578         SQL_FREERESULT($result);
579
580         // Return the result
581         return $GLOBALS['last_url_data'];
582 }
583
584 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
585 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
586         // Make sure by the user registered URLs are always pending
587         if ($addMode == 'reg') {
588                 $status = 'PENDING';
589         } // END - if
590
591         // Prepare content
592         $content = merge_array($extraFields, array(
593                 'url'         => $url,
594                 'frametester' => generateFrametesterUrl($url),
595                 'userid'         => $userid,
596                 'status'      => $status,
597         ));
598
599         // Is limit/reload set?
600         if (!isset($config['limit'])) {
601                 $content['limit']  = '0';
602         } // END - if
603         if (!isset($config['reload'])) {
604                 $content['reload'] = '0';
605         } // END - if
606
607         // Insert the URL into database
608         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
609
610         // Is this id valid?
611         if ($content['insert_id'] == '0') {
612                 // INSERT did not insert any data!
613                 return false;
614         } // END - if
615
616         // Translate status and limit
617         $content['limit'] = translateSurfbarLimit($content['limit']);
618
619         // If in reg-mode we notify admin
620         if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
621                 // Notify admin even when he as unlocked an email
622                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
623         } // END - if
624
625         // Send mail to user
626         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
627
628         // Return the insert id
629         return $content['insert_id'];
630 }
631
632 // Inserts an url by given data array and return the insert id
633 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
634         // Get userid
635         $userid = bigintval($urlData['userid']);
636
637         // Is the id set?
638         if (empty($userid)) $userid = '0';
639
640         // Just run the insert query for now
641         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_urls` (userid,url,status,views_max,views_allowed,fixed_reload) VALUES (%s,'%s','%s',%s,%s,%s)",
642         array(
643         $userid,
644         $urlData['url'],
645         $urlData['status'],
646         $urlData['limit'],
647         $urlData['limit'],
648         $urlData['reload']
649         ), __FUNCTION__, __LINE__
650         );
651
652         // Return insert id
653         return SQL_INSERTID();
654 }
655
656 // Notify admin(s) with a selected message and content
657 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
658         // Prepare template name
659         $templateName = sprintf("admin_surfbar_%s", $messageType);
660
661         // Prepare subject
662         $subject = getMessage(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
663                 strtoupper($messageType)
664         ));
665
666         // Is the subject line there?
667         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
668                 // Set default subject if following eval() wents wrong
669                 $subject = getMessage('ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
670         } // END - if
671
672         // Translate some data if present
673         if (isset($content['status']))        $content['status']        = translateSurfbarUrlStatus($content['status']);
674         if (isset($content['registered']))    $content['registered']    = generateDateTime($content['registered'], 2);
675         if (isset($content['last_locked']))   $content['last_locked']   = generateDateTime($content['last_locked'], 2);
676         if (isset($content['views_total']))   $content['views_total']   = translateComma($content['views_total']);
677         if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
678         if (isset($content['views_max']))     $content['views_max']     = translateComma($content['views_max']);
679
680         // Send the notification out
681         return sendAdminNotification($subject, $templateName, $content, $content['userid']);
682 }
683
684 // Notify the user about the performed action
685 function SURFBAR_NOTIFY_USER ($messageType, $content) {
686         // Skip notification if userid is zero
687         if ($content['userid'] == '0') {
688                 return false;
689         } // END - if
690
691         // Prepare template name
692         $templateName = sprintf("member_surfbar_%s", $messageType);
693
694         // Prepare subject
695         $subject = getMessage(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
696         strtoupper($messageType)
697         ));
698
699         // Is the subject line there?
700         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
701                 // Set default subject if following eval() wents wrong
702                 $subject = getMessage('MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT');
703         } // END - if
704
705         // Translate some data if present
706         if (isset($content['status']))        $content['status']        = translateSurfbarUrlStatus($content['status']);
707         if (isset($content['registered']))    $content['registered']    = generateDateTime($content['registered'], 2);
708         if (isset($content['last_locked']))   $content['last_locked']   = generateDateTime($content['last_locked'], 2);
709         if (isset($content['views_total']))   $content['views_total']   = translateComma($content['views_total']);
710         if (isset($content['views_allowed'])) $content['views_allowed'] = translateComma($content['views_allowed']);
711         if (isset($content['views_max']))     $content['views_max']     = translateComma($content['views_max']);
712
713         // Load template
714         $mailText = loadEmailTemplate($templateName, $content, $content['userid']);
715
716         // Send the email
717         return sendEmail($content['userid'], $subject, $mailText);
718 }
719
720 // Translates the limit
721 function translateSurfbarLimit ($limit) {
722         // Is this zero?
723         if ($limit == '0') {
724                 // Unlimited!
725                 $return = getMessage('MEMBER_SURFBAR_UNLIMITED_VIEWS');
726         } else {
727                 // Translate comma
728                 $return = translateComma($limit);
729         }
730
731         // Return value
732         return $return;
733 }
734
735 // Translate the URL status
736 function translateSurfbarUrlStatus ($status) {
737         // Create constant name
738         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
739
740         // Get message
741         $statusTranslated = getMessage($constantName);
742
743         // Return result
744         return $statusTranslated;
745 }
746
747 // Determine reward
748 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
749         // Static values are default
750         $reward = getConfig('surfbar_static_reward');
751
752         // Do we have static or dynamic?
753         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
754                 // "Calculate" dynamic reward
755                 if ($onlyMin) {
756                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
757                 } else {
758                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
759                 }
760         } // END - if
761
762         // Return reward
763         return $reward;
764 }
765
766 // Determine costs
767 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
768         // Static costs is default
769         $costs  = getConfig('surfbar_static_costs');
770
771         // Do we have static or dynamic?
772         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
773                 // "Calculate" dynamic costs
774                 if ($onlyMin) {
775                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
776                 } else {
777                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
778                 }
779         } // END - if
780
781         // Return costs
782         return $costs;
783 }
784
785 // "Calculate" dynamic add
786 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
787         // Get min/max values
788         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
789         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
790
791         // "Calculate" dynamic part and return it
792         return mt_rand($min, $max);
793 }
794
795 // Determine right template name
796 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
797         // Default is the frameset
798         $templateName = "surfbar_frameset";
799
800         // Any frame set? ;-)
801         if (isGetRequestParameterSet('frame')) {
802                 // Use the frame as a template name part... ;-)
803                 $templateName = sprintf("surfbar_frame_%s",
804                 getRequestParameter('frame')
805                 );
806         } // END - if
807
808         // Return result
809         return $templateName;
810 }
811
812 // Check if the "reload lock" of the current user is full, call this function
813 // before you call SURFBAR_CHECK_RELOAD_LOCK().
814 function SURFBAR_CHECK_RELOAD_FULL() {
815         // Default is full!
816         $isFull = true;
817
818         // Cache static reload lock
819         $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
820         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is '.getConfig('surfbar_static_lock') . '', false);
821
822         // Do we have dynamic model?
823         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
824                 // "Calculate" dynamic lock
825                 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
826         } // END - if
827
828         // Ask the database
829         $result = SQL_QUERY_ESC("SELECT
830         COUNT(l.id) AS cnt
831 FROM
832         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
833 INNER JOIN
834         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
835 ON
836         u.id=l.url_id
837 WHERE
838         l.userid=%s AND
839         (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(l.last_surfed) AND
840         (
841                 ((UNIX_TIMESTAMP(l.last_surfed) - u.fixed_reload) < 0 AND u.fixed_reload > 0) OR
842                 u.fixed_reload = '0'
843         )
844 LIMIT 1",
845                 array(getMemberId()), __FUNCTION__, __LINE__
846         );
847
848         // Fetch row
849         list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
850
851         // Is it null?
852         if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
853                 // Then fix it to zero!
854                 $GLOBALS['surfbar_cache']['user_locks'] = '0';
855         } // END - if
856
857         // Free result
858         SQL_FREERESULT($result);
859
860         // Get total URLs
861         $total = SURFBAR_GET_TOTAL_URLS();
862
863         // Do we have some URLs in lock? Admins can always surf on own URLs!
864         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_USER_LOCKS().",total={$total}", false);
865         $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
866
867         // Return result
868         return $isFull;
869 }
870
871 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
872 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = '0') {
873         // Determine depleted user account
874         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
875
876         // If we dont get any user ids back, there are no URLs
877         if (count($userids['userid']) == '0') {
878                 // No user ids found, no URLs!
879                 return 0;
880         } // END - if
881
882         // Is the exlude userid set?
883         if ($excludeUserId > 0) {
884                 // Then add it
885                 $userids['userid'][$excludeUserId] = $excludeUserId;
886         } // END - if
887
888         // Get amount from database
889         $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
890 FROM `{?_MYSQL_PREFIX?}_surfbar_urls`
891 WHERE `userid` NOT IN (".implode(', ', $userids['userid']).") AND `status`='%s'",
892                 array($status), __FUNCTION__, __LINE__
893         );
894
895         // Fetch row
896         list($cnt) = SQL_FETCHROW($result);
897
898         // Free result
899         SQL_FREERESULT($result);
900
901         // Return result
902         return $cnt;
903 }
904
905 // Check wether the user is allowed to book more URLs
906 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = '0') {
907         // Is this admin and userid is zero or does the user has some URLs left to book?
908         return ((($userid == '0') && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getConfig('surfbar_max_order')));
909 }
910
911 // Get total amount of URLs of given status for current user
912 function SURFBAR_GET_TOTAL_USER_URLS ($userid = '0', $status = '',$exclude = '') {
913         // Is the user 0 and user is logged in?
914         if (($userid == '0') && (isMember())) {
915                 // Then use this userid
916                 $userid = getMemberId();
917         } elseif ($userid == '0') {
918                 // Error!
919                 return (getConfig('surfbar_max_order') + 1);
920         }
921
922         // Default is all URLs
923         $add = '';
924
925         // Is the status set?
926         if (is_array($status)) {
927                 // Only URLs with these status
928                 $add = sprintf(" AND `status` IN('%s')", implode("','", $status));
929         } elseif (!empty($status)) {
930                 // Only URLs with this status
931                 $add = sprintf(" AND `status`='%s'", $status);
932         } elseif (is_array($exclude)) {
933                 // Exclude URLs with these status
934                 $add = sprintf(" AND `status` NOT IN('%s')", implode("','", $exclude));
935         } elseif (!empty($exclude)) {
936                 // Exclude URLs with this status
937                 $add = sprintf(" AND `status` != '%s'", $exclude);
938         }
939
940         // Get amount from database
941         $cnt = countSumTotalData($userid, 'surfbar_urls', 'id', 'userid', true, $add);
942
943         // Return result
944         return $cnt;
945 }
946
947 // Generate a validation code for the given id number
948 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
949         // @TODO Invalid salt should be refused
950         $GLOBALS['surfbar_cache']['salt'] = 'INVALID';
951
952         // Get code length from config
953         $length = getConfig('code_length');
954
955         // Fix length to 10
956         if ($length == '0') $length = 10;
957
958         // Generate a code until the length matches
959         $valCode = '';
960         while (strlen($valCode) != $length) {
961                 // Is the salt set?
962                 if (empty($salt)) {
963                         // Generate random hashed string
964                         $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
965                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
966                 } else {
967                         // Use this as salt!
968                         $GLOBALS['surfbar_cache']['salt'] = $salt;
969                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
970                 }
971
972                 // ... and now the validation code
973                 $valCode = generateRandomCode($length, sha1(SURFBAR_GET_SALT().':'.$urlId), getMemberId());
974                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valCode='.valCode.'', false);
975         } // END - while
976
977         // Hash it with md5() and salt it with the random string
978         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
979
980         // Finally encrypt it PGP-like and return it
981         $valHashedCode = generatePassString($hashedCode);
982
983         // Return hashed value
984         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalValCode='.$valHashedCode.'', false);
985         return $valHashedCode;
986 }
987
988 // Check validation code
989 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
990         // Secure id number
991         $urlId = bigintval($urlId);
992
993         // Now generate the code again
994         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
995
996         // Return result of checking hashes and salts
997         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '---'.$code.'|'.$check.'---', false);
998         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '+++'.$salt.'|'.SURFBAR_GET_DATA('last_salt').'+++', false);
999         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
1000 }
1001
1002 // Lockdown the userid/id combination (reload lock)
1003 function SURFBAR_LOCKDOWN_ID ($urlId) {
1004         //* DEBUG: */ outputHtml('LOCK!');
1005         ///* DEBUG: */ return;
1006         // Just add it to the database
1007         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`userid`, `url_id`) VALUES (%s, %s)",
1008                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__);
1009
1010         // Remove the salt from database
1011         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1012                 array(bigintval($urlId), getMemberId()), __FUNCTION__, __LINE__);
1013 }
1014
1015 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1016 function SURFBAR_PAY_POINTS () {
1017         // Remove it from the URL owner
1018         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS().'', false);
1019         if (SURFBAR_GET_USERID() > 0) {
1020                 subtractPoints(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1021         } // END - if
1022
1023         // Book it to the user
1024         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD().'', false);
1025         addPointsThroughReferalSystem(sprintf("surfbar_%s", getConfig('surfbar_pay_model')), getMemberId(), SURFBAR_GET_DATA('reward'));
1026 }
1027
1028 // Updates the statistics of current URL/userid
1029 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1030         // Init add
1031         $add = '';
1032
1033         // Get allowed views
1034         $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1035
1036         // Do we have a limit?
1037         if ($allowed > 0) {
1038                 // Then count views_max down!
1039                 $add .= ", `views_max`=`views_max`-1";
1040         } // END - if
1041
1042         // Update URL stats
1043         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `views_total`=`views_total`+1".$add." WHERE `id`=%s LIMIT 1",
1044                 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1045
1046         // Update the stats entry
1047         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `count`=`count`+1 WHERE `userid`=%s AND `url_id`=%s LIMIT 1",
1048                 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1049
1050         // Was that update okay?
1051         if (SQL_AFFECTEDROWS() < 1) {
1052                 // No, then insert entry
1053                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (userid,url_id,count) VALUES (%s,%s,1)",
1054                 array(getMemberId(), SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1055         } // END - if
1056
1057         // Update total/daily/weekly/monthly counter
1058         incrementConfigEntry('surfbar_total_counter');
1059         incrementConfigEntry('surfbar_daily_counter');
1060         incrementConfigEntry('surfbar_weekly_counter');
1061         incrementConfigEntry('surfbar_monthly_counter');
1062
1063         // Update config as well
1064         updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1065 }
1066
1067 // Update the salt for validation and statistics
1068 function SURFBAR_UPDATE_SALT_STATS () {
1069         // Update statistics record
1070         SURFBAR_UPDATE_INSERT_STATS_RECORD();
1071
1072         // Simply store the salt from cache away in database...
1073         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `last_salt`='%s' WHERE `url_id`=%s AND `userid`=%s LIMIT 1",
1074                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), getMemberId()), __FUNCTION__, __LINE__);
1075
1076         // Debug message
1077         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt='.SURFBAR_GET_SALT().',id='.SURFBAR_GET_ID().',userid='.getMemberId().'', false);
1078
1079         // Was that okay?
1080         if (SQL_AFFECTEDROWS() < 1) {
1081                 // Insert missing entry!
1082                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`url_id`, `userid`, `last_salt`) VALUES (%s, %s, '%s')",
1083                         array(SURFBAR_GET_ID(), getMemberId(), SURFBAR_GET_SALT()), __FUNCTION__, __LINE__);
1084         } // END - if
1085
1086         // Debug message
1087         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows='.SQL_AFFECTEDROWS().'', false);
1088
1089         // Return if the update was okay
1090         return (SQL_AFFECTEDROWS() == 1);
1091 }
1092
1093 // Check if the reload lock is active for given id
1094 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1095         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . '', false);
1096         // Ask the database
1097         $result = SQL_QUERY_ESC("SELECT COUNT(`id`) AS cnt
1098 FROM
1099         `{?_MYSQL_PREFIX?}_surfbar_locks`
1100 WHERE
1101         `userid`=%s AND `url_id`=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`last_surfed`)
1102 ORDER BY
1103         `last_surfed` ASC
1104 LIMIT 1",
1105                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1106         );
1107
1108         // Fetch counter
1109         list($cnt) = SQL_FETCHROW($result);
1110
1111         // Free result
1112         SQL_FREERESULT($result);
1113
1114         // Return check
1115         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $cnt . ',' . SURFBAR_GET_SURF_LOCK() . '', false);
1116         return ($cnt == 1);
1117 }
1118
1119 // Determine which user hash no more points left
1120 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1121         // Init array
1122         $userids = array(
1123                 'userid'      => array(),
1124                 'points'   => array(),
1125                 'notified' => array(),
1126         );
1127
1128         // Do we have a current user id?
1129         if ((isMember()) && ($limit == '0')) {
1130                 // Then add this as well
1131                 $userids['userid'][getMemberId()]      = getMemberId();
1132                 $userids['points'][getMemberId()]   = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
1133                 $userids['notified'][getMemberId()] = '0';
1134
1135                 // Get all userid except logged in one
1136                 $result = SQL_QUERY_ESC("SELECT
1137         u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1138 FROM
1139         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1140 INNER JOIN
1141         `{?_MYSQL_PREFIX?}_user_data` AS d
1142 ON
1143         u.userid=d.userid
1144 WHERE
1145         u.userid NOT IN (%s,0) AND u.`status`='ACTIVE'
1146 GROUP BY
1147         u.userid
1148 ORDER BY
1149         u.userid ASC",
1150                         array(getMemberId()), __FUNCTION__, __LINE__);
1151         } else {
1152                 // Get all userid
1153                 $result = SQL_QUERY("SELECT
1154         u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1155 FROM
1156         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1157 INNER JOIN
1158         `{?_MYSQL_PREFIX?}_user_data` AS d
1159 ON
1160         u.userid=d.userid
1161 WHERE
1162         u.`status`='ACTIVE'
1163 GROUP BY
1164         u.userid
1165 ORDER BY
1166         u.userid ASC", __FUNCTION__, __LINE__);
1167         }
1168
1169         // Load all userid
1170         while ($content = SQL_FETCHARRAY($result)) {
1171                 // Get total points
1172                 $points = countSumTotalData($content['userid'], 'user_points', 'points') - countSumTotalData($content['userid'], 'user_data', 'used_points');
1173                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']},points={$points}", false);
1174
1175                 // Shall we add this to ignore?
1176                 if ($points <= $limit) {
1177                         // Ignore this one!
1178                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "userid={$content['userid']} has depleted points amount!", false);
1179                         $userids['userid'][$content['userid']]      = $content['userid'];
1180                         $userids['points'][$content['userid']]   = $points;
1181                         $userids['notified'][$content['userid']] = $content['notified'];
1182                 } // END - if
1183         } // END - while
1184
1185         // Free result
1186         SQL_FREERESULT($result);
1187
1188         // Debug message
1189         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UIDs::count=".count($userids)." (with own userid=".getMemberId().')', false);
1190
1191         // Return result
1192         return $userids;
1193 }
1194
1195 // Determine how many users are Online in surfbar
1196 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1197         // Count all users in surfbar modue and return the value
1198         $result = SQL_QUERY("SELECT
1199         `id`
1200 FROM
1201         `{?_MYSQL_PREFIX?}_surfbar_stats`
1202 WHERE
1203         (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`last_surfed`)) <= {?online_timeout?}
1204 GROUP BY
1205         `userid` ASC", __FUNCTION__, __LINE__);
1206
1207         // Fetch count
1208         $cnt = SQL_NUMROWS($result);
1209
1210         // Free result
1211         SQL_FREERESULT($result);
1212
1213         // Return result
1214         return $cnt;
1215 }
1216
1217 // Determine waiting time for one URL
1218 function SURFBAR_DETERMINE_WAIT_TIME () {
1219         // Get fixed reload lock
1220         $fixed = SURFBAR_GET_FIXED_RELOAD();
1221
1222         // Is the fixed reload time set?
1223         if ($fixed > 0) {
1224                 // Return it
1225                 return $fixed;
1226         } // END - if
1227
1228         // Static time is default
1229         $time = getConfig('surfbar_static_time');
1230
1231         // Which payment model do we have?
1232         if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1233                 // "Calculate" dynamic time
1234                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1235         } // END - if
1236
1237         // Return value
1238         return $time;
1239 }
1240
1241 // Changes the status of an URL from given to other
1242 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1243         // Make new status always lower-case
1244         $newStatus = strtolower($newStatus);
1245
1246         // Get URL data for status comparison if missing
1247         if ((!is_array($data)) || (count($data) == '0')) {
1248                 // Fetch missing URL data
1249                 $data = SURFBAR_GET_URL_DATA($urlId);
1250         } // END - if
1251
1252         // Is the new status set?
1253         if ((!is_string($newStatus)) || (empty($newStatus))) {
1254                 // Abort here, but fine!
1255                 return true;
1256         } // END - if
1257
1258         // Is the status like prevStatus is saying?
1259         if ($data[$urlId]['status'] != $prevStatus) {
1260                 // No, then abort here
1261                 return false;
1262         } // END - if
1263
1264
1265         // Update the status now
1266         // ---------- Comment out for debugging/developing member actions! ---------
1267         //SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `status`='%s' WHERE `id`=%s LIMIT 1",
1268         //      array($newStatus, bigintval($urlId)), __FUNCTION__, __LINE__);
1269         // ---------- Comment out for debugging/developing member actions! ---------
1270
1271         // Was that fine?
1272         // ---------- Comment out for debugging/developing member actions! ---------
1273         //if (SQL_AFFECTEDROWS() != 1) {
1274         //      // No, something went wrong
1275         //      return false;
1276         //} // END - if
1277         // ---------- Comment out for debugging/developing member actions! ---------
1278
1279         // Prepare content for notification routines
1280         $data[$urlId]['userid']         = $data[$urlId]['userid'];
1281         $data[$urlId]['frametester'] = generateFrametesterUrl($data[$urlId]['url']);
1282         $data[$urlId]['reward']      = translateComma(getConfig('surfbar_static_reward'));
1283         $data[$urlId]['costs']       = translateComma(getConfig('surfbar_static_costs'));
1284
1285         // Do some dirty fixing here:
1286         if (($data[$urlId]['status'] == 'STOPPED') && ($newStatus == 'pending')) {
1287                 // Fix for template change
1288                 $newStatus = 'continued';
1289         } // END - if
1290
1291         // Send admin notification
1292         SURFBAR_NOTIFY_ADMIN("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1293
1294         // Send user notification
1295         SURFBAR_NOTIFY_USER("url_{$data[$urlId]['status']}_{$newStatus}", $data[$urlId]);
1296
1297         // All done!
1298         return true;
1299 }
1300
1301 // Calculate minimum value for dynamic payment model
1302 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1303         // Addon is zero by default
1304         $addon = '0';
1305
1306         // Percentage part
1307         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1308
1309         // Get total users
1310         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1311
1312         // Get online users
1313         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1314
1315         // Calculate addon
1316         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1317
1318         // Get total URLs
1319         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1320
1321         // Get user's total URLs
1322         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1323
1324         // Calculate addon
1325         if ($totalUrls > 0) {
1326                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1327         } else {
1328                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1329         }
1330
1331         // Return addon
1332         return $addon;
1333 }
1334
1335 // Calculate maximum value for dynamic payment model
1336 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1337         // Addon is zero by default
1338         $addon = '0';
1339
1340         // Maximum value
1341         $max = log(2);
1342
1343         // Percentage part
1344         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1345
1346         // Get total users
1347         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true);
1348
1349         // Calculate addon
1350         $addon += abs($max * $percent * $totalUsers);
1351
1352         // Get total URLs
1353         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1354
1355         // Calculate addon
1356         $addon += abs($max * $percent * $totalUrls);
1357
1358         // Return addon
1359         return $addon;
1360 }
1361
1362 // Calculate dynamic lock
1363 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1364         // Default lock is 30 seconds
1365         $addon = 30;
1366
1367         // Get online users
1368         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1369
1370         // Calculate lock
1371         $addon = abs(log($onlineUsers / $addon + 1));
1372
1373         // Return value
1374         return $addon;
1375 }
1376
1377 // "Getter" for lock ids array
1378 function SURFBAR_GET_LOCK_IDS () {
1379         // Prepare some arrays
1380         $IDs = array();
1381         $USE = array();
1382         $ignored = array();
1383
1384         // Get all id from locks within the timestamp
1385         $result = SQL_QUERY_ESC("SELECT `id`, `url_id`, UNIX_TIMESTAMP(`last_surfed`) AS last_surfed
1386 FROM
1387         `{?_MYSQL_PREFIX?}_surfbar_locks`
1388 WHERE
1389         `userid`=%s
1390 ORDER BY
1391         `id` ASC", array(getMemberId()),
1392         __FUNCTION__, __LINE__);
1393
1394         // Load all entries
1395         while ($content = SQL_FETCHARRAY($result)) {
1396                 // Debug message
1397                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['id'].',url='.$content['url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK().'', false);
1398
1399                 // Skip entries that are too old
1400                 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['url_id'], $ignored))) {
1401                         // Debug message
1402                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1403
1404                         // Add only if missing or bigger
1405                         if ((!isset($IDs[$content['url_id']])) || ($IDs[$content['url_id']] > $content['last_surfed'])) {
1406                                 // Debug message
1407                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1408
1409                                 // Add this id
1410                                 $IDs[$content['url_id']] = $content['last_surfed'];
1411                                 $USE[$content['url_id']] = $content['id'];
1412                         } // END - if
1413                 } else {
1414                         // Debug message
1415                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['id'].',url='.$content['url_id'].',last='.$content['last_surfed'].'', false);
1416
1417                         // Ignore these old entries!
1418                         $ignored[] = $content['url_id'];
1419                         unset($IDs[$content['url_id']]);
1420                         unset($USE[$content['url_id']]);
1421                 }
1422         } // END - while
1423
1424         // Free result
1425         SQL_FREERESULT($result);
1426
1427         // Return array
1428         return $USE;
1429 }
1430
1431 // "Getter" for maximum random number
1432 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1433         // Count max availabe entries
1434         $result = SQL_QUERY("SELECT sbu.id AS cnt
1435 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1436 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1437 ON sbu.id=sbs.url_id
1438 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1439 ON sbu.id=l.url_id
1440 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."
1441 GROUP BY sbu.id", __FUNCTION__, __LINE__);
1442
1443         // Log last query
1444         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1445
1446         // Fetch max rand
1447         $maxRand = SQL_NUMROWS($result);
1448
1449         // Free result
1450         SQL_FREERESULT($result);
1451
1452         // Return value
1453         return $maxRand;
1454 }
1455
1456 // Load all URLs of the current user and return it as an array
1457 function SURFBAR_GET_USER_URLS () {
1458         // Init array
1459         $URLs = array();
1460
1461         // Begin the query
1462         $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
1463 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1464 WHERE u.userid=%s AND u.status != 'DELETED'
1465 ORDER BY u.id ASC",
1466         array(getMemberId()), __FUNCTION__, __LINE__);
1467
1468         // Are there entries?
1469         if (SQL_NUMROWS($result) > 0) {
1470                 // Load all rows
1471                 while ($row = SQL_FETCHARRAY($result)) {
1472                         // Add the row
1473                         $URLs[$row['id']] = $row;
1474                 } // END - while
1475         } // END - if
1476
1477         // Free result
1478         SQL_FREERESULT($result);
1479
1480         // Return the array
1481         return $URLs;
1482 }
1483
1484 // "Getter" for member action array for given status
1485 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1486         // Init array
1487         $returnArray = array();
1488
1489         // Get all assigned actions
1490         $result = SQL_QUERY_ESC("SELECT action FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `status`='%s' ORDER BY `id` ASC",
1491         array($status), __FUNCTION__, __LINE__);
1492
1493         // Some entries there?
1494         if (SQL_NUMROWS($result) > 0) {
1495                 // Load all actions
1496                 // @TODO This can be somehow rewritten
1497                 while ($content = SQL_FETCHARRAY($result)) {
1498                         $returnArray[] = $content['action'];
1499                 } // END - if
1500         } // END - if
1501
1502         // Free result
1503         SQL_FREERESULT($result);
1504
1505         // Return result
1506         return $returnArray;
1507 }
1508
1509 // Reload to configured stop page
1510 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1511         // Internal or external?
1512         if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1513                 // Reload to internal page
1514                 redirectToUrl('surfbar.php?frame=' . $page);
1515         } else {
1516                 // Reload to external page
1517                 redirectToConfiguredUrl('surfbar_pause_url');
1518         }
1519 }
1520
1521 // Determine next id for surfbar or get data for given id, always call this before you call other
1522 // getters below this function!!!
1523 function SURFBAR_DETERMINE_NEXT_ID ($urlId = '0') {
1524         // Default is no id and no random number
1525         $nextId = '0';
1526         $randNum = '0';
1527
1528         // Is the id set?
1529         if ($urlId == '0') {
1530                 // Get array with lock ids
1531                 $USE = SURFBAR_GET_LOCK_IDS();
1532
1533                 // Shall we add some URL ids to ignore?
1534                 $add = '';
1535                 if (count($USE) > 0) {
1536                         // Ignore some!
1537                         $add = " AND sbu.id NOT IN (";
1538                         foreach ($USE as $url_id => $lid) {
1539                                 // Add URL id
1540                                 $add .= $url_id.',';
1541                         } // END - foreach
1542
1543                         // Add closing bracket
1544                         $add = substr($add, 0, -1) . ')';
1545                 } // END - if
1546
1547                 // Determine depleted user account
1548                 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1549
1550                 // Get maximum randomness factor
1551                 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['userid'], $add);
1552
1553                 // If more than one URL can be called generate the random number!
1554                 if ($maxRand > 1) {
1555                         // Generate random number
1556                         $randNum = mt_rand(0, ($maxRand - 1));
1557                 } // END - if
1558
1559                 // And query the database
1560                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK().'', false);
1561                 $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
1562 FROM `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1563 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1564 ON sbu.id=sbs.url_id
1565 LEFT JOIN `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1566 ON sbu.id=l.url_id
1567 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."
1568 GROUP BY sbu.id
1569 ORDER BY l.last_surfed ASC, sbu.id ASC
1570 LIMIT %s,1",
1571                         array($randNum), __FUNCTION__, __LINE__
1572                 );
1573         } else {
1574                 // Get data from specified id number
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 != %s AND sbu.`status`='ACTIVE' AND sbu.id=%s AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))
1582 LIMIT 1",
1583                         array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1584                 );
1585         }
1586
1587         // Is there an id number?
1588         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS().'', false);
1589         if (SQL_NUMROWS($result) == 1) {
1590                 // Load/cache data
1591                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1592                 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1593                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1594
1595                 // Determine waiting time
1596                 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1597
1598                 // Is the last salt there?
1599                 if (is_null($GLOBALS['surfbar_cache']['last_salt'])) {
1600                         // Then repair it wit the static!
1601                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1602                         $GLOBALS['surfbar_cache']['last_salt'] = '';
1603                 } // END - if
1604
1605                 // Fix missing last_surfed
1606                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1607                         // Fix it here
1608                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1609                         $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1610                 } // END - if
1611
1612                 // Get base/fixed reward and costs
1613                 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1614                 $GLOBALS['surfbar_cache']['costs']  = SURFBAR_DETERMINE_COSTS();
1615                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1616
1617                 // Only in dynamic model add the dynamic bonus!
1618                 if (getConfig('surfbar_pay_model') == 'DYNAMIC') {
1619                         // Calculate dynamic reward/costs and add it
1620                         $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1621                         $GLOBALS['surfbar_cache']['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1622                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS().'', false);
1623                 } // END - if
1624
1625                 // Now get the id
1626                 $nextId = SURFBAR_GET_ID();
1627         } // END - if
1628
1629         // Free result
1630         SQL_FREERESULT($result);
1631
1632         // Return result
1633         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'nextId='.$nextId.'', false);
1634         return $nextId;
1635 }
1636
1637 // -----------------------------------------------------------------------------
1638 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1639 // THE $GLOBALS['surfbar_cache'] ARRAY!
1640 // -----------------------------------------------------------------------------
1641
1642 // Initializes the surfbar
1643 function SURFBAR_INIT () {
1644         // Init cache array
1645         $GLOBALS['surfbar_cache'] = array();
1646 }
1647
1648 // Private getter for data elements
1649 function SURFBAR_GET_DATA ($element) {
1650         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element={$element}", false);
1651
1652         // Default is null
1653         $data = null;
1654
1655         // Is the entry there?
1656         if (isset($GLOBALS['surfbar_cache'][$element])) {
1657                 // Then take it
1658                 $data = $GLOBALS['surfbar_cache'][$element];
1659         } else { // END - if
1660                 print("<pre>");
1661                 print_r($GLOBALS['surfbar_cache']);
1662                 print("</pre>");
1663                 debug_report_bug();
1664         }
1665
1666         // Return result
1667         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1668         return $data;
1669 }
1670
1671 // Getter for reward from cache
1672 function SURFBAR_GET_REWARD () {
1673         // Get data element and return its contents
1674         return SURFBAR_GET_DATA('reward');
1675 }
1676
1677 // Getter for costs from cache
1678 function SURFBAR_GET_COSTS () {
1679         // Get data element and return its contents
1680         return SURFBAR_GET_DATA('costs');
1681 }
1682
1683 // Getter for URL from cache
1684 function SURFBAR_GET_URL () {
1685         // Get data element and return its contents
1686         return SURFBAR_GET_DATA('url');
1687 }
1688
1689 // Getter for salt from cache
1690 function SURFBAR_GET_SALT () {
1691         // Get data element and return its contents
1692         return SURFBAR_GET_DATA('salt');
1693 }
1694
1695 // Getter for id from cache
1696 function SURFBAR_GET_ID () {
1697         // Get data element and return its contents
1698         return SURFBAR_GET_DATA('id');
1699 }
1700
1701 // Getter for userid from cache
1702 function SURFBAR_GET_USERID () {
1703         // Get data element and return its contents
1704         return SURFBAR_GET_DATA('userid');
1705 }
1706
1707 // Getter for user reload locks
1708 function SURFBAR_GET_USER_LOCKS () {
1709         // Get data element and return its contents
1710         return SURFBAR_GET_DATA('user_locks');
1711 }
1712
1713 // Getter for reload time
1714 function SURFBAR_GET_RELOAD_TIME () {
1715         // Get data element and return its contents
1716         return SURFBAR_GET_DATA('time');
1717 }
1718
1719 // Getter for allowed views
1720 function SURFBAR_GET_VIEWS_ALLOWED () {
1721         // Get data element and return its contents
1722         return SURFBAR_GET_DATA('views_allowed');
1723 }
1724
1725 // Getter for fixed reload
1726 function SURFBAR_GET_FIXED_RELOAD () {
1727         // Get data element and return its contents
1728         return SURFBAR_GET_DATA('fixed_reload');
1729 }
1730
1731 // Getter for surf lock
1732 function SURFBAR_GET_SURF_LOCK () {
1733         // Get data element and return its contents
1734         return SURFBAR_GET_DATA('surf_lock');
1735 }
1736
1737 // Getter for new status
1738 function SURFBAR_GET_NEW_STATUS () {
1739         // Get data element and return its contents
1740         return SURFBAR_GET_DATA('new_status');
1741 }
1742
1743 // [EOF]
1744 ?>