root/branches/release-39/php/mt.php.pre @ 2479

Revision 2479, 31.5 kB (checked in by takayama, 18 months ago)

Fixed BugId:79960
* Changed file name to small letter

  • 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        isset($cfg['searchmaxresults']) or
368            $cfg['searchmaxresults'] = '20';
369        isset($cfg['maxresults']) or
370            $cfg['maxresults'] = $cfg['searchmaxresults'];
371        isset($cfg['singlecommunity']) or
372            $cfg['singlecommunity'] = '0';
373        isset($cfg['usersessioncookiename']) or
374            $cfg['usersessioncookiename'] = 'DEFAULT';
375        isset($cfg['usersessioncookiedomain']) or
376            $cfg['usersessioncookiedomain'] = '<$MTBlogHost exclude_port="1"$>';
377        isset($cfg['usersessioncookiepath']) or
378            $cfg['usersessioncookiepath'] = 'DEFAULT';
379        isset($cfg['usersessioncookietimeout']) or
380            $cfg['usersessioncookietimeout'] = 60*60*4;
381    }
382
383    function configure_paths($blog_site_path) {
384        if (preg_match('/^\./', $blog_site_path)) {
385            // relative address, so tack on the MT dir in front
386            $blog_site_path = $this->config('MTDir') .
387                DIRECTORY_SEPARATOR . $blog_site_path;
388        }
389        $this->config('PHPTemplateDir') or
390            $this->config('PHPTemplateDir', $blog_site_path .
391            DIRECTORY_SEPARATOR . 'templates');
392        $this->config('PHPCacheDir') or
393            $this->config('PHPCacheDir', $blog_site_path .
394            DIRECTORY_SEPARATOR . 'cache');
395
396        $ctx =& $this->context();
397        $ctx->template_dir = $this->config('PHPTemplateDir');
398        $ctx->compile_dir = $ctx->template_dir . '_c';
399        $ctx->cache_dir = $this->config('PHPCacheDir');
400    }
401
402    /***
403     * Mainline handler function.
404     */
405    function view($blog_id = null) {
406        require_once("MTUtil.php");
407
408        $blog_id or $blog_id = $this->blog_id;
409
410        $ctx =& $this->context();
411        $this->init_plugins();
412        $ctx->caching = $this->caching;
413
414        // Some defaults...
415        $mtdb =& $this->db();
416        $ctx->mt->db =& $mtdb;
417
418        // Set up our customer error handler
419        set_error_handler(array(&$this, 'error_handler'));
420
421        // User-specified request through request variable
422        $path = $this->request;
423
424        // Apache request
425        if (!$path && $_SERVER['REQUEST_URI']) {
426            $path = $_SERVER['REQUEST_URI'];
427            // strip off any query string...
428            $path = preg_replace('/\?.*/', '', $path);
429            // strip any duplicated slashes...
430            $path = preg_replace('!/+!', '/', $path);
431        }
432
433        // IIS request by error document...
434        if (preg_match('/IIS/', $_SERVER['SERVER_SOFTWARE'])) {
435            // assume 404 handler
436            if (preg_match('/^\d+;(.*)$/', $_SERVER['QUERY_STRING'], $matches)) {
437                $path = $matches[1];
438                $path = preg_replace('!^http://[^/]+!', '', $path);
439                if (preg_match('/\?(.+)?/', $path, $matches)) {
440                    $_SERVER['QUERY_STRING'] = $matches[1];
441                    $path = preg_replace('/\?.*$/', '', $path);
442                }
443            }
444        }
445
446        // now set the path so it may be queried
447        $this->request = $path;
448
449        // When we are invoked as an ErrorDocument, the parameters are
450        // in the environment variables REDIRECT_*
451        if (isset($_SERVER['REDIRECT_QUERY_STRING'])) {
452            // todo: populate $_GET and QUERY_STRING with REDIRECT_QUERY_STRING
453            $_SERVER['QUERY_STRING'] = getenv('REDIRECT_QUERY_STRING');
454        }
455
456        if (preg_match('/\.(\w+)$/', $path, $matches)) {
457            $req_ext = strtolower($matches[1]);
458        }
459
460        $this->blog_id = $blog_id;
461
462        $data =& $this->resolve_url($path);
463        if (!$data) {
464            // 404!
465            $this->http_error = 404;
466            header("HTTP/1.1 404 Not found");
467            return $ctx->error($this->translate("Page not found - [_1]", $path), E_USER_ERROR);
468        }
469
470        $info =& $data['fileinfo'];
471        $fi_path = $info['fileinfo_url'];
472        $fid = $info['fileinfo_id'];
473        $at = $info['fileinfo_archive_type'];
474        $ts = $info['fileinfo_startdate'];
475        $tpl_id = $info['fileinfo_template_id'];
476        $cat = $info['fileinfo_category_id'];
477        $auth = $info['fileinfo_author_id'];
478        $entry_id = $info['fileinfo_entry_id'];
479        $blog_id = $info['fileinfo_blog_id'];
480        $blog =& $data['blog'];
481        if ($at == 'index') {
482            $at = null;
483            $ctx->stash('index_archive', true);
484        } else {
485            $ctx->stash('index_archive', false);
486        }
487        $tts = $data['template']['template_modified_on'];
488        if ($tts) {
489            $tts = offset_time(datetime_to_timestamp($tts), $blog);
490        }
491        $ctx->stash('template_timestamp', $tts);
492        $ctx->stash('template_created_on', $data['template']['template_created_on']);
493
494        $page_layout = $data['blog']['blog_page_layout'];
495        $columns = get_page_column($page_layout);
496        $vars =& $ctx->__stash['vars'];
497        $vars['page_columns'] = $columns;
498        $vars['page_layout'] = $page_layout;
499
500        if (isset($data['template']['template_identifier']))
501            $vars[$data['template']['template_identifier']] = 1;
502
503        $this->configure_paths($blog['blog_site_path']);
504
505        // start populating our stash
506        $ctx->stash('blog_id', $blog_id);
507        $ctx->stash('blog', $blog);
508        $ctx->stash('build_template_id', $tpl_id);
509
510        // conditional get support...
511        if ($this->caching) {
512            $this->cache_modified_check = true;
513        }
514        if ($this->conditional) {
515            $last_ts = $blog['blog_children_modified_on'];
516            $last_modified = $ctx->_hdlr_date(array('ts' => $last_ts, 'format' => '%a, %d %b %Y %H:%M:%S GMT', 'language' => 'en', 'utc' => 1), $ctx);
517            $this->doConditionalGet($last_modified);
518        }
519
520        $cache_id = $blog_id.';'.$fi_path;
521        if (!$ctx->is_cached('mt:'.$tpl_id, $cache_id)) {
522            if (isset($at) && ($at != 'Category')) {
523                global $_archivers;
524                require_once("archive_lib.php");
525                global $_archivers;
526                if (!isset($_archivers[$at])) {
527                    // 404
528                    $this->http_errr = 404;
529                    header("HTTP/1.1 404 Not Found");
530                    return $ctx->error($this->translate("Page not found - [_1]", $at), E_USER_ERROR);
531                }
532                $archiver = $_archivers[$at];
533                $archiver->template_params($ctx);
534            }
535
536            if ($cat) {
537                $archive_category = $mtdb->fetch_category($cat);
538                $ctx->stash('category', $archive_category);
539                $ctx->stash('archive_category', $archive_category);
540            }
541            if ($auth) {
542                $archive_author = $mtdb->fetch_author($auth);
543                $ctx->stash('author', $archive_author);
544                $ctx->stash('archive_author', $archive_author);
545            }
546            if (isset($at)) {
547                if (($at != 'Category') && isset($ts)) {
548                    list($ts_start, $ts_end) = $archiver->get_range($ctx, $ts);
549                    $ctx->stash('current_timestamp', $ts_start);
550                    $ctx->stash('current_timestamp_end', $ts_end);
551                }
552                $ctx->stash('current_archive_type', $at);
553            }
554   
555            if (isset($entry_id) && ($entry_id) && ($at == 'Individual' || $at == 'Page')) {
556                if ($at == 'Individual') {
557                    $entry =& $mtdb->fetch_entry($entry_id);
558                } elseif($at == 'Page') {
559                    $entry =& $mtdb->fetch_page($entry_id);
560                }
561                $ctx->stash('entry', $entry);
562                $ctx->stash('current_timestamp', $entry['entry_authored_on']);
563            }
564
565            if ($at == 'Category') {
566                $vars =& $ctx->__stash['vars'];
567                $vars['archive_class']                    = "category-archive";
568                $vars['category_archive']                 = 1;
569                $vars['archive_template']                 = 1;
570                $vars['archive_listing']                  = 1;
571                $vars['module_category-monthly_archives'] = 1;
572            }
573        }
574
575        $output = $ctx->fetch('mt:'.$tpl_id, $cache_id);
576
577        $this->http_error = 200;
578        header("HTTP/1.1 200 OK");
579        // content-type header-- need to supplement with charset
580        $content_type = $ctx->stash('content_type');
581
582        if (!isset($content_type)) {
583            $content_type = $this->mime_types['__default__'];
584            if ($req_ext && (isset($this->mime_types[$req_ext]))) {
585                $content_type = $this->mime_types[$req_ext];
586            }
587        }
588        $charset = $this->config('PublishCharset');
589        if (isset($charset)) {
590            if (!preg_match('/charset=/', $content_type))
591                $content_type .= '; charset=' . $charset;
592        }
593        header("Content-Type: $content_type");
594
595        // finally, issue output
596        $output = preg_replace('/^\s*/', '', $output);
597        echo $output;
598
599        if ($this->debugging) {
600            $this->log("Queries: ".$mtdb->num_queries);
601            $this->log("Queries executed:");
602            $queries = $mtdb->savedqueries;
603            foreach ($queries as $q) {
604                $this->log($q);
605            }
606            $this->log_dump();
607        }
608        restore_error_handler();
609    }
610
611    function &resolve_url($path) {
612        $data =& $this->db->resolve_url($path, $this->blog_id);
613        if ( isset($data)
614            && isset($data['fileinfo']['fileinfo_entry_id'])
615            && is_numeric($data['fileinfo']['fileinfo_entry_id'])
616        ) {
617            if (strtolower($data['templatemap']['templatemap_archive_type']) == 'page') {
618                $entry = $this->db->fetch_page($data['fileinfo']['fileinfo_entry_id']);
619            } else {
620                $entry = $this->db->fetch_entry($data['fileinfo']['fileinfo_entry_id']);
621            }
622            require_once('function.mtentrystatus.php');
623            if (!isset($entry) || $entry['entry_status'] != STATUS_RELEASE)
624                return;
625        }
626        return $data;
627    }
628
629    function doConditionalGet($last_modified) {
630        // Thanks to Simon Willison...
631        //   http://simon.incutio.com/archive/2003/04/23/conditionalGet
632        // A PHP implementation of conditional get, see
633        //   http://fishbowl.pastiche.org/archives/001132.html
634        $etag = '"'.md5($last_modified).'"';
635        // Send the headers
636        header("Last-Modified: $last_modified");
637        header("ETag: $etag");
638        // See if the client has provided the required headers
639        $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?
640            stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :
641            false;
642        $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
643            stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) :
644            false;
645        if (!$if_modified_since && !$if_none_match) {
646            return;
647        }
648        // At least one of the headers is there - check them
649        if ($if_none_match && $if_none_match != $etag) {
650            return; // etag is there but doesn't match
651        }
652        if ($if_modified_since && $if_modified_since != $last_modified) {
653            return; // if-modified-since is there but doesn't match
654        }
655        // Nothing has changed since their last request - serve a 304 and exit
656        header('HTTP/1.1 304 Not Modified');
657        exit;
658    }
659
660    function display($tpl, $cid = null) {
661        $ctx =& $this->context();
662        $this->init_plugins();
663        $blog =& $ctx->stash('blog');
664        if (!$blog) {
665            $db =& $this->db();
666            $ctx->mt->db =& $db;
667            $blog =& $db->fetch_blog($this->blog_id);
668            $ctx->stash('blog', $blog);
669            $ctx->stash('blog_id', $this->blog_id);
670            $this->configure_paths($blog['blog_site_path']);
671        }
672        return $ctx->display($tpl, $cid);
673    }
674
675    function fetch($tpl, $cid = null) {
676        $ctx =& $this->context();
677        $this->init_plugins();
678        $blog =& $ctx->stash('blog');
679        if (!$blog) {
680            $db =& $this->db();
681            $ctx->mt->db =& $db;
682            $blog =& $db->fetch_blog($this->blog_id);
683            $ctx->stash('blog', $blog);
684            $ctx->stash('blog_id', $this->blog_id);
685            $this->configure_paths($blog['blog_site_path']);
686        }
687        return $ctx->fetch($tpl, $cid);
688    }
689
690    function log_dump() {
691        if ($_SERVER['REMOTE_ADDR']) {
692            // web view...
693            echo "<div class=\"debug\" style=\"border:1px solid red; margin:0.5em; padding: 0 1em; text-align:left; background-color:#ddd; color:#000\"><pre>";
694            echo implode("\n", $this->log);
695            echo "</pre></div>\n\n";
696        } else {
697            // console view...
698            $stderr = fopen('php://stderr', 'w');
699            fwrite($stderr,implode("\n", $this->log));
700            echo (implode("\n", $this->log));
701            fclose($stderr);
702        }
703    }
704
705    function error_handler($errno, $errstr, $errfile, $errline) {
706        if ($errno & (E_ALL ^ E_NOTICE)) {
707            if (version_compare(phpversion(), '4.3.0', '>=')) {
708                $charset = $this->config('PublishCharset');
709                $errstr = htmlentities($errstr, ENT_COMPAT, $charset);
710                $errfile = htmlentities($errfile, ENT_COMPAT, $charset);
711            } else {
712                $errstr = htmlentities($errstr, ENT_COMPAT);
713                $errfile = htmlentities($errfile, ENT_COMPAT);
714            }
715            $mtphpdir = $this->config('PHPDir');
716            $ctx =& $this->context();
717            $ctx->stash('blog_id', $this->blog_id);
718            $ctx->stash('blog', $this->db->fetch_blog($this->blog_id));
719            $ctx->stash('error_message', $errstr."<!-- file: $errfile; line: $errline; code: $errno -->");
720            $ctx->stash('error_code', $errno);
721            $http_error = $this->http_error;
722            if (!$http_error) {
723                $http_error = 500;
724            }
725            $ctx->stash('http_error', $http_error);
726            $ctx->stash('error_file', $errfile);
727            $ctx->stash('error_line', $errline);
728            $ctx->template_dir = $mtphpdir . DIRECTORY_SEPARATOR . 'tmpl';
729            $ctx->caching = 0;
730            $ctx->stash('StaticWebPath', $this->config('StaticWebPath'));
731            $ctx->stash('PublishCharset', $this->config('PublishCharset'));
732            $charset = $this->config('PublishCharset');
733            $out = $ctx->tag('Include', array('type' => 'dynamic_error', 'dynamic_error' => 1, 'system_template' => 1));
734            if (isset($out)) {
735                header("Content-type: text/html; charset=".$charset);
736                echo $out;
737            } else {
738                header("HTTP/1.1 500 Server Error");
739                header("Content-type: text/plain");
740                echo "Error executing error template.";
741            }
742            exit;
743        }
744    }
745
746    /***
747     * Retrieves a context and rendering object.
748     */
749    function &context() {
750        static $ctx;
751        if (isset($ctx)) return $ctx;
752
753        require_once('MTViewer.php');
754        $ctx = new MTViewer($this);
755        $ctx->mt =& $this;
756        $mtphpdir = $this->config('PHPDir');
757        $mtlibdir = $this->config('PHPLibDir');
758        $ctx->compile_check = 1;
759        $ctx->caching = false;
760        $ctx->plugins_dir[] = $mtlibdir;
761        $ctx->plugins_dir[] = $mtphpdir . DIRECTORY_SEPARATOR . "plugins";
762        if ($this->debugging) {
763            $ctx->debugging_ctrl = 'URL';
764            $ctx->debug_tpl = $mtphpdir . DIRECTORY_SEPARATOR .
765                'extlib' . DIRECTORY_SEPARATOR .
766                'smarty' . DIRECTORY_SEPARATOR . "libs" . DIRECTORY_SEPARATOR .
767                'debug.tpl';
768        }
769        #if (isset($this->config('SafeMode')) && ($this->config('SafeMode'))) {
770        #    // disable PHP support
771        #    $ctx->php_handling = SMARTY_PHP_REMOVE;
772        #}
773        return $ctx;
774    }
775
776    function log($msg = null) {
777        $this->log[] = $msg;
778    }
779
780    function translate($str, $params = null) {
781        if ( ( $params !== null ) && ( !is_array($params) ) )
782            $params = array( $params );
783        return translate_phrase($str, $params);
784    }
785
786    function translate_templatized_item($str) {
787        return translate_phrase($str[1]);
788    }
789
790    function translate_templatized($tmpl) {
791        $cb = array($this, 'translate_templatized_item');
792        $out = preg_replace_callback('/<(?:_|mt)_trans phrase="(.+?)".*?>/i', $cb, $tmpl);
793        return $out;
794    }
795}
796
797function is_valid_email($addr) {
798    if (preg_match('/[ |\t|\r|\n]*\"?([^\"]+\"?@[^ <>\t]+\.[^ <>\t][^ <>\t]+)[ |\t|\r|\n]*/', $addr, $matches)) {
799        return $matches[1];
800    } else {
801        return 0;
802    }
803}
804
805$spam_protect_map = array(':' => '&#58;', '@' => '&#64;', '.' => '&#46;');
806function spam_protect($str) {
807    global $spam_protect_map;
808    return strtr($str, $spam_protect_map);
809}
810
811function datetime_to_timestamp($dt) {
812    $dt = preg_replace('/[^0-9]/', '', $dt);
813    $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));
814    return $ts;
815}
816
817function offset_time($ts, $blog = null, $dir = null) {
818    if (isset($blog)) {
819        if (!is_array($blog)) {
820            global $mt;
821            $blog = $mt->db->fetch_blog($blog);
822        }
823        $offset = $blog['blog_server_offset'];
824    } else {
825        global $mt;
826        $offset = $mt->config('TimeOffset');
827    }
828    intval($offset) or $offset = 0;
829    $tsa = localtime($ts);
830
831    if ($tsa[8]) {  // daylight savings offset
832        $offset++;
833    }
834    if ($dir == '-') {
835        $offset *= -1;
836    }
837    $ts += $offset * 3600;
838    return $ts;
839}
840function _strip_index($url, $blog) {
841    global $mt;
842    $index = $mt->config('IndexBasename');
843    $ext = $blog['blog_file_extension'];
844    if ($ext != '') $ext = '.' . $ext;
845    $index = preg_quote($index . $ext);
846    $url = preg_replace("/\/$index(#.*)?$/", '/$1', $url);
847    return $url;
848}
849
850function translate_phrase_param($str, $params = null) {
851    if (is_array($params) && (strpos($str, '[_') !== false)) {
852        for ($i = 1; $i <= count($params); $i++) {
853            $str = preg_replace("/\\[_$i\\]/", $params[$i-1], $str);
854        }
855    }
856    return $str;
857}
858?>
Note: See TracBrowser for help on using the browser.