]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions.php
More geo functions
[Github/YOURLS.git] / includes / functions.php
1 <?php\r
2 /*\r
3  * YOURLS\r
4  * Function library\r
5  */\r
6 \r
7 if (defined('YOURLS_DEBUG') && YOURLS_DEBUG == true) {\r
8         error_reporting(E_ALL);\r
9 } else {\r
10         error_reporting(E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING);\r
11 }\r
12 \r
13 // function to convert an integer (1337) to a string (3jk). Input integer processed as a string to beat PHP's int max value\r
14 function yourls_int2string( $id ) {\r
15         $str = yourls_base2base(trim(strval($id)), 10, YOURLS_URL_CONVERT);\r
16         if (YOURLS_URL_CONVERT <= 37)\r
17                 $str = strtolower($str);\r
18         return $str;\r
19 }\r
20 \r
21 // function to convert a string (3jk) to an integer (1337)\r
22 function yourls_string2int( $str ) {\r
23         if (YOURLS_URL_CONVERT <= 37)\r
24                 $str = strtolower($str);\r
25         return yourls_base2base(trim($str), YOURLS_URL_CONVERT, 10);\r
26 }\r
27 \r
28 // Make sure a link keyword (ie "1fv" as in "site.com/1fv") is valid.\r
29 function yourls_sanitize_string($in) {\r
30         if (YOURLS_URL_CONVERT <= 37)\r
31                 $in = strtolower($in);\r
32         return substr(preg_replace('/[^a-zA-Z0-9]/', '', $in), 0, 199);\r
33 }\r
34 \r
35 // A few sanity checks on the URL\r
36 function yourls_sanitize_url($url) {\r
37         // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')\r
38         $url = str_replace('http://http://', 'http://', $url);\r
39 \r
40         // make sure there's a protocol, add http:// if not\r
41         if ( !preg_match('!^([a-zA-Z]+://)!', $url ) )\r
42                 $url = 'http://'.$url;\r
43         \r
44         $url = yourls_clean_url($url);\r
45         \r
46         return substr( $url, 0, 199 );\r
47 }\r
48 \r
49 // Function to filter all invalid characters from a URL. Stolen from WP's clean_url()\r
50 function yourls_clean_url( $url ) {\r
51         $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);\r
52         $strip = array('%0d', '%0a', '%0D', '%0A');\r
53         $url = yourls_deep_replace($strip, $url);\r
54         $url = str_replace(';//', '://', $url);\r
55         \r
56         return $url;\r
57 }\r
58 \r
59 // Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''\r
60 // Stolen from WP's _deep_replace\r
61 function yourls_deep_replace($search, $subject){\r
62         $found = true;\r
63         while($found) {\r
64                 $found = false;\r
65                 foreach( (array) $search as $val ) {\r
66                         while(strpos($subject, $val) !== false) {\r
67                                 $found = true;\r
68                                 $subject = str_replace($val, '', $subject);\r
69                         }\r
70                 }\r
71         }\r
72         \r
73         return $subject;\r
74 }\r
75 \r
76 \r
77 // Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)\r
78 // TODO FIXME FFS: unused ?\r
79 function yourls_sanitize_int($in) {\r
80         return ( substr(preg_replace('/[^0-9]/', '', strval($in) ), 0, 20) );\r
81 }\r
82 \r
83 // Make sure a integer is safe\r
84 // Note: this is not checking for integers, since integers on 32bits system are way too limited\r
85 // TODO: find a way to validate as integer\r
86 function yourls_intval($in) {\r
87         return mysql_real_escape_string($in);\r
88 }\r
89 \r
90 // Escape a string\r
91 function yourls_escape( $in ) {\r
92         return mysql_real_escape_string($in);\r
93 }\r
94 \r
95 // Check to see if a given keyword is reserved (ie reserved URL or an existing page)\r
96 // Returns bool\r
97 function yourls_keyword_is_reserved( $keyword ) {\r
98         global $yourls_reserved_URL;\r
99         \r
100         if ( in_array( $keyword, $yourls_reserved_URL)\r
101                 or file_exists(dirname(dirname(__FILE__))."/pages/$keyword.php")\r
102                 or is_dir(dirname(dirname(__FILE__))."/$keyword")\r
103         )\r
104                 return true;\r
105         \r
106         return false;\r
107 }\r
108 \r
109 // Function: Get IP Address. Returns a DB safe string.\r
110 function yourls_get_IP() {\r
111         if(!empty($_SERVER['HTTP_CLIENT_IP'])) {\r
112                 $ip_address = $_SERVER['HTTP_CLIENT_IP'];\r
113         } else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {\r
114                 $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];\r
115         } else if(!empty($_SERVER['REMOTE_ADDR'])) {\r
116                 $ip_address = $_SERVER['REMOTE_ADDR'];\r
117         } else {\r
118                 $ip_address = '';\r
119         }\r
120         if(strpos($ip_address, ',') !== false) {\r
121                 $ip_address = explode(',', $ip_address);\r
122                 $ip_address = $ip_address[0];\r
123         }\r
124         \r
125         $ip_address = preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip_address );\r
126 \r
127         return $ip_address;\r
128 }\r
129 \r
130 // Add the "Edit" row\r
131 function yourls_table_edit_row( $keyword ) {\r
132         global $ydb;\r
133         \r
134         $table = YOURLS_DB_TABLE_URL;\r
135         $keyword = yourls_sanitize_string( $keyword );\r
136         $id = yourls_string2int( $keyword ); // used as HTML #id\r
137         $url = $ydb->get_row("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");\r
138         $safe_url = stripslashes( $url->url );\r
139         $www = YOURLS_SITE;\r
140         \r
141         if( $url ) {\r
142                 $return = <<<RETURN\r
143 <tr id="edit-$id" class="edit-row"><td colspan="5"><strong>Original URL</strong>:<input type="text" id="edit-url-$id" name="edit-url-$id" value="$safe_url" class="text" size="100" /> <strong>Short URL</strong>: $www/<input type="text" id="edit-keyword-$id" name="edit-keyword-$id" value="$keyword" class="text" size="10" /></td><td colspan="1"><input type="button" id="edit-submit-$id" name="edit-submit-$id" value="Save" title="Save new values" class="button" onclick="edit_save('$id');" />&nbsp;<input type="button" id="edit-close-$id" name="edit-close-$id" value="X" title="Cancel editing" class="button" onclick="hide_edit('$id');" /><input type="hidden" id="old_keyword_$id" value="$keyword"/></td></tr>\r
144 RETURN;\r
145         } else {\r
146                 $return = '<tr><td colspan="6">Error, URL not found</td></tr>';\r
147         }\r
148         \r
149         return $return;\r
150 }\r
151 \r
152 // Add a link row\r
153 function yourls_table_add_row( $keyword, $url, $ip, $clicks, $timestamp ) {\r
154         $keyword = yourls_sanitize_string( $keyword );\r
155         $id = yourls_string2int( $keyword ); // used as HTML #id\r
156         $date = date( 'M d, Y H:i', $timestamp+( YOURLS_HOURS_OFFSET * 3600) );\r
157         $clicks = number_format($clicks);\r
158         $www = YOURLS_SITE;\r
159         $shorturl = YOURLS_SITE.'/'.$keyword;\r
160         \r
161         return <<<ROW\r
162 <tr id="id-$id"><td id="keyword-$id"><a href="$shorturl">$shorturl</a></td><td id="url-$id"><a href="$url" title="$url">$url</a></td><td id="timestamp-$id">$date</td><td>$ip</td><td>$clicks</td><td class="actions"><input type="button" id="edit-button-$id" name="edit-button" value="Edit" class="button" onclick="edit('$id');" />&nbsp;<input type="button" id="delete-button-$id" name="delete-button" value="Del" class="button" onclick="remove('$id');" /><input type="hidden" id="keyword_$id" value="$keyword"/></td></tr>\r
163 ROW;\r
164 }\r
165 \r
166 // Get next id a new link will have if no custom keyword provided\r
167 function yourls_get_next_decimal() {\r
168         return (int)yourls_get_option( 'next_id' );\r
169 }\r
170 \r
171 // Update id for next link with no custom keyword\r
172 function yourls_update_next_decimal( $int = '' ) {\r
173         $int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;\r
174         return yourls_update_option( 'next_id', $int );\r
175 }\r
176 \r
177 // Delete a link in the DB\r
178 function yourls_delete_link_by_keyword( $keyword ) {\r
179         global $ydb;\r
180 \r
181         $table = YOURLS_DB_TABLE_URL;\r
182         $keyword = yourls_sanitize_string( $keyword );\r
183         return $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");\r
184 }\r
185 \r
186 // SQL query to insert a new link in the DB. Needs sanitized data. Returns boolean for success or failure of the inserting\r
187 function yourls_insert_link_in_db($url, $keyword) {\r
188         global $ydb;\r
189 \r
190         $table = YOURLS_DB_TABLE_URL;\r
191         $timestamp = date('Y-m-d H:i:s');\r
192         $ip = yourls_get_IP();\r
193         $insert = $ydb->query("INSERT INTO `$table` VALUES('$keyword', '$url', '$timestamp', '$ip', 0);");\r
194         \r
195         return (bool)$insert;\r
196 }\r
197 \r
198 // Add a new link in the DB, either with custom keyword, or find one\r
199 function yourls_add_new_link( $url, $keyword = '' ) {\r
200         global $ydb;\r
201 \r
202         if ( !$url || $url == 'http://' || $url == 'https://' ) {\r
203                 $return['status'] = 'fail';\r
204                 $return['code'] = 'error:nourl';\r
205                 $return['message'] = 'Missing URL input';\r
206                 return $return;\r
207         }\r
208 \r
209         $table = YOURLS_DB_TABLE_URL;\r
210         $url = mysql_real_escape_string( yourls_sanitize_url($url) );\r
211         $strip_url = stripslashes($url);\r
212         $url_exists = $ydb->get_row("SELECT keyword,url FROM `$table` WHERE `url` = '".$strip_url."';");\r
213         $ip = yourls_get_IP();\r
214         $return = array();\r
215 \r
216         // New URL : store it\r
217         if( !$url_exists ) {\r
218 \r
219                 // Custom keyword provided\r
220                 if ( $keyword ) {\r
221                         $keyword = mysql_real_escape_string(yourls_sanitize_string($keyword));\r
222                         if ( !yourls_keyword_is_free($keyword) ) {\r
223                                 // This shorturl either reserved or taken already\r
224                                 $return['status'] = 'fail';\r
225                                 $return['code'] = 'error:keyword';\r
226                                 $return['message'] = 'Short URL '.$keyword.' already exists in database or is reserved';\r
227                         } else {\r
228                                 // all clear, store !\r
229                                 yourls_insert_link_in_db($url, $keyword);\r
230                                 $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );\r
231                                 $return['status'] = 'success';\r
232                                 $return['message'] = $strip_url.' added to database';\r
233                                 $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );\r
234                                 $return['shorturl'] = YOURLS_SITE .'/'. $keyword;\r
235                         }\r
236 \r
237                 // Create random keyword        \r
238                 } else {\r
239                         $timestamp = date('Y-m-d H:i:s');\r
240                         $id = yourls_get_next_decimal();\r
241                         $ok = false;\r
242                         do {\r
243                                 $keyword = yourls_int2string( $id );\r
244                                 $free = yourls_keyword_is_free($keyword);\r
245                                 $add_url = @yourls_insert_link_in_db($url, $keyword);\r
246                                 $ok = ($free && $add_url);\r
247                                 if ( $ok === false && $add_url === 1 ) {\r
248                                         // we stored something, but shouldn't have (ie reserved id)\r
249                                         $delete = yourls_delete_link_by_keyword( $keyword );\r
250                                         $return['extra_info'] .= '(deleted '.$keyword.')';\r
251                                 } else {\r
252                                         // everything ok, populate needed vars\r
253                                         $return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'date' => $timestamp, 'ip' => $ip );\r
254                                         $return['status'] = 'success';\r
255                                         $return['message'] = $strip_url.' added to database';\r
256                                         $return['html'] = yourls_table_add_row( $keyword, $url, $ip, 0, time() );\r
257                                         $return['shorturl'] = YOURLS_SITE .'/'. $keyword;\r
258                                 }\r
259                                 $id++;\r
260                         } while (!$ok);\r
261                         @yourls_update_next_decimal($id);\r
262                 }\r
263         } else {\r
264                 // URL was already stored\r
265                 $return['status'] = 'fail';\r
266                 $return['code'] = 'error:url';\r
267                 $return['message'] = $strip_url.' already exists in database';\r
268                 $return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;\r
269         }\r
270 \r
271         return $return;\r
272 }\r
273 \r
274 \r
275 // Edit a link\r
276 function yourls_edit_link($url, $keyword, $newkeyword='') {\r
277         global $ydb;\r
278 \r
279         $table = YOURLS_DB_TABLE_URL;\r
280         $url = mysql_real_escape_string(yourls_sanitize_url($url));\r
281         $keyword = yourls_sanitize_string( $keyword );\r
282         $newkeyword = yourls_sanitize_string( $newkeyword );\r
283         $strip_url = stripslashes($url);\r
284         $old_url = $ydb->get_var("SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';");\r
285         \r
286         // Check if new URL is not here already\r
287         if ($old_url != $url) {\r
288                 $new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$strip_url';"));\r
289         } else {\r
290                 $new_url_already_there = false;\r
291         }\r
292         \r
293         // Check if the new keyword is not here already\r
294         if ( $newkeyword != $keyword ) {\r
295                 $keyword_is_ok = yourls_keyword_is_free( $newkeyword );\r
296         } else {\r
297                 $keyword_is_ok = true;\r
298         }\r
299         \r
300         // All clear, update\r
301         if ( !$new_url_already_there && $keyword_is_ok ) {\r
302                 $timestamp4screen = date( 'Y M d H:i', time()+( yourls_HOURS_OFFSET * 3600) );\r
303                 $timestamp4db = date('Y-m-d H:i:s', time()+( yourls_HOURS_OFFSET * 3600) );\r
304                 $update_url = $ydb->query("UPDATE `$table` SET `url` = '$url', `timestamp` = '$timestamp4db', `keyword` = '$newkeyword' WHERE `keyword` = '$keyword';");\r
305                 if( $update_url ) {\r
306                         $return['url'] = array( 'keyword' => $newkeyword, 'shorturl' => YOURLS_SITE.'/'.$newkeyword, 'url' => $strip_url, 'date' => $timestamp4screen);\r
307                         $return['status'] = 'success';\r
308                         $return['message'] = 'Link updated in database';\r
309                 } else {\r
310                         $return['status'] = 'fail';\r
311                         $return['message'] = 'Error updating '.$strip_url.' (Short URL: '.$keyword.') to database';\r
312                 }\r
313         \r
314         // Nope\r
315         } else {\r
316                 $return['status'] = 'fail';\r
317                 $return['message'] = 'URL or keyword already exists in database';\r
318         }\r
319         \r
320         return $return;\r
321 }\r
322 \r
323 \r
324 // Check if keyword id is free (ie not already taken, and not reserved)\r
325 function yourls_keyword_is_free( $keyword ) {\r
326         global $ydb;\r
327 \r
328         $table = YOURLS_DB_TABLE_URL;\r
329         if ( yourls_keyword_is_reserved($keyword) )\r
330                 return false;\r
331                 \r
332         $already_exists = $ydb->get_var("SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';");\r
333         if ( $already_exists )\r
334                 return false;\r
335 \r
336         return true;\r
337 }\r
338 \r
339 \r
340 // Display a page\r
341 function yourls_page( $page ) {\r
342         $include = dirname(dirname(__FILE__))."/pages/$page.php";\r
343         if (!file_exists($include)) {\r
344                 die("Page '$page' not found");\r
345         }\r
346         include($include);\r
347         die();  \r
348 }\r
349 \r
350 // Connect to DB\r
351 function yourls_db_connect() {\r
352         global $ydb;\r
353 \r
354         if (!defined('YOURLS_DB_USER')\r
355                 or !defined('YOURLS_DB_PASS')\r
356                 or !defined('YOURLS_DB_NAME')\r
357                 or !defined('YOURLS_DB_HOST')\r
358                 or !class_exists('ezSQL_mysql')\r
359         ) die ('DB config/class missing');\r
360         \r
361         $ydb =  new ezSQL_mysql(YOURLS_DB_USER, YOURLS_DB_PASS, YOURLS_DB_NAME, YOURLS_DB_HOST);\r
362         if ( $ydb->last_error )\r
363                 die( $ydb->last_error );\r
364         \r
365         if ( defined('YOURLS_DEBUG') && YOURLS_DEBUG === true )\r
366                 $ydb->show_errors = true;\r
367         \r
368         // return $ydb;\r
369 }\r
370 \r
371 // Return JSON output. Compatible with PHP prior to 5.2\r
372 function yourls_json_encode($array) {\r
373         if (function_exists('json_encode')) {\r
374                 return json_encode($array);\r
375         } else {\r
376                 require_once(dirname(__FILE__).'/functions-json.php');\r
377                 return yourls_array_to_json($array);\r
378         }\r
379 }\r
380 \r
381 // Return XML output.\r
382 function yourls_xml_encode($array) {\r
383         require_once(dirname(__FILE__).'/functions-xml.php');\r
384         $converter= new yourls_array2xml;\r
385         return $converter->array2xml($array);\r
386 }\r
387 \r
388 // Return array of all informations associated with keyword. Returns false if keyword not found. Set optional $use_cache to false to force fetching from DB\r
389 function yourls_get_keyword_infos( $keyword, $use_cache = true ) {\r
390         global $ydb;\r
391         $keyword = yourls_sanitize_string( $keyword );\r
392 \r
393         if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {\r
394                 return $ydb->infos[$keyword];\r
395         }\r
396         \r
397         $table = YOURLS_DB_TABLE_URL;\r
398         $infos = $ydb->get_row("SELECT * FROM `$table` WHERE `keyword` = '$keyword'");\r
399         \r
400         if( $infos ) {\r
401                 $infos = (array)$infos;\r
402                 $ydb->infos[$keyword] = $infos;\r
403         } else {\r
404                 $ydb->infos[$keyword] = false;\r
405         }\r
406                 \r
407         return $ydb->infos[$keyword];\r
408 }\r
409 \r
410 // Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found\r
411 function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {\r
412         global $ydb;\r
413         \r
414         $keyword = yourls_sanitize_string( $keyword );\r
415         $infos = yourls_get_keyword_infos( $keyword );\r
416         \r
417         if ( isset($infos[$field]) && $infos[$field] !== false )\r
418                 return $infos[$field];\r
419 \r
420         return $notfound;       \r
421 }\r
422 \r
423 // Return long URL associated with keyword. Optional $notfound = string default message if nothing found\r
424 function yourls_get_keyword_longurl( $keyword, $notfound = false ) {\r
425         return yourls_get_keyword_info( $keyword, 'url', $notfound );\r
426 }\r
427 \r
428 // Return number of clicks on a keyword. Optional $notfound = string default message if nothing found\r
429 function yourls_get_keyword_clicks( $keyword, $notfound = false ) {\r
430         return yourls_get_keyword_info( $keyword, 'clicks', $notfound );\r
431 }\r
432 \r
433 // Return IP that added a keyword. Optional $notfound = string default message if nothing found\r
434 function yourls_get_keyword_IP( $keyword, $notfound = false ) {\r
435         return yourls_get_keyword_info( $keyword, 'ip', $notfound );\r
436 }\r
437 \r
438 // Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found\r
439 function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {\r
440         return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );\r
441 }\r
442 \r
443 // Update click count on a short URL\r
444 function yourls_update_clicks( $keyword ) {\r
445         global $ydb;\r
446         $keyword = yourls_sanitize_string( $keyword );\r
447         $table = YOURLS_DB_TABLE_URL;\r
448         return $ydb->query("UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'");\r
449 }\r
450 \r
451 \r
452 // Return array for API stat requests\r
453 function yourls_api_stats( $filter, $limit ) {\r
454         global $ydb;\r
455 \r
456         switch( $filter ) {\r
457                 case 'bottom':\r
458                         $sort_by = 'clicks';\r
459                         $sort_order = 'asc';\r
460                         break;\r
461                 case 'last':\r
462                         $sort_by = 'timestamp';\r
463                         $sort_order = 'desc';\r
464                         break;\r
465                 case 'rand':\r
466                 case 'random':\r
467                         $sort_by = 'RAND()';\r
468                         $sort_order = '';\r
469                         break;\r
470                 case 'top':\r
471                 default:\r
472                         $sort_by = 'clicks';\r
473                         $sort_order = 'desc';\r
474                         break;\r
475         }\r
476         \r
477         $limit = intval( $limit );\r
478         $table_url = YOURLS_DB_TABLE_URL;\r
479         $results = $ydb->get_results("SELECT * FROM $table_url WHERE 1=1 ORDER BY $sort_by $sort_order LIMIT 0, $limit;");\r
480 \r
481         $return = array();\r
482         $i = 1;\r
483 \r
484         foreach ($results as $res) {\r
485                 $return['links']['link_'.$i++] = array(\r
486                         'shorturl' => YOURLS_SITE .'/'. $res->keyword,\r
487                         'url' => $res->url,\r
488                         'timestamp' => $res->timestamp,\r
489                         'ip' => $res->ip,\r
490                         'clicks' => $res->clicks\r
491                 );\r
492         }\r
493 \r
494         $return['stats'] = yourls_get_db_stats();\r
495 \r
496         return $return;\r
497 }\r
498 \r
499 \r
500 // Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array\r
501 function yourls_get_db_stats( $where = '' ) {\r
502         global $ydb;\r
503         $table_url = YOURLS_DB_TABLE_URL;\r
504 \r
505         $totals = $ydb->get_row("SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where");\r
506         return array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );\r
507 }\r
508 \r
509 // Return API result. Dies after this\r
510 function yourls_api_output( $mode, $return ) {\r
511         switch ( $mode ) {\r
512                 case 'json':\r
513                         header('Content-type: application/json');\r
514                         echo yourls_json_encode($return);\r
515                         break;\r
516                 \r
517                 case 'xml':\r
518                         header('Content-type: application/xml');\r
519                         echo yourls_xml_encode($return);\r
520                         break;\r
521                         \r
522                 case 'simple':\r
523                 default:\r
524                         echo $return['shorturl'];\r
525                         break;\r
526         }\r
527         die();\r
528 }\r
529 \r
530 // Display HTML head and <body> tag\r
531 function yourls_html_head( $context = 'index' ) {\r
532         // Load components as needed\r
533         switch ( $context ) {\r
534                 case 'bookmark':\r
535                 case 'infos':\r
536                         $share = true;\r
537                         $insert = true;\r
538                         $tablesorter = true;\r
539                         break;\r
540                         \r
541                 case 'index':\r
542                         $share = false;\r
543                         $insert = true;\r
544                         $tablesorter = true;\r
545                         break;\r
546                 \r
547                 case 'install':\r
548                 case 'login':\r
549                 case 'new':\r
550                 case 'tools':\r
551                 case 'upgrade':\r
552                         $share = false;\r
553                         $insert = false;\r
554                         $tablesorter = false;\r
555                         break;\r
556         }\r
557         \r
558         ?>\r
559 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r
560 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\r
561 <head>\r
562         <title>YOURLS &raquo; Your Own URL Shortener | <?php echo YOURLS_SITE; ?></title>\r
563         <link rel="icon" type="image/gif" href="<?php echo YOURLS_SITE; ?>/images/favicon.gif" />\r
564         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\r
565         <meta name="copyright" content="Copyright &copy; 2008-<?php echo date('Y'); ?> YOURS" />\r
566         <meta name="author" content="Ozh Richard, Lester Chan" />\r
567         <meta name="description" content="Insert URL &laquo; YOURLS &raquo; Your Own URL Shortener' | <?php echo YOURLS_SITE; ?>" />\r
568         <script src="<?php echo YOURLS_SITE; ?>/js/jquery-1.3.2.min.js" type="text/javascript"></script>\r
569         <link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/style.css" type="text/css" media="screen" />\r
570         <?php if ($tablesorter) { ?>\r
571                 <link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/tablesorter.css" type="text/css" media="screen" />\r
572                 <script src="<?php echo YOURLS_SITE; ?>/js/jquery.tablesorter.min.js" type="text/javascript"></script>\r
573         <?php } ?>\r
574         <?php if ($insert) { ?>\r
575                 <script src="<?php echo YOURLS_SITE; ?>/js/insert.js" type="text/javascript"></script>\r
576         <?php } ?>\r
577         <?php if ($share) { ?>\r
578                 <script src="<?php echo YOURLS_SITE; ?>/js/share.js" type="text/javascript"></script>\r
579         <?php } ?>\r
580 </head>\r
581 <body class="<?php echo $context; ?>">\r
582         <?php\r
583 }\r
584 \r
585 // Display HTML footer (including closing body & html tags)\r
586 function yourls_html_footer() {\r
587         global $ydb;\r
588         \r
589         $num_queries = $ydb->num_queries > 1 ? $ydb->num_queries.' queries' : $ydb->num_queries.' query';\r
590         ?>\r
591         <div id="footer"><p>Powered by <a href="http://yourls.org/" title="YOURLS">YOURLS</a> v<?php echo YOURLS_VERSION; echo ' &ndash; '.$num_queries; ?></p></div>\r
592         <?php if( defined('YOURLS_DEBUG') && YOURLS_DEBUG == true ) {\r
593                 echo '<p>'. $ydb->all_queries .'<p>';\r
594         } ?>\r
595         </body>\r
596         </html>\r
597         <?php\r
598 }\r
599 \r
600 // Display "Add new URL" box\r
601 function yourls_html_addnew( $url = '', $keyword = '' ) {\r
602         $url = $url ? $url : 'http://';\r
603         ?>\r
604         <div id="new_url">\r
605                 <div>\r
606                         <form id="new_url_form" action="" method="get">\r
607                                 <div><strong>Enter the URL</strong>:<input type="text" id="add-url" name="url" value="<?php echo $url; ?>" class="text" size="90" />\r
608                                 Optional: <strong>Custom short URL</strong>:<input type="text" id="add-keyword" name="keyword" value="<?php echo $keyword; ?>" maxlength="12" class="text" size="8" />\r
609                                 <input type="button" id="add-button" name="add-button" value="Shorten The URL" class="button" onclick="add();" /></div>\r
610                         </form>\r
611                         <div id="feedback" style="display:none"></div>\r
612                 </div>\r
613         </div>\r
614         <?php\r
615 }\r
616 \r
617 // Display main table's footer\r
618 function yourls_html_tfooter( $params = array() ) {\r
619         extract( $params ); // extract $search_text, $page, $search_in_sql ...\r
620 \r
621         ?>\r
622         <tfoot>\r
623                 <tr>\r
624                         <th colspan="4" style="text-align: left;">\r
625                                 <form action="" method="get">\r
626                                         <div>\r
627                                                 <div style="float:right;">\r
628                                                         <input type="submit" id="submit-sort" value="Filter" class="button primary" />\r
629                                                         &nbsp;\r
630                                                         <input type="button" id="submit-clear-filter" value="Clear Filter" class="button" onclick="window.parent.location.href = 'index.php'" />\r
631                                                 </div>\r
632 \r
633                                                 Search&nbsp;for&nbsp;\r
634                                                 <input type="text" name="s_search" class="text" size="20" value="<?php echo $search_text; ?>" />\r
635                                                 &nbsp;in&nbsp;\r
636                                                 <select name="s_in" size="1">\r
637                                                         <!-- <option value="id"<?php if($search_in_sql == 'id') { echo ' selected="selected"'; } ?>>ID</option> -->\r
638                                                         <option value="url"<?php if($search_in_sql == 'url') { echo ' selected="selected"'; } ?>>URL</option>\r
639                                                         <option value="ip"<?php if($search_in_sql == 'ip') { echo ' selected="selected"'; } ?>>IP</option>\r
640                                                 </select>\r
641                                                 &ndash;&nbsp;Order&nbsp;by&nbsp;\r
642                                                 <select name="s_by" size="1">\r
643                                                         <option value="id"<?php if($sort_by_sql == 'id') { echo ' selected="selected"'; } ?>>ID</option>\r
644                                                         <option value="url"<?php if($sort_by_sql == 'url') { echo ' selected="selected"'; } ?>>URL</option>\r
645                                                         <option value="timestamp"<?php if($sort_by_sql == 'timestamp') { echo ' selected="selected"'; } ?>>Date</option>\r
646                                                         <option value="ip"<?php if($sort_by_sql == 'ip') { echo ' selected="selected"'; } ?>>IP</option>\r
647                                                         <option value="clicks"<?php if($sort_by_sql == 'clicks') { echo ' selected="selected"'; } ?>>Clicks</option>\r
648                                                 </select>\r
649                                                 <select name="s_order" size="1">\r
650                                                         <option value="asc"<?php if($sort_order_sql == 'asc') { echo ' selected="selected"'; } ?>>Ascending</option>\r
651                                                         <option value="desc"<?php if($sort_order_sql == 'desc') { echo ' selected="selected"'; } ?>>Descending</option>\r
652                                                 </select>\r
653                                                 &ndash;&nbsp;Show&nbsp;\r
654                                                 <input type="text" name="perpage" class="text" size="2" value="<?php echo $perpage; ?>" />&nbsp;rows<br/>\r
655                                                 \r
656                                                 Show links with\r
657                                                 <select name="link_filter" size="1">\r
658                                                         <option value="more"<?php if($link_filter === 'more') { echo ' selected="selected"'; } ?>>more</option>\r
659                                                         <option value="less"<?php if($link_filter === 'less') { echo ' selected="selected"'; } ?>>less</option>\r
660                                                 </select>\r
661                                                 than\r
662                                                 <input type="text" name="link_limit" class="text" size="4" value="<?php echo $link_limit; ?>" />clicks\r
663 \r
664                                                 \r
665                                         </div>\r
666                                 </form>\r
667                         </th>\r
668                         <th colspan="3" style="text-align: right;">\r
669                                 Pages (<?php echo $total_pages; ?>):\r
670                                 <?php\r
671                                         if ($page >= 4) {\r
672                                                 echo '<b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page=1'.'" title="Go to First Page">&laquo; First</a></b> ... ';\r
673                                         }\r
674                                         if($page > 1) {\r
675                                                 echo ' <b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($page-1).'" title="&laquo; Go to Page '.($page-1).'">&laquo;</a></b> ';\r
676                                         }\r
677                                         for($i = $page - 2 ; $i  <= $page +2; $i++) {\r
678                                                 if ($i >= 1 && $i <= $total_pages) {\r
679                                                         if($i == $page) {\r
680                                                                 echo "<strong>[$i]</strong> ";\r
681                                                         } else {\r
682                                                                 echo '<a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($i).'" title="Page '.$i.'">'.$i.'</a> ';\r
683                                                         }\r
684                                                 }\r
685                                         }\r
686                                         if($page < $total_pages) {\r
687                                                 echo ' <b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($page+1).'" title="Go to Page '.($page+1).' &raquo;">&raquo;</a></b> ';\r
688                                         }\r
689                                         if (($page+2) < $total_pages) {\r
690                                                 echo ' ... <b><a href="'.$base_page.'?s_by='.$sort_by_sql.'&amp;s_order='.$sort_order_sql.$search_url.'&amp;perpage='.$perpage.'&amp;page='.($total_pages).'" title="Go to Last Page">Last &raquo;</a></b>';\r
691                                         }\r
692                                 ?>\r
693                         </th>\r
694                 </tr>\r
695         </tfoot>\r
696         <?php\r
697 }\r
698 \r
699 // Display the Quick Share box of the tools.php page\r
700 function yourls_share_box( $longurl, $shorturl, $title='', $text='' ) {\r
701         $text = ( $text ? '"'.$text.'" ' : '' );\r
702         $title = ( $title ? "$title " : '' );\r
703         $share = htmlspecialchars_decode( $title.$text.$shorturl );\r
704         $_share = rawurlencode( $share );\r
705         $_url = rawurlencode( $shorturl );\r
706         $count = 140 - strlen( $share );\r
707         ?>\r
708         \r
709         <div id="shareboxes">\r
710 \r
711                 <div id="copybox" class="share">\r
712                 <h2>Your short link</h2>\r
713                         <p><input id="copylink" class="text" size="40" value="<?php echo $shorturl; ?>" /></p>\r
714                         <p><small>Original link: <a href="<?php echo $longurl; ?>"><?php echo $longurl; ?></a></small></p>\r
715                 </div>\r
716 \r
717                 <div id="sharebox" class="share">\r
718                         <h2>Quick Share</h2>\r
719                         <div id="tweet">\r
720                                 <span id="charcount"><?php echo $count; ?></span>\r
721                                 <textarea id="tweet_body"><?php echo $share; ?></textarea>\r
722                         </div>\r
723                         <p id="share_links">Share with \r
724                                 <a id="share_tw" href="http://twitter.com/home?status=<?php echo $_share; ?>" title="Tweet this!" onclick="share('tw');return false">Twitter</a>\r
725                                 <a id="share_fb" href="http://www.facebook.com/share.php?u=<?php echo $_url; ?>" title="Share on Facebook" onclick="share('fb');return false;">Facebook</a>\r
726                                 <a id="share_ff" href="http://friendfeed.com/share/bookmarklet/frame#title=<?php echo $_share; ?>" title="Share on Friendfeed" onclick="javascript:share('ff');return false;">FriendFeed</a>\r
727                         </p>\r
728                         </div>\r
729                 </div>\r
730         \r
731         </div>\r
732         \r
733         <?php\r
734 }\r
735 \r
736 // Get number of SQL queries performed\r
737 function yourls_get_num_queries() {\r
738         global $ydb;\r
739 \r
740         return $ydb->num_queries;\r
741 }\r
742 \r
743 // Compat http_build_query for PHP4\r
744 if (!function_exists('http_build_query')) {\r
745         function http_build_query($data, $prefix=null, $sep=null) {\r
746                 return yourls_http_build_query($data, $prefix, $sep);\r
747         }\r
748 }\r
749 \r
750 // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)\r
751 function yourls_http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {\r
752         $ret = array();\r
753 \r
754         foreach ( (array) $data as $k => $v ) {\r
755                 if ( $urlencode)\r
756                         $k = urlencode($k);\r
757                 if ( is_int($k) && $prefix != null )\r
758                         $k = $prefix.$k;\r
759                 if ( !empty($key) )\r
760                         $k = $key . '%5B' . $k . '%5D';\r
761                 if ( $v === NULL )\r
762                         continue;\r
763                 elseif ( $v === FALSE )\r
764                         $v = '0';\r
765 \r
766                 if ( is_array($v) || is_object($v) )\r
767                         array_push($ret,yourls_http_build_query($v, '', $sep, $k, $urlencode));\r
768                 elseif ( $urlencode )\r
769                         array_push($ret, $k.'='.urlencode($v));\r
770                 else\r
771                         array_push($ret, $k.'='.$v);\r
772         }\r
773 \r
774         if ( NULL === $sep )\r
775                 $sep = ini_get('arg_separator.output');\r
776 \r
777         return implode($sep, $ret);\r
778 }\r
779 \r
780 // Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.\r
781 function yourls_get_user_agent() {\r
782         if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )\r
783                 return '-';\r
784         \r
785         $ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));\r
786         $ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );\r
787                 \r
788         return substr( $ua, 0, 254 );\r
789 }\r
790 \r
791 // Redirect to another page\r
792 function yourls_redirect( $location, $code = 301 ) {\r
793         // Anti fool check: cannot redirect to the URL we currently are on\r
794         if( preg_replace('!^[^:]+://!', '', $location) != $_SERVER["SERVER_NAME"].$_SERVER['REQUEST_URI'] ) {\r
795                 $protocol = $_SERVER["SERVER_PROTOCOL"];\r
796                 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )\r
797                         $protocol = 'HTTP/1.0';\r
798 \r
799                 $code = intval( $code );\r
800                 $desc = yourls_get_HTTP_status($code);\r
801 \r
802                 if ( php_sapi_name() != 'cgi-fcgi' )\r
803                                 header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups\r
804                 header("Location: $location");\r
805                 die();\r
806         }\r
807 }\r
808 \r
809 // Redirect to another page using Javascript\r
810 function yourls_redirect_javascript( $location ) {\r
811         echo <<<REDIR\r
812         <script type="text/javascript">\r
813         //window.location="$location";\r
814         </script>\r
815         <small>(if you are not redirected after 10 seconds, please <a href="$location">click here</a>)</small>\r
816 REDIR;\r
817 }\r
818 \r
819 // Return a HTTP status code\r
820 function yourls_get_HTTP_status( $code ) {\r
821         $code = intval( $code );\r
822         $headers_desc = array(\r
823                 100 => 'Continue',\r
824                 101 => 'Switching Protocols',\r
825                 102 => 'Processing',\r
826 \r
827                 200 => 'OK',\r
828                 201 => 'Created',\r
829                 202 => 'Accepted',\r
830                 203 => 'Non-Authoritative Information',\r
831                 204 => 'No Content',\r
832                 205 => 'Reset Content',\r
833                 206 => 'Partial Content',\r
834                 207 => 'Multi-Status',\r
835                 226 => 'IM Used',\r
836 \r
837                 300 => 'Multiple Choices',\r
838                 301 => 'Moved Permanently',\r
839                 302 => 'Found',\r
840                 303 => 'See Other',\r
841                 304 => 'Not Modified',\r
842                 305 => 'Use Proxy',\r
843                 306 => 'Reserved',\r
844                 307 => 'Temporary Redirect',\r
845 \r
846                 400 => 'Bad Request',\r
847                 401 => 'Unauthorized',\r
848                 402 => 'Payment Required',\r
849                 403 => 'Forbidden',\r
850                 404 => 'Not Found',\r
851                 405 => 'Method Not Allowed',\r
852                 406 => 'Not Acceptable',\r
853                 407 => 'Proxy Authentication Required',\r
854                 408 => 'Request Timeout',\r
855                 409 => 'Conflict',\r
856                 410 => 'Gone',\r
857                 411 => 'Length Required',\r
858                 412 => 'Precondition Failed',\r
859                 413 => 'Request Entity Too Large',\r
860                 414 => 'Request-URI Too Long',\r
861                 415 => 'Unsupported Media Type',\r
862                 416 => 'Requested Range Not Satisfiable',\r
863                 417 => 'Expectation Failed',\r
864                 422 => 'Unprocessable Entity',\r
865                 423 => 'Locked',\r
866                 424 => 'Failed Dependency',\r
867                 426 => 'Upgrade Required',\r
868 \r
869                 500 => 'Internal Server Error',\r
870                 501 => 'Not Implemented',\r
871                 502 => 'Bad Gateway',\r
872                 503 => 'Service Unavailable',\r
873                 504 => 'Gateway Timeout',\r
874                 505 => 'HTTP Version Not Supported',\r
875                 506 => 'Variant Also Negotiates',\r
876                 507 => 'Insufficient Storage',\r
877                 510 => 'Not Extended'\r
878         );\r
879 \r
880         if ( isset( $headers_desc[$code] ) )\r
881                 return $headers_desc[$code];\r
882         else\r
883                 return '';\r
884 }\r
885 \r
886 \r
887 // Log a redirect (for stats)\r
888 function yourls_log_redirect( $keyword ) {\r
889         global $ydb;\r
890         $table = YOURLS_DB_TABLE_LOG;\r
891         \r
892         $keyword = yourls_sanitize_string( $keyword );\r
893         $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) : 'direct' );\r
894         $ua = yourls_get_user_agent();\r
895         $ip = yourls_get_IP();\r
896         $location = yourls_geo_ip_to_countrycode( $ip );\r
897         \r
898         return $ydb->query( "INSERT INTO `$table` VALUES ('', NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );\r
899 }\r
900 \r
901 // Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/\r
902 function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {\r
903         if ( !file_exists( dirname(__FILE__).'/geo/GeoIP.dat') || !file_exists( dirname(__FILE__).'/geo/geoip.inc') )\r
904                 return $default;\r
905 \r
906         if ( $ip == '' )\r
907                 $ip = yourls_get_IP();\r
908                 \r
909         require_once( dirname(__FILE__).'/geo/geoip.inc') ;\r
910         $gi = geoip_open( dirname(__FILE__).'/geo/GeoIP.dat', GEOIP_STANDARD);\r
911         $location = geoip_country_code_by_addr($gi, $ip);\r
912         geoip_close($gi);\r
913 \r
914         return $location;\r
915 }\r
916 \r
917 // Converts a 2 letter country code to long name (ie AU -> Australia)\r
918 function yourls_geo_countrycode_to_countryname( $code ) {\r
919         // Load the Geo class if not already done\r
920         if( !class_exists('GeoIP') ) {\r
921                 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');\r
922         }\r
923         \r
924         if( class_exists('GeoIP') ) {\r
925                 $geo = new GeoIP;\r
926                 $id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[$code];\r
927                 $long = $geo->GEOIP_COUNTRY_NAMES[$id];\r
928                 return $long;\r
929         } else {\r
930                 return false;\r
931         }\r
932 }\r
933 \r
934 // Return flag URL from 2 letter country code\r
935 function yourls_geo_get_flag( $code ) {\r
936         // Load the Geo class if not already done\r
937         if( !class_exists('GeoIP') ) {\r
938                 $temp = yourls_geo_ip_to_countrycode('127.0.0.1');\r
939         }\r
940         \r
941         if( class_exists('GeoIP') ) {\r
942                 return YOURLS_SITE.'/includes/geo/flags/flag_'.(strtolower($code)).'.gif';\r
943         } else {\r
944                 return false;\r
945         }\r
946 }\r
947 \r
948 \r
949 // Check if an upgrade is needed\r
950 function yourls_upgrade_is_needed() {\r
951         // check YOURLS_VERSION && YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS\r
952         list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();\r
953 \r
954         // Using floatval() to get 1.4 from 1.4-alpha\r
955         if( ( $currentver < floatval( YOURLS_VERSION ) ) || ( $currentsql < floatval( YOURLS_DB_VERSION ) ) )   \r
956                 return true;\r
957                 \r
958         return false;\r
959 }\r
960 \r
961 // Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.\r
962 function yourls_get_current_version_from_sql() {\r
963         $currentver = yourls_get_option( 'version' );\r
964         $currentsql = yourls_get_option( 'db_version' );\r
965         if( !$currentver )\r
966                 $currentver = '1.3';\r
967         if( !$currentsql )\r
968                 $currentsql = '100';\r
969                 \r
970         return array( $currentver, $currentsql);\r
971 }\r
972 \r
973 // Read an option from DB (or from cache if available). Return value or $default if not found\r
974 function yourls_get_option( $option_name, $default = false ) {\r
975         global $ydb;\r
976         if ( !isset( $ydb->option[$option_name] ) ) {\r
977                 $table = YOURLS_DB_TABLE_OPTIONS;\r
978                 $option_name = yourls_escape( $option_name );\r
979                 $row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );\r
980                 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values\r
981                         $value = $row->option_value;\r
982                 } else { // option does not exist, so we must cache its non-existence\r
983                         $value = $default;\r
984                 }\r
985                 $ydb->option[$option_name] = yourls_maybe_unserialize( $value );\r
986         }\r
987 \r
988         return $ydb->option[$option_name];\r
989 }\r
990 \r
991 // Read all options from DB at once\r
992 function yourls_get_all_options() {\r
993         global $ydb;\r
994         $table = YOURLS_DB_TABLE_OPTIONS;\r
995         \r
996         $allopt = $ydb->get_results("SELECT `option_name`, `option_value` FROM `$table` WHERE 1=1");\r
997         \r
998         foreach( $allopt as $option ) {\r
999                 $ydb->option[$option->option_name] = yourls_maybe_unserialize( $option->option_value );\r
1000         }\r
1001 }\r
1002 \r
1003 // Update (add if doesn't exist) an option to DB\r
1004 function yourls_update_option( $option_name, $newvalue ) {\r
1005         global $ydb;\r
1006         $table = YOURLS_DB_TABLE_OPTIONS;\r
1007 \r
1008         $safe_option_name = yourls_escape( $option_name );\r
1009 \r
1010         $oldvalue = yourls_get_option( $safe_option_name );\r
1011 \r
1012         // If the new and old values are the same, no need to update.\r
1013         if ( $newvalue === $oldvalue )\r
1014                 return false;\r
1015 \r
1016         if ( false === $oldvalue ) {\r
1017                 yourls_add_option( $option_name, $newvalue );\r
1018                 return true;\r
1019         }\r
1020 \r
1021         $_newvalue = yourls_escape( yourls_maybe_serialize( $newvalue ) );\r
1022 \r
1023         $ydb->query( "UPDATE `$table` SET `option_value` = '$_newvalue' WHERE `option_name` = '$option_name'");\r
1024 \r
1025         if ( $ydb->rows_affected == 1 ) {\r
1026                 $ydb->option[$option_name] = $newvalue;\r
1027                 return true;\r
1028         }\r
1029         return false;\r
1030 }\r
1031 \r
1032 // Add an option to the DB\r
1033 function yourls_add_option( $name, $value = '' ) {\r
1034         global $ydb;\r
1035         $table = YOURLS_DB_TABLE_OPTIONS;\r
1036         $safe_name = yourls_escape( $name );\r
1037 \r
1038         // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query\r
1039         if ( false !== yourls_get_option( $safe_name ) )\r
1040                 return;\r
1041 \r
1042         $_value = yourls_escape( yourls_maybe_serialize( $value ) );\r
1043 \r
1044         $ydb->query( "INSERT INTO `$table` (`option_name`, `option_value`) VALUES ('$name', '$_value')" );\r
1045         $ydb->option[$name] = $value;\r
1046         return;\r
1047 }\r
1048 \r
1049 \r
1050 // Delete an option from the DB\r
1051 function yourls_delete_option( $name ) {\r
1052         global $ydb;\r
1053         $table = YOURLS_DB_TABLE_OPTIONS;\r
1054         $name = yourls_escape( $name );\r
1055 \r
1056         // Get the ID, if no ID then return\r
1057         $option = $ydb->get_row( "SELECT option_id FROM `$table` WHERE `option_name` = '$name'" );\r
1058         if ( is_null($option) || !$option->option_id )\r
1059                 return false;\r
1060         $ydb->query( "DELETE FROM `$table` WHERE `option_name` = '$name'" );\r
1061         return true;\r
1062 }\r
1063 \r
1064 \r
1065 \r
1066 // Serialize data if needed. Stolen from WordPress\r
1067 function yourls_maybe_serialize( $data ) {\r
1068         if ( is_array( $data ) || is_object( $data ) )\r
1069                 return serialize( $data );\r
1070 \r
1071         if ( yourls_is_serialized( $data ) )\r
1072                 return serialize( $data );\r
1073 \r
1074         return $data;\r
1075 }\r
1076 \r
1077 // Check value to find if it was serialized. Stolen from WordPress\r
1078 function yourls_is_serialized( $data ) {\r
1079         // if it isn't a string, it isn't serialized\r
1080         if ( !is_string( $data ) )\r
1081                 return false;\r
1082         $data = trim( $data );\r
1083         if ( 'N;' == $data )\r
1084                 return true;\r
1085         if ( !preg_match( '/^([adObis]):/', $data, $badions ) )\r
1086                 return false;\r
1087         switch ( $badions[1] ) {\r
1088                 case 'a' :\r
1089                 case 'O' :\r
1090                 case 's' :\r
1091                         if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )\r
1092                                 return true;\r
1093                         break;\r
1094                 case 'b' :\r
1095                 case 'i' :\r
1096                 case 'd' :\r
1097                         if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )\r
1098                                 return true;\r
1099                         break;\r
1100         }\r
1101         return false;\r
1102 }\r
1103 \r
1104 // Unserialize value only if it was serialized. Stolen from WP\r
1105 function yourls_maybe_unserialize( $original ) {\r
1106         if ( yourls_is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in\r
1107                 return @unserialize( $original );\r
1108         return $original;\r
1109 }\r
1110 \r
1111 // Determine if the current page is private\r
1112 function yourls_is_private() {\r
1113         if (defined('YOURLS_PRIVATE') && YOURLS_PRIVATE == true) {\r
1114 \r
1115                 // Allow overruling of particular pages\r
1116                 $current = basename( $_SERVER["SCRIPT_NAME"] );\r
1117 \r
1118                 switch( $current ) {\r
1119                 \r
1120                 case 'yourls-api.php':\r
1121                         if( !defined('YOURLS_PRIVATE_API') || YOURLS_PRIVATE_API != false )\r
1122                                 return true;\r
1123                         break;\r
1124                                 \r
1125                 case 'yourls-infos.php':\r
1126                         if( !defined('YOURLS_PRIVATE_INFOS') || YOURLS_PRIVATE_INFOS !== false )\r
1127                                 return true;\r
1128                         break;\r
1129                 \r
1130                 default:\r
1131                         return true;\r
1132                         break;\r
1133                 }\r
1134         }\r
1135         \r
1136         return false;\r
1137 }\r
1138 \r
1139 // Show login form if required\r
1140 function yourls_maybe_require_auth() {\r
1141         if( yourls_is_private() )\r
1142                 require_once( dirname(__FILE__).'/auth.php' );\r
1143 }