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