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