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