Mail templates for undelete in surfbar added
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // -----------------------------------------------------------------------------
41 //                               Admin functions
42 // -----------------------------------------------------------------------------
43 //
44 // Admin has added an URL with given user id and so on
45 function SURFBAR_ADMIN_ADD_URL ($url, $limit) {
46         // Do some pre-checks
47         if (!IS_ADMIN()) {
48                 // Not an admin
49                 return false;
50         } elseif (!VALIDATE_URL($url)) {
51                 // URL invalid
52                 return false;
53         } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
54                 // URL already found in surfbar!
55                 return false;
56         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
57                 // No more allowed!
58                 return false;
59         } elseif ("".($limit + 0)."" != "".$limit."") {
60                 // Invalid amount entered
61                 return false;
62         }
63
64         // Register the new URL
65         return SURFBAR_REGISTER_URL($url, "0", "ACTIVE", "unlock", $limit);
66 }
67 // Admin unlocked an email so we can migrate the URL
68 function SURFBAR_ADMIN_MIGRATE_URL ($url, $uid) {
69         // Do some pre-checks
70         if (!IS_ADMIN()) {
71                 // Not an admin
72                 return false;
73         } elseif (!VALIDATE_URL($url)) {
74                 // URL invalid
75                 return false;
76         } elseif (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
77                 // URL already found in surfbar!
78                 return false;
79         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($uid)) {
80                 // No more allowed!
81                 return false;
82         }
83
84         // Register the new URL
85         return SURFBAR_REGISTER_URL($url, $uid, "MIGRATED", "migrate");
86 }
87 // Admin function for unlocking URLs
88 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
89         // Is this an admin or invalid array?
90         if (!IS_ADMIN()) {
91                 // Not admin or invalid IDs array
92                 return false;
93         } elseif (!is_array($IDs)) {
94                 // No array
95                 return false;
96         } elseif (count($IDs) == 0) {
97                 // Empty array
98                 return false;
99         }
100
101         // Set to true to make AND expression valid if first URL got unlocked
102         $done = true;
103
104         // Update the status for all ids
105         foreach ($IDs as $id => $dummy) {
106                 // Test all ids through (ignores failed)
107                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "ACTIVE")));
108         } // END - if
109
110         // Return total status
111         return $done;
112 }
113 // Admin function for rejecting URLs
114 function SURFBAR_ADMIN_REJECT_URL_IDS ($IDs) {
115         // Is this an admin or invalid array?
116         if (!IS_ADMIN()) {
117                 // Not admin or invalid IDs array
118                 return false;
119         } elseif (!is_array($IDs)) {
120                 // No array
121                 return false;
122         } elseif (count($IDs) == 0) {
123                 // Empty array
124                 return false;
125         }
126
127         // Set to true to make AND expression valid if first URL got unlocked
128         $done = true;
129
130         // Update the status for all ids
131         foreach ($IDs as $id => $dummy) {
132                 // Test all ids through (ignores failed)
133                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "REJECTED")));
134         } // END - if
135
136         // Return total status
137         return $done;
138 }
139 //
140 // -----------------------------------------------------------------------------
141 //                               Member functions
142 // -----------------------------------------------------------------------------
143 //
144 // Member has added an URL
145 function SURFBAR_MEMBER_ADD_URL ($url, $limit) {
146         global $_CONFIG;
147
148         // Do some pre-checks
149         if (!IS_MEMBER()) {
150                 // Not a member
151                 return false;
152         } elseif (!VALIDATE_URL($url)) {
153                 // URL invalid
154                 return false;
155         } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
156                 // URL already found in surfbar!
157                 return false;
158         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
159                 // No more allowed!
160                 return false;
161         } elseif ("".($limit + 0)."" != "".$limit."") {
162                 // Invalid amount entered
163                 return false;
164         }
165
166         // Register the new URL
167         return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], "PENDING", "reg", $limit);
168 }
169 // Create list of actions depending on status for the user
170 function SURFBAR_MEMBER_ACTIONS ($urlId, $status) {
171         // Load all actions in an array for given status
172         $actionArray = SURFBAR_GET_ACTION_ARRAY($status);
173
174         // Init HTML code
175         $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\">
176 <tr>\n";
177
178         // Calculate width
179         $width = round(100 / count($actionArray));
180
181         // "Walk" through all actions and create forms
182         foreach ($actionArray as $actionId=>$action) {
183                 // Add form for this action
184                 $OUT .= sprintf("       <td align=\"center\" width=\"%d%%\">
185                 <form action=\"".URL."/modules.php?module=login&amp;what=surfbar_list\" method=\"post\" style=\"padding-bottom:0px\">
186                         <input type=\"hidden\" name=\"id\" value=\"%s\" />
187                         <input type=\"hidden\" name=\"action\" value=\"%s\" />
188                         <input type=\"submit\" class=\"member_submit\" name=\"ok\" title=\"{--MEMBER_SURFBAR_ACTION_%s_TITLE--}\" value=\"{--MEMBER_SURFBAR_ACTION_%s_SUBMIT--}\" />
189                 </form>
190         </td>\n",
191                         $width,
192                         bigintval($urlId),
193                         strtolower($action),
194                         strtoupper($action),
195                         strtoupper($action)
196                 );
197         } // END - foreach
198
199         // Close table
200         $OUT .= "</tr>
201 </table>\n";
202
203         // Return code
204         return $OUT;
205 }
206 // Do the member form request
207 function SURFBAR_MEMBER_DO_FORM ($formData, $URLs) {
208         global $SURFBAR_CACHE;
209
210         // By default no action is performed
211         $performed = false;
212
213         // Is this a member?
214         if (!IS_MEMBER()) {
215                 // No member!
216                 return false;
217         } elseif ((!isset($formData['id'])) || (!isset($formData['action']))) {
218                 // Important form elements are missing!
219                 return false;
220         } elseif (!isset($URLs[$formData['id']])) {
221                 // ID not found in cache
222                 return false;
223         } elseif (!SURFBAR_VALIDATE_MEMBER_ACTION_STATUS($formData['action'], $URLs[$formData['id']]['status'])) {
224                 // Action not allowed for current URL status
225                 return false;
226         }
227
228         // Create the function name for selected action
229         $functionName = sprintf("SURFBAR_MEMBER_%s_ACTION", strtoupper(SQL_ESCAPE($formData['action'])));
230
231         // Is the function there?
232         if (function_exists($functionName)) {
233                 // Add new status
234                 $URLs[$formData['id']]['new_status'] = $SURFBAR_CACHE['new_status'];
235
236                 // Extract URL data for call-back
237                 $urlData = array($URLs[$formData['id']]);
238
239                 // Action found so execute it
240                 $performed = call_user_func_array($functionName, $urlData);
241         } else {
242                 // Log invalid request
243                 DEBUG_LOG(__FUNCTION__, __LINE__, " action={$formData['action']},id={$formData['id']},function={$functionName}");
244                 ADD_FATAL(sprintf("Invalid member action! action=%s,id=%s,function=%s", $formData['action'], $formData['id'], $functionName));
245         }
246
247         // Return status
248         return $performed;
249 }
250 // Validate if the requested action can be performed on current URL status
251 function SURFBAR_VALIDATE_MEMBER_ACTION_STATUS ($action, $status) {
252         global $SURFBAR_CACHE;
253
254         // Search for the requested action/status combination in database
255         $result = SQL_QUERY_ESC("SELECT new_status FROM "._MYSQL_PREFIX."_surfbar_actions WHERE action='%s' AND status='%s' LIMIT 1",
256                 array($action, $status), __FILE__, __LINE__);
257
258         // Is the entry there?
259         $isValid = (SQL_NUMROWS($result) == 1);
260
261         // Fetch the new status if found
262         if ($isValid) {
263                 // Load new status
264                 list($SURFBAR_CACHE['new_status']) = SQL_FETCHROW($result);
265         } // END - if
266
267         // Free result
268         SQL_FREERESULT($result);
269
270         // Return status
271         return $isValid;
272 }
273 //
274 // -----------------------------------------------------------------------------
275 //                               Member actions
276 // -----------------------------------------------------------------------------
277 //
278 // Retreat a booked URL
279 function SURFBAR_MEMBER_RETREAT_ACTION ($urlData) {
280         // Create the data array for next function call
281         $data = array(
282                 $urlData['id'] => $urlData
283         );
284
285         // Simply change the status here
286         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
287 }
288 // Book an URL now (from migration)
289 function SURFBAR_MEMBER_BOOKNOW_ACTION ($urlData) {
290         // Create the data array for next function call
291         $data = array(
292                 $urlData['id'] => $urlData
293         );
294
295         // Simply change the status here
296         return SURFBAR_CHANGE_STATUS ($urlData['id'], $urlData['status'], $urlData['new_status'], $data);
297 }
298 // Show edit form or do the changes
299 function SURFBAR_MEMBER_EDIT_ACTION ($urlData) {
300         // Is the "execute" flag there?
301         if (isset($urlData['execute'])) {
302                 // Execute the changes
303                 return SURFBAR_MEMBER_EXECUTE_ACTION("edit", $urlData);
304         } // END - if
305
306         // Display form
307         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("edit", $urlData);
308 }
309 // Show delete form or do the changes
310 function SURFBAR_MEMBER_DELETE_ACTION ($urlData) {
311         // Is the "execute" flag there?
312         if (isset($urlData['execute'])) {
313                 // Execute the changes
314                 return SURFBAR_MEMBER_EXECUTE_ACTION("del", $urlData);
315         } // END - if
316
317         // Display form
318         return SURFBAR_MEMBER_DISPLAY_ACTION_FORM("del", $urlData);
319 }
320 // Display selected "action form"
321 function SURFBAR_MEMBER_DISPLAY_ACTION_FORM ($action, $urlData) {
322         // Translate some data
323         $urlData['registered']  = MAKE_DATETIME($urlData['registered'], "2");
324         $urlData['views_total'] = TRANSLATE_COMMA($urlData['views_total']);
325
326         // Load the form and display it
327         LOAD_TEMPLATE(sprintf("member_surfbar_%s_action_form", $action), false, $urlData);
328
329         // All fine by default ... ;-)
330         return true;
331 }
332 //
333 // -----------------------------------------------------------------------------
334 //                           Self-maintenance functions
335 // -----------------------------------------------------------------------------
336 //
337 // Main function
338 function SURFBAR_HANDLE_SELF_MAINTENANCE () {
339         // Handle URLs which limit has depleted so we can stop them
340         SURFBAR_HANDLE_DEPLETED_VIEWS();
341
342         // Handle low-points amounts
343         SURFBAR_HANDLE_LOW_POINTS();
344 }
345 // Handle URLs which limit has depleted
346 function SURFBAR_HANDLE_DEPLETED_VIEWS () {
347         // Get all URLs
348         $urlArray = SURFBAR_GET_URL_DATA("0", "views_max", "id", "ASC", "id", " AND views_allowed>0 AND status='ACTIVE'");
349
350         // Do we have some entries?
351         if (count($urlArray) > 0) {
352                 // Then handle all!
353                 foreach ($urlArray as $id => $urlData) {
354                         // Backup data
355                         $data = $urlData;
356
357                         // Rewrite array for next call
358                         $urlData[$id] = $data;
359
360                         // Handle the status
361                         SURFBAR_CHANGE_STATUS($id, "ACTIVE", "DEPLETED", $urlData);
362                 } // END - foreach
363         } // END - if
364 }
365 // Alert users which have URLs booked and are low on points amount
366 function SURFBAR_HANDLE_LOW_POINTS () {
367         global $_CONFIG;
368
369         // Get all userids
370         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS($_CONFIG['surfbar_warn_low_points']);
371
372         // "Walk" through all URLs
373         foreach ($UIDs['uid'] as $uid => $dummy) {
374                 // Is the last notification far enougth away to notify again?
375                 if ((time() - $UIDs['notified'][$uid]) >= $_CONFIG['surfbar_low_interval']) {
376                         // Prepare content
377                         $content = array(
378                                 'uid'      => $uid,
379                                 'low'      => TRANSLATE_COMMA($_CONFIG['surfbar_warn_low_points']),
380                                 'points'   => TRANSLATE_COMMA($UIDs['points'][$uid]),
381                                 'notified' => MAKE_DATETIME($UIDs['notified'][$uid]),
382                                 'interval' => CREATE_FANCY_TIME($_CONFIG['surfbar_low_interval'])
383                         );
384
385                         // Notify this user
386                         SURFBAR_NOTIFY_USER("low_points", $content);
387
388                         // Update last notified
389                         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_data SET surfbar_low_notified=NOW() WHERE userid=%s LIMIT 1",
390                                 array($uid), __FILE__, __LINE__);
391                 } // END - if
392         } // END - foreach
393 }
394 //
395 // -----------------------------------------------------------------------------
396 //                               Generic functions
397 // -----------------------------------------------------------------------------
398 //
399 // Looks up by an URL
400 function SURFBAR_LOOKUP_BY_URL ($url, $uid) {
401         // Now lookup that given URL by itself
402         $urlArray = SURFBAR_GET_URL_DATA($url, "url", "id", "ASC", "id", sprintf(" AND userid=%s", bigintval($uid)));
403
404         // Was it found?
405         return (count($urlArray) > 0);
406 }
407 // Load URL data by given search term and column
408 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id", $add="") {
409         global $lastUrlData;
410
411         // By default nothing is found
412         $lastUrlData = array();
413
414         // Is the column an id number?
415         if (($column == "id") || ($column == "userid")) {
416                 // Extra secure input
417                 $searchTerm = bigintval($searchTerm);
418         } // END - if
419
420         // If the column is "id" there can be only one entry
421         $limit = "";
422         if ($column == "id") {
423                 $limit = "LIMIT 1";
424         } // END - if
425
426         // Look up the record
427         $result = SQL_QUERY_ESC("SELECT id, userid, url, views_total, status, registered, last_locked, lock_reason, views_max, views_allowed
428 FROM "._MYSQL_PREFIX."_surfbar_urls
429 WHERE %s='%s'".$add."
430 ORDER BY %s %s
431 %s",
432                 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
433
434         // Is there at least one record?
435         if (SQL_NUMROWS($result) > 0) {
436                 // Then load all!
437                 while ($dataRow = SQL_FETCHARRAY($result)) {
438                         // Shall we group these results?
439                         if ($group == "id") {
440                                 // Add the row by id as index
441                                 $lastUrlData[$dataRow['id']] = $dataRow;
442                         } else {
443                                 // Group entries
444                                 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
445                         }
446                 } // END - while
447         } // END - if
448
449         // Free the result
450         SQL_FREERESULT($result);
451
452         // Return the result
453         return $lastUrlData;
454 }
455 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
456 function SURFBAR_REGISTER_URL ($url, $uid, $status="PENDING", $addMode="reg", $limit=0) {
457         global $_CONFIG;
458
459         // Make sure by the user registered URLs are always pending
460         if ($addMode == "reg") $status = "PENDING";
461
462         // Prepare content
463         $content = array(
464                 'url'         => $url,
465                 'frametester' => FRAMETESTER($url),
466                 'uid'         => $uid,
467                 'status'      => $status,
468                 'limit'       => $limit
469         );
470
471         // Insert the URL into database
472         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
473
474         // Is this ID valid?
475         if ($content['insert_id'] == 0) {
476                 // INSERT did not insert any data!
477                 return false;
478         } // END - if
479
480         // Translate status and limit
481         $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
482         $content['limit'] = SURFBAR_TRANSLATE_LIMIT($content['limit']);
483
484         // If in reg-mode we notify admin
485         if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
486                 // Notify admin even when he as unlocked an email
487                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
488         } // END - if
489
490         // Send mail to user
491         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
492
493         // Return the insert id
494         return $content['insert_id'];
495 }
496 // Inserts an url by given data array and return the insert id
497 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
498         // Get userid
499         $uid = bigintval($urlData['uid']);
500
501         // Is the id set?
502         if (empty($uid)) $uid = 0;
503
504         // Just run the insert query for now
505         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid,url,status,views_max,views_allowed) VALUES (%s,'%s','%s','%s','%s')",
506                 array(
507                         $uid,
508                         $urlData['url'],
509                         $urlData['status'],
510                         $urlData['limit'],
511                         $urlData['limit']
512                 ), __FILE__, __LINE__
513         );
514
515         // Return insert id
516         return SQL_INSERTID();
517 }
518 // Notify admin(s) with a selected message and content
519 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
520         // Prepare template name
521         $templateName = sprintf("admin_surfbar_%s", $messageType);
522
523         // Set default subject if following eval() wents wrong
524         $subject = ADMIN_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
525
526         // Prepare subject
527         $subject = constant(sprintf("ADMIN_SURFBAR_NOTIFY_%s_SUBJECT",
528                 strtoupper($messageType)
529         ));
530
531         // Send the notification out
532         return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
533 }
534 // Notify the user about the performed action
535 function SURFBAR_NOTIFY_USER ($messageType, $content) {
536         // Skip notification if userid is zero
537         if ($content['uid'] == 0) {
538                 return false;
539         } // END - if
540
541         // Prepare template name
542         $templateName = sprintf("member_surfbar_%s", $messageType);
543
544         // Set default subject if following eval() wents wrong
545         $subject = MEMBER_SURFBAR_NOTIFY_DEFAULT_SUBJECT;
546
547         // Prepare subject
548         $subject = constant(sprintf("MEMBER_SURFBAR_NOTIFY_%s_SUBJECT",
549                 strtoupper($messageType)
550         ));
551
552         // Load template
553         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content, $content['uid']);
554
555         // Send the email
556         return SEND_EMAIL($content['uid'], $subject, $mailText);
557 }
558 // Translates the limit
559 function SURFBAR_TRANSLATE_LIMIT ($limit) {
560         // Is this zero?
561         if ($limit == 0) {
562                 // Unlimited!
563                 $return = MEMBER_SURFBAR_UNLIMITED_VIEWS;
564         } else {
565                 // Translate comma
566                 $return = TRANSLATE_COMMA($limit);
567         }
568
569         // Return value
570         return $return;
571 }
572 // Translate the URL status
573 function SURFBAR_TRANSLATE_STATUS ($status) {
574         // Create constant name
575         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
576
577         // Set default translated status
578         $statusTranslated = "!".$constantName."!";
579
580         // Is the constant there?
581         if (defined($constantName)) {
582                 // Then get it's value
583                 $statusTranslated = constant($constantName);
584         } // END - if
585
586         // Return result
587         return $statusTranslated;
588 }
589 // Determine reward
590 function SURFBAR_DETERMINE_REWARD ($onlyMin=false) {
591         global $_CONFIG;
592
593         // Static values are default
594         $reward = $_CONFIG['surfbar_static_reward'];
595
596         // Do we have static or dynamic?
597         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
598                 // "Calculate" dynamic reward
599                 if ($onlyMin) {
600                         $reward += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
601                 } else {
602                         $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
603                 }
604         } // END - if
605
606         // Return reward
607         return $reward;
608 }
609 // Determine costs
610 function SURFBAR_DETERMINE_COSTS ($onlyMin=false) {
611         global $_CONFIG;
612
613         // Static costs is default
614         $costs  = $_CONFIG['surfbar_static_costs'];
615
616         // Do we have static or dynamic?
617         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
618                 // "Calculate" dynamic costs
619                 if ($onlyMin) {
620                         $costs += SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
621                 } else {
622                         $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
623                 }
624         } // END - if
625
626         // Return costs
627         return $costs;
628 }
629 // "Calculate" dynamic add
630 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
631         // Get min/max values
632         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
633         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
634
635         // "Calculate" dynamic part and return it
636         return mt_rand($min, $max);
637 }
638 // Determine right template name
639 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
640         // Default is the frameset
641         $templateName = "surfbar_frameset";
642
643         // Any frame set? ;-)
644         if (isset($_GET['frame'])) {
645                 // Use the frame as a template name part... ;-)
646                 $templateName = sprintf("surfbar_frame_%s",
647                         SQL_ESCAPE($_GET['frame'])
648                 );
649         } // END - if
650
651         // Return result
652         return $templateName;
653 }
654 // Check if the "reload lock" of the current user is full, call this function
655 // before you call SURFBAR_CHECK_RELOAD_LOCK().
656 function SURFBAR_CHECK_RELOAD_FULL() {
657         global $SURFBAR_CACHE, $_CONFIG;
658
659         // Default is full!
660         $isFull = true;
661
662         // Cache static reload lock
663         $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
664         //DEBUG_LOG(__FUNCTION__, __LINE__, "Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."", false);
665
666         // Do we have dynamic model?
667         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
668                 // "Calculate" dynamic lock
669                 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
670         } // END - if
671
672         // Ask the database
673         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
674 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
675 LIMIT 1",
676                 array($GLOBALS['userid']), __FILE__, __LINE__
677         );
678
679         // Fetch row
680         list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
681
682         // Is it null?
683         if (is_null($SURFBAR_CACHE['user_locks'])) {
684                 // Then fix it to zero!
685                 $SURFBAR_CACHE['user_locks'] = 0;
686         } // END - if
687
688         // Free result
689         SQL_FREERESULT($result);
690
691         // Get total URLs
692         $total = SURFBAR_GET_TOTAL_URLS();
693
694         // Do we have some URLs in lock? Admins can always surf on own URLs!
695         //DEBUG_LOG(__FUNCTION__, __LINE__, "userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}", false);
696         $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
697
698         // Return result
699         return $isFull;
700 }
701 // Get total amount of URLs of given status for current user or of ACTIVE URLs by default
702 function SURFBAR_GET_TOTAL_URLS ($status="ACTIVE", $excludeUserId=0) {
703         // Determine depleted user account
704         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
705
706         // Is the exlude userid set?
707         if ($excludeUserId > 0) {
708                 // Then add it
709                 $UIDs['uid'][$excludeUserId] = $excludeUserId;
710         } // END - if
711
712         // Get amount from database
713         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
714 FROM "._MYSQL_PREFIX."_surfbar_urls
715 WHERE userid NOT IN (".implode(",", $UIDs['uid']).") AND status='%s'",
716                 array($status), __FILE__, __LINE__
717         );
718
719         // Fetch row
720         list($cnt) = SQL_FETCHROW($result);
721
722         // Free result
723         SQL_FREERESULT($result);
724
725         // Return result
726         return $cnt;
727 }
728 // Check wether the user is allowed to book more URLs
729 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
730         global $_CONFIG;
731
732         // Is this admin and userid is zero or does the user has some URLs left to book?
733         return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
734 }
735 // Get total amount of URLs of given status for current user
736 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
737         global $_CONFIG;
738
739         // Is the user 0 and user is logged in?
740         if (($uid == 0) && (IS_MEMBER())) {
741                 // Then use this userid
742                 $uid = $GLOBALS['userid'];
743         } elseif ($uid == 0) {
744                 // Error!
745                 return ($_CONFIG['surfbar_max_order'] + 1);
746         }
747
748         // Default is all URLs
749         $ADD = "";
750
751         // Is the status set?
752         if (is_array($status)) {
753                 // Only URLs with these status
754                 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
755         } elseif (!empty($status)) {
756                 // Only URLs with this status
757                 $ADD = sprintf(" AND status='%s'", $status);
758         } elseif (is_array($exclude)) {
759                 // Exclude URLs with these status
760                 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
761         } elseif (!empty($exclude)) {
762                 // Exclude URLs with this status
763                 $ADD = sprintf(" AND status != '%s'", $exclude);
764         }
765
766         // Get amount from database
767         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
768 FROM "._MYSQL_PREFIX."_surfbar_urls
769 WHERE userid=%s".$ADD."
770 LIMIT %s",
771                 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
772         );
773
774         // Fetch row
775         list($cnt) = SQL_FETCHROW($result);
776
777         // Free result
778         SQL_FREERESULT($result);
779
780         // Return result
781         return $cnt;
782 }
783 // Generate a validation code for the given id number
784 function SURFBAR_GENERATE_VALIDATION_CODE ($urlId, $salt="") {
785         global $_CONFIG, $SURFBAR_CACHE;
786
787         // @TODO Invalid salt should be refused
788         $SURFBAR_CACHE['salt'] = "INVALID";
789
790         // Get code length from config
791         $length = $_CONFIG['code_length'];
792
793         // Fix length to 10
794         if ($length == 0) $length = 10;
795
796         // Generate a code until the length matches
797         $valCode = "";
798         while (strlen($valCode) != $length) {
799                 // Is the salt set?
800                 if (empty($salt)) {
801                         // Generate random hashed string
802                         $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
803                         //DEBUG_LOG(__FUNCTION__, __LINE__, "newSalt=".SURFBAR_GET_SALT()."", false);
804                 } else {
805                         // Use this as salt!
806                         $SURFBAR_CACHE['salt'] = $salt;
807                         //DEBUG_LOG(__FUNCTION__, __LINE__, "oldSalt=".SURFBAR_GET_SALT()."", false);
808                 }
809
810                 // ... and now the validation code
811                 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$urlId), $GLOBALS['userid']);
812                 //DEBUG_LOG(__FUNCTION__, __LINE__, "valCode={$valCode}", false);
813         } // END - while
814
815         // Hash it with md5() and salt it with the random string
816         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
817
818         // Finally encrypt it PGP-like and return it
819         $valHashedCode = generatePassString($hashedCode);
820
821         // Return hashed value
822         //DEBUG_LOG(__FUNCTION__, __LINE__, "finalValCode={$valHashedCode}", false);
823         return $valHashedCode;
824 }
825 // Check validation code
826 function SURFBAR_CHECK_VALIDATION_CODE ($urlId, $check, $salt) {
827         global $SURFBAR_CACHE;
828
829         // Secure id number
830         $urlId = bigintval($urlId);
831
832         // Now generate the code again
833         $code = SURFBAR_GENERATE_VALIDATION_CODE($urlId, $salt);
834
835         // Return result of checking hashes and salts
836         //DEBUG_LOG(__FUNCTION__, __LINE__, "---".$code."|".$check."---", false);
837         //DEBUG_LOG(__FUNCTION__, __LINE__, "+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++", false);
838         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
839 }
840 // Lockdown the userid/id combination (reload lock)
841 function SURFBAR_LOCKDOWN_ID ($urlId) {
842         //* DEBUG: */ print "LOCK!");
843         ///* DEBUG: */ return;
844         // Just add it to the database
845         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES (%s, %s)",
846                 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__);
847
848         // Remove the salt from database
849         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
850                 array(bigintval($urlId), $GLOBALS['userid']), __FILE__, __LINE__);
851 }
852 // Pay points to the user and remove it from the sender
853 function SURFBAR_PAY_POINTS ($urlId) {
854         // Remove it from the URL owner
855         //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."", false);
856         if (SURFBAR_GET_USERID() > 0) {
857                 SUB_POINTS("surfbar", SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
858         } // END - if
859
860         // Book it to the user
861         //DEBUG_LOG(__FUNCTION__, __LINE__, "uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."", false);
862         ADD_POINTS_REFSYSTEM("surfbar", $GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
863 }
864 // Updates the statistics of current URL/userid
865 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
866         global $_CONFIG;
867
868         // Init add
869         $ADD = "";
870
871         // Get allowed views
872         $allowed = SURFBAR_GET_ALLOWED_VIEWS();
873
874         // Do we have a limit?
875         if ($allowed > 0) {
876                 // Then count views_max down!
877                 $ADD .= ",views_max=views_max-1";
878         } // END - if
879
880         // Update URL stats
881         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1".$ADD." WHERE id=%s LIMIT 1",
882                 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
883
884         // Update the stats entry
885         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
886                 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
887
888         // Was that update okay?
889         if (SQL_AFFECTEDROWS() < 1) {
890                 // No, then insert entry
891                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES (%s,%s,1)",
892                         array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
893         } // END - if
894
895         // Update total/daily/weekly/monthly counter
896         $_CONFIG['surfbar_total_counter']++;
897         $_CONFIG['surfbar_daily_counter']++;
898         $_CONFIG['surfbar_weekly_counter']++;
899         $_CONFIG['surfbar_monthly_counter']++;
900
901         // Update config as well
902         UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
903 }
904 // Update the salt for validation and statistics
905 function SURFBAR_UPDATE_SALT_STATS () {
906         // Update statistics record
907         SURFBAR_UPDATE_INSERT_STATS_RECORD();
908
909         // Simply store the salt from cache away in database...
910         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
911                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
912
913         // Debug message
914         //DEBUG_LOG(__FUNCTION__, __LINE__, "salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."", false);
915
916         // Was that okay?
917         if (SQL_AFFECTEDROWS() < 1) {
918                 // Insert missing entry!
919                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES (%s, %s, '%s')",
920                         array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
921         } // END - if
922
923         // Debug message
924         //DEBUG_LOG(__FUNCTION__, __LINE__, "affectedRows=".SQL_AFFECTEDROWS()."", false);
925
926         // Return if the update was okay
927         return (SQL_AFFECTEDROWS() == 1);
928 }
929 // Check if the reload lock is active for given id
930 function SURFBAR_CHECK_RELOAD_LOCK ($urlId) {
931         //DEBUG_LOG(__FUNCTION__, __LINE__, "id={$urlId}", false);
932         // Ask the database
933         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
934 FROM "._MYSQL_PREFIX."_surfbar_locks
935 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
936 ORDER BY last_surfed ASC
937 LIMIT 1",
938                 array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
939         );
940
941         // Fetch counter
942         list($cnt) = SQL_FETCHROW($result);
943
944         // Free result
945         SQL_FREERESULT($result);
946
947         // Return check
948         //DEBUG_LOG(__FUNCTION__, __LINE__, "cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."", false);
949         return ($cnt == 1);
950 }
951 // Determine which user hash no more points left
952 function SURFBAR_DETERMINE_DEPLETED_USERIDS ($limit=0) {
953         // Init array
954         $UIDs = array(
955                 'uid'      => array(),
956                 'points'   => array(),
957                 'notified' => array(),
958         );
959
960         // Do we have a current user id?
961         if ((IS_MEMBER()) && ($limit == 0)) {
962                 // Then add this as well
963                 $UIDs['uid'][$GLOBALS['userid']]      = $GLOBALS['userid'];
964                 $UIDs['points'][$GLOBALS['userid']]   = GET_TOTAL_DATA($GLOBALS['userid'], "user_points", "points") - GET_TOTAL_DATA($GLOBALS['userid'], "user_data", "used_points");
965                 $UIDs['notified'][$GLOBALS['userid']] = 0;
966
967                 // Get all userid except logged in one
968                 $result = SQL_QUERY_ESC("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
969 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
970 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
971 ON u.userid=d.userid
972 WHERE u.userid NOT IN (%s,0) AND u.status='ACTIVE'
973 GROUP BY u.userid
974 ORDER BY u.userid ASC",
975                         array($GLOBALS['userid']), __FILE__, __LINE__);
976         } else {
977                 // Get all userid
978                 $result = SQL_QUERY("SELECT u.userid, UNIX_TIMESTAMP(d.surfbar_low_notified) AS notified
979 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
980 INNER JOIN "._MYSQL_PREFIX."_user_data AS d
981 ON u.userid=d.userid
982 WHERE u.status='ACTIVE'
983 GROUP BY u.userid
984 ORDER BY u.userid ASC", __FILE__, __LINE__);
985         }
986
987         // Load all userid
988         while (list($uid, $notified) = SQL_FETCHROW($result)) {
989                 // Get total points
990                 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
991                 //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid},points={$points}", false);
992
993                 // Shall we add this to ignore?
994                 if ($points <= $limit) {
995                         // Ignore this one!
996                         //DEBUG_LOG(__FUNCTION__, __LINE__, "uid={$uid} has depleted points amount!", false);
997                         $UIDs['uid'][$uid] = $uid;
998                         $UIDs['points'][$uid] = $points;
999                         $UIDs['notified'][$uid] = $notified;
1000                 } // END - if
1001         } // END - while
1002
1003         // Free result
1004         SQL_FREERESULT($result);
1005
1006         // Debug message
1007         //DEBUG_LOG(__FUNCTION__, __LINE__, "UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")", false);
1008
1009         // Return result
1010         return $UIDs;
1011 }
1012 // Determine how many users are Online in surfbar
1013 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
1014         global $_CONFIG;
1015
1016         // Count all users in surfbar modue and return the value
1017         $result = SQL_QUERY_ESC("SELECT id
1018 FROM "._MYSQL_PREFIX."_surfbar_stats
1019 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
1020 GROUP BY userid",
1021                 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
1022
1023         // Fetch count
1024         $cnt = SQL_NUMROWS($result);
1025
1026         // Free result
1027         SQL_FREERESULT($result);
1028
1029         // Return result
1030         return $cnt;
1031 }
1032 // Determine waiting time for one URL 
1033 function SURFBAR_DETERMINE_WAIT_TIME () {
1034         global $_CONFIG;
1035
1036         // Static time is default
1037         $time = $_CONFIG['surfbar_static_time'];
1038
1039         // Which payment model do we have?
1040         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1041                 // "Calculate" dynamic time
1042                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
1043         } // END - if
1044
1045         // Return value
1046         return $time;
1047 }
1048 // Changes the status of an URL from given to other
1049 function SURFBAR_CHANGE_STATUS ($urlId, $prevStatus, $newStatus, $data=array()) {
1050         global $_CONFIG;
1051
1052         // Get URL data for status comparison if missing
1053         if ((!is_array($data)) || (count($data) == 0)) {
1054                 // Fetch missing URL data
1055                 $data = SURFBAR_GET_URL_DATA($urlId);
1056         } // END - if
1057
1058         // Is the status like prevStatus is saying?
1059         if ($data[$urlId]['status'] != $prevStatus) {
1060                 // No, then abort here
1061                 return false;
1062         } // END - if
1063
1064
1065         // Update the status now
1066         // ---------- Comment out for debugging/developing member actions! ---------
1067         //SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
1068         //      array($newStatus, bigintval($urlId)), __FILE__, __LINE__);
1069         // ---------- Comment out for debugging/developing member actions! ---------
1070
1071         // Was that fine?
1072         if (SQL_AFFECTEDROWS() != 1) {
1073                 // No, something went wrong
1074                 return false;
1075         } // END - if
1076
1077         // Prepare content for notification routines
1078         $data[$urlId]['uid']         = $data[$urlId]['userid'];
1079         $data[$urlId]['frametester'] = FRAMETESTER($data[$urlId]['url']);
1080         $data[$urlId]['reward']      = TRANSLATE_COMMA($_CONFIG['surfbar_static_reward']);
1081         $data[$urlId]['costs']       = TRANSLATE_COMMA($_CONFIG['surfbar_static_costs']);
1082         $data[$urlId]['status']      = SURFBAR_TRANSLATE_STATUS($newStatus);
1083         $data[$urlId]['registered']  = MAKE_DATETIME($data[$urlId]['registered'], "2");
1084         $newStatus = strtolower($newStatus);
1085
1086         // Send admin notification
1087         SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$urlId]);
1088
1089         // Send user notification
1090         SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$urlId]);
1091
1092         // All done!
1093         return true;
1094 }
1095 // Calculate minimum value for dynamic payment model
1096 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
1097         global $_CONFIG;
1098
1099         // Addon is zero by default
1100         $addon = 0;
1101
1102         // Percentage part
1103         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1104
1105         // Get total users
1106         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1107
1108         // Get online users
1109         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1110
1111         // Calculate addon
1112         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
1113
1114         // Get total URLs
1115         $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1116
1117         // Get user's total URLs
1118         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "ACTIVE");
1119
1120         // Calculate addon
1121         if ($totalUrls > 0) {
1122                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
1123         } else {
1124                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
1125         }
1126
1127         // Return addon
1128         return $addon;
1129 }
1130 // Calculate maximum value for dynamic payment model
1131 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
1132         global $_CONFIG;
1133
1134         // Addon is zero by default
1135         $addon = 0;
1136
1137         // Maximum value
1138         $max = log(2);
1139
1140         // Percentage part
1141         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
1142
1143         // Get total users
1144         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
1145
1146         // Calculate addon
1147         $addon += abs($max * $percent * $totalUsers);
1148
1149         // Get total URLs
1150         $totalUrls = SURFBAR_GET_TOTAL_URLS("ACTIVE", "0");
1151
1152         // Calculate addon
1153         $addon += abs($max * $percent * $totalUrls);
1154
1155         // Return addon
1156         return $addon;
1157 }
1158 // Calculate dynamic lock
1159 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
1160         global $_CONFIG;
1161
1162         // Default lock is 30 seconds
1163         $addon = 30;
1164
1165         // Get online users
1166         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
1167
1168         // Calculate lock
1169         $addon = abs(log($onlineUsers / $addon + 1));
1170
1171         // Return value
1172         return $addon;
1173 }
1174 // "Getter" for lock ids array
1175 function SURFBAR_GET_LOCK_IDS () {
1176         // Prepare some arrays
1177         $IDs = array();
1178         $USE = array();
1179         $ignored = array();
1180
1181         // Get all id from locks within the timestamp
1182         $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
1183 FROM
1184         "._MYSQL_PREFIX."_surfbar_locks
1185 WHERE
1186         userid=%s
1187 ORDER BY
1188         id ASC", array($GLOBALS['userid']),
1189                 __FILE__, __LINE__);
1190
1191         // Load all entries
1192         while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
1193                 // Debug message
1194                 //DEBUG_LOG(__FUNCTION__, __LINE__, "next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."", false);
1195
1196                 // Skip entries that are too old
1197                 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
1198                         // Debug message
1199                         //DEBUG_LOG(__FUNCTION__, __LINE__, "okay - lid={$lid},url={$url},last={$last}", false);
1200
1201                         // Add only if missing or bigger
1202                         if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
1203                                 // Debug message
1204                                 //DEBUG_LOG(__FUNCTION__, __LINE__, "ADD - lid={$lid},url={$url},last={$last}", false);
1205
1206                                 // Add this ID
1207                                 $IDs[$url] = $last;
1208                                 $USE[$url] = $lid;
1209                         } // END - if
1210                 } else {
1211                         // Debug message
1212                         //DEBUG_LOG(__FUNCTION__, __LINE__, "ignore - lid={$lid},url={$url},last={$last}", false);
1213
1214                         // Ignore these old entries!
1215                         $ignored[] = $url;
1216                         unset($IDs[$url]);
1217                         unset($USE[$url]);
1218                 }
1219         } // END - while
1220
1221         // Free result
1222         SQL_FREERESULT($result);
1223
1224         // Return array
1225         return $USE;
1226 }
1227 // "Getter" for maximum random number
1228 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
1229         global $_CONFIG;
1230         // Count max availabe entries
1231         $result = SQL_QUERY("SELECT sbu.id AS cnt
1232 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1233 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1234 ON sbu.id=sbs.url_id
1235 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1236 ON sbu.id=l.url_id
1237 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0)) AND sbu.status='ACTIVE'".$ADD."
1238 GROUP BY sbu.id", __FILE__, __LINE__);
1239
1240         // Log last query
1241         //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1242
1243         // Fetch max rand
1244         $maxRand = SQL_NUMROWS($result);
1245
1246         // Free result
1247         SQL_FREERESULT($result);
1248
1249         // Return value
1250         return $maxRand;
1251 }
1252 // Load all URLs of the current user and return it as an array
1253 function SURFBAR_GET_USER_URLS () {
1254         // Init array
1255         $URLs = array();
1256
1257         // Begin the query
1258         $result = SQL_QUERY_ESC("SELECT u.id, u.userid, u.url, u.views_total, u.status, UNIX_TIMESTAMP(u.registered) AS registered, UNIX_TIMESTAMP(u.last_locked) AS last_locked, u.lock_reason AS lock_reason
1259 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
1260 WHERE u.userid=%s AND u.status != 'DELETED'
1261 ORDER BY u.id ASC",
1262                 array($GLOBALS['userid']), __FILE__, __LINE__);
1263
1264         // Are there entries?
1265         if (SQL_NUMROWS($result) > 0) {
1266                 // Load all rows
1267                 while ($row = SQL_FETCHARRAY($result)) {
1268                         // Add the row
1269                         $URLs[$row['id']] = $row;
1270                 } // END - while
1271         } // END - if
1272
1273         // Free result
1274         SQL_FREERESULT($result);
1275
1276         // Return the array
1277         return $URLs;
1278 }
1279 // "Getter" for member action array for given status
1280 function SURFBAR_GET_ACTION_ARRAY ($status) {
1281         // Init array
1282         $returnArray = array();
1283
1284         // Get all assigned actions
1285         $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_surfbar_actions WHERE status='%s' ORDER BY id ASC",
1286                 array($status), __FILE__, __LINE__);
1287
1288         // Some entries there?
1289         if (SQL_NUMROWS($result) > 0) {
1290                 // Load all actions
1291                 while (list($action) = SQL_FETCHROW($result)) {
1292                         $returnArray[] = $action;
1293                 } // END - if
1294         } // END - if
1295
1296         // Free result
1297         SQL_FREERESULT($result);
1298
1299         // Return result
1300         return $returnArray;
1301 }
1302 // Reload to configured stop page
1303 function SURFBAR_RELOAD_TO_STOP_PAGE($page="stop") {
1304         global $_CONFIG;
1305
1306         // Internal or external?
1307         if (($_CONFIG['surfbar_pause_mode'] == "INTERNAL") || (empty($_CONFIG['surfbar_pause_url']))) {
1308                 // Reload to internal page
1309                 LOAD_URL("surfbar.php?frame=".$page);
1310         } else {
1311                 // Reload to external page
1312                 LOAD_URL($_CONFIG['surfbar_pause_url']);
1313         }
1314 }
1315
1316 // Determine next id for surfbar or get data for given id, always call this before you call other
1317 // getters below this function!!!
1318 function SURFBAR_DETERMINE_NEXT_ID ($urlId = 0) {
1319         global $SURFBAR_CACHE, $_CONFIG;
1320
1321         // Default is no id and no random number
1322         $nextId = 0;
1323         $randNum = 0;
1324
1325         // Is the ID set?
1326         if ($urlId == 0) {
1327                 // Get array with lock ids
1328                 $USE = SURFBAR_GET_LOCK_IDS();
1329
1330                 // Shall we add some URL ids to ignore?
1331                 $ADD = "";
1332                 if (count($USE) > 0) {
1333                         // Ignore some!
1334                         $ADD = " AND sbu.id NOT IN (";
1335                         foreach ($USE as $url_id => $lid) {
1336                                 // Add URL id
1337                                 $ADD .= $url_id.",";
1338                         } // END - foreach
1339
1340                         // Add closing bracket
1341                         $ADD = substr($ADD, 0, -1) . ")";
1342                 } // END - if
1343
1344                 // Determine depleted user account
1345                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
1346
1347                 // Get maximum randomness factor
1348                 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs['uid'], $ADD);
1349
1350                 // If more than one URL can be called generate the random number!
1351                 if ($maxRand > 1) {
1352                         // Generate random number
1353                         $randNum = mt_rand(0, ($maxRand - 1));
1354                 } // END - if
1355
1356                 // And query the database
1357                 //DEBUG_LOG(__FUNCTION__, __LINE__, "randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."", false);
1358                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1359 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1360 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1361 ON sbu.id=sbs.url_id
1362 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1363 ON sbu.id=l.url_id
1364 WHERE sbu.userid NOT IN (".implode(",", $UIDs['uid']).") AND sbu.status='ACTIVE' AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))".$ADD."
1365 GROUP BY sbu.id
1366 ORDER BY l.last_surfed ASC, sbu.id ASC
1367 LIMIT %s,1",
1368                         array($randNum), __FILE__, __LINE__
1369                 );
1370         } else {
1371                 // Get data from specified id number
1372                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.views_total, sbu.views_max, sbu.views_allowed, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1373 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1374 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1375 ON sbu.id=sbs.url_id
1376 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1377 ON sbu.id=l.url_id
1378 WHERE sbu.userid != %s AND sbu.status='ACTIVE' AND sbu.id=%s AND (sbu.views_allowed=0 OR (sbu.views_allowed > 0 AND sbu.views_max > 0))
1379 LIMIT 1",
1380                         array($GLOBALS['userid'], bigintval($urlId)), __FILE__, __LINE__
1381                 );
1382         }
1383
1384         // Is there an id number?
1385         //DEBUG_LOG(__FUNCTION__, __LINE__, "lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."", false);
1386         if (SQL_NUMROWS($result) == 1) {
1387                 // Load/cache data
1388                 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - BEFORE", false);
1389                 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1390                 //DEBUG_LOG(__FUNCTION__, __LINE__, "count(".count($SURFBAR_CACHE).") - AFTER", false);
1391
1392                 // Determine waiting time
1393                 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1394
1395                 // Is the last salt there?
1396                 if (is_null($SURFBAR_CACHE['last_salt'])) {
1397                         // Then repair it wit the static!
1398                         //DEBUG_LOG(__FUNCTION__, __LINE__, "last_salt - FIXED!", false);
1399                         $SURFBAR_CACHE['last_salt'] = "";
1400                 } // END - if
1401
1402                 // Fix missing last_surfed
1403                 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1404                         // Fix it here
1405                         //DEBUG_LOG(__FUNCTION__, __LINE__, "last_surfed - FIXED!", false);
1406                         $SURFBAR_CACHE['last_surfed'] = 0;
1407                 } // END - if
1408
1409                 // Get base/fixed reward and costs
1410                 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1411                 $SURFBAR_CACHE['costs']  = SURFBAR_DETERMINE_COSTS();
1412                 //DEBUG_LOG(__FUNCTION__, __LINE__, "BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1413
1414                 // Only in dynamic model add the dynamic bonus!
1415                 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1416                         // Calculate dynamic reward/costs and add it
1417                         $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1418                         $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1419                         //DEBUG_LOG(__FUNCTION__, __LINE__, "DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."", false);
1420                 } // END - if
1421
1422                 // Now get the id
1423                 $nextId = SURFBAR_GET_ID();
1424         } // END - if
1425
1426         // Free result
1427         SQL_FREERESULT($result);
1428
1429         // Return result
1430         //DEBUG_LOG(__FUNCTION__, __LINE__, "nextId={$nextId}", false);
1431         return $nextId;
1432 }
1433 // -----------------------------------------------------------------------------
1434 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1435 // $SURFBAR_CACHE ARRAY!
1436 // -----------------------------------------------------------------------------
1437 // Private getter for data elements
1438 function SURFBAR_GET_DATA ($element) {
1439         global $SURFBAR_CACHE;
1440         //DEBUG_LOG(__FUNCTION__, __LINE__, "element={$element}", false);
1441
1442         // Default is null
1443         $data = null;
1444
1445         // Is the entry there?
1446         if (isset($SURFBAR_CACHE[$element])) {
1447                 // Then take it
1448                 $data = $SURFBAR_CACHE[$element];
1449         } else { // END - if
1450                 print("<pre>");
1451                 print_r($SURFBAR_CACHE);
1452                 debug_print_backtrace();
1453                 die("</pre>");
1454         }
1455
1456         // Return result
1457         //DEBUG_LOG(__FUNCTION__, __LINE__, "element[$element]={$data}", false);
1458         return $data;
1459 }
1460 // Getter for reward from cache
1461 function SURFBAR_GET_REWARD () {
1462         // Get data element and return its contents
1463         return SURFBAR_GET_DATA('reward');
1464 }
1465 // Getter for costs from cache
1466 function SURFBAR_GET_COSTS () {
1467         // Get data element and return its contents
1468         return SURFBAR_GET_DATA('costs');
1469 }
1470 // Getter for URL from cache
1471 function SURFBAR_GET_URL () {
1472         // Get data element and return its contents
1473         return SURFBAR_GET_DATA('url');
1474 }
1475 // Getter for salt from cache
1476 function SURFBAR_GET_SALT () {
1477         // Get data element and return its contents
1478         return SURFBAR_GET_DATA('salt');
1479 }
1480 // Getter for id from cache
1481 function SURFBAR_GET_ID () {
1482         // Get data element and return its contents
1483         return SURFBAR_GET_DATA('id');
1484 }
1485 // Getter for userid from cache
1486 function SURFBAR_GET_USERID () {
1487         // Get data element and return its contents
1488         return SURFBAR_GET_DATA('userid');
1489 }
1490 // Getter for user reload locks
1491 function SURFBAR_GET_USER_RELOAD_LOCK () {
1492         // Get data element and return its contents
1493         return SURFBAR_GET_DATA('user_locks');
1494 }
1495 // Getter for reload time
1496 function SURFBAR_GET_RELOAD_TIME () {
1497         // Get data element and return its contents
1498         return SURFBAR_GET_DATA('time');
1499 }
1500 // Getter for allowed views
1501 function SURFBAR_GET_ALLOWED_VIEWS () {
1502         // Get data element and return its contents
1503         return SURFBAR_GET_DATA('views_allowed');
1504 }
1505 //
1506 ?>