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