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