Newer
Older
insanelyBlog / core.php
<?php

// Start session
session_start();

// REALLY NICE ERROR PAGE KINDA THING
function nice_error($err, $errstr = false, $file, $line)
{
	if ($errstr) { $errno = $err; $err = $errstr; }
	if (($errstr && $errno != 2048) || !$errstr)
	{
		ob_end_clean();
		header('Content-type: text/plain');
		die($err.(isset($errno) ? ' ('.$errno.')' : '')." [$file] <$line>");
	}
}
set_error_handler('nice_error');

// LOAD CONFIG
define('_FS_PATH', dirname(__FILE__).'/');
require_once _FS_PATH.'config.php';

// FEEDBACK
$info = array();
$error = array();

// SEO
if (isset($_GET['pathsec']))
{
	$seo = explode('/', $_GET['pathsec']);
	foreach ($seo AS $a=>$b)
		$seo[$a] = htmlspecialchars($b);
} else
	$seo = array('');

// DATABASE
$_sql = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME) or nice_error('Sorry, but we cant connect to the database server right now.');
$_sql->query("SET NAMES ".DBCHAR);
$_sql->query("SET CHARACTER SET ".DBCHAR);

// LANGUAGE
$_locale = (array)json_decode(file_get_contents(_FS_PATH.'includes/locale/hu_HU.lng'));

// OTHER CLEVER STUFFS
function clear_cache() { header("Cache-Control: no-cache, must-revalidate"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); }

function redirect($url = '/', $status = false) { header('Location: '.$url.($status ? '?status='.$status : '')); exit; }
function isnum($in) { return is_numeric($in); }
function sqlprot($in) { global $_sql; return $_sql->real_escape_string($in); }

function trimlink($in, $length = 140) { $in = html_entity_decode(strip_tags($in)); if (strlen($in) > $length) return substr($in, 0, $length-3).'...'; return $in; }

// SETTINGS
require_once _FS_PATH.'includes/settings.class.php';
$_set = settings::getdata();


// CLASSES
require_once _FS_PATH.'includes/user.class.php';
require_once _FS_PATH.'includes/blog.class.php';
require_once _FS_PATH.'includes/page.class.php';
require_once _FS_PATH.'includes/check.class.php';
require_once _FS_PATH.'includes/comment.class.php';


// FUNCTIONS
function get_page_link($slug, $p = false)					{ global $_set; $prefix = ($p ? $_set['url'] : ''); if ($_set['seo']) return $prefix."/$_set[subPage]/$slug"; return $prefix."/?pathsec=$_set[subPage]/$slug"; }
function get_entry_link($slug, $p = false, $admin = false)	{ global $_set; $prefix = ($p ? $_set['url'] : '').($admin ? '/admin' : null); if ($_set['seo']) return $prefix."/$_set[subEntry]/$slug"; return $prefix."/?pathsec=$_set[subEntry]/$slug"; }
function get_profile_link($slug = false, $p = false)		{ global $_set; $prefix = ($p ? $_set['url'] : ''); if (!$slug) { global $user; if (LOGGEDIN) $slug = $user['userName']; else $slug = ''; } if ($_set['seo'])	return $prefix."/$_set[subProfile]/$slug"; return $prefix."/?pathsec=$_set[subProfile]/$slug"; }
function get_profile_picture($userData = false, $p = false)	{ global $_set; $prefix = ($p ? $_set['url'] : ''); if (!$userData) if (LOGGEDIN) { global $user; $userData = $user;} else $userData = array('userPic'=>0); return $prefix.($userData['userPic'] ? "/data/profile_pics/$userData[userId].jpg" : '/data/imgs/'.$_set['defaultProfilePic']); }
function get_current_link($p = false)						{ global $_set, $seo; $prefix = ($p ? $_set['url'] : ''); $link = ''; for ($i = 0; $i < sizeof($seo); $i++) $link .= '/'.$seo[$i]; return $prefix.($_set['seo'] ? $link : '/?pathsec='.$link); }

function get_theme_lib() { global $_set; if (file_exists(_FS_PATH.'themes/'.$_set['mainTheme'])) return 'themes/'.$_set['mainTheme']; return false; }
function get_theme()
{
	global $_set;
	if (file_exists(_FS_PATH.'themes/'.$_set['mainTheme'].'/template.php'))
		return _FS_PATH.'themes/'.$_set['mainTheme'].'/template.php';
	return false;
}
function get_site_link() { global $_set; return $_set['url']; }
function get_site_body() { global $output; return output_replacer($output); }

