Make WordPress Core

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

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

Massive options cleanup and another step of cleaning up the upgrade/install.

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