root/trunk/php/mt.php @ 3019

Revision 3019, 31.8 kB (checked in by bchoate, 15 months ago)

Updated versions to match release.

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