function get_navigation($append = '', $returnarray = false)
{
	global $_locale, $_sql, $seo, $_title;
	$navLinks = array();
	if ($seo[0] && isset($_title[0])) array_push($navLinks, array('link' => '/', 'title' => $_locale['home']));
	$navQuery = $_sql->query("SELECT pageSlug, pageTitle FROM pages WHERE pageDeleted IS NULL ORDER BY pageTitle ASC");
	while ($navData = $navQuery->fetch_assoc())
		array_push($navLinks, array('link' => get_page_link($navData['pageSlug']), 'title' => $navData['pageTitle']));

	if ($returnarray)
		return $navLinks;

	for ($i = 0; $i < sizeof($navLinks); $i++)
	{
		$link = explode('/', $navLinks[$i]['link']);
		for ($b = 1; $b < sizeof($link); $b++)
		{
			$active = true;
			if (isset($seo[$b-1]) && $seo[$b-1] == $link[$b] && $active)
				$active = true; else $active = false;
		}
		echo "<li><a href='".$navLinks[$i]['link'].$append."'".($active ? " class='active'":'').">".$navLinks[$i]['title']."</a></li>";
	}
}
function get_tags($append = '')
{
	global $_sql;
	$tags = $_sql->query("SELECT tagId, tagName, COUNT(taggedId) AS taggedposts FROM tagged INNER JOIN tags ON tagId = taggedTag GROUP BY tagId ORDER BY tagName ASC");
	if ($tags->num_rows)
	{
		while ($data = $tags->fetch_assoc())
			echo "<li><a href='/tag/$data[tagId]$append'>$data[tagName]</a> <span>$data[taggedposts]</span></li>";
	}
}

function get_entry_admin($d)
{
	global $user;
	if (!LOGGEDIN) return '';

	if ($user['userLevel'] > 3) return "<span class='admin'>".($d['entryPinned'] ? "<a href='/admin/entry/$d[entrySlug]/unpin' class='pin unpin'>{locale:unpin}</a>":"<a href='/admin/entry/$d[entrySlug]/pin' class='pin'>{locale:pin}</a>")."<a href='/admin/entry/$d[entrySlug]' class='edit'>{locale:edit}</a><a href='/admin/entry/$d[entrySlug]/delete' class='delete' onclick='return confirm(\"{locale:delete_confirm}\")'>{locale:delete}</a></span>";
	if ($user['userLevel'] > 2 && $d['entryBy'] == $user['userId']) return "<span class='admin'><a href='/admin/entry/$d[entrySlug]' class='edit'>{locale:edit}</a></span>";
}

function get_page_title()
{
	global $_title, $_set;
	if (!empty($_title))
	{
		$title2 = '';
		for ($i=sizeof($_title)-1; $i>=0; $i--)
			$title2 .= $_title[$i].', ';

		$trepf = array('{title}', '{page}');
		$trept = array($_set['title'], rtrim($title2, ', '));
		echo str_replace($trepf, $trept, ($_set['titleFormat'] ? $_set['titleFormat'] : '{page} | {title}'));
	} else
		echo $_set['title'];
}
function get_page_extra_head()
{
	global $_head, $metaimage, $_set;
	if (!empty($_head))
	{
		for ($i=0; $i<sizeof($_head); $i++)
			echo $_head[$i]."\n";
	}
	echo '<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="'.$_set['url'].'/rss" />'."\n";
	if ($metaimage)
	{
		if (!strpos($metaimage, 'http')) $metaimage = $_set['url'].$metaimage;
		echo '<link rel="image_src" href="'.$metaimage.'" />'."\n";
		echo '<meta property="og:image" content="'.$metaimage.'" />';
	}
}

function get_page_extra_body()
{
	global $_body, $_set;
	if (!empty($_body))
		for ($i=0; $i<sizeof($_body); $i++)
			echo $_body[$i]."\n";
}

function get_errors()
{
	global $error;
	if (!empty($error))
	{
		echo "<div id='errors'>";
		for($i=0; $i<sizeof($error); $i++)
			echo "<li>$error[$i]</li>";
		echo "</ul></div>";
	}
}

function get_infos()
{
	global $info;
	if (!empty($info))
	{
		echo "<div id='infos'>";
		for($i=0; $i<sizeof($info); $i++)
			echo "<li>$info[$i]</li>";
		echo "</ul></div>";
	}
}

function set_pin($pin)	{ global $_SESSION; $_SESSION['entry_pin'] = $pin; }
function get_pin()	{ global $_SESSION; return isset($_SESSION['entry_pin']) ? $_SESSION['entry_pin'] : false; }

function theme_component($comp) {
	$cf = get_theme_lib().'/components/'.$comp.'.php';
	if (file_exists($cf))
		return $cf;
	return false;
}

function show_date($ts) { global $_set; return (!(int)date('Hi', $ts) ? date($_set['dateformatShort'], $ts) : date($_set['dateformat'], $ts)); }

