Extension ext-surfbar continued:
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/31/2008 *
4  * ===================                          Last change: 08/31/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : surfbar_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for surfbar                            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die Surfbar                      *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 //------------------------------------------------------------------------------
44 //                               Admin functions
45 //------------------------------------------------------------------------------
46
47 // Admin has added an URL with given user id and so on
48 function doSurfbarAdminAddUrl ($url, $limit, $reload, $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 (count($IDs) == 0) {
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 (count($IDs) == 0) {
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 getSurfbarActionsDataById ($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 = SQL_QUERY_ESC("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 (SQL_NUMROWS($result) == 1) {
303                         // Load it
304                         list($GLOBALS[__FUNCTION__][$id][$columnName]) = SQL_FETCHROW($result);
305                 } // END - if
306
307                 // Free result
308                 SQL_FREERESULT($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 = SQL_QUERY_ESC("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 = (SQL_NUMROWS($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']) = SQL_FETCHROW($result);
334         } // END - if
335
336         // Free result
337         SQL_FREERESULT($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                 SQL_QUERY_ESC("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 (count($urlArray) > 0) {
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                         SQL_QUERY_ESC("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 (count($urlArray) > 0);
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 = SQL_QUERY_ESC("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 (!SQL_HASZERONUMS($result)) {
641                 // Then load all!
642                 while ($dataRow = SQL_FETCHARRAY($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         SQL_FREERESULT($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         SQL_QUERY_ESC("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 insert id
732         return SQL_INSERTID();
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 = SQL_QUERY_ESC("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']) = SQL_FETCHROW($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         SQL_FREERESULT($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 (count($userids['url_userid']) == 0) {
1004                 // No user ids found, no URLs!
1005                 return 0;
1006         } // END - if
1007
1008         // Is the exlude userid set?
1009         if (isValidUserId($excludeUserId)) {
1010                 // Then add it
1011                 $userids['url_userid'][$excludeUserId] = $excludeUserId;
1012         } // END - if
1013
1014         // Get amount from database
1015         $result = SQL_QUERY_ESC("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) = SQL_FETCHROW($result);
1028
1029         // Free result
1030         SQL_FREERESULT($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                 SQL_QUERY_ESC('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         SQL_QUERY_ESC('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() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - 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 (isValidUserId(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         SQL_QUERY_ESC('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         SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_surfbar_stats` SET `stats_count`=`stats_count`+1 WHERE `stats_userid`=%s AND `stats_url_id`=%s LIMIT 1',
1184                 array(
1185                         getMemberId(),
1186                         getSurfbarId()
1187                 ), __FUNCTION__, __LINE__);
1188
1189         // Was that update okay?
1190         if (SQL_HASZEROAFFECTED()) {
1191                 // No, then insert entry
1192                 SQL_QUERY_ESC('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         SQL_QUERY("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() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - UPDATE!');
1235
1236         // Was that okay?
1237         if (SQL_HASZEROAFFECTED()) {
1238                 // Insert missing entry!
1239                 SQL_QUERY("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=' . SQL_AFFECTEDROWS() . ' - EXIT!');
1254
1255         // Return if the update was okay
1256         return (!SQL_HASZEROAFFECTED());
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 = SQL_QUERY_ESC('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) = SQL_FETCHROW($result);
1278
1279         // Free result
1280         SQL_FREERESULT($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 = SQL_QUERY_ESC("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 = SQL_QUERY("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 = SQL_FETCHARRAY($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         SQL_FREERESULT($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 = SQL_QUERY('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 = SQL_NUMROWS($result);
1382
1383         // Free result
1384         SQL_FREERESULT($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 ((!is_array($data)) || (count($data) == 0)) {
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                 'abort'       => NULL
1433         );
1434
1435         // Run pre filter chain
1436         $filterData = runFilterChain('pre_change_surfbar_url_status', $filterData);
1437
1438         // Abort here?
1439         if (!is_null($filterData['abort'])) {
1440                 // Abort here
1441                 return $filterData['abort'];
1442         } // END - if
1443
1444         // Update the status now
1445         // ---------- Comment out for debugging/developing member actions! ---------
1446         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_surfbar_urls` SET `url_status`='%s' WHERE `url_id`=%s LIMIT 1",
1447                 array(
1448                         $newStatus,
1449                         bigintval($urlId)
1450                 ), __FUNCTION__, __LINE__);
1451         // ---------- Comment out for debugging/developing member actions! ---------
1452
1453         // Was that fine?
1454         // ---------- Comment out for debugging/developing member actions! ---------
1455         if (SQL_AFFECTEDROWS() != 1) {
1456                 // No, something went wrong
1457                 return FALSE;
1458         } // END - if
1459         // ---------- Comment out for debugging/developing member actions! ---------
1460
1461         // Run post filter chain
1462         $filterData = runFilterChain('post_change_surfbar_url_status', $filterData);
1463
1464         // Check if generic 'data' is there
1465         assert(isset($filterData['data']));
1466
1467         // All done!
1468         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - EXIT!');
1469         return TRUE;
1470 }
1471
1472 // Calculate minimum value for dynamic payment model
1473 function calculateSurfbarDynamicMininumValue () {
1474         // Addon is zero by default
1475         $addon = '0';
1476
1477         // Percentage part
1478         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1479
1480         // Get total users
1481         $totalUsers = getTotalConfirmedUser();
1482
1483         // Get online users
1484         $onlineUsers = determineSurfbarTotalOnline();
1485
1486         // Calculate addon
1487         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1488
1489         // Get total URLs
1490         $totalUrls = getSurfbarTotalUrls('ACTIVE', 0);
1491
1492         // Get user's total URLs
1493         $userUrls = getSurfbarTotalUserUrls(0, 'ACTIVE');
1494
1495         // Calculate addon
1496         if ($totalUrls > 0) {
1497                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1498         } else {
1499                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1500         }
1501
1502         // Return addon
1503         return $addon;
1504 }
1505
1506 // Calculate maximum value for dynamic payment model
1507 function calculateSurfbarDynamicMaximumValue () {
1508         // Addon is zero by default
1509         $addon = '0';
1510
1511         // Maximum value
1512         $max = log(2);
1513
1514         // Percentage part
1515         $percent = abs(log(getConfig('surfbar_dynamic_percent') / 100 + 1));
1516
1517         // Get total users
1518         $totalUsers = getTotalConfirmedUser();
1519
1520         // Calculate addon
1521         $addon += abs($max * $percent * $totalUsers);
1522
1523         // Get total URLs
1524         $totalUrls = getSurfbarTotalUrls('ACTIVE', 0);
1525
1526         // Calculate addon
1527         $addon += abs($max * $percent * $totalUrls);
1528
1529         // Return addon
1530         return $addon;
1531 }
1532
1533 // Calculate dynamic lock
1534 function calculateSurfbarDynamicLock () {
1535         // Default lock is 30 seconds
1536         $addon = 30;
1537
1538         // Get online users
1539         $onlineUsers = determineSurfbarTotalOnline();
1540
1541         // Calculate lock
1542         $addon = abs(log($onlineUsers / $addon + 1));
1543
1544         // Return value
1545         return $addon;
1546 }
1547
1548 // "Getter" for lock ids array
1549 function getSurfbarLockIdsArray () {
1550         // Prepare some arrays
1551         $IDs = array();
1552         $USE = array();
1553         $ignored = array();
1554
1555         // Get all id from locks within the timestamp
1556         $result = SQL_QUERY_ESC("SELECT
1557         `locks_id`,
1558         `locks_url_id`,
1559         UNIX_TIMESTAMP(`locks_last_surfed`) AS `last_surfed`
1560 FROM
1561         `{?_MYSQL_PREFIX?}_surfbar_locks`
1562 WHERE
1563         `locks_userid`=%s
1564 ORDER BY
1565         `locks_id` ASC", array(getMemberId()),
1566         __FUNCTION__, __LINE__);
1567
1568         // Load all entries
1569         while ($content = SQL_FETCHARRAY($result)) {
1570                 // Debug message
1571                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'next - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',rest='.(time() - $content['last_surfed']).'/'.getSurfbarSurfLock());
1572
1573                 // Skip entries that are too old
1574                 if (($content['last_surfed'] > (time() - getSurfbarSurfLock())) && (!in_array($content['locks_url_id'], $ignored))) {
1575                         // Debug message
1576                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'okay - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1577
1578                         // Add only if missing or bigger
1579                         if ((!isset($IDs[$content['locks_url_id']])) || ($IDs[$content['locks_url_id']] > $content['last_surfed'])) {
1580                                 // Debug message
1581                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1582
1583                                 // Add this id
1584                                 $IDs[$content['locks_url_id']] = $content['last_surfed'];
1585                                 $USE[$content['locks_url_id']] = $content['locks_id'];
1586                         } // END - if
1587                 } else {
1588                         // Debug message
1589                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ignore - lid='.$content['locks_id'].',url='.$content['locks_url_id'].',last='.$content['last_surfed']);
1590
1591                         // Ignore these old entries!
1592                         array_push($ignored, $content['locks_url_id']);
1593                         unset($IDs[$content['locks_url_id']]);
1594                         unset($USE[$content['locks_url_id']]);
1595                 }
1596         } // END - while
1597
1598         // Free result
1599         SQL_FREERESULT($result);
1600
1601         // Return array
1602         return $USE;
1603 }
1604
1605 // "Getter" for maximum random number
1606 function getSurfbarMaximumRandom ($userids, $add) {
1607         // Count max availabe entries
1608         $result = SQL_QUERY("SELECT
1609         sbu.`url_id` AS `cnt`
1610 FROM
1611         `{?_MYSQL_PREFIX?}_surfbar_urls` AS `sbu`
1612 LEFT JOIN
1613         `{?_MYSQL_PREFIX?}_surfbar_salts` AS `sbs`
1614 ON
1615         sbu.`url_id`=sbs.`salts_url_id`
1616 LEFT JOIN
1617         `{?_MYSQL_PREFIX?}_surfbar_locks` AS `l`
1618 ON
1619         sbu.`url_id`=l.`locks_url_id`
1620 WHERE
1621         sbu.`url_userid` NOT IN (" . implode(',', $userids) . ") AND
1622         (sbu.`url_views_allowed`=0 OR (sbu.`url_views_allowed` > 0 AND sbu.`url_views_max` > 0)) AND
1623         sbu.`url_status`='ACTIVE'
1624         " . $add . "
1625 GROUP BY
1626         sbu.`url_id` ASC", __FUNCTION__, __LINE__);
1627
1628         // Log last query
1629         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1630
1631         // Fetch max rand
1632         $maxRand = SQL_NUMROWS($result);
1633
1634         // Free result
1635         SQL_FREERESULT($result);
1636
1637         // Return value
1638         return $maxRand;
1639 }
1640
1641 // Load all URLs of the current user and return it as an array
1642 function getSurfbarUserUrls () {
1643         // Init array
1644         $urlArray = array();
1645
1646         // Begin the query
1647         $result = SQL_QUERY_ESC("SELECT
1648         u.`url_id`,
1649         u.`url_userid`,
1650         u.`url_package_id`,
1651         u.`url`,
1652         u.`url_status`,
1653         u.`url_views_total`,
1654         u.`url_views_max`,
1655         u.`url_views_allowed`,
1656         UNIX_TIMESTAMP(u.`url_registered`) AS `url_registered`,
1657         UNIX_TIMESTAMP(u.`url_last_locked`) AS `url_last_locked`,
1658         u.`url_lock_reason`
1659 FROM
1660         `{?_MYSQL_PREFIX?}_surfbar_urls` AS u
1661 WHERE
1662         u.`url_userid`=%s AND
1663         u.`url_status` != 'DELETED'
1664 ORDER BY
1665         u.`url_id` ASC",
1666                 array(getMemberId()), __FUNCTION__, __LINE__);
1667
1668         // Are there entries?
1669         if (!SQL_HASZERONUMS($result)) {
1670                 // Load all rows
1671                 while ($row = SQL_FETCHARRAY($result)) {
1672                         // Add the row
1673                         $urlArray[$row['url_id']] = $row;
1674                 } // END - while
1675         } // END - if
1676
1677         // Free result
1678         SQL_FREERESULT($result);
1679
1680         // Return the array
1681         return $urlArray;
1682 }
1683
1684 // "Getter" for member action array for given status
1685 function getSurfbarArrayFromStatus ($status) {
1686         // Init array
1687         $returnArray = array();
1688
1689         // Get all assigned actions
1690         $result = SQL_QUERY_ESC("SELECT `actions_action` FROM `{?_MYSQL_PREFIX?}_surfbar_actions` WHERE `actions_status`='%s' ORDER BY `actions_id` ASC",
1691                 array($status), __FUNCTION__, __LINE__);
1692
1693         // Some entries there?
1694         if (!SQL_HASZERONUMS($result)) {
1695                 // Load all actions
1696                 // @TODO This can be somehow rewritten
1697                 while ($content = SQL_FETCHARRAY($result)) {
1698                         array_push($returnArray, $content['actions_action']);
1699                 } // END - if
1700         } // END - if
1701
1702         // Free result
1703         SQL_FREERESULT($result);
1704
1705         // Return result
1706         return $returnArray;
1707 }
1708
1709 // Reload to configured stop page
1710 function redirectToSurfbarStopPage ($page = 'stop') {
1711         // Internal or external?
1712         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'page=' . $page . ' - ENTERED!');
1713         if ((getConfig('surfbar_pause_mode') == 'INTERNAL') || (getConfig('surfbar_pause_url') == '')) {
1714                 // Reload to internal page
1715                 redirectToUrl('surfbar.php?frame=' . $page);
1716         } else {
1717                 // Reload to external page
1718                 redirectToConfiguredUrl('surfbar_pause_url');
1719         }
1720 }
1721
1722 /**
1723  * Determine next id for surfbar or get data for given id, always call this
1724  * before you call other getters below this function!
1725  */
1726 function determineSurfbarNextId ($urlId = NULL) {
1727         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ' - ENTERED!');
1728         // Default is no id and no random number
1729         $nextId = '0';
1730         $randNum = '0';
1731
1732         // Is the id set?
1733         if (is_null($urlId)) {
1734                 // Get array with lock ids
1735                 $USE = getSurfbarLockIdsArray();
1736
1737                 // Shall we add some URL ids to ignore?
1738                 $add = '';
1739                 if (count($USE) > 0) {
1740                         // Ignore some!
1741                         $add = " AND sbu.`url_id` NOT IN (";
1742                         foreach ($USE as $url_id => $lid) {
1743                                 // Add URL id
1744                                 $add .= $url_id.',';
1745                         } // END - foreach
1746
1747                         // Add closing bracket
1748                         $add = substr($add, 0, -1) . ')';
1749                 } // END - if
1750
1751                 // Determine depleted user account
1752                 $userids = determineSurfbarDepletedUserids();
1753
1754                 // Get maximum randomness factor
1755                 $maxRand = getSurfbarMaximumRandom($userids['url_userid'], $add);
1756
1757                 // If more than one URL can be called generate the random number!
1758                 if ($maxRand > 1) {
1759                         // Generate random number
1760                         $randNum = mt_rand(0, ($maxRand - 1));
1761                 } // END - if
1762
1763                 // And query the database
1764                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'randNum='.$randNum.',maxRand='.$maxRand.',surfLock='.getSurfbarSurfLock());
1765                 $result = SQL_QUERY_ESC("SELECT
1766         sbu.`url_id`,
1767         sbu.`url_userid`,
1768         sbu.`url_package_id`,
1769         sbu.`url`,
1770         sbs.`salts_last_salt`,
1771         sbu.`url_views_total`,
1772         sbu.`url_views_max`,
1773         sbu.`url_views_allowed`,
1774         UNIX_TIMESTAMP(l.`locks_last_surfed`) AS `last_surfed`,
1775         sbu.`url_fixed_reload`
1776 FROM
1777         `{?_MYSQL_PREFIX?}_surfbar_urls` AS `sbu`
1778 LEFT JOIN
1779         `{?_MYSQL_PREFIX?}_surfbar_salts` AS `sbs`
1780 ON
1781         sbu.`url_id`=sbs.`salts_url_id`
1782 LEFT JOIN
1783         `{?_MYSQL_PREFIX?}_surfbar_locks` AS `l`
1784 ON
1785         sbu.`url_id`=l.`locks_url_id`
1786 WHERE
1787         (sbu.`url_userid` NOT IN (" . implode(',', $userids['url_userid']) . ") OR sbu.`url_userid` IS NULL) AND
1788         sbu.`url_status`='ACTIVE' AND
1789         (sbu.`url_views_allowed`=0 OR (sbu.`url_views_allowed` > 0 AND sbu.`url_views_max` > 0))
1790         " . $add . "
1791 GROUP BY
1792         sbu.`url_id`
1793 ORDER BY
1794         l.`locks_last_surfed` ASC,
1795         sbu.`url_id` ASC
1796 LIMIT %s,1",
1797                         array($randNum), __FUNCTION__, __LINE__
1798                 );
1799         } else {
1800                 // Get data from specified id number
1801                 $result = SQL_QUERY_ESC("SELECT
1802         sbu.`url_id`,
1803         sbu.`url_userid`,
1804         sbu.`url_package_id`,
1805         sbu.`url`,
1806         sbs.`salts_last_salt`,
1807         sbu.`url_views_total`,
1808         sbu.`url_views_max`,
1809         sbu.`url_views_allowed`,
1810         UNIX_TIMESTAMP(l.`locks_last_surfed`) AS `last_surfed`,
1811         sbu.`url_fixed_reload`
1812 FROM
1813         `{?_MYSQL_PREFIX?}_surfbar_urls` AS `sbu`
1814 LEFT JOIN
1815         `{?_MYSQL_PREFIX?}_surfbar_salts` AS `sbs`
1816 ON
1817         sbu.`url_id`=sbs.`salts_url_id`
1818 LEFT JOIN
1819         `{?_MYSQL_PREFIX?}_surfbar_locks` AS `l`
1820 ON
1821         sbu.`url_id`=l.`locks_url_id`
1822 WHERE
1823         (sbu.`url_userid` != %s OR sbu.`url_userid` IS NULL) AND
1824         sbu.`url_status`='ACTIVE' AND
1825         sbu.`url_id`=%s AND
1826         (sbu.`url_views_allowed` = 0 OR (sbu.`url_views_allowed` > 0 AND sbu.`url_views_max` > 0))
1827 LIMIT 1",
1828                         array(getMemberId(), bigintval($urlId)), __FUNCTION__, __LINE__
1829                 );
1830         }
1831
1832         // Is there an id number?
1833         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'lastQuery='.getConfig('db_last_query').'|numRows='.SQL_NUMROWS($result).'|Affected='.SQL_AFFECTEDROWS());
1834         if (SQL_NUMROWS($result) == 1) {
1835                 // Load/cache data
1836                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - BEFORE', FALSE);
1837                 $GLOBALS['surfbar_cache'] = merge_array($GLOBALS['surfbar_cache'], SQL_FETCHARRAY($result));
1838                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count('.count($GLOBALS['surfbar_cache']).') - AFTER', FALSE);
1839
1840                 // Determine waiting time
1841                 $GLOBALS['surfbar_cache']['waiting'] = determineSurfbarWaitingTime();
1842
1843                 // Is the last salt there?
1844                 if (is_null($GLOBALS['surfbar_cache']['salts_last_salt'])) {
1845                         // Then repair it wit the static!
1846                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_salt - FIXED!', FALSE);
1847                         $GLOBALS['surfbar_cache']['salts_last_salt'] = '';
1848                 } // END - if
1849
1850                 // Fix missing last_surfed
1851                 if ((!isset($GLOBALS['surfbar_cache']['last_surfed'])) || (is_null($GLOBALS['surfbar_cache']['last_surfed']))) {
1852                         // Fix it here
1853                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'last_surfed - FIXED!', FALSE);
1854                         $GLOBALS['surfbar_cache']['last_surfed'] = '0';
1855                 } // END - if
1856
1857                 // Get base/fixed reward and costs
1858                 $GLOBALS['surfbar_cache']['reward'] = determineSurfbarReward();
1859                 $GLOBALS['surfbar_cache']['costs']  = determineSurfbarCosts();
1860                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'BASE/STATIC - reward='.getSurfbarReward().'|costs='.getSurfbarCosts());
1861
1862                 // Only in dynamic model add the dynamic bonus!
1863                 if (getSurfbarPaymentModel() == 'DYNAMIC') {
1864                         // Calculate dynamic reward/costs and add it
1865                         $GLOBALS['surfbar_cache']['reward'] += calculateSurfbarDynamicAddValue();
1866                         $GLOBALS['surfbar_cache']['costs']  += calculateSurfbarDynamicAddValue();
1867                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'DYNAMIC+ - reward='.getSurfbarReward().'|costs='.getSurfbarCosts());
1868                 } // END - if
1869
1870                 // Now get the id
1871                 $nextId = getSurfbarId();
1872         } // END - if
1873
1874         // Free result
1875         SQL_FREERESULT($result);
1876
1877         // Return result
1878         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'urlId=' . $urlId . ',nextId=' . $nextId . ' - EXIT!');
1879         return $nextId;
1880 }
1881
1882 // Generates an URL to the given booking package
1883 function generateSurfbarPackageLink ($packageId) {
1884         // Base URL
1885         $url  = '{%url=modules.php?module=admin&amp;what=list_surfbar_packages';
1886
1887         // Is package id given?
1888         if ((!is_null($packageId)) && ($packageId > 0)) {
1889                 // Then add it
1890                 $url .= '&amp;package_id=' . bigintval($packageId);
1891         } // END - if
1892
1893         // Finish URL EL code
1894         $url .= '%}';
1895
1896         // Return it
1897         return $url;
1898 }
1899
1900 //-----------------------------------------------------------------------------
1901 // Wrapper function
1902 //-----------------------------------------------------------------------------
1903
1904 // "Getter" for surfbar_dynamic_percent
1905 function getSurfbarDynamicPercent () {
1906         // Is there cache?
1907         if (!isset($GLOBALS[__FUNCTION__])) {
1908                 // Determine it
1909                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_dynamic_percent');
1910         } // END - if
1911
1912         // Return cache
1913         return $GLOBALS[__FUNCTION__];
1914 }
1915
1916 // "Getter" for surfbar_static_reward
1917 function getSurfbarStaticReward () {
1918         // Is there cache?
1919         if (!isset($GLOBALS[__FUNCTION__])) {
1920                 // Determine it
1921                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_reward');
1922         } // END - if
1923
1924         // Return cache
1925         return $GLOBALS[__FUNCTION__];
1926 }
1927
1928 // "Getter" for surfbar_static_time
1929 function getSurfbarStaticTime () {
1930         // Is there cache?
1931         if (!isset($GLOBALS[__FUNCTION__])) {
1932                 // Determine it
1933                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_static_time');
1934         } // END - if
1935
1936         // Return cache
1937         return $GLOBALS[__FUNCTION__];
1938 }
1939
1940 // "Getter" for surfbar_max_order
1941 function getSurfbarMaxOrder () {
1942         // Is there cache?
1943         if (!isset($GLOBALS[__FUNCTION__])) {
1944                 // Determine it
1945                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_max_order');
1946         } // END - if
1947
1948         // Return cache
1949         return $GLOBALS[__FUNCTION__];
1950 }
1951
1952 // "Getter" for surfbar_payment_model
1953 function getSurfbarPaymentModel () {
1954         // Is there cache?
1955         if (!isset($GLOBALS[__FUNCTION__])) {
1956                 // Determine it
1957                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_payment_model');
1958         } // END - if
1959
1960         // Return cache
1961         return $GLOBALS[__FUNCTION__];
1962 }
1963
1964 // "Getter" for surfbar_stats_reload
1965 function getSurfbarStatsReload () {
1966         // Is there cache?
1967         if (!isset($GLOBALS[__FUNCTION__])) {
1968                 // Determine it
1969                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_stats_reload');
1970         } // END - if
1971
1972         // Return cache
1973         return $GLOBALS[__FUNCTION__];
1974 }
1975
1976 // "Getter" for surfbar_restart_time
1977 function getSurfbarRestartTime () {
1978         // Is there cache?
1979         if (!isset($GLOBALS[__FUNCTION__])) {
1980                 // Determine it
1981                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_restart_time');
1982         } // END - if
1983
1984         // Return cache
1985         return $GLOBALS[__FUNCTION__];
1986 }
1987
1988 // "Getter" for surfbar_auto_start
1989 function getSurfbarAutoStart () {
1990         // Is there cache?
1991         if (!isset($GLOBALS[__FUNCTION__])) {
1992                 // Determine it
1993                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_auto_start');
1994         } // END - if
1995
1996         // Return cache
1997         return $GLOBALS[__FUNCTION__];
1998 }
1999
2000 // Checks whether auto-start is enabled
2001 function isSurfbarAutoStartEnabled () {
2002         // Is there cache?
2003         if (!isset($GLOBALS[__FUNCTION__])) {
2004                 // Determine it
2005                 $GLOBALS[__FUNCTION__] = (getSurfbarAutoStart() == 'Y');
2006         } // END - if
2007
2008         // Return cache
2009         return $GLOBALS[__FUNCTION__];
2010 }
2011
2012 // "Getter" for surfbar_daily_counter
2013 function getSurfbarDailyCounter () {
2014         // Is there cache?
2015         if (!isset($GLOBALS[__FUNCTION__])) {
2016                 // Determine it
2017                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_daily_counter');
2018         } // END - if
2019
2020         // Return cache
2021         return $GLOBALS[__FUNCTION__];
2022 }
2023
2024 // "Getter" for surfbar_yester_counter
2025 function getSurfbarYesterCounter () {
2026         // Is there cache?
2027         if (!isset($GLOBALS[__FUNCTION__])) {
2028                 // Determine it
2029                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_yester_counter');
2030         } // END - if
2031
2032         // Return cache
2033         return $GLOBALS[__FUNCTION__];
2034 }
2035
2036 // "Getter" for surfbar_weekly_counter
2037 function getSurfbarWeeklyCounter () {
2038         // Is there cache?
2039         if (!isset($GLOBALS[__FUNCTION__])) {
2040                 // Determine it
2041                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_weekly_counter');
2042         } // END - if
2043
2044         // Return cache
2045         return $GLOBALS[__FUNCTION__];
2046 }
2047
2048 // "Getter" for surfbar_monthly_counter
2049 function getSurfbarMonthlyCounter () {
2050         // Is there cache?
2051         if (!isset($GLOBALS[__FUNCTION__])) {
2052                 // Determine it
2053                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_monthly_counter');
2054         } // END - if
2055
2056         // Return cache
2057         return $GLOBALS[__FUNCTION__];
2058 }
2059
2060 // "Getter" for surfbar_total_counter
2061 function getSurfbarTotalCounter () {
2062         // Is there cache?
2063         if (!isset($GLOBALS[__FUNCTION__])) {
2064                 // Determine it
2065                 $GLOBALS[__FUNCTION__] = getConfig('surfbar_total_counter');
2066         } // END - if
2067
2068         // Return cache
2069         return $GLOBALS[__FUNCTION__];
2070 }
2071
2072 //------------------------------------------------------------------------------
2073 //                             Template helper functions
2074 //------------------------------------------------------------------------------
2075
2076 // Template helper to generate a selection box for surfbar actions
2077 function doTemplateSurfbarActionsActionSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2078         // Init array
2079         $actionsAction = array(
2080                 0 => array('actions_action' => 'EDIT'),
2081                 1 => array('actions_action' => 'DELETE'),
2082                 2 => array('actions_action' => 'PAUSE'),
2083                 3 => array('actions_action' => 'UNPAUSE'),
2084                 4 => array('actions_action' => 'FRAMETEST'),
2085                 5 => array('actions_action' => 'RETREAT'),
2086                 6 => array('actions_action' => 'RESUBMIT'),
2087                 7 => array('actions_action' => 'BOOKNOW')
2088         );
2089
2090         // Handle it over to generateSelectionBoxFromArray()
2091         $content = generateSelectionBoxFromArray($actionsAction, 'actions_action', 'actions_action', '', '_surfbar', '', $default, '', FALSE, TRUE);
2092
2093         // Return prepared content
2094         return $content;
2095 }
2096
2097 // Template helper to generate a selection box for surfbar status
2098 function doTemplateSurfbarActionsStatusSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2099         // Init array
2100         $status = array(
2101                 0 => array('actions_status' => 'PENDING'),
2102                 1 => array('actions_status' => 'ACTIVE'),
2103                 2 => array('actions_status' => 'LOCKED'),
2104                 3 => array('actions_status' => 'STOPPED'),
2105                 4 => array('actions_status' => 'REJECTED'),
2106                 5 => array('actions_status' => 'DELETED'),
2107                 6 => array('actions_status' => 'MIGRATED'),
2108                 7 => array('actions_status' => 'DEPLETED')
2109         );
2110
2111         // Handle it over to generateSelectionBoxFromArray()
2112         $content = generateSelectionBoxFromArray($status, 'actions_status', 'actions_status', '', '_surfbar', '', $default, '', FALSE, TRUE);
2113
2114         // Return prepared content
2115         return $content;
2116 }
2117
2118 // Template helper to generate a selection box for surfbar status
2119 function doTemplateSurfbarActionsNewStatusSelectionBox ($templateName, $clear = FALSE, $default = NULL) {
2120         // Init array
2121         $status = array(
2122                 0 => array('actions_new_status' => 'PENDING'),
2123                 1 => array('actions_new_status' => 'ACTIVE'),
2124                 2 => array('actions_new_status' => 'LOCKED'),
2125                 3 => array('actions_new_status' => 'STOPPED'),
2126                 4 => array('actions_new_status' => 'REJECTED'),
2127                 5 => array('actions_new_status' => 'DELETED'),
2128                 6 => array('actions_new_status' => 'MIGRATED'),
2129                 7 => array('actions_new_status' => 'DEPLETED')
2130         );
2131
2132         // Handle it over to generateSelectionBoxFromArray()
2133         $content = generateSelectionBoxFromArray($status, 'actions_new_status', 'actions_new_status', '', '_surfbar', '', $default, '', TRUE, TRUE);
2134
2135         // Return prepared content
2136         return $content;
2137 }
2138
2139 //------------------------------------------------------------------------------
2140 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE IF THEY DON'T "WRAP"
2141 // THE $GLOBALS['surfbar_cache'] ARRAY!
2142 //------------------------------------------------------------------------------
2143
2144 // Initializes the surfbar
2145 function initSurfbar () {
2146         // Init cache array
2147         $GLOBALS['surfbar_cache'] = array();
2148 }
2149
2150 // Private getter for data elements
2151 function getSurfbarData ($element) {
2152         // Debug message
2153         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element=' . $element . ' - ENTERED!');
2154
2155         // Default is null
2156         $data = NULL;
2157
2158         // Is the entry there?
2159         if (isset($GLOBALS['surfbar_cache'][$element])) {
2160                 // Then take it
2161                 $data = $GLOBALS['surfbar_cache'][$element];
2162         } // END - if
2163
2164         // Return result
2165         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'element[' . $element . ']=[' . gettype($data) . ']' . $data . ' - EXIT!');
2166         return $data;
2167 }
2168
2169 // Getter for reward from cache
2170 function getSurfbarReward () {
2171         // Get data element and return its contents
2172         return getSurfbarData('reward');
2173 }
2174
2175 // Getter for costs from cache
2176 function getSurfbarCosts () {
2177         // Get data element and return its contents
2178         return getSurfbarData('costs');
2179 }
2180
2181 // Getter for URL from cache
2182 function getSurfbarUrl () {
2183         // Get data element and return its contents
2184         return getSurfbarData('url');
2185 }
2186
2187 // Getter for salt from cache
2188 function getSurfbarSalt () {
2189         // Get data element and return its contents
2190         return getSurfbarData('salt');
2191 }
2192
2193 // Getter for id from cache
2194 function getSurfbarId () {
2195         // Get data element and return its contents
2196         return getSurfbarData('url_id');
2197 }
2198
2199 // Getter for userid from cache
2200 function getSurfbarUserid () {
2201         // Get data element and return its contents
2202         return getSurfbarData('url_userid');
2203 }
2204
2205 // Getter for user reload locks
2206 function getSurfbarUserLocks () {
2207         // Get data element and return its contents
2208         return getSurfbarData('user_locks');
2209 }
2210
2211 // Getter for reload time
2212 function getSurfbarWaitingTime () {
2213         // Get data element and return its contents
2214         return getSurfbarData('waiting');
2215 }
2216
2217 // Getter for allowed views
2218 function getSurfbarViewsAllowed () {
2219         // Get data element and return its contents
2220         return getSurfbarData('url_views_allowed');
2221 }
2222
2223 // Getter for maximum views
2224 function getSurfbarViewsMax () {
2225         // Get data element and return its contents
2226         return getSurfbarData('url_views_max');
2227 }
2228
2229 // Getter for fixed reload
2230 function getSurfbarFixedReload () {
2231         // Get data element and return its contents
2232         return getSurfbarData('url_fixed_reload');
2233 }
2234
2235 // Getter for fixed waiting time
2236 function getSurfbarFixedWaitingTime () {
2237         // Get data element and return its contents
2238         return getSurfbarData('url_fixed_waiting');
2239 }
2240
2241 // Getter for package id
2242 function getSurfbarPackageId () {
2243         // Get data element and return its contents
2244         return getSurfbarData('url_package_id');
2245 }
2246
2247 // Getter for surf lock
2248 function getSurfbarSurfLock () {
2249         // Get data element and return its contents
2250         return getSurfbarData('surf_lock');
2251 }
2252
2253 // Getter for new status
2254 function getSurfbarNewStatus () {
2255         // Get data element and return its contents
2256         return getSurfbarData('new_status');
2257 }
2258
2259 // Getter for last salt
2260 function getSurfbarLastSalt () {
2261         // Get data element and return its contents
2262         return getSurfbarData('salts_last_salt');
2263 }
2264
2265 // [EOF]
2266 ?>