Make WordPress Core

source: trunk/wp-includes/functions.php @ 1374

Last change on this file since 1374 was 1374, checked in by rboren, 21 years ago

More rewrite rule refactoring. Move the permalink parser into generate_rewrite_rules() and make it handle categories and authors.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 61.3 KB
Line 
1<?php
2
3if (!function_exists('_')) {
4        function _($string) {
5                return $string;
6        }
7}
8
9if (!function_exists('floatval')) {
10        function floatval($string) {
11                return ((float) $string);
12        }
13}
14
15function popuplinks($text) {
16        // Comment text in popup windows should be filtered through this.
17        // Right now it's a moderately dumb function, ideally it would detect whether
18        // a target or rel attribute was already there and adjust its actions accordingly.
19        $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
20        return $text;
21}
22
23function mysql2date($dateformatstring, $mysqlstring, $use_b2configmonthsdays = 1) {
24        global $month, $weekday;
25        $m = $mysqlstring;
26        if (empty($m)) {
27                return false;
28        }
29        $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)); 
30        if (!empty($month) && !empty($weekday) && $use_b2configmonthsdays) {
31                $datemonth = $month[date('m', $i)];
32                $dateweekday = $weekday[date('w', $i)];
33                $dateformatstring = ' '.$dateformatstring;
34                $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit(substr($dateweekday, 0, 3)), $dateformatstring);
35                $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
36                $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
37                $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit(substr($datemonth, 0, 3)), $dateformatstring);
38                $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
39        }
40        $j = @date($dateformatstring, $i);
41        if (!$j) {
42        // for debug purposes
43        //      echo $i." ".$mysqlstring;
44        }
45        return $j;
46}
47
48function current_time($type, $gmt = 0) {
49        switch ($type) {
50                case 'mysql':
51                        if ($gmt) $d = gmdate('Y-m-d H:i:s');
52                        else $d = gmdate('Y-m-d H:i:s', (time() + (get_settings('gmt_offset') * 3600)));
53                        return $d;
54                        break;
55                case 'timestamp':
56                        if ($gmt) $d = time();
57                        else $d = time() + (get_settings('gmt_offset') * 3600);
58                        return $d;
59                        break;
60        }
61}
62
63function date_i18n($dateformatstring, $unixtimestamp) {
64        global $month, $weekday;
65        $i = $unixtimestamp; 
66        if ((!empty($month)) && (!empty($weekday))) {
67                $datemonth = $month[date('m', $i)];
68                $dateweekday = $weekday[date('w', $i)];
69                $dateformatstring = ' '.$dateformatstring;
70                $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit(substr($dateweekday, 0, 3)), $dateformatstring);
71                $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
72                $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
73                $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit(substr($datemonth, 0, 3)), $dateformatstring);
74                $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
75        }
76        $j = @date($dateformatstring, $i);
77        return $j;
78        }
79
80function get_weekstartend($mysqlstring, $start_of_week) {
81        $my = substr($mysqlstring,0,4);
82        $mm = substr($mysqlstring,8,2);
83        $md = substr($mysqlstring,5,2);
84        $day = mktime(0,0,0, $md, $mm, $my);
85        $weekday = date('w',$day);
86        $i = 86400;
87        while ($weekday > get_settings('start_of_week')) {
88                $weekday = date('w',$day);
89                $day = $day - 86400;
90                $i = 0;
91        }
92        $week['start'] = $day + 86400 - $i;
93        $week['end']   = $day + 691199;
94        return $week;
95}
96
97function get_lastpostdate($timezone = 'server') {
98        global $cache_lastpostdate, $pagenow, $wpdb;
99        $add_seconds_blog = get_settings('gmt_offset') * 3600;
100        $add_seconds_server = date('Z');
101        $now = current_time('mysql', 1);
102        if ( !isset($cache_lastpostdate[$timezone]) ) {
103                switch(strtolower($timezone)) {
104                        case 'gmt':
105                                $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");
106                                break;
107                        case 'blog':
108                                $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");
109                                break;
110                        case 'server':
111                                $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");
112                                break;
113                }
114                $cache_lastpostdate[$timezone] = $lastpostdate;
115        } else {
116                $lastpostdate = $cache_lastpostdate[$timezone];
117        }
118        return $lastpostdate;
119}
120
121function get_lastpostmodified($timezone = 'server') {
122        global $cache_lastpostmodified, $pagenow, $wpdb;
123        $add_seconds_blog = get_settings('gmt_offset') * 3600;
124        $add_seconds_server = date('Z');
125        $now = current_time('mysql', 1);
126        if ( !isset($cache_lastpostmodified[$timezone]) ) {
127                switch(strtolower($timezone)) {
128                        case 'gmt':
129                                $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");
130                                break;
131                        case 'blog':
132                                $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");
133                                break;
134                        case 'server':
135                                $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");
136                                break;
137                }
138                $lastpostdate = get_lastpostdate($timezone);
139                if ($lastpostdate > $lastpostmodified) {
140                        $lastpostmodified = $lastpostdate;
141                }
142                $cache_lastpostmodified[$timezone] = $lastpostmodified;
143        } else {
144                $lastpostmodified = $cache_lastpostmodified[$timezone];
145        }
146        return $lastpostmodified;
147}
148
149function user_pass_ok($user_login,$user_pass) {
150        global $cache_userdata;
151        if ( empty($cache_userdata[$user_login]) ) {
152                $userdata = get_userdatabylogin($user_login);
153        } else {
154                $userdata = $cache_userdata[$user_login];
155        }
156        return (md5($user_pass) == $userdata->user_pass);
157}
158
159function get_currentuserinfo() { // a bit like get_userdata(), on steroids
160        global $user_login, $userdata, $user_level, $user_ID, $user_nickname, $user_email, $user_url, $user_pass_md5, $cookiehash;
161        // *** retrieving user's data from cookies and db - no spoofing
162
163        if (isset($_COOKIE['wordpressuser_' . $cookiehash])) 
164                $user_login = $_COOKIE['wordpressuser_' . $cookiehash];
165        $userdata = get_userdatabylogin($user_login);
166        $user_level = $userdata->user_level;
167        $user_ID = $userdata->ID;
168        $user_nickname = $userdata->user_nickname;
169        $user_email = $userdata->user_email;
170        $user_url = $userdata->user_url;
171        $user_pass_md5 = md5($userdata->user_pass);
172}
173
174function get_userdata($userid) {
175        global $wpdb, $cache_userdata;
176        if ( empty($cache_userdata[$userid]) ) {
177                $user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE ID = '$userid'");
178                $user->user_nickname = stripslashes($user->user_nickname);
179                $user->user_firstname = stripslashes($user->user_firstname);
180                $user->user_lastname = stripslashes($user->user_lastname);
181                $user->user_description = stripslashes($user->user_description);
182                $cache_userdata[$userid] = $user;
183        } else {
184                $user = $cache_userdata[$userid];
185        }
186        return $user;
187}
188
189function get_userdatabylogin($user_login) {
190        global $cache_userdata, $wpdb;
191        if ( empty($cache_userdata["$user_login"]) ) {
192                $user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE user_login = '$user_login'");
193                $cache_userdata["$user_login"] = $user;
194        } else {
195                $user = $cache_userdata["$user_login"];
196        }
197        return $user;
198}
199
200function get_userid($user_login) {
201        global $cache_userdata, $wpdb;
202        if ( empty($cache_userdata["$user_login"]) ) {
203                $user_id = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_login = '$user_login'");
204
205                $cache_userdata["$user_login"] = $user_id;
206        } else {
207                $user_id = $cache_userdata["$user_login"];
208        }
209        return $user_id;
210}
211
212function get_usernumposts($userid) {
213        global $wpdb;
214        return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid'");
215}
216
217// examine a url (supposedly from this blog) and try to
218// determine the post ID it represents.
219function url_to_postid($url = '') {
220        global $wpdb;
221
222        $siteurl = get_settings('home');
223        // Take a link like 'http://example.com/blog/something'
224        // and extract just the '/something':
225        $uri = preg_replace("#$siteurl#i", '', $url);
226
227        // on failure, preg_replace just returns the subject string
228        // so if $uri and $siteurl are the same, they didn't match:
229        if ($uri == $siteurl) 
230                return 0;
231               
232        // First, check to see if there is a 'p=N' to match against:
233        preg_match('#[?&]p=(\d+)#', $uri, $values);
234        $p = intval($values[1]);
235        if ($p) return $p;
236       
237        // Match $uri against our permalink structure
238        $permalink_structure = get_settings('permalink_structure');
239       
240        // Matt's tokenizer code
241        $rewritecode = array(
242                '%year%',
243                '%monthnum%',
244                '%day%',
245                '%hour%',
246                '%minute%',
247                '%second%',
248                '%postname%',
249                '%post_id%'
250        );
251        $rewritereplace = array(
252                '([0-9]{4})?',
253                '([0-9]{1,2})?',
254                '([0-9]{1,2})?',
255                '([0-9]{1,2})?',
256                '([0-9]{1,2})?',
257                '([0-9]{1,2})?',
258                '([_0-9a-z-]+)?',
259                '([0-9]+)?'
260        );
261
262        // Turn the structure into a regular expression
263        $matchre = str_replace('/', '/?', $permalink_structure);
264        $matchre = str_replace($rewritecode, $rewritereplace, $matchre);
265
266        // Extract the key values from the uri:
267        preg_match("#$matchre#",$uri,$values);
268
269        // Extract the token names from the structure:
270        preg_match_all("#%(.+?)%#", $permalink_structure, $tokens);
271
272        for($i = 0; $i < count($tokens[1]); $i++) {
273                $name = $tokens[1][$i];
274                $value = $values[$i+1];
275
276                // Create a variable named $year, $monthnum, $day, $postname, or $post_id:
277                $$name = $value;
278        }
279       
280        // If using %post_id%, we're done:
281        if (intval($post_id)) return intval($post_id);
282
283        // Otherwise, build a WHERE clause, making the values safe along the way:
284        if ($year) $where .= " AND YEAR(post_date) = '" . intval($year) . "'";
285        if ($monthnum) $where .= " AND MONTH(post_date) = '" . intval($monthnum) . "'";
286        if ($day) $where .= " AND DAYOFMONTH(post_date) = '" . intval($day) . "'";
287        if ($hour) $where .= " AND HOUR(post_date) = '" . intval($hour) . "'";
288        if ($minute) $where .= " AND MINUTE(post_date) = '" . intval($minute) . "'";
289        if ($second) $where .= " AND SECOND(post_date) = '" . intval($second) . "'";
290        if ($postname) $where .= " AND post_name = '" . $wpdb->escape($postname) . "' ";
291
292        // Run the query to get the post ID:
293        $id = intval($wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE 1 = 1 " . $where));
294
295        return $id;
296}
297
298
299/* Options functions */
300
301function get_settings($setting) {
302        global $wpdb, $cache_settings;
303        if (strstr($_SERVER['REQUEST_URI'], 'install.php')) {
304                return false;
305        }
306
307        if ( (empty($cache_settings)) ) {
308                $settings = get_alloptions();
309                $cache_settings = $settings;
310        } else {
311                $settings = $cache_settings;
312        }
313
314        if ('home' == $setting && '' == $settings->home) return $settings->siteurl;
315
316        if (!isset($settings->$setting)) {
317                return false;
318        } else {
319                return stripslashes($settings->$setting);
320        }
321}
322
323function get_alloptions() {
324        global $wpdb;
325        $options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
326        if ($options) {
327                foreach ($options as $option) {
328                        // "When trying to design a foolproof system,
329                        //  never underestimate the ingenuity of the fools :)"
330                        if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
331                        if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
332                        if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
333
334                        $all_options->{$option->option_name} = $option->option_value;
335                }
336        }
337        return $all_options;
338}
339
340function update_option($option_name, $newvalue) {
341        global $wpdb, $cache_settings;
342        $newvalue = stripslashes($newvalue);
343        $newvalue = trim($newvalue); // I can't think of any situation we wouldn't want to trim
344        $newvalue = $wpdb->escape($newvalue);
345        $wpdb->query("UPDATE $wpdb->options SET option_value = '$newvalue' WHERE option_name = '$option_name'");
346        $cache_settings = get_alloptions(); // Re cache settings
347        return true;
348}
349
350
351// thx Alex Stapleton, http://alex.vort-x.net/blog/
352function add_option($name, $value='') {
353        // Adds an option if it doesn't already exist
354        global $wpdb;
355        if(!get_settings($name)) {
356                $name = $wpdb->escape($name);
357                $value = $wpdb->escape($value);
358                $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value) VALUES ('$name', '$value')");
359
360                if($wpdb->insert_id) {
361                        global $cache_settings;
362                        $cache_settings->{$name} = $value;
363                }
364        }
365        return;
366}
367
368function delete_option($name) {
369        global $wpdb;
370        // Get the ID, if no ID then return
371        $option_id = $wpdb->get_var("SELECT option_id FROM $wpdb->options WHERE option_name = '$name'");
372        if (!$option_id) return false;
373        $wpdb->query("DELETE FROM $wpdb->optiongroup_options WHERE option_id = '$option_id'");
374        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = '$name'");
375        return true;
376}
377
378function get_postdata($postid) {
379        global $post, $wpdb;
380
381        $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = '$postid'");
382       
383        $postdata = array (
384                'ID' => $post->ID, 
385                'Author_ID' => $post->post_author, 
386                'Date' => $post->post_date, 
387                'Content' => $post->post_content, 
388                'Excerpt' => $post->post_excerpt, 
389                'Title' => $post->post_title, 
390                'Category' => $post->post_category,
391                'Lat' => $post->post_lat,
392                'Lon' => $post->post_lon,
393                'post_status' => $post->post_status,
394                'comment_status' => $post->comment_status,
395                'ping_status' => $post->ping_status,
396                'post_password' => $post->post_password,
397                'to_ping' => $post->to_ping,
398                'pinged' => $post->pinged,
399                'post_name' => $post->post_name
400        );
401        return $postdata;
402}
403
404function get_commentdata($comment_ID,$no_cache=0,$include_unapproved=false) { // less flexible, but saves DB queries
405        global $postc,$id,$commentdata, $wpdb;
406        if ($no_cache) {
407                $query = "SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_ID'";
408                if (false == $include_unapproved) {
409                    $query .= " AND comment_approved = '1'";
410                }
411                $myrow = $wpdb->get_row($query, ARRAY_A);
412        } else {
413                $myrow['comment_ID']=$postc->comment_ID;
414                $myrow['comment_post_ID']=$postc->comment_post_ID;
415                $myrow['comment_author']=$postc->comment_author;
416                $myrow['comment_author_email']=$postc->comment_author_email;
417                $myrow['comment_author_url']=$postc->comment_author_url;
418                $myrow['comment_author_IP']=$postc->comment_author_IP;
419                $myrow['comment_date']=$postc->comment_date;
420                $myrow['comment_content']=$postc->comment_content;
421                $myrow['comment_karma']=$postc->comment_karma;
422                if (strstr($myrow['comment_content'], '<trackback />')) {
423                        $myrow['comment_type'] = 'trackback';
424                } elseif (strstr($myrow['comment_content'], '<pingback />')) {
425                        $myrow['comment_type'] = 'pingback';
426                } else {
427                        $myrow['comment_type'] = 'comment';
428                }
429        }
430        return $myrow;
431}
432
433function get_catname($cat_ID) {
434        global $cache_catnames, $wpdb;
435        if ( !$cache_catnames ) {
436        $results = $wpdb->get_results("SELECT * FROM $wpdb->categories") or die('Oops, couldn\'t query the db for categories.');
437                foreach ($results as $post) {
438                        $cache_catnames[$post->cat_ID] = $post->cat_name;
439                }
440        }
441        $cat_name = $cache_catnames[$cat_ID];
442        return $cat_name;
443}
444
445function gzip_compression() {
446        global $gzip_compressed;
447        if (strstr($_SERVER['PHP_SELF'], 'wp-admin')) return true;
448                if (!$gzip_compressed) {
449                $phpver = phpversion(); //start gzip compression
450                if($phpver >= "4.0.4pl1") {
451                        if(extension_loaded("zlib")) { 
452                                ob_start("ob_gzhandler"); 
453                        }
454                } else if($phpver > "4.0") {
455                        if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
456                                if(extension_loaded("zlib")) { 
457                                        $do_gzip_compress = TRUE; 
458                                        ob_start(); 
459                                        ob_implicit_flush(0); 
460                                        header("Content-Encoding: gzip");
461                                }
462                        }
463                } //end gzip compression - that piece of script courtesy of the phpBB dev team
464                $gzip_compressed=1;
465        }
466}
467
468
469// functions to count the page generation time (from phpBB2)
470// ( or just any time between timer_start() and timer_stop() )
471
472function timer_start() {
473    global $timestart;
474    $mtime = microtime();
475    $mtime = explode(" ",$mtime);
476    $mtime = $mtime[1] + $mtime[0];
477    $timestart = $mtime;
478    return true;
479}
480
481function timer_stop($display=0,$precision=3) { //if called like timer_stop(1), will echo $timetotal
482    global $timestart,$timeend;
483    $mtime = microtime();
484    $mtime = explode(" ",$mtime);
485    $mtime = $mtime[1] + $mtime[0];
486    $timeend = $mtime;
487    $timetotal = $timeend-$timestart;
488    if ($display)
489        echo number_format($timetotal,$precision);
490    return $timetotal;
491}
492
493function weblog_ping($server = '', $path = '') {
494        $debug = false;
495        include_once (ABSPATH . WPINC . '/class-xmlrpc.php');
496        include_once (ABSPATH . WPINC . '/class-xmlrpcs.php');
497
498        $f = new xmlrpcmsg('weblogUpdates.ping',
499                array(new xmlrpcval(get_settings('blogname'), 'string'),
500                        new xmlrpcval(get_settings('home') ,'string')));
501        $c = new xmlrpc_client($path, $server, 80);
502        $r = $c->send($f);
503
504        if ('0' != $r) {       
505                if ($debug) {
506                        echo "<h3>Response Object Dump:</h3>
507                                <pre>\n";
508                        print_r($r);
509                        echo "</pre>\n";
510                }
511
512                $v = @phpxmlrpc_decode($r->value());
513                if (!$r->faultCode()) {
514                        $result['message'] =  "<p class=\"rpcmsg\">";
515                        $result['message'] = $result['message'] .  $v["message"] . "<br />\n";
516                        $result['message'] = $result['message'] . "</p>";
517                } else {
518                        $result['err'] = $r->faultCode();
519                        $result['message'] =  "<!--\n";
520                        $result['message'] = $result['message'] . "Fault: ";
521                        $result['message'] = $result['message'] . "Code: " . $r->faultCode();
522                        $result['message'] = $result['message'] . " Reason '" .$r->faultString()."'<BR>";
523                        $result['message'] = $result['message'] . "-->\n";
524                }
525
526                if ($debug) print '<blockquote>' . $result['message'] . '</blockquote>';
527        }
528}
529
530function generic_ping($post_id = 0) {
531        $services = get_settings('ping_sites');
532        $services = preg_replace("|(\s)+|", '$1', $services); // Kill dupe lines
533        $services = trim($services);
534        if ('' != $services) {
535                $services = explode("\n", $services);
536                foreach ($services as $service) {
537                        $uri = parse_url($service);
538                        weblog_ping($uri['host'], $uri['path']);
539                }
540        }
541}
542
543add_action('publish_post', 'generic_ping');
544
545// Send a Trackback
546function trackback($trackback_url, $title, $excerpt, $ID) {
547        global $wpdb;
548        $title = urlencode(stripslashes($title));
549        $excerpt = urlencode(stripslashes($excerpt));
550        $blog_name = urlencode(stripslashes(get_settings('blogname')));
551        $tb_url = $trackback_url;
552        $url = urlencode(get_permalink($ID));
553        $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
554        $trackback_url = parse_url($trackback_url);
555        $http_request  = 'POST ' . $trackback_url['path'] . $trackback_url['query'] . " HTTP/1.0\r\n";
556        $http_request .= 'Host: '.$trackback_url['host']."\r\n";
557        $http_request .= 'Content-Type: application/x-www-form-urlencoded'."\r\n";
558        $http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
559        $http_request .= "\r\n";
560        $http_request .= $query_string;
561        $fs = @fsockopen($trackback_url['host'], 80);
562        @fputs($fs, $http_request);
563/*
564        $debug_file = 'trackback.log';
565        $fp = fopen($debug_file, 'a');
566        fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
567        while(!@feof($fs)) {
568                fwrite($fp, @fgets($fs, 4096));
569        }
570        fwrite($fp, "\n\n");
571        fclose($fp);
572*/
573        @fclose($fs);
574
575        $wpdb->query("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
576        $wpdb->query("UPDATE $wpdb->posts SET to_ping = REPLACE(to_ping, '$tb_url', '') WHERE ID = '$ID'");
577        return $result;
578}
579
580// trackback - reply
581function trackback_response($error = 0, $error_message = '') {
582        if ($error) {
583                echo '<?xml version="1.0" encoding="iso-8859-1"?'.">\n";
584                echo "<response>\n";
585                echo "<error>1</error>\n";
586                echo "<message>$error_message</message>\n";
587                echo "</response>";
588        } else {
589                echo '<?xml version="1.0" encoding="iso-8859-1"?'.">\n";
590                echo "<response>\n";
591                echo "<error>0</error>\n";
592                echo "</response>";
593        }
594        die();
595}
596
597function make_url_footnote($content) {
598        preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
599        $j = 0;
600        for ($i=0; $i<count($matches[0]); $i++) {
601                $links_summary = (!$j) ? "\n" : $links_summary;
602                $j++;
603                $link_match = $matches[0][$i];
604                $link_number = '['.($i+1).']';
605                $link_url = $matches[2][$i];
606                $link_text = $matches[4][$i];
607                $content = str_replace($link_match, $link_text.' '.$link_number, $content);
608                $link_url = (strtolower(substr($link_url,0,7)) != 'http://') ? get_settings('home') . $link_url : $link_url;
609                $links_summary .= "\n".$link_number.' '.$link_url;
610        }
611        $content = strip_tags($content);
612        $content .= $links_summary;
613        return $content;
614}
615
616
617function xmlrpc_getposttitle($content) {
618        global $post_default_title;
619        if (preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle)) {
620                $post_title = $matchtitle[0];
621                $post_title = preg_replace('/<title>/si', '', $post_title);
622                $post_title = preg_replace('/<\/title>/si', '', $post_title);
623        } else {
624                $post_title = $post_default_title;
625        }
626        return $post_title;
627}
628       
629function xmlrpc_getpostcategory($content) {
630        global $post_default_category;
631        if (preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat)) {
632                $post_category = trim($matchcat[1], ',');
633                $post_category = explode(',', $post_category);
634        } else {
635                $post_category = $post_default_category;
636        }
637        return $post_category;
638}
639
640function xmlrpc_removepostdata($content) {
641        $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content);
642        $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content);
643        $content = trim($content);
644        return $content;
645}
646
647function debug_fopen($filename, $mode) {
648        global $debug;
649        if ($debug == 1) {
650                $fp = fopen($filename, $mode);
651                return $fp;
652        } else {
653                return false;
654        }
655}
656
657function debug_fwrite($fp, $string) {
658        global $debug;
659        if ($debug == 1) {
660                fwrite($fp, $string);
661        }
662}
663
664function debug_fclose($fp) {
665        global $debug;
666        if ($debug == 1) {
667                fclose($fp);
668        }
669}
670
671function pingback($content, $post_ID) {
672include_once (ABSPATH . WPINC . '/class-xmlrpc.php');
673include_once (ABSPATH . WPINC . '/class-xmlrpcs.php');
674        // original code by Mort (http://mort.mine.nu:8080)
675        global $wp_version;
676        $log = debug_fopen('./pingback.log', 'a');
677        $post_links = array();
678        debug_fwrite($log, 'BEGIN '.time()."\n");
679
680        // Variables
681        $ltrs = '\w';
682        $gunk = '/#~:.?+=&%@!\-';
683        $punc = '.:?\-';
684        $any = $ltrs.$gunk.$punc;
685        $pingback_str_dquote = 'rel="pingback"';
686        $pingback_str_squote = 'rel=\'pingback\'';
687        $x_pingback_str = 'x-pingback: ';
688        $pingback_href_original_pos = 27;
689
690        // Step 1
691        // Parsing the post, external links (if any) are stored in the $post_links array
692        // This regexp comes straight from phpfreaks.com
693        // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
694        preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
695
696        // Debug
697        debug_fwrite($log, 'Post contents:');
698        debug_fwrite($log, $content."\n");
699       
700        // Step 2.
701        // Walking thru the links array
702        // first we get rid of links pointing to sites, not to specific files
703        // Example:
704        // http://dummy-weblog.org
705        // http://dummy-weblog.org/
706        // http://dummy-weblog.org/post.php
707        // We don't wanna ping first and second types, even if they have a valid <link/>
708
709        foreach($post_links_temp[0] as $link_test){
710                $test = parse_url($link_test);
711                if (isset($test['query'])) {
712                        $post_links[] = $link_test;
713                } elseif(($test['path'] != '/') && ($test['path'] != '')) {
714                        $post_links[] = $link_test;
715                }
716        }
717
718        foreach ($post_links as $pagelinkedto){
719                debug_fwrite($log, 'Processing -- '.$pagelinkedto."\n\n");
720
721                $bits = parse_url($pagelinkedto);
722                if (!isset($bits['host'])) {
723                        debug_fwrite($log, 'Couldn\'t find a hostname for '.$pagelinkedto."\n\n");
724                        continue;
725                }
726                $host = $bits['host'];
727                $path = isset($bits['path']) ? $bits['path'] : '';
728                if (isset($bits['query'])) {
729                        $path .= '?'.$bits['query'];
730                }
731                if (!$path) {
732                        $path = '/';
733                }
734                $port = isset($bits['port']) ? $bits['port'] : 80;
735
736                // Try to connect to the server at $host
737                $fp = fsockopen($host, $port, $errno, $errstr, 30);
738                if (!$fp) {
739                        debug_fwrite($log, 'Couldn\'t open a connection to '.$host."\n\n");
740                        continue;
741                }
742
743                // Send the GET request
744                $request = "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: WordPress/$wp_version PHP/" . phpversion() . "\r\n\r\n";
745                ob_end_flush();
746                fputs($fp, $request);
747
748                // Start receiving headers and content
749                $contents = '';
750                $headers = '';
751                $gettingHeaders = true;
752                $found_pingback_server = 0;
753                while (!feof($fp)) {
754                        $line = fgets($fp, 4096);
755                        if (trim($line) == '') {
756                                $gettingHeaders = false;
757                        }
758                        if (!$gettingHeaders) {
759                                $contents .= trim($line)."\n";
760                                $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
761                                $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
762                        } else {
763                                $headers .= trim($line)."\n";
764                                $x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str);
765                        }
766                        if ($x_pingback_header_offset) {
767                                preg_match('#x-pingback: (.+)#is', $headers, $matches);
768                                $pingback_server_url = trim($matches[1]);
769                                debug_fwrite($log, "Pingback server found from X-Pingback header @ $pingback_server_url\n");
770                                $found_pingback_server = 1;
771                                break;
772                        }
773                        if ($pingback_link_offset_dquote || $pingback_link_offset_squote) {
774                                $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
775                                $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
776                                $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
777                                $pingback_href_start = $pingback_href_pos+6;
778                                $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
779                                $pingback_server_url_len = $pingback_href_end-$pingback_href_start;
780                                $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
781                                debug_fwrite($log, "Pingback server found from Pingback <link /> tag @ $pingback_server_url\n");
782                                $found_pingback_server = 1;
783                                break;
784                        }
785                }
786
787                if (!$found_pingback_server) {
788                        debug_fwrite($log, "Pingback server not found\n\n*************************\n\n");
789                        @fclose($fp);
790                } else {
791                        debug_fwrite($log,"\n\nPingback server data\n");
792
793                        // Assuming there's a "http://" bit, let's get rid of it
794                        $host_clear = substr($pingback_server_url, 7);
795
796                        //  the trailing slash marks the end of the server name
797                        $host_end = strpos($host_clear, '/');
798
799                        // Another clear cut
800                        $host_len = $host_end-$host_start;
801                        $host = substr($host_clear, 0, $host_len);
802                        debug_fwrite($log, 'host: '.$host."\n");
803
804                        // If we got the server name right, the rest of the string is the server path
805                        $path = substr($host_clear,$host_end);
806                        debug_fwrite($log, 'path: '.$path."\n\n");
807
808                         // Now, the RPC call
809                        $method = 'pingback.ping';
810                        debug_fwrite($log, 'Page Linked To: '.$pagelinkedto."\n");
811                        debug_fwrite($log, 'Page Linked From: ');
812                        $pagelinkedfrom = get_permalink($post_ID);
813                        debug_fwrite($log, $pagelinkedfrom."\n");
814
815                        $client = new xmlrpc_client($path, $host, 80);
816                        $message = new xmlrpcmsg($method, array(new xmlrpcval($pagelinkedfrom), new xmlrpcval($pagelinkedto)));
817                        $result = $client->send($message);
818                        if ($result){
819                                if (!$result->value()){
820                                        debug_fwrite($log, $result->faultCode().' -- '.$result->faultString());
821                                } else {
822                                        $value = phpxmlrpc_decode($result->value());
823                                        if (is_array($value)) {
824                                                $value_arr = '';
825                                                foreach($value as $blah) {
826                                                        $value_arr .= $blah.' |||| ';
827                                                }
828                                                debug_fwrite($log, $value_arr);
829                                        } else {
830                                                debug_fwrite($log, $value);
831                                        }
832                                }
833                        }
834                        @fclose($fp);
835                }
836        }
837
838        debug_fwrite($log, "\nEND: ".time()."\n****************************\n\r");
839        debug_fclose($log);
840}
841
842function doGeoUrlHeader($post_list = '') {
843    global $posts;
844
845    if ($posts && 1 === count($posts) && ! empty($posts[0]->post_lat)) {
846        // there's only one result  see if it has a geo code
847        $row = $posts[0];
848        $lat = $row->post_lat;
849        $lon = $row->post_lon;
850        $title = $row->post_title;
851        if(($lon != null) && ($lat != null) ) {
852            echo "<meta name=\"ICBM\" content=\"".$lat.", ".$lon."\" />\n";
853            echo "<meta name=\"DC.title\" content=\"".convert_chars(strip_tags(get_bloginfo("name")))." - ".$title."\" />\n";
854            echo "<meta name=\"geo.position\" content=\"".$lat.";".$lon."\" />\n";
855            return;
856        }
857    } else {
858        if(get_settings('use_default_geourl')) {
859            // send the default here
860            echo "<meta name='ICBM' content=\"". get_settings('default_geourl_lat') .", ". get_settings('default_geourl_lon') ."\" />\n";
861            echo "<meta name='DC.title' content=\"".convert_chars(strip_tags(get_bloginfo("name")))."\" />\n";
862            echo "<meta name='geo.position' content=\"". get_settings('default_geourl_lat') .";". get_settings('default_geourl_lon') ."\" />\n";
863        }
864    }
865}
866
867function getRemoteFile($host,$path) {
868    $fp = fsockopen($host, 80, $errno, $errstr);
869    if ($fp) {
870        fputs($fp,"GET $path HTTP/1.0\r\nHost: $host\r\n\r\n");
871        while ($line = fgets($fp, 4096)) {
872            $lines[] = $line;
873        }
874        fclose($fp);
875        return $lines;
876    } else {
877        return false;
878    }
879}
880
881function pingGeoURL($blog_ID) {
882
883    $ourUrl = get_settings('home') ."/index.php?p=".$blog_ID;
884    $host="geourl.org";
885    $path="/ping/?p=".$ourUrl;
886    getRemoteFile($host,$path); 
887}
888
889/* wp_set_comment_status:
890   part of otaku42's comment moderation hack
891   changes the status of a comment according to $comment_status.
892   allowed values:
893   hold   : set comment_approve field to 0
894   approve: set comment_approve field to 1
895   delete : remove comment out of database
896   
897   returns true if change could be applied
898   returns false on database error or invalid value for $comment_status
899 */
900function wp_set_comment_status($comment_id, $comment_status) {
901    global $wpdb;
902
903    switch($comment_status) {
904                case 'hold':
905                        $query = "UPDATE $wpdb->comments SET comment_approved='0' WHERE comment_ID='$comment_id' LIMIT 1";
906                break;
907                case 'approve':
908                        $query = "UPDATE $wpdb->comments SET comment_approved='1' WHERE comment_ID='$comment_id' LIMIT 1";
909                break;
910                case 'delete':
911                        $query = "DELETE FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1";
912                break;
913                default:
914                        return false;
915    }
916   
917    if ($wpdb->query($query)) {
918                do_action('wp_set_comment_status', $comment_id);
919                return true;
920    } else {
921                return false;
922    }
923}
924
925
926/* wp_get_comment_status
927   part of otaku42's comment moderation hack
928   gets the current status of a comment
929
930   returned values:
931   "approved"  : comment has been approved
932   "unapproved": comment has not been approved
933   "deleted   ": comment not found in database
934
935   a (boolean) false signals an error
936 */
937function wp_get_comment_status($comment_id) {
938    global $wpdb;
939   
940    $result = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1");
941    if ($result == NULL) {
942        return "deleted";
943    } else if ($result == "1") {
944        return "approved";
945    } else if ($result == "0") {
946        return "unapproved";
947    } else {
948        return false;
949    }
950}
951
952function wp_notify_postauthor($comment_id, $comment_type='comment') {
953    global $wpdb;
954    global $querystring_start, $querystring_equal, $querystring_separator;
955   
956    $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1");
957    $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID='$comment->comment_post_ID' LIMIT 1");
958    $user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE ID='$post->post_author' LIMIT 1");
959
960    if ('' == $user->user_email) return false; // If there's no email to send the comment to
961
962        $comment_author_domain = gethostbyaddr($comment->comment_author_IP);
963
964        $blogname = stripslashes(get_settings('blogname'));
965       
966        if ('comment' == $comment_type) {
967                $notify_message  = "New comment on your post #$comment->comment_post_ID \"".stripslashes($post->post_title)."\"\r\n\r\n";
968                $notify_message .= "Author : $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
969                $notify_message .= "E-mail : $comment->comment_author_email\r\n";
970                $notify_message .= "URI    : $comment->comment_author_url\r\n";
971                $notify_message .= "Whois  : http://ws.arin.net/cgi-bin/whois.pl?queryinput=$comment->comment_author_IP\r\n";
972                $notify_message .= "Comment:\r\n".stripslashes($comment->comment_content)."\r\n\r\n";
973                $notify_message .= "You can see all comments on this post here: \r\n";
974                $subject = '[' . $blogname . '] Comment: "' .stripslashes($post->post_title).'"';
975        } elseif ('trackback' == $comment_type) {
976                $notify_message  = "New trackback on your post #$comment_post_ID \"".stripslashes($post->post_title)."\"\r\n\r\n";
977                $notify_message .= "Website: $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
978                $notify_message .= "URI    : $comment->comment_author_url\r\n";
979                $notify_message .= "Excerpt: \n".stripslashes($comment->comment_content)."\r\n\r\n";
980                $notify_message .= "You can see all trackbacks on this post here: \r\n";
981                $subject = '[' . $blogname . '] Trackback: "' .stripslashes($post->post_title).'"';
982        } elseif ('pingback' == $comment_type) {
983                $notify_message  = "New pingback on your post #$comment_post_ID \"".stripslashes($post->post_title)."\"\r\n\r\n";
984                $notify_message .= "Website: $comment->comment_author\r\n";
985                $notify_message .= "URI    : $comment->comment_author_url\r\n";
986                $notify_message .= "Excerpt: \n[...] $original_context [...]\r\n\r\n";
987                $notify_message .= "You can see all pingbacks on this post here: \r\n";
988                $subject = '[' . $blogname . '] Pingback: "' .stripslashes($post->post_title).'"';
989        }
990        $notify_message .= get_permalink($comment->comment_post_ID) . '#comments';
991
992        if ('' == $comment->comment_author_email || '' == $comment->comment_author) {
993                $from = "From: \"$blogname\" <wordpress@" . $_SERVER['SERVER_NAME'] . '>';
994        } else {
995                $from = 'From: "' . stripslashes($comment->comment_author) . "\" <$comment->comment_author_email>";
996        }
997
998        $message_headers = "MIME-Version: 1.0\r\n"
999                . "$from\r\n"
1000                . "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\r\n";
1001
1002        @mail($user->user_email, $subject, $notify_message, $message_headers);
1003   
1004    return true;
1005}
1006
1007/* wp_notify_moderator
1008   notifies the moderator of the blog (usually the admin)
1009   about a new comment that waits for approval
1010   always returns true
1011 */
1012function wp_notify_moderator($comment_id) {
1013    global $wpdb;
1014    global $querystring_start, $querystring_equal, $querystring_separator;
1015   
1016    $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1");
1017    $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID='$comment->comment_post_ID' LIMIT 1");
1018    $user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE ID='$post->post_author' LIMIT 1");
1019
1020    $comment_author_domain = gethostbyaddr($comment->comment_author_IP);
1021    $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
1022
1023    $notify_message  = "A new comment on the post #$comment->comment_post_ID \"".stripslashes($post->post_title)."\" is waiting for your approval\r\n\r\n";
1024    $notify_message .= "Author : $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
1025    $notify_message .= "E-mail : $comment->comment_author_email\r\n";
1026    $notify_message .= "URL    : $comment->comment_author_url\r\n";
1027    $notify_message .= "Whois  : http://ws.arin.net/cgi-bin/whois.pl?queryinput=$comment->comment_author_IP\r\n";
1028    $notify_message .= "Comment:\r\n".stripslashes($comment->comment_content)."\r\n\r\n";
1029    $notify_message .= "To approve this comment, visit: " . get_settings('siteurl') . "/wp-admin/post.php?action=mailapprovecomment&p=".$comment->comment_post_ID."&comment=$comment_id\r\n";
1030    $notify_message .= "To delete this comment, visit: " . get_settings('siteurl') . "/wp-admin/post.php?action=confirmdeletecomment&p=".$comment->comment_post_ID."&comment=$comment_id\r\n";
1031    $notify_message .= "Currently $comments_waiting comments are waiting for approval. Please visit the moderation panel:\r\n";
1032    $notify_message .= get_settings('siteurl') . "/wp-admin/moderation.php\r\n";
1033
1034    $subject = '[' . stripslashes(get_settings('blogname')) . '] Please approve: "' .stripslashes($post->post_title).'"';
1035    $admin_email = get_settings("admin_email");
1036    $from  = "From: $admin_email";
1037
1038    $message_headers = "MIME-Version: 1.0\r\n"
1039        . "$from\r\n"
1040        . "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\r\n";
1041
1042    @mail($admin_email, $subject, $notify_message, $message_headers);
1043   
1044    return true;
1045}
1046
1047
1048function start_wp() {
1049        global $post, $id, $postdata, $authordata, $day, $preview, $page, $pages, $multipage, $more, $numpages;
1050        global $pagenow;
1051        if (!$preview) {
1052                $id = $post->ID;
1053        } else {
1054                $id = 0;
1055                $postdata = array (
1056                        'ID' => 0,
1057                        'Author_ID' => $_GET['preview_userid'],
1058                        'Date' => $_GET['preview_date'],
1059                        'Content' => $_GET['preview_content'],
1060                        'Excerpt' => $_GET['preview_excerpt'],
1061                        'Title' => $_GET['preview_title'],
1062                        'Category' => $_GET['preview_category'],
1063                        'Notify' => 1
1064                        );
1065        }
1066        $authordata = get_userdata($post->post_author);
1067
1068        $day = mysql2date('d.m.y', $post->post_date);
1069        $currentmonth = mysql2date('m', $post->post_date);
1070        $numpages = 1;
1071        if (!$page)
1072                $page = 1;
1073        if (isset($p))
1074                $more = 1;
1075        $content = $post->post_content;
1076        if (preg_match('/<!--nextpage-->/', $post->post_content)) {
1077                if ($page > 1)
1078                        $more = 1;
1079                $multipage = 1;
1080                $content = stripslashes($post->post_content);
1081                $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
1082                $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
1083                $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
1084                $pages = explode('<!--nextpage-->', $content);
1085                $numpages = count($pages);
1086        } else {
1087                $pages[0] = stripslashes($post->post_content);
1088                $multipage = 0;
1089        }
1090        return true;
1091}
1092
1093function is_new_day() {
1094        global $day, $previousday;
1095        if ($day != $previousday) {
1096                return(1);
1097        } else {
1098                return(0);
1099        }
1100}
1101
1102// Filters: these are the core of WP's plugin architecture
1103
1104function apply_filters($tag, $string) {
1105        global $wp_filter;
1106        if (isset($wp_filter['all'])) {
1107                foreach ($wp_filter['all'] as $priority => $functions) {
1108                        if (isset($wp_filter[$tag][$priority]))
1109                                $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
1110                        else
1111                                $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
1112                        $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
1113                }
1114
1115        }
1116       
1117        if (isset($wp_filter[$tag])) {
1118                ksort($wp_filter[$tag]);
1119                foreach ($wp_filter[$tag] as $priority => $functions) {
1120                        foreach($functions as $function) {
1121                                        $string = $function($string);
1122                        }
1123                }
1124        }
1125        return $string;
1126}
1127
1128function add_filter($tag, $function_to_add, $priority = 10) {
1129        global $wp_filter;
1130        // So the format is wp_filter['tag']['array of priorities']['array of functions']
1131        if (!@in_array($function_to_add, $wp_filter[$tag]["$priority"])) {
1132                $wp_filter[$tag]["$priority"][] = $function_to_add;
1133        }
1134        return true;
1135}
1136
1137function remove_filter($tag, $function_to_remove, $priority = 10) {
1138        global $wp_filter;
1139        if (@in_array($function_to_remove, $wp_filter[$tag]["$priority"])) {
1140                foreach ($wp_filter[$tag]["$priority"] as $function) {
1141                        if ($function_to_remove != $function) {
1142                                $new_function_list[] = $function;
1143                        }
1144                }
1145                $wp_filter[$tag]["$priority"] = $new_function_list;
1146        }
1147        //die(var_dump($wp_filter));
1148        return true;
1149}
1150
1151// The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
1152
1153function do_action($tag, $string) {
1154        return apply_filters($tag, $string);
1155}
1156
1157function add_action($tag, $function_to_add, $priority = 10) {
1158        add_filter($tag, $function_to_add, $priority);
1159}
1160
1161function remove_action($tag, $function_to_remove, $priority = 10) {
1162        remove_filter($tag, $function_to_remove, $priority);
1163}
1164
1165function preg_index($number, $matches = '') {
1166    $match_prefix = '$';
1167    $match_suffix = '';
1168   
1169    if (! empty($matches)) {
1170        $match_prefix = '$' . $matches . '['; 
1171        $match_suffix = ']';
1172    }       
1173   
1174    return "$match_prefix$number$match_suffix";       
1175}
1176
1177function generate_rewrite_rules($permalink_structure = '') {
1178    $rewritecode = 
1179        array(
1180        '%year%',
1181        '%monthnum%',
1182        '%day%',
1183        '%hour%',
1184        '%minute%',
1185        '%second%',
1186        '%postname%',
1187        '%post_id%',
1188    '%category%',
1189    '%author%'
1190        );
1191
1192    $rewritereplace = 
1193        array(
1194        '([0-9]{4})',
1195        '([0-9]{1,2})',
1196        '([0-9]{1,2})',
1197        '([0-9]{1,2})',
1198        '([0-9]{1,2})',
1199        '([0-9]{1,2})',
1200        '([_0-9a-z-]+)',
1201        '([0-9]+)',
1202        '(.*)',
1203        '([_0-9a-z-]+)'
1204        );
1205
1206    $queryreplace = 
1207        array (
1208        'year=',
1209        'monthnum=',
1210        'day=',
1211        'hour=',
1212        'minute=',
1213        'second=',
1214        'name=',
1215        'p=',
1216    'category_name=',
1217    'author_name='
1218        );
1219
1220    $feedregex = '(feed|rdf|rss|rss2|atom)/?$';
1221    $trackbackregex = 'trackback/?$';
1222    $pageregex = 'page/?([0-9]{1,})/?$';
1223
1224    $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));   
1225    preg_match_all('/%.+?%/', $permalink_structure, $tokens);
1226
1227    $num_tokens = count($tokens[0]);
1228
1229    $index = 'index.php';
1230    $feedindex = 'wp-feed.php';
1231    $trackbackindex = 'wp-trackback.php';
1232    for ($i = 0; $i < $num_tokens; ++$i) {
1233             if (0 < $i) {
1234                 $queries[$i] = $queries[$i - 1] . '&';
1235             }
1236             
1237             $query_token = str_replace($rewritecode, $queryreplace, $tokens[0][$i]) . preg_index($i+1, $matches);
1238             $queries[$i] .= $query_token;
1239             }
1240
1241    $structure = str_replace($front, '', $permalink_structure);
1242    $structure = trim($structure, '/');
1243    $dirs = explode('/', $structure);
1244    $num_dirs = count($dirs);
1245
1246    $front = preg_replace('|^/+|', '', $front);
1247
1248    $post_rewrite = array();
1249    $struct = $front;
1250    for ($j = 0; $j < $num_dirs; ++$j) {
1251        $struct .= $dirs[$j] . '/';
1252        $match = str_replace($rewritecode, $rewritereplace, $struct);
1253        $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
1254        $query = $queries[$num_toks - 1];
1255
1256        $pagematch = $match . $pageregex;
1257        $pagequery = $index . '?' . $query . '&paged=' . preg_index($num_toks + 1, $matches);
1258
1259        $feedmatch = $match . $feedregex;
1260        $feedquery = $feedindex . '?' . $query . '&feed=' . preg_index($num_toks + 1, $matches);
1261
1262        $post = 0;
1263        if (strstr($struct, '%postname%') || strstr($struct, '%post_id%')) {
1264                $post = 1;
1265                $trackbackmatch = $match . $trackbackregex;
1266                $trackbackquery = $trackbackindex . '?' . $query;
1267                $match = $match . '?([0-9]+)?/?$';
1268                $query = $index . '?' . $query . '&page=' . preg_index($num_toks + 1, $matches);
1269        } else {
1270            $match .= '?';
1271            $query = $index . '?' . $query;
1272        }
1273       
1274        $post_rewrite = array($feedmatch => $feedquery, $pagematch => $pagequery, $match => $query) + $post_rewrite;
1275
1276        if ($post) {
1277            $post_rewrite = array($trackbackmatch => $trackbackquery) + $post_rewrite;
1278        }
1279    }
1280
1281    return $post_rewrite;
1282}
1283
1284/* rewrite_rules
1285 * Construct rewrite matches and queries from permalink structure.
1286 * matches - The name of the match array to use in the query strings.
1287 *           If empty, $1, $2, $3, etc. are used.
1288 * Returns an associate array of matches and queries.
1289 */
1290function rewrite_rules($matches = '', $permalink_structure = '') {
1291    $rewrite = array();
1292
1293    if (empty($permalink_structure)) {
1294        $permalink_structure = get_settings('permalink_structure');
1295       
1296        if (empty($permalink_structure)) {
1297            return $rewrite;
1298        }
1299    }
1300
1301    $post_rewrite = generate_rewrite_rules($permalink_structure);
1302
1303    // If the permalink does not have year, month, and day, we need to create a
1304    // separate archive rule.
1305    $doarchive = false;
1306    if (! (strstr($permalink_structure, '%year') && strstr($permalink_structure, '%monthnum') && strstr($permalink_structure, '%day')) ) {
1307        $doarchive = true;
1308        $archive_structure = $front . '%year%/%monthnum%/%day%/';
1309        $archive_rewrite =  generate_rewrite_rules($archive_structure);
1310    }
1311
1312    $feedregex = '(feed|rdf|rss|rss2|atom)/?$';
1313    $pageregex = 'page/?([0-9]{1,})/?$';
1314    $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));   
1315
1316    // Site feed
1317    $sitefeedmatch = 'feed/?([_0-9a-z-]+)?/?$';
1318    $sitefeedquery = 'wp-feed.php?feed=' . preg_index(1, $matches);
1319
1320    // Site comment feed
1321    $sitecommentfeedmatch = 'comments/feed/?([_0-9a-z-]+)?/?$';
1322    $sitecommentfeedquery = 'wp-feed.php?feed=' . preg_index(1, $matches) . '&withcomments=1';
1323
1324    // Site page
1325    $sitepagematch = $pageregex;
1326    $sitepagequery = 'index.php?paged=' . preg_index(1, $matches);
1327
1328    $site_rewrite = array(
1329                     $sitefeedmatch => $sitefeedquery,
1330                     $sitecommentfeedmatch => $sitecommentfeedquery,
1331                     $sitepagematch => $sitepagequery,
1332                     );
1333
1334    // Categories
1335        if ( '' == get_settings('category_base') )
1336                $category_structure = $front . 'category/';
1337        else
1338            $category_structure = get_settings('category_base') . '/';
1339
1340    $category_structure = $category_structure . '%category%';
1341    $category_rewrite = generate_rewrite_rules($category_structure);
1342
1343    // Authors
1344    $author_structure = $front . 'author/%author%';
1345    $author_rewrite = generate_rewrite_rules($author_structure);
1346
1347
1348    // Put them together.
1349    $rewrite = $site_rewrite + $category_rewrite + $author_rewrite + $post_rewrite;
1350
1351    // Add on archive rewrite rules if needed.
1352    if ($doarchive) {
1353        $rewrite = $rewrite + $archive_rewrite;
1354    }
1355
1356    return $rewrite;
1357}
1358
1359function get_posts($args) {
1360        global $wpdb;
1361        parse_str($args, $r);
1362        if (!isset($r['numberposts'])) $r['numberposts'] = 5;
1363        if (!isset($r['offset'])) $r['offset'] = 0;
1364        // The following not implemented yet
1365        if (!isset($r['category'])) $r['category'] = '';
1366        if (!isset($r['orderby'])) $r['orderby'] = '';
1367        if (!isset($r['order'])) $r['order'] = '';
1368
1369        $now = current_time('mysql');
1370
1371        $posts = $wpdb->get_results("SELECT DISTINCT * FROM $wpdb->posts WHERE post_date <= '$now' AND (post_status = 'publish') GROUP BY $wpdb->posts.ID ORDER BY post_date DESC LIMIT " . $r['offset'] . ',' . $r['numberposts']);
1372       
1373        return $posts;
1374}
1375
1376function check_comment($author, $email, $url, $comment, $user_ip) {
1377        if (1 == get_settings('comment_moderation')) return false; // If moderation is set to manual
1378
1379        if ( (count(explode('http:', $comment)) - 1) >= get_settings('comment_max_links') )
1380                return false; // Check # of external links
1381
1382        if ('' == trim( get_settings('moderation_keys') ) ) return true; // If moderation keys are empty
1383        $words = explode("\n", get_settings('moderation_keys') );
1384        foreach ($words as $word) {
1385                $word = trim($word);
1386
1387                // Skip empty lines
1388                if (empty($word)) { continue; }
1389
1390                $pattern = "#$word#i";
1391                if ( preg_match($pattern, $author) ) return false;
1392                if ( preg_match($pattern, $email) ) return false;
1393                if ( preg_match($pattern, $url) ) return false;
1394                if ( preg_match($pattern, $comment) ) return false;
1395                if ( preg_match($pattern, $user_ip) ) return false;
1396        }
1397
1398        return true;
1399}
1400
1401function query_posts($query) {
1402    global $wpdb, $pagenow, $request;
1403
1404    parse_str($query);
1405
1406    // First let's clear some variables
1407    $whichcat = '';
1408    $whichauthor = '';
1409    $result = '';
1410    $where = '';
1411    $limits = '';
1412    $distinct = '';
1413    $join = '';
1414
1415    $add_hours = intval(get_settings('gmt_offset'));
1416    $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours));
1417    $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)";
1418
1419    // If a month is specified in the querystring, load that month
1420    if ('' != $m) {
1421        $m = '' . preg_replace('|[^0-9]|', '', $m);
1422        $where .= ' AND YEAR(post_date)=' . substr($m, 0, 4);
1423        if (strlen($m)>5)
1424            $where .= ' AND MONTH(post_date)=' . substr($m, 4, 2);
1425        if (strlen($m)>7)
1426            $where .= ' AND DAYOFMONTH(post_date)=' . substr($m, 6, 2);
1427        if (strlen($m)>9)
1428            $where .= ' AND HOUR(post_date)=' . substr($m, 8, 2);
1429        if (strlen($m)>11)
1430            $where .= ' AND MINUTE(post_date)=' . substr($m, 10, 2);
1431        if (strlen($m)>13)
1432            $where .= ' AND SECOND(post_date)=' . substr($m, 12, 2);
1433    }
1434
1435    if ('' != $hour) {
1436        $hour = '' . intval($hour);
1437        $where .= " AND HOUR(post_date)='$hour'";
1438    }
1439
1440    if ('' != $minute) {
1441        $minute = '' . intval($minute);
1442        $where .= " AND MINUTE(post_date)='$minute'";
1443    }
1444
1445    if ('' != $second) {
1446        $second = '' . intval($second);
1447        $where .= " AND SECOND(post_date)='$second'";
1448    }
1449
1450    if ('' != $year) {
1451        $year = '' . intval($year);
1452        $where .= " AND YEAR(post_date)='$year'";
1453    }
1454
1455    if ('' != $monthnum) {
1456        $monthnum = '' . intval($monthnum);
1457        $where .= " AND MONTH(post_date)='$monthnum'";
1458    }
1459
1460    if ('' != $day) {
1461        $day = '' . intval($day);
1462        $where .= " AND DAYOFMONTH(post_date)='$day'";
1463    }
1464
1465    if ('' != $name) {
1466        $name = preg_replace('/[^a-z0-9-_]/', '', $name);
1467        $where .= " AND post_name = '$name'";
1468    }
1469
1470    if ('' != $w) {
1471        $w = ''.intval($w);
1472        $where .= " AND WEEK(post_date, 1)='$w'";
1473    }
1474
1475    // If a post number is specified, load that post
1476    if (($p != '') && ($p != 'all')) {
1477        $p = intval($p);
1478        $where = ' AND ID = '.$p;
1479    }
1480
1481    // If a search pattern is specified, load the posts that match
1482    if (!empty($s)) {
1483        $s = addslashes_gpc($s);
1484        $search = ' AND (';
1485        $s = preg_replace('/, +/', ' ', $s);
1486        $s = str_replace(',', ' ', $s);
1487        $s = str_replace('"', ' ', $s);
1488        $s = trim($s);
1489        if ($exact) {
1490            $n = '';
1491        } else {
1492            $n = '%';
1493        }
1494        if (!$sentence) {
1495            $s_array = explode(' ',$s);
1496            $search .= '((post_title LIKE \''.$n.$s_array[0].$n.'\') OR (post_content LIKE \''.$n.$s_array[0].$n.'\'))';
1497            for ( $i = 1; $i < count($s_array); $i = $i + 1) {
1498                $search .= ' AND ((post_title LIKE \''.$n.$s_array[$i].$n.'\') OR (post_content LIKE \''.$n.$s_array[$i].$n.'\'))';
1499            }
1500            $search .= ' OR (post_title LIKE \''.$n.$s.$n.'\') OR (post_content LIKE \''.$n.$s.$n.'\')';
1501            $search .= ')';
1502        } else {
1503            $search = ' AND ((post_title LIKE \''.$n.$s.$n.'\') OR (post_content LIKE \''.$n.$s.$n.'\'))';
1504        }
1505    }
1506
1507    // Category stuff
1508
1509    if ((empty($cat)) || ($cat == 'all') || ($cat == '0') || 
1510        // Bypass cat checks if fetching specific posts
1511        (
1512         intval($year) || intval($monthnum) || intval($day) || intval($w) ||
1513         intval($p) || !empty($name) || !empty($s)
1514         )
1515                ) {
1516        $whichcat='';
1517    } else {
1518        $cat = ''.urldecode($cat).'';
1519        $cat = addslashes_gpc($cat);
1520        if (stristr($cat,'-')) {
1521            // Note: if we have a negative, we ignore all the positives. It must
1522            // always mean 'everything /except/ this one'. We should be able to do
1523            // multiple negatives but we don't :-(
1524            $eq = '!=';
1525            $andor = 'AND';
1526            $cat = explode('-',$cat);
1527            $cat = intval($cat[1]);
1528        } else {
1529            $eq = '=';
1530            $andor = 'OR';
1531        }
1532        $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) ";
1533        $cat_array = explode(' ',$cat);
1534        $whichcat .= ' AND (category_id '.$eq.' '.intval($cat_array[0]);
1535        $whichcat .= get_category_children($cat_array[0], ' '.$andor.' category_id '.$eq.' ');
1536        for ($i = 1; $i < (count($cat_array)); $i = $i + 1) {
1537            $whichcat .= ' '.$andor.' category_id '.$eq.' '.intval($cat_array[$i]);
1538            $whichcat .= get_category_children($cat_array[$i], ' '.$andor.' category_id '.$eq.' ');
1539        }
1540        $whichcat .= ')';
1541        if ($eq == '!=') {
1542            $cat = '-'.$cat; // Put back the knowledge that we are excluding a category.
1543        }
1544    }
1545
1546    // Category stuff for nice URIs
1547
1548    if ('' != $category_name) {
1549        if (stristr($category_name,'/')) {
1550            $category_name = explode('/',$category_name);
1551            if ($category_name[count($category_name)-1]) {
1552                $category_name = $category_name[count($category_name)-1]; // no trailing slash
1553            } else {
1554                $category_name = $category_name[count($category_name)-2]; // there was a trailling slash
1555            }
1556        }
1557        $category_name = preg_replace('|[^a-z0-9-_]|i', '', $category_name);
1558        $tables = ", $wpdb->post2cat, $wpdb->categories";
1559        $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) LEFT JOIN $wpdb->categories ON ($wpdb->post2cat.category_id = $wpdb->categories.cat_ID) ";
1560        $whichcat = " AND (category_nicename = '$category_name'";
1561        $cat = $wpdb->get_var("SELECT cat_ID FROM $wpdb->categories WHERE category_nicename = '$category_name'");
1562        $whichcat .= get_category_children($cat, " OR category_id = ");
1563        $whichcat .= ")";
1564    }
1565
1566    // Author/user stuff
1567
1568    if ((empty($author)) || ($author == 'all') || ($author == '0')) {
1569        $whichauthor='';
1570    } else {
1571        $author = ''.urldecode($author).'';
1572        $author = addslashes_gpc($author);
1573        if (stristr($author, '-')) {
1574            $eq = '!=';
1575            $andor = 'AND';
1576            $author = explode('-', $author);
1577            $author = ''.intval($author[1]);
1578        } else {
1579            $eq = '=';
1580            $andor = 'OR';
1581        }
1582        $author_array = explode(' ', $author);
1583        $whichauthor .= ' AND (post_author '.$eq.' '.intval($author_array[0]);
1584        for ($i = 1; $i < (count($author_array)); $i = $i + 1) {
1585            $whichauthor .= ' '.$andor.' post_author '.$eq.' '.intval($author_array[$i]);
1586        }
1587        $whichauthor .= ')';
1588    }
1589
1590    // Author stuff for nice URIs
1591
1592    if ('' != $author_name) {
1593        if (stristr($author_name,'/')) {
1594            $author_name = explode('/',$author_name);
1595            if ($author_name[count($author_name)-1]) {
1596                $author_name = $author_name[count($author_name)-1];#no trailing slash
1597            } else {
1598                $author_name = $author_name[count($author_name)-2];#there was a trailling slash
1599            }
1600        }
1601        $author_name = preg_replace('|[^a-z0-9-_]|', '', strtolower($author_name));
1602        $author = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$author_name."'");
1603        $whichauthor .= ' AND (post_author = '.intval($author).')';
1604    }
1605
1606    $where .= $search.$whichcat.$whichauthor;
1607
1608    if ((empty($order)) || ((strtoupper($order) != 'ASC') && (strtoupper($order) != 'DESC'))) {
1609        $order='DESC';
1610    }
1611
1612    // Order by
1613    if (empty($orderby)) {
1614        $orderby='date '.$order;
1615    } else {
1616        // Used to filter values
1617        $allowed_keys = array('author','date','category','title');
1618        $orderby = urldecode($orderby);
1619        $orderby = addslashes_gpc($orderby);
1620        $orderby_array = explode(' ',$orderby);
1621        if (!in_array($orderby_array[0],$allowed_keys)) {
1622            $orderby_array[0] = 'date';
1623        }
1624        $orderby = $orderby_array[0].' '.$order;
1625        if (count($orderby_array)>1) {
1626            for ($i = 1; $i < (count($orderby_array)); $i = $i + 1) {
1627                // Only allow certain values for safety
1628                if (in_array($orderby_array[$i],$allowed_keys)) {
1629                    $orderby .= ',post_'.$orderby_array[$i].' '.$order;
1630                }
1631            }
1632        }
1633    }
1634
1635    if ((!$whichcat) && (!$m) && (!$p) && (!$w) && (!$s) && empty($poststart) && empty($postend)) {
1636        if ($what_to_show == 'posts') {
1637            $limits = ' LIMIT '.$posts_per_page;
1638        } elseif ($what_to_show == 'days' && empty($monthnum) && empty($year) && empty($day)) {
1639            $lastpostdate = get_lastpostdate();
1640            $lastpostdate = mysql2date('Y-m-d 00:00:00',$lastpostdate);
1641            $lastpostdate = mysql2date('U',$lastpostdate);
1642            $otherdate = date('Y-m-d H:i:s', ($lastpostdate - (($posts_per_page-1) * 86400)));
1643            $where .= " AND post_date > '$otherdate'";
1644        }
1645    }
1646
1647    if ( !empty($postend) && ($postend > $poststart) && (!$m) && empty($monthnum) && empty($year) && empty($day) &&(!$w) && (!$whichcat) && (!$s) && (!$p)) {
1648        if ($what_to_show == 'posts' || ($what_to_show == 'paged' && (!$paged))) {
1649            $poststart = intval($poststart);
1650            $postend = intval($postend);
1651            $limposts = $postend - $poststart;
1652            $limits = ' LIMIT '.$poststart.','.$limposts;
1653        } elseif ($what_to_show == 'days') {
1654            $poststart = intval($poststart);
1655            $postend = intval($postend);
1656            $limposts = $postend - $poststart;
1657            $lastpostdate = get_lastpostdate();
1658            $lastpostdate = mysql2date('Y-m-d 00:00:00',$lastpostdate);
1659            $lastpostdate = mysql2date('U',$lastpostdate);
1660            $startdate = date('Y-m-d H:i:s', ($lastpostdate - (($poststart -1) * 86400)));
1661            $otherdate = date('Y-m-d H:i:s', ($lastpostdate - (($postend -1) * 86400)));
1662            $where .= " AND post_date > '$otherdate' AND post_date < '$startdate'";
1663        }
1664    } else {
1665        if (($what_to_show == 'paged') && (!$p) && (!$more)) {
1666            if ($pagenow != 'post.php') {
1667                $pgstrt = '';
1668                if ($paged) {
1669                    $pgstrt = (intval($paged) -1) * $posts_per_page . ', ';
1670                }
1671                $limits = 'LIMIT '.$pgstrt.$posts_per_page;
1672            } else {
1673                if (($m) || ($p) || ($w) || ($s) || ($whichcat)) {
1674                    $limits = '';
1675                } else {
1676                    $pgstrt = '';
1677                    if ($paged) {
1678                        $pgstrt = (intval($paged) -1) * $posts_per_page . ', ';
1679                    }
1680                    $limits = 'LIMIT '.$pgstrt.$posts_per_page;
1681                }
1682            }
1683        }
1684        elseif (($m) || ($p) || ($w) || ($s) || ($whichcat) || ($author) || $monthnum || $year || $day) {
1685            $limits = '';
1686        }
1687    }
1688
1689    if ($p == 'all') {
1690        $where = '';
1691    }
1692
1693    $now = gmdate('Y-m-d H:i:59');
1694
1695    if ($pagenow != 'post.php' && $pagenow != 'edit.php') {
1696        if ((empty($poststart)) || (empty($postend)) || !($postend > $poststart)) {
1697            $where .= " AND post_date_gmt <= '$now'";
1698        }
1699
1700        $distinct = 'DISTINCT';
1701    }
1702    $where .= ' AND (post_status = "publish"';
1703
1704    // Get private posts
1705    if (isset($user_ID) && ('' != intval($user_ID)))
1706        $where .= " OR post_author = $user_ID AND post_status != 'draft')";
1707    else
1708        $where .= ')';
1709    $where .= " GROUP BY $wpdb->posts.ID";
1710    $request = " SELECT $distinct * FROM $wpdb->posts $join WHERE 1=1".$where." ORDER BY post_$orderby $limits";
1711
1712
1713    if ($preview) {
1714        $request = 'SELECT 1-1'; // dummy mysql query for the preview
1715        // little funky fix for IEwin, rawk on that code
1716        $is_winIE = ((preg_match('/MSIE/',$HTTP_USER_AGENT)) && (preg_match('/Win/',$HTTP_USER_AGENT)));
1717        if (($is_winIE) && (!isset($IEWin_bookmarklet_fix))) {
1718            $preview_content =  preg_replace('/\%u([0-9A-F]{4,4})/e',  "'&#'.base_convert('\\1',16,10).';'", $preview_content);
1719        }
1720    }
1721
1722    // error_log("$request");
1723    // echo $request;
1724    return $wpdb->get_results($request);
1725}
1726
1727function update_post_caches($posts) {
1728    global $category_cache, $comment_count_cache, $post_meta_cache;
1729    global $wpdb;
1730
1731    // No point in doing all this work if we didn't match any posts.
1732    if (! $posts) {
1733        return;
1734    }
1735
1736    // Get the categories for all the posts
1737    foreach ($posts as $post) {
1738        $post_id_list[] = $post->ID;
1739    }
1740    $post_id_list = implode(',', $post_id_list);
1741
1742    $dogs = $wpdb->get_results("SELECT DISTINCT
1743        ID, category_id, cat_name, category_nicename, category_description, category_parent
1744        FROM $wpdb->categories, $wpdb->post2cat, $wpdb->posts
1745        WHERE category_id = cat_ID AND post_id = ID AND post_id IN ($post_id_list)");
1746       
1747    foreach ($dogs as $catt) {
1748        $category_cache[$catt->ID][] = $catt;
1749    }
1750
1751    // Do the same for comment numbers
1752    $comment_counts = $wpdb->get_results("SELECT ID, COUNT( comment_ID ) AS ccount
1753        FROM $wpdb->posts
1754        LEFT JOIN $wpdb->comments ON ( comment_post_ID = ID  AND comment_approved =  '1')
1755        WHERE post_status =  'publish' AND ID IN ($post_id_list)
1756        GROUP BY ID");
1757   
1758    if ($comment_counts) {
1759        foreach ($comment_counts as $comment_count) {
1760            $comment_count_cache["$comment_count->ID"] = $comment_count->ccount;
1761        }
1762    }
1763
1764    // Get post-meta info
1765    if ( $meta_list = $wpdb->get_results("
1766                        SELECT post_id,meta_key,meta_value
1767                        FROM $wpdb->postmeta 
1768                        WHERE post_id IN($post_id_list)
1769                        ORDER BY post_id,meta_key
1770                ", ARRAY_A) ) {
1771               
1772        // Change from flat structure to hierarchical:
1773        $post_meta_cache = array();
1774        foreach ($meta_list as $metarow) {
1775            $mpid = $metarow['post_id'];
1776            $mkey = $metarow['meta_key'];
1777            $mval = $metarow['meta_value'];
1778                       
1779            // Force subkeys to be array type:
1780            if (!isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]))
1781                $post_meta_cache[$mpid] = array();
1782            if (!isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]))
1783                $post_meta_cache[$mpid]["$mkey"] = array();
1784                       
1785            // Add a value to the current pid/key:
1786            $post_meta_cache[$mpid][$mkey][] = $mval;
1787        }
1788    }
1789}
1790
1791function update_category_cache() {
1792    global $cache_categories, $wpdb;
1793    $dogs = $wpdb->get_results("SELECT * FROM $wpdb->categories WHERE 1=1");
1794    foreach ($dogs as $catt) {
1795        $cache_categories[$catt->cat_ID] = $catt;
1796    }
1797}
1798
1799function update_user_cache() {
1800    global $cache_userdata, $wpdb;
1801
1802    $users = $wpdb->get_results("SELECT * FROM $wpdb->users WHERE user_level > 0");
1803    foreach ($users as $user) {
1804        $cache_userdata[$user->ID] = $user;
1805    }
1806}
1807
1808function wp_head() {
1809        do_action('wp_head', '');
1810}
1811
1812?>
Note: See TracBrowser for help on using the repository browser.