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