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