root/branches/release-36/php/mt.php.pre @ 2104

Revision 2104, 30.9 kB (checked in by takayama, 19 months ago)

Implemented BugId:71811, BugId:79438
* Added SSI support into the Dynamic Publishing
* Added cache option support

  • 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        // Changes dbdriver from native to PDO, if we can.
239        // * PHP Version >= 5.0
240        // * DBDriver == sqlite / with out UseSQLite2
241        // * PDO and PDO_SQLITE extensions loaded
242        if (version_compare(PHP_VERSION, '5.0') > 0
243            && $cfg['dbdriver'] == 'sqlite'
244            && !isset($cfg['usesqlite2'])
245            && extension_loaded('pdo')
246            && extension_loaded('pdo_sqlite'))
247        {
248            $cfg['dbdriver'] = 'pdo_sqlite';
249        }
250        $this->config =& $cfg;
251        $this->config_defaults();
252
253        // read in the database password
254        if (!isset($cfg['dbpassword'])) {
255            $db_pass_file = $cfg['mtdir'] . DIRECTORY_SEPARATOR . 'mt-db-pass.cgi';
256            if (file_exists($db_pass_file)) {
257                $password = implode('', file($db_pass_file));
258                $password = trim($password, "\n\r\0");
259                $cfg['dbpassword'] = $password;
260            }
261        }
262
263        // set up include path
264        // add MT-PHP 'plugins' and 'lib' directories to the front
265        // of the existing PHP include path:
266        if (strtoupper(substr(PHP_OS, 0,3) == 'WIN')) {
267            $path_sep = ';';
268        } else {
269            $path_sep = ':';
270        }
271        ini_set('include_path',
272            $cfg['phpdir'] . DIRECTORY_SEPARATOR . "lib" . $path_sep .
273            $cfg['phpdir'] . DIRECTORY_SEPARATOR . "extlib" . $path_sep .
274            $cfg['phpdir'] . DIRECTORY_SEPARATOR . "extlib" . DIRECTORY_SEPARATOR . "smarty" . DIRECTORY_SEPARATOR . "libs" . $path_sep .
275            ini_get('include_path')
276        );
277    }
278
279    function configure_from_db() {
280        $cfg =& $this->config;
281        $mtdb =& $this->db();
282        $db_config = $mtdb->fetch_config();
283        if ($db_config) {
284            $data = $db_config['config_data'];
285            $data = preg_split('/[\r?\n]/', $data);
286            foreach ($data as $line) {
287                // search through the file
288                if (!ereg('^\s*\#',$line)) {
289                    // ignore lines starting with the hash symbol
290                    if (preg_match('/^\s*(\S+)\s+(.*)$/', $line, $regs)) {
291                        $key = strtolower(trim($regs[1]));
292                        $value = trim($regs[2]);
293                        if (($key == 'PluginSwitch') || ($key == 'PluginSchemaVersion')) { # special case for hash
294                            if (preg_match('/^(.+)=(.+)$/', $value, $match))
295                                $cfg[$key][trim($match[1])] = trim($match[2]);
296                        } else {
297                            $cfg[$key] or $cfg[$key] = $value;
298                        }
299                    }
300                }
301            }
302            if ($cfg['dbdriver'] == 'mysql' or $cfg['dbdriver'] == 'postgres') {
303                if ($cfg['sqlsetnames']) {
304                    $Charset = array(
305                        'postgres' => array('utf-8' => 'UNICODE', 'shift_jis' => 'SJIS', 'euc-jp' => 'EUC_JP'),
306                        'mysql' => array('utf-8' => 'utf8', 'shift_jis' => 'sjis', 'euc-jp' => 'ujis'));
307                    $lang = $Charset[$cfg['dbdriver']][strtolower($cfg['publishcharset'])];
308                    if ($lang) {
309                        $mtdb->query("SET NAMES '$lang'");
310                    }
311                }
312            }           
313        }
314    }
315
316    function config_defaults() {
317        $cfg =& $this->config;
318        // assign defaults:
319        if (substr($cfg['cgipath'], strlen($cfg['cgipath']) - 1, 1) != '/')
320            $cfg['cgipath'] .= '/';
321        isset($cfg['staticwebpath']) or
322            $cfg['staticwebpath'] = $cfg['cgipath'] . 'mt-static/';
323        isset($cfg['publishcharset']) or
324            $cfg['publishcharset'] = '__PUBLISH_CHARSET__';
325        isset($cfg['trackbackscript']) or
326            $cfg['trackbackscript'] = 'mt-tb.cgi';
327        isset($cfg['adminscript']) or
328            $cfg['adminscript'] = 'mt.cgi';
329        isset($cfg['commentscript']) or
330            $cfg['commentscript'] = 'mt-comments.cgi';
331        isset($cfg['atomscript']) or
332            $cfg['atomscript'] = 'mt-atom.cgi';
333        isset($cfg['xmlrpcscript']) or
334            $cfg['xmlrpcscript'] = 'mt-xmlrpc.cgi';
335        isset($cfg['searchscript']) or
336            $cfg['searchscript'] = 'mt-search.cgi';
337        isset($cfg['defaultlanguage']) or
338            $cfg['defaultlanguage'] = '__BUILD_LANGUAGE__';
339        isset($cfg['globalsanitizespec']) or
340            $cfg['globalsanitizespec'] = 'a href,b,i,br/,p,strong,em,ul,ol,li,blockquote,pre';
341        isset($cfg['signonurl']) or
342            $cfg['signonurl'] = 'https://www.typekey.com/t/typekey/login?';
343        isset($cfg['signoffurl']) or
344            $cfg['signoffurl'] = 'https://www.typekey.com/t/typekey/logout?';
345        isset($cfg['identityurl']) or
346            $cfg['identityurl'] = 'http://profile.typekey.com/';
347        isset($cfg['publishcommentericon']) or
348            $cfg['publishcommentericon'] = '1';
349        isset($cfg['allowcomments']) or
350            $cfg['allowcomments'] = '1';
351        isset($cfg['allowpings']) or
352            $cfg['allowpings'] = '1';
353        isset($cfg['indexbasename']) or
354            $cfg['indexbasename'] = 'index';
355        isset($cfg['typekeyversion']) or
356            $cfg['typekeyversion'] = '1.1';
357        isset($cfg['assetcachedir']) or
358            $cfg['assetcachedir'] = 'assets_c';
359        isset($cfg['userpicthumbnailsize']) or
360            $cfg['userpicthumbnailsize'] = '100';
361        isset($cfg['pluginpath']) or
362            $cfg['pluginpath'] = array($this->config('MTDir') . DIRECTORY_SEPARATOR . 'plugins');
363        isset($cfg['timeoffset']) or
364            $cfg['timeoffset'] = '__DEFAULT_TIMEZONE__';
365        isset($cfg['includesdir']) or
366            $cfg['includesdir'] = 'includes_c';
367    }
368
369    function configure_paths($blog_site_path) {
370        if (preg_match('/^\./', $blog_site_path)) {
371            // relative address, so tack on the MT dir in front
372            $blog_site_path = $this->config('MTDir') .
373                DIRECTORY_SEPARATOR . $blog_site_path;
374        }
375        $this->config('PHPTemplateDir') or
376            $this->config('PHPTemplateDir', $blog_site_path .
377            DIRECTORY_SEPARATOR . 'templates');
378        $this->config('PHPCacheDir') or
379            $this->config('PHPCacheDir', $blog_site_path .
380            DIRECTORY_SEPARATOR . 'cache');
381
382        $ctx =& $this->context();
383        $ctx->template_dir = $this->config('PHPTemplateDir');
384        $ctx->compile_dir = $ctx->template_dir . '_c';
385        $ctx->cache_dir = $this->config('PHPCacheDir');
386    }
387
388    /***
389     * Mainline handler function.
390     */
391    function view($blog_id = null) {
392        if ($this->debugging) {
393            require_once("MTUtil.php");
394        }
395        $blog_id or $blog_id = $this->blog_id;
396
397        $ctx =& $this->context();
398        $this->init_plugins();
399        $ctx->caching = $this->caching;
400
401        // Some defaults...
402        $mtdb =& $this->db();
403        $ctx->mt->db =& $mtdb;
404
405        // Set up our customer error handler
406        set_error_handler(array(&$this, 'error_handler'));
407
408        // User-specified request through request variable
409        $path = $this->request;
410
411        // Apache request
412        if (!$path && $_SERVER['REQUEST_URI']) {
413            $path = $_SERVER['REQUEST_URI'];
414            // strip off any query string...
415            $path = preg_replace('/\?.*/', '', $path);
416            // strip any duplicated slashes...
417            $path = preg_replace('!/+!', '/', $path);
418        }
419
420        // IIS request by error document...
421        if (preg_match('/IIS/', $_SERVER['SERVER_SOFTWARE'])) {
422            // assume 404 handler
423            if (preg_match('/^\d+;(.*)$/', $_SERVER['QUERY_STRING'], $matches)) {
424                $path = $matches[1];
425                $path = preg_replace('!^http://[^/]+!', '', $path);
426                if (preg_match('/\?(.+)?/', $path, $matches)) {
427                    $_SERVER['QUERY_STRING'] = $matches[1];
428                    $path = preg_replace('/\?.*$/', '', $path);
429                }
430            }
431        }
432
433        // now set the path so it may be queried
434        $this->request = $path;
435
436        // When we are invoked as an ErrorDocument, the parameters are
437        // in the environment variables REDIRECT_*
438        if (isset($_SERVER['REDIRECT_QUERY_STRING'])) {
439            // todo: populate $_GET and QUERY_STRING with REDIRECT_QUERY_STRING
440            $_SERVER['QUERY_STRING'] = getenv('REDIRECT_QUERY_STRING');
441        }
442
443        if (preg_match('/\.(\w+)$/', $path, $matches)) {
444            $req_ext = strtolower($matches[1]);
445        }
446
447        $this->blog_id = $blog_id;
448
449        $data =& $this->resolve_url($path);
450        if (!$data) {
451            // 404!
452            $this->http_error = 404;
453            header("HTTP/1.1 404 Not found");
454            return $ctx->error($this->translate("Page not found - [_1]", $path), E_USER_ERROR);
455        }
456
457        $info =& $data['fileinfo'];
458        $fi_path = $info['fileinfo_url'];
459        $fid = $info['fileinfo_id'];
460        $at = $info['fileinfo_archive_type'];
461        $ts = $info['fileinfo_startdate'];
462        $tpl_id = $info['fileinfo_template_id'];
463        $cat = $info['fileinfo_category_id'];
464        $auth = $info['fileinfo_author_id'];
465        $entry_id = $info['fileinfo_entry_id'];
466        $blog_id = $info['fileinfo_blog_id'];
467        $blog =& $data['blog'];
468        if ($at == 'index') {
469            $at = null;
470            $ctx->stash('index_archive', true);
471        } else {
472            $ctx->stash('index_archive', false);
473        }
474        $tts = $data['template']['template_modified_on'];
475        if ($tts) {
476            $tts = offset_time(datetime_to_timestamp($tts), $blog);
477        }
478        $ctx->stash('template_timestamp', $tts);
479        $ctx->stash('template_created_on', $data['template']['template_created_on']);
480
481        $columns_map = array(
482            'layout-wt'  => 2,
483            'layout-tw'  => 2,
484            'layout-wm'  => 2,
485            'layout-mw'  => 2,
486            'layout-wtt' => 3,
487            'layout-twt' => 3);
488        $page_layout = $data['blog']['blog_page_layout'];
489        $columns = 0;
490        if(array_key_exists($page_layout, $columns_map))
491             $columns = $columns_map[$page_layout];
492        $vars =& $ctx->__stash['vars'];
493        $vars['page_columns'] = $columns;
494        $vars['page_layout'] = $page_layout;
495
496        if (isset($data['template']['template_identifier']))
497            $vars[$data['template']['template_identifier']] = 1;
498
499        $this->configure_paths($blog['blog_site_path']);
500
501        // start populating our stash
502        $ctx->stash('blog_id', $blog_id);
503        $ctx->stash('blog', $blog);
504        $ctx->stash('build_template_id', $tpl_id);
505
506        // conditional get support...
507        if ($this->caching) {
508            $this->cache_modified_check = true;
509        }
510        if ($this->conditional) {
511            $last_ts = $blog['blog_children_modified_on'];
512            $last_modified = $ctx->_hdlr_date(array('ts' => $last_ts, 'format' => '%a, %d %b %Y %H:%M:%S GMT', 'language' => 'en', 'utc' => 1), $ctx);
513            $this->doConditionalGet($last_modified);
514        }
515
516        $cache_id = $blog_id.';'.$fi_path;
517        if (!$ctx->is_cached('mt:'.$tpl_id, $cache_id)) {
518            if (isset($at) && ($at != 'Category')) {
519                global $_archivers;
520                require_once("archive_lib.php");
521                global $_archivers;
522                if (!isset($_archivers[$at])) {
523                    // 404
524                    $this->http_errr = 404;
525                    header("HTTP/1.1 404 Not Found");
526                    return $ctx->error($this->translate("Page not found - [_1]", $at), E_USER_ERROR);
527                }
528                $archiver = $_archivers[$at];
529                $archiver->template_params($ctx);
530            }
531
532            if ($cat) {
533                $archive_category = $mtdb->fetch_category($cat);
534                $ctx->stash('category', $archive_category);
535                $ctx->stash('archive_category', $archive_category);
536            }
537            if ($auth) {
538                $archive_author = $mtdb->fetch_author($auth);
539                $ctx->stash('author', $archive_author);
540                $ctx->stash('archive_author', $archive_author);
541            }
542            if (isset($at)) {
543                if (($at != 'Category') && isset($ts)) {
544                    list($ts_start, $ts_end) = $archiver->get_range($ctx, $ts);
545                    $ctx->stash('current_timestamp', $ts_start);
546                    $ctx->stash('current_timestamp_end', $ts_end);
547                }
548                $ctx->stash('current_archive_type', $at);
549            }
550   
551            if (isset($entry_id) && ($entry_id) && ($at == 'Individual' || $at == 'Page')) {
552                if ($at == 'Individual') {
553                    $entry =& $mtdb->fetch_entry($entry_id);
554                } elseif($at == 'Page') {
555                    $entry =& $mtdb->fetch_page($entry_id);
556                }
557                $ctx->stash('entry', $entry);
558                $ctx->stash('current_timestamp', $entry['entry_authored_on']);
559            }
560
561            if ($at == 'Category') {
562                $vars =& $ctx->__stash['vars'];
563                $vars['archive_class'] = "category-archive";
564                $vars['category_archive'] = 1;
565                $vars['archive_template'] = 1;
566                $vars['module_category-monthly_archives'] = 1;
567            }
568        }
569
570        $output = $ctx->fetch('mt:'.$tpl_id, $cache_id);
571
572        $this->http_error = 200;
573        header("HTTP/1.1 200 OK");
574        // content-type header-- need to supplement with charset
575        $content_type = $ctx->stash('content_type');
576
577        if (!isset($content_type)) {
578            $content_type = $this->mime_types['__default__'];
579            if ($req_ext && (isset($this->mime_types[$req_ext]))) {
580                $content_type = $this->mime_types[$req_ext];
581            }
582        }
583        $charset = $this->config('PublishCharset');
584        if (isset($charset)) {
585            if (!preg_match('/charset=/', $content_type))
586                $content_type .= '; charset=' . $charset;
587        }
588        header("Content-Type: $content_type");
589
590        // finally, issue output
591        $output = preg_replace('/^\s*/', '', $output);
592        echo $output;
593
594        if ($this->debugging) {
595            $this->log("Queries: ".$mtdb->num_queries);
596            $this->log("Queries executed:");
597            $queries = $mtdb->savedqueries;
598            foreach ($queries as $q) {
599                $this->log($q);
600            }
601            $this->log_dump();
602        }
603        restore_error_handler();
604    }
605
606    function &resolve_url($path) {
607        $data =& $this->db->resolve_url($path, $this->blog_id);
608        if ( isset($data)
609            && isset($data['fileinfo']['fileinfo_entry_id'])
610            && is_numeric($data['fileinfo']['fileinfo_entry_id'])
611        ) {
612            if (strtolower($data['templatemap']['templatemap_archive_type']) == 'page') {
613                $entry = $this->db->fetch_page($data['fileinfo']['fileinfo_entry_id']);
614            } else {
615                $entry = $this->db->fetch_entry($data['fileinfo']['fileinfo_entry_id']);
616            }
617            require_once('function.mtentrystatus.php');
618            if (!isset($entry) || $entry['entry_status'] != STATUS_RELEASE)
619                return;
620        }
621        return $data;
622    }
623
624    function doConditionalGet($last_modified) {
625        // Thanks to Simon Willison...
626        //   http://simon.incutio.com/archive/2003/04/23/conditionalGet
627        // A PHP implementation of conditional get, see
628        //   http://fishbowl.pastiche.org/archives/001132.html
629        $etag = '"'.md5($last_modified).'"';
630        // Send the headers
631        header("Last-Modified: $last_modified");
632        header("ETag: $etag");
633        // See if the client has provided the required headers
634        $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?
635            stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :
636            false;
637        $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
638            stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) :
639            false;
640        if (!$if_modified_since && !$if_none_match) {
641            return;
642        }
643        // At least one of the headers is there - check them
644        if ($if_none_match && $if_none_match != $etag) {
645            return; // etag is there but doesn't match
646        }
647        if ($if_modified_since && $if_modified_since != $last_modified) {
648            return; // if-modified-since is there but doesn't match
649        }
650        // Nothing has changed since their last request - serve a 304 and exit
651        header('HTTP/1.1 304 Not Modified');
652        exit;
653    }
654
655    function display($tpl, $cid = null) {
656        $ctx =& $this->context();
657        $this->init_plugins();
658        $blog =& $ctx->stash('blog');
659        if (!$blog) {
660            $db =& $this->db();
661            $ctx->mt->db =& $db;
662            $blog =& $db->fetch_blog($this->blog_id);
663            $ctx->stash('blog', $blog);
664            $ctx->stash('blog_id', $this->blog_id);
665            $this->configure_paths($blog['blog_site_path']);
666        }
667        return $ctx->display($tpl, $cid);
668    }
669
670    function fetch($tpl, $cid = null) {
671        $ctx =& $this->context();
672        $this->init_plugins();
673        $blog =& $ctx->stash('blog');
674        if (!$blog) {
675            $db =& $this->db();
676            $ctx->mt->db =& $db;
677            $blog =& $db->fetch_blog($this->blog_id);
678            $ctx->stash('blog', $blog);
679            $ctx->stash('blog_id', $this->blog_id);
680            $this->configure_paths($blog['blog_site_path']);
681        }
682        return $ctx->fetch($tpl, $cid);
683    }
684
685    function log_dump() {
686        if ($_SERVER['REMOTE_ADDR']) {
687            // web view...
688            echo "<div class=\"debug\" style=\"border:1px solid red; margin:0.5em; padding: 0 1em; text-align:left; background-color:#ddd; color:#000\"><pre>";
689            echo implode("\n", $this->log);
690            echo "</pre></div>\n\n";
691        } else {
692            // console view...
693            $stderr = fopen('php://stderr', 'w');
694            fwrite($stderr,implode("\n", $this->log));
695            echo (implode("\n", $this->log));
696            fclose($stderr);
697        }
698    }
699
700    function error_handler($errno, $errstr, $errfile, $errline) {
701        if ($errno & (E_ALL ^ E_NOTICE)) {
702            if (version_compare(phpversion(), '4.3.0', '>=')) {
703                $charset = $this->config('PublishCharset');
704                $errstr = htmlentities($errstr, ENT_COMPAT, $charset);
705                $errfile = htmlentities($errfile, ENT_COMPAT, $charset);
706            } else {
707                $errstr = htmlentities($errstr, ENT_COMPAT);
708                $errfile = htmlentities($errfile, ENT_COMPAT);
709            }
710            $mtphpdir = $this->config('PHPDir');
711            $ctx =& $this->context();
712            $ctx->stash('blog_id', $this->blog_id);
713            $ctx->stash('blog', $this->db->fetch_blog($this->blog_id));
714            $ctx->stash('error_message', $errstr."<!-- file: $errfile; line: $errline; code: $errno -->");
715            $ctx->stash('error_code', $errno);
716            $http_error = $this->http_error;
717            if (!$http_error) {
718                $http_error = 500;
719            }
720            $ctx->stash('http_error', $http_error);
721            $ctx->stash('error_file', $errfile);
722            $ctx->stash('error_line', $errline);
723            $ctx->template_dir = $mtphpdir . DIRECTORY_SEPARATOR . 'tmpl';
724            $ctx->caching = 0;
725            $ctx->stash('StaticWebPath', $this->config('StaticWebPath'));
726            $ctx->stash('PublishCharset', $this->config('PublishCharset'));
727            $charset = $this->config('PublishCharset');
728            $out = $ctx->tag('Include', array('type' => 'dynamic_error', 'dynamic_error' => 1, 'system_template' => 1));
729            if (isset($out)) {
730                header("Content-type: text/html; charset=".$charset);
731                echo $out;
732            } else {
733                header("HTTP/1.1 500 Server Error");
734                header("Content-type: text/plain");
735                echo "Error executing error template.";
736            }
737            exit;
738        }
739    }
740
741    /***
742     * Retrieves a context and rendering object.
743     */
744    function &context() {
745        static $ctx;
746        if (isset($ctx)) return $ctx;
747
748        require_once('MTViewer.php');
749        $ctx = new MTViewer($this);
750        $ctx->mt =& $this;
751        $mtphpdir = $this->config('PHPDir');
752        $mtlibdir = $this->config('PHPLibDir');
753        $ctx->compile_check = 1;
754        $ctx->caching = false;
755        $ctx->plugins_dir[] = $mtlibdir;
756        $ctx->plugins_dir[] = $mtphpdir . DIRECTORY_SEPARATOR . "plugins";
757        if ($this->debugging) {
758            $ctx->debugging_ctrl = 'URL';
759            $ctx->debug_tpl = $mtphpdir . DIRECTORY_SEPARATOR .
760                'extlib' . DIRECTORY_SEPARATOR .
761                'smarty' . DIRECTORY_SEPARATOR . "libs" . DIRECTORY_SEPARATOR .
762                'debug.tpl';
763        }
764        #if (isset($this->config('SafeMode')) && ($this->config('SafeMode'))) {
765        #    // disable PHP support
766        #    $ctx->php_handling = SMARTY_PHP_REMOVE;
767        #}
768        return $ctx;
769    }
770
771    function log($msg = null) {
772        $this->log[] = $msg;
773    }
774
775    function translate($str, $params = null) {
776        return translate_phrase($str, $params);
777    }
778
779    function translate_templatized_item($str) {
780        return translate_phrase($str[1]);
781    }
782
783    function translate_templatized($tmpl) {
784        $cb = array($this, 'translate_templatized_item');
785        $out = preg_replace_callback('/<(?:_|mt)_trans phrase="(.+?)".*?>/i', $cb, $tmpl);
786        return $out;
787    }
788}
789
790function is_valid_email($addr) {
791    if (preg_match('/[ |\t|\r|\n]*\"?([^\"]+\"?@[^ <>\t]+\.[^ <>\t][^ <>\t]+)[ |\t|\r|\n]*/', $addr, $matches)) {
792        return $matches[1];
793    } else {
794        return 0;
795    }
796}
797
798$spam_protect_map = array(':' => '&#58;', '@' => '&#64;', '.' => '&#46;');
799function spam_protect($str) {
800    global $spam_protect_map;
801    return strtr($str, $spam_protect_map);
802}
803
804function datetime_to_timestamp($dt) {
805    $dt = preg_replace('/[^0-9]/', '', $dt);
806    $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));
807    return $ts;
808}
809
810function offset_time($ts, $blog = null, $dir = null) {
811    if (isset($blog)) {
812        if (!is_array($blog)) {
813            global $mt;
814            $blog = $mt->db->fetch_blog($blog);
815        }
816        $offset = $blog['blog_server_offset'];
817    } else {
818        global $mt;
819        $offset = $mt->config('TimeOffset');
820    }
821    intval($offset) or $offset = 0;
822    $tsa = localtime($ts);
823
824    if ($tsa[8]) {  // daylight savings offset
825        $offset++;
826    }
827    if ($dir == '-') {
828        $offset *= -1;
829    }
830    $ts += $offset * 3600;
831    return $ts;
832}
833function _strip_index($url, $blog) {
834    global $mt;
835    $index = $mt->config('IndexBasename');
836    $ext = $blog['blog_file_extension'];
837    if ($ext != '') $ext = '.' . $ext;
838    $index = preg_quote($index . $ext);
839    $url = preg_replace("/\/$index(#.*)?$/", '/$1', $url);
840    return $url;
841}
842
843function translate_phrase_param($str, $params = null) {
844    if (is_array($params) && (strpos($str, '[_') !== false)) {
845        for ($i = 1; $i <= count($params); $i++) {
846            $str = preg_replace("/\\[_$i\\]/", $params[$i-1], $str);
847        }
848    }
849    return $str;
850}
851?>
Note: See TracBrowser for help on using the browser.