Location: PHPKode > projects > Blite > blite-0.1-beta6/blite/init.php
<?php
/*
 *      Copyright 2012 Douglas Robbins <hide@address.com>
 *      
 *      This file is part of Blite, a blogging application, available at
 *      <http://blite.ca/>.
 * 
 *      Blite is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 3 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

$cfg['sqlfile'] = $cfg['datadir'] . '/' . $cfg['dbname'];
$stop_error = '';

// 'Stop' checks.

// Check for PHP 5.3+
if (!function_exists('array_replace')) {
	$stop_error = "This application requires PHP 5.3 or later.";
}
// Check for sqlite3 extension.
if (!extension_loaded('sqlite3')) {
	$stop_error = "The PHP sqlite extension is not loaded.";
}
// Check that dbdir & db exist and are writable.
if (!is_dir($cfg['datadir'])) {
	$stop_error = "The data directory set in the configuration does not exist.";
}
elseif (!is_writable($cfg['datadir'])) {
	$stop_error = "The data directory set in the configuration is not writable by PHP.";
}
elseif (!file_exists($cfg['sqlfile'])) {
	$stop_error = "The sqlite database set in the configuration does not exist.";
}
elseif (!is_writable($cfg['sqlfile'])) {
	$stop_error = "The sqlite database set in the configuration is not writable by PHP.";
}

if (!empty($stop_error)) {
	echo $stop_error;
	exit;
}

if ( !is_dir($cfg['datadir'] . '/cache') ) {
	mkdir($cfg['datadir'] . '/cache');
}

// Load settings from db.

$queries = 0;

// Settings that should be treated as integer values.
$ints = array( 'threadsperpage', 'maxcommentlength', 'editfor', 'numrecentposts', 'numrecentcomments' );

$db = new SQLite3($cfg['sqlfile']);

$query_params = '';
$results = db_query("SELECT * FROM settings");

while ($row = db_getdata($results)) {
	if ($row['name'] == 'allowedtags') {
		$cfg['allowedtags'] = explode(' ', $row['value']);
	}
	elseif ( in_array($row['name'], $ints) ) {
		$cfg[$row['name']] = abs($row['value']);
	}
	else {
		$cfg[$row['name']] = $row['value'];
	}
}

// Theme & CSS File.

// Fall back to the default theme if the theme specified in the db is missing.
if ( !is_dir('themes/' . $cfg['theme']) ) {
	$cfg['theme'] = 'default';
}
$cssfile = 'themes/' . $cfg['theme'] . '/browse.css';
$cssver = @filemtime($cssfile);
$cssfile = $cssfile . '?v=' . $cssver;

// Home URL. Where to go when lost...

$protocol = 'http';
if (!empty($_SERVER['HTTPS'])) {
	$protocol = 'https';
}
$domain = $_SERVER['SERVER_NAME'];
$request = $_SERVER['REQUEST_URI'];
$parts = explode('/', $request);
$numparts = count($parts);
$lastpart = $parts[$numparts-1];
$cfg['home'] = $protocol . '://' . $domain . str_replace($lastpart,'',$request);

// Put $cfg['allowedtags'] into formats for PHP strip_tags() function and for
// display on-screen below the comment form.

$php_allowedtags = '';
$showtags = '';
foreach ($cfg['allowedtags'] as $key => $val) {
	if ($val == 'html' || $val == 'body' || $val == 'p') {
		unset ($cfg['allowedtags'][$key]);
	}
	else {
		$php_allowedtags .= '<' . $val . '>';
		$showtags .= '&lt;'.$val.'&gt;, ';
	}
}
if (!empty($showtags)) {
	$showtags = substr($showtags, 0, -2) . '.';
}
if (in_array('code', $cfg['allowedtags'])) {
	$usecode = "<li>" . $lang['usecode'] . "</li>";
}

// <br> and <blockquote> must be allowed for comment functionality.
// We exclude them from the $cfg['allowedtags'] and add them here.

$php_allowedtags .= '<br><blockquote>';

//

session_start();

// Unset cache control headers set by default in a PHP session.
if (!empty($browse)) {
	header('Cache-Control:');
	header('Pragma:');
}

// Admin user.

$authuser = FALSE;
$authstr = sha1($cfg['adminpass'] . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
if (!empty($_COOKIE['admin']) && $_COOKIE['admin'] == $authstr) {
	$authuser = TRUE;
	// Set session values for comment form.
	$_SESSION['com_name'] = $cfg['adminname'];
	$_SESSION['com_email'] = $cfg['adminmail'];
}
elseif (!empty($_COOKIE['admin'])) {
	setcookie('admin', '', '0', '', '');
}

$adminnav = "<li><a href='login.php' rel='nofollow'>" . $lang['adminlogin'] . "</a></li>\n";
if ($authuser) {
	$adminnav  = "<li><a href='post.php'>" . $lang['adminnewpost'] . "</a></li>\n";
	$adminnav .= "<li><a href='list.php?s=2'>" . $lang['admindrafts'] . "</a></li>\n";
	$adminnav .= "<li><a href='list.php?s=3'>" . $lang['adminretracted'] . "</a></li>\n";
	$adminnav .= "<li><a href='categories.php'>" . $lang['admincats'] . "</a></li>\n";
	$adminnav .= "<li><a href='settings.php'>" . $lang['adminsettings'] . "</a></li>\n";
	$adminnav .= "<li><a href='spambox.php'>" . $lang['adminspambox'] . "</a></li>\n";
	$adminnav .= "<li><a href='login.php?logout=1'>" . $lang['adminlogout'] . "</a></li>\n";
}

// Or cookies for a guest.

else {
	$idstr = sha1($_SERVER['REMOTE_ADDR'] .  $_SERVER['HTTP_USER_AGENT']);
	if (!empty($_COOKIE['guest_name_'.$idstr])) {
		$_SESSION['com_name'] = $_COOKIE['guest_name_'.$idstr];
	}
	if (!empty($_COOKIE['guest_email_'.$idstr])) {
		$_SESSION['com_email'] = $_COOKIE['guest_email_'.$idstr];
	}
	if (!empty($_COOKIE['guest_web_'.$idstr])) {
		$_SESSION['com_web'] = $_COOKIE['guest_web_'.$idstr];
	}
}

// Timeoffset.

date_default_timezone_set('GMT');
$timeoffset = 0;
if (!empty($_COOKIE['timeoffset'])) {
	$timeoffset = abs($_COOKIE['timeoffset']) * 3600;
	if ($_COOKIE['timeoffset']{0} == '-') {
		$timeoffset = '-'.$timeoffset;
	}
}

// Main template.

$page = array(
	'charset'         => $cfg['charset'],
	'blogname'        => $cfg['sitename'], // HTML allowed.
	'blognametext'    => htmlspecialchars(strip_tags($cfg['sitename'])),
	'description'     => htmlspecialchars(strip_tags($cfg['sitedescription'])),
	'pagetitle'       => htmlspecialchars(strip_tags($cfg['sitename'])),
	'cssfile'         => $cssfile,
	'rss'             => '',
	'contentclass'    => 'browse',
	'rssicon'         => '',
	'rsstext'         => '',
	'maincontent'     => '',
	
	'infobar'         => ''
);

//
// Global functions.
//

function db_getdata($prep) {
	
	// db type is hardcoded to sqlite for now.
	$sqltype = 'sqlite';
	
	if ($sqltype == 'sqlite' && !empty($prep) ) {
		$row = $prep->fetchArray();
	}
	
	if (!empty($row)) {
		return $row;
	}
	
}

function db_query($query) {
	
	global $query_params;
	global $queries;
	$queries++;
	
	/*
	$debug = "<div style='font-size:10pt; margin:10px'>" . $queries . '. ' . $query . "</div>\n";
	echo $debug;
	*/
	
	// db type is hardcoded to sqlite for now.
	$sqltype = 'sqlite';
	
	if ($sqltype == 'sqlite' && !empty($query) ) {
		global $db;
		$val_type = array(
			'int' => SQLITE3_INTEGER,
			'txt' => SQLITE3_TEXT
		);
		$stmt = $db->prepare($query);
		$int = 1;
		if (!empty($query_params)) {
			foreach ($query_params as $key => $val) {
				$stmt->bindValue( $int, $GLOBALS[$key], $val_type[$val] );
				$int++;
			}
		}
		$results = $stmt->execute();
	}
	
	if (!empty($results)) {
		return $results;
	}
	
}

