root/branches/release-32/php/mt.php.pre @ 1554

Revision 1554, 29.8 kB (checked in by takayama, 20 months ago)

Implemented fbz:68986
* Implemented UI for session cache
* Implemented php side

  • Property svn:keywords set to Author Date Id Revision
Line 
1<?php
2# Movable Type (r) Open Source (C) 2004-2008 Six Apart, Ltd.
3# This program is distributed under the terms of the
4# GNU General Public License, version 2.
5#
6# $Id$
7
8define('VERSION', '__API_VERSION__');
9define('VERSION_ID', '__PRODUCT_VERSION_ID__');
10define('PRODUCT_VERSION', '__PRODUCT_VERSION__');
11define('PRODUCT_NAME', '__PRODUCT_NAME__');
12
13global $Lexicon;
14$Lexicon = array();
15
16class MT {
17    var $mime_types = array(
18        '__default__' => 'text/html',
19        'css' => 'text/css',
20        'txt' => 'text/plain',
21        'rdf' => 'text/xml',
22        'rss' => 'text/xml',
23        'xml' => 'text/xml',
24    );
25    var $blog_id;
26    var $db;
27    var $config;
28    var $debugging = false;
29    var $caching = false;
30    var $conditional = false;
31    var $log = array();
32    var $id;
33    var $request;
34    var $http_error;
35    var $cfg_file;
36    var $cache_driver;
37
38    /***
39     * Constructor for MT class. Also declares a global variable
40     * '$mt' and assigns itself to that. There can only be one
41     * instance of this class.
42     */
43    function MT($blog_id = null, $cfg_file = null) {
44        error_reporting(E_ALL ^ E_NOTICE);
45        global $mt;
46        if (isset($mt)) {
47            die("Only one instance of the MT class can be created.");
48        }
49        $this->id = md5(uniqid('MT',true));
50        $this->init($blog_id, $cfg_file);
51    }
52
53    function init($blog_id = null, $cfg_file = null) {
54        if (isset($blog_id)) {
55            $this->blog_id = $blog_id;
56        }
57
58        if (!file_exists($cfg_file)) {
59            $mtdir = dirname(dirname(__FILE__));
60            $cfg_file = $mtdir . DIRECTORY_SEPARATOR . "mt-config.cgi";
61        }
62
63        $this->configure($cfg_file);
64        $this->init_addons();
65        $this->configure_from_db();
66
67        $lang = substr(strtolower($this->config('DefaultLanguage')), 0, 2);
68        if (!@include_once("l10n_$lang.php"))
69            include_once("l10n_en.php");
70
71        if (extension_loaded('mbstring')) {
72            $charset = $this->config('PublishCharset');
73            mb_internal_encoding($charset);
74            mb_http_output($charset);
75        }
76    }
77
78    function init_addons() {
79        $mtdir = dirname(dirname(__FILE__));
80        $path = $mtdir . DIRECTORY_SEPARATOR . "addons";
81        if (is_dir($path)) {
82            $ctx =& $this->context();
83            if ($dh = opendir($path)) {
84                while (($file = readdir($dh)) !== false) {
85                    if ($file == "." || $file == "..") {
86                        continue;
87                    }
88                    $plugin_dir = $path . DIRECTORY_SEPARATOR . $file
89                        . DIRECTORY_SEPARATOR . 'php';
90                    if (is_dir($plugin_dir))
91                        $ctx->add_plugin_dir($plugin_dir);
92                }
93                closedir($dh);
94            }
95        }
96    }
97
98    function init_plugins() {
99        $plugin_paths = $this->config('PluginPath');
100        $ctx =& $this->context();
101
102        foreach ($plugin_paths as $path) {
103            if ($dh = opendir($path)) {
104                 while (($file = readdir($dh)) !== false) {
105                     if ($file == "." || $file == "..")
106                         continue;
107                     $plugin_dir = $path . DIRECTORY_SEPARATOR . $file
108                         . DIRECTORY_SEPARATOR . 'php';
109                     if (is_dir($plugin_dir))
110                         $ctx->add_plugin_dir($plugin_dir);
111                 }
112                 closedir($dh);
113            }
114        }
115
116        $plugin_dir = $this->config('PHPDir') . DIRECTORY_SEPARATOR
117            . 'plugins';
118        if (is_dir($plugin_dir))
119            $ctx->add_plugin_dir($plugin_dir);
120
121        # Load any php directories found during the 'init_addons' loop
122        foreach ($ctx->plugins_dir as $plugin_dir)
123            if (is_dir($plugin_dir))
124                $this->load_plugin($plugin_dir);
125    }
126
127    function load_plugin($plugin_dir) {
128        $ctx =& $this->context();
129        // global filters have to be handled differently from
130        // tag attributes, so this causes them to be recognized
131        // as they should...
132        if ($dh = opendir($plugin_dir)) {
133            while (($file = readdir($dh)) !== false) {
134                if (preg_match('/^modifier\.(.+?)\.php$/', $file, $matches)) {
135                    $ctx->add_global_filter($matches[1]);
136                } elseif (preg_match('/^init\.(.+?)\.php$/', $file, $matches)) {
137                    // load 'init' plugin file
138                    require_once($file);
139                }
140            }
141            closedir($dh);
142        }
143    }
144
145    /***
146     * Retreives a handle to the database and assigns it to
147     * the member variable 'db'.
148     */
149    function &db() {
150        if (isset($this->db)) return $this->db;
151
152        require_once("mtdb_".$this->config('DBDriver').".php");
153        $mtdbclass = 'MTDatabase_'.$this->config('DBDriver');
154        $this->db = new $mtdbclass($this->config('DBUser'),
155            $this->config('DBPassword'), $this->config('Database'),
156            $this->config('DBHost'), $this->config('DBPort'), $this->config('DBSocket'));
157        return $this->db;
158    }
159
160    /***
161     * Retreives a handle to the cache driver.
162     */
163    function &cache_driver() {
164        if (isset($this->cache_driver)) return $this->cache_driver;
165   
166        # Check for memcached enabled
167        $servers  = $this->config['MemcachedServers'];
168        if (isset($servers)) {
169            if (extension_loaded('memcache')) {
170                require_once("MTCache_memcached.php");
171                $this->cache_driver = new MTCache_memcached($servers);
172            }
173        } else {
174            require_once("MTCache_session.php");
175            $this->cache_driver = new MTCache_session();
176        }
177        return $this->cache_driver;
178    }
179
180    function config($id, $value = null) {
181        $id = strtolower($id);
182        if (isset($value))
183            $this->config[$id] = $value;
184        return $this->config[$id];
185    }
186
187    /***
188     * Loads configuration data from mt.cfg and mt-db-pass.cgi files.
189     * Stores content in the 'config' member variable.
190     */
191    function configure($file = null) {
192        if (isset($this->config)) return $config;
193
194        $this->cfg_file = $file;
195
196        $cfg = array();
197        $type_array = array('pluginpath', 'alttemplate', 'outboundtrackbackdomains', 'memcachedservers');
198        if ($fp = file($file)) {
199            foreach ($fp as $line) {
200                // search through the file
201                if (!ereg('^\s*\#',$line)) {
202                    // ignore lines starting with the hash symbol
203                    if (preg_match('/^\s*(\S+)\s+(.*)$/', $line, $regs)) {
204                        $key = strtolower(trim($regs[1]));
205                        $value = trim($regs[2]);
206                        if (in_array($key, $type_array)) {
207                            $cfg[$key][] = $value;
208                        } else {
209                            $cfg[$key] = $value;
210                        }
211                    }
212                }
213            }
214        } else {
215            die("Unable to open configuration file $file");
216        }
217
218        // setup directory locations
219        // location of mt.php
220        $cfg['phpdir'] = realpath(dirname(__FILE__));
221        // path to MT directory
222        $cfg['mtdir'] = realpath(dirname($file));
223        // path to handlers
224        $cfg['phplibdir'] = $cfg['phpdir'] . DIRECTORY_SEPARATOR . 'lib';
225
226        $cfg['dbhost'] or $cfg['dbhost'] = 'localhost'; // default to localhost
227        $driver = $cfg['objectdriver'];
228        $driver = preg_replace('/^DB[ID]::/', '', $driver);
229        $driver or $driver = 'mysql';
230        $cfg['dbdriver'] = strtolower($driver);
231   
232        if ((strlen($cfg['database'])<1 || strlen($cfg['dbuser'])<1)) {
233            if (($cfg['dbdriver'] != 'sqlite') && ($cfg['dbdriver'] != 'mssqlserver')) {
234                die("Unable to read database or username");
235            }
236        }
237
238        $this->config =& $cfg;
239        $this->config_defaults();
240
241        // read in the database password
242        if (!isset($cfg['dbpassword'])) {
243            $db_pass_file = $cfg['mtdir'] . DIRECTORY_SEPARATOR . 'mt-db-pass.cgi';
244            if (file_exists($db_pass_file)) {
245                $password = implode('', file($db_pass_file));
246                $password = trim($password, "\n\r\0");
247                $cfg['dbpassword'] = $password;
248            }
249        }
250
251        // set up include path
252        // add MT-PHP 'plugins' and 'lib' directories to the front
253        // of the existing PHP include path:
254        if (strtoupper(substr(PHP_OS, 0,3) == 'WIN')) {
255            $path_sep = ';';
256        } else {
257            $path_sep = ':';
258        }
259        ini_set('include_path',
260            $cfg['phpdir'] . DIRECTORY_SEPARATOR . "lib" . $path_sep .
261            $cfg['phpdir'] . DIRECTORY_SEPARATOR . "extlib" . $path_sep .
262            $cfg['phpdir'] . DIRECTORY_SEPARATOR . "extlib" . DIRECTORY_SEPARATOR . "smarty" . DIRECTORY_SEPARATOR . "libs" . $path_sep .
263            ini_get('include_path')
264        );
265    }
266
267    function configure_from_db() {
268        $cfg =& $this->config;
269        $mtdb =& $this->db();
270        $db_config = $mtdb->fetch_config();
271        if ($db_config) {
272            $data = $db_config['config_data'];
273            $data = preg_split('/[\r?\n]/', $data);
274            foreach ($data as $line) {
275                // search through the file
276                if (!ereg('^\s*\#',$line)) {
277                    // ignore lines starting with the hash symbol
278                    if (preg_match('/^\s*(\S+)\s+(.*)$/', $line, $regs)) {
279                        $key = strtolower(trim($regs[1]));
280                        $value = trim($regs[2]);
281                        if (($key == 'PluginSwitch') || ($key == 'PluginSchemaVersion')) { # special case for hash
282                            if (preg_match('/^(.+)=(.+)$/', $value, $match))
283                                $cfg[$key][trim($match[1])] = trim($match[2]);
284                        } else {
285                            $cfg[$key] or $cfg[$key] = $value;
286                        }
287                    }
288                }
289            }
290            if ($cfg['dbdriver'] == 'mysql' or $cfg['dbdriver'] == 'postgres') {
291                if ($cfg['sqlsetnames']) {
292                    $Charset = array(
293                        'postgres' => array('utf-8' => 'UNICODE', 'shift_jis' => 'SJIS', 'euc-jp' => 'EUC_JP'),
294                        'mysql' => array('utf-8' => 'utf8', 'shift_jis' => 'sjis', 'euc-jp' => 'ujis'));
295                    $lang = $Charset[$cfg['dbdriver']][strtolower($cfg['publishcharset'])];
296                    if ($lang) {
297                        $mtdb->query("SET NAMES '$lang'");
298                    }
299                }
300            }           
301        }
302    }
303
304    function config_defaults() {
305        $cfg =& $this->config;
306        // assign defaults:
307        if (substr($cfg['cgipath'], strlen($cfg['cgipath']) - 1, 1) != '/')
308            $cfg['cgipath'] .= '/';
309        isset($cfg['staticwebpath']) or
310            $cfg['staticwebpath'] = $cfg['cgipath'] . 'mt-static/';
311        isset($cfg['publishcharset']) or
312            $cfg['publishcharset'] = '__PUBLISH_CHARSET__';
313        isset($cfg['trackbackscript']) or
314            $cfg['trackbackscript'] = 'mt-tb.cgi';
315        isset($cfg['adminscript']) or
316            $cfg['adminscript'] = 'mt.cgi';
317        isset($cfg['commentscript']) or
318            $cfg['commentscript'] = 'mt-comments.cgi';
319        isset($cfg['atomscript']) or
320            $cfg['atomscript'] = 'mt-atom.cgi';
321        isset($cfg['xmlrpcscript']) or
322            $cfg['xmlrpcscript'] = 'mt-xmlrpc.cgi';
323        isset($cfg['searchscript']) or
324            $cfg['searchscript'] = 'mt-search.cgi';
325        isset($cfg['defaultlanguage']) or
326            $cfg['defaultlanguage'] = '__BUILD_LANGUAGE__';
327        isset($cfg['globalsanitizespec']) or
328            $cfg['globalsanitizespec'] = 'a href,b,i,br/,p,strong,em,ul,ol,li,blockquote,pre';
329        isset($cfg['signonurl']) or
330            $cfg['signonurl'] = 'https://www.typekey.com/t/typekey/login?';
331        isset($cfg['signoffurl']) or
332            $cfg['signoffurl'] = 'https://www.typekey.com/t/typekey/logout?';
333        isset($cfg['identityurl']) or
334            $cfg['identityurl'] = 'http://profile.typekey.com/';
335        isset($cfg['publishcommentericon']) or
336            $cfg['publishcommentericon'] = '1';
337        isset($cfg['allowcomments']) or
338            $cfg['allowcomments'] = '1';
339        isset($cfg['allowpings']) or
340            $cfg['allowpings'] = '1';
341        isset($cfg['indexbasename']) or
342            $cfg['indexbasename'] = 'index';
343        isset($cfg['typekeyversion']) or
344            $cfg['typekeyversion'] = '1.1';
345        isset($cfg['assetcachedir']) or
346            $cfg['assetcachedir'] = 'assets_c';
347        isset($cfg['userpicthumbnailsize']) or
348            $cfg['userpicthumbnailsize'] = '100';
349        isset($cfg['pluginpath']) or
350            $cfg['pluginpath'] = array($this->config('MTDir') . DIRECTORY_SEPARATOR . 'plugins');
351    }
352
353    function configure_paths($blog_site_path) {
354        if (preg_match('/^\./', $blog_site_path)) {
355            // relative address, so tack on the MT dir in front
356            $blog_site_path = $this->config('MTDir') .
357                DIRECTORY_SEPARATOR . $blog_site_path;
358        }
359        $this->config('PHPTemplateDir') or
360            $this->config('PHPTemplateDir', $blog_site_path .
361            DIRECTORY_SEPARATOR . 'templates');
362        $this->config('PHPCacheDir') or
363            $this->config('PHPCacheDir', $blog_site_path .
364            DIRECTORY_SEPARATOR . 'cache');
365
366        $ctx =& $this->context();
367        $ctx->template_dir = $this->config('PHPTemplateDir');
368        $ctx->compile_dir = $ctx->template_dir . '_c';
369        $ctx->cache_dir = $this->config('PHPCacheDir');
370    }
371
372    /***
373     * Mainline handler function.
374     */
375    function view($blog_id = null) {
376        if ($this->debugging) {
377            require_once("MTUtil.php");
378        }
379        $blog_id or $blog_id = $this->blog_id;
380
381        $ctx =& $this->context();
382        $this->init_plugins();
383        $ctx->caching = $this->caching;
384
385        // Some defaults...
386        $mtdb =& $this->db();
387        $ctx->mt->db =& $mtdb;
388
389        // Set up our customer error handler
390        set_error_handler(array(&$this, 'error_handler'));
391
392        // User-specified request through request variable
393        $path = $this->request;
394
395        // Apache request
396        if (!$path && $_SERVER['REQUEST_URI']) {
397            $path = $_SERVER['REQUEST_URI'];
398            // strip off any query string...
399            $path = preg_replace('/\?.*/', '', $path);
400            // strip any duplicated slashes...
401            $path = preg_replace('!/+!', '/', $path);
402        }
403
404        // IIS request by error document...
405        if (preg_match('/IIS/', $_SERVER['SERVER_SOFTWARE'])) {
406            // assume 404 handler
407            if (preg_match('/^\d+;(.*)$/', $_SERVER['QUERY_STRING'], $matches)) {
408                $path = $matches[1];
409                $path = preg_replace('!^http://[^/]+!', '', $path);
410                if (preg_match('/\?(.+)?/', $path, $matches)) {
411                    $_SERVER['QUERY_STRING'] = $matches[1];
412                    $path = preg_replace('/\?.*$/', '', $path);
413                }
414            }
415        }
416
417        // now set the path so it may be queried
418        $this->request = $path;
419
420        // When we are invoked as an ErrorDocument, the parameters are
421        // in the environment variables REDIRECT_*
422        if (isset($_SERVER['REDIRECT_QUERY_STRING'])) {
423            // todo: populate $_GET and QUERY_STRING with REDIRECT_QUERY_STRING
424            $_SERVER['QUERY_STRING'] = getenv('REDIRECT_QUERY_STRING');
425        }
426
427        if (preg_match('/\.(\w+)$/', $path, $matches)) {
428            $req_ext = strtolower($matches[1]);
429        }
430
431        $this->blog_id = $blog_id;
432
433        $data =& $this->resolve_url($path);
434        if (!$data) {
435            // 404!
436            $this->http_error = 404;
437            header("HTTP/1.1 404 Not found");
438            return $ctx->error("Page not found - $path", E_USER_ERROR);
439        }
440
441        $info =& $data['fileinfo'];
442        $fi_path = $info['fileinfo_url'];
443        $fid = $info['fileinfo_id'];
444        $at = $info['fileinfo_archive_type'];
445        $ts = $info['fileinfo_startdate'];
446        $tpl_id = $info['fileinfo_template_id'];
447        $cat = $info['fileinfo_category_id'];
448        $auth = $info['fileinfo_author_id'];
449        $entry_id = $info['fileinfo_entry_id'];
450        $blog_id = $info['fileinfo_blog_id'];
451        $blog =& $data['blog'];
452        if ($at == 'index') {
453            $at = null;
454            $ctx->stash('index_archive', true);
455        } else {
456            $ctx->stash('index_archive', false);
457        }
458        $tts = $data['template']['template_modified_on'];
459        if ($tts) {
460            $tts = offset_time(datetime_to_timestamp($tts), $blog);
461        }
462        $ctx->stash('template_timestamp', $tts);
463        $ctx->stash('template_created_on', $data['template']['template_created_on']);
464
465        $columns_map = array(
466            'layout-wt'  => 2,
467            'layout-tw'  => 2,
468            'layout-wm'  => 2,
469            'layout-mw'  => 2,
470            'layout-wtt' => 3,
471            'layout-twt' => 3);
472        $page_layout = $data['blog']['blog_page_layout'];
473        $columns = 0;
474        if(array_key_exists($page_layout, $columns_map))
475             $columns = $columns_map[$page_layout];
476        $vars =& $ctx->__stash['vars'];
477        $vars['page_columns'] = $columns;
478        $vars['page_layout'] = $page_layout;
479
480        $this->configure_paths($blog['blog_site_path']);
481
482        // start populating our stash
483        $ctx->stash('blog_id', $blog_id);
484        $ctx->stash('blog', $blog);
485        $ctx->stash('build_template_id', $tpl_id);
486
487        // conditional get support...
488        if ($this->caching) {
489            $this->cache_modified_check = true;
490        }
491        if ($this->conditional) {
492            $last_ts = $blog['blog_children_modified_on'];
493            $last_modified = $ctx->_hdlr_date(array('ts' => $last_ts, 'format' => '%a, %d %b %Y %H:%M:%S GMT', 'language' => 'en', 'utc' => 1), $ctx);
494            $this->doConditionalGet($last_modified);
495        }
496
497        $cache_id = $blog_id.';'.$fi_path;
498        if (!$ctx->is_cached('mt:'.$tpl_id, $cache_id)) {
499            if (isset($at) && ($at != 'Category')) {
500                global $_archivers;
501                require_once("archive_lib.php");
502                global $_archivers;
503                if (!isset($_archivers[$at])) {
504                    // 404
505                    $this->http_errr = 404;
506                    header("HTTP/1.1 404 Not Found");
507                    return $ctx->error("Page not found - $at", E_USER_ERROR);
508                }
509                $archiver = $_archivers[$at];
510                $archiver->template_params($ctx);
511            }
512
513            if ($cat) {
514                $archive_category = $mtdb->fetch_category($cat);
515                $ctx->stash('category', $archive_category);
516                $ctx->stash('archive_category', $archive_category);
517            }
518            if ($auth) {
519                $archive_author = $mtdb->fetch_author($auth);
520                $ctx->stash('author', $archive_author);
521                $ctx->stash('archive_author', $archive_author);
522            }
523            if (isset($at)) {
524                if (($at != 'Category') && isset($ts)) {
525                    list($ts_start, $ts_end) = $archiver->get_range($ctx, $ts);
526                    $ctx->stash('current_timestamp', $ts_start);
527                    $ctx->stash('current_timestamp_end', $ts_end);
528                }
529                $ctx->stash('current_archive_type', $at);
530            }
531   
532            if (isset($entry_id) && ($entry_id) && ($at == 'Individual' || $at == 'Page')) {
533                if ($at == 'Individual') {
534                    $entry =& $mtdb->fetch_entry($entry_id);
535                } elseif($at == 'Page') {
536                    $entry =& $mtdb->fetch_page($entry_id);
537                }
538                $ctx->stash('entry', $entry);
539                $ctx->stash('current_timestamp', $entry['entry_authored_on']);
540            }
541
542            if ($at == 'Category') {
543                $vars =& $ctx->__stash['vars'];
544                $vars['archive_class'] = "category-archive";
545                $vars['category_archive'] = 1;
546                $vars['main_template'] = 1;
547                $vars['archive_template'] = 1;
548                $vars['module_category-monthly_archives'] = 1;
549            }
550        }
551
552        $output = $ctx->fetch('mt:'.$tpl_id, $cache_id);
553
554        $this->http_error = 200;
555        header("HTTP/1.1 200 OK");
556        // content-type header-- need to supplement with charset
557        $content_type = $ctx->stash('content_type');
558
559        if (!isset($content_type)) {
560            $content_type = $this->mime_types['__default__'];
561            if ($req_ext && (isset($this->mime_types[$req_ext]))) {
562                $content_type = $this->mime_types[$req_ext];
563            }
564        }
565        $charset = $this->config('PublishCharset');
566        if (isset($charset)) {
567            if (!preg_match('/charset=/', $content_type))
568                $content_type .= '; charset=' . $charset;
569        }
570        header("Content-Type: $content_type");
571
572        // finally, issue output
573        $output = preg_replace('/^\s*/', '', $output);
574        echo $output;
575
576        if ($this->debugging) {
577            $this->log("Queries: ".$mtdb->num_queries);
578            $this->log("Queries executed:");
579            $queries = $mtdb->savedqueries;
580            foreach ($queries as $q) {
581                $this->log($q);
582            }
583            $this->log_dump();
584        }
585        restore_error_handler();
586    }
587
588    function &resolve_url($path) {
589        $data =& $this->db->resolve_url($path, $this->blog_id);
590        if ( isset($data)
591            && isset($data['fileinfo']['fileinfo_entry_id'])
592            && is_numeric($data['fileinfo']['fileinfo_entry_id'])
593        ) {
594            if (strtolower($data['templatemap']['templatemap_archive_type']) == 'page') {
595                $entry = $this->db->fetch_page($data['fileinfo']['fileinfo_entry_id']);
596            } else {
597                $entry = $this->db->fetch_entry($data['fileinfo']['fileinfo_entry_id']);
598            }
599            require_once('function.mtentrystatus.php');
600            if (!isset($entry) || $entry['entry_status'] != STATUS_RELEASE)
601                return;
602        }
603        return $data;
604    }
605
606    function doConditionalGet($last_modified) {
607        // Thanks to Simon Willison...
608        //   http://simon.incutio.com/archive/2003/04/23/conditionalGet
609        // A PHP implementation of conditional get, see
610        //   http://fishbowl.pastiche.org/archives/001132.html
611        $etag = '"'.md5($last_modified).'"';
612        // Send the headers
613        header("Last-Modified: $last_modified");
614        header("ETag: $etag");
615        // See if the client has provided the required headers
616        $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?
617            stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :
618            false;
619        $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
620            stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) :
621            false;
622        if (!$if_modified_since && !$if_none_match) {
623            return;
624        }
625        // At least one of the headers is there - check them
626        if ($if_none_match && $if_none_match != $etag) {
627            return; // etag is there but doesn't match
628        }
629        if ($if_modified_since && $if_modified_since != $last_modified) {
630            return; // if-modified-since is there but doesn't match
631        }
632        // Nothing has changed since their last request - serve a 304 and exit
633        header('HTTP/1.1 304 Not Modified');
634        exit;
635    }
636
637    function display($tpl, $cid = null) {
638        $ctx =& $this->context();
639        $this->init_plugins();
640        $blog =& $ctx->stash('blog');
641        if (!$blog) {
642            $db =& $this->db();
643            $ctx->mt->db =& $db;
644            $blog =& $db->fetch_blog($this->blog_id);
645            $ctx->stash('blog', $blog);
646            $ctx->stash('blog_id', $this->blog_id);
647            $this->configure_paths($blog['blog_site_path']);
648        }
649        return $ctx->display($tpl, $cid);
650    }
651
652    function fetch($tpl, $cid = null) {
653        $ctx =& $this->context();
654        $this->init_plugins();
655        $blog =& $ctx->stash('blog');
656        if (!$blog) {
657            $db =& $this->db();
658            $ctx->mt->db =& $db;
659            $blog =& $db->fetch_blog($this->blog_id);
660            $ctx->stash('blog', $blog);
661            $ctx->stash('blog_id', $this->blog_id);
662            $this->configure_paths($blog['blog_site_path']);
663        }
664        return $ctx->fetch($tpl, $cid);
665    }
666
667    function log_dump() {
668        if ($_SERVER['REMOTE_ADDR']) {
669            // web view...
670            echo "<div class=\"debug\" style=\"border:1px solid red; margin:0.5em; padding: 0 1em; text-align:left; background-color:#ddd; color:#000\"><pre>";
671            echo implode("\n", $this->log);
672            echo "</pre></div>\n\n";
673        } else {
674            // console view...
675            $stderr = fopen('php://stderr', 'w');
676            fwrite($stderr,implode("\n", $this->log));
677            echo (implode("\n", $this->log));
678            fclose($stderr);
679        }
680    }
681
682    function error_handler($errno, $errstr, $errfile, $errline) {
683        if ($errno & (E_ALL ^ E_NOTICE)) {
684            $errstr = htmlentities($errstr);
685            $errfile = htmlentities($errfile);
686            $mtphpdir = $this->config('PHPDir');
687            $ctx =& $this->context();
688            $ctx->stash('blog_id', $this->blog_id);
689            $ctx->stash('blog', $this->db->fetch_blog($this->blog_id));
690            $ctx->stash('error_message', $errstr."<!-- file: $errfile; line: $errline; code: $errno -->");
691            $ctx->stash('error_code', $errno);
692            $http_error = $this->http_error;
693            if (!$http_error) {
694                $http_error = 500;
695            }
696            $ctx->stash('http_error', $http_error);
697            $ctx->stash('error_file', $errfile);
698            $ctx->stash('error_line', $errline);
699            $ctx->template_dir = $mtphpdir . DIRECTORY_SEPARATOR . 'tmpl';
700            $ctx->caching = 0;
701            $ctx->stash('StaticWebPath', $this->config('StaticWebPath'));
702            $ctx->stash('PublishCharset', $this->config('PublishCharset'));
703            $charset = $this->config('PublishCharset');
704            $out = $ctx->tag('Include', array('type' => 'dynamic_error'));
705            if (isset($out)) {
706                header("Content-type: text/html; charset=".$charset);
707                echo $out;
708            } else {
709                header("HTTP/1.1 500 Server Error");
710                header("Content-type: text/plain");
711                echo "Error executing error template.";
712            }
713            exit;
714        }
715    }
716
717    /***
718     * Retreives a context and rendering object.
719     */
720    function &context() {
721        static $ctx;
722        if (isset($ctx)) return $ctx;
723
724        require_once('MTViewer.php');
725        $ctx = new MTViewer($this);
726        $ctx->mt =& $this;
727        $mtphpdir = $this->config('PHPDir');
728        $mtlibdir = $this->config('PHPLibDir');
729        $ctx->compile_check = 1;
730        $ctx->caching = false;
731        $ctx->plugins_dir[] = $mtlibdir;
732        $ctx->plugins_dir[] = $mtphpdir . DIRECTORY_SEPARATOR . "plugins";
733        if ($this->debugging) {
734            $ctx->debugging_ctrl = 'URL';
735            $ctx->debug_tpl = $mtphpdir . DIRECTORY_SEPARATOR .
736                'extlib' . DIRECTORY_SEPARATOR .
737                'smarty' . DIRECTORY_SEPARATOR . "libs" . DIRECTORY_SEPARATOR .
738                'debug.tpl';
739        }
740        #if (isset($this->config('SafeMode')) && ($this->config('SafeMode'))) {
741        #    // disable PHP support
742        #    $ctx->php_handling = SMARTY_PHP_REMOVE;
743        #}
744        return $ctx;
745    }
746
747    function log($msg = null) {
748        $this->log[] = $msg;
749    }
750
751    function translate($str, $params = null) {
752        return translate_phrase($str, $params);
753    }
754
755    function translate_templatized_item($str) {
756        return translate_phrase($str[1]);
757    }
758
759    function translate_templatized($tmpl) {
760        $cb = array($this, 'translate_templatized_item');
761        $out = preg_replace_callback('/<(?:_|mt)_trans phrase="(.+?)".*?>/i', $cb, $tmpl);
762        return $out;
763    }
764}
765
766function is_valid_email($addr) {
767    if (preg_match('/[ |\t|\r|\n]*\"?([^\"]+\"?@[^ <>\t]+\.[^ <>\t][^ <>\t]+)[ |\t|\r|\n]*/', $addr, $matches)) {
768        return $matches[1];
769    } else {
770        return 0;
771    }
772}
773
774$spam_protect_map = array(':' => '&#58;', '@' => '&#64;', '.' => '&#46;');
775function spam_protect($str) {
776    global $spam_protect_map;
777    return strtr($str, $spam_protect_map);
778}
779
780function datetime_to_timestamp($dt) {
781    $dt = preg_replace('/[^0-9]/', '', $dt);
782    $ts = mktime(substr($dt, 8, 2), substr($dt, 10, 2), substr($dt, 12, 2), substr($dt, 4, 2), substr($dt, 6, 2), substr($dt, 0, 4));
783    return $ts;
784}
785
786function offset_time($ts, $blog = null, $dir = null) {
787    if (isset($blog)) {
788        if (!is_array($blog)) {
789            global $mt;
790            $blog = $mt->db->fetch_blog($blog);
791        }
792        $offset = $blog['blog_server_offset'];
793    } else {
794        global $mt;
795        $offset = $mt->config('TimeOffset');
796    }
797    intval($offset) or $offset = 0;
798    $tsa = localtime($ts);
799
800    if ($tsa[8]) {  // daylight savings offset
801        $offset++;
802    }
803    if ($dir == '-') {
804        $offset *= -1;
805    }
806    $ts += $offset * 3600;
807    return $ts;
808}
809function _strip_index($url, $blog) {
810    global $mt;
811    $index = $mt->config('IndexBasename');
812    $ext = $blog['blog_file_extension'];
813    if ($ext != '') $ext = '.' . $ext;
814    $index = preg_quote($index . $ext);
815    $url = preg_replace("/\/$index(#.*)?$/", '/$1', $url);
816    return $url;
817}
818
819function translate_phrase_param($str, $params = null) {
820    if (is_array($params) && (strpos($str, '[_') !== false)) {
821        for ($i = 1; $i <= count($params); $i++) {
822            $str = preg_replace("/\\[_$i\\]/", $params[$i-1], $str);
823        }
824    }
825    return $str;
826}
827?>
Note: See TracBrowser for help on using the browser.