forked from YOURLS/YOURLS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.php
2252 lines (1926 loc) · 66.6 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* YOURLS
* Function library
*/
/**
* Determine the allowed character set in short URLs
*
*/
function yourls_get_shorturl_charset() {
static $charset = null;
if( $charset !== null )
return $charset;
if( defined('YOURLS_URL_CONVERT') && in_array( YOURLS_URL_CONVERT, array( 62, 64 ) ) ) {
$charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
} else {
// defined to 36, or wrongly defined
$charset = '0123456789abcdefghijklmnopqrstuvwxyz';
}
$charset = yourls_apply_filter( 'get_shorturl_charset', $charset );
return $charset;
}
/**
* Make an optimized regexp pattern from a string of characters
*
*/
function yourls_make_regexp_pattern( $string ) {
$pattern = preg_quote( $string, '-' ); // add - as an escaped characters -- this is fixed in PHP 5.3
// Simple benchmarks show that regexp with smarter sequences (0-9, a-z, A-Z...) are not faster or slower than 0123456789 etc...
return $pattern;
}
/**
* Is a URL a short URL? Accept either 'http://sho.rt/abc' or 'abc'
*
*/
function yourls_is_shorturl( $shorturl ) {
// TODO: make sure this function evolves with the feature set.
$is_short = false;
// Is $shorturl a URL (http://sho.rt/abc) or a keyword (abc) ?
if( yourls_get_protocol( $shorturl ) ) {
$keyword = yourls_get_relative_url( $shorturl );
} else {
$keyword = $shorturl;
}
// Check if it's a valid && used keyword
if( $keyword && $keyword == yourls_sanitize_string( $keyword ) && yourls_keyword_is_taken( $keyword ) ) {
$is_short = true;
}
return yourls_apply_filter( 'is_shorturl', $is_short, $shorturl );
}
/**
* Check to see if a given keyword is reserved (ie reserved URL or an existing page). Returns bool
*
*/
function yourls_keyword_is_reserved( $keyword ) {
global $yourls_reserved_URL;
$keyword = yourls_sanitize_keyword( $keyword );
$reserved = false;
if ( in_array( $keyword, $yourls_reserved_URL)
or file_exists( YOURLS_ABSPATH ."/pages/$keyword.php" )
or is_dir( YOURLS_ABSPATH ."/$keyword" )
)
$reserved = true;
return yourls_apply_filter( 'keyword_is_reserved', $reserved, $keyword );
}
/**
* Function: Get client IP Address. Returns a DB safe string.
*
*/
function yourls_get_IP() {
$ip = '';
// Precedence: if set, X-Forwarded-For > HTTP_X_FORWARDED_FOR > HTTP_CLIENT_IP > HTTP_VIA > REMOTE_ADDR
$headers = array( 'X-Forwarded-For', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_VIA', 'REMOTE_ADDR' );
foreach( $headers as $header ) {
if ( !empty( $_SERVER[ $header ] ) ) {
$ip = $_SERVER[ $header ];
break;
}
}
// headers can contain multiple IPs (X-Forwarded-For = client, proxy1, proxy2). Take first one.
if ( strpos( $ip, ',' ) !== false )
$ip = substr( $ip, 0, strpos( $ip, ',' ) );
return yourls_apply_filter( 'get_IP', yourls_sanitize_ip( $ip ) );
}
/**
* Get next id a new link will have if no custom keyword provided
*
*/
function yourls_get_next_decimal() {
return yourls_apply_filter( 'get_next_decimal', (int)yourls_get_option( 'next_id' ) );
}
/**
* Update id for next link with no custom keyword
*
*/
function yourls_update_next_decimal( $int = '' ) {
$int = ( $int == '' ) ? yourls_get_next_decimal() + 1 : (int)$int ;
$update = yourls_update_option( 'next_id', $int );
yourls_do_action( 'update_next_decimal', $int, $update );
return $update;
}
/**
* Delete a link in the DB
*
*/
function yourls_delete_link_by_keyword( $keyword ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_delete_link_by_keyword', null, $keyword );
if ( null !== $pre )
return $pre;
global $ydb;
$table = YOURLS_DB_TABLE_URL;
$keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
$delete = $ydb->query("DELETE FROM `$table` WHERE `keyword` = '$keyword';");
yourls_do_action( 'delete_link', $keyword, $delete );
return $delete;
}
/**
* SQL query to insert a new link in the DB. Returns boolean for success or failure of the inserting
*
*/
function yourls_insert_link_in_db( $url, $keyword, $title = '' ) {
global $ydb;
$url = yourls_escape( yourls_sanitize_url( $url ) );
$keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
$title = yourls_escape( yourls_sanitize_title( $title ) );
$table = YOURLS_DB_TABLE_URL;
$timestamp = date('Y-m-d H:i:s');
$ip = yourls_get_IP();
$insert = $ydb->query("INSERT INTO `$table` (`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) VALUES('$keyword', '$url', '$title', '$timestamp', '$ip', 0);");
yourls_do_action( 'insert_link', (bool)$insert, $url, $keyword, $title, $timestamp, $ip );
return (bool)$insert;
}
/**
* Check if a URL already exists in the DB. Return NULL (doesn't exist) or an object with URL informations.
*
*/
function yourls_url_exists( $url ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_url_exists', false, $url );
if ( false !== $pre )
return $pre;
global $ydb;
$table = YOURLS_DB_TABLE_URL;
$url = yourls_escape( yourls_sanitize_url( $url) );
$url_exists = $ydb->get_row( "SELECT * FROM `$table` WHERE `url` = '".$url."';" );
return yourls_apply_filter( 'url_exists', $url_exists, $url );
}
/**
* Add a new link in the DB, either with custom keyword, or find one
*
*/
function yourls_add_new_link( $url, $keyword = '', $title = '' ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );
if ( false !== $pre )
return $pre;
$url = yourls_encodeURI( $url );
$url = yourls_escape( yourls_sanitize_url( $url ) );
if ( !$url || $url == 'http://' || $url == 'https://' ) {
$return['status'] = 'fail';
$return['code'] = 'error:nourl';
$return['message'] = yourls__( 'Missing or malformed URL' );
$return['errorCode'] = '400';
return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );
}
// Prevent DB flood
$ip = yourls_get_IP();
yourls_check_IP_flood( $ip );
// Prevent internal redirection loops: cannot shorten a shortened URL
if( yourls_get_relative_url( $url ) ) {
if( yourls_is_shorturl( $url ) ) {
$return['status'] = 'fail';
$return['code'] = 'error:noloop';
$return['message'] = yourls__( 'URL is a short URL' );
$return['errorCode'] = '400';
return yourls_apply_filter( 'add_new_link_fail_noloop', $return, $url, $keyword, $title );
}
}
yourls_do_action( 'pre_add_new_link', $url, $keyword, $title );
$strip_url = stripslashes( $url );
$return = array();
// duplicates allowed or new URL => store it
if( yourls_allow_duplicate_longurls() || !( $url_exists = yourls_url_exists( $url ) ) ) {
if( isset( $title ) && !empty( $title ) ) {
$title = yourls_sanitize_title( $title );
} else {
$title = yourls_get_remote_title( $url );
}
$title = yourls_apply_filter( 'add_new_title', $title, $url, $keyword );
// Custom keyword provided
if ( $keyword ) {
yourls_do_action( 'add_new_link_custom_keyword', $url, $keyword, $title );
$keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
$keyword = yourls_apply_filter( 'custom_keyword', $keyword, $url, $title );
if ( !yourls_keyword_is_free( $keyword ) ) {
// This shorturl either reserved or taken already
$return['status'] = 'fail';
$return['code'] = 'error:keyword';
$return['message'] = yourls_s( 'Short URL %s already exists in database or is reserved', $keyword );
} else {
// all clear, store !
yourls_insert_link_in_db( $url, $keyword, $title );
$return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => date('Y-m-d H:i:s'), 'ip' => $ip );
$return['status'] = 'success';
$return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
$return['title'] = $title;
$return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
$return['shorturl'] = YOURLS_SITE .'/'. $keyword;
}
// Create random keyword
} else {
yourls_do_action( 'add_new_link_create_keyword', $url, $keyword, $title );
$timestamp = date( 'Y-m-d H:i:s' );
$id = yourls_get_next_decimal();
$ok = false;
do {
$keyword = yourls_int2string( $id );
$keyword = yourls_apply_filter( 'random_keyword', $keyword, $url, $title );
if ( yourls_keyword_is_free($keyword) ) {
if( @yourls_insert_link_in_db( $url, $keyword, $title ) ){
// everything ok, populate needed vars
$return['url'] = array('keyword' => $keyword, 'url' => $strip_url, 'title' => $title, 'date' => $timestamp, 'ip' => $ip );
$return['status'] = 'success';
$return['message'] = /* //translators: eg "http://someurl/ added to DB" */ yourls_s( '%s added to database', yourls_trim_long_string( $strip_url ) );
$return['title'] = $title;
$return['html'] = yourls_table_add_row( $keyword, $url, $title, $ip, 0, time() );
$return['shorturl'] = YOURLS_SITE .'/'. $keyword;
}else{
// database error, couldnt store result
$return['status'] = 'fail';
$return['code'] = 'error:db';
$return['message'] = yourls_s( 'Error saving url to database' );
}
$ok = true;
}
$id++;
} while ( !$ok );
@yourls_update_next_decimal( $id );
}
// URL was already stored
} else {
yourls_do_action( 'add_new_link_already_stored', $url, $keyword, $title );
$return['status'] = 'fail';
$return['code'] = 'error:url';
$return['url'] = array( 'keyword' => $url_exists->keyword, 'url' => $strip_url, 'title' => $url_exists->title, 'date' => $url_exists->timestamp, 'ip' => $url_exists->ip, 'clicks' => $url_exists->clicks );
$return['message'] = /* //translators: eg "http://someurl/ already exists" */ yourls_s( '%s already exists in database', yourls_trim_long_string( $strip_url ) );
$return['title'] = $url_exists->title;
$return['shorturl'] = YOURLS_SITE .'/'. $url_exists->keyword;
}
yourls_do_action( 'post_add_new_link', $url, $keyword, $title );
$return['statusCode'] = 200; // regardless of result, this is still a valid request
return yourls_apply_filter( 'add_new_link', $return, $url, $keyword, $title );
}
/**
* Edit a link
*
*/
function yourls_edit_link( $url, $keyword, $newkeyword='', $title='' ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_edit_link', null, $keyword, $url, $keyword, $newkeyword, $title );
if ( null !== $pre )
return $pre;
global $ydb;
$table = YOURLS_DB_TABLE_URL;
$url = yourls_escape (yourls_sanitize_url( $url ) );
$keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
$title = yourls_escape( yourls_sanitize_title( $title ) );
$newkeyword = yourls_escape( yourls_sanitize_string( $newkeyword ) );
$strip_url = stripslashes( $url );
$strip_title = stripslashes( $title );
$old_url = $ydb->get_var( "SELECT `url` FROM `$table` WHERE `keyword` = '$keyword';" );
// Check if new URL is not here already
if ( $old_url != $url && !yourls_allow_duplicate_longurls() ) {
$new_url_already_there = intval($ydb->get_var("SELECT COUNT(keyword) FROM `$table` WHERE `url` = '$url';"));
} else {
$new_url_already_there = false;
}
// Check if the new keyword is not here already
if ( $newkeyword != $keyword ) {
$keyword_is_ok = yourls_keyword_is_free( $newkeyword );
} else {
$keyword_is_ok = true;
}
yourls_do_action( 'pre_edit_link', $url, $keyword, $newkeyword, $new_url_already_there, $keyword_is_ok );
// All clear, update
if ( ( !$new_url_already_there || yourls_allow_duplicate_longurls() ) && $keyword_is_ok ) {
$update_url = $ydb->query( "UPDATE `$table` SET `url` = '$url', `keyword` = '$newkeyword', `title` = '$title' WHERE `keyword` = '$keyword';" );
if( $update_url ) {
$return['url'] = array( 'keyword' => $newkeyword, 'shorturl' => YOURLS_SITE.'/'.$newkeyword, 'url' => $strip_url, 'display_url' => yourls_trim_long_string( $strip_url ), 'title' => $strip_title, 'display_title' => yourls_trim_long_string( $strip_title ) );
$return['status'] = 'success';
$return['message'] = yourls__( 'Link updated in database' );
} else {
$return['status'] = 'fail';
$return['message'] = /* //translators: "Error updating http://someurl/ (Shorturl: http://sho.rt/blah)" */ yourls_s( 'Error updating %s (Short URL: %s)', yourls_trim_long_string( $strip_url ), $keyword ) ;
}
// Nope
} else {
$return['status'] = 'fail';
$return['message'] = yourls__( 'URL or keyword already exists in database' );
}
return yourls_apply_filter( 'edit_link', $return, $url, $keyword, $newkeyword, $title, $new_url_already_there, $keyword_is_ok );
}
/**
* Update a title link (no checks for duplicates etc..)
*
*/
function yourls_edit_link_title( $keyword, $title ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_edit_link_title', null, $keyword, $title );
if ( null !== $pre )
return $pre;
global $ydb;
$keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
$title = yourls_escape( yourls_sanitize_title( $title ) );
$table = YOURLS_DB_TABLE_URL;
$update = $ydb->query("UPDATE `$table` SET `title` = '$title' WHERE `keyword` = '$keyword';");
return $update;
}
/**
* Check if keyword id is free (ie not already taken, and not reserved). Return bool.
*
*/
function yourls_keyword_is_free( $keyword ) {
$free = true;
if ( yourls_keyword_is_reserved( $keyword ) or yourls_keyword_is_taken( $keyword ) )
$free = false;
return yourls_apply_filter( 'keyword_is_free', $free, $keyword );
}
/**
* Check if a keyword is taken (ie there is already a short URL with this id). Return bool.
*
*/
function yourls_keyword_is_taken( $keyword ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_keyword_is_taken', false, $keyword );
if ( false !== $pre )
return $pre;
global $ydb;
$keyword = yourls_escape( yourls_sanitize_keyword( $keyword ) );
$taken = false;
$table = YOURLS_DB_TABLE_URL;
$already_exists = $ydb->get_var( "SELECT COUNT(`keyword`) FROM `$table` WHERE `keyword` = '$keyword';" );
if ( $already_exists )
$taken = true;
return yourls_apply_filter( 'keyword_is_taken', $taken, $keyword );
}
/**
* Return XML output.
*
*/
function yourls_xml_encode( $array ) {
require_once( YOURLS_INC.'/functions-xml.php' );
$converter= new yourls_array2xml;
return $converter->array2xml( $array );
}
/**
* Return array of all information associated with keyword. Returns false if keyword not found. Set optional $use_cache to false to force fetching from DB
*
*/
function yourls_get_keyword_infos( $keyword, $use_cache = true ) {
global $ydb;
$keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
yourls_do_action( 'pre_get_keyword', $keyword, $use_cache );
if( isset( $ydb->infos[$keyword] ) && $use_cache == true ) {
return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
}
yourls_do_action( 'get_keyword_not_cached', $keyword );
$table = YOURLS_DB_TABLE_URL;
$infos = $ydb->get_row( "SELECT * FROM `$table` WHERE `keyword` = '$keyword'" );
if( $infos ) {
$infos = (array)$infos;
$ydb->infos[ $keyword ] = $infos;
} else {
$ydb->infos[ $keyword ] = false;
}
return yourls_apply_filter( 'get_keyword_infos', $ydb->infos[$keyword], $keyword );
}
/**
* Return (string) selected information associated with a keyword. Optional $notfound = string default message if nothing found
*
*/
function yourls_get_keyword_info( $keyword, $field, $notfound = false ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_get_keyword_info', false, $keyword, $field, $notfound );
if ( false !== $pre )
return $pre;
$keyword = yourls_sanitize_string( $keyword );
$infos = yourls_get_keyword_infos( $keyword );
$return = $notfound;
if ( isset( $infos[ $field ] ) && $infos[ $field ] !== false )
$return = $infos[ $field ];
return yourls_apply_filter( 'get_keyword_info', $return, $keyword, $field, $notfound );
}
/**
* Return title associated with keyword. Optional $notfound = string default message if nothing found
*
*/
function yourls_get_keyword_title( $keyword, $notfound = false ) {
return yourls_get_keyword_info( $keyword, 'title', $notfound );
}
/**
* Return long URL associated with keyword. Optional $notfound = string default message if nothing found
*
*/
function yourls_get_keyword_longurl( $keyword, $notfound = false ) {
return yourls_get_keyword_info( $keyword, 'url', $notfound );
}
/**
* Return number of clicks on a keyword. Optional $notfound = string default message if nothing found
*
*/
function yourls_get_keyword_clicks( $keyword, $notfound = false ) {
return yourls_get_keyword_info( $keyword, 'clicks', $notfound );
}
/**
* Return IP that added a keyword. Optional $notfound = string default message if nothing found
*
*/
function yourls_get_keyword_IP( $keyword, $notfound = false ) {
return yourls_get_keyword_info( $keyword, 'ip', $notfound );
}
/**
* Return timestamp associated with a keyword. Optional $notfound = string default message if nothing found
*
*/
function yourls_get_keyword_timestamp( $keyword, $notfound = false ) {
return yourls_get_keyword_info( $keyword, 'timestamp', $notfound );
}
/**
* Update click count on a short URL. Return 0/1 for error/success.
*
*/
function yourls_update_clicks( $keyword, $clicks = false ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_update_clicks', false, $keyword, $clicks );
if ( false !== $pre )
return $pre;
global $ydb;
$keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
$table = YOURLS_DB_TABLE_URL;
if ( $clicks !== false && is_int( $clicks ) && $clicks >= 0 )
$update = $ydb->query( "UPDATE `$table` SET `clicks` = $clicks WHERE `keyword` = '$keyword'" );
else
$update = $ydb->query( "UPDATE `$table` SET `clicks` = clicks + 1 WHERE `keyword` = '$keyword'" );
yourls_do_action( 'update_clicks', $keyword, $update, $clicks );
return $update;
}
/**
* Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
*
*/
function yourls_get_stats( $filter = 'top', $limit = 10, $start = 0 ) {
global $ydb;
switch( $filter ) {
case 'bottom':
$sort_by = 'clicks';
$sort_order = 'asc';
break;
case 'last':
$sort_by = 'timestamp';
$sort_order = 'desc';
break;
case 'rand':
case 'random':
$sort_by = 'RAND()';
$sort_order = '';
break;
case 'top':
default:
$sort_by = 'clicks';
$sort_order = 'desc';
break;
}
// Fetch links
$limit = intval( $limit );
$start = intval( $start );
if ( $limit > 0 ) {
$table_url = YOURLS_DB_TABLE_URL;
$results = $ydb->get_results( "SELECT * FROM `$table_url` WHERE 1=1 ORDER BY `$sort_by` $sort_order LIMIT $start, $limit;" );
$return = array();
$i = 1;
foreach ( (array)$results as $res ) {
$return['links']['link_'.$i++] = array(
'shorturl' => YOURLS_SITE .'/'. $res->keyword,
'url' => $res->url,
'title' => $res->title,
'timestamp'=> $res->timestamp,
'ip' => $res->ip,
'clicks' => $res->clicks,
);
}
}
$return['stats'] = yourls_get_db_stats();
$return['statusCode'] = 200;
return yourls_apply_filter( 'get_stats', $return, $filter, $limit, $start );
}
/**
* Return array of stats. (string)$filter is 'bottom', 'last', 'rand' or 'top'. (int)$limit is the number of links to return
*
*/
function yourls_get_link_stats( $shorturl ) {
global $ydb;
$table_url = YOURLS_DB_TABLE_URL;
$shorturl = yourls_escape( yourls_sanitize_keyword( $shorturl ) );
$res = $ydb->get_row( "SELECT * FROM `$table_url` WHERE keyword = '$shorturl';" );
$return = array();
if( !$res ) {
// non existent link
$return = array(
'statusCode' => 404,
'message' => 'Error: short URL not found',
);
} else {
$return = array(
'statusCode' => 200,
'message' => 'success',
'link' => array(
'shorturl' => YOURLS_SITE .'/'. $res->keyword,
'url' => $res->url,
'title' => $res->title,
'timestamp'=> $res->timestamp,
'ip' => $res->ip,
'clicks' => $res->clicks,
)
);
}
return yourls_apply_filter( 'get_link_stats', $return, $shorturl );
}
/**
* Get total number of URLs and sum of clicks. Input: optional "AND WHERE" clause. Returns array
*
* IMPORTANT NOTE: make sure arguments for the $where clause have been sanitized and yourls_escape()'d
* before calling this function.
*
*/
function yourls_get_db_stats( $where = '' ) {
global $ydb;
$table_url = YOURLS_DB_TABLE_URL;
$totals = $ydb->get_row( "SELECT COUNT(keyword) as count, SUM(clicks) as sum FROM `$table_url` WHERE 1=1 $where" );
$return = array( 'total_links' => $totals->count, 'total_clicks' => $totals->sum );
return yourls_apply_filter( 'get_db_stats', $return, $where );
}
/**
* Get number of SQL queries performed
*
*/
function yourls_get_num_queries() {
global $ydb;
return yourls_apply_filter( 'get_num_queries', $ydb->num_queries );
}
/**
* Returns a sanitized a user agent string. Given what I found on http://www.user-agents.org/ it should be OK.
*
*/
function yourls_get_user_agent() {
if ( !isset( $_SERVER['HTTP_USER_AGENT'] ) )
return '-';
$ua = strip_tags( html_entity_decode( $_SERVER['HTTP_USER_AGENT'] ));
$ua = preg_replace('![^0-9a-zA-Z\':., /{}\(\)\[\]\+@&\!\?;_\-=~\*\#]!', '', $ua );
return yourls_apply_filter( 'get_user_agent', substr( $ua, 0, 254 ) );
}
/**
* Redirect to another page
*
*/
function yourls_redirect( $location, $code = 301 ) {
yourls_do_action( 'pre_redirect', $location, $code );
$location = yourls_apply_filter( 'redirect_location', $location, $code );
$code = yourls_apply_filter( 'redirect_code', $code, $location );
// Redirect, either properly if possible, or via Javascript otherwise
if( !headers_sent() ) {
yourls_status_header( $code );
header( "Location: $location" );
} else {
yourls_redirect_javascript( $location );
}
die();
}
/**
* Set HTTP status header
*
*/
function yourls_status_header( $code = 200 ) {
if( headers_sent() )
return;
$protocol = $_SERVER['SERVER_PROTOCOL'];
if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
$protocol = 'HTTP/1.0';
$code = intval( $code );
$desc = yourls_get_HTTP_status( $code );
@header ("$protocol $code $desc"); // This causes problems on IIS and some FastCGI setups
yourls_do_action( 'status_header', $code );
}
/**
* Redirect to another page using Javascript. Set optional (bool)$dontwait to false to force manual redirection (make sure a message has been read by user)
*
*/
function yourls_redirect_javascript( $location, $dontwait = true ) {
yourls_do_action( 'pre_redirect_javascript', $location, $dontwait );
$location = yourls_apply_filter( 'redirect_javascript', $location, $dontwait );
if( $dontwait ) {
$message = yourls_s( 'if you are not redirected after 10 seconds, please <a href="%s">click here</a>', $location );
echo <<<REDIR
<script type="text/javascript">
window.location="$location";
</script>
<small>($message)</small>
REDIR;
} else {
echo '<p>' . yourls_s( 'Please <a href="%s">click here</a>', $location ) . '</p>';
}
yourls_do_action( 'post_redirect_javascript', $location );
}
/**
* Return a HTTP status code
*
*/
function yourls_get_HTTP_status( $code ) {
$code = intval( $code );
$headers_desc = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
510 => 'Not Extended'
);
if ( isset( $headers_desc[$code] ) )
return $headers_desc[$code];
else
return '';
}
/**
* Log a redirect (for stats)
*
* This function does not check for the existence of a valid keyword, in order to save a query. Make sure the keyword
* exists before calling it.
*
* @since 1.4
* @param string $keyword short URL keyword
* @return mixed Result of the INSERT query (1 on success)
*/
function yourls_log_redirect( $keyword ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_log_redirect', false, $keyword );
if ( false !== $pre )
return $pre;
if ( !yourls_do_log_redirect() )
return true;
global $ydb;
$table = YOURLS_DB_TABLE_LOG;
$keyword = yourls_escape( yourls_sanitize_string( $keyword ) );
$referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? yourls_escape( yourls_sanitize_url( $_SERVER['HTTP_REFERER'] ) ) : 'direct' );
$ua = yourls_escape( yourls_get_user_agent() );
$ip = yourls_escape( yourls_get_IP() );
$location = yourls_escape( yourls_geo_ip_to_countrycode( $ip ) );
return $ydb->query( "INSERT INTO `$table` (click_time, shorturl, referrer, user_agent, ip_address, country_code) VALUES (NOW(), '$keyword', '$referrer', '$ua', '$ip', '$location')" );
}
/**
* Check if we want to not log redirects (for stats)
*
*/
function yourls_do_log_redirect() {
return ( !defined( 'YOURLS_NOSTATS' ) || YOURLS_NOSTATS != true );
}
/**
* Converts an IP to a 2 letter country code, using GeoIP database if available in includes/geo/
*
* @since 1.4
* @param string $ip IP or, if empty string, will be current user IP
* @param string $defaut Default string to return if IP doesn't resolve to a country (malformed, private IP...)
* @return string 2 letter country code (eg 'US') or $default
*/
function yourls_geo_ip_to_countrycode( $ip = '', $default = '' ) {
// Allow plugins to short-circuit the Geo IP API
$location = yourls_apply_filter( 'shunt_geo_ip_to_countrycode', false, $ip, $default ); // at this point $ip can be '', check if your plugin hooks in here
if ( false !== $location )
return $location;
if ( $ip == '' )
$ip = yourls_get_IP();
// Use IPv4 or IPv6 DB & functions
if( false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
$db = 'GeoIP.dat';
$func = 'geoip_country_code_by_addr';
} else {
$db = 'GeoIPv6.dat';
$func = 'geoip_country_code_by_addr_v6';
}
if ( !file_exists( YOURLS_INC . '/geo/' . $db ) || !file_exists( YOURLS_INC .'/geo/geoip.inc' ) )
return $default;
require_once( YOURLS_INC . '/geo/geoip.inc' );
$gi = geoip_open( YOURLS_INC . '/geo/' . $db, GEOIP_STANDARD );
try {
$location = call_user_func( $func, $gi, $ip );
} catch ( Exception $e ) {
$location = '';
}
geoip_close( $gi );
if( '' == $location )
$location = $default;
return yourls_apply_filter( 'geo_ip_to_countrycode', $location, $ip, $default );
}
/**
* Converts a 2 letter country code to long name (ie AU -> Australia)
*
*/
function yourls_geo_countrycode_to_countryname( $code ) {
// Allow plugins to short-circuit the Geo IP API
$country = yourls_apply_filter( 'shunt_geo_countrycode_to_countryname', false, $code );
if ( false !== $country )
return $country;
// Load the Geo class if not already done
if( !class_exists( 'GeoIP', false ) ) {
$temp = yourls_geo_ip_to_countrycode( '127.0.0.1' );
}
if( class_exists( 'GeoIP', false ) ) {
$geo = new GeoIP;
$id = $geo->GEOIP_COUNTRY_CODE_TO_NUMBER[ $code ];
$long = $geo->GEOIP_COUNTRY_NAMES[ $id ];
return $long;
} else {
return false;
}
}
/**
* Return flag URL from 2 letter country code
*
*/
function yourls_geo_get_flag( $code ) {
if( file_exists( YOURLS_INC.'/geo/flags/flag_'.strtolower($code).'.gif' ) ) {
$img = yourls_match_current_protocol( YOURLS_SITE.'/includes/geo/flags/flag_'.( strtolower( $code ) ).'.gif' );
} else {
$img = false;
}
return yourls_apply_filter( 'geo_get_flag', $img, $code );
}
/**
* Check if an upgrade is needed
*
*/
function yourls_upgrade_is_needed() {
// check YOURLS_DB_VERSION exist && match values stored in YOURLS_DB_TABLE_OPTIONS
list( $currentver, $currentsql ) = yourls_get_current_version_from_sql();
if( $currentsql < YOURLS_DB_VERSION )
return true;
return false;
}
/**
* Get current version & db version as stored in the options DB. Prior to 1.4 there's no option table.
*
*/
function yourls_get_current_version_from_sql() {
$currentver = yourls_get_option( 'version' );
$currentsql = yourls_get_option( 'db_version' );
// Values if version is 1.3
if( !$currentver )
$currentver = '1.3';
if( !$currentsql )
$currentsql = '100';
return array( $currentver, $currentsql);
}
/**
* Read an option from DB (or from cache if available). Return value or $default if not found
*
* Pretty much stolen from WordPress
*
* @since 1.4
* @param string $option Option name. Expected to not be SQL-escaped.
* @param mixed $default Optional value to return if option doesn't exist. Default false.
* @return mixed Value set for the option.
*/
function yourls_get_option( $option_name, $default = false ) {
global $ydb;
// Allow plugins to short-circuit options
$pre = yourls_apply_filter( 'shunt_option_'.$option_name, false );
if ( false !== $pre )
return $pre;
// If option not cached already, get its value from the DB
if ( !isset( $ydb->option[$option_name] ) ) {
$table = YOURLS_DB_TABLE_OPTIONS;
$option_name = yourls_escape( $option_name );
$row = $ydb->get_row( "SELECT `option_value` FROM `$table` WHERE `option_name` = '$option_name' LIMIT 1" );
if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
$value = $row->option_value;
} else { // option does not exist, so we must cache its non-existence
$value = $default;
}
$ydb->option[ $option_name ] = yourls_maybe_unserialize( $value );
}
return yourls_apply_filter( 'get_option_'.$option_name, $ydb->option[$option_name] );
}
/**
* Read all options from DB at once
*
* The goal is to read all options at once and then populate array $ydb->option, to prevent further
* SQL queries if we need to read an option value later.
* It's also a simple check whether YOURLS is installed or not (no option = assuming not installed) after
* a check for DB server reachability has been performed
*
* @since 1.4
*/