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