3 require_once(dirname(__FILE__).'/functions-compat.php');
5 if ( !function_exists('_') ) {
11 function get_profile($field, $user = false) {
14 $user = $wpdb->escape($_COOKIE[USER_COOKIE]);
15 return $wpdb->get_var("SELECT $field FROM $wpdb->users WHERE user_login = '$user'");
18 function mysql2date($dateformatstring, $mysqlstring, $translate = true) {
19 global $month, $weekday, $month_abbrev, $weekday_abbrev;
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));
26 if ( -1 == $i || false == $i )
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);
40 $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
42 $j = @date($dateformatstring, $i);
45 // echo $i." ".$mysqlstring;
50 function current_time($type, $gmt = 0) {
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)));
58 if ( $gmt ) $d = time();
59 else $d = time() + (get_settings('gmt_offset') * 3600);
65 function date_i18n($dateformatstring, $unixtimestamp) {
66 global $month, $weekday, $month_abbrev, $weekday_abbrev;
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);
80 $j = @date($dateformatstring, $i);
84 function 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);
92 if ( $weekday < get_settings('start_of_week') )
93 $weekday = 7 - (get_settings('start_of_week') - $weekday);
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);
103 $week['start'] = $day + 86400 - $i;
104 // $week['end'] = $day - $i + 691199;
105 $week['end'] = $week['start'] + 604799;
109 function 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)) {
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");
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");
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");
126 $cache_lastpostdate[$timezone] = $lastpostdate;
128 $lastpostdate = $cache_lastpostdate[$timezone];
130 return $lastpostdate;
133 function 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)) {
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");
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");
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");
150 $lastpostdate = get_lastpostdate($timezone);
151 if ( $lastpostdate > $lastpostmodified ) {
152 $lastpostmodified = $lastpostdate;
154 $cache_lastpostmodified[$timezone] = $lastpostmodified;
156 $lastpostmodified = $cache_lastpostmodified[$timezone];
158 return $lastpostmodified;
161 function user_pass_ok($user_login,$user_pass) {
162 global $cache_userdata;
163 if ( empty($cache_userdata[$user_login]) ) {
164 $userdata = get_userdatabylogin($user_login);
166 $userdata = $cache_userdata[$user_login];
168 return (md5($user_pass) == $userdata->user_pass);
172 function get_usernumposts($userid) {
174 return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid' AND post_status = 'publish'");
178 // examine a url (supposedly from this blog) and try to
179 // determine the post ID it represents.
180 function url_to_postid($url) {
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;
188 // Check to see if we are using rewrite rules
189 $rewrite = $wp_rewrite->wp_rewrite_rules();
191 // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
192 if ( empty($rewrite) )
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
200 // Get rid of the #anchor
201 $url_split = explode('#', $url);
202 $url = $url_split[0];
204 // Get rid of URI ?query=string
205 $url_split = explode('?', $url);
206 $url = $url_split[0];
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);
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);
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);
220 if ( false !== strpos($url, get_settings('home')) ) {
221 // Chop off http://domain.com
222 $url = str_replace(get_settings('home'), '', $url);
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);
230 // Trim leading and lagging slashes
231 $url = trim($url, '/');
238 $request_match = $request;
239 foreach ($rewrite as $match => $query) {
240 // If the requesting file is the anchor of the match, prepend it
242 if ( (! empty($url)) && (strpos($match, $url) === 0) ) {
243 $request_match = $url . '/' . $request;
246 if ( preg_match("!^$match!", $request_match, $matches) ) {
248 // Trim the query of everything up to the '?'.
249 $query = preg_replace("!^.+\?!", '', $query);
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;
264 function maybe_unserialize($original) {
265 if ( false !== $gm = @ unserialize($original) )
271 /* Options functions */
273 function get_settings($setting) {
276 $value = wp_cache_get($setting, 'options');
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();
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');
293 // If home is not set use siteurl.
294 if ( 'home' == $setting && '' == $value )
295 return get_settings('siteurl');
297 if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
298 $value = preg_replace('|/+$|', '', $value);
300 return apply_filters( 'option_' . $setting, maybe_unserialize($value) );
303 function get_option($option) {
304 return get_settings($option);
307 function get_user_option( $option, $user = 0 ) {
308 global $wpdb, $current_user;
311 $user = $current_user;
313 $user = get_userdata($user);
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};
320 return get_option( $option );
323 function form_option($option) {
324 echo htmlspecialchars( get_option($option), ENT_QUOTES );
327 function 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");
333 $wpdb->show_errors();
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);
347 return apply_filters('all_options', $all_options);
350 function update_option($option_name, $newvalue) {
353 if ( is_string($newvalue) )
354 $newvalue = trim($newvalue);
356 // If the new and old values are the same, no need to update.
357 $oldvalue = get_option($option_name);
358 if ( $newvalue == $oldvalue ) {
362 if ( false === $oldvalue ) {
363 add_option($option_name, $newvalue);
367 if ( is_array($newvalue) || is_object($newvalue) )
368 $newvalue = serialize($newvalue);
370 wp_cache_set($option_name, $newvalue, 'options');
372 $newvalue = $wpdb->escape($newvalue);
373 $option_name = $wpdb->escape($option_name);
374 $wpdb->query("UPDATE $wpdb->options SET option_value = '$newvalue' WHERE option_name = '$option_name'");
375 if ( $wpdb->rows_affected == 1 ) {
376 do_action("update_option_{$option_name}", $oldvalue, $newvalue);
382 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
385 $option_name = $wpdb->prefix . $option_name;
386 return update_usermeta( $user_id, $option_name, $newvalue );
389 // thx Alex Stapleton, http://alex.vort-x.net/blog/
390 function add_option($name, $value = '', $description = '', $autoload = 'yes') {
393 // Make sure the option doesn't already exist
394 if ( false !== get_option($name) )
397 if ( is_array($value) || is_object($value) )
398 $value = serialize($value);
400 wp_cache_set($name, $value, 'options');
402 $name = $wpdb->escape($name);
403 $value = $wpdb->escape($value);
404 $description = $wpdb->escape($description);
405 $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, option_description, autoload) VALUES ('$name', '$value', '$description', '$autoload')");
410 function delete_option($name) {
412 // Get the ID, if no ID then return
413 $option_id = $wpdb->get_var("SELECT option_id FROM $wpdb->options WHERE option_name = '$name'");
414 if ( !$option_id ) return false;
415 $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = '$name'");
416 wp_cache_delete($name, 'options');
420 function add_post_meta($post_id, $key, $value, $unique = false) {
421 global $wpdb, $post_meta_cache;
424 if ( $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
425 = '$key' AND post_id = '$post_id'") ) {
431 if ( is_array($value) || is_object($value) )
432 $value = $wpdb->escape(serialize($value));
434 $wpdb->query("INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) VALUES ('$post_id','$key','$value')");
436 $post_meta_cache['$post_id'][$key][] = $original;
441 function delete_post_meta($post_id, $key, $value = '') {
442 global $wpdb, $post_meta_cache;
444 if ( empty($value) ) {
445 $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE
446 post_id = '$post_id' AND meta_key = '$key'");
448 $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE
449 post_id = '$post_id' AND meta_key = '$key' AND meta_value = '$value'");
455 if ( empty($value) ) {
456 $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id'
457 AND meta_key = '$key'");
458 unset($post_meta_cache['$post_id'][$key]);
460 $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id'
461 AND meta_key = '$key' AND meta_value = '$value'");
462 $cache_key = $post_meta_cache['$post_id'][$key];
463 if ($cache_key) foreach ( $cache_key as $index => $data )
464 if ( $data == $value )
465 unset($post_meta_cache['$post_id'][$key][$index]);
468 unset($post_meta_cache['$post_id'][$key]);
473 function get_post_meta($post_id, $key, $single = false) {
474 global $wpdb, $post_meta_cache;
476 if ( isset($post_meta_cache[$post_id][$key]) ) {
478 return maybe_unserialize( $post_meta_cache[$post_id][$key][0] );
480 return maybe_unserialize( $post_meta_cache[$post_id][$key] );
484 $metalist = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = '$key'", ARRAY_N);
488 foreach ($metalist as $metarow) {
489 $values[] = $metarow[0];
494 if ( count($values) ) {
495 $return = maybe_unserialize( $values[0] );
503 return maybe_unserialize($return);
506 function update_post_meta($post_id, $key, $value, $prev_value = '') {
507 global $wpdb, $post_meta_cache;
509 $original_value = $value;
510 if ( is_array($value) || is_object($value) )
511 $value = $wpdb->escape(serialize($value));
513 $original_prev = $prev_value;
514 if ( is_array($prev_value) || is_object($prev_value) )
515 $prev_value = $wpdb->escape(serialize($prev_value));
517 if (! $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
518 = '$key' AND post_id = '$post_id'") ) {
522 if ( empty($prev_value) ) {
523 $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE
524 meta_key = '$key' AND post_id = '$post_id'");
525 $cache_key = $post_meta_cache['$post_id'][$key];
526 if ( !empty($cache_key) )
527 foreach ($cache_key as $index => $data)
528 $post_meta_cache['$post_id'][$key][$index] = $original_value;
530 $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE
531 meta_key = '$key' AND post_id = '$post_id' AND meta_value = '$prev_value'");
532 $cache_key = $post_meta_cache['$post_id'][$key];
533 if ( !empty($cache_key) )
534 foreach ($cache_key as $index => $data)
535 if ( $data == $original_prev )
536 $post_meta_cache['$post_id'][$key][$index] = $original_value;
542 // Deprecated. Use get_post().
543 function get_postdata($postid) {
544 $post = &get_post($postid);
548 'Author_ID' => $post->post_author,
549 'Date' => $post->post_date,
550 'Content' => $post->post_content,
551 'Excerpt' => $post->post_excerpt,
552 'Title' => $post->post_title,
553 'Category' => $post->post_category,
554 'post_status' => $post->post_status,
555 'comment_status' => $post->comment_status,
556 'ping_status' => $post->ping_status,
557 'post_password' => $post->post_password,
558 'to_ping' => $post->to_ping,
559 'pinged' => $post->pinged,
560 'post_name' => $post->post_name
566 // Retrieves post data given a post ID or post object.
567 // Handles post caching.
568 function &get_post(&$post, $output = OBJECT) {
569 global $post_cache, $wpdb;
571 if ( empty($post) ) {
572 if ( isset($GLOBALS['post']) )
573 $_post = & $GLOBALS['post'];
576 } elseif ( is_object($post) ) {
577 if ( 'static' == $post->post_status )
578 return get_page($post, $output);
579 if ( !isset($post_cache[$post->ID]) )
580 $post_cache[$post->ID] = &$post;
581 $_post = & $post_cache[$post->ID];
583 if ( $_post = wp_cache_get($post, 'pages') )
584 return get_page($_post, $output);
585 elseif ( isset($post_cache[$post]) )
586 $_post = & $post_cache[$post];
588 $query = "SELECT * FROM $wpdb->posts WHERE ID = '$post' LIMIT 1";
589 $_post = & $wpdb->get_row($query);
590 if ( 'static' == $_post->post_status )
591 return get_page($_post, $output);
592 $post_cache[$post] = & $_post;
596 if ( defined(WP_IMPORTING) )
599 if ( $output == OBJECT ) {
601 } elseif ( $output == ARRAY_A ) {
602 return get_object_vars($_post);
603 } elseif ( $output == ARRAY_N ) {
604 return array_values(get_object_vars($_post));
610 function &get_children($post = 0, $output = OBJECT) {
611 global $post_cache, $wpdb;
613 if ( empty($post) ) {
614 if ( isset($GLOBALS['post']) )
615 $post_parent = & $GLOBALS['post']->post_parent;
618 } elseif ( is_object($post) ) {
619 $post_parent = $post->post_parent;
621 $post_parent = $post;
624 $post_parent = (int) $post_parent;
626 $query = "SELECT * FROM $wpdb->posts WHERE post_parent = $post_parent";
628 $children = $wpdb->get_results($query);
631 foreach ( $children as $key => $child ) {
632 $post_cache[$child->ID] =& $children[$key];
633 $kids[$child->ID] =& $children[$key];
639 if ( $output == OBJECT ) {
641 } elseif ( $output == ARRAY_A ) {
642 foreach ( $kids as $kid )
643 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
645 } elseif ( $output == ARRAY_N ) {
646 foreach ( $kids as $kid )
647 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
654 function set_page_path($page) {
655 $page->fullpath = '/' . $page->post_name;
656 $path = $page->fullpath;
658 while ($curpage->post_parent != 0) {
659 $curpage = get_page($curpage->post_parent);
660 $path = '/' . $curpage->post_name . $path;
663 $page->fullpath = $path;
668 // Retrieves page data given a page ID or page object.
669 // Handles page caching.
670 function &get_page(&$page, $output = OBJECT) {
673 if ( empty($page) ) {
674 if ( isset($GLOBALS['page']) ) {
675 $_page = & $GLOBALS['page'];
676 wp_cache_add($_page->ID, $_page, 'pages');
680 } elseif ( is_object($page) ) {
681 if ( 'static' != $page->post_status )
682 return get_post($page, $output);
683 wp_cache_add($page->ID, $page, 'pages');
686 if ( isset($GLOBALS['page']) && ($page == $GLOBALS['page']->ID) ) {
687 $_page = & $GLOBALS['page'];
688 wp_cache_add($_page->ID, $_page, 'pages');
689 } elseif ( $_page = $GLOBALS['post_cache'][$page] ) {
690 return get_post($page, $output);
691 } elseif ( $_page = wp_cache_get($page, 'pages') ) {
694 $query = "SELECT * FROM $wpdb->posts WHERE ID= '$page' LIMIT 1";
695 $_page = & $wpdb->get_row($query);
696 if ( 'static' != $_page->post_status )
697 return get_post($_page, $output);
698 wp_cache_add($_page->ID, $_page, 'pages');
702 if (!isset($_page->fullpath)) {
703 $_page = set_page_path($_page);
704 wp_cache_replace($_page->cat_ID, $_page, 'pages');
707 if ( $output == OBJECT ) {
709 } elseif ( $output == ARRAY_A ) {
710 return get_object_vars($_page);
711 } elseif ( $output == ARRAY_N ) {
712 return array_values(get_object_vars($_page));
718 function set_category_path($cat) {
719 $cat->fullpath = '/' . $cat->category_nicename;
720 $path = $cat->fullpath;
722 while ($curcat->category_parent != 0) {
723 $curcat = get_category($curcat->category_parent);
724 $path = '/' . $curcat->category_nicename . $path;
727 $cat->fullpath = $path;
732 // Retrieves category data given a category ID or category object.
733 // Handles category caching.
734 function &get_category(&$category, $output = OBJECT) {
737 if ( empty($category) )
740 if ( is_object($category) ) {
741 wp_cache_add($category->cat_ID, $category, 'category');
742 $_category = $category;
744 if ( ! $_category = wp_cache_get($category, 'category') ) {
745 $_category = $wpdb->get_row("SELECT * FROM $wpdb->categories WHERE cat_ID = '$category' LIMIT 1");
746 wp_cache_add($category, $_category, 'category');
750 if ( !isset($_category->fullpath) ) {
751 $_category = set_category_path($_category);
752 wp_cache_replace($_category->cat_ID, $_category, 'category');
755 if ( $output == OBJECT ) {
757 } elseif ( $output == ARRAY_A ) {
758 return get_object_vars($_category);
759 } elseif ( $output == ARRAY_N ) {
760 return array_values(get_object_vars($_category));
766 // Retrieves comment data given a comment ID or comment object.
767 // Handles comment caching.
768 function &get_comment(&$comment, $output = OBJECT) {
769 global $comment_cache, $wpdb;
771 if ( empty($comment) )
774 if ( is_object($comment) ) {
775 if ( !isset($comment_cache[$comment->comment_ID]) )
776 $comment_cache[$comment->comment_ID] = &$comment;
777 $_comment = & $comment_cache[$comment->comment_ID];
779 if ( !isset($comment_cache[$comment]) ) {
780 $_comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment' LIMIT 1");
781 $comment_cache[$comment->comment_ID] = & $_comment;
783 $_comment = & $comment_cache[$comment];
787 if ( $output == OBJECT ) {
789 } elseif ( $output == ARRAY_A ) {
790 return get_object_vars($_comment);
791 } elseif ( $output == ARRAY_N ) {
792 return array_values(get_object_vars($_comment));
798 function get_catname($cat_ID) {
799 $category = &get_category($cat_ID);
800 return $category->cat_name;
803 function get_all_category_ids() {
806 if ( ! $cat_ids = wp_cache_get('all_category_ids', 'category') ) {
807 $cat_ids = $wpdb->get_col("SELECT cat_ID FROM $wpdb->categories");
808 wp_cache_add('all_category_ids', $cat_ids, 'category');
814 function get_all_page_ids() {
817 if ( ! $page_ids = wp_cache_get('all_page_ids', 'pages') ) {
818 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_status='static'");
819 wp_cache_add('all_page_ids', $page_ids, 'pages');
825 function gzip_compression() {
826 if ( !get_settings('gzipcompression') ) return false;
828 if ( extension_loaded('zlib') ) {
829 ob_start('ob_gzhandler');
834 // functions to count the page generation time (from phpBB2)
835 // ( or just any time between timer_start() and timer_stop() )
837 function timer_stop($display = 0, $precision = 3) { //if called like timer_stop(1), will echo $timetotal
838 global $timestart, $timeend;
839 $mtime = microtime();
840 $mtime = explode(' ',$mtime);
841 $mtime = $mtime[1] + $mtime[0];
843 $timetotal = $timeend-$timestart;
845 echo number_format($timetotal,$precision);
849 function weblog_ping($server = '', $path = '') {
851 include_once (ABSPATH . WPINC . '/class-IXR.php');
853 // using a timeout of 3 seconds should be enough to cover slow servers
854 $client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
855 $client->timeout = 3;
856 $client->useragent .= ' -- WordPress/'.$wp_version;
858 // when set to true, this outputs debug messages by itself
859 $client->debug = false;
860 $home = trailingslashit( get_option('home') );
861 if ( !$client->query('weblogUpdates.extendedPing', get_settings('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
862 $client->query('weblogUpdates.ping', get_settings('blogname'), $home);
865 function generic_ping($post_id = 0) {
866 $services = get_settings('ping_sites');
867 $services = preg_replace("|(\s)+|", '$1', $services); // Kill dupe lines
868 $services = trim($services);
869 if ( '' != $services ) {
870 $services = explode("\n", $services);
871 foreach ($services as $service) {
872 weblog_ping($service);
880 function trackback($trackback_url, $title, $excerpt, $ID) {
881 global $wpdb, $wp_version;
883 if ( empty($trackback_url) )
886 $title = urlencode($title);
887 $excerpt = urlencode($excerpt);
888 $blog_name = urlencode(get_settings('blogname'));
889 $tb_url = $trackback_url;
890 $url = urlencode(get_permalink($ID));
891 $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
892 $trackback_url = parse_url($trackback_url);
893 $http_request = 'POST ' . $trackback_url['path'] . ($trackback_url['query'] ? '?'.$trackback_url['query'] : '') . " HTTP/1.0\r\n";
894 $http_request .= 'Host: '.$trackback_url['host']."\r\n";
895 $http_request .= 'Content-Type: application/x-www-form-urlencoded; charset='.get_settings('blog_charset')."\r\n";
896 $http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
897 $http_request .= "User-Agent: WordPress/" . $wp_version;
898 $http_request .= "\r\n\r\n";
899 $http_request .= $query_string;
900 if ( '' == $trackback_url['port'] )
901 $trackback_url['port'] = 80;
902 $fs = @fsockopen($trackback_url['host'], $trackback_url['port'], $errno, $errstr, 4);
903 @fputs($fs, $http_request);
905 $debug_file = 'trackback.log';
906 $fp = fopen($debug_file, 'a');
907 fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
909 fwrite($fp, @fgets($fs, 4096));
916 $tb_url = addslashes( $tb_url );
917 $wpdb->query("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
918 return $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_url', '')) WHERE ID = '$ID'");
921 function make_url_footnote($content) {
922 preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
924 for ($i=0; $i<count($matches[0]); $i++) {
925 $links_summary = (!$j) ? "\n" : $links_summary;
927 $link_match = $matches[0][$i];
928 $link_number = '['.($i+1).']';
929 $link_url = $matches[2][$i];
930 $link_text = $matches[4][$i];
931 $content = str_replace($link_match, $link_text.' '.$link_number, $content);
932 $link_url = ((strtolower(substr($link_url,0,7)) != 'http://') && (strtolower(substr($link_url,0,8)) != 'https://')) ? get_settings('home') . $link_url : $link_url;
933 $links_summary .= "\n".$link_number.' '.$link_url;
935 $content = strip_tags($content);
936 $content .= $links_summary;
941 function xmlrpc_getposttitle($content) {
942 global $post_default_title;
943 if ( preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle) ) {
944 $post_title = $matchtitle[0];
945 $post_title = preg_replace('/<title>/si', '', $post_title);
946 $post_title = preg_replace('/<\/title>/si', '', $post_title);
948 $post_title = $post_default_title;
953 function xmlrpc_getpostcategory($content) {
954 global $post_default_category;
955 if ( preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat) ) {
956 $post_category = trim($matchcat[1], ',');
957 $post_category = explode(',', $post_category);
959 $post_category = $post_default_category;
961 return $post_category;
964 function xmlrpc_removepostdata($content) {
965 $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content);
966 $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content);
967 $content = trim($content);
971 function debug_fopen($filename, $mode) {
974 $fp = fopen($filename, $mode);
981 function debug_fwrite($fp, $string) {
984 fwrite($fp, $string);
988 function debug_fclose($fp) {
995 function spawn_pinger() {
998 if ( $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE TRIM(to_ping) != '' LIMIT 1") )
1001 if ( $wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_pingme' OR meta_key = '_encloseme' LIMIT 1") )
1004 if ( substr(php_sapi_name(), 0, 3) == 'cgi' )
1008 $ping_url = get_settings('siteurl') .'/wp-admin/execute-pings.php';
1009 $parts = parse_url($ping_url);
1010 $argyle = @ fsockopen($parts['host'], $_SERVER['SERVER_PORT'], $errno, $errstr, 0.01);
1012 fputs($argyle, "GET {$parts['path']}?time=".time()." HTTP/1.0\r\nHost: {$_SERVER['HTTP_HOST']}\r\n\r\n");
1016 function do_enclose( $content, $post_ID ) {
1017 global $wp_version, $wpdb;
1018 include_once (ABSPATH . WPINC . '/class-IXR.php');
1020 $log = debug_fopen(ABSPATH . '/enclosures.log', 'a');
1021 $post_links = array();
1022 debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");
1024 $pung = get_enclosed( $post_ID );
1027 $gunk = '/#~:.?+=&%@!\-';
1029 $any = $ltrs . $gunk . $punc;
1031 preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
1033 debug_fwrite($log, 'Post contents:');
1034 debug_fwrite($log, $content."\n");
1036 foreach($post_links_temp[0] as $link_test) :
1037 if ( !in_array($link_test, $pung) ) : // If we haven't pung it already
1038 $test = parse_url($link_test);
1039 if ( isset($test['query']) )
1040 $post_links[] = $link_test;
1041 elseif (($test['path'] != '/') && ($test['path'] != ''))
1042 $post_links[] = $link_test;
1046 foreach ($post_links as $url) :
1047 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%')") ) {
1048 if ( $headers = wp_get_http_headers( $url) ) {
1049 $len = (int) $headers['content-length'];
1050 $type = $wpdb->escape( $headers['content-type'] );
1051 $allowed_types = array( 'video', 'audio' );
1052 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
1053 $meta_value = "$url\n$len\n$type\n";
1054 $wpdb->query( "INSERT INTO `$wpdb->postmeta` ( `post_id` , `meta_key` , `meta_value` )
1055 VALUES ( '$post_ID', 'enclosure' , '$meta_value')" );
1062 function wp_get_http_headers( $url, $red = 1 ) {
1064 @set_time_limit( 60 );
1069 $parts = parse_url( $url );
1070 $file = $parts['path'] . ($parts['query'] ? '?'.$parts['query'] : '');
1071 $host = $parts['host'];
1072 if ( !isset( $parts['port'] ) )
1073 $parts['port'] = 80;
1075 $head = "HEAD $file HTTP/1.1\r\nHOST: $host\r\nUser-Agent: WordPress/" . $wp_version . "\r\n\r\n";
1077 $fp = @fsockopen($host, $parts['port'], $err_num, $err_msg, 3);
1082 fputs( $fp, $head );
1083 while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
1084 $response .= fgets( $fp, 2048 );
1086 preg_match_all('/(.*?): (.*)\r/', $response, $matches);
1087 $count = count($matches[1]);
1088 for ( $i = 0; $i < $count; $i++) {
1089 $key = strtolower($matches[1][$i]);
1090 $headers["$key"] = $matches[2][$i];
1093 $code = preg_replace('/.*?(\d{3}).*/i', '$1', $response);
1095 $headers['status_code'] = $code;
1097 if ( '302' == $code || '301' == $code )
1098 return wp_get_http_headers( $url, ++$red );
1100 preg_match('/.*([0-9]{3}).*/', $response, $return);
1101 $headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
1105 // Deprecated. Use the new post loop.
1106 function start_wp() {
1107 global $wp_query, $post;
1109 // Since the old style loop is being used, advance the query iterator here.
1110 $wp_query->next_post();
1112 setup_postdata($post);
1115 // Setup global post data.
1116 function setup_postdata($post) {
1117 global $id, $postdata, $authordata, $day, $page, $pages, $multipage, $more, $numpages, $wp_query;
1122 $authordata = get_userdata($post->post_author);
1124 $day = mysql2date('d.m.y', $post->post_date);
1125 $currentmonth = mysql2date('m', $post->post_date);
1127 $page = get_query_var('page');
1130 if ( is_single() || is_page() )
1132 $content = $post->post_content;
1133 if ( preg_match('/<!--nextpage-->/', $content) ) {
1137 $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
1138 $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
1139 $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
1140 $pages = explode('<!--nextpage-->', $content);
1141 $numpages = count($pages);
1143 $pages[0] = $post->post_content;
1149 function is_new_day() {
1150 global $day, $previousday;
1151 if ( $day != $previousday ) {
1158 // Filters: these are the core of WP's plugin architecture
1160 function merge_filters($tag) {
1162 if ( isset($wp_filter['all']) ) {
1163 foreach ($wp_filter['all'] as $priority => $functions) {
1164 if ( isset($wp_filter[$tag][$priority]) )
1165 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
1167 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
1168 $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
1172 if ( isset($wp_filter[$tag]) )
1173 ksort( $wp_filter[$tag] );
1176 function apply_filters($tag, $string) {
1179 $args = array_slice(func_get_args(), 2);
1181 merge_filters($tag);
1183 if ( !isset($wp_filter[$tag]) ) {
1186 foreach ($wp_filter[$tag] as $priority => $functions) {
1187 if ( !is_null($functions) ) {
1188 foreach($functions as $function) {
1190 $all_args = array_merge(array($string), $args);
1191 $function_name = $function['function'];
1192 $accepted_args = $function['accepted_args'];
1194 if ( $accepted_args == 1 )
1195 $the_args = array($string);
1196 elseif ( $accepted_args > 1 )
1197 $the_args = array_slice($all_args, 0, $accepted_args);
1198 elseif ( $accepted_args == 0 )
1201 $the_args = $all_args;
1203 $string = call_user_func_array($function_name, $the_args);
1210 function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
1213 // check that we don't already have the same filter at the same priority
1214 if ( isset($wp_filter[$tag]["$priority"]) ) {
1215 foreach($wp_filter[$tag]["$priority"] as $filter) {
1216 // uncomment if we want to match function AND accepted_args
1217 // if ( $filter == array($function, $accepted_args) ) {
1218 if ( $filter['function'] == $function_to_add ) {
1224 // So the format is wp_filter['tag']['array of priorities']['array of ['array (functions, accepted_args)]']
1225 $wp_filter[$tag]["$priority"][] = array('function'=>$function_to_add, 'accepted_args'=>$accepted_args);
1229 function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
1232 // rebuild the list of filters
1233 if ( isset($wp_filter[$tag]["$priority"]) ) {
1234 foreach($wp_filter[$tag]["$priority"] as $filter) {
1235 if ( $filter['function'] != $function_to_remove ) {
1236 $new_function_list[] = $filter;
1239 $wp_filter[$tag]["$priority"] = $new_function_list;
1244 // The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
1246 function do_action($tag, $arg = '') {
1248 $extra_args = array_slice(func_get_args(), 2);
1249 if ( is_array($arg) )
1250 $args = array_merge($arg, $extra_args);
1252 $args = array_merge(array($arg), $extra_args);
1254 merge_filters($tag);
1256 if ( !isset($wp_filter[$tag]) ) {
1259 foreach ($wp_filter[$tag] as $priority => $functions) {
1260 if ( !is_null($functions) ) {
1261 foreach($functions as $function) {
1263 $function_name = $function['function'];
1264 $accepted_args = $function['accepted_args'];
1266 if ( $accepted_args == 1 ) {
1267 if ( is_array($arg) )
1270 $the_args = array($arg);
1271 } elseif ( $accepted_args > 1 ) {
1272 $the_args = array_slice($args, 0, $accepted_args);
1273 } elseif ( $accepted_args == 0 ) {
1279 $string = call_user_func_array($function_name, $the_args);
1285 function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
1286 add_filter($tag, $function_to_add, $priority, $accepted_args);
1289 function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
1290 remove_filter($tag, $function_to_remove, $priority, $accepted_args);
1293 function get_page_uri($page_id) {
1294 $page = get_page($page_id);
1295 $uri = urldecode($page->post_name);
1297 // A page cannot be it's own parent.
1298 if ( $page->post_parent == $page->ID )
1301 while ($page->post_parent != 0) {
1302 $page = get_page($page->post_parent);
1303 $uri = urldecode($page->post_name) . "/" . $uri;
1309 function get_posts($args) {
1311 parse_str($args, $r);
1312 if ( !isset($r['numberposts']) )
1313 $r['numberposts'] = 5;
1314 if ( !isset($r['offset']) )
1316 if ( !isset($r['category']) )
1317 $r['category'] = '';
1318 if ( !isset($r['orderby']) )
1319 $r['orderby'] = 'post_date';
1320 if ( !isset($r['order']) )
1321 $r['order'] = 'DESC';
1323 $now = current_time('mysql');
1325 $posts = $wpdb->get_results(
1326 "SELECT DISTINCT * FROM $wpdb->posts " .
1327 ( empty( $r['category'] ) ? "" : ", $wpdb->post2cat " ) .
1328 " WHERE post_date <= '$now' AND (post_status = 'publish') ".
1329 ( empty( $r['category'] ) ? "" : "AND $wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $r['category']. " " ) .
1330 " GROUP BY $wpdb->posts.ID ORDER BY " . $r['orderby'] . " " . $r['order'] . " LIMIT " . $r['offset'] . ',' . $r['numberposts'] );
1332 update_post_caches($posts);
1337 function &query_posts($query) {
1339 return $wp_query->query($query);
1342 function update_post_cache(&$posts) {
1348 for ($i = 0; $i < count($posts); $i++) {
1349 $post_cache[$posts[$i]->ID] = &$posts[$i];
1353 function clean_post_cache($id) {
1356 if ( isset( $post_cache[$id] ) )
1357 unset( $post_cache[$id] );
1360 function update_page_cache(&$pages) {
1366 for ($i = 0; $i < count($pages); $i++) {
1367 $page_cache[$pages[$i]->ID] = &$pages[$i];
1368 wp_cache_add($pages[$i]->ID, $pages[$i], 'pages');
1373 function clean_page_cache($id) {
1376 if ( isset( $page_cache[$id] ) )
1377 unset( $page_cache[$id] );
1380 function update_post_category_cache($post_ids) {
1381 global $wpdb, $category_cache;
1383 if ( empty($post_ids) )
1386 if ( is_array($post_ids) )
1387 $post_ids = implode(',', $post_ids);
1389 $dogs = $wpdb->get_results("SELECT post_id, category_id FROM $wpdb->post2cat WHERE post_id IN ($post_ids)");
1394 foreach ($dogs as $catt)
1395 $category_cache[$catt->post_id][$catt->category_id] = &get_category($catt->category_id);
1398 function update_post_caches(&$posts) {
1399 global $post_cache, $category_cache, $comment_count_cache, $post_meta_cache;
1402 // No point in doing all this work if we didn't match any posts.
1406 // Get the categories for all the posts
1407 for ($i = 0; $i < count($posts); $i++) {
1408 $post_id_array[] = $posts[$i]->ID;
1409 $post_cache[$posts[$i]->ID] = &$posts[$i];
1410 $comment_count_cache[$posts[$i]->ID] = $posts[$i]->comment_count;
1413 $post_id_list = implode(',', $post_id_array);
1415 update_post_category_cache($post_id_list);
1417 // Get post-meta info
1418 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) ) {
1419 // Change from flat structure to hierarchical:
1420 $post_meta_cache = array();
1421 foreach ($meta_list as $metarow) {
1422 $mpid = $metarow['post_id'];
1423 $mkey = $metarow['meta_key'];
1424 $mval = $metarow['meta_value'];
1426 // Force subkeys to be array type:
1427 if ( !isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]) )
1428 $post_meta_cache[$mpid] = array();
1429 if ( !isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]) )
1430 $post_meta_cache[$mpid]["$mkey"] = array();
1432 // Add a value to the current pid/key:
1433 $post_meta_cache[$mpid][$mkey][] = $mval;
1438 function update_category_cache() {
1442 function wp_head() {
1443 do_action('wp_head');
1446 function wp_footer() {
1447 do_action('wp_footer');
1450 function is_single ($post = '') {
1453 if ( !$wp_query->is_single )
1456 if ( empty( $post) )
1459 $post_obj = $wp_query->get_queried_object();
1461 if ( $post == $post_obj->ID )
1463 elseif ( $post == $post_obj->post_title )
1465 elseif ( $post == $post_obj->post_name )
1471 function is_page ($page = '') {
1474 if ( !$wp_query->is_page )
1480 $page_obj = $wp_query->get_queried_object();
1482 if ( $page == $page_obj->ID )
1484 elseif ( $page == $page_obj->post_title )
1486 else if ( $page == $page_obj->post_name )
1492 function is_attachment () {
1495 return $wp_query->is_attachment;
1498 function is_preview() {
1501 return $wp_query->is_preview;
1504 function is_archive () {
1507 return $wp_query->is_archive;
1510 function is_date () {
1513 return $wp_query->is_date;
1516 function is_year () {
1519 return $wp_query->is_year;
1522 function is_month () {
1525 return $wp_query->is_month;
1528 function is_day () {
1531 return $wp_query->is_day;
1534 function is_time () {
1537 return $wp_query->is_time;
1540 function is_author ($author = '') {
1543 if ( !$wp_query->is_author )
1546 if ( empty($author) )
1549 $author_obj = $wp_query->get_queried_object();
1551 if ( $author == $author_obj->ID )
1553 elseif ( $author == $author_obj->nickname )
1555 elseif ( $author == $author_obj->user_nicename )
1561 function is_category ($category = '') {
1564 if ( !$wp_query->is_category )
1567 if ( empty($category) )
1570 $cat_obj = $wp_query->get_queried_object();
1572 if ( $category == $cat_obj->cat_ID )
1574 else if ( $category == $cat_obj->cat_name )
1576 elseif ( $category == $cat_obj->category_nicename )
1582 function is_search () {
1585 return $wp_query->is_search;
1588 function is_feed () {
1591 return $wp_query->is_feed;
1594 function is_trackback () {
1597 return $wp_query->is_trackback;
1600 function is_admin () {
1603 return ( $wp_query->is_admin || strstr($_SERVER['REQUEST_URI'], 'wp-admin/') );
1606 function is_home () {
1609 return $wp_query->is_home;
1612 function is_404 () {
1615 return $wp_query->is_404;
1618 function is_comments_popup () {
1621 return $wp_query->is_comments_popup;
1624 function is_paged () {
1627 return $wp_query->is_paged;
1630 function in_the_loop() {
1633 return $wp_query->in_the_loop;
1636 function get_query_var($var) {
1639 return $wp_query->get($var);
1642 function have_posts() {
1645 return $wp_query->have_posts();
1648 function rewind_posts() {
1651 return $wp_query->rewind_posts();
1654 function the_post() {
1657 $wp_query->the_post();
1660 function get_theme_root() {
1661 return apply_filters('theme_root', ABSPATH . "wp-content/themes");
1664 function get_theme_root_uri() {
1665 return apply_filters('theme_root_uri', get_settings('siteurl') . "/wp-content/themes", get_settings('siteurl'));
1668 function get_stylesheet() {
1669 return apply_filters('stylesheet', get_settings('stylesheet'));
1672 function get_stylesheet_directory() {
1673 $stylesheet = get_stylesheet();
1674 $stylesheet_dir = get_theme_root() . "/$stylesheet";
1675 return apply_filters('stylesheet_directory', $stylesheet_dir, $stylesheet);
1678 function get_stylesheet_directory_uri() {
1679 $stylesheet = rawurlencode( get_stylesheet() );
1680 $stylesheet_dir_uri = get_theme_root_uri() . "/$stylesheet";
1681 return apply_filters('stylesheet_directory_uri', $stylesheet_dir_uri, $stylesheet);
1684 function get_stylesheet_uri() {
1685 $stylesheet_dir_uri = get_stylesheet_directory_uri();
1686 $stylesheet_uri = $stylesheet_dir_uri . "/style.css";
1687 return apply_filters('stylesheet_uri', $stylesheet_uri, $stylesheet_dir_uri);
1690 function get_template() {
1691 $template = get_settings('template');
1692 if (!file_exists(get_theme_root() . "/$template")) { //works for dirs too
1693 update_option('template', 'default');
1694 update_option('stylesheet', 'default');
1696 return apply_filters('template', get_settings('template'));
1699 function get_template_directory() {
1700 $template = get_template();
1701 $template_dir = get_theme_root() . "/$template";
1702 return apply_filters('template_directory', $template_dir, $template);
1705 function get_template_directory_uri() {
1706 $template = get_template();
1707 $template_dir_uri = get_theme_root_uri() . "/$template";
1708 return apply_filters('template_directory_uri', $template_dir_uri, $template);
1711 function get_theme_data($theme_file) {
1712 $theme_data = implode('', file($theme_file));
1713 preg_match("|Theme Name:(.*)|i", $theme_data, $theme_name);
1714 preg_match("|Theme URI:(.*)|i", $theme_data, $theme_uri);
1715 preg_match("|Description:(.*)|i", $theme_data, $description);
1716 preg_match("|Author:(.*)|i", $theme_data, $author_name);
1717 preg_match("|Author URI:(.*)|i", $theme_data, $author_uri);
1718 preg_match("|Template:(.*)|i", $theme_data, $template);
1719 if ( preg_match("|Version:(.*)|i", $theme_data, $version) )
1720 $version = $version[1];
1723 if ( preg_match("|Status:(.*)|i", $theme_data, $status) )
1724 $status = $status[1];
1728 $description = wptexturize($description[1]);
1730 $name = $theme_name[1];
1731 $name = trim($name);
1734 if ( '' == $author_uri[1] ) {
1735 $author = $author_name[1];
1737 $author = '<a href="' . $author_uri[1] . '" title="' . __('Visit author homepage') . '">' . $author_name[1] . '</a>';
1740 return array('Name' => $name, 'Title' => $theme, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1], 'Status' => $status);
1743 function get_themes() {
1745 global $wp_broken_themes;
1747 if ( isset($wp_themes) )
1751 $wp_broken_themes = array();
1752 $theme_root = get_theme_root();
1753 $theme_loc = str_replace(ABSPATH, '', $theme_root);
1755 // Files in wp-content/themes directory
1756 $themes_dir = @ dir($theme_root);
1757 if ( $themes_dir ) {
1758 while(($theme_dir = $themes_dir->read()) !== false) {
1759 if ( is_dir($theme_root . '/' . $theme_dir) && is_readable($theme_root . '/' . $theme_dir) ) {
1760 if ( $theme_dir{0} == '.' || $theme_dir == '..' || $theme_dir == 'CVS' ) {
1763 $stylish_dir = @ dir($theme_root . '/' . $theme_dir);
1764 $found_stylesheet = false;
1765 while (($theme_file = $stylish_dir->read()) !== false) {
1766 if ( $theme_file == 'style.css' ) {
1767 $theme_files[] = $theme_dir . '/' . $theme_file;
1768 $found_stylesheet = true;
1772 if ( !$found_stylesheet ) {
1773 $wp_broken_themes[$theme_dir] = array('Name' => $theme_dir, 'Title' => $theme_dir, 'Description' => __('Stylesheet is missing.'));
1779 if ( !$themes_dir || !$theme_files ) {
1785 foreach($theme_files as $theme_file) {
1786 if ( ! is_readable("$theme_root/$theme_file") ) {
1787 $wp_broken_themes[$theme_file] = array('Name' => $theme_file, 'Title' => $theme_file, 'Description' => __('File not readable.'));
1791 $theme_data = get_theme_data("$theme_root/$theme_file");
1793 $name = $theme_data['Name'];
1794 $title = $theme_data['Title'];
1795 $description = wptexturize($theme_data['Description']);
1796 $version = $theme_data['Version'];
1797 $author = $theme_data['Author'];
1798 $template = $theme_data['Template'];
1799 $stylesheet = dirname($theme_file);
1801 foreach (array('png', 'gif', 'jpg', 'jpeg') as $ext) {
1802 if (file_exists("$theme_root/$stylesheet/screenshot.$ext")) {
1803 $screenshot = "screenshot.$ext";
1808 if ( empty($name) ) {
1809 $name = dirname($theme_file);
1813 if ( empty($template) ) {
1814 if ( file_exists(dirname("$theme_root/$theme_file/index.php")) ) {
1815 $template = dirname($theme_file);
1821 $template = trim($template);
1823 if ( !file_exists("$theme_root/$template/index.php") ) {
1824 $wp_broken_themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => __('Template is missing.'));
1828 $stylesheet_files = array();
1829 $stylesheet_dir = @ dir("$theme_root/$stylesheet");
1830 if ( $stylesheet_dir ) {
1831 while(($file = $stylesheet_dir->read()) !== false) {
1832 if ( !preg_match('|^\.+$|', $file) && preg_match('|\.css$|', $file) )
1833 $stylesheet_files[] = "$theme_loc/$stylesheet/$file";
1837 $template_files = array();
1838 $template_dir = @ dir("$theme_root/$template");
1839 if ( $template_dir ) {
1840 while(($file = $template_dir->read()) !== false) {
1841 if ( !preg_match('|^\.+$|', $file) && preg_match('|\.php$|', $file) )
1842 $template_files[] = "$theme_loc/$template/$file";
1846 $template_dir = dirname($template_files[0]);
1847 $stylesheet_dir = dirname($stylesheet_files[0]);
1849 if ( empty($template_dir) )
1850 $template_dir = '/';
1851 if ( empty($stylesheet_dir) )
1852 $stylesheet_dir = '/';
1854 // Check for theme name collision. This occurs if a theme is copied to
1855 // a new theme directory and the theme header is not updated. Whichever
1856 // theme is first keeps the name. Subsequent themes get a suffix applied.
1857 // The Default and Classic themes always trump their pretenders.
1858 if ( isset($themes[$name]) ) {
1859 if ( ('WordPress Default' == $name || 'WordPress Classic' == $name) &&
1860 ('default' == $stylesheet || 'classic' == $stylesheet) ) {
1861 // If another theme has claimed to be one of our default themes, move
1863 $suffix = $themes[$name]['Stylesheet'];
1864 $new_name = "$name/$suffix";
1865 $themes[$new_name] = $themes[$name];
1866 $themes[$new_name]['Name'] = $new_name;
1868 $name = "$name/$stylesheet";
1872 $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);
1875 // Resolve theme dependencies.
1876 $theme_names = array_keys($themes);
1878 foreach ($theme_names as $theme_name) {
1879 $themes[$theme_name]['Parent Theme'] = '';
1880 if ( $themes[$theme_name]['Stylesheet'] != $themes[$theme_name]['Template'] ) {
1881 foreach ($theme_names as $parent_theme_name) {
1882 if ( ($themes[$parent_theme_name]['Stylesheet'] == $themes[$parent_theme_name]['Template']) && ($themes[$parent_theme_name]['Template'] == $themes[$theme_name]['Template']) ) {
1883 $themes[$theme_name]['Parent Theme'] = $themes[$parent_theme_name]['Name'];
1890 $wp_themes = $themes;
1895 function get_theme($theme) {
1896 $themes = get_themes();
1898 if ( array_key_exists($theme, $themes) )
1899 return $themes[$theme];
1904 function get_current_theme() {
1905 $themes = get_themes();
1906 $theme_names = array_keys($themes);
1907 $current_template = get_settings('template');
1908 $current_stylesheet = get_settings('stylesheet');
1909 $current_theme = 'WordPress Default';
1912 foreach ($theme_names as $theme_name) {
1913 if ( $themes[$theme_name]['Stylesheet'] == $current_stylesheet &&
1914 $themes[$theme_name]['Template'] == $current_template ) {
1915 $current_theme = $themes[$theme_name]['Name'];
1921 return $current_theme;
1924 function get_query_template($type) {
1926 if ( file_exists(TEMPLATEPATH . "/{$type}.php") )
1927 $template = TEMPLATEPATH . "/{$type}.php";
1929 return apply_filters("{$type}_template", $template);
1932 function get_404_template() {
1933 return get_query_template('404');
1936 function get_archive_template() {
1937 return get_query_template('archive');
1940 function get_author_template() {
1941 return get_query_template('author');
1944 function get_category_template() {
1946 if ( file_exists(TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php') )
1947 $template = TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php';
1948 else if ( file_exists(TEMPLATEPATH . "/category.php") )
1949 $template = TEMPLATEPATH . "/category.php";
1951 return apply_filters('category_template', $template);
1954 function get_date_template() {
1955 return get_query_template('date');
1958 function get_home_template() {
1961 if ( file_exists(TEMPLATEPATH . "/home.php") )
1962 $template = TEMPLATEPATH . "/home.php";
1963 else if ( file_exists(TEMPLATEPATH . "/index.php") )
1964 $template = TEMPLATEPATH . "/index.php";
1966 return apply_filters('home_template', $template);
1969 function get_page_template() {
1972 $id = $wp_query->post->ID;
1973 $template = get_post_meta($id, '_wp_page_template', true);
1975 if ( 'default' == $template )
1978 if ( ! empty($template) && file_exists(TEMPLATEPATH . "/$template") )
1979 $template = TEMPLATEPATH . "/$template";
1980 else if ( file_exists(TEMPLATEPATH . "/page.php") )
1981 $template = TEMPLATEPATH . "/page.php";
1985 return apply_filters('page_template', $template);
1988 function get_paged_template() {
1989 return get_query_template('paged');
1992 function get_search_template() {
1993 return get_query_template('search');
1996 function get_single_template() {
1997 return get_query_template('single');
2000 function get_attachment_template() {
2002 $type = explode('/', $posts[0]->post_mime_type);
2003 if ( $template = get_query_template($type[0]) )
2005 elseif ( $template = get_query_template($type[1]) )
2007 elseif ( $template = get_query_template("$type[0]_$type[1]") )
2010 return get_query_template('attachment');
2013 function get_comments_popup_template() {
2014 if ( file_exists( TEMPLATEPATH . '/comments-popup.php') )
2015 $template = TEMPLATEPATH . '/comments-popup.php';
2017 $template = get_theme_root() . '/default/comments-popup.php';
2019 return apply_filters('comments_popup_template', $template);
2022 // Borrowed from the PHP Manual user notes. Convert entities, while
2023 // preserving already-encoded entities:
2024 function htmlentities2($myHTML) {
2025 $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
2026 $translation_table[chr(38)] = '&';
2027 return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&" , strtr($myHTML, $translation_table));
2031 function is_plugin_page() {
2032 global $plugin_page;
2034 if ( isset($plugin_page) )
2041 add_query_arg: Returns a modified querystring by adding
2042 a single key & value or an associative array.
2043 Setting a key value to emptystring removes the key.
2044 Omitting oldquery_or_uri uses the $_SERVER value.
2047 add_query_arg(newkey, newvalue, oldquery_or_uri) or
2048 add_query_arg(associative_array, oldquery_or_uri)
2050 function add_query_arg() {
2052 if ( is_array(func_get_arg(0)) ) {
2053 if ( @func_num_args() < 2 )
2054 $uri = $_SERVER['REQUEST_URI'];
2056 $uri = @func_get_arg(1);
2058 if ( @func_num_args() < 3 )
2059 $uri = $_SERVER['REQUEST_URI'];
2061 $uri = @func_get_arg(2);
2064 if ( strstr($uri, '?') ) {
2065 $parts = explode('?', $uri, 2);
2066 if ( 1 == count($parts) ) {
2070 $base = $parts[0] . '?';
2074 else if ( strstr($uri, '/') ) {
2082 parse_str($query, $qs);
2083 if ( is_array(func_get_arg(0)) ) {
2084 $kayvees = func_get_arg(0);
2085 $qs = array_merge($qs, $kayvees);
2087 $qs[func_get_arg(0)] = func_get_arg(1);
2090 foreach($qs as $k => $v) {
2097 $ret = $base . $ret;
2098 return trim($ret, '?');
2101 function remove_query_arg($key, $query) {
2102 return add_query_arg($key, '', $query);
2105 function load_template($file) {
2106 global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query,
2109 extract($wp_query->query_vars);
2111 require_once($file);
2114 function add_magic_quotes($array) {
2117 foreach ($array as $k => $v) {
2118 if ( is_array($v) ) {
2119 $array[$k] = add_magic_quotes($v);
2121 $array[$k] = $wpdb->escape($v);
2127 function wp_remote_fopen( $uri ) {
2128 if ( ini_get('allow_url_fopen') ) {
2129 $fp = fopen( $uri, 'r' );
2133 while( $remote_read = fread($fp, 4096) )
2134 $linea .= $remote_read;
2137 } else if ( function_exists('curl_init') ) {
2138 $handle = curl_init();
2139 curl_setopt ($handle, CURLOPT_URL, $uri);
2140 curl_setopt ($handle, CURLOPT_CONNECTTIMEOUT, 1);
2141 curl_setopt ($handle, CURLOPT_RETURNTRANSFER, 1);
2142 $buffer = curl_exec($handle);
2143 curl_close($handle);
2150 function wp($query_vars = '') {
2153 $wp->main($query_vars);
2156 function status_header( $header ) {
2157 if ( 200 == $header )
2159 elseif ( 301 == $header )
2160 $text = 'Moved Permanently';
2161 elseif ( 302 == $header )
2162 $text = 'Moved Temporarily';
2163 elseif ( 304 == $header )
2164 $text = 'Not Modified';
2165 elseif ( 404 == $header )
2166 $text = 'Not Found';
2167 elseif ( 410 == $header )
2170 @header("HTTP/1.1 $header $text");
2171 @header("Status: $header $text");
2174 function nocache_headers() {
2175 @ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
2176 @ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2177 @ header('Cache-Control: no-cache, must-revalidate, max-age=0');
2178 @ header('Pragma: no-cache');
2181 function get_usermeta( $user_id, $meta_key = '') {
2183 $user_id = (int) $user_id;
2185 if ( !empty($meta_key) ) {
2186 $meta_key = preg_replace('|a-z0-9_|i', '', $meta_key);
2187 $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2189 $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id'");
2192 if ( empty($metas) ) {
2193 if ( empty($meta_key) )
2199 foreach ($metas as $index => $meta) {
2200 @ $value = unserialize($meta->meta_value);
2201 if ( $value === FALSE )
2202 $value = $meta->meta_value;
2207 if ( count($values) == 1 )
2213 function update_usermeta( $user_id, $meta_key, $meta_value ) {
2215 if ( !is_numeric( $user_id ) )
2217 $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
2219 if ( is_array($meta_value) || is_object($meta_value) )
2220 $meta_value = serialize($meta_value);
2221 $meta_value = trim( $meta_value );
2223 if (empty($meta_value)) {
2224 delete_usermeta($user_id, $meta_key);
2227 $cur = $wpdb->get_row("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2229 $wpdb->query("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value )
2231 ( '$user_id', '$meta_key', '$meta_value' )");
2232 } else if ( $cur->meta_value != $meta_value ) {
2233 $wpdb->query("UPDATE $wpdb->usermeta SET meta_value = '$meta_value' WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2238 $user = get_userdata($user_id);
2239 wp_cache_delete($user_id, 'users');
2240 wp_cache_delete($user->user_login, 'userlogins');
2245 function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) {
2247 if ( !is_numeric( $user_id ) )
2249 $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
2251 if ( is_array($meta_value) || is_object($meta_value) )
2252 $meta_value = serialize($meta_value);
2253 $meta_value = trim( $meta_value );
2255 if ( ! empty($meta_value) )
2256 $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key' AND meta_value = '$meta_value'");
2258 $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2260 $user = get_userdata($user_id);
2261 wp_cache_delete($user_id, 'users');
2262 wp_cache_delete($user->user_login, 'userlogins');
2267 function register_activation_hook($file, $function) {
2268 $file = plugin_basename($file);
2270 add_action('activate_' . $file, $function);
2273 function register_deactivation_hook($file, $function) {
2274 $file = plugin_basename($file);
2276 add_action('deactivate_' . $file, $function);
2279 function plugin_basename($file) {
2280 $file = preg_replace('|\\\\+|', '\\\\', $file);
2281 $file = preg_replace('/^.*wp-content[\\\\\/]plugins[\\\\\/]/', '', $file);
2285 function get_num_queries() {
2287 return $wpdb->num_queries;