Make WordPress Core

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

Last change on this file since 1597 was 1597, checked in by saxmatt, 21 years ago

Remove optiongroup_options table.

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