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