Add new directory structure. Tags will contain current and past releases, and stable will contain any bug fixes to the current stable release so users won't have to get the potentially broken trunk build to fix a screwup in stable.

Trunk updated to 0.9

git-svn-id: http://kusabax.cultnet.net/svn/repo/stable@176 73d99b7e-4f53-4972-b7b7-2ecd3c4d89ee
This commit is contained in:
Sazpaimon committed 2009-05-27 06:37:50 +00:00
commit 88bacfad9c
316 files changed
+79806

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
<?php
function clearBlotterCache() {
if (KU_APC) {
apc_delete('blotter|all');
apc_delete('blotter|last4');
}
}
/**
* Clear cache for the supplied post ID of the supplied board
*
* @param integer $id Post ID
* @param string $board Board name
*/
function clearPostCache($id, $board) {
global $tc_db;
if (KU_APC) {
apc_delete('post|' . $board . '|' . $id);
}
$tc_db->Execute("DELETE FROM `" . KU_DBPREFIX . "reports` WHERE `postid` = " . $id . " AND `board` = " . $tc_db->qstr($board));
}
?>
+136
View File
@@ -0,0 +1,136 @@
<?php
function getQuoteIds($quote, $replies = false) {
$rangeids_validated = array();
if (strpos($quote, ',') !== false) {
$postids = split(',', $quote);
} else {
$postids = array($quote);
}
$i = 0;
foreach ($postids as $postid) {
if (strpos($postid, 'l') === 0 && $replies !== false) {
if (strlen($postid) > 1) {
$last_posts_to_fetch = substr($postid, 1);
if ($last_posts_to_fetch >= 1) {
$last_posts_to_fetch = min($last_posts_to_fetch, $replies);
$min_posts_to_fetch = max((($replies + 1) - $last_posts_to_fetch), 1);
if ($min_posts_to_fetch > 1) {
$min_posts_to_fetch++;
}
$lastposts = range($min_posts_to_fetch, ($replies + 1));
$key = array_search($postid, $postids, true);
array_insert($postids, $key, $lastposts);
$key = array_search($postid, $postids, true);
if ($key !== false) {
unset($postids[$key]);
}
}
}
}
if (strpos($postid, '-') !== false) {
$range_processed = Array();
$rangeids = split('-', $postid);
if (count($rangeids) == 2) {
if(empty($rangeids[1])){
$postids['BETWEEN'][$i][] = 0;
$postids['BETWEEN'][$i][] = $rangeids[0];
}
else {
$postids['BETWEEN'][$i][] = $rangeids[0];
$postids['BETWEEN'][$i][] = $rangeids[1];
}
$i++;
}
}
if (strpos($postid, 'r') === 0 && $replies !== false) {
if (strlen($postid) > 1) {
$random_posts_to_fetch = substr($postid, 1);
if ($random_posts_to_fetch >= 1) {
$randposts = array();
//$random_posts_to_fetch = min($random_posts_to_fetch, $replies);
for ($i=0;$i<$random_posts_to_fetch;$i++) {
$postinserted = false;
while (!$postinserted) {
$randpost = rand(1, $replies);
//if (!in_array($randpost, $randposts)) {
$randposts[] = $randpost;
$postinserted = true;
//}
}
}
$key = array_search($postid, $postids, true);
array_insert($postids, $key, $randposts);
$key = array_search($postid, $postids, true);
if ($key !== false) {
unset($postids[$key]);
}
}
}
}
}
return $postids;
}
function array_insert(&$array, $position, $insert_array) {
if (!is_int($position)) {
$i = 0;
foreach ($array as $key => $value) {
if ($key == $position) {
$position = $i;
break;
}
$i++;
}
}
$first_array = array_splice($array, 0, $position);
$array = array_merge($first_array, $insert_array, $array);
}
function cleanBoardName($board) {
return trim(str_replace('/', '', str_replace('|', '', str_replace(' ', '', $board))));
}
/**
* Convert a board ID to a board name
*
* @param integer $boardid Board ID
* @return string Board directory
*/
function boardid_to_dir($boardid) {
global $tc_db;
$query = "SELECT `name` FROM `".KU_DBPREFIX."boards` WHERE `id` = ".$tc_db->qstr($boardid)."";
$results = $tc_db->SelectLimit($query, 1);
if (count($results)>0) {
foreach($results AS $line) {
return $line['name'];
}
}
}
/**
* Calculate the number of pages which will be needed for the supplied number of posts
*
* @param integer $boardtype Board type
* @param integer $numposts Number of posts
* @return integer Number of pages required
*/
function calculatenumpages($boardtype, $numposts) {
if ($boardtype==1) {
return (floor($numposts/KU_THREADSTXT));
} elseif ($boardtype==3) {
return (floor($numposts/30));
}
return (floor($numposts/KU_THREADS));
}
?>
+4
View File
@@ -0,0 +1,4 @@
<?php
/* Place any functions you create here. Note that this is not meant for module functions, which should be placed in the module's php file. */
?>
+169
View File
@@ -0,0 +1,169 @@
<?php
/**
* Recursively delete a directory
*
* @param string $path Intial path to delete
*/
function removeDir($path) {
$normal_files = glob($path . "*");
$hidden_files = glob($path . "\.?*");
$all_files = array_merge($normal_files, $hidden_files);
foreach ($all_files as $file) {
/* Skip pseudo links to current and parent dirs (./ and ../). */
if (preg_match("/(\.|\.\.)$/", $file))
{
continue;
}
if (is_file($file) === TRUE) {
/* Remove each file in this Directory */
unlink($file);
echo _gettext('Removed File').': '. $file . "<br />";
}
else if (is_dir($file) === TRUE) {
/* If this Directory contains a Subdirectory, run this Function on it */
removeDir($file);
}
}
/* Remove Directory once Files have been removed (If Exists) */
if (is_dir($path) === TRUE) {
rmdir($path);
echo '<br />'. _gettext('Removed Directory').': ' . $path . "<br /><br />";
}
}
/**
* Remove a board
*
* @param string $dir Directory to remove
* @return boolean Result
*/
function removeBoard($dir){
global $tc_db;
if(!isset($GLOBALS['remerror'])) {
$GLOBALS['remerror'] = false;
}
if($handle = opendir(KU_BOARDSDIR . $dir)){ /* If the folder exploration is sucsessful, continue */
while (false !== ($file = readdir($handle))){ /* As long as storing the next file to $file is successful, continue */
$path = $dir . '/' . $file;
if(is_file(KU_BOARDSDIR . $path)){
if(!unlink(KU_BOARDSDIR . $path)){
echo '<u><font color="red">'.sprintf(_gettext('"%s" could not be deleted. This may be due to a permissions problem.</u><br />Directory cannot be deleted until all files are deleted.'), $path).'</font><br />';
$GLOBALS['remerror'] = true;
return false;
}
} else
if(is_dir(KU_BOARDSDIR . $path) && substr($file, 0, 1) != '.'){
removeBoard($path);
@rmdir(KU_BOARDSDIR . $path);
}
}
closedir($handle); /* Close the folder exploration */
}
if(!$GLOBALS['remerror']) /* If no errors occured, delete the now empty directory */
if(!rmdir(KU_BOARDSDIR . $dir)){
echo '<strong><font color="red">'.sprintf(_gettext('Could not remove directory "%s". This may be due to a permissions problem.'),$dir).'</font></strong><br />'.$GLOBALS['remerror'];
return false;
} else
return true;
return false;
}
/*
------------ lixlpixel recursive PHP functions -------------
recursive_directory_size( directory, human readable format )
expects path to directory and optional TRUE / FALSE
PHP has to have the rights to read the directory you specify
and all files and folders inside the directory to count size
if you choose to get human readable format,
the function returns the filesize in bytes, KB and MB
------------------------------------------------------------
to use this function to get the filesize in bytes, write:
recursive_directory_size('path/to/directory/to/count');
to use this function to get the size in a nice format, write:
recursive_directory_size('path/to/directory/to/count',TRUE);
*/
/**
* Find the size of a directory, including any subdirectories
*
* @param string $directory Directory
* @param boolean $format Format
* @return array Size/number of files
*/
function recursive_directory_size($directory, $format=FALSE)
{
$size = 0;
$files = 0;
/* If the path has a slash at the end we remove it here */
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
/* If the path is not valid or is not a directory ... */
if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory))
{
/* ... We return -1 and exit the function */
return -1;
}
/* We open the directory */
if($handle = opendir($directory))
{
/* And scan through the items inside */
while(($file = readdir($handle)) !== false)
{
/* We build the new path */
$path = $directory.'/'.$file;
/* If the filepointer is not the current directory or the parent directory */
if($file != '.' && $file != '..')
{
/* If the new path is a file */
if(is_file($path))
{
/* We add the filesize to the total size */
$size += filesize($path);
$files++;
/* If the new path is a directory */
}elseif(is_dir($path))
{
/* If $format is set to true, follow the directory and recalculate from there */
if ($format) {
/* We call this function with the new path */
$handlesize = recursive_directory_size($path);
if (is_int($handlesize)) {
/* If the function returns more than zero */
if($handlesize >= 0)
{
/* We add the result to the total size */
$size += $handlesize;
/* Else we return -1 and exit the function */
}else{
return -1;
}
/* Else we return -1 and exit the function */
}else{
return -1;
}
}
}
}
}
/* Close the directory */
closedir($handle);
}
/* Return the total filesize in bytes */
return array($size,$files);
}
?>
+44
View File
@@ -0,0 +1,44 @@
<?php
/*
* Common encryption functions
*
* Allow for more advanced encryption using the random seed set in the
* configuration.
*/
function get_rnd_iv($iv_len) {
$iv = '';
while ($iv_len-- > 0) {
$iv .= chr(mt_rand() & 0xff);
}
return $iv;
}
function md5_encrypt($plain_text, $password, $iv_len = 16) {
$plain_text .= "\x13";
$n = strlen($plain_text);
if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));
$i = 0;
$enc_text = get_rnd_iv($iv_len);
$iv = substr($password ^ $enc_text, 0, 512);
while ($i < $n) {
$block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
$enc_text .= $block;
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return base64_encode($enc_text);
}
function md5_decrypt($enc_text, $password, $iv_len = 16) {
$enc_text = base64_decode($enc_text);
$n = strlen($enc_text);
$i = $iv_len;
$plain_text = '';
$iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
while ($i < $n) {
$block = substr($enc_text, $i, 16);
$plain_text .= $block ^ pack('H*', md5($iv));
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return preg_replace('/\\x13\\x00*$/', '', $plain_text);
}
?>
+107
View File
@@ -0,0 +1,107 @@
<?php
function getBlotter($all = false) {
global $tc_db;
if (KU_APC) {
if ($all) {
$cache_blotter = apc_fetch('blotter|all');
} else {
$cache_blotter = apc_fetch('blotter|last4');
}
if ($cache_blotter !== false) {
return $cache_blotter;
}
}
$output = '';
if ($all) {
$limit = '';
} else {
$limit = ' LIMIT 4';
}
$results = $tc_db->GetAll("SELECT * FROM `" . KU_DBPREFIX . "blotter` ORDER BY `id` DESC" . $limit);
if (count($results) > 0) {
if ($all) {
$output .= '<pre>';
}
foreach ($results as $line) {
if ($all && $line['important'] == 1) {
$output .= '<font style="color: red;">';
} elseif (!$all) {
$output .= '<li class="blotterentry" style="display: none;">' . "\n";
if ($line['important'] == 1) {
$output .= ' <span style="color: red;">' . "\n" . ' ';
}
$output .= ' ';
}
$output .= date('m/d/y', $line['at']) . ' - ' . $line['message'];
if ($all && $line['important'] == 1) {
$output .= '</font>' . "\n";
} elseif (!$all) {
$output .= "\n";
if ($line['important'] == 1) {
$output .= ' </span>' . "\n";
}
$output .= '</li>';
} else {
$output .= "\n";
}
$output .= "\n";
}
if ($all) {
$output .= '</pre>';
}
}
if (KU_APC) {
if ($all) {
apc_store('blotter|all', $output);
} else {
apc_store('blotter|last4', $output);
}
}
return $output;
}
function getBlotterLastUpdated() {
global $tc_db;
return $tc_db->GetOne("SELECT `at` FROM `" . KU_DBPREFIX . "blotter` ORDER BY `id` DESC LIMIT 1");
}
/**
* Gets information about the filetype provided, which is specified in the manage panel
*
* @param string $filetype Filetype
* @return array Filetype image, width, and height
*/
function getfiletypeinfo($filetype) {
global $tc_db;
$return = '';
if (KU_APC) {
$return = apc_fetch('filetype|' . $filetype);
}
if ($return != '') {
return unserialize($return);
}
$results = $tc_db->GetAll("SELECT `image`, `image_w`, `image_h` FROM `" . KU_DBPREFIX . "filetypes` WHERE `filetype` = " . $tc_db->qstr($filetype) . " LIMIT 1");
if (count($results) > 0) {
foreach($results AS $line) {
$return = array($line['image'],$line['image_w'],$line['image_h']);
}
} else {
/* No info was found, return the generic icon */
$return = array('generic.png',48,48);
}
if (KU_APC) {
apc_store('filetype|' . $filetype, serialize($return), 600);
}
return $return;
}
?>
+91
View File
@@ -0,0 +1,91 @@
<?php
function changeLocale($newlocale) {
global $CURRENTLOCALE, $EMULATEGETTEXT, $text_domains;
$CURRENTLOCALE = $newlocale;
$EMULATEGETTEXT = 1;
_textdomain('kusaba');
_setlocale(LC_ALL, $newlocale);
_bindtextdomain('kusaba', KU_ROOTDIR . 'inc/lang', $newlocale);
_bind_textdomain_codeset('kusaba', KU_CHARSET);
}
function exitWithErrorPage($errormsg, $extended = '') {
global $dwoo, $dwoo_data, $board_class;
if (!isset($dwoo)) {
require_once KU_ROOTDIR . 'lib/dwoo.php';
}
if (!isset($board_class)) {
require_once KU_ROOTDIR . 'inc/classes/board-post.class.php';
$board_class = new Board('');
}
$dwoo_data->assign('styles', explode(':', KU_MENUSTYLES));
$dwoo_data->assign('errormsg', $errormsg);
if ($extended != '') {
$dwoo_data->assign('errormsgext', '<br /><div style="text-align: center;font-size: 1.25em;">' . $extended . '</div>');
} else {
$dwoo_data->assign('errormsgext', $extended);
}
echo $dwoo->get(KU_TEMPLATEDIR . '/error.tpl', $dwoo_data);
die();
}
/**
* Add an entry to the modlog
*
* @param string $entry Entry text
* @param integer $category Category to file under. 0 - No category, 1 - Login, 2 - Cleanup/rebuild boards and html files, 3 - Board adding/deleting, 4 - Board updates, 5 - Locking/stickying, 6 - Staff changes, 7 - Thread deletion/post deletion, 8 - Bans, 9 - News, 10 - Global changes, 11 - Wordfilter
* @param string $forceusername Username to force as the entry username
*/
function management_addlogentry($entry, $category = 0, $forceusername = '') {
global $tc_db;
$username = ($forceusername == '') ? $_SESSION['manageusername'] : $forceusername;
if ($entry != '') {
$tc_db->Execute("INSERT INTO `" . KU_DBPREFIX . "modlog` ( `entry` , `user` , `category` , `timestamp` ) VALUES ( " . $tc_db->qstr($entry) . " , '" . $username . "' , " . $tc_db->qstr($category) . " , '" . time() . "' )");
}
if (KU_RSS) {
require_once(KU_ROOTDIR . 'inc/classes/rss.class.php');
$rss_class = new RSS();
print_page(KU_BOARDSDIR . 'modlogrss.xml', $rss_class->GenerateModLogRSS($entry), '');
}
}
function sendStaffMail($subject, $message) {
$emails = split(':', KU_APPEAL);
$expires = ($line['until'] > 0) ? date("F j, Y, g:i a", $line['until']) : 'never';
foreach ($emails as $email) {
@mail($email, $subject, $message, 'From: "' . KU_NAME . '" <kusaba@noreply' . KU_DOMAIN . '>' . "\r\n" . 'Reply-To: kusaba@noreply' . KU_DOMAIN . "\r\n" . 'X-Mailer: kusaba' . KU_VERSION . '/PHP' . phpversion());
}
}
/* Depending on the configuration, use either a meta refresh or a direct header */
function do_redirect($url, $ispost = false, $file = '') {
global $board_class;
$headermethod = true;
if ($headermethod) {
if ($ispost) {
header('Location: ' . $url);
} else {
die('<meta http-equiv="refresh" content="1;url=' . $url . '">');
}
} else {
if ($ispost && $file != '') {
echo sprintf(_gettext('%s uploaded.'), $file) . ' ' . _gettext('Updating pages.');
} elseif ($ispost) {
echo _gettext('Post added.') . ' ' . _gettext('Updating pages.'); # TEE COME BACK
} else {
echo '---> ---> --->';
}
die('<meta http-equiv="refresh" content="1;url=' . $url . '">');
}
}
?>
+117
View File
@@ -0,0 +1,117 @@
<?php
/*
* This file is part of kusaba.
*
* kusaba 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 2 of the License, or (at your option) any later
* version.
*
* kusaba 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
* kusaba; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* Module functions
*
* Provides module and hook functionality
*
* @package kusaba
*/
function hook_process($hookname, $data) {
global $hooks;
if (is_array($hooks[$hookname])) {
foreach ($hooks[$hookname] as $hook) {
$data = module_call_function($hook, 'process_' . $hookname, $data);
}
}
return $data;
}
function modules_load_all() {
foreach (modules_list() as $module) {
module_load($module);
}
}
/* Fetch the names of the modules in the inc/modules/ directory */
function modules_list() {
$modules = array();
if ($modules_handle = opendir(KU_ROOTDIR . 'inc/modules')) {
while (false !== ($file = readdir($modules_handle))) {
/* We don't want hidden files, nor . or .. */
if ($file != '.' && $file != '..' && !is_dir($file) && strpos($file, '.php') != false) {
$modules[] = substr($file, 0, -4);
}
}
} else {
echo _gettext('Unable to open the modules directory!');
}
return $modules;
}
/* Load a module's script and call its initialization function */
function module_load($module) {
global $modules_loaded;
if (!in_array($module, $modules_loaded)) {
/* Include the module file */
include(KU_ROOTDIR . 'inc/modules/' . $module . '.php');
/* Call the initialization function */
module_call_function($module, 'init');
/* Add this module to the loaded modules list */
$modules_loaded[] = $module;
/* The module was loaded, return true to show that it was a success */
return true;
}
return false;
}
/* Call a module's function, such as module_init() */
function module_call_function($module, $function, $data = null) {
if (function_exists($module . '_' . $function)) {
if ($data == null) {
return call_user_func($module . '_' . $function);
}
return call_user_func($module . '_' . $function, $data);
}
return false;
}
function module_setting_get($module, $key) {
global $tc_db;
$query = "SELECT `value` FROM `".KU_DBPREFIX."module_settings` WHERE `module` = ".$tc_db->qstr($module)." AND `key` = ".$tc_db->qstr($key)." LIMIT 1";
$result = $tc_db->GetOne($query);
return $result;
}
function module_setting_set($module, $key, $value, $type = 'string') {
global $tc_db;
$exists = $tc_db->GetOne("SELECT COUNT(*) FROM `".KU_DBPREFIX."module_settings` WHERE `module` = ".$tc_db->qstr($module)." AND `key` = ".$tc_db->qstr($key)." LIMIT 1");
if ($exists > 0) {
$result = $tc_db->Execute("UPDATE `".KU_DBPREFIX."module_settings` SET `value` = ".$tc_db->qstr($value).") WHERE `module` = ".$tc_db->qstr($module)." AND `key` = ".$tc_db->qstr($key)."");
} else {
$result = $tc_db->Execute("INSERT INTO `".KU_DBPREFIX."module_settings` (`module` , `key` , `value` , `type`) VALUES (".$tc_db->qstr($module).", ".$tc_db->qstr($key).", ".$tc_db->qstr($value).", ".$tc_db->qstr($type).")");
}
return $result;
}
?>
+81
View File
@@ -0,0 +1,81 @@
<?php
/**
* Format an amount of bytes to a better looking representation of the size
*
* @param integer $number Bytes
* @return string Formatted amount
*/
function ConvertBytes($number) {
$len = strlen($number);
if($len < 4) {
return sprintf("%dB", $number);
} elseif($len <= 6) {
return sprintf("%0.2fKB", $number/1024);
} elseif($len <= 9) {
return sprintf("%0.2fMB", $number/1024/1024);
}
return sprintf("%0.2fGB", $number/1024/1024/1024);
}
function timeDiff($timestamp,$detailed=false, $max_detail_levels=8, $precision_level='second'){
$now = time();
#If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = '' : $action = 'ago';
# Set the periods of time
$periods = array(_gettext('second'), _gettext('minute'), _gettext('hour'), _gettext('day'), _gettext('week'), _gettext('month'), _gettext('year'), _gettext('decade'));
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
$diff = ($action == '' ? $timestamp - $now : $now - $timestamp);
$prec_key = array_search($precision_level,$periods);
# round diff to the precision_level
$diff = round(($diff/$lengths[$prec_key]))*$lengths[$prec_key];
# if the diff is very small, display for ex "just seconds ago"
if ($diff <= 10) {
$periodago = max(0,$prec_key-1);
$agotxt = $periods[$periodago].'s';
return "$agotxt $action";
}
# Go from decades backwards to seconds
$time = "";
for ($i = (sizeof($lengths) - 1); $i>=0; $i--) {
if ($i > 0) {
if($diff > $lengths[$i-1] && ($max_detail_levels > 0)) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc
$time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' '); # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
$max_detail_levels--;
}
}
}
# Basic error checking.
if($time == "") {
return "Error-- Unable to calculate time.";
} else {
if ($action != '') {
return $time.$action;
}
return $time;
}
}
function microtime_float() {
return array_sum(explode(' ', microtime()));
}
function formatJapaneseNumbers($input) {
$patterns = array('/1/', '/2/', '/3/', '/4/', '/5/', '/6/', '/7/', '/8/', '/9/', '/0/');
$replace = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
return preg_replace($patterns, $replace, $input);
}
?>
+29
View File
@@ -0,0 +1,29 @@
<?php
/**
* Generate the list of pages, linking to each
*
* @param integer $boardpage Current board page
* @param integer $pages Number of pages
* @param string $board Board directory
* @return string Generated page list
*/
/* <3 coda for this wonderful snippet
print $contents to $filename by using a temporary file and renaming it */
function print_page($filename, $contents, $board) {
global $tc_db;
$tempfile = tempnam(KU_BOARDSDIR . $board . '/res', 'tmp'); /* Create the temporary file */
$fp = fopen($tempfile, 'w');
fwrite($fp, $contents);
fclose($fp);
/* If we aren't able to use the rename function, try the alternate method */
if (!@rename($tempfile, $filename)) {
copy($tempfile, $filename);
unlink($tempfile);
}
chmod($filename, 0664); /* it was created 0600 */
}
?>
+22
View File
@@ -0,0 +1,22 @@
<?php
function getCWebPath() {
if (KU_WEBCORAL != '') {
return KU_WEBCORAL . '/';
}
return KU_WEBPATH . '/';
}
function getCLBoardPath($board = '', $loadbalanceurl = '', $archivedir = '') {
global $board_class;
if ($loadbalanceurl == '') {
if (KU_BOARDSCORAL != '' && $archivedir == '') {
return KU_BOARDSCORAL . '/' . $board;
} else {
return KU_BOARDSPATH . '/' . $board . $archivedir;
}
} elseif ($board != '') {
return $loadbalanceurl;
}
}
?>
+255
View File
@@ -0,0 +1,255 @@
<?php
/**
* Display the embedded video
*
* @param array $post Post data
* @return string Embedded video
*/
function embeddedVideoBox($post) {
global $tc_db;
$results = $tc_db->GetAll("SELECT HIGH_PRIORITY * FROM `" . KU_DBPREFIX . "embeds`");
$output = '<span style="float: left;">' . "\n";
foreach ($results as $line) {
if ($post['file_type'] == $line['filetype']) {
$code = $line['code'];
/*$width = $line['width'];
$height = $line['height'];*/
$replace = array('SET_HEIGHT', 'SET_WIDTH', 'EMBED_ID');
$trueval = array($line['height'], $line['width'], $post['file']);
$code = str_replace($replace, $trueval, $code);
$output .= $code;
}
}
$output .= '</span>&nbsp;' . "\n";
return $output;
}
/**
* Check if the supplied md5 file hash is currently recorded inside of the database, attached to a non-deleted post
*/
function checkMd5($md5, $board, $boardid) {
global $tc_db;
$matches = $tc_db->GetAll("SELECT `id`, `parentid` FROM `".KU_DBPREFIX."posts` WHERE `boardid` = " . $boardid . " AND `IS_DELETED` = 0 AND `file_md5` = ".$tc_db->qstr($md5)." LIMIT 1");
if (count($matches) > 0) {
$real_parentid = ($matches[0][1] == 0) ? $matches[0][0] : $matches[0][1];
return array($real_parentid, $matches[0][0]);
}
return false;
}
/* Image handling */
/**
* Create a thumbnail
*
* @param string $name File to be thumbnailed
* @param string $filename Path to place the thumbnail
* @param integer $new_w Maximum width
* @param integer $new_h Maximum height
* @return boolean Success/fail
*/
function createThumbnail($name, $filename, $new_w, $new_h) {
if (KU_THUMBMETHOD == 'imagemagick') {
$convert = 'convert ' . escapeshellarg($name);
if (!KU_ANIMATEDTHUMBS) {
$convert .= '[0] ';
}
$convert .= ' -resize ' . $new_w . 'x' . $new_h . ' -quality ';
if (substr($filename, 0, -3) != 'gif') {
$convert .= '70';
} else {
$convert .= '90';
}
$convert .= ' ' . escapeshellarg($filename);
exec($convert);
if (is_file($filename)) {
return true;
} else {
return false;
}
} elseif (KU_THUMBMETHOD == 'gd') {
$system=explode(".", $filename);
$system = array_reverse($system);
if (preg_match("/jpg|jpeg/", $system[0])) {
$src_img=imagecreatefromjpeg($name);
} else if (preg_match("/png/", $system[0])) {
$src_img=imagecreatefrompng($name);
} else if (preg_match("/gif/", $system[0])) {
$src_img=imagecreatefromgif($name);
} else {
return false;
}
if (!$src_img) {
exitWithErrorPage(_gettext('Unable to read uploaded file during thumbnailing.'), _gettext('A common cause for this is an incorrect extension when the file is actually of a different type.'));
}
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if ($old_x > $old_y) {
$percent = $new_w / $old_x;
} else {
$percent = $new_h / $old_y;
}
$thumb_w = round($old_x * $percent);
$thumb_h = round($old_y * $percent);
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
fastImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y, $system);
if (preg_match("/png/", $system[0])) {
if (!imagepng($dst_img,$filename,0,PNG_ALL_FILTERS) ) {
echo 'unable to imagepng.';
return false;
}
} else if (preg_match("/jpg|jpeg/", $system[0])) {
if (!imagejpeg($dst_img, $filename, 70)) {
echo 'unable to imagejpg.';
return false;
}
} else if (preg_match("/gif/", $system[0])) {
if (!imagegif($dst_img, $filename)) {
echo 'unable to imagegif.';
return false;
}
}
imagedestroy($dst_img);
imagedestroy($src_img);
return true;
}
return false;
}
/* Author: Tim Eckel - Date: 12/17/04 - Project: FreeRingers.net - Freely distributable. */
/**
* Faster method than only calling imagecopyresampled()
*
* @return boolean Success/fail
*/
function fastImageCopyResampled(&$dst_image, &$src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $system, $quality = 3) {
/*
Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5.
1 = Up to 600 times faster. Poor results, just uses imagecopyresized but removes black edges.
2 = Up to 95 times faster. Images may appear too sharp, some people may prefer it.
3 = Up to 60 times faster. Will give high quality smooth results very close to imagecopyresampled.
4 = Up to 25 times faster. Almost identical to imagecopyresampled for most images.
5 = No speedup. Just uses imagecopyresampled, highest quality but no advantage over imagecopyresampled.
*/
if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; }
if (preg_match("/png/", $system[0]) || preg_match("/gif/", $system[0])) {
$colorcount = imagecolorstotal($src_image);
if ($colorcount <= 256 && $colorcount != 0) {
imagetruecolortopalette($dst_image,true,$colorcount);
imagepalettecopy($dst_image,$src_image);
$transparentcolor = imagecolortransparent($src_image);
imagefill($dst_image,0,0,$transparentcolor);
imagecolortransparent($dst_image,$transparentcolor);
}
else {
imageAlphaBlending($dst_image, false);
imageSaveAlpha($dst_image, true); //If the image has Alpha blending, lets save it
}
}
if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {
$temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);
if (preg_match("/png/", $system[0])) {
$background = imagecolorallocate($temp, 0, 0, 0);
ImageColorTransparent($temp, $background); // make the new temp image all transparent
imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel
}
imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);
imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);
imagedestroy ($temp);
}
else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
return true;
}
/*
Link validator
Will use cURL to attempt to visit a webpage, and then return based upon how the
request was handled. Used for embedded videos to validate the ID is existant.
Thanks phadeguy - http://www.zend.com/codex.php?id=1256&single=1
expects a link url as string
returns an array of three elements:
return_array[0] = HTTP version
return_array[1] = Returned error number (200, 404, etc)
return_array[2] = Returned error text ("OK", "File Not Found", etc) */
function check_link($link) {
$main = array();
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $link);
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_NOBODY, 1);
// curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, 10);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
ob_start();
curl_exec ($ch);
$stuff = ob_get_contents();
ob_end_clean();
curl_close ($ch);
$parts = split("n",$stuff,2);
$main = split(" ",$parts[0],3);
return $main;
}
/**
* Trim the threads to the page limit and delete posts which are older than limited
*/
function TrimToPageLimit($board) {
global $tc_db;
if ($board['maxage'] != 0) {
// If the maximum thread age setting is not zero (do not delete old threads), find posts which are older than the limit, and delete them
$results = $tc_db->GetAll("SELECT `id`, `timestamp` FROM `".KU_DBPREFIX."posts` WHERE `boardid` = " . $board['id'] . " AND `IS_DELETED` = 0 AND `parentid` = 0 AND `stickied` = 0 AND ((`timestamp` + " . ($board['maxage']*3600) . ") < " . time() . ")");
foreach($results AS $line) {
// If it is older than the limit
$post_class = new Post($line['id'], $board['name'], $board['id']);
$post_class->Delete(true);
}
}
if ($board['maxpages'] != 0) {
// If the maximum pages setting is not zero (do not limit pages), find posts which are over the limit, and delete them
$results = $tc_db->GetAll("SELECT `id`, `stickied` FROM `".KU_DBPREFIX."posts` WHERE `boardid` = " . $board['id'] . " AND `IS_DELETED` = 0 AND `parentid` = 0");
$results_count = count($results);
if (calculatenumpages($board['type'], $results_count) >= $board['maxpages']) {
$board['maxthreads'] = ($board['maxpages'] * KU_THREADS);
$numthreadsover = ($results_count - $board['maxthreads']);
if ($numthreadsover > 0) {
$resultspost = $tc_db->GetAll("SELECT `id`, `stickied` FROM `".KU_DBPREFIX."posts` WHERE `boardid` = " . $board['id'] . " AND `IS_DELETED` = 0 AND `parentid` = 0 AND `stickied` = 0 ORDER BY `bumped` ASC LIMIT " . $numthreadsover);
foreach($resultspost AS $linepost) {
$post_class = new Post($linepost['id'], $board['name'], $board['id']);
$post_class->Delete(true);
}
}
}
}
// If the thread was marked for deletion more than two hours ago, delete it
$results = $tc_db->GetAll("SELECT `id` FROM `".KU_DBPREFIX."posts` WHERE `boardid` = " . $board['id'] . " AND `IS_DELETED` = 0 AND `parentid` = 0 AND `stickied` = 0 AND `deleted_timestamp` > 0 AND (`deleted_timestamp` <= " . time() . ")");
foreach($results AS $line) {
// If it is older than the limit
$post_class = new Post($line['id'], $board['name'], $board['id']);
$post_class->Delete(true);
}
}
?>
+312
View File
@@ -0,0 +1,312 @@
<?php
/**
* Format the display of the name and tripcode of a post
*
* @param string $name Name used in post
* @param string $email Email used in post
* @param string $tripcode Tripcode used in post
* @return string Generated name and tripcode html
*/
function formatDate($timestamp, $type = 'post', $locale = 'en', $email = '') {
$output = '';
if ($email != '') {
$output .= '<a href="mailto:' . $email . '">';
}
if ($type == 'post') {
if ($locale == 'ja') {
/* Format the timestamp japanese style */
$fulldate = strftime ("%Yy%mm%dd(DAYOFWEEK) %HH%MM%SS", $timestamp);
$dayofweek = strftime('%a', $timestamp);
/* I don't like this method, but I can't rely on PHP's locale settings to do it for me... */
switch ($dayofweek) {
case 'Sun':
$dayofweek = '&#26085;';
break;
case 'Mon':
$dayofweek = '&#26376;';
break;
case 'Tue':
$dayofweek = '&#28779;';
break;
case 'Wed':
$dayofweek = '&#27700;';
break;
case 'Thu':
$dayofweek = '&#26408;';
break;
case 'Fri':
$dayofweek = '&#37329;';
break;
case 'Sat':
$dayofweek = '&#22303;';
break;
default:
// The date must be in the correct language already, so let's convert it to unicode if it isn't already.
$dayofweek = mb_convert_encoding($dayofweek, "UTF-8", "JIS, eucjp-win, sjis-win");
break;
}
$fulldate = formatJapaneseNumbers($fulldate);
//Convert the symbols for year, month, etc to unicode equivalents. We couldn't do this above beause the numbers would be formatted to japanese.
$fulldate = str_replace(array("y","m","d","H","M","S"), array("&#24180;","&#26376;","&#26085;","&#26178;","&#20998;","&#31186;"), $fulldate);
$fulldate = str_replace('DAYOFWEEK', $dayofweek, $fulldate);
return $output.$fulldate.(($email != '') ? ('</a>') : (""));
} else {
/* Format the timestamp english style */
return $output.date('y/m/d(D)H:i', $timestamp).(($email != '') ? ('</a>') : (""));
}
}
return $output.date('y/m/d(D)H:i', $timestamp).(($email != '') ? ('</a>') : (""));
}
/**
* Format the provided input into a reflink, which follows the Japanese locale if it is set.
*/
function formatReflink($post_board, $post_thread_start_id, $post_id, $locale = 'en') {
$return = ' ';
$reflink_noquote = '<a href="' . KU_BOARDSFOLDER . $post_board . '/res/' . $post_thread_start_id . '.html#' . $post_id . '" onclick="return highlight(\'' . $post_id . '\');">';
$reflink_quote = '<a href="' . KU_BOARDSFOLDER . $post_board . '/res/' . $post_thread_start_id . '.html#i' . $post_id . '" onclick="return insert(\'>>' . $post_id . '\\n\');">';
if ($locale == 'ja') {
$return .= $reflink_quote . formatJapaneseNumbers($post_id) . '</a>' . $reflink_noquote . '番</a>';
} else {
$return .= $reflink_noquote . 'No.&nbsp;' . '</a>' . $reflink_quote . $post_id . '</a>';
}
return $return . "\n";
}
/**
* Calculate the different name and tripcode for the name field provided
*
* @param string $post_name Text entered in the Name field
* @return array Name and tripcode
*/
function calculateNameAndTripcode($post_name) {
global $tc_db;
if(ereg("(#|!)(.*)", $post_name, $regs)){
$cap = $regs[2];
$cap_full = '#' . $regs[2];
// {{{ Special tripcode check
$trips = unserialize(KU_TRIPS);
if (count($trips) > 0) {
if (isset($trips[$cap_full])) {
$forcedtrip = $trips[$cap_full];
return array(ereg_replace("(#)(.*)", "", $post_name), $forcedtrip);
}
}
// }}}
if (function_exists('mb_convert_encoding')) {
$recoded_cap = mb_convert_encoding($cap, 'SJIS', 'UTF-8');
if ($recoded_cap != '') {
$cap = $recoded_cap;
}
}
if (strpos($post_name, '#') === false) {
$cap_delimiter = '!';
} elseif (strpos($post_name, '!') === false) {
$cap_delimiter = '#';
} else {
$cap_delimiter = (strpos($post_name, '#') < strpos($post_name, '!')) ? '#' : '!';
}
if (ereg("(.*)(" . $cap_delimiter . ")(.*)", $cap, $regs_secure)) {
$cap = $regs_secure[1];
$cap_secure = $regs_secure[3];
$is_secure_trip = true;
} else {
$is_secure_trip = false;
}
$tripcode = '';
if ($cap != '') {
/* From Futabally */
$cap = strtr($cap, "&amp;", "&");
$cap = strtr($cap, "&#44;", ", ");
$salt = substr($cap."H.", 1, 2);
$salt = ereg_replace("[^\.-z]", ".", $salt);
$salt = strtr($salt, ":;<=>?@[\\]^_`", "ABCDEFGabcdef");
$tripcode = substr(crypt($cap, $salt), -10);
}
if ($is_secure_trip) {
if ($cap != '') {
$tripcode .= '!';
}
$secure_tripcode = md5($cap_secure . KU_RANDOMSEED);
if (function_exists('base64_encode')) {
$secure_tripcode = base64_encode($secure_tripcode);
}
if (function_exists('str_rot13')) {
$secure_tripcode = str_rot13($secure_tripcode);
}
$secure_tripcode = substr($secure_tripcode, 2, 10);
$tripcode .= '!' . $secure_tripcode;
}
$name = ereg_replace("(" . $cap_delimiter . ")(.*)", "", $post_name);
return array($name, $tripcode);
}
return $post_name;
}
/**
* Format a long message to be shortened if it exceeds the allowed length on a page
*
* @param string $message Post message
* @param string $board Board directory
* @param integer $threadid Thread ID
* @param boolean $page Is rendering for a page
* @return string The formatted message
*/
function formatLongMessage($message, $board, $threadid, $page) {
$output = '';
if ((strlen($message) > KU_LINELENGTH || count(explode('<br />', $message)) > 15) && $page) {
$message_exploded = explode('<br />', $message);
$message_shortened = '';
for ($i = 0; $i <= 14; $i++) {
if (isset($message_exploded[$i])) {
$message_shortened .= $message_exploded[$i] . '<br />';
}
}
if (strlen($message_shortened) > KU_LINELENGTH) {
$message_shortened = substr($message_shortened, 0, KU_LINELENGTH);
}
$message_shortened = closeOpenTags($message_shortened);
$output = $message_shortened . '<div class="abbrev">' . "\n" .
' ' . sprintf(_gettext('Message too long. Click %shere%s to view the full text.'), '<a href="' . KU_BOARDSFOLDER . $board . '/res/' . $threadid . '.html">', '</a>') . "\n" .
'</div>' . "\n";
} else {
$output .= $message . "\n";
}
return $output;
}
/* Thanks milianw - php.net */
/**
* Closes all HTML tags left open
*
* @param string $html HTML to be checked
* @return string HTML with all tags closed
*/
function closeOpenTags($html){
/* Put all opened tags into an array */
preg_match_all("#<([a-z]+)( .*)?(?!/)>#iU", $html, $result);
$openedtags=$result[1];
/* Put all closed tags into an array */
preg_match_all("#</([a-z]+)>#iU", $html, $result);
$closedtags=$result[1];
$len_opened = count($openedtags);
/* All tags are closed */
if(count($closedtags) == $len_opened){
return $html;
}
$openedtags = array_reverse($openedtags);
/* Close tags */
for($i=0;$i<$len_opened;$i++) {
if ($openedtags[$i]!='br') {
if (!in_array($openedtags[$i], $closedtags)){
$html .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]);
}
}
}
return $html;
}
/* By Darien Hager, Jan 2007 */
/**
* Find the string value of a pair of ords
*
* @param string $ords Ords
* @param string $encoding Encoding
* @return string String
*/
function ords_to_unistr($ords, $encoding = 'UTF-8'){
if (!function_exists('mb_convert_encoding')) {
return false;
}
/* Turns an array of ordinal values into a string of unicode characters */
$str = '';
for($i = 0; $i < sizeof($ords); $i++){
/* Pack this number into a 4-byte string
(Or multiple one-byte strings, depending on context.) */
$v = $ords[$i];
$str .= pack("N",$v);
}
$str = mb_convert_encoding($str,$encoding,"UCS-4BE");
return($str);
}
/**
* Find the ord value of a string
*
* @param string $str String
* @param string $encoding Encoding
* @return array Ords
*/
function unistr_to_ords($str, $encoding = 'UTF-8'){
if (!function_exists('mb_convert_encoding')) {
return false;
}
/* Turns a string of unicode characters into an array of ordinal values,
Even if some of those characters are multibyte. */
$str = mb_convert_encoding($str,"UCS-4BE",$encoding);
$ords = array();
/* Visit each unicode character */
for($i = 0; $i < mb_strlen($str,"UCS-4BE"); $i++){
/* Now we have 4 bytes. Find their total numeric value */
$s2 = mb_substr($str,$i,1,"UCS-4BE");
$val = unpack("N",$s2);
$ords[] = $val[1];
}
return($ords);
}
function processPost($id, $newthreadid, $oldthreadid, $board_from, $board_to, $boardid) {
global $tc_db;
$message = $tc_db->GetOne("SELECT `message` FROM " . KU_DBPREFIX . "posts WHERE `boardid` = " . $boardid . " AND `id` = " . $id . " LIMIT 1");
if ($message != '') {
$message_new = str_replace('/read.php/' . $board_from . '/' . $oldthreadid, '/read.php/' . $board_to . '/' . $newthreadid, $message);
if ($message_new != $message) {
$tc_db->GetOne("UPDATE " . KU_DBPREFIX . "posts SET `message` = " . $tc_db->qstr($message) . " WHERE `boardid` = " . $boardid . " AND `id` = " . $id);
}
}
}
?>
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* Run a greater than zero check on each ID in the array
*
* @param array $ids Array of thread IDs
*/
function isNormalUser($authority) {
if ($authority == 1 || $authority == 2) {
return false;
} else {
return true;
}
}
?>