-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions-base.php
More file actions
1955 lines (1701 loc) · 48.8 KB
/
Copy pathfunctions-base.php
File metadata and controls
1955 lines (1701 loc) · 48.8 KB
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
/**
* The Config class provides a set of static properties and methods which store
* and facilitate configuration of the theme.
**/
class ArgumentException extends Exception{}
class Config{
static
$body_classes = array(), # Body classes
$theme_settings = array(), # Theme settings
$custom_post_types = array(), # Custom post types to register
$custom_taxonomies = array(), # Custom taxonomies to register
$styles = array(), # Stylesheets to register
$scripts = array(), # Scripts to register
$links = array(), # <link>s to include in <head>
$metas = array(); # <meta>s to include in <head>
/**
* Creates and returns a normalized name for a resource url defined by $src.
**/
static function generate_name($src, $ignore_suffix=''){
$base = basename($src, $ignore_suffix);
$name = slug($base);
return $name;
}
/**
* Registers a stylesheet with built-in wordpress style registration.
* Arguments to this can either be a string or an array with required css
* attributes.
*
* A string argument will be treated as the src value for the css, and all
* other attributes will default to the most common values. To override
* those values, you must pass the attribute array.
*
* Array Argument:
* $attr = array(
* 'name' => 'theme-style', # Wordpress uses this to identify queued files
* 'media' => 'all', # What media types this should apply to
* 'admin' => False, # Should this be used in admin as well?
* 'src' => 'http://some.domain/style.css',
* );
**/
static function add_css($attr){
# Allow string arguments, defining source.
if (is_string($attr)){
$new = array();
$new['src'] = $attr;
$attr = $new;
}
if (!isset($attr['src'])){
throw new ArgumentException('add_css expects argument array to contain key "src"');
}
$default = array(
'name' => self::generate_name($attr['src'], '.css'),
'media' => 'all',
'admin' => False,
);
$attr = array_merge($default, $attr);
$is_admin = (is_admin() or is_login());
if (
($attr['admin'] and $is_admin) or
(!$attr['admin'] and !$is_admin)
){
wp_deregister_style($attr['name']);
wp_enqueue_style($attr['name'], $attr['src'], null, null, $attr['media']);
}
}
/**
* Functions similar to add_css, but appends scripts to the footer instead.
* Accepts a string or array argument, like add_css, with the string
* argument assumed to be the src value for the script.
*
* Array Argument:
* $attr = array(
* 'name' => 'jquery', # Wordpress uses this to identify queued files
* 'admin' => False, # Should this be used in admin as well?
* 'src' => 'http://some.domain/style.js',
* );
**/
static function add_script($attr){
# Allow string arguments, defining source.
if (is_string($attr)){
$new = array();
$new['src'] = $attr;
$attr = $new;
}
if (!isset($attr['src'])){
throw new ArgumentException('add_script expects argument array to contain key "src"');
}
$default = array(
'name' => self::generate_name($attr['src'], '.js'),
'admin' => False,
);
$attr = array_merge($default, $attr);
$is_admin = (is_admin() or is_login());
if (
($attr['admin'] and $is_admin) or
(!$attr['admin'] and !$is_admin)
){
# Override previously defined scripts
wp_deregister_script($attr['name']);
wp_enqueue_script($attr['name'], $attr['src'], null, null, True);
}
}
}
/**
* Abstracted field class, all form fields should inherit from this.
*
* @package default
* @author Jared Lang
**/
abstract class Field{
protected function check_for_default(){
if ($this->value === null){
$this->value = $this->default;
}
}
function __construct($attr){
$this->name = @$attr['name'];
$this->id = @$attr['id'];
$this->value = @$attr['value'];
$this->description = @$attr['description'];
$this->default = @$attr['default'];
$this->check_for_default();
}
function label_html(){
ob_start();
?>
<label class="block" for="<?=htmlentities($this->id)?>"><?=__($this->name)?></label>
<?php
return ob_get_clean();
}
function input_html(){
return "Abstract Input Field, Override in Descendants";
}
function description_html(){
ob_start();
?>
<?php if($this->description):?>
<p class="description"><?=__($this->description)?></p>
<?php endif;?>
<?php
return ob_get_clean();
}
function html(){
$label = $this->label_html();
$input = $this->input_html();
$description = $this->description_html();
return $label.$input.$description;
}
}
/**
* Abstracted choices field. Choices fields have an additional attribute named
* choices which allow a selection of values to be chosen from.
*
* @package default
* @author Jared Lang
**/
abstract class ChoicesField extends Field{
function __construct($attr){
$this->choices = @$attr['choices'];
parent::__construct($attr);
}
}
/**
* TextField class represents a simple text input
*
* @package default
* @author Jared Lang
**/
class TextField extends Field{
protected $type_attr = 'text';
function input_html(){
ob_start();
?>
<input type="<?=$this->type_attr?>" id="<?=htmlentities($this->id)?>" name="<?=htmlentities($this->id)?>" value="<?=htmlentities($this->value)?>" />
<?php
return ob_get_clean();
}
}
/**
* PasswordField can be used to accept sensitive information, not encrypted on
* wordpress' end however.
*
* @package default
* @author Jared Lang
**/
class PasswordField extends TextField{
protected $type_attr = 'password';
}
/**
* TextareaField represents a textarea form element
*
* @package default
* @author Jared Lang
**/
class TextareaField extends Field{
function input_html(){
ob_start();
?>
<textarea id="<?=htmlentities($this->id)?>" name="<?=htmlentities($this->id)?>"><?=htmlentities($this->value)?></textarea>
<?php
return ob_get_clean();
}
}
/**
* Select form element
*
* @package default
* @author Jared Lang
**/
class SelectField extends ChoicesField{
function input_html(){
ob_start();
?>
<select name="<?=htmlentities($this->id)?>" id="<?=htmlentities($this->id)?>">
<?php foreach($this->choices as $key=>$value):?>
<option<?php if($this->value == $value):?> selected="selected"<?php endif;?> value="<?=htmlentities($value)?>"><?=htmlentities($key)?></option>
<?php endforeach;?>
</select>
<?php
return ob_get_clean();
}
}
/**
* Radio form element
*
* @package default
* @author Jared Lang
**/
class RadioField extends ChoicesField{
function input_html(){
ob_start();
?>
<ul class="radio-list">
<?php $i = 0; foreach($this->choices as $key=>$value): $id = htmlentities($this->id).'_'.$i++;?>
<li>
<input<?php if($this->value == $value):?> checked="checked"<?php endif;?> type="radio" name="<?=htmlentities($this->id)?>" id="<?=$id?>" value="<?=htmlentities($value)?>" />
<label for="<?=$id?>"><?=htmlentities($key)?></label>
</li>
<?php endforeach;?>
</ul>
<?php
return ob_get_clean();
}
}
/**
* Checkbox form element
*
* @package default
* @author Jared Lang
**/
class CheckboxField extends ChoicesField{
function input_html(){
ob_start();
?>
<ul class="checkbox-list">
<?php $i = 0; foreach($this->choices as $key=>$value): $id = htmlentities($this->id).'_'.$i++;?>
<li>
<input<?php if(is_array($this->value) and in_array($value, $this->value)):?> checked="checked"<?php endif;?> type="checkbox" name="<?=htmlentities($this->id)?>[]" id="<?=$id?>" value="<?=htmlentities($value)?>" />
<label for="<?=$id?>"><?=htmlentities($key)?></label>
</li>
<?php endforeach;?>
</ul>
<?php
return ob_get_clean();
}
}
/**
* Convenience class to calculate total execution times.
*
* @package default
* @author Jared Lang
**/
class Timer{
private $start_time = null;
private $end_time = null;
public function start_timer(){
$this->start_time = microtime(True);
$this->end_time = null;
}
public function stop_timer(){
$this->end_time = microtime(True);
}
public function clear_timer(){
$this->start_time = null;
$this->end_time = null;
}
public function reset_timer(){
$this->clear_timer();
$this->start_timer();
}
public function elapsed(){
if ($this->end_time !== null){
return $this->end_time - $this->start_time;
}else{
return microtime(True) - $this->start_time;
}
}
public function __toString(){
return $this->elapsed;
}
/**
* Returns a started instance of timer
*
* @return instance of Timer
* @author Jared Lang
**/
public static function start(){
$timer_instance = new self();
$timer_instance->start_timer();
return $timer_instance;
}
}
/**
* Strings passed to this function will be modified under the assumption that
* they were outputted by wordpress' the_output filter. It checks for a handful
* of things like empty, unnecessary, and unclosed tags.
*
* @return string
* @author Jared Lang
**/
function cleanup($content){
# Balance auto paragraphs
$lines = explode("\n", $content);
foreach($lines as $key=>$line){
$null = null;
$found_closed = preg_match_all('/<\/p>/', $line, $null);
$found_opened = preg_match_all('/<p[^>]*>/', $line, $null);
$diff = $found_closed - $found_opened;
# Balanced tags
if ($diff == 0){continue;}
# missing closed
if ($diff < 0){
$lines[$key] = $lines[$key] . str_repeat('</p>', abs($diff));
}
# missing open
if ($diff > 0){
$lines[$key] = str_repeat('<p>', abs($diff)) . $lines[$key];
}
}
$content = implode("\n", $lines);
#Remove incomplete tags at start and end
$content = preg_replace('/^<\/p>[\s]*/i', '', $content);
$content = preg_replace('/[\s]*<p>$/i', '', $content);
$content = preg_replace('/^<br \/>/i', '', $content);
$content = preg_replace('/<br \/>$/i', '', $content);
#Remove paragraph and linebreak tags wrapped around shortcodes
$content = preg_replace('/(<p>|<br \/>)\[/i', '[', $content);
$content = preg_replace('/\](<\/p>|<br \/>)/i', ']', $content);
#Remove empty paragraphs
$content = preg_replace('/<p><\/p>/i', '', $content);
return $content;
}
/**
* Return an array of choices representing all the images uploaded to the media
* gallery.
*
* @return array
* @author Jared Lang
**/
function get_image_choices(){
$image_mimes = array(
'image/jpeg',
'image/png',
);
$images = array('(None)' => null);
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'numberposts' => -1,
);
$attachments = get_posts($args);
$attachments = array_filter($attachments, function( $a ) {
$is_image = (strpos($a->post_mime_type, "image/") !== False);
return $is_image;
});
foreach($attachments as $image){
$filename = basename(get_attached_file($image->ID));
$value = $image->ID;
$key = $image->post_title. " | {$filename}";
$images[$key] = $value;
}
return $images;
}
/**
* Given a mimetype, will attempt to return a string representing the
* application it is associated with. If the mimetype is unknown, the default
* return is 'document'.
*
* @return string
* @author Jared Lang
**/
function mimetype_to_application($mimetype){
switch($mimetype){
default:
$type = 'document';
break;
case 'text/html':
$type = "html";
break;
case 'application/zip':
$type = "zip";
break;
case 'application/pdf':
$type = 'pdf';
break;
case 'application/msword':
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
$type = 'word';
break;
case 'application/msexcel':
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
$type = 'excel';
break;
case 'application/vnd.ms-powerpoint':
case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
$type = 'powerpoint';
break;
}
return $type;
}
/**
* Fetches objects defined by arguments passed, outputs the objects according
* to the objectsToHTML method located on the object. Used by the auto
* generated shortcodes enabled on custom post types. See also:
*
* CustomPostType::objectsToHTML
* CustomPostType::toHTML
*
* @return string
* @author Jared Lang
**/
function sc_object_list($attr, $default_content=null){
if (!is_array($attr)){return '';}
# set defaults and combine with passed arguments
$defaults = array(
'type' => null,
'limit' => -1,
'join' => 'or',
'class' => '',
);
$options = array_merge($defaults, $attr);
# verify options
if ($options['type'] == null){
return '<p class="error">No type defined for object list.</p>';
}
if (!is_numeric($options['limit'])){
return '<p class="error">Invalid limit argument, must be a number.</p>';
}
if (!in_array(strtoupper($options['join']), array('AND', 'OR'))){
return '<p class="error">Invalid join type, must be one of "and" or "or".</p>';
}
if (null == ($class = get_custom_post_type($options['type']))){
return '<p class="error">Invalid post type.</p>';
}
# get taxonomies and translation
$translate = array(
'tags' => 'post_tag',
'categories' => 'category',
);
$taxonomies = array_diff(array_keys($attr), array_keys($defaults));
# assemble taxonomy query
$tax_queries = array();
$tax_queries['relation'] = strtoupper($options['join']);
foreach($taxonomies as $tax){
$terms = $options[$tax];
$terms = trim(preg_replace('/\s+/', ' ', $terms));
$terms = explode(' ', $terms);
if (array_key_exists($tax, $translate)){
$tax = $translate[$tax];
}
$tax_queries[] = array(
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $terms,
);
}
# perform query
$query_array = array(
'tax_query' => $tax_queries,
'post_status' => 'publish',
'post_type' => $options['type'],
'posts_per_page' => $options['limit'],
'orderby' => 'menu_order title',
'order' => 'ASC',
);
$class = new $class;
$objects = $class->get_objects($query_array);
if (count($objects)){
$html = $class->objectsToHTML($objects, $options['class']);
}else{
$html = $default_content;
}
return $html;
}
/**
* Creates an array of shortcodes mapped to a documentation string for that
* shortcode. Used to generate the auto shortcode documentation.
*
* @return array
* @author Jared Lang
**/
function shortcodes(){
$file = file_get_contents(THEME_DIR.'/shortcodes.php');
$documentation = "\/\*\*(?P<documentation>.*?)\*\*\/";
$declaration = "function[\s]+(?P<declaration>[^\(]+)";
# Auto generated shortcode documentation.
$codes = array();
$auto = array_filter(installed_custom_post_types(), function( $c ) {
return $c->options("use_shortcode");
});
foreach($auto as $code){
$scode = $code->options('name').'-list';
$plural = $code->options('plural_name');
$doc = <<<DOC
Outputs a list of {$plural} filtered by arbitrary taxonomies, for example a tag
or category. A default output for when no objects matching the criteria are
found.
Example:
# Output a maximum of 5 items tagged foo or bar, with a default output.
[{$scode} tags="foo bar" limit="5"]No {$plural} were found.[/{$scode}]
# Output all objects categorized as foo
[{$scode} categories="foo"]
# Output all objects matching the terms in the custom taxonomy named foo
[{$scode} foo="term list example"]
# Outputs all objects found categorized as staff and tagged as small.
[{$scode} limit="5" join="and" categories="staff" tags="small"]
DOC;
$codes[] = array(
'documentation' => $doc,
'shortcode' => $scode,
);
}
# Defined shortcode documentation
$found = preg_match_all("/{$documentation}\s*{$declaration}/is", $file, $matches);
if ($found){
foreach ($matches['declaration'] as $key=>$match){
$codes[$match]['documentation'] = $matches['documentation'][$key];
$codes[$match]['shortcode'] = str_replace(
array('sc_', '_',),
array('', '-',),
$matches['declaration'][$key]
);
}
}
return $codes;
}
/**
* Returns true if the current request is on the login screen.
*
* @return boolean
* @author Jared Lang
**/
function is_login(){
return in_array($GLOBALS['pagenow'], array(
'wp-login.php',
'wp-register.php',
));
}
/**
* Given an arbitrary number of arguments, will return a string with the
* arguments dumped recursively, similar to the output of print_r but with pre
* tags wrapped around the output.
*
* @return string
* @author Jared Lang
**/
function dump(){
$args = func_get_args();
$out = array();
foreach($args as $arg){
$out[] = print_r($arg, True);
}
$out = implode("<br />", $out);
return "<pre>{$out}</pre>";
}
/**
* Will add a debug comment to the output when the debug constant is set true.
* Any value, including null, is enough to trigger it.
*
* @return void
* @author Jared Lang
**/
if (DEBUG){
function debug($string){
print "<!-- DEBUG: {$string} -->\n";
}
}else{
function debug($string){return;}
}
/**
* Will execute the function $func with the arguments passed via $args if the
* debug constant is set true. Returns whatever value the called function
* returns, or void if debug is not set active.
*
* @return mixed
* @author Jared Lang
**/
if (DEBUG){
function debug_callfunc($func, $args){
return call_user_func_array($func, $args);
}
}else{
function debug_callfunc($func, $args){return;}
}
/**
* Sets the default values for any theme options that are not currently stored.
*
* @return void
* @author Jared Lang
**/
function set_defaults_for_options(){
$values = get_option(THEME_OPTIONS_NAME);
if ($values === False or is_string($values)){
add_option(THEME_OPTIONS_NAME);
$values = array();
}
$options = array();
foreach(Config::$theme_settings as $option){
if (is_array($option)){
$options = array_merge($option, $options);
}else{
$options[] = $option;
}
}
foreach ($options as $option){
$key = str_replace(
array(THEME_OPTIONS_NAME, '[', ']'),
array('', '', ''),
$option->id
);
if ($option->default !== null and !isset($values[$key])){
$values[$key] = $option->default;
update_option(THEME_OPTIONS_NAME, $values);
}
}
}
/**
* Responsible for running code that needs to be executed as wordpress is
* initializing. Good place to register scripts, stylesheets, theme elements,
* etc.
*
* @return void
* @author Jared Lang
**/
function __init__(){
add_theme_support('menus');
add_theme_support('post-thumbnails');
add_image_size('homepage', 620);
add_image_size('single-post-thumbnail', 220, 230, true);
add_image_size('personnel-img', 110, 128, false);
register_nav_menu('header-menu', __('Header Menu'));
register_nav_menu('footer-menu', __('Footer Menu'));
register_sidebar(array(
'name' => __('Sidebar'),
'id' => 'sidebar',
'description' => 'Sidebar found on two column page templates and search pages',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
/*
register_sidebar(array(
'name' => __('Below the Fold - Left'),
'id' => 'bottom-left',
'description' => 'Left column on the bottom of pages, after flickr images if enabled.',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
register_sidebar(array(
'name' => __('Below the Fold - Center'),
'id' => 'bottom-center',
'description' => 'Center column on the bottom of pages, after news if enabled.',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
register_sidebar(array(
'name' => __('Below the Fold - Right'),
'id' => 'bottom-right',
'description' => 'Right column on the bottom of pages, after events if enabled.',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
*/
register_sidebar(array(
'name' => __('Footer - Column One'),
'id' => 'bottom-one',
'description' => 'Far left column in footer on the bottom of pages.',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
register_sidebar(array(
'name' => __('Footer - Column Two'),
'id' => 'bottom-two',
'description' => 'Second column from the left in footer, on the bottom of pages.',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
register_sidebar(array(
'name' => __('Footer - Column Three'),
'id' => 'bottom-three',
'description' => 'Third column from the left in footer, on the bottom of pages.',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
register_sidebar(array(
'name' => __('Footer - Column Four'),
'id' => 'bottom-four',
'description' => 'Far right in footer on the bottom of pages.',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
));
foreach(Config::$styles as $style){Config::add_css($style);}
foreach(Config::$scripts as $script){Config::add_script($script);}
global $timer;
$timer = Timer::start();
wp_deregister_script('l10n');
set_defaults_for_options();
}
add_action('after_setup_theme', '__init__');
/**
* Runs as wordpress is shutting down.
*
* @return void
* @author Jared Lang
**/
function __shutdown__(){
global $timer;
$elapsed = round($timer->elapsed() * 1000);
debug("{$elapsed} milliseconds");
}
add_action('shutdown', '__shutdown__');
/**
* Using the user defined value for Flickr ID set in the admin, will return the
* photostream URL for that ID. Will return null if no id is set.
*
* @return string
* @author Jared Lang
**/
function get_flickr_feed_url(){
$rss_url = "http://api.flickr.com/services/feeds/photos_public.gne?id=%s&lang=en-us&format=rss_200";
$options = get_option(THEME_OPTIONS_NAME);
$id = $options['flickr_id'];
if ($id){
return sprintf($rss_url, $id);
}else{
return null;
}
}
function get_flickr_stream_url(){
$rss_url = "http://flickr.com/photos/%s";
$options = get_option(THEME_OPTIONS_NAME);
$id = $options['flickr_id'];
if ($id){
return sprintf($rss_url, $id);
}else{
return null;
}
}
function get_article_image($article){
$image = $article->get_enclosure();
if ($image){
return ($image->get_thumbnail()) ? $image->get_thumbnail() : $image->get_link();
}else{
$matches = array();
$found = preg_match('/<img[^>]+src=[\'\"]([^\'\"]+)[\'\"][^>]+>/i', $article->get_content(), $matches);
if($found){
return $matches[1];
}
}
return null;
}
/**
* Handles fetching and processing of feeds. Currently uses SimplePie to parse
* retrieved feeds, and automatically handles caching of content fetches.
* Multiple calls to the same feed url will not result in multiple parsings, per
* request as they are stored in memory for later use.
**/
class FeedManager{
static private
$feeds = array(),
$cache_length = 0xD2F0;
/**
* Provided a URL, will return an array representing the feed item for that
* URL. A feed item contains the content, url, simplepie object, and failure
* status for the URL passed. Handles caching of content requests.
*
* @return array
* @author Jared Lang
**/
static protected function __new_feed($url){
$timer = Timer::start();
require_once ABSPATH . '/wp-includes/class-simplepie.php';
$simplepie = null;
$failed = False;
$cache_key = 'feedmanager-'.md5($url);
$content = get_site_transient($cache_key);
if ($content === False){
$content = wp_remote_retrieve_body( wp_remote_get( $url ) );
if ( ! $content ){
$failed = True;
$content = null;
error_log('FeedManager failed to fetch data using url of '.$url);
}else{
set_site_transient($cache_key, $content, self::$cache_length);
}
}
if ($content){
$simplepie = new SimplePie();
$simplepie->set_raw_data($content);
$simplepie->init();
$simplepie->handle_content_type();
if ($simplepie->error){
error_log($simplepie->error);
$simplepie = null;
$failed = True;
}
}else{
$failed = True;
}
$elapsed = round($timer->elapsed() * 1000);
debug("__new_feed: {$elapsed} milliseconds");
return array(
'content' => $content,
'url' => $url,
'simplepie' => $simplepie,
'failed' => $failed,
);
}
/**
* Returns all the items for a given feed defined by URL
*
* @return array
* @author Jared Lang
**/
static protected function __get_items($url){
if (!array_key_exists($url, self::$feeds)){
self::$feeds[$url] = self::__new_feed($url);
}
if (!self::$feeds[$url]['failed']){
return self::$feeds[$url]['simplepie']->get_items();
}else{
return array();
}
}
/**
* Retrieve the current cache expiration value.
*
* @return void
* @author Jared Lang
**/
static public function get_cache_expiration(){
return self::$cache_length;
}
/**
* Set the cache expiration length for all feeds from this manager.
*
* @return void
* @author Jared Lang
**/
static public function set_cache_expiration($expire){
if (is_number($expire)){
self::$cache_length = (int)$expire;
}
}
/**
* Returns all items from the feed defined by URL and limited by the start
* and limit arguments.
*
* @return array
* @author Jared Lang
**/
static public function get_items($url, $start=null, $limit=null){
if ($start === null){$start = 0;}
$items = self::__get_items($url);
$items = array_slice($items, $start, $limit);
return $items;