Ticket #2984: functions.php

File functions.php, 71.1 KB (added by ttscoff, 6 years ago)
Line 
1<?php
2
3require_once(dirname(__FILE__).'/functions-compat.php');
4
5if ( !function_exists('_') ) {
6        function _($string) {
7                return $string;
8        }
9}
10
11function get_profile($field, $user = false) {
12        global $wpdb;
13        if ( !$user )
14                $user = $wpdb->escape($_COOKIE[USER_COOKIE]);
15        return $wpdb->get_var("SELECT $field FROM $wpdb->users WHERE user_login = '$user'");
16}
17
18function mysql2date($dateformatstring, $mysqlstring, $translate = true) {
19        global $month, $weekday, $month_abbrev, $weekday_abbrev;
20        $m = $mysqlstring;
21        if ( empty($m) ) {
22                return false;
23        }
24        $i = mktime(substr($m,11,2),substr($m,14,2),substr($m,17,2),substr($m,5,2),substr($m,8,2),substr($m,0,4));
25       
26        if ( -1 == $i || false == $i )
27                $i = 0;
28
29        if ( !empty($month) && !empty($weekday) && $translate ) {
30                $datemonth = $month[date('m', $i)];
31                $datemonth_abbrev = $month_abbrev[$datemonth];
32                $dateweekday = $weekday[date('w', $i)];
33                $dateweekday_abbrev = $weekday_abbrev[$dateweekday];
34                $dateformatstring = ' '.$dateformatstring;
35                $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
36                $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
37                $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
38                $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
39
40                $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
41        }
42        $j = @date($dateformatstring, $i);
43        if ( !$j ) {
44        // for debug purposes
45        //      echo $i." ".$mysqlstring;
46        }
47        return $j;
48}
49
50function current_time($type, $gmt = 0) {
51        switch ($type) {
52                case 'mysql':
53                        if ( $gmt ) $d = gmdate('Y-m-d H:i:s');
54                        else $d = gmdate('Y-m-d H:i:s', (time() + (get_settings('gmt_offset') * 3600)));
55                        return $d;
56                        break;
57                case 'timestamp':
58                        if ( $gmt ) $d = time();
59                        else $d = time() + (get_settings('gmt_offset') * 3600);
60                        return $d;
61                        break;
62        }
63}
64
65function date_i18n($dateformatstring, $unixtimestamp) {
66        global $month, $weekday, $month_abbrev, $weekday_abbrev;
67        $i = $unixtimestamp;
68        if ( (!empty($month)) && (!empty($weekday)) ) {
69                $datemonth = $month[date('m', $i)];
70                $datemonth_abbrev = $month_abbrev[$datemonth];
71                $dateweekday = $weekday[date('w', $i)];
72                $dateweekday_abbrev = $weekday_abbrev[$dateweekday];
73                $dateformatstring = ' '.$dateformatstring;
74                $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
75                $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
76                $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
77                $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
78                $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
79        }
80        $j = @date($dateformatstring, $i);
81        return $j;
82        }
83
84function get_weekstartend($mysqlstring, $start_of_week) {
85        $my = substr($mysqlstring,0,4);
86        $mm = substr($mysqlstring,8,2);
87        $md = substr($mysqlstring,5,2);
88        $day = mktime(0,0,0, $md, $mm, $my);
89        $weekday = date('w',$day);
90        $i = 86400;
91
92        if ( $weekday < get_settings('start_of_week') )
93                $weekday = 7 - (get_settings('start_of_week') - $weekday);
94
95        while ($weekday > get_settings('start_of_week')) {
96                $weekday = date('w',$day);
97                if ( $weekday < get_settings('start_of_week') )
98                        $weekday = 7 - (get_settings('start_of_week') - $weekday);
99
100                $day = $day - 86400;
101                $i = 0;
102        }
103        $week['start'] = $day + 86400 - $i;
104        // $week['end'] = $day - $i + 691199;
105        $week['end'] = $week['start'] + 604799;
106        return $week;
107}
108
109function get_lastpostdate($timezone = 'server') {
110        global $cache_lastpostdate, $pagenow, $wpdb;
111        $add_seconds_blog = get_settings('gmt_offset') * 3600;
112        $add_seconds_server = date('Z');
113        $now = current_time('mysql', 1);
114        if ( !isset($cache_lastpostdate[$timezone]) ) {
115                switch(strtolower($timezone)) {
116                        case 'gmt':
117                                $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
118                                break;
119                        case 'blog':
120                                $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
121                                break;
122                        case 'server':
123                                $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
124                                break;
125                }
126                $cache_lastpostdate[$timezone] = $lastpostdate;
127        } else {
128                $lastpostdate = $cache_lastpostdate[$timezone];
129        }
130        return $lastpostdate;
131}
132
133function get_lastpostmodified($timezone = 'server') {
134        global $cache_lastpostmodified, $pagenow, $wpdb;
135        $add_seconds_blog = get_settings('gmt_offset') * 3600;
136        $add_seconds_server = date('Z');
137        $now = current_time('mysql', 1);
138        if ( !isset($cache_lastpostmodified[$timezone]) ) {
139                switch(strtolower($timezone)) {
140                        case 'gmt':
141                                $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
142                                break;
143                        case 'blog':
144                                $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
145                                break;
146                        case 'server':
147                                $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
148                                break;
149                }
150                $lastpostdate = get_lastpostdate($timezone);
151                if ( $lastpostdate > $lastpostmodified ) {
152                        $lastpostmodified = $lastpostdate;
153                }
154                $cache_lastpostmodified[$timezone] = $lastpostmodified;
155        } else {
156                $lastpostmodified = $cache_lastpostmodified[$timezone];
157        }
158        return $lastpostmodified;
159}
160
161function user_pass_ok($user_login,$user_pass) {
162        global $cache_userdata;
163        if ( empty($cache_userdata[$user_login]) ) {
164                $userdata = get_userdatabylogin($user_login);
165        } else {
166                $userdata = $cache_userdata[$user_login];
167        }
168        return (md5($user_pass) == $userdata->user_pass);
169}
170
171
172function get_usernumposts($userid) {
173        global $wpdb;
174        return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid' AND post_status = 'publish'");
175}
176
177
178// examine a url (supposedly from this blog) and try to
179// determine the post ID it represents.
180function url_to_postid($url) {
181        global $wp_rewrite;
182
183        // First, check to see if there is a 'p=N' or 'page_id=N' to match against
184        preg_match('#[?&](p|page_id)=(\d+)#', $url, $values);
185        $id = intval($values[2]);
186        if ( $id ) return $id;
187
188        // Check to see if we are using rewrite rules
189        $rewrite = $wp_rewrite->wp_rewrite_rules();
190
191        // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
192        if ( empty($rewrite) )
193                return 0;
194
195        // $url cleanup by Mark Jaquith
196        // This fixes things like #anchors, ?query=strings, missing 'www.',
197        // added 'www.', or added 'index.php/' that will mess up our WP_Query
198        // and return a false negative
199
200        // Get rid of the #anchor
201        $url_split = explode('#', $url);
202        $url = $url_split[0];
203
204        // Get rid of URI ?query=string
205        $url_split = explode('?', $url);
206        $url = $url_split[0];
207
208        // Add 'www.' if it is absent and should be there
209        if ( false !== strpos(get_settings('home'), '://www.') && false === strpos($url, '://www.') )
210                $url = str_replace('://', '://www.', $url);
211
212        // Strip 'www.' if it is present and shouldn't be
213        if ( false === strpos(get_settings('home'), '://www.') )
214                $url = str_replace('://www.', '://', $url);
215
216        // Strip 'index.php/' if we're not using path info permalinks
217        if ( false === strpos($rewrite, 'index.php/') )
218                $url = str_replace('index.php/', '', $url);
219
220        if ( false !== strpos($url, get_settings('home')) ) {
221                // Chop off http://domain.com
222                $url = str_replace(get_settings('home'), '', $url);
223        } else {
224                // Chop off /path/to/blog
225                $home_path = parse_url(get_settings('home'));
226                $home_path = $home_path['path'];
227                $url = str_replace($home_path, '', $url);
228        }
229
230        // Trim leading and lagging slashes
231        $url = trim($url, '/');
232
233        $request = $url;
234
235        // Done with cleanup
236
237        // Look for matches.
238        $request_match = $request;
239        foreach ($rewrite as $match => $query) {
240                // If the requesting file is the anchor of the match, prepend it
241                // to the path info.
242                if ( (! empty($url)) && (strpos($match, $url) === 0) ) {
243                        $request_match = $url . '/' . $request;
244                }
245
246                if ( preg_match("!^$match!", $request_match, $matches) ) {
247                        // Got a match.
248                        // Trim the query of everything up to the '?'.
249                        $query = preg_replace("!^.+\?!", '', $query);
250
251                        // Substitute the substring matches into the query.
252                        eval("\$query = \"$query\";");
253                        $query = new WP_Query($query);
254                        if ( $query->is_single || $query->is_page )
255                                return $query->post->ID;
256                        else
257                                return 0;
258                }
259        }
260        return 0;
261}
262
263
264function maybe_unserialize($original) {
265        if ( false !== $gm = @ unserialize($original) )
266                return $gm;
267        else
268                return $original;
269}
270
271/* Options functions */
272
273function get_settings($setting) {
274        global $wpdb;
275
276        $value = wp_cache_get($setting, 'options');
277
278        if ( false === $value ) {
279                if ( defined('WP_INSTALLING') )
280                        $wpdb->hide_errors();
281                $row = $wpdb->get_row("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1");
282                if ( defined('WP_INSTALLING') )
283                        $wpdb->show_errors();
284
285                if( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
286                        $value = $row->option_value;
287                        wp_cache_set($setting, $value, 'options');
288                } else {
289                        return false;
290                }
291        }
292
293        // If home is not set use siteurl.
294        if ( 'home' == $setting && '' == $value )
295                return get_settings('siteurl');
296
297        if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
298                $value = preg_replace('|/+$|', '', $value);
299
300        return apply_filters( 'option_' . $setting, maybe_unserialize($value) );
301}
302
303function get_option($option) {
304        return get_settings($option);
305}
306
307function get_user_option( $option, $user = 0 ) {
308        global $wpdb;
309       
310        if ( empty($user) )
311                $user = wp_get_current_user();
312        else
313                $user = get_userdata($user);
314
315        if ( isset( $user->{$wpdb->prefix . $option} ) ) // Blog specific
316                return $user->{$wpdb->prefix . $option};
317        elseif ( isset( $user->{$option} ) ) // User specific and cross-blog
318                return $user->{$option};
319        else // Blog global
320                return get_option( $option );
321}
322
323function form_option($option) {
324        echo htmlspecialchars( get_option($option), ENT_QUOTES );
325}
326
327function get_alloptions() {
328        global $wpdb, $wp_queries;
329        $wpdb->hide_errors();
330        if ( !$options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'") ) {
331                $options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
332        }
333        $wpdb->show_errors();
334
335        foreach ($options as $option) {
336                // "When trying to design a foolproof system,
337                //  never underestimate the ingenuity of the fools :)" -- Dougal
338                if ( 'siteurl' == $option->option_name )
339                        $option->option_value = preg_replace('|/+$|', '', $option->option_value);
340                if ( 'home' == $option->option_name )
341                        $option->option_value = preg_replace('|/+$|', '', $option->option_value);
342                if ( 'category_base' == $option->option_name )
343                        $option->option_value = preg_replace('|/+$|', '', $option->option_value);
344                $value = maybe_unserialize($option->option_value);
345                $all_options->{$option->option_name} = apply_filters('pre_option_' . $option->option_name, $value);
346        }
347        return apply_filters('all_options', $all_options);
348}
349
350function update_option($option_name, $newvalue) {
351        global $wpdb;
352
353        if ( is_string($newvalue) )
354                $newvalue = trim($newvalue);
355
356        // If the new and old values are the same, no need to update.
357        $oldvalue = get_option($option_name);
358        if ( $newvalue == $oldvalue ) {
359                return false;
360        }
361
362        if ( false === $oldvalue ) {
363                add_option($option_name, $newvalue);
364                return true;
365        }
366
367        $_newvalue = $newvalue;
368        if ( is_array($newvalue) || is_object($newvalue) )
369                $newvalue = serialize($newvalue);
370
371        wp_cache_set($option_name, $newvalue, 'options');
372
373        $newvalue = $wpdb->escape($newvalue);
374        $option_name = $wpdb->escape($option_name);
375        $wpdb->query("UPDATE $wpdb->options SET option_value = '$newvalue' WHERE option_name = '$option_name'");
376        if ( $wpdb->rows_affected == 1 ) {
377                do_action("update_option_{$option_name}", array('old'=>$oldvalue, 'new'=>$_newvalue));
378                return true;
379        }
380        return false;
381}
382
383function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
384        global $wpdb;
385        if ( !$global )
386                $option_name = $wpdb->prefix . $option_name;
387        return update_usermeta( $user_id, $option_name, $newvalue );
388}
389
390// thx Alex Stapleton, http://alex.vort-x.net/blog/
391function add_option($name, $value = '', $description = '', $autoload = 'yes') {
392        global $wpdb;
393
394        // Make sure the option doesn't already exist
395        if ( false !== get_option($name) )
396                return;
397
398        if ( is_array($value) || is_object($value) )
399                $value = serialize($value);
400
401        wp_cache_set($name, $value, 'options');
402
403        $name = $wpdb->escape($name);
404        $value = $wpdb->escape($value);
405        $description = $wpdb->escape($description);
406        $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, option_description, autoload) VALUES ('$name', '$value', '$description', '$autoload')");
407
408        return;
409}
410
411function delete_option($name) {
412        global $wpdb;
413        // Get the ID, if no ID then return
414        $option_id = $wpdb->get_var("SELECT option_id FROM $wpdb->options WHERE option_name = '$name'");
415        if ( !$option_id ) return false;
416        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = '$name'");
417        wp_cache_delete($name, 'options');
418        return true;
419}
420
421function add_post_meta($post_id, $key, $value, $unique = false) {
422        global $wpdb, $post_meta_cache;
423
424        if ( $unique ) {
425                if ( $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
426= '$key' AND post_id = '$post_id'") ) {
427                        return false;
428                }
429        }
430
431        $original = $value;
432        if ( is_array($value) || is_object($value) )
433                $value = $wpdb->escape(serialize($value));
434
435        $wpdb->query("INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) VALUES ('$post_id','$key','$value')");
436
437        $post_meta_cache['$post_id'][$key][] = $original;
438
439        return true;
440}
441
442function delete_post_meta($post_id, $key, $value = '') {
443        global $wpdb, $post_meta_cache;
444
445        if ( empty($value) ) {
446                $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE
447post_id = '$post_id' AND meta_key = '$key'");
448        } else {
449                $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE
450post_id = '$post_id' AND meta_key = '$key' AND meta_value = '$value'");
451        }
452
453        if ( !$meta_id )
454                return false;
455
456        if ( empty($value) ) {
457                $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id'
458AND meta_key = '$key'");
459                unset($post_meta_cache['$post_id'][$key]);
460        } else {
461                $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id'
462AND meta_key = '$key' AND meta_value = '$value'");
463                $cache_key = $post_meta_cache['$post_id'][$key];
464                if ($cache_key) foreach ( $cache_key as $index => $data )
465                        if ( $data == $value )
466                                unset($post_meta_cache['$post_id'][$key][$index]);
467        }
468
469        unset($post_meta_cache['$post_id'][$key]);
470
471        return true;
472}
473
474function get_post_meta($post_id, $key, $single = false) {
475        global $wpdb, $post_meta_cache;
476
477        if ( isset($post_meta_cache[$post_id][$key]) ) {
478                if ( $single ) {
479                        return maybe_unserialize( $post_meta_cache[$post_id][$key][0] );
480                } else {
481                        return maybe_unserialize( $post_meta_cache[$post_id][$key] );
482                }
483        }
484
485        $metalist = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = '$key'", ARRAY_N);
486
487        $values = array();
488        if ( $metalist ) {
489                foreach ($metalist as $metarow) {
490                        $values[] = $metarow[0];
491                }
492        }
493
494        if ( $single ) {
495                if ( count($values) ) {
496                        $return = maybe_unserialize( $values[0] );
497                } else {
498                        return '';
499                }
500        } else {
501                $return = $values;
502        }
503
504        return maybe_unserialize($return);
505}
506
507function update_post_meta($post_id, $key, $value, $prev_value = '') {
508        global $wpdb, $post_meta_cache;
509
510        $original_value = $value;
511        if ( is_array($value) || is_object($value) )
512                $value = $wpdb->escape(serialize($value));
513
514        $original_prev = $prev_value;
515        if ( is_array($prev_value) || is_object($prev_value) )
516                $prev_value = $wpdb->escape(serialize($prev_value));
517
518        if (! $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
519= '$key' AND post_id = '$post_id'") ) {
520                return false;
521        }
522
523        if ( empty($prev_value) ) {
524                $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE
525meta_key = '$key' AND post_id = '$post_id'");
526                $cache_key = $post_meta_cache['$post_id'][$key];
527                if ( !empty($cache_key) )
528                        foreach ($cache_key as $index => $data)
529                                $post_meta_cache['$post_id'][$key][$index] = $original_value;
530        } else {
531                $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE
532meta_key = '$key' AND post_id = '$post_id' AND meta_value = '$prev_value'");
533                $cache_key = $post_meta_cache['$post_id'][$key];
534                if ( !empty($cache_key) )
535                        foreach ($cache_key as $index => $data)
536                                if ( $data == $original_prev )
537                                        $post_meta_cache['$post_id'][$key][$index] = $original_value;
538        }
539
540        return true;
541}
542
543// Deprecated.  Use get_post().
544function get_postdata($postid) {
545        $post = &get_post($postid);
546
547        $postdata = array (
548                'ID' => $post->ID,
549                'Author_ID' => $post->post_author,
550                'Date' => $post->post_date,
551                'Content' => $post->post_content,
552                'Excerpt' => $post->post_excerpt,
553                'Title' => $post->post_title,
554                'Category' => $post->post_category,
555                'post_status' => $post->post_status,
556                'comment_status' => $post->comment_status,
557                'ping_status' => $post->ping_status,
558                'post_password' => $post->post_password,
559                'to_ping' => $post->to_ping,
560                'pinged' => $post->pinged,
561                'post_name' => $post->post_name
562        );
563
564        return $postdata;
565}
566
567// Retrieves post data given a post ID or post object.
568// Handles post caching.
569function &get_post(&$post, $output = OBJECT) {
570        global $post_cache, $wpdb;
571
572        if ( empty($post) ) {
573                if ( isset($GLOBALS['post']) )
574                        $_post = & $GLOBALS['post'];
575                else
576                        $_post = null;
577        } elseif ( is_object($post) ) {
578                if ( 'static' == $post->post_status )
579                        return get_page($post, $output);
580                if ( !isset($post_cache[$post->ID]) )
581                        $post_cache[$post->ID] = &$post;
582                $_post = & $post_cache[$post->ID];
583        } else {
584                if ( $_post = wp_cache_get($post, 'pages') )
585                        return get_page($_post, $output);
586                elseif ( isset($post_cache[$post]) )
587                        $_post = & $post_cache[$post];
588                else {
589                        $query = "SELECT * FROM $wpdb->posts WHERE ID = '$post' LIMIT 1";
590                        $_post = & $wpdb->get_row($query);
591                        if ( 'static' == $_post->post_status )
592                                return get_page($_post, $output);
593                        $post_cache[$post] = & $_post;
594                }
595        }
596
597        if ( defined(WP_IMPORTING) )
598                unset($post_cache);
599
600        if ( $output == OBJECT ) {
601                return $_post;
602        } elseif ( $output == ARRAY_A ) {
603                return get_object_vars($_post);
604        } elseif ( $output == ARRAY_N ) {
605                return array_values(get_object_vars($_post));
606        } else {
607                return $_post;
608        }
609}
610
611function &get_children($post = 0, $output = OBJECT) {
612        global $post_cache, $wpdb;
613
614        if ( empty($post) ) {
615                if ( isset($GLOBALS['post']) )
616                        $post_parent = & $GLOBALS['post']->post_parent;
617                else
618                        return false;
619        } elseif ( is_object($post) ) {
620                $post_parent = $post->post_parent;
621        } else {
622                $post_parent = $post;
623        }
624
625        $post_parent = (int) $post_parent;
626
627        $query = "SELECT * FROM $wpdb->posts WHERE post_parent = $post_parent";
628
629        $children = $wpdb->get_results($query);
630
631        if ( $children ) {
632                foreach ( $children as $key => $child ) {
633                        $post_cache[$child->ID] =& $children[$key];
634                        $kids[$child->ID] =& $children[$key];
635                }
636        } else {
637                return false;
638        }
639
640        if ( $output == OBJECT ) {
641                return $kids;
642        } elseif ( $output == ARRAY_A ) {
643                foreach ( $kids as $kid )
644                        $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
645                return $weeuns;
646        } elseif ( $output == ARRAY_N ) {
647                foreach ( $kids as $kid )
648                        $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
649                return $babes;
650        } else {
651                return $kids;
652        }
653}
654
655function set_page_path($page) {
656        $page->fullpath = '/' . $page->post_name;
657        $path = $page->fullpath;
658        $curpage = $page;
659        while ($curpage->post_parent != 0) {
660                $curpage = get_page($curpage->post_parent);
661                $path = '/' . $curpage->post_name . $path;
662        }
663       
664        $page->fullpath = $path;
665
666        return $page;
667}
668
669// Retrieves page data given a page ID or page object.
670// Handles page caching.
671function &get_page(&$page, $output = OBJECT) {
672        global $wpdb;
673
674        if ( empty($page) ) {
675                if ( isset($GLOBALS['page']) ) {
676                        $_page = & $GLOBALS['page'];
677                        wp_cache_add($_page->ID, $_page, 'pages');
678                } else {
679                        $_page = null;
680                }
681        } elseif ( is_object($page) ) {
682                if ( 'static' != $page->post_status )
683                        return get_post($page, $output);
684                wp_cache_add($page->ID, $page, 'pages');
685                $_page = $page;
686        } else {
687                if ( isset($GLOBALS['page']) && ($page == $GLOBALS['page']->ID) ) {
688                        $_page = & $GLOBALS['page'];
689                        wp_cache_add($_page->ID, $_page, 'pages');
690                } elseif ( $_page = $GLOBALS['post_cache'][$page] ) {
691                        return get_post($page, $output);
692                } elseif ( $_page = wp_cache_get($page, 'pages') ) {
693                        // Got it.
694                } else {
695                        $query = "SELECT * FROM $wpdb->posts WHERE ID= '$page' LIMIT 1";
696                        $_page = & $wpdb->get_row($query);
697                        if ( 'static' != $_page->post_status )
698                                return get_post($_page, $output);
699                        wp_cache_add($_page->ID, $_page, 'pages');
700                }
701        }
702       
703        if (!isset($_page->fullpath)) {
704                $_page = set_page_path($_page);
705                wp_cache_replace($_page->cat_ID, $_page, 'pages');
706        }
707
708        if ( $output == OBJECT ) {
709                return $_page;
710        } elseif ( $output == ARRAY_A ) {
711                return get_object_vars($_page);
712        } elseif ( $output == ARRAY_N ) {
713                return array_values(get_object_vars($_page));
714        } else {
715                return $_page;
716        }
717}
718
719function set_category_path($cat) {
720        $cat->fullpath = '/' . $cat->category_nicename;
721        $path = $cat->fullpath;
722        $curcat = $cat;
723        while ($curcat->category_parent != 0) {
724                $curcat = get_category($curcat->category_parent);
725                $path = '/' . $curcat->category_nicename . $path;
726        }
727       
728        $cat->fullpath = $path;
729
730        return $cat;
731}
732
733// Retrieves category data given a category ID or category object.
734// Handles category caching.
735function &get_category(&$category, $output = OBJECT) {
736        global $wpdb;
737
738        if ( empty($category) )
739                return null;
740
741        if ( is_object($category) ) {
742                wp_cache_add($category->cat_ID, $category, 'category');
743                $_category = $category;
744        } else {
745                if ( ! $_category = wp_cache_get($category, 'category') ) {
746                        $_category = $wpdb->get_row("SELECT * FROM $wpdb->categories WHERE cat_ID = '$category' LIMIT 1");
747                        wp_cache_add($category, $_category, 'category');
748                }
749        }
750
751        $_category = apply_filters('get_category', $_category);
752
753        if ( !isset($_category->fullpath) ) {
754                $_category = set_category_path($_category);
755                wp_cache_replace($_category->cat_ID, $_category, 'category');   
756        }
757
758        if ( $output == OBJECT ) {
759                return $_category;
760        } elseif ( $output == ARRAY_A ) {
761                return get_object_vars($_category);
762        } elseif ( $output == ARRAY_N ) {
763                return array_values(get_object_vars($_category));
764        } else {
765                return $_category;
766        }
767}
768
769// Retrieves comment data given a comment ID or comment object.
770// Handles comment caching.
771function &get_comment(&$comment, $output = OBJECT) {
772        global $comment_cache, $wpdb;
773
774        if ( empty($comment) )
775                return null;
776
777        if ( is_object($comment) ) {
778                if ( !isset($comment_cache[$comment->comment_ID]) )
779                        $comment_cache[$comment->comment_ID] = &$comment;
780                $_comment = & $comment_cache[$comment->comment_ID];
781        } else {
782                if ( !isset($comment_cache[$comment]) ) {
783                        $_comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment' LIMIT 1");
784                        $comment_cache[$comment->comment_ID] = & $_comment;
785                } else {
786                        $_comment = & $comment_cache[$comment];
787                }
788        }
789
790        if ( $output == OBJECT ) {
791                return $_comment;
792        } elseif ( $output == ARRAY_A ) {
793                return get_object_vars($_comment);
794        } elseif ( $output == ARRAY_N ) {
795                return array_values(get_object_vars($_comment));
796        } else {
797                return $_comment;
798        }
799}
800
801function get_catname($cat_ID) {
802        $category = &get_category($cat_ID);
803        return $category->cat_name;
804}
805
806function get_all_category_ids() {
807        global $wpdb;
808       
809        if ( ! $cat_ids = wp_cache_get('all_category_ids', 'category') ) {
810                $cat_ids = $wpdb->get_col("SELECT cat_ID FROM $wpdb->categories");
811                wp_cache_add('all_category_ids', $cat_ids, 'category');
812        }
813       
814        return $cat_ids;
815}
816
817function get_all_page_ids() {
818        global $wpdb;
819       
820        if ( ! $page_ids = wp_cache_get('all_page_ids', 'pages') ) {
821                $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_status='static'");
822                wp_cache_add('all_page_ids', $page_ids, 'pages');
823        }
824       
825        return $page_ids;
826}
827
828function gzip_compression() {
829        if ( !get_settings('gzipcompression') ) return false;
830
831        if ( extension_loaded('zlib') ) {
832                ob_start('ob_gzhandler');
833        }
834}
835
836
837// functions to count the page generation time (from phpBB2)
838// ( or just any time between timer_start() and timer_stop() )
839
840function timer_stop($display = 0, $precision = 3) { //if called like timer_stop(1), will echo $timetotal
841        global $timestart, $timeend;
842        $mtime = microtime();
843        $mtime = explode(' ',$mtime);
844        $mtime = $mtime[1] + $mtime[0];
845        $timeend = $mtime;
846        $timetotal = $timeend-$timestart;
847        if ( $display )
848                echo number_format($timetotal,$precision);
849        return $timetotal;
850}
851
852function weblog_ping($server = '', $path = '') {
853        global $wp_version;
854        include_once (ABSPATH . WPINC . '/class-IXR.php');
855
856        // using a timeout of 3 seconds should be enough to cover slow servers
857        $client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
858        $client->timeout = 3;
859        $client->useragent .= ' -- WordPress/'.$wp_version;
860
861        // when set to true, this outputs debug messages by itself
862        $client->debug = false;
863        $home = trailingslashit( get_option('home') );
864        if ( !$client->query('weblogUpdates.extendedPing', get_settings('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
865                $client->query('weblogUpdates.ping', get_settings('blogname'), $home);
866}
867
868function generic_ping($post_id = 0) {
869        $services = get_settings('ping_sites');
870        $services = preg_replace("|(\s)+|", '$1', $services); // Kill dupe lines
871        $services = trim($services);
872        if ( '' != $services ) {
873                $services = explode("\n", $services);
874                foreach ($services as $service) {
875                        weblog_ping($service);
876                }
877        }
878
879        return $post_id;
880}
881
882// Send a Trackback
883function trackback($trackback_url, $title, $excerpt, $ID) {
884        global $wpdb, $wp_version;
885
886        if ( empty($trackback_url) )
887                return;
888
889        $title = urlencode($title);
890        $excerpt = urlencode($excerpt);
891        $blog_name = urlencode(get_settings('blogname'));
892        $tb_url = $trackback_url;
893        $url = urlencode(get_permalink($ID));
894        $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
895        $trackback_url = parse_url($trackback_url);
896        $http_request = 'POST ' . $trackback_url['path'] . ($trackback_url['query'] ? '?'.$trackback_url['query'] : '') . " HTTP/1.0\r\n";
897        $http_request .= 'Host: '.$trackback_url['host']."\r\n";
898        $http_request .= 'Content-Type: application/x-www-form-urlencoded; charset='.get_settings('blog_charset')."\r\n";
899        $http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
900        $http_request .= "User-Agent: WordPress/" . $wp_version;
901        $http_request .= "\r\n\r\n";
902        $http_request .= $query_string;
903        if ( '' == $trackback_url['port'] )
904                $trackback_url['port'] = 80;
905        $fs = @fsockopen($trackback_url['host'], $trackback_url['port'], $errno, $errstr, 4);
906        @fputs($fs, $http_request);
907/*
908        $debug_file = 'trackback.log';
909        $fp = fopen($debug_file, 'a');
910        fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
911        while(!@feof($fs)) {
912                fwrite($fp, @fgets($fs, 4096));
913        }
914        fwrite($fp, "\n\n");
915        fclose($fp);
916*/
917        @fclose($fs);
918
919        $tb_url = addslashes( $tb_url );
920        $wpdb->query("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
921        return $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_url', '')) WHERE ID = '$ID'");
922}
923
924function make_url_footnote($content) {
925        preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
926        $j = 0;
927        for ($i=0; $i<count($matches[0]); $i++) {
928                $links_summary = (!$j) ? "\n" : $links_summary;
929                $j++;
930                $link_match = $matches[0][$i];
931                $link_number = '['.($i+1).']';
932                $link_url = $matches[2][$i];
933                $link_text = $matches[4][$i];
934                $content = str_replace($link_match, $link_text.' '.$link_number, $content);
935                $link_url = ((strtolower(substr($link_url,0,7)) != 'http://') && (strtolower(substr($link_url,0,8)) != 'https://')) ? get_settings('home') . $link_url : $link_url;
936                $links_summary .= "\n".$link_number.' '.$link_url;
937        }
938        $content = strip_tags($content);
939        $content .= $links_summary;
940        return $content;
941}
942
943
944function xmlrpc_getposttitle($content) {
945        global $post_default_title;
946        if ( preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle) ) {
947                $post_title = $matchtitle[0];
948                $post_title = preg_replace('/<title>/si', '', $post_title);
949                $post_title = preg_replace('/<\/title>/si', '', $post_title);
950        } else {
951                $post_title = $post_default_title;
952        }
953        return $post_title;
954}
955
956function xmlrpc_getpostcategory($content) {
957        global $post_default_category;
958        if ( preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat) ) {
959                $post_category = trim($matchcat[1], ',');
960                $post_category = explode(',', $post_category);
961        } else {
962                $post_category = $post_default_category;
963        }
964        return $post_category;
965}
966
967function xmlrpc_removepostdata($content) {
968        $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content);
969        $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content);
970        $content = trim($content);
971        return $content;
972}
973
974function debug_fopen($filename, $mode) {
975        global $debug;
976        if ( $debug == 1 ) {
977                $fp = fopen($filename, $mode);
978                return $fp;
979        } else {
980                return false;
981        }
982}
983
984function debug_fwrite($fp, $string) {
985        global $debug;
986        if ( $debug == 1 ) {
987                fwrite($fp, $string);
988        }
989}
990
991function debug_fclose($fp) {
992        global $debug;
993        if ( $debug == 1 ) {
994                fclose($fp);
995        }
996}
997
998function spawn_pinger() {
999        global $wpdb, $wp_version;
1000        $doping = false;
1001        if ( $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE TRIM(to_ping) != '' LIMIT 1") )
1002                $doping = true;
1003
1004        if ( $wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_pingme' OR meta_key = '_encloseme' LIMIT 1") )
1005                $doping = true;
1006
1007        if ( substr(php_sapi_name(), 0, 3) == 'cgi' )
1008                return $doping;
1009
1010        if ( $doping ) {
1011                $ping_url = get_settings('siteurl') .'/wp-admin/execute-pings.php';
1012                $parts = parse_url($ping_url);
1013                $argyle = @ fsockopen($parts['host'], $_SERVER['SERVER_PORT'], $errno, $errstr, 0.01);
1014                if ( $argyle )
1015                        fputs($argyle, "GET {$parts['path']}?time=".time()." HTTP/1.0\r\nHost: {$_SERVER['HTTP_HOST']}\r\nUser-Agent: WordPress/{$wp_version}\r\n\r\n");
1016       }
1017}
1018
1019function do_enclose( $content, $post_ID ) {
1020        global $wp_version, $wpdb;
1021        include_once (ABSPATH . WPINC . '/class-IXR.php');
1022
1023        $log = debug_fopen(ABSPATH . '/enclosures.log', 'a');
1024        $post_links = array();
1025        debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");
1026
1027        $pung = get_enclosed( $post_ID );
1028
1029        $ltrs = '\w';
1030        $gunk = '/#~:.?+=&%@!\-';
1031        $punc = '.:?\-';
1032        $any = $ltrs . $gunk . $punc;
1033
1034        preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
1035
1036        debug_fwrite($log, 'Post contents:');
1037        debug_fwrite($log, $content."\n");
1038
1039        foreach($post_links_temp[0] as $link_test) :
1040                if ( !in_array($link_test, $pung) ) : // If we haven't pung it already
1041                        $test = parse_url($link_test);
1042                        if ( isset($test['query']) )
1043                                $post_links[] = $link_test;
1044                        elseif (($test['path'] != '/') && ($test['path'] != ''))
1045                                $post_links[] = $link_test;
1046                endif;
1047        endforeach;
1048
1049        foreach ($post_links as $url) :
1050                if ( $url != '' && !$wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE post_id = '$post_ID' AND meta_key = 'enclosure' AND meta_value LIKE ('$url%')") ) {
1051                        if ( $headers = wp_get_http_headers( $url) ) {
1052                                $len = (int) $headers['content-length'];
1053                                $type = $wpdb->escape( $headers['content-type'] );
1054                                $allowed_types = array( 'video', 'audio' );
1055                                if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
1056                                        $meta_value = "$url\n$len\n$type\n";
1057                                        $wpdb->query( "INSERT INTO `$wpdb->postmeta` ( `post_id` , `meta_key` , `meta_value` )
1058                                        VALUES ( '$post_ID', 'enclosure' , '$meta_value')" );
1059                                }
1060                        }
1061                }
1062        endforeach;
1063}
1064
1065function wp_get_http_headers( $url, $red = 1 ) {
1066        global $wp_version;
1067        @set_time_limit( 60 );
1068
1069        if ( $red > 5 )
1070           return false;
1071
1072        $parts = parse_url( $url );
1073        $file = $parts['path'] . ($parts['query'] ? '?'.$parts['query'] : '');
1074        $host = $parts['host'];
1075        if ( !isset( $parts['port'] ) )
1076                $parts['port'] = 80;
1077
1078        $head = "HEAD $file HTTP/1.1\r\nHOST: $host\r\nUser-Agent: WordPress/" . $wp_version . "\r\n\r\n";
1079
1080        $fp = @fsockopen($host, $parts['port'], $err_num, $err_msg, 3);
1081        if ( !$fp )
1082                return false;
1083
1084        $response = '';
1085        fputs( $fp, $head );
1086        while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
1087                $response .= fgets( $fp, 2048 );
1088        fclose( $fp );
1089        preg_match_all('/(.*?): (.*)\r/', $response, $matches);
1090        $count = count($matches[1]);
1091        for ( $i = 0; $i < $count; $i++) {
1092                $key = strtolower($matches[1][$i]);
1093                $headers["$key"] = $matches[2][$i];
1094        }
1095
1096        preg_match('/.*([0-9]{3}).*/', $response, $return);
1097        $headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
1098
1099    $code = $headers['response'];
1100    if ( ('302' == $code || '301' == $code) && isset($headers['location']) )
1101        return wp_get_http_headers( $headers['location'], ++$red );
1102
1103        return $headers;
1104}
1105
1106// Deprecated.  Use the new post loop.
1107function start_wp() {
1108        global $wp_query, $post;
1109
1110        // Since the old style loop is being used, advance the query iterator here.
1111        $wp_query->next_post();
1112
1113        setup_postdata($post);
1114}
1115
1116// Setup global post data.
1117function setup_postdata($post) {
1118        global $id, $postdata, $authordata, $day, $page, $pages, $multipage, $more, $numpages, $wp_query;
1119        global $pagenow;
1120
1121        $id = $post->ID;
1122
1123        $authordata = get_userdata($post->post_author);
1124
1125        $day = mysql2date('d.m.y', $post->post_date);
1126        $currentmonth = mysql2date('m', $post->post_date);
1127        $numpages = 1;
1128        $page = get_query_var('page');
1129        if ( !$page )
1130                $page = 1;
1131        if ( is_single() || is_page() )
1132                $more = 1;
1133        $content = $post->post_content;
1134        if ( preg_match('/<!--nextpage-->/', $content) ) {
1135                if ( $page > 1 )
1136                        $more = 1;
1137                $multipage = 1;
1138                $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
1139                $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
1140                $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
1141                $pages = explode('<!--nextpage-->', $content);
1142                $numpages = count($pages);
1143        } else {
1144                $pages[0] = $post->post_content;
1145                $multipage = 0;
1146        }
1147        return true;
1148}
1149
1150// Setup global user vars.  Used by set_current_user() for back compat.
1151function setup_userdata($user_id = '') {
1152        global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity;
1153
1154        if ( '' == $user_id )
1155                $user = wp_get_current_user();
1156        else 
1157                $user = new WP_User($user_id);
1158
1159        if ( 0 == $user->ID )
1160                return;
1161
1162        $userdata = $user->data;
1163        $user_login     = $user->user_login;
1164        $user_level     = $user->user_level;
1165        $user_ID        = $user->ID;
1166        $user_email     = $user->user_email;
1167        $user_url       = $user->user_url;
1168        $user_pass_md5  = md5($user->user_pass);
1169        $user_identity  = $user->display_name;
1170}
1171
1172function is_new_day() {
1173        global $day, $previousday;
1174        if ( $day != $previousday ) {
1175                return(1);
1176        } else {
1177                return(0);
1178        }
1179}
1180
1181// Filters: these are the core of WP's plugin architecture
1182
1183function merge_filters($tag) {
1184        global $wp_filter;
1185        if ( isset($wp_filter['all']) ) {
1186                foreach ($wp_filter['all'] as $priority => $functions) {
1187                        if ( isset($wp_filter[$tag][$priority]) )
1188                                $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
1189                        else
1190                                $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
1191                        $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
1192                }
1193        }
1194
1195        if ( isset($wp_filter[$tag]) )
1196                ksort( $wp_filter[$tag] );
1197}
1198
1199function apply_filters($tag, $string) {
1200        global $wp_filter;
1201
1202        $args = array_slice(func_get_args(), 2);
1203
1204        merge_filters($tag);
1205
1206        if ( !isset($wp_filter[$tag]) ) {
1207                return $string;
1208        }
1209        foreach ($wp_filter[$tag] as $priority => $functions) {
1210                if ( !is_null($functions) ) {
1211                        foreach($functions as $function) {
1212
1213                                $all_args = array_merge(array($string), $args);
1214                                $function_name = $function['function'];
1215                                $accepted_args = $function['accepted_args'];
1216
1217                                if ( $accepted_args == 1 )
1218                                        $the_args = array($string);
1219                                elseif ( $accepted_args > 1 )
1220                                        $the_args = array_slice($all_args, 0, $accepted_args);
1221                                elseif ( $accepted_args == 0 )
1222                                        $the_args = NULL;
1223                                else
1224                                        $the_args = $all_args;
1225
1226                                $string = call_user_func_array($function_name, $the_args);
1227                        }
1228                }
1229        }
1230        return $string;
1231}
1232
1233function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
1234        global $wp_filter;
1235
1236        // check that we don't already have the same filter at the same priority
1237        if ( isset($wp_filter[$tag]["$priority"]) ) {
1238                foreach($wp_filter[$tag]["$priority"] as $filter) {
1239                        // uncomment if we want to match function AND accepted_args
1240                        // if ( $filter == array($function, $accepted_args) ) {
1241                        if ( $filter['function'] == $function_to_add ) {
1242                                return true;
1243                        }
1244                }
1245        }
1246
1247        // So the format is wp_filter['tag']['array of priorities']['array of ['array (functions, accepted_args)]']
1248        $wp_filter[$tag]["$priority"][] = array('function'=>$function_to_add, 'accepted_args'=>$accepted_args);
1249        return true;
1250}
1251
1252function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
1253        global $wp_filter;
1254
1255        // rebuild the list of filters
1256        if ( isset($wp_filter[$tag]["$priority"]) ) {
1257                $new_function_list = array();
1258                foreach($wp_filter[$tag]["$priority"] as $filter) {
1259                        if ( $filter['function'] != $function_to_remove ) {
1260                                $new_function_list[] = $filter;
1261                        }
1262                }
1263                $wp_filter[$tag]["$priority"] = $new_function_list;
1264        }
1265        return true;
1266}
1267
1268// The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
1269
1270function do_action($tag, $arg = '') {
1271        global $wp_filter;
1272        $extra_args = array_slice(func_get_args(), 2);
1273        if ( is_array($arg) )
1274                $args = array_merge($arg, $extra_args);
1275        else
1276                $args = array_merge(array($arg), $extra_args);
1277
1278        merge_filters($tag);
1279
1280        if ( !isset($wp_filter[$tag]) ) {
1281                return;
1282        }
1283        foreach ($wp_filter[$tag] as $priority => $functions) {
1284                if ( !is_null($functions) ) {
1285                        foreach($functions as $function) {
1286
1287                                $function_name = $function['function'];
1288                                $accepted_args = $function['accepted_args'];
1289
1290                                if ( $accepted_args == 1 ) {
1291                                        if ( is_array($arg) )
1292                                                $the_args = $arg;
1293                                        else
1294                                                $the_args = array($arg);
1295                                } elseif ( $accepted_args > 1 ) {
1296                                        $the_args = array_slice($args, 0, $accepted_args);
1297                                } elseif ( $accepted_args == 0 ) {
1298                                        $the_args = NULL;
1299                                } else {
1300                                        $the_args = $args;
1301                                }
1302
1303                                $string = call_user_func_array($function_name, $the_args);
1304                        }
1305                }
1306        }
1307}
1308
1309function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
1310        add_filter($tag, $function_to_add, $priority, $accepted_args);
1311}
1312
1313function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
1314        remove_filter($tag, $function_to_remove, $priority, $accepted_args);
1315}
1316
1317function get_page_uri($page_id) {
1318        $page = get_page($page_id);
1319        $uri = urldecode($page->post_name);
1320
1321        // A page cannot be it's own parent.
1322        if ( $page->post_parent == $page->ID )
1323                return $uri;
1324
1325        while ($page->post_parent != 0) {
1326                $page = get_page($page->post_parent);
1327                $uri = urldecode($page->post_name) . "/" . $uri;
1328        }
1329
1330        return $uri;
1331}
1332
1333function get_posts($args) {
1334        global $wpdb;
1335        parse_str($args, $r);
1336        if ( !isset($r['numberposts']) )
1337                $r['numberposts'] = 5;
1338        if ( !isset($r['offset']) )
1339                $r['offset'] = 0;
1340        if ( !isset($r['category']) )
1341                $r['category'] = '';
1342        if ( !isset($r['orderby']) )
1343                $r['orderby'] = 'post_date';
1344        if ( !isset($r['order']) )
1345                $r['order'] = 'DESC';
1346
1347        $now = current_time('mysql');
1348
1349        $posts = $wpdb->get_results(
1350                "SELECT DISTINCT * FROM $wpdb->posts " .
1351                ( empty( $r['category'] ) ? "" : ", $wpdb->post2cat " ) .
1352                " WHERE post_date <= '$now' AND (post_status = 'publish') ".
1353                ( empty( $r['category'] ) ? "" : "AND $wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $r['category']. " " ) .
1354                " GROUP BY $wpdb->posts.ID ORDER BY " . $r['orderby'] . " " . $r['order'] . " LIMIT " . $r['offset'] . ',' . $r['numberposts'] );
1355
1356        update_post_caches($posts);
1357
1358        return $posts;
1359}
1360
1361function &query_posts($query) {
1362        global $wp_query;
1363        return $wp_query->query($query);
1364}
1365
1366function update_post_cache(&$posts) {
1367        global $post_cache;
1368
1369        if ( !$posts )
1370                return;
1371
1372        for ($i = 0; $i < count($posts); $i++) {
1373                $post_cache[$posts[$i]->ID] = &$posts[$i];
1374        }
1375}
1376
1377function clean_post_cache($id) {
1378        global $post_cache;
1379
1380        if ( isset( $post_cache[$id] ) )
1381                unset( $post_cache[$id] );
1382}
1383
1384function update_page_cache(&$pages) {
1385        global $page_cache;
1386
1387        if ( !$pages )
1388                return;
1389
1390        for ($i = 0; $i < count($pages); $i++) {
1391                $page_cache[$pages[$i]->ID] = &$pages[$i];
1392                wp_cache_add($pages[$i]->ID, $pages[$i], 'pages');
1393        }
1394}
1395
1396
1397function clean_page_cache($id) {
1398        global $page_cache;
1399
1400        if ( isset( $page_cache[$id] ) )
1401                unset( $page_cache[$id] );
1402}
1403
1404function update_post_category_cache($post_ids) {
1405        global $wpdb, $category_cache;
1406
1407        if ( empty($post_ids) )
1408                return;
1409
1410        if ( is_array($post_ids) )
1411                $post_ids = implode(',', $post_ids);
1412
1413        $dogs = $wpdb->get_results("SELECT post_id, category_id FROM $wpdb->post2cat WHERE post_id IN ($post_ids)");
1414
1415        if ( empty($dogs) )
1416                return;
1417               
1418        foreach ($dogs as $catt)
1419                $category_cache[$catt->post_id][$catt->category_id] = &get_category($catt->category_id);
1420}
1421
1422function update_post_caches(&$posts) {
1423        global $post_cache, $category_cache, $comment_count_cache, $post_meta_cache;
1424        global $wpdb;
1425
1426        // No point in doing all this work if we didn't match any posts.
1427        if ( !$posts )
1428                return;
1429
1430        // Get the categories for all the posts
1431        for ($i = 0; $i < count($posts); $i++) {
1432                $post_id_array[] = $posts[$i]->ID;
1433                $post_cache[$posts[$i]->ID] = &$posts[$i];
1434                $comment_count_cache[$posts[$i]->ID] = $posts[$i]->comment_count;
1435        }
1436
1437        $post_id_list = implode(',', $post_id_array);
1438
1439        update_post_category_cache($post_id_list);
1440
1441        // Get post-meta info
1442        if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN($post_id_list) ORDER BY post_id, meta_key", ARRAY_A) ) {
1443                // Change from flat structure to hierarchical:
1444                $post_meta_cache = array();
1445                foreach ($meta_list as $metarow) {
1446                        $mpid = $metarow['post_id'];
1447                        $mkey = $metarow['meta_key'];
1448                        $mval = $metarow['meta_value'];
1449
1450                        // Force subkeys to be array type:
1451                        if ( !isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]) )
1452                                $post_meta_cache[$mpid] = array();
1453                        if ( !isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]) )
1454                                $post_meta_cache[$mpid]["$mkey"] = array();
1455
1456                        // Add a value to the current pid/key:
1457                        $post_meta_cache[$mpid][$mkey][] = $mval;
1458                }
1459        }
1460}
1461
1462function update_category_cache() {
1463        return true;
1464}
1465
1466function wp_head() {
1467        do_action('wp_head');
1468}
1469
1470function wp_footer() {
1471        do_action('wp_footer');
1472}
1473
1474function is_single ($post = '') {
1475        global $wp_query;
1476
1477        if ( !$wp_query->is_single )
1478                return false;
1479
1480        if ( empty( $post) )
1481                return true;
1482
1483        $post_obj = $wp_query->get_queried_object();
1484
1485        if ( $post == $post_obj->ID )
1486                return true;
1487        elseif ( $post == $post_obj->post_title )
1488                return true;
1489        elseif ( $post == $post_obj->post_name )
1490                return true;
1491
1492        return false;
1493}
1494
1495function is_page ($page = '') {
1496        global $wp_query;
1497
1498        if ( !$wp_query->is_page )
1499                return false;
1500
1501        if ( empty($page) )
1502                return true;
1503
1504        $page_obj = $wp_query->get_queried_object();
1505
1506        if ( $page == $page_obj->ID )
1507                return true;
1508        elseif ( $page == $page_obj->post_title )
1509                return true;
1510        else if ( $page == $page_obj->post_name )
1511                return true;
1512
1513        return false;
1514}
1515
1516function is_attachment () {
1517        global $wp_query;
1518
1519        return $wp_query->is_attachment;
1520}
1521
1522function is_preview() {
1523        global $wp_query;
1524       
1525        return $wp_query->is_preview;
1526}
1527
1528function is_archive () {
1529        global $wp_query;
1530
1531        return $wp_query->is_archive;
1532}
1533
1534function is_date () {
1535        global $wp_query;
1536
1537        return $wp_query->is_date;
1538}
1539
1540function is_year () {
1541        global $wp_query;
1542
1543        return $wp_query->is_year;
1544}
1545
1546function is_month () {
1547        global $wp_query;
1548
1549        return $wp_query->is_month;
1550}
1551
1552function is_day () {
1553        global $wp_query;
1554
1555        return $wp_query->is_day;
1556}
1557
1558function is_time () {
1559        global $wp_query;
1560
1561        return $wp_query->is_time;
1562}
1563
1564function is_author ($author = '') {
1565        global $wp_query;
1566
1567        if ( !$wp_query->is_author )
1568                return false;
1569
1570        if ( empty($author) )
1571                return true;
1572
1573        $author_obj = $wp_query->get_queried_object();
1574
1575        if ( $author == $author_obj->ID )
1576                return true;
1577        elseif ( $author == $author_obj->nickname )
1578                return true;
1579        elseif ( $author == $author_obj->user_nicename )
1580                return true;
1581
1582        return false;
1583}
1584
1585function is_category ($category = '') {
1586        global $wp_query;
1587
1588        if ( !$wp_query->is_category )
1589                return false;
1590
1591        if ( empty($category) )
1592                return true;
1593
1594        $cat_obj = $wp_query->get_queried_object();
1595
1596        if ( $category == $cat_obj->cat_ID )
1597                return true;
1598        else if ( $category == $cat_obj->cat_name )
1599                return true;
1600        elseif ( $category == $cat_obj->category_nicename )
1601                return true;
1602
1603        return false;
1604}
1605
1606function is_search () {
1607        global $wp_query;
1608
1609        return $wp_query->is_search;
1610}
1611
1612function is_feed () {
1613        global $wp_query;
1614
1615        return $wp_query->is_feed;
1616}
1617
1618function is_trackback () {
1619        global $wp_query;
1620
1621        return $wp_query->is_trackback;
1622}
1623
1624function is_admin () {
1625        global $wp_query;
1626
1627        return ( $wp_query->is_admin || strstr($_SERVER['REQUEST_URI'], 'wp-admin/') );
1628}
1629
1630function is_home () {
1631        global $wp_query;
1632
1633        return $wp_query->is_home;
1634}
1635
1636function is_404 () {
1637        global $wp_query;
1638
1639        return $wp_query->is_404;
1640}
1641
1642function is_comments_popup () {
1643        global $wp_query;
1644
1645        return $wp_query->is_comments_popup;
1646}
1647
1648function is_paged () {
1649        global $wp_query;
1650
1651        return $wp_query->is_paged;
1652}
1653
1654function in_the_loop() {
1655        global $wp_query;
1656
1657        return $wp_query->in_the_loop;
1658}
1659
1660function get_query_var($var) {
1661        global $wp_query;
1662
1663        return $wp_query->get($var);
1664}
1665
1666function have_posts() {
1667        global $wp_query;
1668
1669        return $wp_query->have_posts();
1670}
1671
1672function rewind_posts() {
1673        global $wp_query;
1674
1675        return $wp_query->rewind_posts();
1676}
1677
1678function the_post() {
1679        global $wp_query;
1680
1681        $wp_query->the_post();
1682}
1683
1684function get_theme_root() {
1685        return apply_filters('theme_root', ABSPATH . "wp-content/themes");
1686}
1687
1688function get_theme_root_uri() {
1689        return apply_filters('theme_root_uri', get_settings('siteurl') . "/wp-content/themes", get_settings('siteurl'));
1690}
1691
1692function get_stylesheet() {
1693        return apply_filters('stylesheet', get_settings('stylesheet'));
1694}
1695
1696function get_stylesheet_directory() {
1697        $stylesheet = get_stylesheet();
1698        $stylesheet_dir = get_theme_root() . "/$stylesheet";
1699        return apply_filters('stylesheet_directory', $stylesheet_dir, $stylesheet);
1700}
1701
1702function get_stylesheet_directory_uri() {
1703        $stylesheet = rawurlencode( get_stylesheet() );
1704        $stylesheet_dir_uri = get_theme_root_uri() . "/$stylesheet";
1705        return apply_filters('stylesheet_directory_uri', $stylesheet_dir_uri, $stylesheet);
1706}
1707
1708function get_stylesheet_uri() {
1709        $stylesheet_dir_uri = get_stylesheet_directory_uri();
1710        $stylesheet_uri = $stylesheet_dir_uri . "/style.css";
1711        return apply_filters('stylesheet_uri', $stylesheet_uri, $stylesheet_dir_uri);
1712}
1713
1714function get_template() {
1715        $template = get_settings('template');
1716        if (!file_exists(get_theme_root() . "/$template")) { //works for dirs too
1717                update_option('template', 'default');
1718                update_option('stylesheet', 'default');
1719        }
1720        return apply_filters('template', get_settings('template'));
1721}
1722
1723function get_template_directory() {
1724        $template = get_template();
1725        $template_dir = get_theme_root() . "/$template";
1726        return apply_filters('template_directory', $template_dir, $template);
1727}
1728
1729function get_template_directory_uri() {
1730        $template = get_template();
1731        $template_dir_uri = get_theme_root_uri() . "/$template";
1732        return apply_filters('template_directory_uri', $template_dir_uri, $template);
1733}
1734
1735function get_theme_data($theme_file) {
1736        $theme_data = implode('', file($theme_file));
1737        preg_match("|Theme Name:(.*)|i", $theme_data, $theme_name);
1738        preg_match("|Theme URI:(.*)|i", $theme_data, $theme_uri);
1739        preg_match("|Description:(.*)|i", $theme_data, $description);
1740        preg_match("|Author:(.*)|i", $theme_data, $author_name);
1741        preg_match("|Author URI:(.*)|i", $theme_data, $author_uri);
1742        preg_match("|Template:(.*)|i", $theme_data, $template);
1743        if ( preg_match("|Version:(.*)|i", $theme_data, $version) )
1744                $version = trim($version[1]);
1745        else
1746                $version ='';
1747        if ( preg_match("|Status:(.*)|i", $theme_data, $status) )
1748                $status = trim($status[1]);
1749        else
1750                $status = 'publish';
1751
1752        $description = wptexturize(trim($description[1]));
1753
1754        $name = $theme_name[1];
1755        $name = trim($name);
1756        $theme = $name;
1757
1758        if ( '' == $author_uri[1] ) {
1759                $author = trim($author_name[1]);
1760        } else {
1761                $author = '<a href="' . trim($author_uri[1]) . '" title="' . __('Visit author homepage') . '">' . trim($author_name[1]) . '</a>';
1762        }
1763
1764        return array('Name' => $name, 'Title' => $theme, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1], 'Status' => $status);
1765}
1766
1767function get_themes() {
1768        global $wp_themes;
1769        global $wp_broken_themes;
1770
1771        if ( isset($wp_themes) )
1772                return $wp_themes;
1773
1774        $themes = array();
1775        $wp_broken_themes = array();
1776        $theme_root = get_theme_root();
1777        $theme_loc = str_replace(ABSPATH, '', $theme_root);
1778
1779        // Files in wp-content/themes directory
1780        $themes_dir = @ dir($theme_root);
1781        if ( $themes_dir ) {
1782                while(($theme_dir = $themes_dir->read()) !== false) {
1783                        if ( is_dir($theme_root . '/' . $theme_dir) && is_readable($theme_root . '/' . $theme_dir) ) {
1784                                if ( $theme_dir{0} == '.' || $theme_dir == '..' || $theme_dir == 'CVS' ) {
1785                                        continue;
1786                                }
1787                                $stylish_dir = @ dir($theme_root . '/' . $theme_dir);
1788                                $found_stylesheet = false;
1789                                while (($theme_file = $stylish_dir->read()) !== false) {
1790                                        if ( $theme_file == 'style.css' ) {
1791                                                $theme_files[] = $theme_dir . '/' . $theme_file;
1792                                                $found_stylesheet = true;
1793                                                break;
1794                                        }
1795                                }
1796                                if ( !$found_stylesheet ) {
1797                                        $wp_broken_themes[$theme_dir] = array('Name' => $theme_dir, 'Title' => $theme_dir, 'Description' => __('Stylesheet is missing.'));
1798                                }
1799                        }
1800                }
1801        }
1802
1803        if ( !$themes_dir || !$theme_files ) {
1804                return $themes;
1805        }
1806
1807        sort($theme_files);
1808
1809        foreach($theme_files as $theme_file) {
1810                if ( ! is_readable("$theme_root/$theme_file") ) {
1811                        $wp_broken_themes[$theme_file] = array('Name' => $theme_file, 'Title' => $theme_file, 'Description' => __('File not readable.'));
1812                        continue;
1813                }
1814
1815                $theme_data = get_theme_data("$theme_root/$theme_file");
1816
1817                $name = $theme_data['Name'];
1818                $title = $theme_data['Title'];
1819                $description = wptexturize($theme_data['Description']);
1820                $version = $theme_data['Version'];
1821                $author = $theme_data['Author'];
1822                $template = $theme_data['Template'];
1823                $stylesheet = dirname($theme_file);
1824
1825                foreach (array('png', 'gif', 'jpg', 'jpeg') as $ext) {
1826                        if (file_exists("$theme_root/$stylesheet/screenshot.$ext")) {
1827                                $screenshot = "screenshot.$ext";
1828                                break;
1829                        }
1830                }
1831
1832                if ( empty($name) ) {
1833                        $name = dirname($theme_file);
1834                        $title = $name;
1835                }
1836
1837                if ( empty($template) ) {
1838                        if ( file_exists(dirname("$theme_root/$theme_file/index.php")) ) {
1839                                $template = dirname($theme_file);
1840                        } else {
1841                                continue;
1842                        }
1843                }
1844
1845                $template = trim($template);
1846
1847                if ( !file_exists("$theme_root/$template/index.php") ) {
1848                        $wp_broken_themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => __('Template is missing.'));
1849                        continue;
1850                }
1851
1852                $stylesheet_files = array();
1853                $stylesheet_dir = @ dir("$theme_root/$stylesheet");
1854                if ( $stylesheet_dir ) {
1855                        while(($file = $stylesheet_dir->read()) !== false) {
1856                                if ( !preg_match('|^\.+$|', $file) && preg_match('|\.css$|', $file) )
1857                                        $stylesheet_files[] = "$theme_loc/$stylesheet/$file";
1858                        }
1859                }
1860
1861                $template_files = array();
1862                $template_dir = @ dir("$theme_root/$template");
1863                if ( $template_dir ) {
1864                        while(($file = $template_dir->read()) !== false) {
1865                                if ( !preg_match('|^\.+$|', $file) && preg_match('|\.php$|', $file) )
1866                                        $template_files[] = "$theme_loc/$template/$file";
1867                        }
1868                }
1869
1870                $template_dir = dirname($template_files[0]);
1871                $stylesheet_dir = dirname($stylesheet_files[0]);
1872
1873                if ( empty($template_dir) )
1874                        $template_dir = '/';
1875                if ( empty($stylesheet_dir) )
1876                        $stylesheet_dir = '/';
1877
1878                // Check for theme name collision.  This occurs if a theme is copied to
1879                // a new theme directory and the theme header is not updated.  Whichever
1880                // theme is first keeps the name.  Subsequent themes get a suffix applied.
1881                // The Default and Classic themes always trump their pretenders.
1882                if ( isset($themes[$name]) ) {
1883                        if ( ('WordPress Default' == $name || 'WordPress Classic' == $name) &&
1884                                         ('default' == $stylesheet || 'classic' == $stylesheet) ) {
1885                                // If another theme has claimed to be one of our default themes, move
1886                                // them aside.
1887                                $suffix = $themes[$name]['Stylesheet'];
1888                                $new_name = "$name/$suffix";
1889                                $themes[$new_name] = $themes[$name];
1890                                $themes[$new_name]['Name'] = $new_name;
1891                        } else {
1892                                $name = "$name/$stylesheet";
1893                        }
1894                }
1895
1896                $themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template, 'Stylesheet' => $stylesheet, 'Template Files' => $template_files, 'Stylesheet Files' => $stylesheet_files, 'Template Dir' => $template_dir, 'Stylesheet Dir' => $stylesheet_dir, 'Status' => $theme_data['Status'], 'Screenshot' => $screenshot);
1897        }
1898
1899        // Resolve theme dependencies.
1900        $theme_names = array_keys($themes);
1901
1902        foreach ($theme_names as $theme_name) {
1903                $themes[$theme_name]['Parent Theme'] = '';
1904                if ( $themes[$theme_name]['Stylesheet'] != $themes[$theme_name]['Template'] ) {
1905                        foreach ($theme_names as $parent_theme_name) {
1906                                if ( ($themes[$parent_theme_name]['Stylesheet'] == $themes[$parent_theme_name]['Template']) && ($themes[$parent_theme_name]['Template'] == $themes[$theme_name]['Template']) ) {
1907                                        $themes[$theme_name]['Parent Theme'] = $themes[$parent_theme_name]['Name'];
1908                                        break;
1909                                }
1910                        }
1911                }
1912        }
1913
1914        $wp_themes = $themes;
1915
1916        return $themes;
1917}
1918
1919function get_theme($theme) {
1920        $themes = get_themes();
1921
1922        if ( array_key_exists($theme, $themes) )
1923                return $themes[$theme];
1924
1925        return NULL;
1926}
1927
1928function get_current_theme() {
1929        $themes = get_themes();
1930        $theme_names = array_keys($themes);
1931        $current_template = get_settings('template');
1932        $current_stylesheet = get_settings('stylesheet');
1933        $current_theme = 'WordPress Default';
1934
1935        if ( $themes ) {
1936                foreach ($theme_names as $theme_name) {
1937                        if ( $themes[$theme_name]['Stylesheet'] == $current_stylesheet &&
1938                                        $themes[$theme_name]['Template'] == $current_template ) {
1939                                $current_theme = $themes[$theme_name]['Name'];
1940                                break;
1941                        }
1942                }
1943        }
1944
1945        return $current_theme;
1946}
1947
1948function get_query_template($type) {
1949        $template = '';
1950        if ( file_exists(TEMPLATEPATH . "/{$type}.php") )
1951                $template = TEMPLATEPATH . "/{$type}.php";
1952
1953        return apply_filters("{$type}_template", $template);
1954}
1955
1956function get_404_template() {
1957        return get_query_template('404');
1958}
1959
1960function get_archive_template() {
1961        return get_query_template('archive');
1962}
1963
1964function get_author_template() {
1965        return get_query_template('author');
1966}
1967
1968function get_category_template() {
1969        $template = '';
1970        if ( file_exists(TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php') )
1971                $template = TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php';
1972        else if ( file_exists(TEMPLATEPATH . "/category.php") )
1973                $template = TEMPLATEPATH . "/category.php";
1974
1975        return apply_filters('category_template', $template);
1976}
1977
1978function get_date_template() {
1979        return get_query_template('date');
1980}
1981
1982function get_home_template() {
1983        $template = '';
1984
1985        if ( file_exists(TEMPLATEPATH . "/home.php") )
1986                $template = TEMPLATEPATH . "/home.php";
1987        else if ( file_exists(TEMPLATEPATH . "/index.php") )
1988                $template = TEMPLATEPATH . "/index.php";
1989
1990        return apply_filters('home_template', $template);
1991}
1992
1993function get_page_template() {
1994        global $wp_query;
1995
1996        $id = $wp_query->post->ID;
1997        $template = get_post_meta($id, '_wp_page_template', true);
1998
1999        if ( 'default' == $template )
2000                $template = '';
2001
2002        if ( ! empty($template) && file_exists(TEMPLATEPATH . "/$template") )
2003                $template = TEMPLATEPATH . "/$template";
2004        else if ( file_exists(TEMPLATEPATH . "/page.php") )
2005                $template = TEMPLATEPATH . "/page.php";
2006        else
2007                $template = '';
2008
2009        return apply_filters('page_template', $template);
2010}
2011
2012function get_paged_template() {
2013        return get_query_template('paged');
2014}
2015
2016function get_search_template() {
2017        return get_query_template('search');
2018}
2019
2020function get_single_template() {
2021        return get_query_template('single');
2022}
2023
2024function get_attachment_template() {
2025        global $posts;
2026        $type = explode('/', $posts[0]->post_mime_type);
2027        if ( $template = get_query_template($type[0]) )
2028                return $template;
2029        elseif ( $template = get_query_template($type[1]) )
2030                return $template;
2031        elseif ( $template = get_query_template("$type[0]_$type[1]") )
2032                return $template;
2033        else
2034                return get_query_template('attachment');
2035}
2036
2037function get_comments_popup_template() {
2038        if ( file_exists( TEMPLATEPATH . '/comments-popup.php') )
2039                $template = TEMPLATEPATH . '/comments-popup.php';
2040        else
2041                $template = get_theme_root() . '/default/comments-popup.php';
2042
2043        return apply_filters('comments_popup_template', $template);
2044}
2045
2046// Borrowed from the PHP Manual user notes. Convert entities, while
2047// preserving already-encoded entities:
2048function htmlentities2($myHTML) {
2049        $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
2050        $translation_table[chr(38)] = '&';
2051        return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , strtr($myHTML, $translation_table));
2052}
2053
2054
2055function is_plugin_page() {
2056        global $plugin_page;
2057
2058        if ( isset($plugin_page) )
2059                return true;
2060
2061        return false;
2062}
2063
2064/*
2065add_query_arg: Returns a modified querystring by adding
2066a single key & value or an associative array.
2067Setting a key value to emptystring removes the key.
2068Omitting oldquery_or_uri uses the $_SERVER value.
2069
2070Parameters:
2071add_query_arg(newkey, newvalue, oldquery_or_uri) or
2072add_query_arg(associative_array, oldquery_or_uri)
2073*/
2074function add_query_arg() {
2075        $ret = '';
2076        if ( is_array(func_get_arg(0)) ) {
2077                if ( @func_num_args() < 2 )
2078                        $uri = $_SERVER['REQUEST_URI'];
2079                else
2080                        $uri = @func_get_arg(1);
2081        } else {
2082                if ( @func_num_args() < 3 )
2083                        $uri = $_SERVER['REQUEST_URI'];
2084                else
2085                        $uri = @func_get_arg(2);
2086        }
2087
2088        if ( preg_match('|^https?://|i', $uri, $matches) ) {
2089                $protocol = $matches[0];
2090                $uri = substr($uri, strlen($protocol));
2091        } else {
2092                $protocol = '';
2093        }
2094
2095        if ( strstr($uri, '?') ) {
2096                $parts = explode('?', $uri, 2);
2097                if ( 1 == count($parts) ) {
2098                        $base = '?';
2099                        $query = $parts[0];
2100                } else {
2101                        $base = $parts[0] . '?';
2102                        $query = $parts[1];
2103                }
2104        } else if ( !empty($protocol) || strstr($uri, '/') ) {
2105                $base = $uri . '?';
2106                $query = '';
2107        } else {
2108                $base = '';
2109                $query = $uri;
2110        }
2111
2112        parse_str($query, $qs);
2113        if ( is_array(func_get_arg(0)) ) {
2114                $kayvees = func_get_arg(0);
2115                $qs = array_merge($qs, $kayvees);
2116        } else {
2117                $qs[func_get_arg(0)] = func_get_arg(1);
2118        }
2119
2120        foreach($qs as $k => $v) {
2121                if ( $v != '' ) {
2122                        if ( $ret != '' )
2123                                $ret .= '&';
2124                        $ret .= "$k=$v";
2125                }
2126        }
2127        $ret = $protocol . $base . $ret;
2128        return trim($ret, '?');
2129}
2130
2131function remove_query_arg($key, $query) {
2132        return add_query_arg($key, '', $query);
2133}
2134
2135function load_template($file) {
2136        global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query,
2137                $wp_rewrite, $wpdb;
2138
2139        extract($wp_query->query_vars);
2140
2141        require_once($file);
2142}
2143
2144function add_magic_quotes($array) {
2145        global $wpdb;
2146
2147        foreach ($array as $k => $v) {
2148                if ( is_array($v) ) {
2149                        $array[$k] = add_magic_quotes($v);
2150                } else {
2151                        $array[$k] = $wpdb->escape($v);
2152                }
2153        }
2154        return $array;
2155}
2156
2157function wp_remote_fopen( $uri ) {
2158        if ( ini_get('allow_url_fopen') ) {
2159                $fp = fopen( $uri, 'r' );
2160                if ( !$fp )
2161                        return false;
2162                $linea = '';
2163                while( $remote_read = fread($fp, 4096) )
2164                        $linea .= $remote_read;
2165                fclose($fp);
2166                return $linea;
2167        } else if ( function_exists('curl_init') ) {
2168                $handle = curl_init();
2169                curl_setopt ($handle, CURLOPT_URL, $uri);
2170                curl_setopt ($handle, CURLOPT_CONNECTTIMEOUT, 1);
2171                curl_setopt ($handle, CURLOPT_RETURNTRANSFER, 1);
2172                $buffer = curl_exec($handle);
2173                curl_close($handle);
2174                return $buffer;
2175        } else {
2176                return false;
2177        }
2178}
2179
2180function wp($query_vars = '') {
2181        global $wp;
2182       
2183        $wp->main($query_vars);
2184}
2185
2186function status_header( $header ) {
2187        if ( 200 == $header )
2188                $text = 'OK';
2189        elseif ( 301 == $header )
2190                $text = 'Moved Permanently';
2191        elseif ( 302 == $header )
2192                $text = 'Moved Temporarily';
2193        elseif ( 304 == $header )
2194                $text = 'Not Modified';
2195        elseif ( 404 == $header ) { //hacked by Brett to make extended archives work
2196                $text = 'OK';
2197                $header = '200'; }
2198        elseif ( 410 == $header )
2199                $text = 'Gone';
2200
2201        @header("HTTP/1.1 $header $text");
2202        @header("Status: $header $text");
2203}
2204
2205
2206function nocache_headers() {
2207        @ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
2208        @ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2209        @ header('Cache-Control: no-cache, must-revalidate, max-age=0');
2210        @ header('Pragma: no-cache');
2211}
2212
2213function get_usermeta( $user_id, $meta_key = '') {
2214        global $wpdb;
2215        $user_id = (int) $user_id;
2216
2217        if ( !empty($meta_key) ) {
2218                $meta_key = preg_replace('|a-z0-9_|i', '', $meta_key);
2219                $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2220        } else {
2221                $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id'");
2222        }
2223
2224        if ( empty($metas) ) {
2225                if ( empty($meta_key) )
2226                        return array();
2227                else
2228                        return '';
2229        }
2230
2231        foreach ($metas as $index => $meta) {
2232                @ $value = unserialize($meta->meta_value);
2233                if ( $value === FALSE )
2234                        $value = $meta->meta_value;
2235
2236                $values[] = $value;
2237        }
2238
2239        if ( count($values) == 1 )
2240                return $values[0];
2241        else
2242                return $values;
2243}
2244
2245function update_usermeta( $user_id, $meta_key, $meta_value ) {
2246        global $wpdb;
2247        if ( !is_numeric( $user_id ) )
2248                return false;
2249        $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
2250
2251        if ( is_array($meta_value) || is_object($meta_value) )
2252                $meta_value = serialize($meta_value);
2253        $meta_value = trim( $meta_value );
2254       
2255        if (empty($meta_value)) {
2256                delete_usermeta($user_id, $meta_key);
2257        }
2258
2259        $cur = $wpdb->get_row("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2260        if ( !$cur ) {
2261                $wpdb->query("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value )
2262                VALUES
2263                ( '$user_id', '$meta_key', '$meta_value' )");
2264        } else if ( $cur->meta_value != $meta_value ) {
2265                $wpdb->query("UPDATE $wpdb->usermeta SET meta_value = '$meta_value' WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2266        } else {
2267                return false;   
2268        }
2269       
2270        $user = get_userdata($user_id);
2271        wp_cache_delete($user_id, 'users');
2272        wp_cache_delete($user->user_login, 'userlogins');
2273       
2274        return true;
2275}
2276
2277function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) {
2278        global $wpdb;
2279        if ( !is_numeric( $user_id ) )
2280                return false;
2281        $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
2282
2283        if ( is_array($meta_value) || is_object($meta_value) )
2284                $meta_value = serialize($meta_value);
2285        $meta_value = trim( $meta_value );
2286
2287        if ( ! empty($meta_value) )
2288                $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key' AND meta_value = '$meta_value'");
2289        else
2290                $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2291               
2292        $user = get_userdata($user_id);
2293        wp_cache_delete($user_id, 'users');
2294        wp_cache_delete($user->user_login, 'userlogins');
2295       
2296        return true;
2297}
2298
2299function register_activation_hook($file, $function) {
2300        $file = plugin_basename($file);
2301
2302        add_action('activate_' . $file, $function);
2303}
2304
2305function register_deactivation_hook($file, $function) {
2306        $file = plugin_basename($file);
2307
2308        add_action('deactivate_' . $file, $function);
2309}
2310
2311function plugin_basename($file) {
2312        $file = preg_replace('|\\\\+|', '\\\\', $file);
2313        $file = preg_replace('/^.*wp-content[\\\\\/]plugins[\\\\\/]/', '', $file);
2314        return $file;
2315}
2316
2317function get_num_queries() {
2318        global $wpdb;
2319        return $wpdb->num_queries;
2320}
2321
2322function wp_nonce_url($actionurl, $action = -1) {
2323        return wp_specialchars(add_query_arg('_wpnonce', wp_create_nonce($action), $actionurl));
2324}
2325
2326function wp_nonce_field($action = -1) {
2327        echo '<input type="hidden" name="_wpnonce" value="' . wp_create_nonce($action) . '" />';
2328        wp_referer_field();
2329}
2330
2331function wp_referer_field() {
2332        $ref = wp_specialchars($_SERVER['REQUEST_URI']);
2333        echo '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
2334        if ( wp_get_original_referer() ) {
2335                $original_ref = wp_specialchars(stripslashes(wp_get_original_referer()));
2336                echo '<input type="hidden" name="_wp_original_http_referer" value="'. $original_ref . '" />';
2337        }
2338}
2339
2340function wp_original_referer_field() {
2341        echo '<input type="hidden" name="_wp_original_http_referer" value="' . wp_specialchars(stripslashes($_SERVER['REQUEST_URI'])) . '" />';
2342}
2343
2344function wp_get_referer() {
2345        foreach ( array($_REQUEST['_wp_http_referer'], $_SERVER['HTTP_REFERER']) as $ref )
2346                if ( !empty($ref) )
2347                        return $ref;
2348        return false;
2349}
2350
2351function wp_get_original_referer() {
2352        if ( !empty($_REQUEST['_wp_original_http_referer']) )
2353                return $_REQUEST['_wp_original_http_referer'];
2354        return false;
2355}
2356
2357function wp_explain_nonce($action) {
2358        if ( $action !== -1 && preg_match('/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches) ) {
2359                $verb = $matches[1];
2360                $noun = $matches[2];
2361
2362                $trans = array();
2363                $trans['update']['attachment'] = array(__('Are you sure you want to edit this attachment: &quot;%s&quot;?'), 'get_the_title');
2364
2365                $trans['add']['category'] = array(__('Are you sure you want to add this category?'), false);
2366                $trans['delete']['category'] = array(__('Are you sure you want to delete this category: &quot;%s&quot;?'), 'get_catname');
2367                $trans['update']['category'] = array(__('Are you sure you want to edit this category: &quot;%s&quot;?'), 'get_catname');
2368
2369                $trans['delete']['comment'] = array(__('Are you sure you want to delete this comment: &quot;%s&quot;?'), 'use_id');
2370                $trans['unapprove']['comment'] = array(__('Are you sure you want to unapprove this comment: &quot;%s&quot;?'), 'use_id');
2371                $trans['approve']['comment'] = array(__('Are you sure you want to approve this comment: &quot;%s&quot;?'), 'use_id');
2372                $trans['update']['comment'] = array(__('Are you sure you want to edit this comment: &quot;%s&quot;?'), 'use_id');
2373                $trans['bulk']['comments'] = array(__('Are you sure you want to bulk modify comments?'), false);
2374                $trans['moderate']['comments'] = array(__('Are you sure you want to moderate comments?'), false);
2375
2376                $trans['add']['bookmark'] = array(__('Are you sure you want to add this bookmark?'), false);
2377                $trans['delete']['bookmark'] = array(__('Are you sure you want to delete this bookmark: &quot;%s&quot;?'), 'use_id');
2378                $trans['update']['bookmark'] = array(__('Are you sure you want to edit this bookmark: &quot;%s&quot;?'), 'use_id');
2379                $trans['bulk']['bookmarks'] = array(__('Are you sure you want to bulk modify bookmarks?'), false);
2380
2381                $trans['add']['page'] = array(__('Are you sure you want to add this page?'), false);
2382                $trans['delete']['page'] = array(__('Are you sure you want to delete this page: &quot;%s&quot;?'), 'get_the_title');
2383                $trans['update']['page'] = array(__('Are you sure you want to edit this page: &quot;%s&quot;?'), 'get_the_title');
2384
2385                $trans['edit']['plugin'] = array(__('Are you sure you want to edit this plugin file: &quot;%s&quot;?'), 'use_id');
2386                $trans['activate']['plugin'] = array(__('Are you sure you want to activate this plugin: &quot;%s&quot;?'), 'use_id');
2387                $trans['deactivate']['plugin'] = array(__('Are you sure you want to deactivate this plugin: &quot;%s&quot;?'), 'use_id');
2388
2389                $trans['add']['post'] = array(__('Are you sure you want to add this post?'), false);
2390                $trans['delete']['post'] = array(__('Are you sure you want to delete this post: &quot;%s&quot;?'), 'get_the_title');
2391                $trans['update']['post'] = array(__('Are you sure you want to edit this post: &quot;%s&quot;?'), 'get_the_title');
2392
2393                $trans['add']['user'] = array(__('Are you sure you want to add this user?'), false);
2394                $trans['delete']['users'] = array(__('Are you sure you want to delete users?'), false);
2395                $trans['bulk']['users'] = array(__('Are you sure you want to bulk modify users?'), false);
2396                $trans['update']['user'] = array(__('Are you sure you want to edit this user: &quot;%s&quot;?'), 'get_author_name');
2397                $trans['update']['profile'] = array(__('Are you sure you want to modify the profile for: &quot;%s&quot;?'), 'get_author_name');
2398
2399                $trans['update']['options'] = array(__('Are you sure you want to edit your settings?'), false);
2400                $trans['update']['permalink'] = array(__('Are you sure you want to change your permalink structure to: %s?'), 'use_id');
2401                $trans['edit']['file'] = array(__('Are you sure you want to edit this file: &quot;%s&quot;?'), 'use_id');
2402                $trans['edit']['theme'] = array(__('Are you sure you want to edit this theme file: &quot;%s&quot;?'), 'use_id');
2403                $trans['switch']['theme'] = array(__('Are you sure you want to switch to this theme: &quot;%s&quot;?'), 'use_id');
2404
2405                if ( isset($trans[$verb][$noun]) ) {
2406                        if ( !empty($trans[$verb][$noun][1]) ) {
2407                                $lookup = $trans[$verb][$noun][1];
2408                                $object = $matches[4];
2409                                if ( 'use_id' != $lookup )
2410                                        $object = call_user_func($lookup, $object);
2411                                return sprintf($trans[$verb][$noun][0], $object);
2412                        } else {
2413                                return $trans[$verb][$noun][0];
2414                        }
2415                }
2416        }
2417
2418        return __('Are you sure you want to do this');
2419}
2420
2421function wp_nonce_ays($action) {
2422        global $pagenow, $menu, $submenu, $parent_file, $submenu_file;
2423
2424        $adminurl = get_settings('siteurl') . '/wp-admin';
2425        if ( wp_get_referer() )
2426                $adminurl = wp_get_referer();
2427
2428        $title = __('WordPress Confirmation');
2429        // Remove extra layer of slashes.
2430        $_POST   = stripslashes_deep($_POST  );
2431        if ( $_POST ) {
2432                $q = http_build_query($_POST);
2433                $q = explode( ini_get('arg_separator.output'), $q);
2434                $html .= "\t<form method='post' action='$pagenow'>\n";
2435                foreach ( (array) $q as $a ) {
2436                        $v = substr(strstr($a, '='), 1);
2437                        $k = substr($a, 0, -(strlen($v)+1));
2438                        $html .= "\t\t<input type='hidden' name='" . wp_specialchars( urldecode($k), 1 ) . "' value='" . wp_specialchars( urldecode($v), 1 ) . "' />\n";
2439                }
2440                $html .= "\t\t<input type='hidden' name='_wpnonce' value='" . wp_create_nonce($action) . "' />\n";
2441                $html .= "\t\t<div id='message' class='confirm fade'>\n\t\t<p>" . wp_explain_nonce($action) . "</p>\n\t\t<p><a href='$adminurl'>" . __('No') . "</a> <input type='submit' value='" . __('Yes') . "' /></p>\n\t\t</div>\n\t</form>\n";
2442        } else {
2443                $html .= "\t<div id='message' class='confirm fade'>\n\t<p>" . wp_explain_nonce($action) . "</p>\n\t<p><a href='$adminurl'>" . __('No') . "</a> <a href='" . add_query_arg( '_wpnonce', wp_create_nonce($action), $_SERVER['REQUEST_URI'] ) . "'>" . __('Yes') . "</a></p>\n\t</div>\n";
2444        }
2445        $html .= "</body>\n</html>";
2446        wp_die($html, $title);
2447}
2448
2449function wp_die($message, $title = '') {
2450        header('Content-Type: text/html; charset=utf-8');
2451
2452        if ( empty($title) )
2453                $title = __('WordPress &rsaquo; Error');
2454?>
2455<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2456<html xmlns="http://www.w3.org/1999/xhtml">
2457<head>
2458        <title><?php echo $title ?></title>
2459        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2460        <style media="screen" type="text/css">
2461        <!--
2462        html {
2463                background: #eee;
2464        }
2465        body {
2466                background: #fff;
2467                color: #000;
2468                font-family: Georgia, "Times New Roman", Times, serif;
2469                margin-left: 25%;
2470                margin-right: 25%;
2471                padding: .2em 2em;
2472        }
2473
2474        h1 {
2475                color: #006;
2476                font-size: 18px;
2477                font-weight: lighter;
2478        }
2479
2480        h2 {
2481                font-size: 16px;
2482        }
2483
2484        p, li, dt {
2485                line-height: 140%;
2486                padding-bottom: 2px;
2487        }
2488
2489        ul, ol {
2490                padding: 5px 5px 5px 20px;
2491        }
2492        #logo {
2493                margin-bottom: 2em;
2494        }
2495        -->
2496        </style>
2497</head>
2498<body>
2499        <h1 id="logo"><img alt="WordPress" src="<?php echo get_settings('siteurl'); ?>/wp-admin/images/wordpress-logo.png" /></h1>
2500        <p><?php echo $message; ?></p>
2501</body>
2502</html>
2503<?php
2504
2505        die();
2506}
2507
2508?>