]> git.mxchange.org Git - mailer.git/blob - inc/libs/surfbar_functions.php
Tons of rewrites (SQL queries), surfbar nearly finished (working: surfing with static...
[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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // Admin has added an URL with given user id
41 function SURFBAR_ADMIN_ADD_URL ($url, $uid, $reward, $paymentId) {
42         // Is this really an admin?
43         if (!IS_ADMIN()) {
44                 // Then leave here
45                 return false;
46         } // END - if
47
48         // Check if that URL does not exist
49         if (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
50                 // Already found!
51                 return false;
52         } // END - if
53
54         // Register the new URL
55         return SURFBAR_REGISTER_URL($url, $uid, $reward, $paymentId, "CONFIRMED", "unlock");
56 }
57 // Looks up by an URL
58 function SURFBAR_LOOKUP_BY_URL ($url) {
59         // Now lookup that given URL by itself
60         $urlArray = SURFBAR_GET_URL_DATA($url, "url");
61
62         // Was it found?
63         return (count($urlArray) > 0);
64 }
65 // Load URL data by given search term and column
66 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
67         global $lastUrlData;
68
69         // By default nothing is found
70         $lastUrlData = array();
71
72         // Is the column an id number?
73         if (($column == "id") || ($column == "userid")) {
74                 // Extra secure input
75                 $searchTerm = bigintval($searchTerm);
76         } // END - if
77
78         // Look up the record
79         $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, views_total, status, registered, last_locked, lock_reason
80 FROM "._MYSQL_PREFIX."_surfbar_urls
81 WHERE %s='%s'
82 ORDER BY %s %s",
83                 array($column, $searchTerm, $order, $sort), __FILE__, __LINE__);
84
85         // Is there at least one record?
86         if (SQL_NUMROWS($result) > 0) {
87                 // Then load all!
88                 while ($dataRow = SQL_FETCHARRAY($result)) {
89                         // Shall we group these results?
90                         if ($group == "id") {
91                                 // Add the row by id as index
92                                 $lastUrlData[$dataRow['id']] = $dataRow;
93                         } else {
94                                 // Group entries
95                                 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
96                         }
97                 } // END - while
98         } // END - if
99
100         // Free the result
101         SQL_FREERESULT($result);
102
103         // Return the result
104         return $lastUrlData;
105 }
106 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
107 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $paymentId, $status="PENDING", $addMode="reg") {
108         global $_CONFIG;
109
110         // Make sure by the user registered URLs are always pending
111         if ($addMode == "reg") $status = "PENDING";
112
113         // Prepare content
114         $content = array(
115                 'url'         => $url,
116                 'frametester' => FRAMETESTER($url),
117                 'uid'         => $uid,
118                 'reward'      => $reward,
119                 'payment_id'  => $paymentId,
120                 'status'      => $status
121         );
122
123         // Insert the URL into database
124         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
125
126         // Translate status and reward
127         $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
128         $content['reward'] = TRANSLATE_COMMA($content['reward']);
129
130         // If in reg-mode we notify admin
131         if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
132                 // Notify admin even when he as unlocked an email
133                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
134         } // END - if
135
136         // Send mail to user
137         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
138
139         // Return the insert id
140         return $content['insert_id'];
141 }
142 // Inserts an url by given data array and return the insert id
143 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
144         // Just run the insert query for now
145         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, payment_id, status) VALUES(%s, '%s', %s, %s, '%s')",
146                 array(
147                         bigintval($urlData['uid']),
148                         $urlData['url'],
149                         (float)$urlData['reward'],
150                         bigintval($urlData['payment_id']),
151                         $urlData['status']
152                 ), __FILE__, __LINE__
153         );
154
155         // Return insert id
156         return SQL_INSERTID();
157 }
158 // Notify admin(s) with a selected message and content
159 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
160         // Prepare template name
161         $templateName = sprintf("admin_surfbar_%s", $messageType);
162
163         // Prepare subject
164         $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
165                 strtoupper($messageType)
166         );
167         eval($eval);
168
169         // Send the notification out
170         SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
171 }
172 // Notify the user about the performed action
173 function SURFBAR_NOTIFY_USER ($messageType, $content) {
174         // Prepare template name
175         $templateName = sprintf("member_surfbar_%s", $messageType);
176
177         // Prepare subject
178         $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
179                 strtoupper($messageType)
180         );
181         eval($eval);
182
183         // Load template
184         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
185
186         // Send the email
187         SEND_EMAIL($content['uid'], $subject, $mailText);
188 }
189 // Translate the URL status
190 function SURFBAR_TRANSLATE_STATUS ($status) {
191         // Create constant name
192         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
193
194         // Set default translated status
195         $statusTranslated = "!".$constantName."!";
196
197         // Generate eval() command
198         if (defined($constantName)) {
199                 $eval = "\$statusTranslated = ".$constantName.";";
200                 eval($eval);
201         } // END - if
202
203         // Return result
204         return $statusTranslated;
205 }
206 // Determine right template name
207 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
208         // Default is the frameset
209         $templateName = "surfbar_frameset";
210
211         // Any frame set? ;-)
212         if (isset($_GET['frame'])) {
213                 // Use the frame as a template name part... ;-)
214                 $templateName = sprintf("surfbar_frame_%s",
215                         SQL_ESCAPE($_GET['frame'])
216                 );
217         } // END - if
218
219         // Return result
220         return $templateName;
221 }
222 // Check if the "reload lock" of the current user is full
223 function SURFBAR_CHECK_RELOAD_FULL() {
224         global $SURFBAR_DATA, $_CONFIG;
225
226         // Default is full!
227         $isFull = true;
228
229         // Do we have static or dynamic mode?
230         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
231                 // Cache static reload lock
232                 $SURFBAR_DATA['surf_lock'] = $_CONFIG['surfbar_static_lock'];
233
234                 // Ask the database
235                 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
236 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
237 LIMIT 1",
238                         array($GLOBALS['userid']), __FILE__, __LINE__
239                 );
240
241                 // Fetch row
242                 list($SURFBAR_DATA['user_locks']) = SQL_FETCHROW($result);
243
244                 // Is it null?
245                 if (is_null($SURFBAR_DATA['user_locks'])) {
246                         // Then fix it to zero!
247                         $SURFBAR_DATA['user_locks'] = 0;
248                 } // END - if
249
250                 // Free result
251                 SQL_FREERESULT($result);
252
253                 // Get total URLs
254                 $total = SURFBAR_GET_TOTAL_URLS();
255
256                 // Do we have some URLs in lock? Admins can always surf on own URLs!
257                 $isFull = (($SURFBAR_DATA['user_locks'] == $total) && ($total > 0));
258         } else {
259                 // Dynamic model...
260                 die("DYNAMIC not yet implemented!");
261         }
262
263         // Return result
264         return $isFull;
265 }
266 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
267 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
268         // Get amount from database
269         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
270 FROM "._MYSQL_PREFIX."_surfbar_urls
271 WHERE userid != %d AND status='%s'",
272                 array($GLOBALS['userid'], $status), __FILE__, __LINE__
273         );
274
275         // Fetch row
276         list($cnt) = SQL_FETCHROW($result);
277
278         // Free result
279         SQL_FREERESULT($result);
280
281         // Return result
282         return $cnt;
283 }
284 // Generate a validation code for the given id number
285 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
286         global $_CONFIG, $SURFBAR_DATA;
287
288         // Generate a code until the length matches
289         $valCode = "";
290         while (strlen($valCode) != $_CONFIG['code_length']) {
291                 // Is the salt set?
292                 if (empty($salt)) {
293                         // Generate random hashed string
294                         $SURFBAR_DATA['salt'] = sha1(GEN_PASS(255));
295                 } else {
296                         // Use this as salt!
297                         $SURFBAR_DATA['salt'] = $salt;
298                 }
299                 //* DEBUG: */ echo "*".$SURFBAR_DATA['salt']."*<br />\n";
300
301                 // ... and now the validation code
302                 $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_DATA('salt').":".$id), $GLOBALS['userid']);
303                 //* DEBUG: */ echo "valCode={$valCode}<br />\n";
304         } // END - while
305
306         // Hash it with md5() and salt it with the random string
307         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_DATA('salt'));
308
309         // Finally encrypt it PGP-like and return it
310         return generatePassString($hashedCode);
311 }
312 // Check validation code
313 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
314         global $SURFBAR_DATA;
315
316         // Secure id number
317         $id = bigintval($id);
318
319         // Now generate the code again
320         $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
321
322         // Return result of checking hashes and salts
323         //* DEBUG: */ echo "--- ".$code."<br />\n--- ".$check."<br />\n";
324         //* DEBUG: */ echo "+++ ".$salt."<br />\n+++ ".SURFBAR_GET_DATA('last_salt')."<br />\n";
325         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
326 }
327 // Lockdown the userid/id combination (reload lock)
328 function SURFBAR_LOCKDOWN_ID ($id) {
329         // Just add it to the database
330         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
331                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
332 }
333 // Pay points to the user and remove it from the sender
334 function SURFBAR_PAY_POINTS ($id) {
335         global $SURFBAR_DATA, $_CONFIG;
336
337         // Re-configure ref-system to surfbar levels
338         $_CONFIG['db_percents'] = "percent";
339         $_CONFIG['db_table']    = "surfbar_reflevels";
340
341         // Book it to the user
342         ADD_POINTS_REFSYSTEM($GLOBALS['userid'], $SURFBAR_DATA['reward']);
343
344         // Remove it from the URL owner
345         SUB_POINTS($SURFBAR_DATA['userid'], $SURFBAR_DATA['reward']);
346 }
347 // Update the salt for validation
348 function SURFBAR_UPDATE_SALT() {
349         global $SURFBAR_DATA;
350
351         // Simply store the salt from cache away in database...
352         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET last_salt='%s', views_total=views_total+1 WHERE id=%s LIMIT 1",
353                 array(SURFBAR_GET_DATA('salt'), SURFBAR_GET_DATA('id')), __FILE__, __LINE__);
354
355         // Return if the update was okay
356         return (SQL_AFFECTEDROWS() == 1);
357 }
358 // Determine next id for surfbar view, always call this before you call other
359 // getters below this function!!!
360 function SURFBAR_GET_NEXT_ID ($id = 0) {
361         global $SURFBAR_DATA, $_CONFIG;
362
363         // Default is no id!
364         $nextId = 0;
365
366         // Is the ID set?
367         if ($id == 0) {
368                 // Set max random factor to total URLs minus 1
369                 $maxRand = SURFBAR_GET_TOTAL_URLS() - 1;
370
371                 // Generate random number
372                 $randNum = mt_rand(0, $maxRand);
373
374                 // And query the database
375                 $result = SQL_QUERY_ESC("SELECT sb.id, sb.userid, sb.url, sb.last_salt, sb.reward, sb.views_total, p.time, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
376 FROM "._MYSQL_PREFIX."_surfbar_urls AS sb
377 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
378 ON sb.payment_id=p.id
379 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
380 ON sb.id=l.url_id
381 WHERE sb.userid != %d AND sb.status='CONFIRMED' AND (l.last_surfed IS NULL OR (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") >= UNIX_TIMESTAMP(l.last_surfed))
382 ORDER BY l.last_surfed DESC, sb.last_salt ASC, sb.id ASC
383 LIMIT %d,1",
384                         array($GLOBALS['userid'], $randNum), __FILE__, __LINE__
385                 );
386         } else {
387                 // Get data from specified id number
388                 $result = SQL_QUERY_ESC("SELECT sb.id, sb.userid, sb.url, sb.last_salt, sb.reward, sb.views_total, p.time
389 FROM "._MYSQL_PREFIX."_surfbar_urls AS sb
390 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
391 ON sb.payment_id=p.id
392 WHERE sb.userid != %s AND sb.status='CONFIRMED' AND sb.id=%s
393 LIMIT 1",
394                         array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
395                 );
396         }
397
398         // Is there an id number?
399         if (SQL_NUMROWS($result) == 1) {
400                 // Load/cache data
401                 //* DEBUG: */ echo "*".count($SURFBAR_DATA)."*<br />\n";
402                 $SURFBAR_DATA = merge_array($SURFBAR_DATA, SQL_FETCHARRAY($result));
403                 //* DEBUG: */ echo "*".count($SURFBAR_DATA)."*<br />\n";
404
405                 // Is the time there?
406                 if (is_null($SURFBAR_DATA['time'])) {
407                         // Then repair it wit the static!
408                         $SURFBAR_DATA['time'] = $_CONFIG['surfbar_static_time'];
409                 } // END - if
410
411                 // Fix missing last_surfed
412                 if ((!isset($SURFBAR_DATA['last_surfed'])) || (is_null($SURFBAR_DATA['last_surfed']))) {
413                         // Fix it here
414                         $SURFBAR_DATA['last_surfed'] = "0";
415                 } // END - if
416
417                 // Are we in static mode?
418                 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
419                         // Then use static reward!
420                         $SURFBAR_DATA['reward'] = $_CONFIG['surfbar_static_reward'];
421                 } else {
422                         // Calculate dynamic reward and add it
423                         $SURFBAR_DATA['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
424                 }
425
426                 // Now get the id
427                 $nextId = SURFBAR_GET_DATA('id');
428         } // END - if
429
430         // Free result
431         SQL_FREERESULT($result);
432
433         // Return result
434         //* DEBUG: */ echo "nextId={$nextId}<br />\n";
435         return $nextId;
436 }
437 // ----------------------------------------------------------------------------
438 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
439 // $SURFBAR_DATA ARRAY!
440 // ----------------------------------------------------------------------------
441 // Private getter for data elements
442 function SURFBAR_GET_DATA ($element) {
443         global $SURFBAR_DATA;
444
445         // Default is null
446         $data = null;
447
448         // Is the entry there?
449         if (isset($SURFBAR_DATA[$element])) {
450                 // Then take it
451                 $data = $SURFBAR_DATA[$element];
452         } else { // END - if
453                 print("<pre>");
454                 print_r($SURFBAR_DATA);
455                 debug_print_backtrace();
456                 die("</pre>");
457         }
458
459         // Return result
460         return $data;
461 }
462 // Getter for reward from cache
463 function SURFBAR_GET_REWARD () {
464         // Get data element and return its contents
465         return SURFBAR_GET_DATA('reward');
466 }
467 // Getter for URL from cache
468 function SURFBAR_GET_URL () {
469         // Get data element and return its contents
470         return SURFBAR_GET_DATA('url');
471 }
472 // Getter for user reload locks
473 function SURFBAR_GET_USER_RELOAD_LOCK () {
474         // Get data element and return its contents
475         return SURFBAR_GET_DATA('user_locks');
476 }
477 // Getter for reload time
478 function SURFBAR_GET_RELOAD_TIME () {
479         // Get data element and return its contents
480         return SURFBAR_GET_DATA('time');
481 }
482 //
483 ?>