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