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