Make WordPress Core

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

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

404 permalink handler.

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