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