b4364a6a49675a517a35558cf8c4bb57573cdea4
[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, $costs, $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, $costs, $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, costs, 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, $costs, $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                 'costs'       => $costs,
120                 'payment_id'  => $paymentId,
121                 'status'      => $status
122         );
123
124         // Insert the URL into database
125         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
126
127         // Translate status, reward and costs
128         $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
129         $content['reward'] = TRANSLATE_COMMA($content['reward']);
130         $content['costs']  = TRANSLATE_COMMA($content['costs']);
131
132         // If in reg-mode we notify admin
133         if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
134                 // Notify admin even when he as unlocked an email
135                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
136         } // END - if
137
138         // Send mail to user
139         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
140
141         // Return the insert id
142         return $content['insert_id'];
143 }
144 // Inserts an url by given data array and return the insert id
145 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
146         // Just run the insert query for now
147         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, payment_id, status) VALUES(%s, '%s', %s, %s, %s, '%s')",
148                 array(
149                         bigintval($urlData['uid']),
150                         $urlData['url'],
151                         (float)$urlData['reward'],
152                         (float)$urlData['costs'],
153                         bigintval($urlData['payment_id']),
154                         $urlData['status']
155                 ), __FILE__, __LINE__
156         );
157
158         // Return insert id
159         return SQL_INSERTID();
160 }
161 // Notify admin(s) with a selected message and content
162 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
163         // Prepare template name
164         $templateName = sprintf("admin_surfbar_%s", $messageType);
165
166         // Prepare subject
167         $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
168                 strtoupper($messageType)
169         );
170         eval($eval);
171
172         // Send the notification out
173         SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
174 }
175 // Notify the user about the performed action
176 function SURFBAR_NOTIFY_USER ($messageType, $content) {
177         // Prepare template name
178         $templateName = sprintf("member_surfbar_%s", $messageType);
179
180         // Prepare subject
181         $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
182                 strtoupper($messageType)
183         );
184         eval($eval);
185
186         // Load template
187         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
188
189         // Send the email
190         SEND_EMAIL($content['uid'], $subject, $mailText);
191 }
192 // Translate the URL status
193 function SURFBAR_TRANSLATE_STATUS ($status) {
194         // Create constant name
195         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
196
197         // Set default translated status
198         $statusTranslated = "!".$constantName."!";
199
200         // Generate eval() command
201         if (defined($constantName)) {
202                 $eval = "\$statusTranslated = ".$constantName.";";
203                 eval($eval);
204         } // END - if
205
206         // Return result
207         return $statusTranslated;
208 }
209 // Determine right template name
210 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
211         // Default is the frameset
212         $templateName = "surfbar_frameset";
213
214         // Any frame set? ;-)
215         if (isset($_GET['frame'])) {
216                 // Use the frame as a template name part... ;-)
217                 $templateName = sprintf("surfbar_frame_%s",
218                         SQL_ESCAPE($_GET['frame'])
219                 );
220         } // END - if
221
222         // Return result
223         return $templateName;
224 }
225 // Check if the "reload lock" of the current user is full
226 function SURFBAR_CHECK_RELOAD_FULL() {
227         global $SURFBAR_DATA, $_CONFIG;
228
229         // Default is full!
230         $isFull = true;
231
232         // Do we have static or dynamic mode?
233         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
234                 // Cache static reload lock
235                 $SURFBAR_DATA['surf_lock'] = $_CONFIG['surfbar_static_lock'];
236
237                 // Ask the database
238                 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
239 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
240 LIMIT 1",
241                         array($GLOBALS['userid']), __FILE__, __LINE__
242                 );
243
244                 // Fetch row
245                 list($SURFBAR_DATA['user_locks']) = SQL_FETCHROW($result);
246
247                 // Is it null?
248                 if (is_null($SURFBAR_DATA['user_locks'])) {
249                         // Then fix it to zero!
250                         $SURFBAR_DATA['user_locks'] = 0;
251                 } // END - if
252
253                 // Free result
254                 SQL_FREERESULT($result);
255
256                 // Get total URLs
257                 $total = SURFBAR_GET_TOTAL_URLS();
258
259                 // Do we have some URLs in lock? Admins can always surf on own URLs!
260                 $isFull = (($SURFBAR_DATA['user_locks'] == $total) && ($total > 0));
261         } else {
262                 // Dynamic model...
263                 die("DYNAMIC not yet implemented!");
264         }
265
266         // Return result
267         return $isFull;
268 }
269 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
270 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
271         // Get amount from database
272         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
273 FROM "._MYSQL_PREFIX."_surfbar_urls
274 WHERE userid != %d AND status='%s'",
275                 array($GLOBALS['userid'], $status), __FILE__, __LINE__
276         );
277
278         // Fetch row
279         list($cnt) = SQL_FETCHROW($result);
280
281         // Free result
282         SQL_FREERESULT($result);
283
284         // Return result
285         return $cnt;
286 }
287 // Generate a validation code for the given id number
288 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
289         global $_CONFIG, $SURFBAR_DATA;
290
291         // Generate a code until the length matches
292         $valCode = "";
293         while (strlen($valCode) != $_CONFIG['code_length']) {
294                 // Is the salt set?
295                 if (empty($salt)) {
296                         // Generate random hashed string
297                         $SURFBAR_DATA['salt'] = sha1(GEN_PASS(255));
298                 } else {
299                         // Use this as salt!
300                         $SURFBAR_DATA['salt'] = $salt;
301                 }
302                 //* DEBUG: */ echo "*".$SURFBAR_DATA['salt']."*<br />\n";
303
304                 // ... and now the validation code
305                 $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_DATA('salt').":".$id), $GLOBALS['userid']);
306                 //* DEBUG: */ echo "valCode={$valCode}<br />\n";
307         } // END - while
308
309         // Hash it with md5() and salt it with the random string
310         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_DATA('salt'));
311
312         // Finally encrypt it PGP-like and return it
313         return generatePassString($hashedCode);
314 }
315 // Check validation code
316 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
317         global $SURFBAR_DATA;
318
319         // Secure id number
320         $id = bigintval($id);
321
322         // Now generate the code again
323         $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
324
325         // Return result of checking hashes and salts
326         //* DEBUG: */ echo "--- ".$code."<br />\n--- ".$check."<br />\n";
327         //* DEBUG: */ echo "+++ ".$salt."<br />\n+++ ".SURFBAR_GET_DATA('last_salt')."<br />\n";
328         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
329 }
330 // Lockdown the userid/id combination (reload lock)
331 function SURFBAR_LOCKDOWN_ID ($id) {
332         // Just add it to the database
333         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
334                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
335 }
336 // Pay points to the user and remove it from the sender
337 function SURFBAR_PAY_POINTS ($id) {
338         global $SURFBAR_DATA, $_CONFIG;
339
340         // Re-configure ref-system to surfbar levels
341         $_CONFIG['db_percents'] = "percent";
342         $_CONFIG['db_table']    = "surfbar_reflevels";
343
344         // Book it to the user
345         ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
346
347         // Remove it from the URL owner
348         SUB_POINTS($SURFBAR_DATA['userid'], SURFBAR_GET_DATA('costs'));
349 }
350 // Update the salt for validation
351 function SURFBAR_UPDATE_SALT() {
352         global $SURFBAR_DATA;
353
354         // Simply store the salt from cache away in database...
355         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET last_salt='%s', views_total=views_total+1 WHERE id=%s LIMIT 1",
356                 array(SURFBAR_GET_DATA('salt'), SURFBAR_GET_DATA('id')), __FILE__, __LINE__);
357
358         // Return if the update was okay
359         return (SQL_AFFECTEDROWS() == 1);
360 }
361 // Determine next id for surfbar view, always call this before you call other
362 // getters below this function!!!
363 function SURFBAR_GET_NEXT_ID ($id = 0) {
364         global $SURFBAR_DATA, $_CONFIG;
365
366         // Default is no id!
367         $nextId = 0;
368
369         // Is the ID set?
370         if ($id == 0) {
371                 // Set max random factor to total URLs minus 1
372                 $maxRand = SURFBAR_GET_TOTAL_URLS() - 1;
373
374                 // Generate random number
375                 $randNum = mt_rand(0, $maxRand);
376
377                 // And query the database
378                 $result = SQL_QUERY_ESC("SELECT sb.id, sb.userid, sb.url, sb.last_salt, sb.reward, sb.costs, sb.views_total, p.time, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
379 FROM "._MYSQL_PREFIX."_surfbar_urls AS sb
380 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
381 ON sb.payment_id=p.id
382 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
383 ON sb.id=l.url_id
384 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))
385 ORDER BY l.last_surfed DESC, sb.last_salt ASC, sb.id ASC
386 LIMIT %d,1",
387                         array($GLOBALS['userid'], $randNum), __FILE__, __LINE__
388                 );
389         } else {
390                 // Get data from specified id number
391                 $result = SQL_QUERY_ESC("SELECT sb.id, sb.userid, sb.url, sb.last_salt, sb.reward, sb.costs, sb.views_total, p.time
392 FROM "._MYSQL_PREFIX."_surfbar_urls AS sb
393 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
394 ON sb.payment_id=p.id
395 WHERE sb.userid != %s AND sb.status='CONFIRMED' AND sb.id=%s
396 LIMIT 1",
397                         array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
398                 );
399         }
400
401         // Is there an id number?
402         if (SQL_NUMROWS($result) == 1) {
403                 // Load/cache data
404                 //* DEBUG: */ echo "*".count($SURFBAR_DATA)."*<br />\n";
405                 $SURFBAR_DATA = merge_array($SURFBAR_DATA, SQL_FETCHARRAY($result));
406                 //* DEBUG: */ echo "*".count($SURFBAR_DATA)."*<br />\n";
407
408                 // Is the time there?
409                 if (is_null($SURFBAR_DATA['time'])) {
410                         // Then repair it wit the static!
411                         $SURFBAR_DATA['time'] = $_CONFIG['surfbar_static_time'];
412                 } // END - if
413
414                 // Fix missing last_surfed
415                 if ((!isset($SURFBAR_DATA['last_surfed'])) || (is_null($SURFBAR_DATA['last_surfed']))) {
416                         // Fix it here
417                         $SURFBAR_DATA['last_surfed'] = "0";
418                 } // END - if
419
420                 // Are we in static mode?
421                 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
422                         // Then use static reward/costs!
423                         $SURFBAR_DATA['reward'] = $_CONFIG['surfbar_static_reward'];
424                         $SURFBAR_DATA['costs']  = $_CONFIG['surfbar_static_costs'];
425                 } else {
426                         // Calculate dynamic reward/costs and add it
427                         $SURFBAR_DATA['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
428                         $SURFBAR_DATA['costs']  += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
429                 }
430
431                 // Now get the id
432                 $nextId = SURFBAR_GET_DATA('id');
433         } // END - if
434
435         // Free result
436         SQL_FREERESULT($result);
437
438         // Return result
439         //* DEBUG: */ echo "nextId={$nextId}<br />\n";
440         return $nextId;
441 }
442 // ----------------------------------------------------------------------------
443 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
444 // $SURFBAR_DATA ARRAY!
445 // ----------------------------------------------------------------------------
446 // Private getter for data elements
447 function SURFBAR_GET_DATA ($element) {
448         global $SURFBAR_DATA;
449
450         // Default is null
451         $data = null;
452
453         // Is the entry there?
454         if (isset($SURFBAR_DATA[$element])) {
455                 // Then take it
456                 $data = $SURFBAR_DATA[$element];
457         } else { // END - if
458                 print("<pre>");
459                 print_r($SURFBAR_DATA);
460                 debug_print_backtrace();
461                 die("</pre>");
462         }
463
464         // Return result
465         return $data;
466 }
467 // Getter for reward from cache
468 function SURFBAR_GET_REWARD () {
469         // Get data element and return its contents
470         return SURFBAR_GET_DATA('reward');
471 }
472 // Getter for costs from cache
473 function SURFBAR_GET_COSTS () {
474         // Get data element and return its contents
475         return SURFBAR_GET_DATA('costs');
476 }
477 // Getter for URL from cache
478 function SURFBAR_GET_URL () {
479         // Get data element and return its contents
480         return SURFBAR_GET_DATA('url');
481 }
482 // Getter for user reload locks
483 function SURFBAR_GET_USER_RELOAD_LOCK () {
484         // Get data element and return its contents
485         return SURFBAR_GET_DATA('user_locks');
486 }
487 // Getter for reload time
488 function SURFBAR_GET_RELOAD_TIME () {
489         // Get data element and return its contents
490         return SURFBAR_GET_DATA('time');
491 }
492 //
493 ?>