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