function verify_nonce($type,$errormsg) {
	global $cfg;
	global $lang;
	global $db;
	global $queries;
	global $query_params;
	global $nonce;
	global $noncetype;
	$noncetype = $type;
	$error = '';
	$then = $_POST['stamp'];
	$rem = $_SERVER['REMOTE_ADDR'];
	$renonce = sha1( $then . $rem . $cfg['noncesalt'] );
	if ( empty($_POST['nonce']) || empty($_POST['stamp']) ) {
		// Missing nonce or timestamp value.
		$error = '(A) ' . $lang['forminvalid'];
	}
	elseif ( $_POST['nonce'] !== $renonce ) {
		// Invalid nonce.
		$error = '(B) ' . $lang['forminvalid'];
	}
	else {
		$nonce = $_POST['nonce'];
		$query_params = array( 'nonce' => 'txt', 'noncetype' => 'txt' );
		$results = db_query("SELECT id FROM nonces WHERE nonce=? AND type=?");
		//$queries++;
		$row = db_getdata($results);
		if ( !empty($row['id']) ) {
			// nonce exists.
			$error = $errormsg;
		}
	}
	return array($nonce, $then, $error);
}

function valid_email($email) {
	if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
		list ($name,$domain) = explode('@', $email, 2);
		if (!stristr($domain, '.')) {
			$valid = false;
		}
		elseif ( !checkdnsrr($domain,"MX") ) {
			$valid = false;
		}
		else {
			$valid = true;
		}
	}
	else {
		$valid = false;
	}
	return $valid;
}

function encode_code($text) {
	// Based on http://konstruktors.com/blog/wordpress/1850-automatically-escape-html-entities-of-code-fragments-in-comments/
	$encoded = preg_replace_callback('/<code>(.*?)<\/code>/ims',
	create_function('$matches', 'return "<code>" . htmlspecialchars($matches[1]) . "</code>";'), $text);
	if ($encoded) {
		return $encoded;
	}
	else {
		return $text;
	}
}
function decode_code($text) {
	$decoded = preg_replace_callback('/<code>(.*?)<\/code>/ims',
	create_function('$matches', 'return "<code>" . htmlspecialchars_decode($matches[1]) . "</code>";'), $text);
	if ($decoded) {
		return $decoded;
	}
	else {
		return $text;
	}
}

function dom_it($text) {
	$dom = new DOMDocument();
	$dom->preserveWhiteSpace = true;
	$dom->formatOutput = true;
	$dom->encoding = 'UTF-8';
	$text = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<body>\n" . $text . "\n</body>\n</html>\n";
	$dom->loadHTML($text);
	$text = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
	/* $text = preg_replace('/^<\?xml.+?>\n<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveXML())); */
	return $text;
}

function write_file($filename, $content) {
	$fp = fopen($filename, 'w');
	fwrite($fp, $content);
	fclose($fp);	
}
function rm_cache($filename) {
	if (file_exists($filename)) {
		unlink($filename);
	}
}

?>
Return current item: Blite