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