]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/functions.php
Wordpress 2.0.2
[autoinstalls/wordpress.git] / wp-includes / functions.php
1 <?php
2
3 require_once(dirname(__FILE__).'/functions-compat.php');
4
5 if ( !function_exists('_') ) {
6         function _($string) {
7                 return $string;
8         }
9 }
10
11 function 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
18 function 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
50 function 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
65 function 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
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);
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
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)) {
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
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)) {
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
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);
165         } else {
166                 $userdata = $cache_userdata[$user_login];
167         }
168         return (md5($user_pass) == $userdata->user_pass);
169 }
170
171
172 function 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.
180 function 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
264 function maybe_unserialize($original) {
265         if ( false !== $gm = @ unserialize($original) )
266                 return $gm;
267         else
268                 return $original;
269 }
270
271 /* Options functions */
272
273 function 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
303 function get_option($option) {
304         return get_settings($option);
305 }
306
307 function get_user_option( $option, $user = 0 ) {
308         global $wpdb, $current_user;
309         
310         if ( empty($user) )
311                 $user = $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
323 function form_option($option) {
324         echo htmlspecialchars( get_option($option), ENT_QUOTES );
325 }
326
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");
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
350 function 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         if ( is_array($newvalue) || is_object($newvalue) )
368                 $newvalue = serialize($newvalue);
369
370         wp_cache_set($option_name, $newvalue, 'options');
371
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);
377                 return true;
378         }
379         return false;
380 }
381
382 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
383         global $wpdb;
384         if ( !$global )
385                 $option_name = $wpdb->prefix . $option_name;
386         return update_usermeta( $user_id, $option_name, $newvalue );
387 }
388
389 // thx Alex Stapleton, http://alex.vort-x.net/blog/
390 function add_option($name, $value = '', $description = '', $autoload = 'yes') {
391         global $wpdb;
392
393         // Make sure the option doesn't already exist
394         if ( false !== get_option($name) )
395                 return;
396
397         if ( is_array($value) || is_object($value) )
398                 $value = serialize($value);
399
400         wp_cache_set($name, $value, 'options');
401
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')");
406
407         return;
408 }
409
410 function delete_option($name) {
411         global $wpdb;
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');
417         return true;
418 }
419
420 function add_post_meta($post_id, $key, $value, $unique = false) {
421         global $wpdb, $post_meta_cache;
422
423         if ( $unique ) {
424                 if ( $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
425 = '$key' AND post_id = '$post_id'") ) {
426                         return false;
427                 }
428         }
429
430         $original = $value;
431         if ( is_array($value) || is_object($value) )
432                 $value = $wpdb->escape(serialize($value));
433
434         $wpdb->query("INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) VALUES ('$post_id','$key','$value')");
435
436         $post_meta_cache['$post_id'][$key][] = $original;
437
438         return true;
439 }
440
441 function delete_post_meta($post_id, $key, $value = '') {
442         global $wpdb, $post_meta_cache;
443
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'");
447         } else {
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'");
450         }
451
452         if ( !$meta_id )
453                 return false;
454
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]);
459         } else {
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]);
466         }
467
468         unset($post_meta_cache['$post_id'][$key]);
469
470         return true;
471 }
472
473 function get_post_meta($post_id, $key, $single = false) {
474         global $wpdb, $post_meta_cache;
475
476         if ( isset($post_meta_cache[$post_id][$key]) ) {
477                 if ( $single ) {
478                         return maybe_unserialize( $post_meta_cache[$post_id][$key][0] );
479                 } else {
480                         return maybe_unserialize( $post_meta_cache[$post_id][$key] );
481                 }
482         }
483
484         $metalist = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = '$key'", ARRAY_N);
485
486         $values = array();
487         if ( $metalist ) {
488                 foreach ($metalist as $metarow) {
489                         $values[] = $metarow[0];
490                 }
491         }
492
493         if ( $single ) {
494                 if ( count($values) ) {
495                         $return = maybe_unserialize( $values[0] );
496                 } else {
497                         return '';
498                 }
499         } else {
500                 $return = $values;
501         }
502
503         return maybe_unserialize($return);
504 }
505
506 function update_post_meta($post_id, $key, $value, $prev_value = '') {
507         global $wpdb, $post_meta_cache;
508
509         $original_value = $value;
510         if ( is_array($value) || is_object($value) )
511                 $value = $wpdb->escape(serialize($value));
512
513         $original_prev = $prev_value;
514         if ( is_array($prev_value) || is_object($prev_value) )
515                 $prev_value = $wpdb->escape(serialize($prev_value));
516
517         if (! $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
518 = '$key' AND post_id = '$post_id'") ) {
519                 return false;
520         }
521
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;
529         } else {
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;
537         }
538
539         return true;
540 }
541
542 // Deprecated.  Use get_post().
543 function get_postdata($postid) {
544         $post = &get_post($postid);
545
546         $postdata = array (
547                 'ID' => $post->ID,
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
561         );
562
563         return $postdata;
564 }
565
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;
570
571         if ( empty($post) ) {
572                 if ( isset($GLOBALS['post']) )
573                         $_post = & $GLOBALS['post'];
574                 else
575                         $_post = null;
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];
582         } else {
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];
587                 else {
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;
593                 }
594         }
595
596         if ( defined(WP_IMPORTING) )
597                 unset($post_cache);
598
599         if ( $output == OBJECT ) {
600                 return $_post;
601         } elseif ( $output == ARRAY_A ) {
602                 return get_object_vars($_post);
603         } elseif ( $output == ARRAY_N ) {
604                 return array_values(get_object_vars($_post));
605         } else {
606                 return $_post;
607         }
608 }
609
610 function &get_children($post = 0, $output = OBJECT) {
611         global $post_cache, $wpdb;
612
613         if ( empty($post) ) {
614                 if ( isset($GLOBALS['post']) )
615                         $post_parent = & $GLOBALS['post']->post_parent;
616                 else
617                         return false;
618         } elseif ( is_object($post) ) {
619                 $post_parent = $post->post_parent;
620         } else {
621                 $post_parent = $post;
622         }
623
624         $post_parent = (int) $post_parent;
625
626         $query = "SELECT * FROM $wpdb->posts WHERE post_parent = $post_parent";
627
628         $children = $wpdb->get_results($query);
629
630         if ( $children ) {
631                 foreach ( $children as $key => $child ) {
632                         $post_cache[$child->ID] =& $children[$key];
633                         $kids[$child->ID] =& $children[$key];
634                 }
635         } else {
636                 return false;
637         }
638
639         if ( $output == OBJECT ) {
640                 return $kids;
641         } elseif ( $output == ARRAY_A ) {
642                 foreach ( $kids as $kid )
643                         $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
644                 return $weeuns;
645         } elseif ( $output == ARRAY_N ) {
646                 foreach ( $kids as $kid )
647                         $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
648                 return $babes;
649         } else {
650                 return $kids;
651         }
652 }
653
654 function set_page_path($page) {
655         $page->fullpath = '/' . $page->post_name;
656         $path = $page->fullpath;
657         $curpage = $page;
658         while ($curpage->post_parent != 0) {
659                 $curpage = get_page($curpage->post_parent);
660                 $path = '/' . $curpage->post_name . $path;
661         }
662         
663         $page->fullpath = $path;
664
665         return $page;
666 }
667
668 // Retrieves page data given a page ID or page object.
669 // Handles page caching.
670 function &get_page(&$page, $output = OBJECT) {
671         global $wpdb;
672
673         if ( empty($page) ) {
674                 if ( isset($GLOBALS['page']) ) {
675                         $_page = & $GLOBALS['page'];
676                         wp_cache_add($_page->ID, $_page, 'pages');
677                 } else {
678                         $_page = null;
679                 }
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');
684                 $_page = $page;
685         } else {
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') ) {
692                         // Got it.
693                 } else {
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');
699                 }
700         }
701         
702         if (!isset($_page->fullpath)) {
703                 $_page = set_page_path($_page);
704                 wp_cache_replace($_page->cat_ID, $_page, 'pages');
705         }
706
707         if ( $output == OBJECT ) {
708                 return $_page;
709         } elseif ( $output == ARRAY_A ) {
710                 return get_object_vars($_page);
711         } elseif ( $output == ARRAY_N ) {
712                 return array_values(get_object_vars($_page));
713         } else {
714                 return $_page;
715         }
716 }
717
718 function set_category_path($cat) {
719         $cat->fullpath = '/' . $cat->category_nicename;
720         $path = $cat->fullpath;
721         $curcat = $cat;
722         while ($curcat->category_parent != 0) {
723                 $curcat = get_category($curcat->category_parent);
724                 $path = '/' . $curcat->category_nicename . $path;
725         }
726         
727         $cat->fullpath = $path;
728
729         return $cat;
730 }
731
732 // Retrieves category data given a category ID or category object.
733 // Handles category caching.
734 function &get_category(&$category, $output = OBJECT) {
735         global $wpdb;
736
737         if ( empty($category) )
738                 return null;
739
740         if ( is_object($category) ) {
741                 wp_cache_add($category->cat_ID, $category, 'category');
742                 $_category = $category;
743         } else {
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');
747                 }
748         }
749
750         if ( !isset($_category->fullpath) ) {
751                 $_category = set_category_path($_category);
752                 wp_cache_replace($_category->cat_ID, $_category, 'category');   
753         }
754
755         if ( $output == OBJECT ) {
756                 return $_category;
757         } elseif ( $output == ARRAY_A ) {
758                 return get_object_vars($_category);
759         } elseif ( $output == ARRAY_N ) {
760                 return array_values(get_object_vars($_category));
761         } else {
762                 return $_category;
763         }
764 }
765
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;
770
771         if ( empty($comment) )
772                 return null;
773
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];
778         } else {
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;
782                 } else {
783                         $_comment = & $comment_cache[$comment];
784                 }
785         }
786
787         if ( $output == OBJECT ) {
788                 return $_comment;
789         } elseif ( $output == ARRAY_A ) {
790                 return get_object_vars($_comment);
791         } elseif ( $output == ARRAY_N ) {
792                 return array_values(get_object_vars($_comment));
793         } else {
794                 return $_comment;
795         }
796 }
797
798 function get_catname($cat_ID) {
799         $category = &get_category($cat_ID);
800         return $category->cat_name;
801 }
802
803 function get_all_category_ids() {
804         global $wpdb;
805         
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');
809         }
810         
811         return $cat_ids;
812 }
813
814 function get_all_page_ids() {
815         global $wpdb;
816         
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');
820         }
821         
822         return $page_ids;
823 }
824
825 function gzip_compression() {
826         if ( !get_settings('gzipcompression') ) return false;
827
828         if ( extension_loaded('zlib') ) {
829                 ob_start('ob_gzhandler');
830         }
831 }
832
833
834 // functions to count the page generation time (from phpBB2)
835 // ( or just any time between timer_start() and timer_stop() )
836
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];
842         $timeend = $mtime;
843         $timetotal = $timeend-$timestart;
844         if ( $display )
845                 echo number_format($timetotal,$precision);
846         return $timetotal;
847 }
848
849 function weblog_ping($server = '', $path = '') {
850         global $wp_version;
851         include_once (ABSPATH . WPINC . '/class-IXR.php');
852
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;
857
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);
863 }
864
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);
873                 }
874         }
875
876         return $post_id;
877 }
878
879 // Send a Trackback
880 function trackback($trackback_url, $title, $excerpt, $ID) {
881         global $wpdb, $wp_version;
882
883         if ( empty($trackback_url) )
884                 return;
885
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);
904 /*
905         $debug_file = 'trackback.log';
906         $fp = fopen($debug_file, 'a');
907         fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
908         while(!@feof($fs)) {
909                 fwrite($fp, @fgets($fs, 4096));
910         }
911         fwrite($fp, "\n\n");
912         fclose($fp);
913 */
914         @fclose($fs);
915
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'");
919 }
920
921 function make_url_footnote($content) {
922         preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
923         $j = 0;
924         for ($i=0; $i<count($matches[0]); $i++) {
925                 $links_summary = (!$j) ? "\n" : $links_summary;
926                 $j++;
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;
934         }
935         $content = strip_tags($content);
936         $content .= $links_summary;
937         return $content;
938 }
939
940
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);
947         } else {
948                 $post_title = $post_default_title;
949         }
950         return $post_title;
951 }
952
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);
958         } else {
959                 $post_category = $post_default_category;
960         }
961         return $post_category;
962 }
963
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);
968         return $content;
969 }
970
971 function debug_fopen($filename, $mode) {
972         global $debug;
973         if ( $debug == 1 ) {
974                 $fp = fopen($filename, $mode);
975                 return $fp;
976         } else {
977                 return false;
978         }
979 }
980
981 function debug_fwrite($fp, $string) {
982         global $debug;
983         if ( $debug == 1 ) {
984                 fwrite($fp, $string);
985         }
986 }
987
988 function debug_fclose($fp) {
989         global $debug;
990         if ( $debug == 1 ) {
991                 fclose($fp);
992         }
993 }
994
995 function spawn_pinger() {
996         global $wpdb;
997         $doping = false;
998         if ( $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE TRIM(to_ping) != '' LIMIT 1") )
999                 $doping = true;
1000
1001         if ( $wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_pingme' OR meta_key = '_encloseme' LIMIT 1") )
1002                 $doping = true;
1003
1004         if ( substr(php_sapi_name(), 0, 3) == 'cgi' )
1005                 return $doping;
1006
1007         if ( $doping ) {
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);
1011                 if ( $argyle )
1012                         fputs($argyle, "GET {$parts['path']}?time=".time()." HTTP/1.0\r\nHost: {$_SERVER['HTTP_HOST']}\r\n\r\n");
1013        }
1014 }
1015
1016 function do_enclose( $content, $post_ID ) {
1017         global $wp_version, $wpdb;
1018         include_once (ABSPATH . WPINC . '/class-IXR.php');
1019
1020         $log = debug_fopen(ABSPATH . '/enclosures.log', 'a');
1021         $post_links = array();
1022         debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");
1023
1024         $pung = get_enclosed( $post_ID );
1025
1026         $ltrs = '\w';
1027         $gunk = '/#~:.?+=&%@!\-';
1028         $punc = '.:?\-';
1029         $any = $ltrs . $gunk . $punc;
1030
1031         preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
1032
1033         debug_fwrite($log, 'Post contents:');
1034         debug_fwrite($log, $content."\n");
1035
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;
1043                 endif;
1044         endforeach;
1045
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')" );
1056                                 }
1057                         }
1058                 }
1059         endforeach;
1060 }
1061
1062 function wp_get_http_headers( $url, $red = 1 ) {
1063         global $wp_version;
1064         @set_time_limit( 60 );
1065
1066         if ( $red > 5 )
1067            return false;
1068
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;
1074
1075         $head = "HEAD $file HTTP/1.1\r\nHOST: $host\r\nUser-Agent: WordPress/" . $wp_version . "\r\n\r\n";
1076
1077         $fp = @fsockopen($host, $parts['port'], $err_num, $err_msg, 3);
1078         if ( !$fp )
1079                 return false;
1080
1081         $response = '';
1082         fputs( $fp, $head );
1083         while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
1084                 $response .= fgets( $fp, 2048 );
1085         fclose( $fp );
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];
1091         }
1092
1093     $code = preg_replace('/.*?(\d{3}).*/i', '$1', $response);
1094     
1095     $headers['status_code'] = $code;
1096     
1097     if ( '302' == $code || '301' == $code )
1098         return wp_get_http_headers( $url, ++$red );
1099
1100         preg_match('/.*([0-9]{3}).*/', $response, $return);
1101         $headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
1102         return $headers;
1103 }
1104
1105 // Deprecated.  Use the new post loop.
1106 function start_wp() {
1107         global $wp_query, $post;
1108
1109         // Since the old style loop is being used, advance the query iterator here.
1110         $wp_query->next_post();
1111
1112         setup_postdata($post);
1113 }
1114
1115 // Setup global post data.
1116 function setup_postdata($post) {
1117         global $id, $postdata, $authordata, $day, $page, $pages, $multipage, $more, $numpages, $wp_query;
1118         global $pagenow;
1119
1120         $id = $post->ID;
1121
1122         $authordata = get_userdata($post->post_author);
1123
1124         $day = mysql2date('d.m.y', $post->post_date);
1125         $currentmonth = mysql2date('m', $post->post_date);
1126         $numpages = 1;
1127         $page = get_query_var('page');
1128         if ( !$page )
1129                 $page = 1;
1130         if ( is_single() || is_page() )
1131                 $more = 1;
1132         $content = $post->post_content;
1133         if ( preg_match('/<!--nextpage-->/', $content) ) {
1134                 if ( $page > 1 )
1135                         $more = 1;
1136                 $multipage = 1;
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);
1142         } else {
1143                 $pages[0] = $post->post_content;
1144                 $multipage = 0;
1145         }
1146         return true;
1147 }
1148
1149 function is_new_day() {
1150         global $day, $previousday;
1151         if ( $day != $previousday ) {
1152                 return(1);
1153         } else {
1154                 return(0);
1155         }
1156 }
1157
1158 // Filters: these are the core of WP's plugin architecture
1159
1160 function merge_filters($tag) {
1161         global $wp_filter;
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]);
1166                         else
1167                                 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
1168                         $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
1169                 }
1170         }
1171
1172         if ( isset($wp_filter[$tag]) )
1173                 ksort( $wp_filter[$tag] );
1174 }
1175
1176 function apply_filters($tag, $string) {
1177         global $wp_filter;
1178
1179         $args = array_slice(func_get_args(), 2);
1180
1181         merge_filters($tag);
1182
1183         if ( !isset($wp_filter[$tag]) ) {
1184                 return $string;
1185         }
1186         foreach ($wp_filter[$tag] as $priority => $functions) {
1187                 if ( !is_null($functions) ) {
1188                         foreach($functions as $function) {
1189
1190                                 $all_args = array_merge(array($string), $args);
1191                                 $function_name = $function['function'];
1192                                 $accepted_args = $function['accepted_args'];
1193
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 )
1199                                         $the_args = NULL;
1200                                 else
1201                                         $the_args = $all_args;
1202
1203                                 $string = call_user_func_array($function_name, $the_args);
1204                         }
1205                 }
1206         }
1207         return $string;
1208 }
1209
1210 function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
1211         global $wp_filter;
1212
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 ) {
1219                                 return true;
1220                         }
1221                 }
1222         }
1223
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);
1226         return true;
1227 }
1228
1229 function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
1230         global $wp_filter;
1231
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;
1237                         }
1238                 }
1239                 $wp_filter[$tag]["$priority"] = $new_function_list;
1240         }
1241         return true;
1242 }
1243
1244 // The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
1245
1246 function do_action($tag, $arg = '') {
1247         global $wp_filter;
1248         $extra_args = array_slice(func_get_args(), 2);
1249         if ( is_array($arg) )
1250                 $args = array_merge($arg, $extra_args);
1251         else
1252                 $args = array_merge(array($arg), $extra_args);
1253
1254         merge_filters($tag);
1255
1256         if ( !isset($wp_filter[$tag]) ) {
1257                 return;
1258         }
1259         foreach ($wp_filter[$tag] as $priority => $functions) {
1260                 if ( !is_null($functions) ) {
1261                         foreach($functions as $function) {
1262
1263                                 $function_name = $function['function'];
1264                                 $accepted_args = $function['accepted_args'];
1265
1266                                 if ( $accepted_args == 1 ) {
1267                                         if ( is_array($arg) )
1268                                                 $the_args = $arg;
1269                                         else
1270                                                 $the_args = array($arg);
1271                                 } elseif ( $accepted_args > 1 ) {
1272                                         $the_args = array_slice($args, 0, $accepted_args);
1273                                 } elseif ( $accepted_args == 0 ) {
1274                                         $the_args = NULL;
1275                                 } else {
1276                                         $the_args = $args;
1277                                 }
1278
1279                                 $string = call_user_func_array($function_name, $the_args);
1280                         }
1281                 }
1282         }
1283 }
1284
1285 function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
1286         add_filter($tag, $function_to_add, $priority, $accepted_args);
1287 }
1288
1289 function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
1290         remove_filter($tag, $function_to_remove, $priority, $accepted_args);
1291 }
1292
1293 function get_page_uri($page_id) {
1294         $page = get_page($page_id);
1295         $uri = urldecode($page->post_name);
1296
1297         // A page cannot be it's own parent.
1298         if ( $page->post_parent == $page->ID )
1299                 return $uri;
1300
1301         while ($page->post_parent != 0) {
1302                 $page = get_page($page->post_parent);
1303                 $uri = urldecode($page->post_name) . "/" . $uri;
1304         }
1305
1306         return $uri;
1307 }
1308
1309 function get_posts($args) {
1310         global $wpdb;
1311         parse_str($args, $r);
1312         if ( !isset($r['numberposts']) )
1313                 $r['numberposts'] = 5;
1314         if ( !isset($r['offset']) )
1315                 $r['offset'] = 0;
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';
1322
1323         $now = current_time('mysql');
1324
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'] );
1331
1332         update_post_caches($posts);
1333
1334         return $posts;
1335 }
1336
1337 function &query_posts($query) {
1338         global $wp_query;
1339         return $wp_query->query($query);
1340 }
1341
1342 function update_post_cache(&$posts) {
1343         global $post_cache;
1344
1345         if ( !$posts )
1346                 return;
1347
1348         for ($i = 0; $i < count($posts); $i++) {
1349                 $post_cache[$posts[$i]->ID] = &$posts[$i];
1350         }
1351 }
1352
1353 function clean_post_cache($id) {
1354         global $post_cache;
1355
1356         if ( isset( $post_cache[$id] ) )
1357                 unset( $post_cache[$id] );
1358 }
1359
1360 function update_page_cache(&$pages) {
1361         global $page_cache;
1362
1363         if ( !$pages )
1364                 return;
1365
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');
1369         }
1370 }
1371
1372
1373 function clean_page_cache($id) {
1374         global $page_cache;
1375
1376         if ( isset( $page_cache[$id] ) )
1377                 unset( $page_cache[$id] );
1378 }
1379
1380 function update_post_category_cache($post_ids) {
1381         global $wpdb, $category_cache;
1382
1383         if ( empty($post_ids) )
1384                 return;
1385
1386         if ( is_array($post_ids) )
1387                 $post_ids = implode(',', $post_ids);
1388
1389         $dogs = $wpdb->get_results("SELECT post_id, category_id FROM $wpdb->post2cat WHERE post_id IN ($post_ids)");
1390
1391         if ( empty($dogs) )
1392                 return;
1393                 
1394         foreach ($dogs as $catt)
1395                 $category_cache[$catt->post_id][$catt->category_id] = &get_category($catt->category_id);
1396 }
1397
1398 function update_post_caches(&$posts) {
1399         global $post_cache, $category_cache, $comment_count_cache, $post_meta_cache;
1400         global $wpdb;
1401
1402         // No point in doing all this work if we didn't match any posts.
1403         if ( !$posts )
1404                 return;
1405
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;
1411         }
1412
1413         $post_id_list = implode(',', $post_id_array);
1414
1415         update_post_category_cache($post_id_list);
1416
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'];
1425
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();
1431
1432                         // Add a value to the current pid/key:
1433                         $post_meta_cache[$mpid][$mkey][] = $mval;
1434                 }
1435         }
1436 }
1437
1438 function update_category_cache() {
1439         return true;
1440 }
1441
1442 function wp_head() {
1443         do_action('wp_head');
1444 }
1445
1446 function wp_footer() {
1447         do_action('wp_footer');
1448 }
1449
1450 function is_single ($post = '') {
1451         global $wp_query;
1452
1453         if ( !$wp_query->is_single )
1454                 return false;
1455
1456         if ( empty( $post) )
1457                 return true;
1458
1459         $post_obj = $wp_query->get_queried_object();
1460
1461         if ( $post == $post_obj->ID )
1462                 return true;
1463         elseif ( $post == $post_obj->post_title )
1464                 return true;
1465         elseif ( $post == $post_obj->post_name )
1466                 return true;
1467
1468         return false;
1469 }
1470
1471 function is_page ($page = '') {
1472         global $wp_query;
1473
1474         if ( !$wp_query->is_page )
1475                 return false;
1476
1477         if ( empty($page) )
1478                 return true;
1479
1480         $page_obj = $wp_query->get_queried_object();
1481
1482         if ( $page == $page_obj->ID )
1483                 return true;
1484         elseif ( $page == $page_obj->post_title )
1485                 return true;
1486         else if ( $page == $page_obj->post_name )
1487                 return true;
1488
1489         return false;
1490 }
1491
1492 function is_attachment () {
1493         global $wp_query;
1494
1495         return $wp_query->is_attachment;
1496 }
1497
1498 function is_preview() {
1499         global $wp_query;
1500         
1501         return $wp_query->is_preview;
1502 }
1503
1504 function is_archive () {
1505         global $wp_query;
1506
1507         return $wp_query->is_archive;
1508 }
1509
1510 function is_date () {
1511         global $wp_query;
1512
1513         return $wp_query->is_date;
1514 }
1515
1516 function is_year () {
1517         global $wp_query;
1518
1519         return $wp_query->is_year;
1520 }
1521
1522 function is_month () {
1523         global $wp_query;
1524
1525         return $wp_query->is_month;
1526 }
1527
1528 function is_day () {
1529         global $wp_query;
1530
1531         return $wp_query->is_day;
1532 }
1533
1534 function is_time () {
1535         global $wp_query;
1536
1537         return $wp_query->is_time;
1538 }
1539
1540 function is_author ($author = '') {
1541         global $wp_query;
1542
1543         if ( !$wp_query->is_author )
1544                 return false;
1545
1546         if ( empty($author) )
1547                 return true;
1548
1549         $author_obj = $wp_query->get_queried_object();
1550
1551         if ( $author == $author_obj->ID )
1552                 return true;
1553         elseif ( $author == $author_obj->nickname )
1554                 return true;
1555         elseif ( $author == $author_obj->user_nicename )
1556                 return true;
1557
1558         return false;
1559 }
1560
1561 function is_category ($category = '') {
1562         global $wp_query;
1563
1564         if ( !$wp_query->is_category )
1565                 return false;
1566
1567         if ( empty($category) )
1568                 return true;
1569
1570         $cat_obj = $wp_query->get_queried_object();
1571
1572         if ( $category == $cat_obj->cat_ID )
1573                 return true;
1574         else if ( $category == $cat_obj->cat_name )
1575                 return true;
1576         elseif ( $category == $cat_obj->category_nicename )
1577                 return true;
1578
1579         return false;
1580 }
1581
1582 function is_search () {
1583         global $wp_query;
1584
1585         return $wp_query->is_search;
1586 }
1587
1588 function is_feed () {
1589         global $wp_query;
1590
1591         return $wp_query->is_feed;
1592 }
1593
1594 function is_trackback () {
1595         global $wp_query;
1596
1597         return $wp_query->is_trackback;
1598 }
1599
1600 function is_admin () {
1601         global $wp_query;
1602
1603         return ( $wp_query->is_admin || strstr($_SERVER['REQUEST_URI'], 'wp-admin/') );
1604 }
1605
1606 function is_home () {
1607         global $wp_query;
1608
1609         return $wp_query->is_home;
1610 }
1611
1612 function is_404 () {
1613         global $wp_query;
1614
1615         return $wp_query->is_404;
1616 }
1617
1618 function is_comments_popup () {
1619         global $wp_query;
1620
1621         return $wp_query->is_comments_popup;
1622 }
1623
1624 function is_paged () {
1625         global $wp_query;
1626
1627         return $wp_query->is_paged;
1628 }
1629
1630 function in_the_loop() {
1631         global $wp_query;
1632
1633         return $wp_query->in_the_loop;
1634 }
1635
1636 function get_query_var($var) {
1637         global $wp_query;
1638
1639         return $wp_query->get($var);
1640 }
1641
1642 function have_posts() {
1643         global $wp_query;
1644
1645         return $wp_query->have_posts();
1646 }
1647
1648 function rewind_posts() {
1649         global $wp_query;
1650
1651         return $wp_query->rewind_posts();
1652 }
1653
1654 function the_post() {
1655         global $wp_query;
1656
1657         $wp_query->the_post();
1658 }
1659
1660 function get_theme_root() {
1661         return apply_filters('theme_root', ABSPATH . "wp-content/themes");
1662 }
1663
1664 function get_theme_root_uri() {
1665         return apply_filters('theme_root_uri', get_settings('siteurl') . "/wp-content/themes", get_settings('siteurl'));
1666 }
1667
1668 function get_stylesheet() {
1669         return apply_filters('stylesheet', get_settings('stylesheet'));
1670 }
1671
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);
1676 }
1677
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);
1682 }
1683
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);
1688 }
1689
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');
1695         }
1696         return apply_filters('template', get_settings('template'));
1697 }
1698
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);
1703 }
1704
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);
1709 }
1710
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];
1721         else
1722                 $version ='';
1723         if ( preg_match("|Status:(.*)|i", $theme_data, $status) )
1724                 $status = $status[1];
1725         else
1726                 $status ='publish';
1727
1728         $description = wptexturize($description[1]);
1729
1730         $name = $theme_name[1];
1731         $name = trim($name);
1732         $theme = $name;
1733
1734         if ( '' == $author_uri[1] ) {
1735                 $author = $author_name[1];
1736         } else {
1737                 $author = '<a href="' . $author_uri[1] . '" title="' . __('Visit author homepage') . '">' . $author_name[1] . '</a>';
1738         }
1739
1740         return array('Name' => $name, 'Title' => $theme, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1], 'Status' => $status);
1741 }
1742
1743 function get_themes() {
1744         global $wp_themes;
1745         global $wp_broken_themes;
1746
1747         if ( isset($wp_themes) )
1748                 return $wp_themes;
1749
1750         $themes = array();
1751         $wp_broken_themes = array();
1752         $theme_root = get_theme_root();
1753         $theme_loc = str_replace(ABSPATH, '', $theme_root);
1754
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' ) {
1761                                         continue;
1762                                 }
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;
1769                                                 break;
1770                                         }
1771                                 }
1772                                 if ( !$found_stylesheet ) {
1773                                         $wp_broken_themes[$theme_dir] = array('Name' => $theme_dir, 'Title' => $theme_dir, 'Description' => __('Stylesheet is missing.'));
1774                                 }
1775                         }
1776                 }
1777         }
1778
1779         if ( !$themes_dir || !$theme_files ) {
1780                 return $themes;
1781         }
1782
1783         sort($theme_files);
1784
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.'));
1788                         continue;
1789                 }
1790
1791                 $theme_data = get_theme_data("$theme_root/$theme_file");
1792
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);
1800
1801                 foreach (array('png', 'gif', 'jpg', 'jpeg') as $ext) {
1802                         if (file_exists("$theme_root/$stylesheet/screenshot.$ext")) {
1803                                 $screenshot = "screenshot.$ext";
1804                                 break;
1805                         }
1806                 }
1807
1808                 if ( empty($name) ) {
1809                         $name = dirname($theme_file);
1810                         $title = $name;
1811                 }
1812
1813                 if ( empty($template) ) {
1814                         if ( file_exists(dirname("$theme_root/$theme_file/index.php")) ) {
1815                                 $template = dirname($theme_file);
1816                         } else {
1817                                 continue;
1818                         }
1819                 }
1820
1821                 $template = trim($template);
1822
1823                 if ( !file_exists("$theme_root/$template/index.php") ) {
1824                         $wp_broken_themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => __('Template is missing.'));
1825                         continue;
1826                 }
1827
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";
1834                         }
1835                 }
1836
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";
1843                         }
1844                 }
1845
1846                 $template_dir = dirname($template_files[0]);
1847                 $stylesheet_dir = dirname($stylesheet_files[0]);
1848
1849                 if ( empty($template_dir) )
1850                         $template_dir = '/';
1851                 if ( empty($stylesheet_dir) )
1852                         $stylesheet_dir = '/';
1853
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
1862                                 // them aside.
1863                                 $suffix = $themes[$name]['Stylesheet'];
1864                                 $new_name = "$name/$suffix";
1865                                 $themes[$new_name] = $themes[$name];
1866                                 $themes[$new_name]['Name'] = $new_name;
1867                         } else {
1868                                 $name = "$name/$stylesheet";
1869                         }
1870                 }
1871
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);
1873         }
1874
1875         // Resolve theme dependencies.
1876         $theme_names = array_keys($themes);
1877
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'];
1884                                         break;
1885                                 }
1886                         }
1887                 }
1888         }
1889
1890         $wp_themes = $themes;
1891
1892         return $themes;
1893 }
1894
1895 function get_theme($theme) {
1896         $themes = get_themes();
1897
1898         if ( array_key_exists($theme, $themes) )
1899                 return $themes[$theme];
1900
1901         return NULL;
1902 }
1903
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';
1910
1911         if ( $themes ) {
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'];
1916                                 break;
1917                         }
1918                 }
1919         }
1920
1921         return $current_theme;
1922 }
1923
1924 function get_query_template($type) {
1925         $template = '';
1926         if ( file_exists(TEMPLATEPATH . "/{$type}.php") )
1927                 $template = TEMPLATEPATH . "/{$type}.php";
1928
1929         return apply_filters("{$type}_template", $template);
1930 }
1931
1932 function get_404_template() {
1933         return get_query_template('404');
1934 }
1935
1936 function get_archive_template() {
1937         return get_query_template('archive');
1938 }
1939
1940 function get_author_template() {
1941         return get_query_template('author');
1942 }
1943
1944 function get_category_template() {
1945         $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";
1950
1951         return apply_filters('category_template', $template);
1952 }
1953
1954 function get_date_template() {
1955         return get_query_template('date');
1956 }
1957
1958 function get_home_template() {
1959         $template = '';
1960
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";
1965
1966         return apply_filters('home_template', $template);
1967 }
1968
1969 function get_page_template() {
1970         global $wp_query;
1971
1972         $id = $wp_query->post->ID;
1973         $template = get_post_meta($id, '_wp_page_template', true);
1974
1975         if ( 'default' == $template )
1976                 $template = '';
1977
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";
1982         else
1983                 $template = '';
1984
1985         return apply_filters('page_template', $template);
1986 }
1987
1988 function get_paged_template() {
1989         return get_query_template('paged');
1990 }
1991
1992 function get_search_template() {
1993         return get_query_template('search');
1994 }
1995
1996 function get_single_template() {
1997         return get_query_template('single');
1998 }
1999
2000 function get_attachment_template() {
2001         global $posts;
2002         $type = explode('/', $posts[0]->post_mime_type);
2003         if ( $template = get_query_template($type[0]) )
2004                 return $template;
2005         elseif ( $template = get_query_template($type[1]) )
2006                 return $template;
2007         elseif ( $template = get_query_template("$type[0]_$type[1]") )
2008                 return $template;
2009         else
2010                 return get_query_template('attachment');
2011 }
2012
2013 function get_comments_popup_template() {
2014         if ( file_exists( TEMPLATEPATH . '/comments-popup.php') )
2015                 $template = TEMPLATEPATH . '/comments-popup.php';
2016         else
2017                 $template = get_theme_root() . '/default/comments-popup.php';
2018
2019         return apply_filters('comments_popup_template', $template);
2020 }
2021
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};)/","&amp;" , strtr($myHTML, $translation_table));
2028 }
2029
2030
2031 function is_plugin_page() {
2032         global $plugin_page;
2033
2034         if ( isset($plugin_page) )
2035                 return true;
2036
2037         return false;
2038 }
2039
2040 /*
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.
2045
2046 Parameters:
2047 add_query_arg(newkey, newvalue, oldquery_or_uri) or
2048 add_query_arg(associative_array, oldquery_or_uri)
2049 */
2050 function add_query_arg() {
2051         $ret = '';
2052         if ( is_array(func_get_arg(0)) ) {
2053                 if ( @func_num_args() < 2 )
2054                         $uri = $_SERVER['REQUEST_URI'];
2055                 else
2056                         $uri = @func_get_arg(1);
2057         } else {
2058                 if ( @func_num_args() < 3 )
2059                         $uri = $_SERVER['REQUEST_URI'];
2060                 else
2061                         $uri = @func_get_arg(2);
2062         }
2063
2064         if ( strstr($uri, '?') ) {
2065                 $parts = explode('?', $uri, 2);
2066                 if ( 1 == count($parts) ) {
2067                         $base = '?';
2068                         $query = $parts[0];
2069                 } else {
2070                         $base = $parts[0] . '?';
2071                         $query = $parts[1];
2072                 }
2073         }
2074         else if ( strstr($uri, '/') ) {
2075                 $base = $uri . '?';
2076                 $query = '';
2077         } else {
2078                 $base = '';
2079                 $query = $uri;
2080         }
2081
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);
2086         } else {
2087                 $qs[func_get_arg(0)] = func_get_arg(1);
2088         }
2089
2090         foreach($qs as $k => $v) {
2091                 if ( $v != '' ) {
2092                         if ( $ret != '' )
2093                                 $ret .= '&';
2094                         $ret .= "$k=$v";
2095                 }
2096         }
2097         $ret = $base . $ret;
2098         return trim($ret, '?');
2099 }
2100
2101 function remove_query_arg($key, $query) {
2102         return add_query_arg($key, '', $query);
2103 }
2104
2105 function load_template($file) {
2106         global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query,
2107                 $wp_rewrite, $wpdb;
2108
2109         extract($wp_query->query_vars);
2110
2111         require_once($file);
2112 }
2113
2114 function add_magic_quotes($array) {
2115         global $wpdb;
2116
2117         foreach ($array as $k => $v) {
2118                 if ( is_array($v) ) {
2119                         $array[$k] = add_magic_quotes($v);
2120                 } else {
2121                         $array[$k] = $wpdb->escape($v);
2122                 }
2123         }
2124         return $array;
2125 }
2126
2127 function wp_remote_fopen( $uri ) {
2128         if ( ini_get('allow_url_fopen') ) {
2129                 $fp = fopen( $uri, 'r' );
2130                 if ( !$fp )
2131                         return false;
2132                 $linea = '';
2133                 while( $remote_read = fread($fp, 4096) )
2134                         $linea .= $remote_read;
2135                 fclose($fp);
2136                 return $linea;
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);
2144                 return $buffer;
2145         } else {
2146                 return false;
2147         }
2148 }
2149
2150 function wp($query_vars = '') {
2151         global $wp;
2152         
2153         $wp->main($query_vars);
2154 }
2155
2156 function status_header( $header ) {
2157         if ( 200 == $header )
2158                 $text = 'OK';
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 )
2168                 $text = 'Gone';
2169
2170         @header("HTTP/1.1 $header $text");
2171         @header("Status: $header $text");
2172 }
2173
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');
2179 }
2180
2181 function get_usermeta( $user_id, $meta_key = '') {
2182         global $wpdb;
2183         $user_id = (int) $user_id;
2184
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'");
2188         } else {
2189                 $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id'");
2190         }
2191
2192         if ( empty($metas) ) {
2193                 if ( empty($meta_key) )
2194                         return array();
2195                 else
2196                         return '';
2197         }
2198
2199         foreach ($metas as $index => $meta) {
2200                 @ $value = unserialize($meta->meta_value);
2201                 if ( $value === FALSE )
2202                         $value = $meta->meta_value;
2203
2204                 $values[] = $value;
2205         }
2206
2207         if ( count($values) == 1 )
2208                 return $values[0];
2209         else
2210                 return $values;
2211 }
2212
2213 function update_usermeta( $user_id, $meta_key, $meta_value ) {
2214         global $wpdb;
2215         if ( !is_numeric( $user_id ) )
2216                 return false;
2217         $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key);
2218
2219         if ( is_array($meta_value) || is_object($meta_value) )
2220                 $meta_value = serialize($meta_value);
2221         $meta_value = trim( $meta_value );
2222         
2223         if (empty($meta_value)) {
2224                 delete_usermeta($user_id, $meta_key);
2225         }
2226
2227         $cur = $wpdb->get_row("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2228         if ( !$cur ) {
2229                 $wpdb->query("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value )
2230                 VALUES
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'");
2234         } else {
2235                 return false;   
2236         }
2237         
2238         $user = get_userdata($user_id);
2239         wp_cache_delete($user_id, 'users');
2240         wp_cache_delete($user->user_login, 'userlogins');
2241         
2242         return true;
2243 }
2244
2245 function delete_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                 $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key' AND meta_value = '$meta_value'");
2257         else
2258                 $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
2259                 
2260         $user = get_userdata($user_id);
2261         wp_cache_delete($user_id, 'users');
2262         wp_cache_delete($user->user_login, 'userlogins');
2263         
2264         return true;
2265 }
2266
2267 function register_activation_hook($file, $function) {
2268         $file = plugin_basename($file);
2269
2270         add_action('activate_' . $file, $function);
2271 }
2272
2273 function register_deactivation_hook($file, $function) {
2274         $file = plugin_basename($file);
2275
2276         add_action('deactivate_' . $file, $function);
2277 }
2278
2279 function plugin_basename($file) {
2280         $file = preg_replace('|\\\\+|', '\\\\', $file);
2281         $file = preg_replace('/^.*wp-content[\\\\\/]plugins[\\\\\/]/', '', $file);
2282         return $file;
2283 }
2284
2285 function get_num_queries() {
2286         global $wpdb;
2287         return $wpdb->num_queries;
2288 }
2289
2290 ?>