$_title = array();
function addTitle($add) { global $_title; array_push($_title, htmlentities($add)); }

$_head = array();
$head_registered = array();
function addHead($add, $register = false) { global $_head, $head_registered; if (($register && !in_array($register, $head_registered)) || !$register) array_push($_head, $add); }

$_body = array();
$body_registered = array();
function addBody($add, $register = false) { global $_body, $body_registered; if (($register && !in_array($register, $body_registered)) || !$register) array_push($_body, $add); }

$description = false;
function addDescription($add) { global $description; if (!$description) $description = ''; $description .= str_replace(array('"', '\'', "\n", "\r\n", '&lt;', '&gt;'), '', strip_tags($add)).' '; }

function keywords() { global $description, $_set; $keywords = explode(' ', str_replace(array(',','?','.','!'), ' ', ($description ? $description : $_set['description']))); foreach($keywords AS $a => $b) { $val = trim($b); if (strlen($val) > 3) $keywords[$a] = $val; else unset($keywords[$a]); } return implode(',', array_unique($keywords)); }

$metaimage = false;
function addImage($add) { global $metaimage; $metaimage = $add; }

$headerimg = false;
function headerImage($url) { global $headerimg; if (strlen($url) > 3) $headerimg = $url; }

/* POST FUCKER */
function entry_replacer($in)
{
	global $_locale;
	$pattern[] = '#\[music=(.*?)\]#';
	$replace[] = '<iframe style="width: 100%; height: 10em; border: 0; padding: 0; margin: 0;" class="music" src="http://music.sandros.hu/shared/$1?volume=50"></iframe>';

	$pattern[] = '#\[youtube=(.*?)\]#';
	$replace[] = '<iframe style="width: 100%; height: 600px; border: 0; padding: 0; margin: 0;" class="youtube" src="http://www.youtube.com/embed/$1"></iframe>';

	$pattern[] = '#\[spoiler\](.*?)\[/spoiler\]#';
	$replace[] = '<div class="spoiler"><div class="spoiler_b"><button onclick="spoilerToggle($(this))">'.$_locale['show_hidden_content'].'</button><div style="display:none" class="spoiler_c">$1</div></div>';

	$pattern[] = '#\[spoiler=(.*?)\](.*?)\[/spoiler\]#';
	$replace[] = '<div class="spoiler"><div class="spoiler_b"><button onclick="spoilerToggle($(this))">$1</button><div style="display:none" class="spoiler_c">$2</div></div>';


	return preg_replace($pattern, $replace, $in);
}

function entry_show_init($in, $slug, $flink = false)
{
	global $_locale;

	$in = entry_replacer($in);

	$search = array('@<script[^>]*?>.*?</script>@si',	// Strip out javascript
				   '@<style[^>]*?>.*?</style>@siU',		// Strip style tags properly
				   '@<![\s\S]*?--[ \t\n\r]*>@'			// Strip multi-line comments including CDATA
	);
	$in = preg_replace($search, '', $in);

	$in2 = explode('[[MORE]]', $in);
	if (isset($in2[1]) && strlen(trim($in2[1])))
		return $in2[0]."\n<p class='readmore'><a href='".get_entry_link($slug, $flink)."#readmore'>$_locale[entry_read_more]</a></p>\n";
	return $in;
}

function entry_show_all($in) { return str_replace('[[MORE]]', '<a name="readmore"></a>', entry_replacer($in)); }


/* OUTPUT FUCKER */
function regexp_locale($a)
{
	global $_locale;
	if (isset($_locale[$a[1]]))
		return $_locale[$a[1]];
	return $a[0];
}
function output_replacer($in)
{
	return preg_replace_callback('#\{locale:([a-zA-Z\-\_]+?)\}#', 'regexp_locale', $in);
}


/* LOGIN SYSTEM */
if (isset($_COOKIE['filtr_token']))
{
	require_once _FS_PATH.'includes/filtr.class.php';

	$filtr = new filtrLogin();
	$filtr->cache = '/tmp/';
	$filtr->setAppid($_set['filtr_appid']);
	$filtr->setApptoken($_set['filtr_apptoken']);
	$filtr->setToken($_COOKIE['filtr_token']);
    $filtr->Login(); 

	if ($filtr->status())
	{
		$filtr = $filtr->getData();
		$user = new user($filtr['link'], $filtr);
		if ($user)
		{
			$user = $user->data;
			define('LOGGEDIN', true);
		}
		unset($filtr);
	}
}

if (isset($_GET['logout']))
{
	setcookie('filtr_token', '', null, '/');
	redirect();
}

if (!defined('LOGGEDIN'))
	define('LOGGEDIN', false);