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