Make WordPress Core

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

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

Return post ID from generic_ping(). Bug 229.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 53.4 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        return $post_id;
535}
536
537add_action('publish_post', 'generic_ping');
538
539// Send a Trackback
540function trackback($trackback_url, $title, $excerpt, $ID) {
541        global $wpdb;
542        $title = urlencode($title);
543        $excerpt = urlencode($excerpt);
544        $blog_name = urlencode(get_settings('blogname'));
545        $tb_url = $trackback_url;
546        $url = urlencode(get_permalink($ID));
547        $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
548        $trackback_url = parse_url($trackback_url);
549        $http_request  = 'POST ' . $trackback_url['path'] . ($trackback_url['query'] ? '?'.$trackback_url['query'] : '') . " HTTP/1.0\r\n";
550        $http_request .= 'Host: '.$trackback_url['host']."\r\n";
551        $http_request .= 'Content-Type: application/x-www-form-urlencoded; charset='.get_settings('blog_charset')."\r\n";
552        $http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
553        $http_request .= "\r\n";
554        $http_request .= $query_string;
555        $fs = @fsockopen($trackback_url['host'], 80);
556        @fputs($fs, $http_request);
557/*
558        $debug_file = 'trackback.log';
559        $fp = fopen($debug_file, 'a');
560        fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
561        while(!@feof($fs)) {
562                fwrite($fp, @fgets($fs, 4096));
563        }
564        fwrite($fp, "\n\n");
565        fclose($fp);
566*/
567        @fclose($fs);
568
569        $wpdb->query("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
570        $wpdb->query("UPDATE $wpdb->posts SET to_ping = REPLACE(to_ping, '$tb_url', '') WHERE ID = '$ID'");
571        return $result;
572}
573
574// trackback - reply
575function trackback_response($error = 0, $error_message = '') {
576        if ($error) {
577                echo '<?xml version="1.0" encoding="utf-8"?'.">\n";
578                echo "<response>\n";
579                echo "<error>1</error>\n";
580                echo "<message>$error_message</message>\n";
581                echo "</response>";
582        } else {
583                echo '<?xml version="1.0" encoding="utf-8"?'.">\n";
584                echo "<response>\n";
585                echo "<error>0</error>\n";
586                echo "</response>";
587        }
588        die();
589}
590
591function make_url_footnote($content) {
592        preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
593        $j = 0;
594        for ($i=0; $i<count($matches[0]); $i++) {
595                $links_summary = (!$j) ? "\n" : $links_summary;
596                $j++;
597                $link_match = $matches[0][$i];
598                $link_number = '['.($i+1).']';
599                $link_url = $matches[2][$i];
600                $link_text = $matches[4][$i];
601                $content = str_replace($link_match, $link_text.' '.$link_number, $content);
602                $link_url = (strtolower(substr($link_url,0,7)) != 'http://') ? get_settings('home') . $link_url : $link_url;
603                $links_summary .= "\n".$link_number.' '.$link_url;
604        }
605        $content = strip_tags($content);
606        $content .= $links_summary;
607        return $content;
608}
609
610
611function xmlrpc_getposttitle($content) {
612        global $post_default_title;
613        if (preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle)) {
614                $post_title = $matchtitle[0];
615                $post_title = preg_replace('/<title>/si', '', $post_title);
616                $post_title = preg_replace('/<\/title>/si', '', $post_title);
617        } else {
618                $post_title = $post_default_title;
619        }
620        return $post_title;
621}
622       
623function xmlrpc_getpostcategory($content) {
624        global $post_default_category;
625        if (preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat)) {
626                $post_category = trim($matchcat[1], ',');
627                $post_category = explode(',', $post_category);
628        } else {
629                $post_category = $post_default_category;
630        }
631        return $post_category;
632}
633
634function xmlrpc_removepostdata($content) {
635        $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content);
636        $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content);
637        $content = trim($content);
638        return $content;
639}
640
641function debug_fopen($filename, $mode) {
642        global $debug;
643        if ($debug == 1) {
644                $fp = fopen($filename, $mode);
645                return $fp;
646        } else {
647                return false;
648        }
649}
650
651function debug_fwrite($fp, $string) {
652        global $debug;
653        if ($debug == 1) {
654                fwrite($fp, $string);
655        }
656}
657
658function debug_fclose($fp) {
659        global $debug;
660        if ($debug == 1) {
661                fclose($fp);
662        }
663}
664
665function pingback($content, $post_ID) {
666include_once (ABSPATH . WPINC . '/class-xmlrpc.php');
667include_once (ABSPATH . WPINC . '/class-xmlrpcs.php');
668        // original code by Mort (http://mort.mine.nu:8080)
669        global $wp_version;
670        $log = debug_fopen('./pingback.log', 'a');
671        $post_links = array();
672        debug_fwrite($log, 'BEGIN '.time()."\n");
673
674        // Variables
675        $ltrs = '\w';
676        $gunk = '/#~:.?+=&%@!\-';
677        $punc = '.:?\-';
678        $any = $ltrs.$gunk.$punc;
679        $pingback_str_dquote = 'rel="pingback"';
680        $pingback_str_squote = 'rel=\'pingback\'';
681        $x_pingback_str = 'x-pingback: ';
682        $pingback_href_original_pos = 27;
683
684        // Step 1
685        // Parsing the post, external links (if any) are stored in the $post_links array
686        // This regexp comes straight from phpfreaks.com
687        // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
688        preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
689
690        // Debug
691        debug_fwrite($log, 'Post contents:');
692        debug_fwrite($log, $content."\n");
693       
694        // Step 2.
695        // Walking thru the links array
696        // first we get rid of links pointing to sites, not to specific files
697        // Example:
698        // http://dummy-weblog.org
699        // http://dummy-weblog.org/
700        // http://dummy-weblog.org/post.php
701        // We don't wanna ping first and second types, even if they have a valid <link/>
702
703        foreach($post_links_temp[0] as $link_test){
704                $test = parse_url($link_test);
705                if (isset($test['query'])) {
706                        $post_links[] = $link_test;
707                } elseif(($test['path'] != '/') && ($test['path'] != '')) {
708                        $post_links[] = $link_test;
709                }
710        }
711
712        foreach ($post_links as $pagelinkedto){
713                debug_fwrite($log, 'Processing -- '.$pagelinkedto."\n\n");
714
715                $bits = parse_url($pagelinkedto);
716                if (!isset($bits['host'])) {
717                        debug_fwrite($log, 'Couldn\'t find a hostname for '.$pagelinkedto."\n\n");
718                        continue;
719                }
720                $host = $bits['host'];
721                $path = isset($bits['path']) ? $bits['path'] : '';
722                if (isset($bits['query'])) {
723                        $path .= '?'.$bits['query'];
724                }
725                if (!$path) {
726                        $path = '/';
727                }
728                $port = isset($bits['port']) ? $bits['port'] : 80;
729
730                // Try to connect to the server at $host
731                $fp = fsockopen($host, $port, $errno, $errstr, 30);
732                if (!$fp) {
733                        debug_fwrite($log, 'Couldn\'t open a connection to '.$host."\n\n");
734                        continue;
735                }
736
737                // Send the GET request
738                $request = "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: WordPress/$wp_version PHP/" . phpversion() . "\r\n\r\n";
739                ob_end_flush();
740                fputs($fp, $request);
741
742                // Start receiving headers and content
743                $contents = '';
744                $headers = '';
745                $gettingHeaders = true;
746                $found_pingback_server = 0;
747                while (!feof($fp)) {
748                        $line = fgets($fp, 4096);
749                        if (trim($line) == '') {
750                                $gettingHeaders = false;
751                        }
752                        if (!$gettingHeaders) {
753                                $contents .= trim($line)."\n";
754                                $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
755                                $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
756                        } else {
757                                $headers .= trim($line)."\n";
758                                $x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str);
759                        }
760                        if ($x_pingback_header_offset) {
761                                preg_match('#x-pingback: (.+)#is', $headers, $matches);
762                                $pingback_server_url = trim($matches[1]);
763                                debug_fwrite($log, "Pingback server found from X-Pingback header @ $pingback_server_url\n");
764                                $found_pingback_server = 1;
765                                break;
766                        }
767                        if ($pingback_link_offset_dquote || $pingback_link_offset_squote) {
768                                $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
769                                $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
770                                $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
771                                $pingback_href_start = $pingback_href_pos+6;
772                                $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
773                                $pingback_server_url_len = $pingback_href_end-$pingback_href_start;
774                                $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
775                                debug_fwrite($log, "Pingback server found from Pingback <link /> tag @ $pingback_server_url\n");
776                                $found_pingback_server = 1;
777                                break;
778                        }
779                }
780
781                if (!$found_pingback_server) {
782                        debug_fwrite($log, "Pingback server not found\n\n*************************\n\n");
783                        @fclose($fp);
784                } else {
785                        debug_fwrite($log,"\n\nPingback server data\n");
786
787                        // Assuming there's a "http://" bit, let's get rid of it
788                        $host_clear = substr($pingback_server_url, 7);
789
790                        //  the trailing slash marks the end of the server name
791                        $host_end = strpos($host_clear, '/');
792
793                        // Another clear cut
794                        $host_len = $host_end-$host_start;
795                        $host = substr($host_clear, 0, $host_len);
796                        debug_fwrite($log, 'host: '.$host."\n");
797
798                        // If we got the server name right, the rest of the string is the server path
799                        $path = substr($host_clear,$host_end);
800                        debug_fwrite($log, 'path: '.$path."\n\n");
801
802                         // Now, the RPC call
803                        $method = 'pingback.ping';
804                        debug_fwrite($log, 'Page Linked To: '.$pagelinkedto."\n");
805                        debug_fwrite($log, 'Page Linked From: ');
806                        $pagelinkedfrom = get_permalink($post_ID);
807                        debug_fwrite($log, $pagelinkedfrom."\n");
808
809                        $client = new xmlrpc_client($path, $host, 80);
810                        $message = new xmlrpcmsg($method, array(new xmlrpcval($pagelinkedfrom), new xmlrpcval($pagelinkedto)));
811                        $result = $client->send($message);
812                        if ($result){
813                                if (!$result->value()){
814                                        debug_fwrite($log, $result->faultCode().' -- '.$result->faultString());
815                                } else {
816                                        $value = phpxmlrpc_decode($result->value());
817                                        if (is_array($value)) {
818                                                $value_arr = '';
819                                                foreach($value as $blah) {
820                                                        $value_arr .= $blah.' |||| ';
821                                                }
822                                                debug_fwrite($log, $value_arr);
823                                        } else {
824                                                debug_fwrite($log, $value);
825                                        }
826                                }
827                        }
828                        @fclose($fp);
829                }
830        }
831
832        debug_fwrite($log, "\nEND: ".time()."\n****************************\n\r");
833        debug_fclose($log);
834}
835
836function doGeoUrlHeader($post_list = '') {
837    global $posts;
838
839  if (get_settings('use_geo_positions')) {
840                if ($posts && 1 === count($posts) && ! empty($posts[0]->post_lat)) {
841                        // there's only one result  see if it has a geo code
842                        $row = $posts[0];
843                        $lat = $row->post_lat;
844                        $lon = $row->post_lon;
845                        $title = $row->post_title;
846                        if(($lon != null) && ($lat != null) ) {
847                                echo "<meta name=\"ICBM\" content=\"".$lat.", ".$lon."\" />\n";
848                                echo "<meta name=\"DC.title\" content=\"".convert_chars(strip_tags(htmlspecialchars(get_bloginfo("name"))))." - ".$title."\" />\n";
849                                echo "<meta name=\"geo.position\" content=\"".$lat.";".$lon."\" />\n";
850                                return;
851                        }
852                } else {
853                        if(get_settings('use_default_geourl')) {
854                                // send the default here
855                                echo "<meta name='ICBM' content=\"". get_settings('default_geourl_lat') .", ". get_settings('default_geourl_lon') ."\" />\n";
856                                echo "<meta name='DC.title' content=\"".convert_chars(strip_tags(htmlspecialchars(get_bloginfo("name"))))."\" />\n";
857                                echo "<meta name='geo.position' content=\"". get_settings('default_geourl_lat') .";". get_settings('default_geourl_lon') ."\" />\n";
858                        }
859                }
860        }
861}
862
863function getRemoteFile($host,$path) {
864    $fp = fsockopen($host, 80, $errno, $errstr);
865    if ($fp) {
866        fputs($fp,"GET $path HTTP/1.0\r\nHost: $host\r\n\r\n");
867        while ($line = fgets($fp, 4096)) {
868            $lines[] = $line;
869        }
870        fclose($fp);
871        return $lines;
872    } else {
873        return false;
874    }
875}
876
877function pingGeoURL($blog_ID) {
878
879    $ourUrl = get_settings('home') ."/index.php?p=".$blog_ID;
880    $host="geourl.org";
881    $path="/ping/?p=".$ourUrl;
882    getRemoteFile($host,$path); 
883}
884
885/* wp_set_comment_status:
886   part of otaku42's comment moderation hack
887   changes the status of a comment according to $comment_status.
888   allowed values:
889   hold   : set comment_approve field to 0
890   approve: set comment_approve field to 1
891   delete : remove comment out of database
892   
893   returns true if change could be applied
894   returns false on database error or invalid value for $comment_status
895 */
896function wp_set_comment_status($comment_id, $comment_status) {
897    global $wpdb;
898
899    switch($comment_status) {
900                case 'hold':
901                        $query = "UPDATE $wpdb->comments SET comment_approved='0' WHERE comment_ID='$comment_id' LIMIT 1";
902                break;
903                case 'approve':
904                        $query = "UPDATE $wpdb->comments SET comment_approved='1' WHERE comment_ID='$comment_id' LIMIT 1";
905                break;
906                case 'delete':
907                        $query = "DELETE FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1";
908                break;
909                default:
910                        return false;
911    }
912   
913    if ($wpdb->query($query)) {
914                do_action('wp_set_comment_status', $comment_id);
915                return true;
916    } else {
917                return false;
918    }
919}
920
921
922/* wp_get_comment_status
923   part of otaku42's comment moderation hack
924   gets the current status of a comment
925
926   returned values:
927   "approved"  : comment has been approved
928   "unapproved": comment has not been approved
929   "deleted   ": comment not found in database
930
931   a (boolean) false signals an error
932 */
933function wp_get_comment_status($comment_id) {
934    global $wpdb;
935   
936    $result = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1");
937    if ($result == NULL) {
938        return "deleted";
939    } else if ($result == "1") {
940        return "approved";
941    } else if ($result == "0") {
942        return "unapproved";
943    } else {
944        return false;
945    }
946}
947
948function wp_notify_postauthor($comment_id, $comment_type='comment') {
949    global $wpdb;
950    global $querystring_start, $querystring_equal, $querystring_separator;
951   
952    $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1");
953    $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID='$comment->comment_post_ID' LIMIT 1");
954    $user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE ID='$post->post_author' LIMIT 1");
955
956    if ('' == $user->user_email) return false; // If there's no email to send the comment to
957
958        $comment_author_domain = gethostbyaddr($comment->comment_author_IP);
959
960        $blogname = get_settings('blogname');
961       
962        if ('comment' == $comment_type) {
963                $notify_message  = "New comment on your post #$comment->comment_post_ID \"".$post->post_title."\"\r\n\r\n";
964                $notify_message .= "Author : $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
965                $notify_message .= "E-mail : $comment->comment_author_email\r\n";
966                $notify_message .= "URI    : $comment->comment_author_url\r\n";
967                $notify_message .= "Whois  : http://ws.arin.net/cgi-bin/whois.pl?queryinput=$comment->comment_author_IP\r\n";
968                $notify_message .= "Comment:\r\n".$comment->comment_content."\r\n\r\n";
969                $notify_message .= "You can see all comments on this post here: \r\n";
970                $subject = '[' . $blogname . '] Comment: "' .$post->post_title.'"';
971        } elseif ('trackback' == $comment_type) {
972                $notify_message  = "New trackback on your post #$comment_post_ID \"".$post->post_title."\"\r\n\r\n";
973                $notify_message .= "Website: $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
974                $notify_message .= "URI    : $comment->comment_author_url\r\n";
975                $notify_message .= "Excerpt: \n".$comment->comment_content."\r\n\r\n";
976                $notify_message .= "You can see all trackbacks on this post here: \r\n";
977                $subject = '[' . $blogname . '] Trackback: "' .$post->post_title.'"';
978        } elseif ('pingback' == $comment_type) {
979                $notify_message  = "New pingback on your post #$comment_post_ID \"".$post->post_title."\"\r\n\r\n";
980                $notify_message .= "Website: $comment->comment_author\r\n";
981                $notify_message .= "URI    : $comment->comment_author_url\r\n";
982                $notify_message .= "Excerpt: \n[...] $original_context [...]\r\n\r\n";
983                $notify_message .= "You can see all pingbacks on this post here: \r\n";
984                $subject = '[' . $blogname . '] Pingback: "' .$post->post_title.'"';
985        }
986        $notify_message .= get_permalink($comment->comment_post_ID) . '#comments';
987
988        if ('' == $comment->comment_author_email || '' == $comment->comment_author) {
989                $from = "From: \"$blogname\" <wordpress@" . $_SERVER['SERVER_NAME'] . '>';
990        } else {
991                $from = 'From: "' . $comment->comment_author . "\" <$comment->comment_author_email>";
992        }
993
994        $message_headers = "MIME-Version: 1.0\r\n"
995                . "$from\r\n"
996                . "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\r\n";
997
998        @mail($user->user_email, $subject, $notify_message, $message_headers);
999   
1000    return true;
1001}
1002
1003/* wp_notify_moderator
1004   notifies the moderator of the blog (usually the admin)
1005   about a new comment that waits for approval
1006   always returns true
1007 */
1008function wp_notify_moderator($comment_id) {
1009    global $wpdb;
1010    global $querystring_start, $querystring_equal, $querystring_separator;
1011   
1012    $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1");
1013    $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID='$comment->comment_post_ID' LIMIT 1");
1014    $user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE ID='$post->post_author' LIMIT 1");
1015
1016    $comment_author_domain = gethostbyaddr($comment->comment_author_IP);
1017    $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
1018
1019    $notify_message  = "A new comment on the post #$comment->comment_post_ID \"".$post->post_title."\" is waiting for your approval\r\n\r\n";
1020    $notify_message .= "Author : $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
1021    $notify_message .= "E-mail : $comment->comment_author_email\r\n";
1022    $notify_message .= "URL    : $comment->comment_author_url\r\n";
1023    $notify_message .= "Whois  : http://ws.arin.net/cgi-bin/whois.pl?queryinput=$comment->comment_author_IP\r\n";
1024    $notify_message .= "Comment:\r\n".$comment->comment_content."\r\n\r\n";
1025    $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";
1026    $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";
1027    $notify_message .= "Currently $comments_waiting comments are waiting for approval. Please visit the moderation panel:\r\n";
1028    $notify_message .= get_settings('siteurl') . "/wp-admin/moderation.php\r\n";
1029
1030    $subject = '[' . get_settings('blogname') . '] Please approve: "' .$post->post_title.'"';
1031    $admin_email = get_settings("admin_email");
1032    $from  = "From: $admin_email";
1033
1034    $message_headers = "MIME-Version: 1.0\r\n"
1035        . "$from\r\n"
1036        . "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\r\n";
1037
1038    @mail($admin_email, $subject, $notify_message, $message_headers);
1039   
1040    return true;
1041}
1042
1043
1044function start_wp($use_wp_query = false) {
1045  global $post, $id, $postdata, $authordata, $day, $preview, $page, $pages, $multipage, $more, $numpages, $wp_query;
1046        global $pagenow;
1047
1048        if ($use_wp_query) {
1049          $post = $wp_query->next_post();
1050        } else {
1051          $wp_query->next_post();
1052        }
1053
1054        if (!$preview) {
1055                $id = $post->ID;
1056        } else {
1057                $id = 0;
1058                $postdata = array (
1059                        'ID' => 0,
1060                        'Author_ID' => $_GET['preview_userid'],
1061                        'Date' => $_GET['preview_date'],
1062                        'Content' => $_GET['preview_content'],
1063                        'Excerpt' => $_GET['preview_excerpt'],
1064                        'Title' => $_GET['preview_title'],
1065                        'Category' => $_GET['preview_category'],
1066                        'Notify' => 1
1067                        );
1068        }
1069        $authordata = get_userdata($post->post_author);
1070
1071        $day = mysql2date('d.m.y', $post->post_date);
1072        $currentmonth = mysql2date('m', $post->post_date);
1073        $numpages = 1;
1074        if (!$page)
1075                $page = 1;
1076        if (isset($p))
1077                $more = 1;
1078        $content = $post->post_content;
1079        if (preg_match('/<!--nextpage-->/', $post->post_content)) {
1080                if ($page > 1)
1081                        $more = 1;
1082                $multipage = 1;
1083                $content = $post->post_content;
1084                $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
1085                $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
1086                $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
1087                $pages = explode('<!--nextpage-->', $content);
1088                $numpages = count($pages);
1089        } else {
1090                $pages[0] = $post->post_content;
1091                $multipage = 0;
1092        }
1093        return true;
1094}
1095
1096function is_new_day() {
1097        global $day, $previousday;
1098        if ($day != $previousday) {
1099                return(1);
1100        } else {
1101                return(0);
1102        }
1103}
1104
1105// Filters: these are the core of WP's plugin architecture
1106
1107function apply_filters($tag, $string) {
1108        global $wp_filter;
1109        if (isset($wp_filter['all'])) {
1110                foreach ($wp_filter['all'] as $priority => $functions) {
1111                        if (isset($wp_filter[$tag][$priority]))
1112                                $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
1113                        else
1114                                $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
1115                        $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
1116                }
1117
1118        }
1119       
1120        if (isset($wp_filter[$tag])) {
1121                ksort($wp_filter[$tag]);
1122                foreach ($wp_filter[$tag] as $priority => $functions) {
1123                        if (!is_null($functions)) {
1124                foreach($functions as $function) {
1125                                        $string = $function($string);
1126                }
1127            }
1128                }
1129        }
1130        return $string;
1131}
1132
1133function add_filter($tag, $function_to_add, $priority = 10) {
1134        global $wp_filter;
1135        // So the format is wp_filter['tag']['array of priorities']['array of functions']
1136        if (!@in_array($function_to_add, $wp_filter[$tag]["$priority"])) {
1137                $wp_filter[$tag]["$priority"][] = $function_to_add;
1138        }
1139        return true;
1140}
1141
1142function remove_filter($tag, $function_to_remove, $priority = 10) {
1143        global $wp_filter;
1144        if (@in_array($function_to_remove, $wp_filter[$tag]["$priority"])) {
1145                foreach ($wp_filter[$tag]["$priority"] as $function) {
1146                        if ($function_to_remove != $function) {
1147                                $new_function_list[] = $function;
1148                        }
1149                }
1150                $wp_filter[$tag]["$priority"] = $new_function_list;
1151        }
1152        //die(var_dump($wp_filter));
1153        return true;
1154}
1155
1156// The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
1157
1158function do_action($tag, $string) {
1159        return apply_filters($tag, $string);
1160}
1161
1162function add_action($tag, $function_to_add, $priority = 10) {
1163        add_filter($tag, $function_to_add, $priority);
1164}
1165
1166function remove_action($tag, $function_to_remove, $priority = 10) {
1167        remove_filter($tag, $function_to_remove, $priority);
1168}
1169
1170function using_mod_rewrite($permalink_structure = '') {
1171    if (empty($permalink_structure)) {
1172        $permalink_structure = get_settings('permalink_structure');
1173       
1174        if (empty($permalink_structure)) {
1175            return false;
1176        }
1177    }
1178
1179    // If the index is not in the permalink, we're using mod_rewrite.
1180    if (! preg_match('#^/*' . get_settings('blogfilename') . '#', $permalink_structure)) {
1181      return true;
1182    }
1183   
1184    return false;
1185}
1186
1187function preg_index($number, $matches = '') {
1188    $match_prefix = '$';
1189    $match_suffix = '';
1190   
1191    if (! empty($matches)) {
1192        $match_prefix = '$' . $matches . '['; 
1193        $match_suffix = ']';
1194    }       
1195   
1196    return "$match_prefix$number$match_suffix";       
1197}
1198
1199
1200function page_permastruct() {
1201    $permalink_structure = get_settings('permalink_structure');
1202       
1203    if (empty($permalink_structure)) {
1204        return '';
1205    }
1206
1207    $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));   
1208    $index = get_settings('blogfilename');
1209    $prefix = '';
1210    if (preg_match('#^/*' . $index . '#', $front)) {
1211        $prefix = $index . '/';
1212    }
1213
1214    return '/' . $prefix . 'site/%pagename%';   
1215}
1216
1217function generate_rewrite_rules($permalink_structure = '', $matches = '') {
1218    $rewritecode = 
1219        array(
1220        '%year%',
1221        '%monthnum%',
1222        '%day%',
1223        '%hour%',
1224        '%minute%',
1225        '%second%',
1226        '%postname%',
1227        '%post_id%',
1228        '%category%',
1229        '%author%',
1230        '%pagename%',
1231        '%search%'
1232        );
1233
1234    $rewritereplace = 
1235        array(
1236        '([0-9]{4})',
1237        '([0-9]{1,2})',
1238        '([0-9]{1,2})',
1239        '([0-9]{1,2})',
1240        '([0-9]{1,2})',
1241        '([0-9]{1,2})',
1242        '([^/]+)',
1243        '([0-9]+)',
1244        '(.+?)',
1245        '([^/]+)',
1246        '([^/]+)',
1247        '(.+)'
1248        );
1249
1250    $queryreplace = 
1251        array (
1252        'year=',
1253        'monthnum=',
1254        'day=',
1255        'hour=',
1256        'minute=',
1257        'second=',
1258        'name=',
1259        'p=',
1260        'category_name=',
1261        'author_name=',
1262        'pagename=',
1263        's='
1264        );
1265
1266    $feedregex = '(feed|rdf|rss|rss2|atom)/?$';
1267    $trackbackregex = 'trackback/?$';
1268    $pageregex = 'page/?([0-9]{1,})/?$';
1269
1270    $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));   
1271    preg_match_all('/%.+?%/', $permalink_structure, $tokens);
1272
1273    $num_tokens = count($tokens[0]);
1274
1275    $index = get_settings('blogfilename');;
1276    $feedindex = $index;
1277    $trackbackindex = $index;
1278    for ($i = 0; $i < $num_tokens; ++$i) {
1279             if (0 < $i) {
1280                 $queries[$i] = $queries[$i - 1] . '&';
1281             }
1282             
1283             $query_token = str_replace($rewritecode, $queryreplace, $tokens[0][$i]) . preg_index($i+1, $matches);
1284             $queries[$i] .= $query_token;
1285             }
1286
1287    $structure = $permalink_structure;
1288    if ($front != '/') {
1289        $structure = str_replace($front, '', $structure);
1290    }
1291    $structure = trim($structure, '/');
1292    $dirs = explode('/', $structure);
1293    $num_dirs = count($dirs);
1294
1295    $front = preg_replace('|^/+|', '', $front);
1296
1297    $post_rewrite = array();
1298    $struct = $front;
1299    for ($j = 0; $j < $num_dirs; ++$j) {
1300        $struct .= $dirs[$j] . '/';
1301        $match = str_replace($rewritecode, $rewritereplace, $struct);
1302        $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
1303        $query = $queries[$num_toks - 1];
1304
1305        $pagematch = $match . $pageregex;
1306        $pagequery = $index . '?' . $query . '&paged=' . preg_index($num_toks + 1, $matches);
1307
1308        $feedmatch = $match . $feedregex;
1309        $feedquery = $feedindex . '?' . $query . '&feed=' . preg_index($num_toks + 1, $matches);
1310
1311        $post = 0;
1312        if (strstr($struct, '%postname%') || strstr($struct, '%post_id%')
1313            || (strstr($struct, '%year%') &&  strstr($struct, '%monthnum%') && strstr($struct, '%day%') && strstr($struct, '%hour%') && strstr($struct, '%minute') && strstr($struct, '%second%'))) {
1314                $post = 1;
1315                $trackbackmatch = $match . $trackbackregex;
1316                $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
1317                $match = $match . '?([0-9]+)?/?$';
1318                $query = $index . '?' . $query . '&page=' . preg_index($num_toks + 1, $matches);
1319        } else {
1320            $match .= '?$';
1321            $query = $index . '?' . $query;
1322        }
1323       
1324        $post_rewrite = array($feedmatch => $feedquery, $pagematch => $pagequery, $match => $query) + $post_rewrite;
1325
1326        if ($post) {
1327            $post_rewrite = array($trackbackmatch => $trackbackquery) + $post_rewrite;
1328        }
1329    }
1330
1331    return $post_rewrite;
1332}
1333
1334/* rewrite_rules
1335 * Construct rewrite matches and queries from permalink structure.
1336 * matches - The name of the match array to use in the query strings.
1337 *           If empty, $1, $2, $3, etc. are used.
1338 * Returns an associate array of matches and queries.
1339 */
1340function rewrite_rules($matches = '', $permalink_structure = '') {
1341    $rewrite = array();
1342
1343    if (empty($permalink_structure)) {
1344        $permalink_structure = get_settings('permalink_structure');
1345       
1346        if (empty($permalink_structure)) {
1347            return $rewrite;
1348        }
1349    }
1350
1351    $post_rewrite = generate_rewrite_rules($permalink_structure, $matches);
1352
1353    $feedregex = '(feed|rdf|rss|rss2|atom)/?$';
1354    $pageregex = 'page/?([0-9]{1,})/?$';
1355    $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));   
1356    $index = get_settings('blogfilename');
1357    $prefix = '';
1358    if (! using_mod_rewrite($permalink_structure)) {
1359        $prefix = $index . '/';
1360    }
1361
1362    // If the permalink does not have year, month, and day, we need to create a
1363    // separate archive rule.
1364    $doarchive = false;
1365    if (! (strstr($permalink_structure, '%year%') && strstr($permalink_structure, '%monthnum%') && strstr($permalink_structure, '%day%')) ||
1366        preg_match('/%category%.*(%year%|%monthnum%|%day%)/', $permalink_structure)) {
1367        $doarchive = true;
1368        $archive_structure = $front . '%year%/%monthnum%/%day%/';
1369        $archive_rewrite =  generate_rewrite_rules($archive_structure, $matches);
1370    }
1371
1372    // Site feed
1373    $sitefeedmatch = $prefix . 'feed/?([_0-9a-z-]+)?/?$';
1374    $sitefeedquery = 'index.php?feed=_' . preg_index(1, $matches);
1375
1376    // Site comment feed
1377    $sitecommentfeedmatch = $prefix . 'comments/feed/?([_0-9a-z-]+)?/?$';
1378    $sitecommentfeedquery = 'index.php?feed=_' . preg_index(1, $matches) . '&withcomments=1';
1379
1380    // Site page
1381    $sitepagematch = $prefix . $pageregex;
1382    $sitepagequery = 'index.php?paged=' . preg_index(1, $matches);
1383
1384    $site_rewrite = array(
1385                     $sitefeedmatch => $sitefeedquery,
1386                     $sitecommentfeedmatch => $sitecommentfeedquery,
1387                     $sitepagematch => $sitepagequery,
1388                     );
1389
1390    // Search
1391    $search_structure = $prefix . "search/%search%";
1392    $search_rewrite = generate_rewrite_rules($search_structure, $matches);
1393
1394    // Categories
1395        if ( '' == get_settings('category_base') )
1396                $category_structure = $front . 'category/';
1397        else
1398            $category_structure = get_settings('category_base') . '/';
1399
1400    $category_structure = $category_structure . '%category%';
1401    $category_rewrite = generate_rewrite_rules($category_structure, $matches);
1402
1403    // Authors
1404    $author_structure = $front . 'author/%author%';
1405    $author_rewrite = generate_rewrite_rules($author_structure, $matches);
1406
1407    // Site static pages
1408    $page_structure = $prefix . 'site/%pagename%';
1409    $page_rewrite = generate_rewrite_rules($page_structure, $matches);
1410
1411    // Put them together.
1412    $rewrite = $site_rewrite + $page_rewrite + $search_rewrite + $category_rewrite + $author_rewrite;
1413
1414    // Add on archive rewrite rules if needed.
1415    if ($doarchive) {
1416        $rewrite = $rewrite + $archive_rewrite;
1417    }
1418
1419    $rewrite = $rewrite + $post_rewrite;
1420
1421    $rewrite = apply_filters('rewrite_rules_array', $rewrite);
1422    return $rewrite;
1423}
1424
1425function mod_rewrite_rules ($permalink_structure) {
1426    $site_root = str_replace('http://', '', trim(get_settings('siteurl')));
1427    $site_root = preg_replace('|([^/]*)(.*)|i', '$2', $site_root);
1428    if ('/' != substr($site_root, -1)) $site_root = $site_root . '/';
1429   
1430    $home_root = str_replace('http://', '', trim(get_settings('home')));
1431    $home_root = preg_replace('|([^/]*)(.*)|i', '$2', $home_root);
1432    if ('/' != substr($home_root, -1)) $home_root = $home_root . '/';
1433   
1434    $rules = "RewriteEngine On\n";
1435    $rules .= "RewriteBase $home_root\n";
1436    $rewrite = rewrite_rules('', $permalink_structure);
1437    foreach ($rewrite as $match => $query) {
1438        if (strstr($query, 'index.php')) {
1439            $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA]\n";
1440        } else {
1441            $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA]\n";
1442        }
1443    }
1444
1445    $rules = apply_filters('rewrite_rules', $rules);
1446
1447    return $rules;
1448}
1449
1450function get_posts($args) {
1451        global $wpdb;
1452        parse_str($args, $r);
1453        if (!isset($r['numberposts'])) $r['numberposts'] = 5;
1454        if (!isset($r['offset'])) $r['offset'] = 0;
1455        // The following not implemented yet
1456        if (!isset($r['category'])) $r['category'] = '';
1457        if (!isset($r['orderby'])) $r['orderby'] = '';
1458        if (!isset($r['order'])) $r['order'] = '';
1459
1460        $now = current_time('mysql');
1461
1462        $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']);
1463
1464    update_post_caches($posts);
1465       
1466        return $posts;
1467}
1468
1469function check_comment($author, $email, $url, $comment, $user_ip) {
1470        if (1 == get_settings('comment_moderation')) return false; // If moderation is set to manual
1471
1472        if ( (count(explode('http:', $comment)) - 1) >= get_settings('comment_max_links') )
1473                return false; // Check # of external links
1474
1475        if ('' == trim( get_settings('moderation_keys') ) ) return true; // If moderation keys are empty
1476        $words = explode("\n", get_settings('moderation_keys') );
1477        foreach ($words as $word) {
1478                $word = trim($word);
1479
1480                // Skip empty lines
1481                if (empty($word)) { continue; }
1482
1483                $pattern = "#$word#i";
1484                if ( preg_match($pattern, $author) ) return false;
1485                if ( preg_match($pattern, $email) ) return false;
1486                if ( preg_match($pattern, $url) ) return false;
1487                if ( preg_match($pattern, $comment) ) return false;
1488                if ( preg_match($pattern, $user_ip) ) return false;
1489        }
1490
1491        return true;
1492}
1493
1494function query_posts($query) {
1495    global $wp_query;
1496
1497    return $wp_query->query($query);
1498}
1499
1500function update_post_caches($posts) {
1501    global $category_cache, $comment_count_cache, $post_meta_cache;
1502    global $wpdb;
1503
1504    // No point in doing all this work if we didn't match any posts.
1505    if (! $posts) {
1506        return;
1507    }
1508
1509    // Get the categories for all the posts
1510    foreach ($posts as $post) {
1511        $post_id_list[] = $post->ID;
1512    }
1513    $post_id_list = implode(',', $post_id_list);
1514
1515    $dogs = $wpdb->get_results("SELECT DISTINCT
1516        ID, category_id, cat_name, category_nicename, category_description, category_parent
1517        FROM $wpdb->categories, $wpdb->post2cat, $wpdb->posts
1518        WHERE category_id = cat_ID AND post_id = ID AND post_id IN ($post_id_list)");
1519       
1520    if (!empty($dogs)) {
1521        foreach ($dogs as $catt) {
1522            $category_cache[$catt->ID][] = $catt;
1523        }
1524    }
1525
1526    // Do the same for comment numbers
1527    $comment_counts = $wpdb->get_results("SELECT ID, COUNT( comment_ID ) AS ccount
1528        FROM $wpdb->posts
1529        LEFT JOIN $wpdb->comments ON ( comment_post_ID = ID  AND comment_approved =  '1')
1530        WHERE post_status =  'publish' AND ID IN ($post_id_list)
1531        GROUP BY ID");
1532   
1533    if ($comment_counts) {
1534        foreach ($comment_counts as $comment_count) {
1535            $comment_count_cache["$comment_count->ID"] = $comment_count->ccount;
1536        }
1537    }
1538
1539    // Get post-meta info
1540    if ( $meta_list = $wpdb->get_results("
1541                        SELECT post_id,meta_key,meta_value
1542                        FROM $wpdb->postmeta 
1543                        WHERE post_id IN($post_id_list)
1544                        ORDER BY post_id,meta_key
1545                ", ARRAY_A) ) {
1546               
1547        // Change from flat structure to hierarchical:
1548        $post_meta_cache = array();
1549        foreach ($meta_list as $metarow) {
1550            $mpid = $metarow['post_id'];
1551            $mkey = $metarow['meta_key'];
1552            $mval = $metarow['meta_value'];
1553                       
1554            // Force subkeys to be array type:
1555            if (!isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]))
1556                $post_meta_cache[$mpid] = array();
1557            if (!isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]))
1558                $post_meta_cache[$mpid]["$mkey"] = array();
1559                       
1560            // Add a value to the current pid/key:
1561            $post_meta_cache[$mpid][$mkey][] = $mval;
1562        }
1563    }
1564}
1565
1566function update_category_cache() {
1567    global $cache_categories, $wpdb;
1568    $dogs = $wpdb->get_results("SELECT * FROM $wpdb->categories");
1569    foreach ($dogs as $catt) {
1570        $cache_categories[$catt->cat_ID] = $catt;
1571    }
1572}
1573
1574function update_user_cache() {
1575    global $cache_userdata, $wpdb;
1576
1577    if ( $users = $wpdb->get_results("SELECT * FROM $wpdb->users WHERE user_level > 0") ) :
1578                foreach ($users as $user) :
1579                        $cache_userdata[$user->ID] = $user;
1580                endforeach;
1581                return true;
1582        else: 
1583                return false;
1584        endif;
1585}
1586
1587function wp_head() {
1588        do_action('wp_head', '');
1589}
1590
1591function is_single () {
1592    global $wp_query;
1593
1594    return $wp_query->is_single;
1595}
1596
1597function is_page () {
1598    global $wp_query;
1599
1600    return $wp_query->is_page;
1601}
1602
1603function is_archive () {
1604    global $wp_query;
1605
1606    return $wp_query->is_archive;
1607}
1608
1609function is_date () {
1610    global $wp_query;
1611
1612    return $wp_query->is_date;
1613}
1614
1615function is_year () {
1616    global $wp_query;
1617
1618    return $wp_query->is_year;
1619}
1620
1621function is_month () {
1622    global $wp_query;
1623
1624    return $wp_query->is_month;
1625}
1626
1627function is_day () {
1628    global $wp_query;
1629
1630    return $wp_query->is_day;
1631}
1632
1633function is_time () {
1634    global $wp_query;
1635
1636    return $wp_query->is_time;
1637}
1638
1639function is_author () {
1640    global $wp_query;
1641
1642    return $wp_query->is_author;
1643}
1644
1645function is_category () {
1646    global $wp_query;
1647
1648    return $wp_query->is_category;
1649}
1650
1651function is_search () {
1652    global $wp_query;
1653
1654    return $wp_query->is_search;
1655}
1656
1657function is_feed () {
1658    global $wp_query;
1659
1660    return $wp_query->is_feed;
1661}
1662
1663function is_home () {
1664    global $wp_query;
1665
1666    return $wp_query->is_home;
1667}
1668
1669function is_404 () {
1670    global $wp_query;
1671
1672    return $wp_query->is_404;
1673}
1674
1675function get_query_var($var) {
1676  global $wp_query;
1677
1678  return $wp_query->get($var);
1679}
1680
1681function have_posts() {
1682    global $wp_query;
1683
1684    return $wp_query->have_posts();
1685}
1686
1687function the_post() {
1688    start_wp(true);
1689}
1690
1691?>
Note: See TracBrowser for help on using the repository browser.