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