Bad things are now 'classified' as bad (CSS class 'bad' is being used instead of...
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/31/2008 *
4  * ===================                          Last change: 08/31/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : surfbar_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for surfbar                            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die Surfbar                      *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 //------------------------------------------------------------------------------
44 //                               Admin functions
45 //------------------------------------------------------------------------------
46 //
47 // Admin has added an URL with given user id and so on
48 function SURFBAR_ADMIN_ADD_URL ($url, $limit, $reload) {
49         // Do some pre-checks
50         if (!isAdmin()) {
51                 // Not an admin
52                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s: Not admin.", $url, $limit, $reload));
53                 return false;
54         } elseif (!isUrlValid($url)) {
55                 // URL invalid
56                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s: Invalid URL.", $url, $limit, $reload));
57                 return false;
58         } elseif (SURFBAR_LOOKUP_BY_URL($url, 0)) {
59                 // URL already found in surfbar!
60                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s: Already added.", $url, $limit, $reload));
61                 return false;
62         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
63                 // No more allowed!
64                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s: No more URLs allowed.", $url, $limit, $reload));
65                 return false;
66         } elseif ('' . ($limit + 0) . '' != '' . $limit . '') {
67                 // Invalid limit entered
68                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s: Invalid limit entered.", $url, $limit, $reload));
69                 return false;
70         } elseif ('' . ($reload + 0) . '' != '' . $reload . '') {
71                 // Invalid amount entered
72                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Cannot add URL=%s,limit=%s,reload=%s: Invalid reload entered.", $url, $limit, $reload));
73                 return false;
74         }
75
76         // Register the new URL
77         return SURFBAR_REGISTER_URL($url, 0, 'ACTIVE', 'unlock', array('limit' => $limit, 'reload' => $reload));
78 }
79
80 // Admin unlocked an email so we can migrate the URL
81 function SURFBAR_ADMIN_MIGRATE_URL ($url, $userid) {
82         // Do some pre-checks
83         if (!isAdmin()) {
84                 // Not an admin
85                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Not admin, url=' . $url . ',userid=' . $userid);
86                 return false;
87         } elseif (!isUrlValid($url)) {
88                 // URL invalid
89                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Invalid URL, url=' . $url . ',userid=' . $userid);
90                 return false;
91         } elseif (SURFBAR_LOOKUP_BY_URL($url, $userid)) {
92                 // URL already found in surfbar!
93                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Already added, url=' . $url . ',userid=' . $userid);
94                 return false;
95         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($userid)) {
96                 // No more allowed!
97                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot migrate URL: Maximum exceeded, url=' . $url . ',userid=' . $userid);
98                 return false;
99         }
100
101         // Register the new URL
102         return SURFBAR_REGISTER_URL($url, $userid, 'MIGRATED', 'migrate');
103 }
104
105 // Admin function for unlocking URLs
106 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
107         // Is this an admin or invalid array?
108         if (!isAdmin()) {
109                 // Not admin or invalid ids array
110                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not admin');
111                 return false;
112         } elseif (!is_array($IDs)) {
113                 // No array
114                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs type ' . gettype($IDs) . '!=array');
115                 return false;
116         } elseif (count($IDs) == 0) {
117                 // Empty array
118                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs is empty');
119                 return false;
120         }
121
122         // Set to true to make AND expression valid if first URL got unlocked
123         $done = true;
124
125         // Update the status for all ids
126         foreach ($IDs as $id => $dummy) {
127                 // Test all ids through (ignores failed)
128                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'ACTIVE')));
129         } // END - if
130
131         // Return total status
132         return $done;
133 }
134
135 // Admin function for rejecting URLs
136 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
137         // Is this an admin or invalid array?
138         if (!isAdmin()) {
139                 // Not admin or invalid ids array
140                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not admin');
141                 return false;
142         } elseif (!is_array($IDs)) {
143                 // No array
144                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs type ' . gettype($IDs) . '!=array');
145                 return false;
146         } elseif (count($IDs) == 0) {
147                 // Empty array
148                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: IDs is empty');
149                 return false;
150         }
151
152         // Set to true to make AND expression valid if first URL got unlocked
153         $done = true;
154
155         // Update the status for all ids
156         foreach ($IDs as $id => $dummy) {
157                 // Test all ids through (ignores failed)
158                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, 'PENDING', 'REJECTED')));
159         } // END - if
160
161         // Return total status
162         return $done;
163 }
164
165 //
166 //------------------------------------------------------------------------------
167 //                               Member functions
168 //------------------------------------------------------------------------------
169 //
170 // Member has added an URL
171 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
172         // Do some pre-checks
173         if (!isMember()) {
174                 // Not a member
175                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not member');
176                 return false;
177         } elseif ((!isUrlValid($url)) && (!isAdmin())) {
178                 // URL invalid
179                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid, url=' . $url . ',limit=' . $limit);
180                 return false;
181         } elseif (SURFBAR_LOOKUP_BY_URL($url, getMemberId())) {
182                 // URL already found in surfbar!
183                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Already found, url=' . $url . ',limit=' . $limit);
184                 return false;
185         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS(getMemberId())) {
186                 // No more allowed!
187                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Maximum exceeded, url=' . $url . ',limit=' . $limit);
188                 return false;
189         } elseif (''.($limit + 0).'' != ''.$limit.'') {
190                 // Invalid amount entered
191                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid limit, url=' . $url . ',limit=' . $limit);
192                 return false;
193         }
194
195         // Register the new URL
196         return SURFBAR_REGISTER_URL($url, getMemberId(), 'PENDING', 'reg', array('limit' => $limit));
197 }
198
199 // Create list of actions depending on status for the user
200 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
201         // Load all actions in an array for given status
202         $actionArray = SURFBAR_GET_ARRAY_FROM_STATUS($status);
203
204         // Init HTML code
205         $OUT = '<table border="0" cellspacing="0" cellpadding="1" width="100%">
206 <tr>';
207
208         // Calculate width
209         $width = round(100 / count($actionArray));
210
211         // "Walk" through all actions and create forms
212         foreach ($actionArray as $actionId => $action) {
213                 // Add form for this action
214                 $OUT .= loadTemplate('member_list_surfbar_form', true, array(
215                         'width'  => $width,
216                         'url_id' => bigintval($urlId),
217                         'action' => strtolower($action)
218                 ));
219         } // END - foreach
220
221         // Close table
222         $OUT .= '</tr>
223 </table>';
224
225         // Return code
226         return $OUT;
227 }
228
229 // Do the member form request
230 function SURFBAR_MEMBER_DO_FORM ($formData, $urlArray) {
231         // By default no action is performed
232         $performed = false;
233
234         // Is this a member?
235         if (!isMember()) {
236                 // No member!
237                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Not member');
238                 return false;
239         } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
240                 // Important form elements are missing!
241                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Invalid form data, required field id/action not found');
242                 return false;
243         } elseif (!isset($urlArray[$formData['id']])) {
244                 // Id not found in cache
245                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Field id not found in cache');
246                 return false;
247         } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $urlArray[$formData['id']]['url_status'])) {
248                 // Action not allowed for current URL status
249                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot add URL: Action not allowed to perform. action=' . $formData['action'] . ',url_status=' . $urlArray[$formData['id']]['url_status'] . 'id=' . $formData['id']);
250                 return false;
251         }
252
253         // Secure action
254         $action = secureString($formData['action']);
255
256         // Has it changed?
257         if ($action != $formData['action']) {
258                 // Invalid data in action found
259                 return false;
260         } // END - if
261
262         // Create the function name for selected action
263         $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper($action));
264
265         // Is the function there?
266         if (function_exists($functionName)) {
267                 // Add new status
268                 $urlArray[$formData['id']]['new_status'] = SURFBAR_GET_NEW_STATUS('new_status');
269
270                 // Extract URL data for call-back
271                 $urlData = array(merge_array($urlArray[$formData['id']], array($action => $formData)));
272
273                 // Action found so execute it
274                 $performed = call_user_func_array($functionName, $urlData);
275         } else {
276                 // Log invalid request
277                 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid member action! action=' . $formData['action'] . ',id=' . $formData['id'] . ',function=' . $functionName);
278         }
279
280         // Return status
281         return $performed;
282 }
283
284 // Validate if the requested action can be performed on current URL status
285 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
286         // Search for the requested action/status combination in database
287         $result = SQL_QUERY_ESC("SELECT `actions_new_status` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_action`='%s' AND `actions_status`='%s' LIMIT 1",
288                 array($action, $status), __FUNCTION__, __LINE__);
289
290         // Is the entry there?
291         $isValid = (SQL_NUMROWS($result) == 1);
292
293         // Fetch the new status if found
294         if ($isValid) {
295                 // Load new status
296                 list($GLOBALS['surfbar_cache']['new_status']) = SQL_FETCHROW($result);
297         } // END - if
298
299         // Free result
300         SQL_FREERESULT($result);
301
302         // Return status
303         return $isValid;
304 }
305
306 //
307 //------------------------------------------------------------------------------
308 //                               Member actions
309 //------------------------------------------------------------------------------
310 //
311 // Retreat a booked URL
312 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
313         // Create the data array for next function call
314         $data = array(
315                 $urlData['id'] => $urlData
316         );
317
318         // Simply change the status here
319         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
320 }
321
322 // Book an URL now (from migration)
323 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
324         // Create the data array for next function call
325         $data = array(
326                 $urlData['id'] => $urlData
327         );
328
329         // Simply change the status here
330         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['url_status'], $urlData['new_status'], $data);
331 }
332
333 // Show edit form or do the changes
334 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
335         // Is the "execute" flag there?
336         if (isset($urlData['edit']['execute'])) {
337                 // Execute the changes
338                 return SURFBAR_MEMBER_EXECUTE_ACTION('edit', $urlData);
339         } // END - if
340
341         // Display form
342         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('edit', $urlData);
343 }
344
345 // Show delete form or do the changes
346 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
347         // Is the "execute" flag there?
348         if (isset($urlData['delete']['execute'])) {
349                 // Execute the changes
350                 return SURFBAR_MEMBER_EXECUTE_ACTION('delete', $urlData);
351         } // END - if
352
353         // Display form
354         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM('delete', $urlData);
355 }
356
357 // Pause active banner
358 function SURFBAR_MEMBER_PAUSE_ACTION ($urlData) {
359         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
360 }
361
362 // Unpause stopped banner
363 function SURFBAR_MEMBER_UNPAUSE_ACTION ($urlData) {
364         // Fix missing entry for template
365         $urlData['edit'] = $urlData['unpause'];
366         $urlData['edit']['url'] = $urlData['url'];
367         $urlData['edit']['limit'] = SURFBAR_GET_VIEWS_MAX();
368
369         // Return status change
370         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
371 }
372
373 // Resubmit locked URL
374 function SURFBAR_MEMBER_RESUBMIT_ACTION ($urlData) {
375         return SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
376 }
377
378 // Display selected "action form"
379 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
380         // Translate some data if present
381         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
382
383         // Include fields only for action 'edit'
384         if ($action == 'edit') {
385                 // Default is not limited
386                 $urlData['limited_yes'] = '';
387                 $urlData['limited_no']  = ' checked="checked"';
388                 $urlData['limited']     = 'false';
389
390                 // Is this URL limited?
391                 if (SURFBAR_GET_VIEWS_MAX() > 0) {
392                         // Then rewrite form data
393                         $urlData['limited_yes'] = ' checked="checked"';
394                         $urlData['limited_no']  = '';
395                         $urlData['limited']     = 'true';
396                 } // END - if
397         } // END - if
398
399         // Load the form and display it
400         loadTemplate(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
401
402         // All fine by default ... ;-)
403         return true;
404 }
405
406 // Execute choosen action
407 function SURFBAR_MEMBER_EXECUTE_ACTION ($action, $urlData) {
408         // By default nothing is executed
409         $executed = false;
410
411         // Is limitation "no" and "limit" is > 0?
412         if ((isset($urlData[$action]['limited'])) && ($urlData[$action]['limited'] != 'Y') && ((isset($urlData[$action]['limit'])) && ($urlData[$action]['limit'] > 0)) || (!isset($urlData[$action]['limit']))) {
413                 // Set it to unlimited
414                 $urlData[$action]['limit'] = '0';
415         } // END - if
416
417         // Construct function name
418         $functionName = sprintf("SURFBAR_MEMBER_EXECUTE_%s_ACTION", strtoupper($action));
419
420         // Is that function there?
421         if (function_exists($functionName)) {
422                 // Execute the function
423                 if (call_user_func_array($functionName, array($urlData)) == true) {
424                         // Update status as well
425                         $executed = SURFBAR_CHANGE_STATUS($urlData['id'], $urlData['url_status'], $urlData['new_status'], array($urlData['id'] => $urlData));
426                 } // END - if
427         } else {
428                 // Not found
429                 debug_report_bug(__FUNCTION__, __LINE__, 'Callback function ' . $functionName . ' not found.');
430         }
431
432         // Return status
433         return $executed;
434 }
435 // "Execute edit" function: Update changed data
436 function SURFBAR_MEMBER_EXECUTE_EDIT_ACTION ($urlData) {
437         // Default is nothing done
438         $status = false;
439
440         // Has the URL or limit changed?
441         if (true) {
442                 //if (($urlData['url_views_allowed'] != $urlData['edit']['limit']) || ($url1 != $url2)) {
443                 // Run the query
444                 SQL_QUERY_ESC("UPDATE
445         `{?_MYSQL_PREFIX?}_surfbar_urls`
446 SET
447         `url`='%s',
448         `url_views_allowed`=%s,
449         `url_views_max`=%s
450 WHERE
451         `url_id`=%s AND
452         `status`='%s'
453 LIMIT 1",
454                         array(
455                                 $urlData['url'],
456                                 $urlData['edit']['limit'],
457                                 $urlData['edit']['limit'],
458                                 $urlData['id'],
459                                 $urlData['url_status']
460                         ), __FUNCTION__, __LINE__);
461
462                 // All fine
463                 $status = true;
464         } // END - if
465
466         // Return status
467         return $status;
468 }
469 // "Execute delete" function: Does nothing...
470 function SURFBAR_MEMBER_EXECUTE_DELETE_ACTION ($urlData) {
471         // Nothing special to do (see above function for such "special actions" to perform)
472         return true;
473 }
474 //
475 //------------------------------------------------------------------------------
476 //                           Self-maintenance functions
477 //------------------------------------------------------------------------------
478 //
479 // Main function
480 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
481         // Handle URLs which limit has depleted so we can stop them
482         SURFBAR_HANDLE_DEPLETED_VIEWS();
483
484         // Handle low-points amounts
485         SURFBAR_HANDLE_LOW_POINTS();
486 }
487
488 // Handle URLs which limit has depleted
489 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
490         // Get all URLs
491         $urlArray = SURFBAR_GET_URL_DATA(0, 'url_views_max', 'url_id', 'ASC', 'url_id', " AND `url_views_allowed` > 0 AND `url_status`='ACTIVE'");
492
493         // Do we have some entries?
494         if (count($urlArray) > 0) {
495                 // Then handle all!
496                 foreach ($urlArray as $id => $urlData) {
497                         // Backup data
498                         $data = $urlData;
499
500                         // Rewrite array for next call
501                         $urlData = array(
502                                 $id => $data
503                         );
504
505                         // Handle the status
506                         SURFBAR_CHANGE_STATUS($id, 'ACTIVE', 'DEPLETED', $urlData);
507                 } // END - foreach
508         } // END - if
509 }
510
511 // Alert users which have URLs booked and are low on points amount
512 function SURFBAR_HANDLE_LOW_POINTS () {
513         // Get all userids
514         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS(getConfig('surfbar_warn_low_points'));
515
516         // "Walk" through all URLs
517         foreach ($userids['url_userid'] as $userid => $dummy) {
518                 // Is the last notification far enougth away to notify again?
519                 if ((time() - $userids['notified'][$userid]) >= getConfig('surfbar_low_interval')) {
520                         // Prepare content
521                         $content = array(
522                                 'url_userid' => $userid,
523                                 'points'     => $userids['points'][$userid],
524                                 'notified'   => $userids['notified'][$userid]
525                         );
526
527                         // Notify this user
528                         SURFBAR_NOTIFY_USER('low_points', $content);
529
530                         // Update last notified
531                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `surfbar_low_notified`=NOW() WHERE `userid`=%s LIMIT 1",
532                                 array($userid), __FUNCTION__, __LINE__);
533                 } // END - if
534         } // END - foreach
535 }
536
537 //
538 //------------------------------------------------------------------------------
539 //                               Generic functions
540 //------------------------------------------------------------------------------
541 //
542
543 // Looks up by an URL
544 function SURFBAR_LOOKUP_BY_URL ($url, $userid) {
545         // Now lookup that given URL by itself
546         $urlArray = SURFBAR_GET_URL_DATA($url, 'url', 'url_id', 'ASC', 'url_id', sprintf(" AND `url_userid`=%s", bigintval($userid)));
547
548         // Was it found?
549         return (count($urlArray) > 0);
550 }
551
552 // Load URL data by given search term and column
553 function SURFBAR_GET_URL_DATA ($searchTerm, $column = 'url_id', $order = 'url_id', $sort = 'ASC', $group = 'url_id', $add = '') {
554         // By default nothing is found
555         $GLOBALS['last_url_data'] = array();
556
557         // Is the column an id number?
558         if (($column == 'url_id') || ($column == 'url_userid')) {
559                 // Extra secure input
560                 $searchTerm = bigintval($searchTerm);
561         } // END - if
562
563         // If the column is 'id' there can be only one entry
564         $limit = '';
565         if ($column == 'id') {
566                 $limit = "LIMIT 1";
567         } // END - if
568
569         // Look up the record
570         $result = SQL_QUERY_ESC("SELECT
571         `url_id`,
572         `url_userid`,
573         `url`,
574         `url_views_total`,
575         `url_views_max`,
576         `url_views_allowed`,
577         `url_status`,
578         UNIX_TIMESTAMP(`url_registered`) AS `url_registered`,
579         UNIX_TIMESTAMP(`url_last_locked`) AS `url_last_locked`,
580         `url_lock_reason`,
581         `url_views_max`,
582         `url_views_allowed`,
583         `url_fixed_reload`
584 FROM
585         `{?_MYSQL_PREFIX?}_surfbar_urls`
586 WHERE
587         `%s`='%s'" . $add . "
588 ORDER BY
589         `%s` %s
590 %s",
591                 array(
592                         $column,
593                         $searchTerm,
594                         $order,
595                         $sort,
596                         $limit
597                 ), __FUNCTION__, __LINE__);
598
599         // Is there at least one record?
600         if (!SQL_HASZERONUMS($result)) {
601                 // Then load all!
602                 while ($dataRow = SQL_FETCHARRAY($result)) {
603                         // Shall we group these results?
604                         if ($group == 'url_id') {
605                                 // Add the row by id as index
606                                 $GLOBALS['last_url_data'][$dataRow['url_id']] = $dataRow;
607                         } else {
608                                 // Group entries
609                                 $GLOBALS['last_url_data'][$dataRow[$group]][$dataRow['url_id']] = $dataRow;
610                         }
611                 } // END - while
612         } // END - if
613
614         // Free the result
615         SQL_FREERESULT($result);
616
617         // Return the result
618         return $GLOBALS['last_url_data'];
619 }
620
621 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
622 function SURFBAR_REGISTER_URL ($url, $userid, $status = 'PENDING', $addMode = 'reg', $extraFields = array()) {
623         // Make sure by the user registered URLs are always pending
624         if ($addMode == 'reg') {
625                 $status = 'PENDING';
626         } // END - if
627
628         // Prepare content
629         $content = merge_array($extraFields, array(
630                 'url'         => $url,
631                 'url_userid'  => $userid,
632                 'url_status'  => $status,
633         ));
634
635         // Is limit/reload set?
636         if (!isset($content['limit'])) {
637                 $content['limit']  = '0';
638         } // END - if
639         if (!isset($content['reload'])) {
640                 $content['reload'] = '0';
641         } // END - if
642
643         // Insert the URL into database
644         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
645
646         // Is this id valid?
647         if ($content['insert_id'] == '0') {
648                 // INSERT did not insert any data!
649                 return false;
650         } // END - if
651
652         // If in reg-mode we notify admin
653         if (($addMode == 'reg') || (getConfig('surfbar_notify_admin_unlock') == 'Y')) {
654                 // Notify admin even when he as unlocked an email
655                 SURFBAR_NOTIFY_ADMIN('url_' . $addMode, $content);
656         } // END - if
657
658         // Send mail to user
659         SURFBAR_NOTIFY_USER('url_' . $addMode, $content);
660
661         // Return the insert id
662         return $content['insert_id'];
663 }
664
665 // Inserts an url by given data array and return the insert id
666 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
667         // Get userid
668         $userid = bigintval($urlData['url_userid']);
669
670         // Is the id set?
671         if (empty($userid)) {
672                 $userid = 'NULL';
673         } // END - if
674
675         // Just run the insert query for now
676         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_urls` (`url_userid`,`url`,`url_status`,`url_views_max`,`url_views_allowed`,`url_fixed_reload`) VALUES (%s,'%s','%s',%s,%s,%s)",
677                 array(
678                         $userid,
679                         $urlData['url'],
680                         $urlData['url_status'],
681                         $urlData['limit'],
682                         $urlData['limit'],
683                         $urlData['reload']
684                 ), __FUNCTION__, __LINE__
685         );
686
687         // Return insert id
688         return SQL_INSERTID();
689 }
690
691 // Notify admin(s) with a selected message and content
692 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
693         // Prepare template name
694         $templateName = sprintf("admin_surfbar_%s", $messageType);
695
696         // Prepare subject
697         $subject = sprintf("{--ADMIN_SURFBAR_NOTIFY_%s_SUBJECT--}",
698                 strtoupper($messageType)
699         );
700
701         // Is the subject line there?
702         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
703                 // Set default subject if following eval() wents wrong
704                 $subject = '{%message,ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT=' . strtoupper($messageType) . '%}';
705         } // END - if
706
707         // Translate some data if present
708         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
709
710         // Send the notification out
711         return sendAdminNotification($subject, $templateName, $content, $content['url_userid']);
712 }
713
714 // Notify the user about the performed action
715 function SURFBAR_NOTIFY_USER ($messageType, $content) {
716         // Skip notification if userid is zero
717         if ($content['url_userid'] == '0') {
718                 return false;
719         } // END - if
720
721         // Prepare template name
722         $templateName = sprintf("member_surfbar_%s", $messageType);
723
724         // Prepare subject
725         $subject = sprintf("{--MEMBER_SURFBAR_NOTIFY_%s_SUBJECT--}",
726                 strtoupper($messageType)
727         );
728
729         // Is the subject line there?
730         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
731                 // Set default subject if following eval() wents wrong
732                 $subject = '{--MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT--}';
733         } // END - if
734
735         // Translate some data if present
736         $content = SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE($content);
737
738         // Load template
739         $mailText = loadEmailTemplate($templateName, $content, $content['url_userid']);
740
741         // Send the email
742         return sendEmail($content['url_userid'], $subject, $mailText);
743 }
744
745 // Translates some data for template usage
746 // @TODO Can't we use our new expression language instead of this ugly code?
747 function SURFBAR_PREPARE_CONTENT_FOR_TEMPLATE ($content) {
748         // Prepare some code
749         if (isset($content['url_registered']))  $content['url_registered']  = generateDateTime($content['url_registered'], 2);
750         if (isset($content['url_last_locked'])) $content['url_last_locked'] = generateDateTime($content['url_last_locked'], 2);
751
752         // Return translated content
753         return $content;
754 }
755
756 // Translates the limit
757 function translateSurfbarLimit ($limit) {
758         // Is this zero?
759         if ($limit == '0') {
760                 // Unlimited!
761                 $return = '{--MEMBER_SURFBAR_UNLIMITED_VIEWS--}';
762         } else {
763                 // Translate comma
764                 $return = '{%pipe,translateComma=' . $limit . '%}';
765         }
766
767         // Return value
768         return $return;
769 }
770
771 // Translate the URL status
772 function translateSurfbarUrlStatus ($status) {
773         // NULL must be handled carfefully
774         if ((is_null($status)) || (trim($status) == '')) {
775                 // Is NULL, so return other language string
776                 return '{--SURFBAR_URL_STATUS_NONE--}';
777         } else {
778                 // Return regular result
779                 return sprintf("{--SURFBAR_URL_STATUS_%s--}", strtoupper($status));
780         }
781 }
782
783 // Translates the given action into a link title for members
784 function translateMemberSurfbarActionToTitle ($action) {
785         // Do we have cache?
786         if (!isset($GLOBALS[__FUNCTION__][$action])) {
787                 // Construct default return string (unknown
788                 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_TITLE=' . $action . '%}';
789
790                 // ... and the id's name
791                 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_TITLE';
792
793                 // Is the id there?
794                 if (isMessageIdValid($messageId)) {
795                         // Then use it
796                         $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
797                 } // END - if
798         } // END - if
799
800         // Return cache
801         return $GLOBALS[__FUNCTION__][$action];
802 }
803
804 // Translates the given action into a submit button for members
805 function translateMemberSurfbarActionToSubmit ($action) {
806         // Do we have cache?
807         if (!isset($GLOBALS[__FUNCTION__][$action])) {
808                 // Construct default return string (unknown
809                 $GLOBALS[__FUNCTION__][$action] = '{%message,MEMBER_SURFBAR_ACTION_UNKNOWN_SUBMIT=' . $action . '%}';
810
811                 // ... and the id's name
812                 $messageId = 'MEMBER_SURFBAR_ACTION_' . strtoupper($action) . '_SUBMIT';
813
814                 // Is the id there?
815                 if (isMessageIdValid($messageId)) {
816                         // Then use it
817                         $GLOBALS[__FUNCTION__][$action] = '{--' . $messageId . '--}';
818                 } // END - if
819         } // END - if
820
821         // Return cache
822         return $GLOBALS[__FUNCTION__][$action];
823 }
824
825 // Determine reward
826 function SURFBAR_DETERMINE_REWARD ($onlyMin = false) {
827         // Static values are default
828         $reward = getConfig('surfbar_static_reward');
829
830         // Do we have static or dynamic?
831         if (getSurfbarPaymentModel() == 'DYNAMIC') {
832                 // "Calculate" dynamic reward
833                 if ($onlyMin === true) {
834                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
835                 } else {
836                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
837                 }
838         } // END - if
839
840         // Return reward
841         return $reward;
842 }
843
844 // Determine costs
845 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
846         // Static costs is default
847         $costs  = getConfig('surfbar_static_costs');
848
849         // Do we have static or dynamic?
850         if (getSurfbarPaymentModel() == 'DYNAMIC') {
851                 // "Calculate" dynamic costs
852                 if ($onlyMin) {
853                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
854                 } else {
855                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
856                 }
857         } // END - if
858
859         // Return costs
860         return $costs;
861 }
862
863 // "Calculate" dynamic add
864 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
865         // Get min/max values
866         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
867         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
868
869         // "Calculate" dynamic part and return it
870         return mt_rand($min, $max);
871 }
872
873 // Determine right template name
874 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
875         // Default is the frameset
876         $templateName = 'surfbar_frameset';
877
878         // Any frame set? ;-)
879         if (isGetRequestElementSet('frame')) {
880                 // Use the frame as a template name part... ;-)
881                 $templateName = sprintf("surfbar_frame_%s",
882                         getRequestElement('frame')
883                 );
884         } // END - if
885
886         // Return result
887         return $templateName;
888 }
889
890 // Check if the "reload lock" of the current user is full, call this function
891 // before you call SURFBAR_CHECK_RELOAD_LOCK().
892 function SURFBAR_CHECK_RELOAD_FULL () {
893         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Fixed surf lock is ' . getConfig('surfbar_static_lock') . ' - ENTERED!');
894         // Default is full!
895         $isFull = true;
896
897         // Cache static reload lock
898         $GLOBALS['surfbar_cache']['surf_lock'] = getConfig('surfbar_static_lock');
899
900         // Do we have dynamic model?
901         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - BEFORE');
902         if (getSurfbarPaymentModel() == 'DYNAMIC') {
903                 // "Calculate" dynamic lock
904                 $GLOBALS['surfbar_cache']['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
905         } // END - if
906         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'surf_lock=' . $GLOBALS['surfbar_cache']['surf_lock'] . ' - AFTER');
907
908         // Ask the database
909         $result = SQL_QUERY_ESC("SELECT
910         COUNT(l.`locks_id`) AS `cnt`
911 FROM
912         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
913 INNER JOIN
914         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
915 ON
916         u.`url_id`=l.`locks_url_id`
917 WHERE
918         l.`locks_userid`=%s AND
919         (UNIX_TIMESTAMP() - {%%pipe,SURFBAR_GET_SURF_LOCK%%}) < UNIX_TIMESTAMP(l.`locks_last_surfed`) AND
920         (
921                 ((UNIX_TIMESTAMP(l.`locks_last_surfed`) - u.`url_fixed_reload`) < 0 AND u.`url_fixed_reload` > 0) OR
922                 u.`url_fixed_reload` = 0
923         )
924 LIMIT 1",
925                 array(getMemberId()), __FUNCTION__, __LINE__
926         );
927
928         // Fetch row
929         list($GLOBALS['surfbar_cache']['user_locks']) = SQL_FETCHROW($result);
930
931         // Is it null?
932         if (is_null($GLOBALS['surfbar_cache']['user_locks'])) {
933                 // Then fix it to zero!
934                 $GLOBALS['surfbar_cache']['user_locks'] = '0';
935         } // END - if
936
937         // Free result
938         SQL_FREERESULT($result);
939
940         // Get total URLs
941         $total = SURFBAR_GET_TOTAL_URLS();
942
943         // Do we have some URLs in lock? Admins can always surf on own URLs!
944         $isFull = ((SURFBAR_GET_USER_LOCKS() == $total) && ($total > 0));
945
946         // Return result
947         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userLocks=' . SURFBAR_GET_USER_LOCKS() . ',total=' . $total . 'isFull=' . intval($isFull) . ' - EXIT!');
948         return $isFull;
949 }
950
951 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
952 function SURFBAR_GET_TOTAL_URLS ($status = 'ACTIVE', $excludeUserId = NULL) {
953         // Determine depleted user account
954         $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
955
956         // If we dont get any user ids back, there are no URLs
957         if (count($userids['url_userid']) == 0) {
958                 // No user ids found, no URLs!
959                 return 0;
960         } // END - if
961
962         // Is the exlude userid set?
963         if (isValidUserId($excludeUserId)) {
964                 // Then add it
965                 $userids['url_userid'][$excludeUserId] = $excludeUserId;
966         } // END - if
967
968         // Get amount from database
969         $result = SQL_QUERY_ESC("SELECT
970         COUNT(`url_id`) AS cnt
971 FROM
972         `{?_MYSQL_PREFIX?}_surfbar_urls`
973 WHERE
974         `url_userid` NOT IN (".implode(', ', $userids['url_userid']).") AND
975         `url_status`='%s'
976 LIMIT 1",
977                 array($status), __FUNCTION__, __LINE__
978         );
979
980         // Fetch row
981         list($count) = SQL_FETCHROW($result);
982
983         // Free result
984         SQL_FREERESULT($result);
985
986         // Debug message
987         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'cnt=' . $count);
988
989         // Return result
990         return $count;
991 }
992
993 // Check wether the user is allowed to book more URLs
994 function SURFBAR_IF_USER_BOOK_MORE_URLS ($userid = NULL) {
995         // Is this admin and userid is zero or does the user has some URLs left to book?
996         return (((is_null($userid)) && (isAdmin())) || (SURFBAR_GET_TOTAL_USER_URLS($userid, '', array('REJECTED')) < getSurfbarMaxOrder()));
997 }
998
999 // Get total amount of URLs of given status for current user
1000 function SURFBAR_GET_TOTAL_USER_URLS ($userid = NULL, $status = '', $exclude = '') {
1001         // Is the user 0 and user is logged in?
1002         if ((is_null($userid)) && (isMember())) {
1003                 // Then use this userid
1004                 $userid = getMemberId();
1005         } elseif (is_null($userid)) {
1006                 // Error!
1007                 return (getSurfbarMaxOrder() + 1);
1008         }
1009
1010         // Default is all URLs
1011         $add = '';
1012
1013         // Is the status set?
1014         if (is_array($status)) {
1015                 // Only URLs with these status
1016                 $add = sprintf(" WHERE `url_status` IN('%s')", implode("','", $status));
1017         } elseif (!empty($status)) {
1018                 // Only URLs with this status
1019                 $add = sprintf(" WHERE `url_status`='%s'", $status);
1020         } elseif (is_array($exclude)) {
1021                 // Exclude URLs with these status
1022                 $add = sprintf(" WHERE `url_status` NOT IN('%s')", implode("','", $exclude));
1023         } elseif (!empty($exclude)) {
1024                 // Exclude URLs with this status
1025                 $add = sprintf(" WHERE `url_status` != '%s'", $exclude);
1026         }
1027
1028         // Get amount from database
1029         $count = countSumTotalData($userid, 'surfbar_urls', 'url_id', 'url_userid', true, $add);
1030
1031         // Return result
1032         return $count;
1033 }
1034
1035 // Generate a validation code for the given id number
1036 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt = '') {
1037         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ' - ENTERED!');
1038         // Init hash with invalid value
1039         if (empty($salt)) {
1040                  // Generate random hashed string
1041                 $GLOBALS['surfbar_cache']['salt'] = sha1(generatePassword(mt_rand(200, 255)));
1042                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'newSalt='.SURFBAR_GET_SALT().'', false);
1043         } else {
1044                 // Use this as salt!
1045                 $GLOBALS['surfbar_cache']['salt'] = $salt;
1046                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'oldSalt='.SURFBAR_GET_SALT().'', false);
1047         }
1048
1049         // Hash it with md5() and salt it with the random string
1050         $hashedCode = generateHash(md5($urlId . getEncryptSeparator() . getMemberId()), SURFBAR_GET_SALT());
1051
1052         // Finally encrypt it PGP-like and return it
1053         $valHashedCode = encodeHashForCookie($hashedCode);
1054
1055         // Return hashed value
1056         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',salt=' . $salt . ',urlId=' . $urlId . ',salt=' . $salt . ',valHashedCode=' . $valHashedCode . ' - EXIT!');
1057         return $valHashedCode;
1058 }
1059
1060 // Check validation code
1061 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
1062         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',check=' . $check . ',salt=' . $salt . ' - ENTERED!');
1063         // Secure id number
1064         $urlId = bigintval($urlId);
1065
1066         // Now generate the code again
1067         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
1068
1069         // Return result of checking hashes and salts
1070         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',(code==check)=' . intval($code == $check) . ',(salt==salts_last_salt)=' . intval($salt == SURFBAR_GET_DATA('salts_last_salt')) . ' - EXIT!');
1071         return (($code == $check) && ($salt == SURFBAR_GET_DATA('salts_last_salt')));
1072 }
1073
1074 // Lockdown the userid/id combination (reload lock)
1075 function SURFBAR_LOCKDOWN_ID ($urlId) {
1076         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ' - ENTERED!');
1077         // Search for an entry
1078         $countLock = countSumTotalData(getMemberId(), 'surfbar_locks', 'locks_id', 'locks_userid', true, ' AND `locks_url_id`=' . bigintval($urlId));
1079
1080         // Do we have no record?
1081         if ($countLock == 0) {
1082                 // Just add it to the database
1083                 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_locks` (`locks_userid`,`locks_url_id`) VALUES (%s, %s)',
1084                         array(
1085                                 getMemberId(),
1086                                 bigintval($urlId)
1087                         ), __FUNCTION__, __LINE__);
1088         } // END - if
1089
1090         // Remove the salt from database
1091         SQL_QUERY_ESC('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_surfbar_salts` WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1',
1092                 array(
1093                         bigintval($urlId),
1094                         getMemberId()
1095                 ), __FUNCTION__, __LINE__);
1096
1097         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',getMemberId()=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1098 }
1099
1100 // Pay points to the user and remove it from the sender if userid is given else it is a "sponsored surf"
1101 function SURFBAR_PAY_POINTS () {
1102         // Remove it from the URL owner
1103         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS() . ' - ENTERED!');
1104         if (isValidUserId(SURFBAR_GET_USERID())) {
1105                 // Subtract points and ignore return status
1106                 subtractPoints(sprintf("surfbar_%s", getSurfbarPaymentModel()), SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
1107         } // END - if
1108
1109         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.getMemberId().',reward='.SURFBAR_GET_REWARD());
1110         // Init referral system here
1111         initReferralSystem();
1112
1113         // Book it to the user and ignore return status
1114         addPointsThroughReferralSystem(sprintf("surfbar:%s", getSurfbarPaymentModel()), getMemberId(), SURFBAR_GET_REWARD());
1115         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid='.SURFBAR_GET_USERID().',costs='.SURFBAR_GET_COSTS() . ' - EXIT!');
1116 }
1117
1118 // Updates the statistics of current URL/userid
1119 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
1120         // Init add
1121         $add = '';
1122
1123         // Get allowed views
1124         $allowed = SURFBAR_GET_VIEWS_ALLOWED();
1125
1126         // Do we have a limit?
1127         if ($allowed > 0) {
1128                 // Then count views_max down!
1129                 $add .= ',`url_views_max`=`url_views_max`-1';
1130         } // END - if
1131
1132         // Update URL stats
1133         SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_views_total`=`url_views_total`+1' . $add . ' WHERE `url_id`=%s LIMIT 1',
1134                 array(SURFBAR_GET_ID()), __FUNCTION__, __LINE__);
1135
1136         // Update the stats entry
1137         SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `stats_count`=`stats_count`+1 WHERE `stats_userid`=%s AND `stats_url_id`=%s LIMIT 1',
1138                 array(
1139                         getMemberId(),
1140                         SURFBAR_GET_ID()
1141                 ), __FUNCTION__, __LINE__);
1142
1143         // Was that update okay?
1144         if (SQL_HASZEROAFFECTED()) {
1145                 // No, then insert entry
1146                 SQL_QUERY_ESC('INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_stats` (`stats_userid`,`stats_url_id`,`stats_count`) VALUES (%s,%s,1)',
1147                         array(
1148                                 getMemberId(),
1149                                 SURFBAR_GET_ID()
1150                         ), __FUNCTION__, __LINE__);
1151         } // END - if
1152
1153         // Update total/daily/weekly/monthly counter
1154         incrementConfigEntry('surfbar_total_counter');
1155         incrementConfigEntry('surfbar_daily_counter');
1156         incrementConfigEntry('surfbar_weekly_counter');
1157         incrementConfigEntry('surfbar_monthly_counter');
1158
1159         // Update config as well
1160         updateConfiguration(array('surfbar_total_counter', 'surfbar_daily_counter', 'surfbar_weekly_counter', 'surfbar_monthly_counter'), array(1,1,1,1), '+');
1161 }
1162
1163 // Update the salt for validation and statistics
1164 function SURFBAR_UPDATE_SALT_STATS () {
1165         // Update salt
1166         SURFBAR_GENERATE_VALIDATION_CODE(SURFBAR_GET_ID());
1167
1168         // Make sure only valid salts can pass
1169         if (SURFBAR_GET_SALT() == 'INVALID') {
1170                 // Invalid provided
1171                 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid salt provided, id=' . SURFBAR_GET_ID() . ',getMemberId()=' . getMemberId());
1172         } // END - if
1173
1174         // Update statistics record
1175         SURFBAR_UPDATE_INSERT_STATS_RECORD();
1176
1177         // Simply store the salt from cache away in database...
1178         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_salts` SET `salts_last_salt`='%s' WHERE `salts_url_id`=%s AND `salts_userid`=%s LIMIT 1",
1179                 array(
1180                         SURFBAR_GET_SALT(),
1181                         SURFBAR_GET_ID(),
1182                         getMemberId()
1183                 ), __FUNCTION__, __LINE__);
1184
1185         // Debug message
1186         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . SURFBAR_GET_SALT() . ',id=' . SURFBAR_GET_ID() . ',userid=' . getMemberId() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - UPDATE!');
1187
1188         // Was that okay?
1189         if (SQL_HASZEROAFFECTED()) {
1190                 // Insert missing entry!
1191                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_surfbar_salts` (`salts_url_id`,`salts_userid`,`salts_last_salt`) VALUES (%s, %s, '%s')",
1192                         array(
1193                                 SURFBAR_GET_ID(),
1194                                 getMemberId(),
1195                                 SURFBAR_GET_SALT()
1196                         ), __FUNCTION__, __LINE__);
1197         } // END - if
1198
1199         // Debug message
1200         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'affectedRows=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1201
1202         // Return if the update was okay
1203         return (!SQL_HASZEROAFFECTED());
1204 }
1205
1206 // Check if the reload lock is active for given id
1207 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
1208         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $urlId . ' -  ENTERED!');
1209         // Ask the database
1210         $result = SQL_QUERY_ESC("SELECT COUNT(`locks_id`) AS cnt
1211 FROM
1212         `{?_MYSQL_PREFIX?}_surfbar_locks`
1213 WHERE
1214         `locks_userid`=%s AND
1215         `locks_url_id`=%s AND
1216         (UNIX_TIMESTAMP() - ".SURFBAR_GET_SURF_LOCK().") < UNIX_TIMESTAMP(`locks_last_surfed`)
1217 ORDER BY
1218         `locks_last_surfed` ASC
1219 LIMIT 1",
1220                 array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1221         );
1222
1223         // Fetch counter
1224         list($count) = SQL_FETCHROW($result);
1225
1226         // Free result
1227         SQL_FREERESULT($result);
1228
1229         // Return check
1230         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',count=' . $count . ',SURFBAR_GET_SURF_LOCK()=' . SURFBAR_GET_SURF_LOCK() . ' - EXIT!');
1231         return ($count == 1);
1232 }
1233
1234 // Determine which user hash no more points left
1235 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
1236         // Init array
1237         $userids = array(
1238                 'url_userid'   => array(),
1239                 'points'       => array(),
1240                 'notified'     => array(),
1241         );
1242
1243         // Do we have a current user id?
1244         if ((isMember()) && ($limit == '0')) {
1245                 // Then add this as well
1246                 $userids['url_userid'][getMemberId()] = getMemberId();
1247                 $userids['points'][getMemberId()]     = getTotalPoints(getMemberId());
1248                 $userids['notified'][getMemberId()]   = '0';
1249
1250                 // Get all userid except logged in one
1251                 $result = SQL_QUERY_ESC("SELECT
1252         u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1253 FROM
1254         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1255 INNER JOIN
1256         `{?_MYSQL_PREFIX?}_user_data` AS d
1257 ON
1258         u.`url_userid`=d.`userid`
1259 WHERE
1260         u.`url_userid` NOT IN (%s,0) AND
1261         u.`url_status`='ACTIVE'
1262 GROUP BY
1263         u.`url_userid`
1264 ORDER BY
1265         u.`url_userid` ASC",
1266                         array(getMemberId()), __FUNCTION__, __LINE__);
1267         } else {
1268                 // Get all userid
1269                 $result = SQL_QUERY("SELECT
1270         u.url_userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
1271 FROM
1272         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1273 INNER JOIN
1274         `{?_MYSQL_PREFIX?}_user_data` AS d
1275 ON
1276         u.`url_userid`=d.`userid`
1277 WHERE
1278         u.`url_userid` > 0 AND
1279         u.`url_status`='ACTIVE'
1280 GROUP BY
1281         u.`url_userid`
1282 ORDER BY
1283         u.`url_userid` ASC", __FUNCTION__, __LINE__);
1284         }
1285
1286         // Load all userid
1287         while ($content = SQL_FETCHARRAY($result)) {
1288                 // Get total points
1289                 $points = getTotalPoints($content['url_userid']);
1290                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ',points=' . $points);
1291
1292                 // Shall we add this to ignore?
1293                 if ($points <= $limit) {
1294                         // Ignore this one!
1295                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $content['url_userid'] . ' has depleted points amount!');
1296                         $userids['url_userid'][$content['url_userid']] = $content['url_userid'];
1297                         $userids['points'][$content['url_userid']]     = $points;
1298                         $userids['notified'][$content['url_userid']]   = $content['notified'];
1299                 } // END - if
1300         } // END - while
1301
1302         // Free result
1303         SQL_FREERESULT($result);
1304
1305         // Debug message
1306         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'UIDs::count=' . count($userids) . ' (with own userid=' . getMemberId() . ')');
1307
1308         // Return result
1309         return $userids;
1310 }
1311
1312 // Determine how many users are Online in surfbar
1313 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1314         // Count all users in surfbar modue and return the value
1315         $result = SQL_QUERY('SELECT
1316         `stats_id`
1317 FROM
1318         `{?_MYSQL_PREFIX?}_surfbar_stats`
1319 WHERE
1320         (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`stats_last_surfed`)) <= {?online_timeout?}
1321 GROUP BY
1322         `stats_userid` ASC', __FUNCTION__, __LINE__);
1323
1324         // Fetch count
1325         $count = SQL_NUMROWS($result);
1326
1327         // Free result
1328         SQL_FREERESULT($result);
1329
1330         // Return result
1331         return $count;
1332 }
1333
1334 // Determine waiting time for one URL
1335 function SURFBAR_DETERMINE_WAIT_TIME () {
1336         // Get fixed reload lock
1337         $fixed = SURFBAR_GET_FIXED_RELOAD();
1338
1339         // Is the fixed reload time set?
1340         if ($fixed > 0) {
1341                 // Return it
1342                 return $fixed;
1343         } // END - if
1344
1345         // Static time is default
1346         $time = getConfig('surfbar_static_time');
1347
1348         // Which payment model do we have?
1349         if (getSurfbarPaymentModel() == 'DYNAMIC') {
1350                 // "Calculate" dynamic time
1351                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1352         } // END - if
1353
1354         // Return value
1355         return $time;
1356 }
1357
1358 // Changes the status of an URL from given to other
1359 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data = array()) {
1360         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - ENTERED!');
1361         // Make new status always lower-case
1362         $newStatus = strtolower($newStatus);
1363
1364         // Get URL data for status comparison if missing
1365         if ((!is_array($data)) || (count($data) == 0)) {
1366                 // Fetch missing URL data
1367                 $data = SURFBAR_GET_URL_DATA($urlId);
1368         } // END - if
1369
1370         // Prepare array
1371         $filterData =  array(
1372                 'url_id'      => $urlId,
1373                 'prev_status' => $prevStatus,
1374                 'new_status'  => $newStatus,
1375                 'data'        => $data,
1376                 'abort'       => null
1377         );
1378
1379         // Run pre filter chain
1380         $filterData = runFilterChain('pre_change_surfbar_url_status', $filterData);
1381
1382         // Abort here?
1383         if (!is_null($filterData['abort'])) {
1384                 // Abort here
1385                 return $filterData['abort'];
1386         }
1387
1388         // Update the status now
1389         // ---------- Comment out for debugging/developing member actions! ---------
1390         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_status`='%s' WHERE `url_id`=%s LIMIT 1",
1391                 array(
1392                         $newStatus,
1393                         bigintval($urlId)
1394                 ), __FUNCTION__, __LINE__);
1395         // ---------- Comment out for debugging/developing member actions! ---------
1396
1397         // Was that fine?
1398         // ---------- Comment out for debugging/developing member actions! ---------
1399         if (SQL_AFFECTEDROWS() != 1) {
1400                 // No, something went wrong
1401                 return false;
1402         } // END - if
1403         // ---------- Comment out for debugging/developing member actions! ---------
1404
1405         // Run post filter chain
1406         $filterData = runFilterChain('post_change_surfbar_url_status', $filterData);
1407
1408         // Extract data from it again
1409         $data = $filterData['data'];
1410
1411         // All done!
1412         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - EXIT!');
1413         return true;
1414 }
1415
1416 // Calculate minimum value for dynamic payment model
1417 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1418         // Addon is zero by default
1419         $addon = '0';
1420
1421         // Percentage part
1422         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1423
1424         // Get total users
1425         $totalUsers = getTotalConfirmedUser();
1426
1427         // Get online users
1428         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1429
1430         // Calculate addon
1431         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1432
1433         // Get total URLs
1434         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1435
1436         // Get user's total URLs
1437         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, 'ACTIVE');
1438
1439         // Calculate addon
1440         if ($totalUrls > 0) {
1441                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1442         } else {
1443                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1444         }
1445
1446         // Return addon
1447         return $addon;
1448 }
1449
1450 // Calculate maximum value for dynamic payment model
1451 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1452         // Addon is zero by default
1453         $addon = '0';
1454
1455         // Maximum value
1456         $max = log(2);
1457
1458         // Percentage part
1459         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1460
1461         // Get total users
1462         $totalUsers = getTotalConfirmedUser();
1463
1464         // Calculate addon
1465         $addon += abs($max * $percent * $totalUsers);
1466
1467         // Get total URLs
1468         $totalUrls = SURFBAR_GET_TOTAL_URLS('ACTIVE', 0);
1469
1470         // Calculate addon
1471         $addon += abs($max * $percent * $totalUrls);
1472
1473         // Return addon
1474         return $addon;
1475 }
1476
1477 // Calculate dynamic lock
1478 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1479         // Default lock is 30 seconds
1480         $addon = 30;
1481
1482         // Get online users
1483         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1484
1485         // Calculate lock
1486         $addon = abs(log($onlineUsers / $addon + 1));
1487
1488         // Return value
1489         return $addon;
1490 }
1491
1492 // "Getter" for lock ids array
1493 function SURFBAR_GET_LOCK_IDS () {
1494         // Prepare some arrays
1495         $IDs = array();
1496         $USE = array();
1497         $ignored = array();
1498
1499         // Get all id from locks within the timestamp
1500         $result = SQL_QUERY_ESC("SELECT
1501         `locks_id`,
1502         `locks_url_id`,
1503         UNIX_TIMESTAMP(`locks_last_surfed`) AS `last_surfed`
1504 FROM
1505         `{?_MYSQL_PREFIX?}_surfbar_locks`
1506 WHERE
1507         `locks_userid`=%s
1508 ORDER BY
1509         `locks_id` ASC", array(getMemberId()),
1510         __FUNCTION__, __LINE__);
1511
1512         // Load all entries
1513         while ($content = SQL_FETCHARRAY($result)) {
1514                 // Debug message
1515                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',rest='.(time() - $content['last_surfed']).'/'.SURFBAR_GET_SURF_LOCK());
1516
1517                 // Skip entries that are too old
1518                 if (($content['last_surfed'] > (time() - SURFBAR_GET_SURF_LOCK())) && (!in_array($content['locks_url_id'], $ignored))) {
1519                         // Debug message
1520                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1521
1522                         // Add only if missing or bigger
1523                         if ((!isset($IDs[$content['locks_url_id']])) || ($IDs[$content['locks_url_id']] > $content['last_surfed'])) {
1524                                 // Debug message
1525                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1526
1527                                 // Add this id
1528                                 $IDs[$content['locks_url_id']] = $content['last_surfed'];
1529                                 $USE[$content['locks_url_id']] = $content['locks_id'];
1530                         } // END - if
1531                 } else {
1532                         // Debug message
1533                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1534
1535                         // Ignore these old entries!
1536                         $ignored[] = $content['locks_url_id'];
1537                         unset($IDs[$content['locks_url_id']]);
1538                         unset($USE[$content['locks_url_id']]);
1539                 }
1540         } // END - while
1541
1542         // Free result
1543         SQL_FREERESULT($result);
1544
1545         // Return array
1546         return $USE;
1547 }
1548
1549 // "Getter" for maximum random number
1550 function SURFBAR_GET_MAX_RANDOM ($userids, $add) {
1551         // Count max availabe entries
1552         $result = SQL_QUERY("SELECT
1553         sbu.url_id AS cnt
1554 FROM
1555         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1556 LEFT JOIN
1557         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1558 ON
1559         sbu.url_id=sbs.salts_url_id
1560 LEFT JOIN
1561         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1562 ON
1563         sbu.url_id=l.locks_url_id
1564 WHERE
1565         sbu.url_userid NOT IN (" . implode(',', $userids) . ") AND
1566         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0)) AND
1567         sbu.url_status='ACTIVE'
1568         " . $add . "
1569 GROUP BY
1570         sbu.url_id ASC", __FUNCTION__, __LINE__);
1571
1572         // Log last query
1573         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1574
1575         // Fetch max rand
1576         $maxRand = SQL_NUMROWS($result);
1577
1578         // Free result
1579         SQL_FREERESULT($result);
1580
1581         // Return value
1582         return $maxRand;
1583 }
1584
1585 // Load all URLs of the current user and return it as an array
1586 function SURFBAR_GET_USER_URLS () {
1587         // Init array
1588         $urlArray = array();
1589
1590         // Begin the query
1591         $result = SQL_QUERY_ESC("SELECT
1592         u.url_id,
1593         u.url_userid,
1594         u.url,
1595         u.url_status,
1596         u.url_views_total,
1597         u.url_views_max,
1598         u.url_views_allowed,
1599         UNIX_TIMESTAMP(u.url_registered) AS `url_registered`,
1600         UNIX_TIMESTAMP(u.`url_last_locked`) AS `url_last_locked`,
1601         u.`url_lock_reason`
1602 FROM
1603         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1604 WHERE
1605         u.`url_userid`=%s AND
1606         u.`url_status` != 'DELETED'
1607 ORDER BY
1608         u.url_id ASC",
1609         array(getMemberId()), __FUNCTION__, __LINE__);
1610
1611         // Are there entries?
1612         if (!SQL_HASZERONUMS($result)) {
1613                 // Load all rows
1614                 while ($row = SQL_FETCHARRAY($result)) {
1615                         // Add the row
1616                         $urlArray[$row['url_id']] = $row;
1617                 } // END - while
1618         } // END - if
1619
1620         // Free result
1621         SQL_FREERESULT($result);
1622
1623         // Return the array
1624         return $urlArray;
1625 }
1626
1627 // "Getter" for member action array for given status
1628 function SURFBAR_GET_ARRAY_FROM_STATUS ($status) {
1629         // Init array
1630         $returnArray = array();
1631
1632         // Get all assigned actions
1633         $result = SQL_QUERY_ESC("SELECT `actions_action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1634                 array($status), __FUNCTION__, __LINE__);
1635
1636         // Some entries there?
1637         if (!SQL_HASZERONUMS($result)) {
1638                 // Load all actions
1639                 // @TODO This can be somehow rewritten
1640                 while ($content = SQL_FETCHARRAY($result)) {
1641                         $returnArray[] = $content['actions_action'];
1642                 } // END - if
1643         } // END - if
1644
1645         // Free result
1646         SQL_FREERESULT($result);
1647
1648         // Return result
1649         return $returnArray;
1650 }
1651
1652 // Reload to configured stop page
1653 function SURFBAR_RELOAD_TO_STOP_PAGE ($page = 'stop') {
1654         // Internal or external?
1655         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'page=' . $page . ' - ENTERED!');
1656         if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1657                 // Reload to internal page
1658                 redirectToUrl('surfbar.php?frame=' . $page);
1659         } else {
1660                 // Reload to external page
1661                 redirectToConfiguredUrl('surfbar_pause_url');
1662         }
1663 }
1664
1665 // Determine next id for surfbar or get data for given id, always call this before you call other
1666 // getters below this function!
1667 function SURFBAR_DETERMINE_NEXT_ID ($urlId = NULL) {
1668         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ' - ENTERED!');
1669         // Default is no id and no random number
1670         $nextId = '0';
1671         $randNum = '0';
1672
1673         // Is the id set?
1674         if (is_null($urlId)) {
1675                 // Get array with lock ids
1676                 $USE = SURFBAR_GET_LOCK_IDS();
1677
1678                 // Shall we add some URL ids to ignore?
1679                 $add = '';
1680                 if (count($USE) > 0) {
1681                         // Ignore some!
1682                         $add = " AND sbu.`url_id` NOT IN (";
1683                         foreach ($USE as $url_id => $lid) {
1684                                 // Add URL id
1685                                 $add .= $url_id.',';
1686                         } // END - foreach
1687
1688                         // Add closing bracket
1689                         $add = substr($add, 0, -1) . ')';
1690                 } // END - if
1691
1692                 // Determine depleted user account
1693                 $userids = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1694
1695                 // Get maximum randomness factor
1696                 $maxRand = SURFBAR_GET_MAX_RANDOM($userids['url_userid'], $add);
1697
1698                 // If more than one URL can be called generate the random number!
1699                 if ($maxRand > 1) {
1700                         // Generate random number
1701                         $randNum = mt_rand(0, ($maxRand - 1));
1702                 } // END - if
1703
1704                 // And query the database
1705                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.SURFBAR_GET_SURF_LOCK());
1706                 $result = SQL_QUERY_ESC("SELECT
1707         sbu.url_id,
1708         sbu.url_userid,
1709         sbu.url,
1710         sbs.salts_last_salt,
1711         sbu.url_views_total,
1712         sbu.url_views_max,
1713         sbu.url_views_allowed,
1714         UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1715         sbu.url_fixed_reload
1716 FROM
1717         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1718 LEFT JOIN
1719         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1720 ON
1721         sbu.url_id=sbs.salts_url_id
1722 LEFT JOIN
1723         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1724 ON
1725         sbu.url_id=l.locks_url_id
1726 WHERE
1727         sbu.`url_userid` NOT IN (".implode(',', $userids['url_userid']).") AND
1728         sbu.url_status='ACTIVE' AND
1729         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1730         ".$add."
1731 GROUP BY
1732         sbu.`url_id`
1733 ORDER BY
1734         l.locks_last_surfed ASC,
1735         sbu.url_id ASC
1736 LIMIT %s,1",
1737                         array($randNum), __FUNCTION__, __LINE__
1738                 );
1739         } else {
1740                 // Get data from specified id number
1741                 $result = SQL_QUERY_ESC("SELECT
1742         sbu.url_id,
1743         sbu.url_userid,
1744         sbu.url,
1745         sbs.salts_last_salt,
1746         sbu.url_views_total,
1747         sbu.url_views_max,
1748         sbu.url_views_allowed,
1749         UNIX_TIMESTAMP(l.locks_last_surfed) AS last_surfed,
1750         sbu.url_fixed_reload
1751 FROM
1752         `{?_MYSQL_PREFIX?}_surfbar_urls` AS sbu
1753 LEFT JOIN
1754         `{?_MYSQL_PREFIX?}_surfbar_salts` AS sbs
1755 ON
1756         sbu.url_id=sbs.salts_url_id
1757 LEFT JOIN
1758         `{?_MYSQL_PREFIX?}_surfbar_locks` AS l
1759 ON
1760         sbu.url_id=l.locks_url_id
1761 WHERE
1762         sbu.url_userid != %s AND
1763         sbu.url_status='ACTIVE' AND
1764         sbu.url_id=%s AND
1765         (sbu.url_views_allowed=0 OR (sbu.url_views_allowed > 0 AND sbu.url_views_max > 0))
1766 LIMIT 1",
1767                         array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1768                 );
1769         }
1770
1771         // Is there an id number?
1772         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1773         if (SQL_NUMROWS($result) == 1) {
1774                 // Load/cache data
1775                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', false);
1776                 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1777                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', false);
1778
1779                 // Determine waiting time
1780                 $GLOBALS['surfbar_cache']['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1781
1782                 // Is the last salt there?
1783                 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1784                         // Then repair it wit the static!
1785                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', false);
1786                         $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1787                 } // END - if
1788
1789                 // Fix missing last_surfed
1790                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1791                         // Fix it here
1792                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', false);
1793                         $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1794                 } // END - if
1795
1796                 // Get base/fixed reward and costs
1797                 $GLOBALS['surfbar_cache']['reward'] = SURFBAR_DETERMINE_REWARD();
1798                 $GLOBALS['surfbar_cache']['costs']  = SURFBAR_DETERMINE_COSTS();
1799                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS());
1800
1801                 // Only in dynamic model add the dynamic bonus!
1802                 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1803                         // Calculate dynamic reward/costs and add it
1804                         $GLOBALS['surfbar_cache']['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1805                         $GLOBALS['surfbar_cache']['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1806                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.SURFBAR_GET_REWARD().'|costs='.SURFBAR_GET_COSTS());
1807                 } // END - if
1808
1809                 // Now get the id
1810                 $nextId = SURFBAR_GET_ID();
1811         } // END - if
1812
1813         // Free result
1814         SQL_FREERESULT($result);
1815
1816         // Return result
1817         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',nextId=' . $nextId . ' - EXIT!');
1818         return $nextId;
1819 }
1820
1821 //-----------------------------------------------------------------------------
1822 // Wrapper function
1823 //-----------------------------------------------------------------------------
1824
1825 // "Getter" for surfbar_dynamic_percent
1826 function getSurfbarDynamicPercent () {
1827         // Do we have cache?
1828         if (!isset($GLOBALS[__FUNCTION__])) {
1829                 // Determine it
1830                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_dynamic_percent');
1831         } // END - if
1832
1833         // Return cache
1834         return $GLOBALS[__FUNCTION__];
1835 }
1836
1837 // "Getter" for surfbar_static_reward
1838 function getSurfbarStaticReward () {
1839         // Do we have cache?
1840         if (!isset($GLOBALS[__FUNCTION__])) {
1841                 // Determine it
1842                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_reward');
1843         } // END - if
1844
1845         // Return cache
1846         return $GLOBALS[__FUNCTION__];
1847 }
1848
1849 // "Getter" for surfbar_static_time
1850 function getSurfbarStaticTime () {
1851         // Do we have cache?
1852         if (!isset($GLOBALS[__FUNCTION__])) {
1853                 // Determine it
1854                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_time');
1855         } // END - if
1856
1857         // Return cache
1858         return $GLOBALS[__FUNCTION__];
1859 }
1860
1861 // "Getter" for surfbar_max_order
1862 function getSurfbarMaxOrder () {
1863         // Do we have cache?
1864         if (!isset($GLOBALS[__FUNCTION__])) {
1865                 // Determine it
1866                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_max_order');
1867         } // END - if
1868
1869         // Return cache
1870         return $GLOBALS[__FUNCTION__];
1871 }
1872
1873 // "Getter" for surfbar_payment_model
1874 function getSurfbarPaymentModel () {
1875         // Do we have cache?
1876         if (!isset($GLOBALS[__FUNCTION__])) {
1877                 // Determine it
1878                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_payment_model');
1879         } // END - if
1880
1881         // Return cache
1882         return $GLOBALS[__FUNCTION__];
1883 }
1884
1885 //------------------------------------------------------------------------------
1886 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
1887 // THE $GLOBALS['surfbar_cache'] ARRAY!
1888 //------------------------------------------------------------------------------
1889
1890 // Initializes the surfbar
1891 function SURFBAR_INIT () {
1892         // Init cache array
1893         $GLOBALS['surfbar_cache'] = array();
1894 }
1895
1896 // Private getter for data elements
1897 function SURFBAR_GET_DATA ($element) {
1898         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element=' . $element . ' - ENTERED!');
1899
1900         // Default is null
1901         $data = NULL;
1902
1903         // Is the entry there?
1904         if (isset($GLOBALS['surfbar_cache'][$element])) {
1905                 // Then take it
1906                 $data = $GLOBALS['surfbar_cache'][$element];
1907         } else { // END - if
1908                 print('<pre>');
1909                 print_r($GLOBALS['surfbar_cache']);
1910                 print('</pre>');
1911                 debug_report_bug(__FUNCTION__, __LINE__, 'Element ' . $element . ' not found.');
1912         }
1913
1914         // Return result
1915         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data . ' - EXIT!');
1916         return $data;
1917 }
1918
1919 // Getter for reward from cache
1920 function SURFBAR_GET_REWARD () {
1921         // Get data element and return its contents
1922         return SURFBAR_GET_DATA('reward');
1923 }
1924
1925 // Getter for costs from cache
1926 function SURFBAR_GET_COSTS () {
1927         // Get data element and return its contents
1928         return SURFBAR_GET_DATA('costs');
1929 }
1930
1931 // Getter for URL from cache
1932 function SURFBAR_GET_URL () {
1933         // Get data element and return its contents
1934         return SURFBAR_GET_DATA('url');
1935 }
1936
1937 // Getter for salt from cache
1938 function SURFBAR_GET_SALT () {
1939         // Get data element and return its contents
1940         return SURFBAR_GET_DATA('salt');
1941 }
1942
1943 // Getter for id from cache
1944 function SURFBAR_GET_ID () {
1945         // Get data element and return its contents
1946         return SURFBAR_GET_DATA('url_id');
1947 }
1948
1949 // Getter for userid from cache
1950 function SURFBAR_GET_USERID () {
1951         // Get data element and return its contents
1952         return SURFBAR_GET_DATA('url_userid');
1953 }
1954
1955 // Getter for user reload locks
1956 function SURFBAR_GET_USER_LOCKS () {
1957         // Get data element and return its contents
1958         return SURFBAR_GET_DATA('user_locks');
1959 }
1960
1961 // Getter for reload time
1962 function SURFBAR_GET_RELOAD_TIME () {
1963         // Get data element and return its contents
1964         return SURFBAR_GET_DATA('time');
1965 }
1966
1967 // Getter for allowed views
1968 function SURFBAR_GET_VIEWS_ALLOWED () {
1969         // Get data element and return its contents
1970         return SURFBAR_GET_DATA('url_views_allowed');
1971 }
1972
1973 // Getter for maximum views
1974 function SURFBAR_GET_VIEWS_MAX () {
1975         // Get data element and return its contents
1976         return SURFBAR_GET_DATA('url_views_max');
1977 }
1978
1979 // Getter for fixed reload
1980 function SURFBAR_GET_FIXED_RELOAD () {
1981         // Get data element and return its contents
1982         return SURFBAR_GET_DATA('url_fixed_reload');
1983 }
1984
1985 // Getter for surf lock
1986 function SURFBAR_GET_SURF_LOCK () {
1987         // Get data element and return its contents
1988         return SURFBAR_GET_DATA('surf_lock');
1989 }
1990
1991 // Getter for new status
1992 function SURFBAR_GET_NEW_STATUS () {
1993         // Get data element and return its contents
1994         return SURFBAR_GET_DATA('new_status');
1995 }
1996
1997 // Getter for last salt
1998 function SURFBAR_GET_LAST_SALT () {
1999         // Get data element and return its contents
2000         return SURFBAR_GET_DATA('salts_last_salt');
2001 }
2002
2003 // [EOF]
2004 ?>