hello github! 😘

This commit is contained in:
Abdulrahman
2018-01-09 02:09:07 +03:00
commit 7f4a4f6ff9
540 changed files with 70817 additions and 0 deletions

256
includes/CP1256.MAP Executable file
View File

@@ -0,0 +1,256 @@
0x000x0000
0x010x0001
0x020x0002
0x030x0003
0x040x0004
0x050x0005
0x060x0006
0x070x0007
0x080x0008
0x090x0009
0x0A0x000A
0x0B0x000B
0x0C0x000C
0x0D0x000D
0x0E0x000E
0x0F0x000F
0x100x0010
0x110x0011
0x120x0012
0x130x0013
0x140x0014
0x150x0015
0x160x0016
0x170x0017
0x180x0018
0x190x0019
0x1A0x001A
0x1B0x001B
0x1C0x001C
0x1D0x001D
0x1E0x001E
0x1F0x001F
0x200x0020
0x210x0021
0x220x0022
0x230x0023
0x240x0024
0x250x0025
0x260x0026
0x270x0027
0x280x0028
0x290x0029
0x2A0x002A
0x2B0x002B
0x2C0x002C
0x2D0x002D
0x2E0x002E
0x2F0x002F
0x300x0030
0x310x0031
0x320x0032
0x330x0033
0x340x0034
0x350x0035
0x360x0036
0x370x0037
0x380x0038
0x390x0039
0x3A0x003A
0x3B0x003B
0x3C0x003C
0x3D0x003D
0x3E0x003E
0x3F0x003F
0x400x0040
0x410x0041
0x420x0042
0x430x0043
0x440x0044
0x450x0045
0x460x0046
0x470x0047
0x480x0048
0x490x0049
0x4A0x004A
0x4B0x004B
0x4C0x004C
0x4D0x004D
0x4E0x004E
0x4F0x004F
0x500x0050
0x510x0051
0x520x0052
0x530x0053
0x540x0054
0x550x0055
0x560x0056
0x570x0057
0x580x0058
0x590x0059
0x5A0x005A
0x5B0x005B
0x5C0x005C
0x5D0x005D
0x5E0x005E
0x5F0x005F
0x600x0060
0x610x0061
0x620x0062
0x630x0063
0x640x0064
0x650x0065
0x660x0066
0x670x0067
0x680x0068
0x690x0069
0x6A0x006A
0x6B0x006B
0x6C0x006C
0x6D0x006D
0x6E0x006E
0x6F0x006F
0x700x0070
0x710x0071
0x720x0072
0x730x0073
0x740x0074
0x750x0075
0x760x0076
0x770x0077
0x780x0078
0x790x0079
0x7A0x007A
0x7B0x007B
0x7C0x007C
0x7D0x007D
0x7E0x007E
0x7F0x007F
0x800x20AC
0x810x067E
0x820x201A
0x830x0192
0x840x201E
0x850x2026
0x860x2020
0x870x2021
0x880x02C6
0x890x2030
0x8A0x0679
0x8B0x2039
0x8C0x0152
0x8D0x0686
0x8E0x0698
0x8F0x0688
0x900x06AF
0x910x2018
0x920x2019
0x930x201C
0x940x201D
0x950x2022
0x960x2013
0x970x2014
0x980x06A9
0x990x2122
0x9A0x0691
0x9B0x203A
0x9C0x0153
0x9D0x200C
0x9E0x200D
0x9F0x06BA
0xA00x00A0
0xA10x060C
0xA20x00A2
0xA30x00A3
0xA40x00A4
0xA50x00A5
0xA60x00A6
0xA70x00A7
0xA80x00A8
0xA90x00A9
0xAA0x06BE
0xAB0x00AB
0xAC0x00AC
0xAD0x00AD
0xAE0x00AE
0xAF0x00AF
0xB00x00B0
0xB10x00B1
0xB20x00B2
0xB30x00B3
0xB40x00B4
0xB50x00B5
0xB60x00B6
0xB70x00B7
0xB80x00B8
0xB90x00B9
0xBA0x061B
0xBB0x00BB
0xBC0x00BC
0xBD0x00BD
0xBE0x00BE
0xBF0x061F
0xC00x06C1
0xC10x0621
0xC20x0622
0xC30x0623
0xC40x0624
0xC50x0625
0xC60x0626
0xC70x0627
0xC80x0628
0xC90x0629
0xCA0x062A
0xCB0x062B
0xCC0x062C
0xCD0x062D
0xCE0x062E
0xCF0x062F
0xD00x0630
0xD10x0631
0xD20x0632
0xD30x0633
0xD40x0634
0xD50x0635
0xD60x0636
0xD70x00D7
0xD80x0637
0xD90x0638
0xDA0x0639
0xDB0x063A
0xDC0x0640
0xDD0x0641
0xDE0x0642
0xDF0x0643
0xE00x00E0
0xE10x0644
0xE20x00E2
0xE30x0645
0xE40x0646
0xE50x0647
0xE60x0648
0xE70x00E7
0xE80x00E8
0xE90x00E9
0xEA0x00EA
0xEB0x00EB
0xEC0x0649
0xED0x064A
0xEE0x00EE
0xEF0x00EF
0xF00x064B
0xF10x064C
0xF20x064D
0xF30x064E
0xF40x00F4
0xF50x064F
0xF60x0650
0xF70x00F7
0xF80x0651
0xF90x00F9
0xFA0x0652
0xFB0x00FB
0xFC0x00FC
0xFD0x200E
0xFE0x200F
0xFF0x06D2

93
includes/KleejaUploader.php Executable file
View File

@@ -0,0 +1,93 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
#no direct access
if (!defined('IN_COMMON'))
{
exit();
}
interface KleejaUploader
{
/**
* set the allowed extensions of uploaded files
* @param array $allowed_file_extensions an array of allowed extensions, and sizes ['gif'=>122, 'png'=>2421 ..]
* @return void
*/
function setAllowedFileExtensions($allowed_file_extensions);
/**
* get the allowed extensions of uploaded files
* @return array
*/
function getAllowedFileExtensions();
/**
* set the allowed limit of the uploaded files
* @param int $limit
* @return void
*/
function setUploadFieldsLimit($limit);
/**
* get the allowed limit of the uploaded files
* @return int
*/
function getUploadFieldsLimit();
/**
* add an information message to output it to the user
* @param string $message
* @return void
*/
function addInfoMessage($message);
/**
* add an error message to output it to the user
* @param string $message
* @return void
*/
function addErrorMessage($message);
/**
* get all the messages
* @return array
*/
function getMessages();
/**
* save the file information to the database
* @param array $fileInfo
* @return void
*/
function saveToDatabase($fileInfo);
/**
* generate a box of the result and add it to addInfoMessage
* @param array $fileInfo
* @return void
*/
function generateOutputBox($fileInfo);
/**
* here happens the magic, call this on upload submit
* @param int $uploadType upload from files input or links
* @return void
*/
function upload($uploadType);
}

339
includes/adm/a_configs.php Executable file
View File

@@ -0,0 +1,339 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//for style ..
$stylee = "admin_configs";
$current_smt = preg_replace('/[^a-z0-9_]/i','', g('smt', 'str', 'general'));
//words
$action = basename(ADMIN_PATH) . '?cp=options&amp;smt=' . $current_smt;
$n_submit = $lang['UPDATE_CONFIG'];
$options = '';
#$current_type = ig('type') ? g('type') : 'general';
$CONFIGEXTEND = false;
$H_FORM_KEYS = kleeja_add_form_key('adm_configs');
//secondary menu
$query = array(
'SELECT' => 'DISTINCT(c.type), c.display_order, p.plg_disabled, c.plg_id',
'FROM' => "{$dbprefix}config c",
'JOINS' => array(
array(
'LEFT JOIN' => "{$dbprefix}plugins p",
'ON' => 'p.plg_id=c.plg_id'
)
),
'WHERE' => "c.option <> '' AND c.type <> 'groups'",
'ORDER BY' => 'c.display_order'
);
$result = $SQL->build($query);
while($row = $SQL->fetch_array($result))
{
if($row['type'] == 'KLIVE'){
continue;
}
if ($row['plg_id'] > 0 && (is_null($row['plg_disabled']) || $row['plg_disabled'] == 1)) {
continue;
}
$name = !empty($lang['CONFIG_KLJ_MENUS_' . strtoupper($row['type'])]) ? $lang['CONFIG_KLJ_MENUS_' . strtoupper($row['type'])] : (!empty($olang['CONFIG_KLJ_MENUS_' . strtoupper($row['type'])]) ? $olang['CONFIG_KLJ_MENUS_' . strtoupper($row['type'])] : $lang['CONFIG_KLJ_MENUS_OTHER']);
$go_menu[$row['type']] = array('name'=>$name, 'link'=>$action . '&amp;smt=' . $row['type'], 'goto'=>$row['type'], 'current'=> $current_smt == $row['type']);
}
$go_menu['all'] = array('name'=>$lang['CONFIG_KLJ_MENUS_ALL'], 'link'=>$action . '&amp;smt=all', 'goto'=>'all', 'current'=> $current_smt == 'all');
//
// Check form key
//
if (ip('submit'))
{
if(!kleeja_check_form_key('adm_configs'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
}
//general varaibles
#$action = basename(ADMIN_PATH) . '?cp=options&amp;type=' .$current_type;
$STAMP_IMG_URL = file_exists(PATH . 'images/watermark.gif') ? PATH . 'images/watermark.gif' : PATH . 'images/watermark.png';
$stylfiles = $lngfiles = $authtypes = $time_zones = '';
$optionss = array();
$n_googleanalytics = '<a href="http://www.google.com/analytics">Google Analytics</a>';
$query = array(
'SELECT' => '*',
'FROM' => "{$dbprefix}config",
'ORDER BY' => 'display_order, type ASC'
);
$CONFIGEXTEND = $SQL->escape($current_smt);
$CONFIGEXTENDLANG = $go_menu[$current_smt]['name'];
if($current_smt != 'all')
{
$query['WHERE'] = "type = '" . $SQL->escape($current_smt) . "' OR type = ''";
if($current_smt == 'interface')
{
$query['WHERE'] .= " OR name='language'";
}
}
else if($current_smt == 'all')
{
$query['WHERE'] = "type <> 'groups' OR type = ''";
}
$result = $SQL->build($query);
$thumbs_are = get_config('thmb_dims');
while($row=$SQL->fetch_array($result))
{
if($row['type'] == 'KLIVE')
{
continue;
}
if($row['name'] == 'language' && $current_smt == 'interface')
{
$row['type'] = 'interface';
}
#make new lovely array !!
$con[$row['name']] = $row['value'];
if($row['name'] == 'thumbs_imgs')
{
list($thmb_dim_w, $thmb_dim_h) = array_map('trim', @explode('*', $thumbs_are));
}
else if($row['name'] == 'time_zone')
{
$zones = time_zones();
foreach($zones as $z=>$t)
{
$time_zones .= '<option ' . ($con['time_zone'] == $t ? 'selected="selected"' : '') . ' value="' . $t . '">' . $z . '</option>' . "\n";
}
}
else if($row['name'] == 'language')
{
//get languages
if ($dh = @opendir(PATH . 'lang'))
{
while (($file = readdir($dh)) !== false)
{
if(strpos($file, '.') === false && $file != '..' && $file != '.')
{
$lngfiles .= '<option ' . ($con['language'] == $file ? 'selected="selected"' : '') . ' value="' . $file . '">' . $file . '</option>' . "\n";
}
}
@closedir($dh);
}
}
else if($row['name'] == 'user_system')
{
//get auth types
//fix previous choices in old kleeja
if(in_array($con['user_system'], array('2', '3', '4')))
{
$con['user_system'] = str_replace(array('2', '3', '4'), array('phpbb', 'vb', 'mysmartbb'), $con['user_system']);
}
$authtypes .= '<option value="1"' . ($con['user_system']=='1' ? ' selected="selected"' : '') . '>' . $lang['NORMAL'] . '</option>' . "\n";
if ($dh = @opendir(PATH . 'includes/auth_integration'))
{
while (($file = readdir($dh)) !== false)
{
if(strpos($file, '.php') !== false)
{
$file = trim(str_replace('.php', '', $file));
$authtypes .= '<option value="' . $file . '"' . ($con['user_system'] == $file ? ' selected="selected"' : '') . '>' . $file . '</option>' . "\n";
}
}
@closedir($dh);
}
}
is_array($plugin_run_result = Plugins::getInstance()->run('while_fetch_adm_config', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
//options from database [UNDER TEST]
if(!empty($row['option']))
{
$optionss[$row['name']] = array(
'option' => '<div class="form-group">' . "\n" .
'<label for="' . $row['name'] . '">' . (!empty($lang[strtoupper($row['name'])]) ? $lang[strtoupper($row['name'])] : $olang[strtoupper($row['name'])]) . '</label>' . "\n" .
'<div class="box">' . (empty($row['option']) ? '' : $tpl->admindisplayoption($row['option'])) . '</div>' . "\n" .
'</div>' . "\n" . '<div class="clear"></div>',
'type' => $row['type'],
'display_order' => $row['display_order'],
);
}
//when submit
if (ip('submit'))
{
//-->
$new[$row['name']] = p($row['name'], 'str', $con[$row['name']]);
//save them as you want ..
if($row['name'] == 'thumbs_imgs')
{
if(p('thmb_dim_w', 'int') < 10)
{
$_POST['thmb_dim_w'] = 10;
}
if(p('thmb_dim_h', 'int') < 10)
{
$_POST['thmb_dim_h'] = 10;
}
$thumbs_were = p('thmb_dim_w', 'int') . '*' . p('thmb_dim_h', 'int');
update_config('thmb_dims', $thumbs_were);
}
else if($row['name'] == 'livexts')
{
$new['livexts'] = implode(',', array_map('trim', explode(',', p('livexts'))));
}
else if($row['name'] == 'prefixname')
{
$new['prefixname'] = preg_replace('/[^a-z0-9_\-\}\{\:\.]/', '', strtolower(p('prefixname')));
}
else if($row['name'] == 'siteurl')
{
if(p('siteurl')[strlen(p('siteurl'))-1] != '/')
{
$new['siteurl'] .= '/';
}
}
else if($row['name'] == 'mod_writer')
{
if($new['mod_writer'] == 1)
{
if(!file_exists(PATH . '.htaccess') && file_exists(PATH . 'htaccess.txt') && function_exists('rename'))
{
rename(PATH . 'htaccess.txt', PATH . '.htaccess');
}
}
}
else if($row['name'] == 'language')
{
$got_lang = preg_replace('[^a-zA-Z0-9]', '', $new[$row['name']]);
//all groups
foreach ($d_groups as $group_id => $group_info)
{
update_config('language', $got_lang, true, $group_id);
}
delete_cache('data_lang' . $got_lang);
}
is_array($plugin_run_result = Plugins::getInstance()->run('after_submit_adm_config', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$update_query = array(
'UPDATE' => "{$dbprefix}config",
'SET' => "value='" . $SQL->escape($new[$row['name']]) . "'",
'WHERE' => "name='" . $row['name'] . "'"
);
if($current_smt != 'all')
{
$query['WHERE'] .= " AND type = '" . $SQL->escape($current_smt) . "'";
}
$SQL->build($update_query);
}
}
$SQL->freeresult($result);
$types = array();
foreach($optionss as $key => $option)
{
if(empty($types[$option['type']]))
{
$types[$option['type']] = '<ol class="breadcrumb">' .
'<li class="breadcrumb-item"><a href="#">'. $lang['R_CONFIGS'] .'</a></li>' .
'<li class="breadcrumb-item active">'. $go_menu[$option['type']]['name'] .'</li>' .
'</ol>';
}
}
foreach($types as $typekey => $type)
{
$options .= $type;
foreach($optionss as $key => $option)
{
if($option['type'] == $typekey)
{
$options .= str_replace(
array('<input ', '<select ', '<td>', '</td>', '<label>', '<tr>', '</tr>'),
array('<input class="form-control" ', '<select class="form-control" ', '<div class="form-group">', '</div>', '<label class="form-check-label">', '', ''),
$option['option']);
}
}
}
//after submit
if (ip('submit'))
{
#some configs need refresh page ..
$need_refresh_configs = array('language');
is_array($plugin_run_result = Plugins::getInstance()->run('after_submit_adm_config', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
//empty ..
/*
if (empty(p('sitename')) || empty(p('siteurl')) || empty(p('foldername')) || empty(p('filesnum')))
{
$text = $lang['EMPTY_FIELDS'];
$stylee = "admin_err";
}
elseif (!is_numeric(p('filesnum')) || !is_numeric(p('sec_down')))
{
$text = $lang['NUMFIELD_S'];
$stylee = "admin_err";
}
else
{
*/
#delete cache ..
delete_cache('data_config');
foreach($need_refresh_configs as $l)
{
if(ip($l) && p($l) != $config[$l])
{
header('Location: ' . basename(ADMIN_PATH));
exit();
}
}
kleeja_admin_info($lang['CONFIGS_UPDATED'], true, '', true, $action, 3);
//}
}#submit

30
includes/adm/b_lgoutcp.php Executable file
View File

@@ -0,0 +1,30 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//check _GET Csrf token
if(!kleeja_check_form_key_get('GLOBAL_FORM_KEY'))
{
kleeja_admin_err($lang['INVALID_GET_KEY'], true, $lang['ERROR'], true, basename(ADMIN_PATH), 2);
}
//remove just the administator session
if ($usrcp->logout_cp())
{
redirect($config['siteurl']);
$SQL->close();
exit;
}

399
includes/adm/c_files.php Executable file
View File

@@ -0,0 +1,399 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
#number of images per page
$files_acp_perpage = defined('ACP_FILES_PER_PAGE') ? ACP_FILES_PER_PAGE : 20;
#display
$stylee = "admin_files";
$url_or = isset($_REQUEST['order_by']) ? '&amp;order_by=' . htmlspecialchars($_REQUEST['order_by']) . (isset($_REQUEST['order_way']) ? '&amp;order_by=1' : '') : '';
$url_or2 = isset($_REQUEST['order_by']) ? '&amp;order_by=' . htmlspecialchars($_REQUEST['order_by']) : '';
$url_lst = isset($_REQUEST['last_visit']) ? '&amp;last_visit=' . htmlspecialchars($_REQUEST['last_visit']) : '';
$url_sea = ig('search_id') ? '&amp;search_id=' . g('search_id') : '';
$url_pg = ig('page') ? '&amp;page=' . g('page', 'int') : '';
$page_action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . $url_or . $url_sea . $url_lst;
$ord_action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . $url_pg . $url_sea . $url_lst;
$page2_action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . $url_or2 . $url_sea . $url_lst;
$action = $page_action . $url_pg;
$is_search = $affected = false;
$H_FORM_KEYS = kleeja_add_form_key('adm_files');
//
// Check form key
//
if (ip('submit'))
{
#wrong form
if(!kleeja_check_form_key('adm_files'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
$del = array();
#gather to-be-deleted file ids
foreach ($_POST as $key => $value)
{
if(preg_match('/del_(?P<digit>\d+)/', $key))
{
$del[$key] = $value;
}
}
#delete them once by once
$ids = array();
$files_num = $imgs_num = $sizes = 0;
//TODO use IN(...)
foreach ($del as $key => $id)
{
$query = array(
'SELECT' => 'f.id, f.name, f.folder, f.size, f.type',
'FROM' => "{$dbprefix}files f",
'WHERE' => 'f.id = ' . intval($id),
);
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
//delete from folder ..
@kleeja_unlink (PATH . $row['folder'] . '/' . $row['name']);
//delete thumb
if (file_exists(PATH . $row['folder'] . '/thumbs/' . $row['name'] ))
{
@kleeja_unlink (PATH . $row['folder'] . '/thumbs/' . $row['name'] );
}
$is_image = in_array(strtolower(trim($row['type'])), array('gif', 'jpg', 'jpeg', 'bmp', 'png')) ? true : false;
$ids[] = $row['id'];
if($is_image)
{
$imgs_num++;
}
else
{
$files_num++;
}
$sizes += $row['size'];
}
}
is_array($plugin_run_result = Plugins::getInstance()->run('submit_files_admin', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$SQL->freeresult($result);
//no files to delete
if(isset($ids) && sizeof($ids))
{
$query_del = array(
'DELETE' => "{$dbprefix}files",
'WHERE' => "`id` IN (" . implode(',', $ids) . ")"
);
$SQL->build($query_del);
//update number of stats
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => "sizes=sizes-$sizes, files=files-$files_num, imgs=imgs-$imgs_num",
);
$SQL->build($update_query);
if($SQL->affected())
{
delete_cache('data_stats');
$affected = true;
}
}
#show msg now
$text = ($affected && (isset($ids) && sizeof($ids)) ? $lang['FILES_UPDATED'] : $lang['NO_UP_CHANGE_S']) .
'<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . str_replace('&amp;', '&', $action) . '\');", 2000);</script>' . "\n";
$stylee = "admin_info";
}
else
{
//
//Delete all user files [only one user]
//
if(ig('deletefiles'))
{
$query = array(
'SELECT' => 'f.id, f.size, f.name, f.folder',
'FROM' => "{$dbprefix}files f",
);
#get search filter
$filter = get_filter(g('search_id'), 'file_search', false, 'filter_uid');
if(!$filter)
{
kleeja_admin_err($lang['ADMIN_DELETE_FILES_NOF']);
}
$query['WHERE'] = build_search_query(unserialize(htmlspecialchars_decode($filter['filter_value'])));
if($query['WHERE'] == '')
{
kleeja_admin_err($lang['ADMIN_DELETE_FILES_NOF']);
}
$result = $SQL->build($query);
$sizes = false;
$ids = array();
$files_num = $imgs_num = 0;
while($row=$SQL->fetch_array($result))
{
//delete from folder ..
@kleeja_unlink (PATH . $row['folder'] . "/" . $row['name']);
//delete thumb
if (file_exists(PATH . $row['folder'] . "/thumbs/" . $row['name']))
{
@kleeja_unlink (PATH . $row['folder'] . "/thumbs/" . $row['name']);
}
$is_image = in_array(strtolower(trim($row['type'])), array('gif', 'jpg', 'jpeg', 'bmp', 'png')) ? true : false;
$ids[] = $row['id'];
if($is_image)
{
$imgs_num++;
}
else
{
$files_num++;
}
$sizes += $row['size'];
}
$SQL->freeresult($result);
if(($files_num + $imgs_num) == 0)
{
kleeja_admin_err($lang['ADMIN_DELETE_FILES_NOF']);
}
else
{
//update number of stats
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => "sizes=sizes-$sizes, files=files-$files_num, imgs=imgs-$imgs_num",
);
$SQL->build($update_query);
if($SQL->affected())
{
delete_cache('data_stats');
}
//delete all files in just one query
$query_del = array(
'DELETE' => "{$dbprefix}files",
'WHERE' => "`id` IN (" . implode(',', $ids) . ")"
);
$SQL->build($query_del);
kleeja_admin_info(sprintf($lang['ADMIN_DELETE_FILES_OK'], ($files_num + $imgs_num)));
}
}
//
//begin default files page
//
$query = array(
'SELECT' => 'COUNT(f.id) AS total_files',
'FROM' => "{$dbprefix}files f",
'ORDER BY' => 'f.id '
);
#if user system is default, we use users table
if((int) $config['user_system'] == 1)
{
$query['JOINS'] = array(
array(
'LEFT JOIN' => "{$dbprefix}users u",
'ON' => 'u.id=f.user'
)
);
}
$do_not_query_total_files = false;
//posts search ..
if(ig('search_id'))
{
#get search filter
$filter = get_filter(g('search_id'), 'file_search', false, 'filter_uid');
$deletelink = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&deletefiles=' . g('search_id');
$is_search = true;
$query['WHERE'] = build_search_query(unserialize(htmlspecialchars_decode($filter['filter_value'])));
}
else if(isset($_REQUEST['last_visit']))
{
$query['WHERE'] = "f.time > " . intval($_REQUEST['last_visit']);
}
#to-be-deleted
#it is becoming a headache for a big websites. We do not have the time to figure out a solution
if(isset($_REQUEST['order_by']) && in_array($_REQUEST['order_by'], array('real_filename', 'size', 'user', 'user_ip', 'uploads', 'time', 'type', 'folder', 'report')))
{
$query['ORDER BY'] = "f." . $SQL->escape($_REQUEST['order_by']);
}
else
{
$do_not_query_total_files = true;
}
if(!ig('search_id'))
{
//display files or display pics and files only in search
$img_types = array('gif','jpg','png','bmp','jpeg','GIF','JPG','PNG','BMP','JPEG');
$query['WHERE'] = $query['WHERE'] . (empty($query['WHERE']) ? '' : ' AND ') . "f.type NOT IN ('" . implode("', '", $img_types) . "')";
}
else
{
$do_not_query_total_files = false;
}
$query['ORDER BY'] .= (isset($_REQUEST['order_way']) && (int) $_REQUEST['order_way'] == 1) ? ' ASC' : ' DESC';
$nums_rows = 0;
if($do_not_query_total_files)
{
$nums_rows = get_actual_stats('files');
}
else
{
$result_p = $SQL->build($query);
$n_fetch = $SQL->fetch_array($result_p);
$nums_rows = $n_fetch['total_files'];
$SQL->freeresult($result_p);
}
//pager
$currentPage= ig('page') ? g('page', 'int') : 1;
$Pager = new Pagination($files_acp_perpage, $nums_rows, $currentPage);
$start = $Pager->getStartRow();
$no_results = false;
is_array($plugin_run_result = Plugins::getInstance()->run('query_files_admin', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if ($nums_rows > 0)
{
$query['SELECT'] = 'f.*' . ((int) $config['user_system'] == 1 ? ', u.name AS username' : '');
$query['LIMIT'] = "$start, $files_acp_perpage";
$result = $SQL->build($query);
$sizes = false;
$num = 0;
#if Kleeja integtared we dont want make alot of queries
$ids_and_names = array();
while($row=$SQL->fetch_array($result))
{
$userfile = $config['siteurl'] . ($config['mod_writer'] ? 'fileuser-' . $row['user'] . '.html' : 'ucp.php?go=fileuser&amp;id=' . $row['user']);
$file_info = array('::ID::' => $row['id'], '::NAME::' => $row['name'], '::DIR::' => $row['folder'], '::FNAME::' => $row['real_filename']);
$is_image = in_array(strtolower(trim($row['type'])), array('gif', 'jpg', 'jpeg', 'bmp', 'png')) ? true : false;
$url = kleeja_get_link($is_image ? 'image': 'file', $file_info);
#for username in integrated user system
if($row['user'] != '-1' and (int) $config['user_system'] != 1)
{
if(!in_array($row['user'], $ids_and_names))
{
$row['username'] = $usrcp->usernamebyid($row['user']);
$ids_and_names[$row['user']] = $row['username'];
}
else
{
$row['username'] = $ids_and_names[$row['user']];
}
}
$file_name = $row['real_filename'] == '' ? $row['name'] : $row['real_filename'];
//make new lovely arrays !!
$arr[] = array(
'id' => $row['id'],
'name' => "<a title=\"" . $file_name . "\" href=\"" .$url . "\" target=\"blank\">" .
shorten_text($file_name, 25) . "</a>",
'fullname' => $file_name,
'size' => readable_size($row['size']),
'ups' => $row['uploads'],
'direct' => $row['id_form'] == 'direct' ? true : false,
'time_human'=> kleeja_date($row['time']),
'time' => kleeja_date($row['time'], false),
'type' => $row['type'],
'typeicon' => file_exists(PATH . "images/filetypes/". $row['type'] . ".png") ? PATH . "images/filetypes/" . $row['type'] . ".png" : PATH. 'images/filetypes/file.png',
'folder' => $row['folder'],
'report' => $row['report'] > 4 ? "<span style=\"color:red;font-weight:bold\">" . $row['report'] . "</span>":$row['report'],
'user' => $row['user'] == '-1' ? $lang['GUST'] : '<a href="' . $userfile . '" target="_blank">' . $row['username'] . '</a>',
'ip' => '<a href="http://www.ripe.net/whois?form_type=simple&amp;full_query_string=&amp;searchtext=' . $row['user_ip'] . '&amp;do_search=Search" target="_new">' . $row['user_ip'] . '</a>',
'showfilesbyip' => basename(ADMIN_PATH) . '?cp=h_search&amp;s_input=1&amp;s_value=' . $row['user_ip']
);
is_array($plugin_run_result = Plugins::getInstance()->run('arr_files_admin', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$del[$row['id']] = p('del_' . $row['id']);
}
$SQL->freeresult($result);
}
else
{
//no result ..
$no_results = true;
}
#update f_lastvisit
if(!$is_search)
{
if (filter_exists('f_lastvisit', 'filter_uid', 'lastvisit', $userinfo['id'])) {
update_filter('f_lastvisit', time(), 'lastvisit', false, $userinfo['id']);
} else {
insert_filter('f_lastvisit', time(), 'lastvisit', time(), $userinfo['id']);
}
}
//some vars
$total_pages = $Pager->getTotalPages();
$page_nums = $Pager->print_nums($page_action);
$current_page = $Pager->getCurrentPage();
}

268
includes/adm/d_img_ctrl.php Executable file
View File

@@ -0,0 +1,268 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
#number of images per page
$images_acp_perpage = defined('ACP_IMAGES_PER_PAGE') ? ACP_IMAGES_PER_PAGE : 20;
#display
$stylee = "admin_img";
$action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . (ig('page') ? '&amp;page=' . g('page', 'int') : '') .
(ig('last_visit') ? '&amp;last_visit='.g('last_visit', 'int') : '') .
(ig('smt') ? '&smt=' . g('smt') : '');
$action_search = basename(ADMIN_PATH) . "?cp=h_search";
$H_FORM_KEYS = kleeja_add_form_key('adm_img_ctrl');
$is_search = false;
//
// Check form key
//
if (ip('submit'))
{
if(!kleeja_check_form_key('adm_img_ctrl'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
$del = array();
$num = $sizes = 0;
foreach ($_POST as $key => $value)
{
if(preg_match('/del_(?P<digit>\d+)/', $key))
{
$del[$key] = $value;
}
}
//TODO better way
foreach ($del as $key => $id)
{
$query = array(
'SELECT' => '*',
'FROM' => "{$dbprefix}files",
'WHERE' => '`id` = ' . intval($id),
);
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
//delete from folder ..
@kleeja_unlink(PATH . $row['folder'] . '/' . $row['name']);
//delete thumb
if (file_exists(PATH . $row['folder'] . '/thumbs/' . $row['name'] ))
{
@kleeja_unlink(PATH . $row['folder'] . '/thumbs/' . $row['name'] );
}
$ids[] = $row['id'];
$num++;
$sizes += $row['size'];
}
$SQL->free($result);
}
is_array($plugin_run_result = Plugins::getInstance()->run('submit_imgctrl_admin', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
//no files to delete
if(isset($ids) && sizeof($ids))
{
$query_del = array(
'DELETE' => "{$dbprefix}files",
'WHERE' => "`id` IN (" . implode(',', $ids) . ")"
);
$SQL->build($query_del);
//update number of stats
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => "sizes=sizes-$sizes, imgs=imgs-$num",
);
$SQL->build($update_query);
if($SQL->affected())
{
delete_cache('data_stats');
$affected = true;
}
}
//after submit
$text = ($affected ? $lang['FILES_UPDATED'] : $lang['NO_UP_CHANGE_S']) .
'<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') .
'&page=' . (ig('page') ? g('page', 'int') : '1') . '\');", 2000);</script>' . "\n";
$stylee = "admin_info";
}
else
{
$query = array(
'SELECT' => 'COUNT(f.id) AS total_files',
'FROM' => "{$dbprefix}files f",
'ORDER BY' => 'f.id DESC'
);
#if user system is default, we use users table
if((int) $config['user_system'] == 1)
{
$query['JOINS'] = array(
array(
'LEFT JOIN' => "{$dbprefix}users u",
'ON' => 'u.id=f.user'
)
);
}
$img_types = array('gif','jpg','png','bmp','jpeg','GIF','JPG','PNG','BMP','JPEG');
#
# There is a bug with IN statement in MySQL and they said it will solved at 6.0 version
# forums.mysql.com/read.php?10,243691,243888#msg-243888
# $query['WHERE'] = "f.type IN ('" . implode("', '", $img_types) . "')";
#
$query['WHERE'] = "(f.type = '" . implode("' OR f.type = '", $img_types) . "')";
$do_not_query_total_files = false;
if(ig('last_visit'))
{
$query['WHERE'] .= " AND f.time > " . g('last_visit', 'int');
}
else
{
$do_not_query_total_files = true;
}
is_array($plugin_run_result = Plugins::getInstance()->run('query_imgctrl_admin', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$nums_rows = 0;
if($do_not_query_total_files)
{
$nums_rows = get_actual_stats('imgs');
}
else
{
$result_p = $SQL->build($query);
$n_fetch = $SQL->fetch_array($result_p);
$nums_rows = $n_fetch['total_files'];
$SQL->freeresult($result_p);
}
//pager
$currentPage= ig('page') ? g('page', 'int') : 1;
$Pager = new Pagination($images_acp_perpage, $nums_rows, $currentPage);
$start = $Pager->getStartRow();
$no_results = $affected = $sizes = false;
if ($nums_rows > 0)
{
$query['SELECT'] = 'f.*' . ((int) $config['user_system'] == 1 ? ', u.name AS username' : '');
$query['LIMIT'] = "$start, $images_acp_perpage";
$result = $SQL->build($query);
$tdnum = $num = 0;
#if Kleeja integrated we dont want make alot of queries
$ids_and_names = array();
while($row=$SQL->fetch_array($result))
{
$file_info = array('::ID::' => $row['id'], '::NAME::' => $row['name'], '::DIR::' => $row['folder'], '::FNAME::' => $row['real_filename']);
$url = kleeja_get_link('image', $file_info);
$url_thumb = kleeja_get_link('thumb', $file_info);
#for username in integrated user system
if($row['user'] != '-1' and (int) $config['user_system'] != 1)
{
if(!in_array($row['user'], $ids_and_names))
{
$row['username'] = $usrcp->usernamebyid($row['user']);
$ids_and_names[$row['user']] = $row['username'];
}
else
{
$row['username'] = $ids_and_names[$row['user']];
}
}
$file_name = $row['real_filename'] == '' ? $row['name'] : $row['real_filename'];
//make new lovely arrays !!
$arr[] = array(
'id' => $row['id'],
'tdnum' => $tdnum == 0 ? '<ul>': '',
'tdnum2' => $tdnum == 4 ? '</ul>' : '',
'name' => shorten_text($file_name, 25),
'ip' => htmlspecialchars($row['user_ip']),
'href' => $url,
'size' => readable_size($row['size']),
'ups' => $row['uploads'],
'time' => date('d-m-Y h:i a', $row['time']),
'user' => (int) $row['user'] == -1 ? $lang['GUST'] : $row['username'],
'is_user' => (int) $row['user'] == -1 ? 0 : 1,
'thumb_link'=> $url_thumb
);
//fix ...
$tdnum = $tdnum == 4 ? 0 : $tdnum+1;
$del[$row['id']] = p('del_' . $row['id']);
is_array($plugin_run_result = Plugins::getInstance()->run('arr_imgctrl_admin', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
}
$SQL->freeresult($result);
}
else
{
$no_results = true;
}
#update f_lastvisit
if(!$is_search)
{
if (filter_exists('i_lastvisit', 'filter_uid', 'lastvisit', $userinfo['id'])) {
update_filter('i_lastvisit', time(), 'lastvisit', false, $userinfo['id']);
} else {
insert_filter('i_lastvisit', time(), 'lastvisit', time(), $userinfo['id']);
}
}
//pages
$total_pages = $Pager->getTotalPages();
$page_nums = $Pager->print_nums(basename(ADMIN_PATH). '?cp=' . basename(__file__, '.php') .
(ig('last_visit') ? '&last_vists=' . g('last_visit', 'int') : '') .
(ig('smt') ? '&smt=' . g('smt') : '')
, 'onclick="javascript:get_kleeja_link($(this).attr(\'href\'), \'#content\'); return false;"');
$current_page = $Pager->getCurrentPage();
}

173
includes/adm/e_calls.php Executable file
View File

@@ -0,0 +1,173 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//for style ..
$stylee = "admin_calls";
$current_smt = preg_replace('/[^a-z0-9_]/i', '', g('smt', 'str', 'general'));
$action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&amp;page=' . (ig('page') ? g('page', 'int') : 1) . '&amp;smt=' . $current_smt;
$msg_sent = ig('sent') ? g('sent', 'int') : false;
$H_FORM_KEYS = kleeja_add_form_key('adm_calls');
$there_queue = preg_match('!:del_[a-z0-9]{0,3}calls:!i', $config['queue']);
//
// Check form key
//
if (ip('submit'))
{
if(!kleeja_check_form_key('adm_calls'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
}
#add delete process to the queue
if($current_smt == 'del_d30' || $current_smt == 'del_all')
{
if(strpos($config['queue'], ':' . $current_smt . 'calls:') !== false)
{
kleeja_admin_err($lang['DELETE_PROCESS_IN_WORK'], true, $lang['ERROR'], true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php'), 1);
}
else
{
update_config('queue', $config['queue'] . ':' . $current_smt . 'calls:');
kleeja_admin_info($lang['DELETE_PROCESS_QUEUED'], true, '', true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php'));
}
}
$query = array(
'SELECT' => 'c.*',
'FROM' => "`{$dbprefix}call` c",
'ORDER BY' => 'c.id DESC'
);
if($current_smt == 'show_h24')
{
$query['WHERE'] = 'c.time > ' . intval(time() - 3600 * 24);
}
$result = $SQL->build($query);
//pagination
$nums_rows = $SQL->num_rows($result);
$currentPage = ig('page') ? g('page', 'int') : 1;
$Pager = new Pagination($perpage, $nums_rows, $currentPage);
$start = $Pager->getStartRow();
$no_results = false;
$del_nums = array();
if ($nums_rows > 0)
{
$query['LIMIT'] = "$start,$perpage";
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
//make new lovely arrays !!
$arr[] = array(
'id' => $row['id'],
'name' => $row['name'],
'mail' => $row['mail'],
'text' => htmlspecialchars($row['text']),
'human_time'=> kleeja_date($row['time']),
'time' => kleeja_date($row['time'], false),
'ip' => $row['ip'],
'sent' => $row['id'] == $msg_sent,
'ip_finder' => 'http://www.ripe.net/whois?form_type=simple&full_query_string=&searchtext=' . $row['ip'] . '&do_search=Search'
);
$del[$row['id']] = p('del_' . $row['id']);
$sen[$row['id']] = p('v_' . $row['id']);
//when submit !!
if (ip('submit'))
{
if ($del[$row['id']])
{
$del_nums[] = $row['id'];
}
}
if (ip('reply_submit'))
{
if ($sen[$row['id']])
{
$to = $row['mail'];
$subject = $lang['REPLY_CALL'] . ':' . $config['sitename'];
$message = "\n " . $lang['REPLY_CALL'] . " " . $row['name'] . "\r\n " . $lang['REPLIED_ON_CAL'] . " : " . $config['sitename'] .
"\r\n " . $lang['BY_EMAIL'] . ": " . $row['mail'] . "\r\n" . $lang['ADMIN_REPLIED'] . "\r\n" . $sen[$row['id']] . "\r\n\r\n Kleeja.com ";
$send = send_mail($to, $message, $subject, $config['sitemail'], $config['sitename']);
if ($send)
{
//
//We will redirect to pages of results and show info msg there !
//
kleeja_admin_info($lang['IS_SEND_MAIL'], true, '', true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&page=' . (ig('page') ? g('page', 'int') : 1) . '&sent=' . $row['id']);
}
else
{
kleeja_admin_err($lang['ERR_SEND_MAIL'], true, '', true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&page=' . (ig('page') ? g('page', 'int') : 1) . '&sent=' . $row['id']);
}
}
}
}
$SQL->freeresult($result);
}
else
{
$no_results = true;
}
//if deleted
if(sizeof($del_nums))
{
$query_del = array(
'DELETE' => "`{$dbprefix}call`",
'WHERE' => "id IN('" . implode("', '", $del_nums) . "')"
);
$SQL->build($query_del);
}
$total_pages = $Pager->getTotalPages();
$page_nums = $Pager->print_nums(basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php'), 'onclick="javascript:get_kleeja_link($(this).attr(\'href\'), \'#content\'); return false;"');
//after submit
if (ip('submit'))
{
$text = ($SQL->affected() ? $lang['CALLS_UPDATED'] : $lang['NO_UP_CHANGE_S']);
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . $action . '\'); check_msg_and_reports();", 2000);</script>' . "\n";
kleeja_admin_info($text, true, '', true, $action);
}
//secondary menu
$go_menu = array(
'general' => array('name'=>$lang['R_CALLS'], 'link'=> basename(ADMIN_PATH) . '?cp=e_calls&amp;smt=general', 'goto'=>'general', 'current'=> $current_smt == 'general'),
'show_h24' => array('name'=>$lang['SHOW_FROM_24H'], 'link'=> basename(ADMIN_PATH) . '?cp=e_calls&amp;smt=show_h24', 'goto'=>'show_h24', 'current'=> $current_smt == 'show_h24'),
#CHECK IF IT'S ALREADY DONE ?
'del_d30' => array('name'=>$lang['DELETE_EARLIER_30DAYS'], 'link'=> basename(ADMIN_PATH) . '?cp=e_calls&amp;smt=del_d30', 'goto'=>'del_d30', 'current'=> $current_smt == 'del_d30', 'confirm'=>true),
'del_all' => array('name'=>$lang['DELETE_ALL'], 'link'=> basename(ADMIN_PATH) . '?cp=e_calls&amp;smt=del_all', 'goto'=>'del_all', 'current'=> $current_smt == 'del_all', 'confirm'=>true),
);

172
includes/adm/f_reports.php Executable file
View File

@@ -0,0 +1,172 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//for style ..
$stylee = "admin_reports";
$current_smt = preg_replace('/[^a-z0-9_]/i','', g('smt', 'str', 'general'));
$action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&amp;page=' . (ig('page') ? g('page', 'int') : 1) . '&amp;smt=' . $current_smt;
$msg_sent = ig('sent') ? g('sent', 'int') : false;
$H_FORM_KEYS = kleeja_add_form_key('adm_reports');
$there_queue = preg_match('!:del_[a-z0-9]{0,3}reports:!i', $config['queue']);
//
// Check form key
//
if (ip('submit'))
{
if(!kleeja_check_form_key('adm_reports'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
}
#add delete process to the queue
if($current_smt == 'del_d30' || $current_smt == 'del_all')
{
if(strpos($config['queue'], ':' . $current_smt . 'reports:') !== false)
{
kleeja_admin_err($lang['DELETE_PROCESS_IN_WORK'], true, $lang['ERROR'], true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php'), 1);
}
else
{
update_config('queue', $config['queue'] . ':' . $current_smt . 'reports:');
kleeja_admin_info($lang['DELETE_PROCESS_QUEUED'], true, '', true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php'));
}
}
$query = array(
'SELECT' => '*',
'FROM' => "{$dbprefix}reports r",
'ORDER BY' => 'r.id DESC'
);
if($current_smt == 'show_h24')
{
$query['WHERE'] = 'r.time > ' . intval(time() - 3600 * 24);
}
$result = $SQL->build($query);
//pagination
$nums_rows = $SQL->num_rows($result);
$currentPage = ig('page') ? g('page', 'int') : 1;
$Pager = new Pagination($perpage, $nums_rows, $currentPage);
$start = $Pager->getStartRow();
$no_results = false;
$del_nums = array();
if ($nums_rows > 0)
{
$query['LIMIT'] = "$start, $perpage";
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
//make new lovely arrays !!
$arr[] = array(
'id' => $row['id'],
'name' => $row['name'],
'mail' => $row['mail'],
'url' => $row['url'],
'text' => $row['text'],
'human_time'=> kleeja_date($row['time']),
'time' => kleeja_date($row['time'], false),
'ip' => $row['ip'],
'sent' => $row['id'] == $msg_sent,
'ip_finder' => 'http://www.ripe.net/whois?form_type=simple&full_query_string=&searchtext=' . htmlspecialchars($row['ip']) . '&do_search=Search'
);
$del[$row['id']] = p('del_' . $row['id']);
$sen[$row['id']] = p('v_' . $row['id']);
//when submit !!
if (ip('submit'))
{
if ($del[$row['id']])
{
$del_nums[] = $row['id'];
}
}
if (ip('reply_submit'))
{
if ($sen[$row['id']])
{
$to = $row['mail'];
$subject = $lang['REPLY_REPORT'] . ':' . $config['sitename'];
$message = "\n " . $lang['WELCOME'] . " " . $row['name'] . "\r\n " . $lang['U_REPORT_ON'] . " " . $config['sitename']. "\r\n " .
$lang['BY_EMAIL'] . " : " . $row['mail']."\r\n" . $lang['ADMIN_REPLIED'] . ": \r\n" . $sen[$row['id']] . "\r\n\r\n kleeja.com";
$send = send_mail($to, $message, $subject, $config['sitemail'], $config['sitename']);
if ($send)
{
//
//We will redirect to pages of results and show info msg there !
//
kleeja_admin_info($lang['IS_SEND_MAIL'], true, '', true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&page=' . (ig('page') ? g('page', 'int') : 1) . '&sent=' . $row['id']);
}
else
{
kleeja_admin_err($lang['ERR_SEND_MAIL'], true, '', true, basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&page=' . (ig('page') ? g('page', 'int') : 1) . '&sent=' . $row['id']);
}
}
}
}
$SQL->freeresult($result);
}
else #num rows
{
$no_results = true;
}
//if deleted
if(sizeof($del_nums))
{
$query_del = array(
'DELETE' => "{$dbprefix}reports",
'WHERE' => "id IN('" . implode("', '", $del_nums) . "')"
);
$SQL->build($query_del);
}
$total_pages = $Pager->getTotalPages();
$page_nums = $Pager->print_nums(basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php'), 'onclick="javascript:get_kleeja_link($(this).attr(\'href\'), \'#content\'); return false;"');
//after submit
if (ip('submit'))
{
$text = ($SQL->affected() ? $lang['REPORTS_UPDATED'] : $lang['NO_UP_CHANGE_S']);
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . $action . '\'); check_msg_and_reports();", 2000);</script>' . "\n";
kleeja_admin_info($text, true, '', true, $action);
}
//secondary menu
$go_menu = array(
'general' => array('name'=>$lang['R_REPORTS'], 'link'=> basename(ADMIN_PATH) . '?cp=f_reports&amp;smt=general', 'goto'=>'general', 'current'=> $current_smt == 'general'),
'show_h24' => array('name'=>$lang['SHOW_FROM_24H'], 'link'=> basename(ADMIN_PATH) . '?cp=f_reports&amp;smt=show_h24', 'goto'=>'show_h24', 'current'=> $current_smt == 'show_h24'),
#TODO : CHECK IF IT'S ALREADY DONE ?
'del_d30' => array('name'=>$lang['DELETE_EARLIER_30DAYS'], 'link'=> basename(ADMIN_PATH) . '?cp=f_reports&amp;smt=del_d30', 'goto'=>'del_d30', 'current'=> $current_smt == 'del_d30', 'confirm'=>true),
'del_all' => array('name'=>$lang['DELETE_ALL'], 'link'=> basename(ADMIN_PATH) . '?cp=f_reports&amp;smt=del_all', 'goto'=>'del_all', 'current'=> $current_smt == 'del_all', 'confirm'=>true),
);

1295
includes/adm/g_users.php Executable file

File diff suppressed because it is too large Load Diff

167
includes/adm/h_search.php Executable file
View File

@@ -0,0 +1,167 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//for style ..
$stylee = "admin_search";
//search files
$action = basename(ADMIN_PATH) . "?cp=h_search";
//wut the default user system
$default_user_system = (int) $config['user_system'] == 1 ? true : false;
$H_FORM_KEYS = kleeja_add_form_key('adm_files_search');
$H_FORM_KEYS2 = kleeja_add_form_key('adm_users_search');
$current_smt = preg_replace('/[^a-z0-9_]/i', '', g('smt', 'str', 'files'));
#filling the inputs automatically via GET
$filled_ip = $filled_username = '';
if(ig('s_input'))
{
if(g('s_input', 'int') == 2)
{
$filled_username = g('s_value');
}
elseif(g('s_input', 'int') == 1)
{
$filled_ip = g('s_value');
}
}
if (ip('search_file'))
{
if(!kleeja_check_form_key('adm_files_search'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, basename(ADMIN_PATH) . '?cp=h_search', 1);
}
#delete all searches greater than 10
$s_del = array(
'SELECT' => "filter_id",
'FROM' => "{$dbprefix}filters",
'WHERE' => "filter_type='file_search' AND filter_user=" . $userinfo['id'],
'ORDER BY' => "filter_id DESC",
'LIMIT' => '5, 18446744073709551615'
);
$result = $SQL->build($s_del);
$ids = array();
while($row=$SQL->fetch_array($result))
{
$ids[] = $row['filter_id'];
}
$SQL->free($result);
if($ids != '')
{
$query_del = array(
'DELETE' => "{$dbprefix}filters",
'WHERE' => "filter_id IN('" . implode("', '", $ids) . "')"
);
$SQL->build($query_del);
}
#add as a file_search filter
$s = array_map('htmlspecialchars', $_POST);
#reduce number of array keys
unset($s['search_file'], $s['k_form_key'], $s['k_form_time']);
foreach ($s as $key => $v)
{
if ($s[$key] == '')
{
unset($s[$key]);
}
}
$d = serialize($s);
if(($search_id = insert_filter('file_search', $d)))
{
$filter = get_filter($search_id, 'file_search');
redirect(basename(ADMIN_PATH) . "?cp=c_files&search_id=" . $filter['filter_uid'], false);
}
else
{
kleeja_admin_err($lang['ERROR_TRY_AGAIN'], true, $lang['ERROR'], true, basename(ADMIN_PATH) . '?cp=h_search', 1);
}
}
if (ip('search_user'))
{
if(!kleeja_check_form_key('adm_users_search'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, basename(ADMIN_PATH) . '?cp=h_search&smt=users', 1);
}
#delete all searches greater than 10
$s_del = array(
'SELECT' => "filter_id",
'FROM' => "{$dbprefix}filters",
'WHERE' => "filter_type='user_search' AND filter_user=" . $userinfo['id'],
'ORDER BY' => "filter_id DESC",
'LIMIT' => '5, 18446744073709551615'
);
$result = $SQL->build($s_del);
$ids = array();
while($row=$SQL->fetch_array($result))
{
$ids[] = $row['filter_id'];
}
$SQL->free($result);
if($ids != '')
{
$query_del = array(
'DELETE' => "{$dbprefix}filters",
'WHERE' => "filter_id IN('" . implode("', '", $ids) . "')"
);
$SQL->build($query_del);
}
#add as a user_search filter
$s = $_POST;
unset($s['search_user'], $s['k_form_key'], $s['k_form_time']);
$d = serialize($s);
if(($search_id = insert_filter('user_search', $d)))
{
$filter = get_filter($search_id, 'user_search');
redirect(basename(ADMIN_PATH) . "?cp=g_users&smt=show_su&search_id=" . $filter['filter_uid'], false);
}
else
{
kleeja_admin_err($lang['ERROR_TRY_AGAIN'], true, $lang['ERROR'], true, basename(ADMIN_PATH) . '?cp=h_search&smt=users', 1);
}
}
//secondary menu
$go_menu = array(
'files' => array('name'=>$lang['SEARCH_FILES'], 'link'=> basename(ADMIN_PATH) . '?cp=h_search&amp;smt=files', 'goto'=>'files', 'current'=> $current_smt == 'files'),
#'sep1' => array('class'=>'separator'),
'users' => array('name'=>$lang['SEARCH_USERS'], 'link'=> basename(ADMIN_PATH) . '?cp=h_search&amp;smt=users', 'goto'=>'users', 'current'=> $current_smt == 'users'),
#'sep2' => array('class'=>'separator'),
);
if(!$default_user_system)
{
unset($go_menu['users']);
}

58
includes/adm/index.html Executable file
View File

@@ -0,0 +1,58 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256"/>
<title>Powered by Kleeja</title>
<style type="text/css">* {
font-size: 100%;
margin: 0;
padding: 0;
color: #CECFCE;
}
body {
font-family: Tahoma, Arial, sans-serif;
font-size: 100%;
color: #69788E;
margin: 10px 30px;
background: #F7F7F7;
}
a:link, a:visited {
text-decoration: none;
color: #CECFCE;
}
a:active, a:hover {
text-decoration: underline;
color: #111;
}
h1 {
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-size: 1.70em;
font-weight: normal;
color: #333333;
margin-top: 0;
margin-bottom: 10px;
}
.content_box {
border: 1px dashed #CECFCE;
background: #FFFFFF;
padding: 10px;
margin-right: auto;
margin-left: auto;
}</style>
</head>
<body title="&#1603;&#1604;&#1610;&#1580;&#1575;"><br/>
<div class="content_box">
<p>
<a target="_blank" href="http://www.kleeja.com" title="kleeja"></a>
</p>
<br/>
<h1><span style="font-size:250%;color:#D80000;">403 - Access forbidden!</span></h1></div>
<br/>
<div class="content_box"style="font-size: 140%">Powered by Kleeja</div>
</body>
</html>

475
includes/adm/j_plugins.php Executable file
View File

@@ -0,0 +1,475 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license http://www.kleeja.com/license
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
#turn time-limit off
@set_time_limit(0);
#get current case
$case = g('case', 'str');
#set _get form key
$GET_FORM_KEY = kleeja_add_form_key_get('PLUGINS_FORM_KEY');
$H_FORM_KEYS = kleeja_add_form_key('adm_plugins');
$action = ADMIN_PATH . '?cp=' . basename(__file__, '.php');
$plugin_install_link = ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '&amp;case=install&amp;' . $GET_FORM_KEY . '&amp;plg=';
$plugin_uninstall_link = ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '&amp;case=uninstall&amp;' . $GET_FORM_KEY . '&amp;plg=';
$plugin_enable_link = ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '&amp;case=enable&amp;' . $GET_FORM_KEY . '&amp;plg=';
$plugin_disable_link = ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '&amp;case=disable&amp;' . $GET_FORM_KEY . '&amp;plg=';
//check _GET Csrf token
if ($case && in_array($case, array('install', 'uninstall', 'enable', 'disable')))
{
if (!kleeja_check_form_key_get('PLUGINS_FORM_KEY'))
{
kleeja_admin_err($lang['INVALID_GET_KEY'], $action);
}
}
if(ip('newplugin'))
{
if(!kleeja_check_form_key('adm_plugins'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action);
}
$case = 'upload';
}
switch ($case):
default:
# Get installed plugins
$query = array(
'SELECT' => "plg_id, plg_name, plg_ver, plg_disabled, plg_author, plg_dsc",
'FROM' => "{$dbprefix}plugins",
'ORDER BY' => "plg_id ASC",
);
$result = $SQL->build($query);
$installed_plugins = array();
while ($row = $SQL->fetch($result))
{
$installed_plugins[$row['plg_name']] = $row;
$installed_plugins[$row['plg_name']]['extra_info'] = Plugins::getInstance()->installed_plugin_info($row['plg_name']);
$installed_plugins[$row['plg_name']]['icon'] = file_exists(
PATH . KLEEJA_PLUGINS_FOLDER . '/' . $row['plg_name'] . "/icon.png"
)
? PATH . KLEEJA_PLUGINS_FOLDER . '/' . $row['plg_name'] . "/icon.png"
: $STYLE_PATH_ADMIN . 'images/plugin.png';
foreach (array('plugin_title', 'plugin_description') as $localizedInfo)
{
if (is_array($installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo]))
{
if (!empty($installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo][$config['language']]))
{
$installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo] =
shorten_text($installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo][$config['language']], 100);
}
else if (!empty($installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo]['en']))
{
$installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo] =
shorten_text($installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo]['en'], 100);
}
else
{
$installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo] =
shorten_text($installed_plugins[$row['plg_name']]['extra_info'][$localizedInfo][0], 100);
}
}
}
}
$SQL->free($result);
#get available plugins
$dh = opendir(PATH . KLEEJA_PLUGINS_FOLDER);
$available_plugins = array();
while (false !== ($folder_name = readdir($dh)))
{
if (is_dir(PATH . KLEEJA_PLUGINS_FOLDER . '/' . $folder_name) && preg_match('/[a-z0-9_.]{3,}/', $folder_name)) {
if (empty($installed_plugins[$folder_name]))
{
array_push($available_plugins,
array(
'name' => $folder_name,
'icon' => file_exists(PATH . KLEEJA_PLUGINS_FOLDER . '/' . $folder_name . "/icon.png")
? PATH . KLEEJA_PLUGINS_FOLDER . '/' . $folder_name . "/icon.png"
: $STYLE_PATH_ADMIN . 'images/plugin.png',
)
);
}
}
}
@closedir($dh);
$no_plugins = sizeof($available_plugins) == 0 && sizeof($installed_plugins) == 0;
$stylee = "admin_plugins";
break;
//
//upload a plugin
//
case 'upload':
$ERRORS = array();
if(intval($userinfo['founder']) !== 1)
{
$ERRORS[] = $lang['HV_NOT_PRVLG_ACCESS'];
}
#is uploaded?
if(empty($_FILES['plugin_file']['tmp_name']))
{
$ERRORS[] = $lang['CHOSE_F'];
}
#extract it to plugins folder
if(!sizeof($ERRORS))
{
if(class_exists('ZipArchive'))
{
$zip = new ZipArchive;
if ($zip->open($_FILES['plugin_file']['tmp_name']) === true)
{
if(!$zip->extractTo(PATH . KLEEJA_PLUGINS_FOLDER))
{
$ERRORS[] = sprintf($lang['EXTRACT_ZIP_FAILED'], KLEEJA_PLUGINS_FOLDER);
}
$zip->close();
}
else
{
$ERRORS[] = sprintf($lang['EXTRACT_ZIP_FAILED'], KLEEJA_PLUGINS_FOLDER);
}
}
else
{
$ERRORS[] = $lang['NO_ZIP_ARCHIVE'];
}
}
if(!empty($_FILES['plugin_file']['tmp_name']))
{
@unlink($_FILES['plugin_file']['tmp_name']);
}
if(!sizeof($ERRORS))
{
kleeja_admin_info($lang['NO_PROBLEM_AFTER_ZIP'], true, '', true, $action);
}
else
{
kleeja_admin_err('- ' . implode('<br>- ', $ERRORS), ADMIN_PATH . '?cp=' . basename(__file__, '.php'));
}
break;
//
//install a plugin
//
case 'install':
if(intval($userinfo['founder']) !== 1)
{
kleeja_admin_err($lang['HV_NOT_PRVLG_ACCESS'], ADMIN_PATH . '?cp=' . basename(__file__, '.php'));
exit;
}
$plg_name = g('plg', 'str');
if (empty($plg_name))
{
if (defined('DEBUG'))
{
exit('empty($plg_name)');
}
//no plugin selected? back
redirect(ADMIN_PATH . "?cp=" . basename(__file__, '.php'));
}
else
{
if (!file_exists(PATH . KLEEJA_PLUGINS_FOLDER . '/' . $plg_name . '/init.php'))
{
if (defined('DEBUG'))
{
exit('!file_exists($plg_name)');
}
redirect(ADMIN_PATH . "?cp=" . basename(__file__, '.php'));
exit;
}
#if already installed, show a message
if (!empty(Plugins::getInstance()->installed_plugin_info($plg_name)))
{
kleeja_admin_info($lang['PLUGIN_EXISTS_BEFORE'], ADMIN_PATH . '?cp=' . basename(__file__, '.php'));
exit;
}
$kleeja_plugin = array();
include PATH . KLEEJA_PLUGINS_FOLDER . '/' . $plg_name . '/init.php';
$install_callback = $kleeja_plugin[$plg_name]['install'];
$plugin_info = $kleeja_plugin[$plg_name]['information'];
$plugin_first_run = false;
if (!empty($kleeja_plugin[$plg_name]['first_run'][$config['language']]))
{
$plugin_first_run = $kleeja_plugin[$plg_name]['first_run'][$config['language']];
}
else if (!empty($kleeja_plugin[$plg_name]['first_run']['en']))
{
$plugin_first_run = $kleeja_plugin[$plg_name]['first_run']['en'];
}
#check if compatible with kleeja
#'plugin_kleeja_version_min' => '1.8',
# Max version of Kleeja that's required to run this plugin
#'plugin_kleeja_version_max' => '3.8',
if (version_compare(KLEEJA_VERSION, $plugin_info['plugin_kleeja_version_min'], '<'))
{
kleeja_admin_info($lang['PLUGIN_N_CMPT_KLJ'] . '<br>k:' . KLEEJA_VERSION . '|<|p.min:' . $plugin_info['plugin_kleeja_version_min'], ADMIN_PATH . '?cp=' . basename(__file__, '.php'));
exit;
}
if ($plugin_info['plugin_kleeja_version_max'] != '0')
{
if (version_compare(KLEEJA_VERSION, $plugin_info['plugin_kleeja_version_max'], '>'))
{
kleeja_admin_info($lang['PLUGIN_N_CMPT_KLJ'] . '<br>k:' . KLEEJA_VERSION . '|>|p.max:' . $plugin_info['plugin_kleeja_version_max'], ADMIN_PATH . '?cp=' . basename(__file__, '.php'));
exit;
}
}
delete_cache('', true);
if (is_array($plugin_info['plugin_description']))
{
$plugin_info['plugin_description'] = !empty($plugin_info['plugin_description']['en']) ? $plugin_info['plugin_description']['en'] : $plugin_info['plugin_description'][0];
}
#add to database
$insert_query = array(
'INSERT' => '`plg_name` ,`plg_ver`, `plg_author`, `plg_dsc`, `plg_icon`, `plg_uninstall`, `plg_instructions`, `plg_store`, `plg_files`',
'INTO' => "{$dbprefix}plugins",
'VALUES' => "'" . $SQL->escape($plg_name) . "','" . $SQL->escape($plugin_info['plugin_version']) . "', '" . $SQL->escape($plugin_info['plugin_developer']) . "','" . $SQL->escape($plugin_info['plugin_description']) . "', '', '', '', '', ''",
);
$SQL->build($insert_query);
#may God protect you brother.
if(is_callable($install_callback))
{
$install_callback($SQL->insert_id());
}
#show done, msg
$text = '<h3>' . $lang['NEW_PLUGIN_ADDED'] . '</h3>';
if ($plugin_first_run)
{
$text .= $plugin_first_run;
$text .= '<br><hr><a href="' . ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '" class="btn btn-primary btn-lg">' . $lang['GO_BACK_BROWSER'] . '</a>';
}
else
{
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '\');", 2000);</script>' . "\n";
}
$stylee = 'admin_info';
}
break;
//
//uninstall a plugin
//
case 'uninstall':
if(intval($userinfo['founder']) !== 1)
{
kleeja_admin_err($lang['HV_NOT_PRVLG_ACCESS'], ADMIN_PATH . '?cp=' . basename(__file__, '.php'));
exit;
}
$plg_name = g('plg', 'str');
if (empty($plg_name))
{
if (defined('DEV_STAGE'))
{
exit('empty($plg_name)');
}
//no plugin selected? back
redirect(ADMIN_PATH . "?cp=" . basename(__file__, '.php'));
}
else
{
if (!file_exists(PATH . KLEEJA_PLUGINS_FOLDER . '/' . $plg_name . '/init.php'))
{
if (defined('DEV_STAGE'))
{
exit('!file_exists($plg_name)');
}
redirect(ADMIN_PATH . "?cp=" . basename(__file__, '.php'));
exit;
}
$kleeja_plugin = array();
include PATH . KLEEJA_PLUGINS_FOLDER . '/' . $plg_name . '/init.php';
$uninstall_callback = $kleeja_plugin[$plg_name]['uninstall'];
if (!is_callable($uninstall_callback))
{
redirect(ADMIN_PATH . "?cp=" . basename(__file__, '.php'));
exit;
}
$query = array(
'SELECT' => "plg_id",
'FROM' => "{$dbprefix}plugins",
'WHERE' => "plg_name='" . $SQL->escape($plg_name) . "'"
);
$result = $SQL->build($query);
$pluginDatabaseInfo = $SQL->fetch($result);
#sad to see you go, brother
$uninstall_callback(!empty($pluginDatabaseInfo) ? $pluginDatabaseInfo['plg_id'] : 0);
delete_cache('', true);
#remove from database
$query_del = array(
'DELETE' => "`{$dbprefix}plugins`",
'WHERE' => "plg_name='" . $SQL->escape($plg_name) . "'"
);
$SQL->build($query_del);
#show done, msg
$text = '<h3>' . $lang['PLUGIN_DELETED'] . '</h3>';
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '\');", 2000);</script>' . "\n";
$stylee = 'admin_info';
}
break;
//
//disable a plugin
//
case 'disable':
case 'enable':
if(intval($userinfo['founder']) !== 1)
{
kleeja_admin_err($lang['HV_NOT_PRVLG_ACCESS'], ADMIN_PATH . '?cp=' . basename(__file__, '.php'));
exit;
}
$plg_name = g('plg', 'str');
if (empty($plg_name))
{
if (defined('DEV_STAGE'))
{
exit('empty($plg_name)');
}
//no plugin selected? back
redirect(ADMIN_PATH . "?cp=" . basename(__file__, '.php'));
}
else
{
#update database
$update_query = array(
'UPDATE' => "{$dbprefix}plugins",
'SET' => "plg_disabled=" . ($case == 'disable' ? 1 : 0),
'WHERE' => "plg_name='" . $SQL->escape($plg_name) . "'"
);
$SQL->build($update_query);
delete_cache('', true);
#show done, msg
$text = '<h3>' . $lang['PLGUIN_DISABLED_ENABLED'] . '</h3>';
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . ADMIN_PATH . '?cp=' . basename(__file__, '.php') . '\');", 2000);</script>' . "\n";
$stylee = 'admin_info';
}
break;
endswitch;

73
includes/adm/k_ban.php Executable file
View File

@@ -0,0 +1,73 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//for style ..
$stylee = "admin_ban";
$action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php');
$affected = false;
$H_FORM_KEYS = kleeja_add_form_key('adm_ban');
//
// Check form key
//
if (ip('submit'))
{
if(!kleeja_check_form_key('adm_ban'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
}
$query = array(
'SELECT' => 'ban',
'FROM' => "{$dbprefix}stats"
);
$result = $SQL->build($query);
$current_ban_data =$SQL->fetch_array($result);
$ban = p('ban_text', 'str', $current_ban_data['ban']);
//when submit
if (ip('submit'))
{
//update
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => "ban='" . $SQL->escape($ban) . "'"
);
$SQL->build($update_query);
if($SQL->affected())
{
$affected = true;
delete_cache('data_ban');
}
}
$SQL->freeresult($result);
//after submit
if (ip('submit'))
{
$text = ($affected ? $lang['BAN_UPDATED'] : $lang['NO_UP_CHANGE_S']);
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '\');", 2000);</script>' . "\n";
$stylee = "admin_info";
}

75
includes/adm/l_rules.php Executable file
View File

@@ -0,0 +1,75 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//for style ..
$stylee = "admin_rules";
$action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php');
$affected = false;
$H_FORM_KEYS = kleeja_add_form_key('adm_rules');
//
// Check form key
//
if (ip('submit'))
{
if(!kleeja_check_form_key('adm_rules'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
}
$query = array(
'SELECT' => 'rules',
'FROM' => "{$dbprefix}stats"
);
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
$rulesw = p('rules_text', 'str', $row['rules']);
$rules = htmlspecialchars($rulesw);
//when submit
if (ip('submit'))
{
//update
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => "rules = '" . $SQL->real_escape($rulesw) . "'"
);
$SQL->build($update_query);
if($SQL->affected())
{
$affected = true;
delete_cache('data_rules');
}
}
}
$SQL->freeresult($result);
//after submit
if (ip('submit'))
{
$text = ($affected ? $lang['RULES_UPDATED'] : $lang['NO_UP_CHANGE_S']);
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '\');", 2000);</script>' . "\n";
$stylee = "admin_info";
}

235
includes/adm/m_styles.php Executable file
View File

@@ -0,0 +1,235 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
#current secondary menu action
$current_smt = preg_replace('/[^a-z0-9_]/i','', g('smt', 'str', 'general'));
$action = ADMIN_PATH . '?cp=' . basename(__file__, '.php');
$H_FORM_KEYS = kleeja_add_form_key('adm_styles');
//for style ..
$stylee = "admin_styles";
//after submit
if (ip('style_choose') || ig('style_choose'))
{
$style_id = ip('style_choose') ? p('style_choose') : g('style_choose');
$style_id = preg_replace('/[^a-z0-9_\-\.]/i', '', $style_id);
//if empty, let's ignore it
if (empty($style_id))
{
redirect(basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php'));
}
// make style as default
//check _GET Csrf token
if (isset($_REQUEST['home']) && !kleeja_check_form_key_get('adm_start_actions'))
{
kleeja_admin_err($lang['INVALID_GET_KEY'], true, $lang['ERROR'], true, basename(ADMIN_PATH) . '?cp=start', 2);
}
//
//check if this style depend on other style and
//check kleeja version that required by this style
//
if (($style_info = kleeja_style_info($style_id)) != false)
{
if (isset($style_info['depend_on']) && !file_exists(PATH . 'styles/' . $style_info['depend_on']))
{
kleeja_admin_err(sprintf($lang['DEPEND_ON_NO_STYLE_ERR'], $style_info['depend_on']));
}
if (isset($style_info['kleeja_version']) && version_compare(strtolower($style_info['kleeja_version']), strtolower(KLEEJA_VERSION), '>'))
{
kleeja_admin_err(sprintf($lang['KLJ_VER_NO_STYLE_ERR'], $style_info['kleeja_version']));
}
//is this style require some plugins to be installed
if (isset($style_info['plugins_required']))
{
$plugins_required = explode(',', $style_info['plugins_required']);
$plugins_required = array_map('trim', $plugins_required);
$query = array(
'SELECT' => 'plg_name',
'FROM' => "{$dbprefix}plugins",
);
$result = $SQL->build($query);
if ($SQL->num_rows($result) != 0)
{
$plugins_required = array_flip($plugins_required);
while ($row = $SQL->fetch_array($result))
{
if (in_array($row['plg_name'], $plugins_required))
{
unset($plugins_required[$row['plg_name']]);
}
}
}
$SQL->freeresult($result);
$plugins_required = array_flip($plugins_required);
if (sizeof($plugins_required))
{
kleeja_admin_err(sprintf($lang['PLUGINS_REQ_NO_STYLE_ERR'], implode(', ', $plugins_required)));
}
}
}
//make it as default
update_config('style', $style_id);
update_config('style_depend_on', isset($style_info['depend_on']) ? $style_info['depend_on'] : '');
//delete all cache to get new style
delete_cache('', true);
//show msg
kleeja_admin_info(sprintf($lang['STYLE_NOW_IS_DEFAULT'], htmlspecialchars($style_id)), true, '', true, basename(ADMIN_PATH) . '?cp=' . (isset($_REQUEST['home']) ? 'start' : basename(__file__, '.php')));
}
else if (ip('newstyle'))
{
if(intval($userinfo['founder']) !== 1)
{
$ERRORS[] = $lang['HV_NOT_PRVLG_ACCESS'];
}
if(!kleeja_check_form_key('adm_styles'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action);
}
$ERRORS = array();
#is uploaded?
if(empty($_FILES['style_file']['tmp_name']))
{
$ERRORS[] = $lang['CHOSE_F'];
}
#extract it to plugins folder
if(!sizeof($ERRORS))
{
if(class_exists('ZipArchive'))
{
$zip = new ZipArchive;
if ($zip->open($_FILES['style_file']['tmp_name']) === true)
{
if(!$zip->extractTo(PATH . 'styles'))
{
$ERRORS[] = sprintf($lang['EXTRACT_ZIP_FAILED'], 'styles');
}
$zip->close();
}
else
{
$ERRORS[] = sprintf($lang['EXTRACT_ZIP_FAILED'], 'styles');
}
}
else
{
$ERRORS[] = $lang['NO_ZIP_ARCHIVE'];
}
}
if(!empty($_FILES['style_file']['tmp_name']))
{
@unlink($_FILES['style_file']['tmp_name']);
}
if(!sizeof($ERRORS))
{
kleeja_admin_info($lang['NO_PROBLEM_AFTER_ZIP'], true, '', true, $action);
}
else
{
kleeja_admin_err('- ' . implode('<br>- ', $ERRORS), $action);
}
}
//get styles
$arr = array();
if ($dh = @opendir(PATH . 'styles'))
{
while (false !== ($folder_name = readdir($dh)))
{
if (is_dir(PATH . 'styles/' . $folder_name) && preg_match('/[a-z0-9_.]{3,}/', $folder_name))
{
#info
$style_info_arr = array
(
'name' => $folder_name,
'desc' => '',
'copyright'=> '',
'version'=> ''
);
if(($style_info = kleeja_style_info($folder_name)) != false)
{
foreach (array('name', 'desc', 'copyright', 'version') as $InfoKey)
{
if (array_key_exists($InfoKey, $style_info))
{
if(is_array($style_info[$InfoKey]))
{
$style_info_arr[$InfoKey] = !empty($style_info[$InfoKey][$config['language']])
? htmlspecialchars($style_info[$InfoKey][$config['language']])
: htmlspecialchars($style_info[$InfoKey]['en']);
}
else
{
$style_info_arr[$InfoKey] = htmlspecialchars($style_info[$InfoKey]);
}
}
}
}
$arr[] = array
(
'style_name' => $folder_name,
'is_default' => $config['style'] == $folder_name ? true : false,
'link_mk_default' => basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&amp;style_choose=' . $folder_name,
'icon' => file_exists(PATH . 'styles/' . $folder_name . "/screenshot.png")
? PATH . 'styles/' . $folder_name . "/screenshot.png"
: $STYLE_PATH_ADMIN . 'images/style.png',
'info' => $style_info_arr
);
}
}
@closedir($dh);
}

106
includes/adm/n_extra.php Executable file
View File

@@ -0,0 +1,106 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//for style ..
$stylee = "admin_extra";
$current_smt= preg_replace('/[^a-z0-9_]/i', '', g('smt', 'str', 'he'));
$action = basename(ADMIN_PATH) . '?cp=' . basename(__file__, '.php') . '&amp;smt=' . $current_smt;
$H_FORM_KEYS= kleeja_add_form_key('adm_extra');
//
// Check form key
//
if (ip('submit'))
{
if(!kleeja_check_form_key('adm_extra'))
{
kleeja_admin_err($lang['INVALID_FORM_KEY'], true, $lang['ERROR'], true, $action, 1);
}
}
$query = array(
'SELECT' => 'ex_header,ex_footer',
'FROM' => "{$dbprefix}stats"
);
$result = $SQL->build($query);
//is there any change !
$affected = false;
$extras = $SQL->fetch_array($result);
//when submit
if (ip('submit'))
{
$update_sql = '';
if(g('smt') == 'fe')
{
$ex_footer = p('ex_footer', 'str');
$update_sql = "ex_footer = '" . $SQL->real_escape(htmlspecialchars_decode($ex_footer)) . "'";
}
else
{
$ex_header = p('ex_header', 'str');
$update_sql = "ex_header = '" . $SQL->real_escape(htmlspecialchars_decode($ex_header)) . "'";
}
//update
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => $update_sql
);
$SQL->build($update_query);
if($SQL->affected())
{
$affected = true;
//delete cache ..
delete_cache('data_extra');
}
}
else
{
extract($extras);
}
//reverse
//$ex_header = htmlspecialchars_decode($ex_header);
//$ex_footer = htmlspecialchars_decode($ex_footer);
$SQL->freeresult($result);
//after submit
if (ip('submit'))
{
kleeja_admin_info(($affected ? $lang['EXTRA_UPDATED'] : $lang['NO_UP_CHANGE_S']), true, '', true, $action);
}
//secondary menu
$go_menu = array(
'he' => array('name'=>$lang['ADD_HEADER_EXTRA'], 'link'=> basename(ADMIN_PATH) . '?cp=n_extra&amp;smt=he', 'goto'=>'he', 'current'=> $current_smt == 'he'),
'fe' => array('name'=>$lang['ADD_FOOTER_EXTRA'], 'link'=> basename(ADMIN_PATH) . '?cp=n_extra&amp;smt=fe', 'goto'=>'fe', 'current'=> $current_smt == 'fe'),
);

106
includes/adm/p_check_update.php Executable file
View File

@@ -0,0 +1,106 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
$stylee = "admin_check_update";
$current_smt = preg_replace('/[^a-z0-9_]/i', '', g('smt', 'str', 'general'));
$error = false;
$update_link = $config['siteurl'] . 'install/update.php?lang=' . $config['language'];
#to prevent getting the url data for all cats
if($current_smt == 'general'):
//get data from kleeja database
$b_url = empty($_SERVER['SERVER_NAME']) ? $config['siteurl'] : $_SERVER['SERVER_NAME'];
$b_data = fetch_remote_file('http://www.kleeja.com/check_vers/?i=' . urlencode($b_url) . '&v=' . KLEEJA_VERSION, false, 6);
if ($b_data === false && !ig('show_msg'))
{
$text = $lang['ERROR_CHECK_VER'];
$error = true;
}
else
{
//
// there is a file that we brought it !
//
$b_data = @explode('|', $b_data);
$version_data = trim(htmlspecialchars($b_data[0]));
if (version_compare(strtolower(KLEEJA_VERSION), strtolower($version_data), '<'))
{
$text = sprintf($lang['UPDATE_NOW_S'] , KLEEJA_VERSION, strtolower($version_data)) . '<br /><br />' . $lang['UPDATE_KLJ_NOW'];
$error = true;
}
else if (version_compare(strtolower(KLEEJA_VERSION), strtolower($version_data), '='))
{
$text = $lang['U_LAST_VER_KLJ'];
}
else if (version_compare(strtolower(KLEEJA_VERSION), strtolower($version_data), '>'))
{
$text = $lang['U_USE_PRE_RE'];
}
//lets recore it
$v = @unserialize($config['new_version']);
//To prevent expected error [ infinit loop ]
if(ig('show_msg'))
{
$query_get = array(
'SELECT' => '*',
'FROM' => "{$dbprefix}config",
'WHERE' => "name = 'new_version'"
);
$result_get = $SQL->build($query_get);
if(!$SQL->num_rows($result_get))
{
//add new config value
add_config('new_version', '');
}
}
$data = array(
'version_number' => $version_data,
'last_check' => time(),
'msg_appeared' => ig('show_msg') ? true : false,
'copyrights' => !empty($b_data[1]) && strpos($b_data[1], 'yes') !== false ? true : false,
);
$data = serialize($data);
update_config('new_version', $SQL->real_escape($data), false);
delete_cache('data_config');
}
//then go back to start
if(ig('show_msg'))
{
redirect(basename(ADMIN_PATH) . '?update_done=1');
$SQL->close();
exit;
}
#end current_smt == general
endif;
//secondary menu
$go_menu = array(
'general' => array('name'=>$lang['R_CHECK_UPDATE'], 'link'=> basename(ADMIN_PATH) . '?cp=p_check_update&amp;smt=general', 'goto'=>'general', 'current'=> $current_smt == 'general'),
'howto' => array('name'=>$lang['HOW_UPDATE_KLEEJA'], 'link'=> basename(ADMIN_PATH) . '?cp=p_check_update&amp;smt=howto', 'goto'=>'howto', 'current'=> $current_smt == 'howto'),
'site' => array('name'=>'Kleeja.com', 'link'=> 'http://www.kleeja.com', 'goto'=>'site', 'current'=> $current_smt == 'site'),
);

192
includes/adm/r_repair.php Executable file
View File

@@ -0,0 +1,192 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
#turn time-limit off
@set_time_limit(0);
#get current case
$case = false;
if(ig('case'))
{
$case = g('case');
}
#set form ket
$GET_FORM_KEY = kleeja_add_form_key_get('REPAIR_FORM_KEY');
//check _GET Csrf token
if($case && in_array($case, array('clearc', 'sync_files', 'sync_images', 'sync_users', 'tables', 'sync_sizes', 'status_file')))
{
if(!kleeja_check_form_key_get('REPAIR_FORM_KEY'))
{
kleeja_admin_err($lang['INVALID_GET_KEY'], true, $lang['ERROR'], true, basename(ADMIN_PATH), 2);
}
}
switch($case):
default:
# Get real number from database right now
$all_files = get_actual_stats('files');
$all_images = get_actual_stats('imgs');
$all_users = get_actual_stats('users');
$all_sizes = readable_size(get_actual_stats('sizes'));
#links
$del_cache_link = basename(ADMIN_PATH) . '?cp=r_repair&amp;case=clearc&amp;' . $GET_FORM_KEY;
$resync_files_link = $config['siteurl'] . 'go.php?go=resync&amp;case=sync_files';
$resync_images_link = $config['siteurl'] . 'go.php?go=resync&amp;case=sync_images';
$resync_users_link = basename(ADMIN_PATH) . '?cp=r_repair&amp;case=sync_users&amp;' . $GET_FORM_KEY;
$resync_sizes_link = basename(ADMIN_PATH) . '?cp=r_repair&amp;case=sync_sizes&amp;' . $GET_FORM_KEY;
$repair_tables_link = basename(ADMIN_PATH) . '?cp=r_repair&amp;case=tables&amp;' . $GET_FORM_KEY;
$queue_cron_job_url = $config['siteurl'] . 'go.php?go=queue';
$stylee = "admin_repair";
break;
//
//fix tables ..
//
case 'tables':
$query = "SHOW TABLE STATUS";
$result = $SQL->query($query);
$text = '';
while($row=$SQL->fetch_array($result))
{
$queryf = "REPAIR TABLE `" . $row['Name'] . "`";
$resultf = $SQL->query($queryf);
if ($resultf)
{
$text .= '<li>' . $lang['REPAIRE_TABLE'] . $row['Name'] . '</li>';
}
}
$SQL->freeresult($result);
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . basename(ADMIN_PATH) . '?cp=r_repair' . '\');", 2000);</script>' . "\n";
$stylee = 'admin_info';
break;
//
//re-sync sizes ..
//
case 'sync_sizes':
$query_s = array(
'SELECT' => 'size',
'FROM' => "{$dbprefix}files"
);
$result_s = $SQL->build($query_s);
$files_number = $files_sizes = 0;
while($row=$SQL->fetch_array($result_s))
{
$files_number++;
$files_sizes = $files_sizes+$row['size'];
}
$SQL->freeresult($result_s);
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => "files=" . $files_number . ", sizes=" . $files_sizes
);
if ($SQL->build($update_query))
{
$text .= '<li>' . $lang['REPAIRE_F_STAT'] . '</li>';
}
delete_cache('data_stats');
$stylee = 'admin_info';
break;
//
//re-sync total users number ..
//
case 'sync_users':
$query_w = array(
'SELECT' => 'name',
'FROM' => "{$dbprefix}users"
);
$result_w = $SQL->build($query_w);
$user_number = 0;
while($row=$SQL->fetch_array($result_w))
{
$user_number++;
}
$SQL->freeresult($result_w);
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => "users=" . $user_number
);
$result = $SQL->build($update_query);
delete_cache('data_stats');
$text = sprintf($lang['SYNCING'], $lang['USERS_ST']);
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . basename(ADMIN_PATH) . '?cp=r_repair' . '\');", 2000);</script>' . "\n";
$stylee = 'admin_info';
break;
//
//clear all cache ..
//
case 'clearc':
#clear cache
delete_cache('', true);
#show done, msg
$text .= '<li>' . $lang['REPAIRE_CACHE'] . '</li>';
$text .= '<script type="text/javascript"> setTimeout("get_kleeja_link(\'' . basename(ADMIN_PATH) . '?cp=r_repair' . '\');", 2000);</script>' . "\n";
$stylee = 'admin_info';
break;
endswitch;

350
includes/adm/start.php Executable file
View File

@@ -0,0 +1,350 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
// not for directly open
if (!defined('IN_ADMIN'))
{
exit();
}
//style of
$stylee = "admin_start";
$h_lst_files = basename(ADMIN_PATH) . '?cp=c_files&amp;last_visit=';
$h_lst_imgs = basename(ADMIN_PATH) . '?cp=d_img_ctrl&amp;last_visit=';
$current_smt = preg_replace('/[^a-z0-9_]/i', '', g('smt', 'str', 'general'));
$GET_FORM_KEY = kleeja_add_form_key_get('adm_start_actions');
//data
$lst_reg = empty($stat_last_user) ? $lang['UNKNOWN'] : $stat_last_user;
$files_number = $stat_files + $stat_imgs;
$files_sizes = readable_size($stat_sizes);
$users_number = $stat_users;
$last_del_fles = (int) $config['del_f_day'] <= 0 ? $lang['CLOSED_FEATURE'] : kleeja_date($stat_last_f_del);
$php_version = isset($NO_PHPINFO) || !function_exists('phpinfo') ? phpversion() : 'PHP ' . phpversion();
$mysql_version = 'MySQL ' . $SQL->mysql_version();
$max_execution_time = function_exists('ini_get') ? @ini_get('max_execution_time') : @get_cfg_var('max_execution_time');
$upload_max_filesize= function_exists('ini_get') ? @ini_get('upload_max_filesize') : @get_cfg_var('upload_max_filesize');
$post_max_size = function_exists('ini_get') ? @ini_get('post_max_size') : @get_cfg_var('post_max_size');
$memory_limit = function_exists('ini_get') ? @ini_get('memory_limit') : @get_cfg_var('memory_limit');
$s_last_google = $stat_last_google == 0 ? '[ ? ]' : kleeja_date($stat_last_google);
$s_google_num = $stat_google_num;
$s_last_bing = $stat_last_bing == 0 ? '[ ? ]' : kleeja_date($stat_last_bing);
$s_bing_num = $stat_bing_num;
$usernamelang = sprintf($lang['KLEEJA_CP_W'], $username);
$current_year = date('Y');
$progress_session_cleanup = function_exists('ini_get') ? @ini_get('session.upload_progress.cleanup') : @get_cfg_var('session.upload_progress.cleanup');
$progress_session_enabled = function_exists('ini_get') ? @ini_get('session.upload_progress.enabled') : @get_cfg_var('session.upload_progress.enabled');
$extra_adm_start_html = '';
//size board by percent
$per = $stat_sizes / ($config['total_size'] * 1048576);
$per1 = round($per*100, 2);
$per1 = $per1 >= 100 ? 100 : $per1;
//ppl must know about kleeja version!
$kleeja_version = '<a href="' . basename(ADMIN_PATH) . '?cp=p_check_update" onclick="javascript:get_kleeja_link(this.href, \'#content\'); return false;" title="' . $lang['R_CHECK_UPDATE'] . '">' . KLEEJA_VERSION . '</a>';
//admin messages system
$ADM_NOTIFICATIONS = array();
//useing IE6 ! and he is admin ? omg !
$u_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) strtolower($_SERVER['HTTP_USER_AGENT'])) : (function_exists('getenv') ? getenv('HTTP_USER_AGENT') : '');
if(is_browser('ie6, ie8, ie7'))
{
$ADM_NOTIFICATIONS['IE6'] = array('id' => 'IE6', 'msg_type'=> 'error', 'title'=> $lang['NOTE'], 'msg'=> $lang['ADMIN_USING_IE6']);
}
//if upgrading from 1rc6 to 1.0, some files must be deleted !
if(file_exists(PATH . 'includes/adm/files.php') || file_exists(PATH . 'admin.php'))
{
$ADM_NOTIFICATIONS['old_files'] = array('id' => 'old_files', 'msg_type'=> 'info', 'title'=> $lang['NOTE'], 'msg'=> $lang['ADM_UNWANTED_FILES']);
}
//if html url is enabled but .htaccess is not available in the root dir !
if(!file_exists(PATH . '.htaccess') && (int) $config['mod_writer'] == 1)
{
$ADM_NOTIFICATIONS['htmlurlshtaccess'] = array('id' => 'htmlurlshtaccess', 'msg_type'=> 'info', 'title'=> $lang['NOTE'], 'msg'=> $lang['HTML_URLS_ENABLED_NO_HTCC']);
}
//updating
$v = @unserialize($config['new_version']);
if(version_compare(strtolower(KLEEJA_VERSION), strtolower($v['version_number']), '<'))
{
$ADM_NOTIFICATIONS['up_ver_klj'] = array(
'id' => 'up_ver_klj',//this not so important row
'msg_type'=> 'error', 'title'=> $lang['R_CHECK_UPDATE'],
'msg'=> sprintf($lang['UPDATE_NOW_S'] , KLEEJA_VERSION, $v['version_number']) . '<br />' . '<a href="http://www.kleeja.com/">www.kleeja.com</a>'
);
is_array($plugin_run_result = Plugins::getInstance()->run('admin_update_now', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
}
//for progress bar
//if(!$progress_session_enabled)
//{
// $ADM_NOTIFICATIONS[] = array(
// 'id' => 'progress_session_enabled',
// 'msg_type'=> 'info', 'title'=> ('advice for php.ini'),
// 'msg'=> sprintf(('Kleeja developers advise you to change the option "%1$s" to "%2$s" in PHP.INI on your server.') , 'session.upload_progress.enabled', 'On')
// );
//}
is_array($plugin_run_result = Plugins::getInstance()->run('default_admin_page', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
//check upload_max_filesize
if(!empty($d_groups) && is_array($d_groups))
{
$biggest_size = 0;
foreach($d_groups as $gid => $gdata)
{
if(!empty($d_groups[$gid]['exts']) && is_array($d_groups[$gid]['exts']))
{
$u_e_s = $d_groups[$gid]['exts'];
arsort($u_e_s);
if(!empty($u_e_s))
{
$current_size = array_shift($u_e_s);
$biggest_size = $current_size > $biggest_size ? $current_size : $biggest_size;
}
}
}
if(strpos($upload_max_filesize, 'M') !== false)
{
$upload_max_filesize_s = ((int) trim(str_replace('M', '', $upload_max_filesize))) * 1048576;
}
else if(strpos($upload_max_filesize, 'G') !== false)
{
$upload_max_filesize_s = ((int) trim(str_replace('G', '', $upload_max_filesize))) * 1073741824;
}else{
$upload_max_filesize_s = $upload_max_filesize;
}
if(!empty($upload_max_filesize) && $upload_max_filesize_s < $biggest_size)
{
$ADM_NOTIFICATIONS['file_size_ini_low'] = array(
'id' => 'file_size_ini_low',
'msg_type'=> 'info', 'title'=> $lang['NOTE'],
'msg'=> sprintf($lang['PHPINI_FILESIZE_SMALL'] , readable_size($biggest_size), readable_size($upload_max_filesize_s))
);
}
//check post_max_size
if(strpos($post_max_size, 'M') !== false)
{
$post_max_size_s = ((int) trim(str_replace('M', '', $post_max_size))) * 1048576;
}
else if(strpos($post_max_size, 'G') !== false)
{
$post_max_size_s = ((int) trim(str_replace('G', '', $post_max_size))) * 1073741824;
}else
{
$post_max_size_s = $post_max_size;
}
$post_max_size_s_must_be = ($config['filesnum'] * $biggest_size) + 5242880;//+ 5 mega to make sure it's ok
if(!empty($post_max_size) && $post_max_size_s < $post_max_size_s_must_be)
{
$ADM_NOTIFICATIONS['post_m_size_ini_low'] = array(
'id' => 'post_m_size_ini_low',
'msg_type'=> 'info', 'title'=> $lang['NOTE'],
'msg'=> sprintf($lang['PHPINI_MPOSTSIZE_SMALL'] , $config['filesnum'], readable_size($post_max_size_s_must_be))
);
}
}
//
// if 3 days, lets check again !
// rev: let's say cache is not refreshed, so we will redirect alots of time,
// so update_done will be good solution
//
if (empty($v['last_check']) || ((time() - $v['last_check']) > 259200 && !$v['msg_appeared'] && $_SERVER['SERVER_NAME'] != 'localhost' && !ig('update_done')))
{
redirect(basename(ADMIN_PATH) . '?cp=p_check_update&amp;show_msg=1');
$SQL->close();
exit;
}
//if config not safe
if(function_exists('fileperms') && !defined('KLEEJA_NO_CONFIG_CHECK') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' && !@ini_get('safe_mode'))
{
if((bool) (@fileperms(PATH . KLEEJA_CONFIG_FILE) & 0x0002))
{
$ADM_NOTIFICATIONS['config_perm'] = array('id' => 'config_perm', 'msg_type'=> 'info', 'title'=> $lang['NOTE'], 'msg'=> $lang['CONFIG_WRITEABLE']);
}
}
//no htaccess
if(!file_exists(PATH . $config['foldername'] . '/.htaccess'))
{
$ADM_NOTIFICATIONS['htaccess_u'] = array('id' => 'htaccess_u', 'msg_type'=> 'error', 'title'=> $lang['WARN'], 'msg'=> sprintf($lang['NO_HTACCESS_DIR_UP'], $config['foldername']));
}
if(!file_exists(PATH . $config['foldername'] . '/thumbs/.htaccess'))
{
$ADM_NOTIFICATIONS['htaccess_t'] = array('id' => 'htaccess_t', 'msg_type'=> 'error', 'title'=> $lang['WARN'], 'msg'=> sprintf($lang['NO_HTACCESS_DIR_UP_THUMB'], $config['foldername'] . '/thumbs'));
}
//there is cleaning files process now
if((int)$config['klj_clean_files_from'] > 0)
{
$ADM_NOTIFICATIONS['klj_clean_files'] = array('id' => 'klj_clean_files', 'msg_type'=> 'info', 'title'=> $lang['NOTE'], 'msg'=> $lang['T_CLEANING_FILES_NOW']);
}
//if there is no thumbs folder
if(!file_exists(PATH . $config['foldername'] . '/thumbs') && (int) $config['thumbs_imgs'] != 0)
{
$ADM_NOTIFICATIONS['no_thumbs'] = array('id' => 'no_thumbs', 'msg_type'=> 'info', 'title'=> $lang['NOTE'], 'msg'=> sprintf($lang['NO_THUMB_FOLDER'], PATH . $config['foldername'] . '/thumbs'));
}
//is there copyrights for translator ?
$translator_copyrights = isset($lang['S_TRANSLATED_BY']) ? $lang['S_TRANSLATED_BY'] : false;
//secondary menu
$go_menu = array(
'general' => array('name'=>$lang['GENERAL_STAT'], 'link'=> basename(ADMIN_PATH) . '?cp=start&amp;smt=general', 'goto'=>'general', 'current'=> $current_smt == 'general'),
'other' => array('name'=>$lang['OTHER_INFO'], 'link'=> basename(ADMIN_PATH) . '?cp=start&amp;smt=other', 'goto'=>'other', 'current'=> $current_smt == 'other'),
'team' => array('name'=>$lang['KLEEJA_TEAM'], 'link'=> basename(ADMIN_PATH) . '?cp=start&amp;smt=team', 'goto'=>'team', 'current'=> $current_smt == 'team'),
);
# is there a last visit of images and files ?
$files_last_visit = filter_exists('f_lastvisit', 'filter_uid', 'lastvisit', $userinfo['id'])
? get_filter('f_lastvisit', 'lastvisit', true, 'filter_uid', $userinfo['id']) : false;
$image_last_visit = filter_exists('i_lastvisit', 'filter_uid', 'lastvisit', $userinfo['id'])
? get_filter('i_lastvisit', 'lastvisit', true, 'filter_uid', $userinfo['id']) : false;
#hurry, hurry section, get styles
$hurry_style_link = basename(ADMIN_PATH) . '?cp=m_styles&amp;sty_t=st&amp;method=2&amp;home=1&amp;smt=curstyle&amp;' . $GET_FORM_KEY . '&amp;style_choose=';
$hurry_styles_list = '';
if ($dh = @opendir(PATH . 'styles'))
{
while (($file = @readdir($dh)) !== false)
{
if(strpos($file, '.') === false && $file != '..' && $file != '.')
{
$hurry_styles_list .= '<option value="' . htmlspecialchars($file) . '"' . ($config['style'] == $file ? ' selected="selected"' : '') . '>' . $file . '</option>';
}
}
@closedir($dh);
}
#hurry, hurry section, get languages
$hurry_lang_link = basename(ADMIN_PATH) . '?cp=g_users&smt=general&amp;smt=group_data&' . $GET_FORM_KEY . '&amp;lang_change=';
$hurry_langs_list = '';
if ($dh = @opendir(PATH . 'lang'))
{
while (($file = @readdir($dh)) !== false)
{
if(strpos($file, '.') === false && $file != '..' && $file != '.')
{
$hurry_langs_list .= '<option value="' . htmlspecialchars($file) . '"' . ($d_groups[$config['default_group']]['configs']['language'] == $file ? ' selected="selected"' : '') . '>' . $file . '</option>';
}
}
@closedir($dh);
}
$hurry_groups_list = '<option value="-1" selected="selected">' . $lang['ALL'] . '</option>';
$hurry_groups_list .= '<option value="' . $config['default_group'] . '">' . $lang['DEFAULT_GROUP'] . '</option>';
foreach($d_groups as $id=>$ddt)
{
$hurry_groups_list .= '<option value="' . $id . '">' .
str_replace(array('{lang.ADMINS}', '{lang.USERS}', '{lang.GUESTS}'),
array($lang['ADMINS'], $lang['USERS'], $lang['GUESTS']),
$d_groups[$id]['data']['group_name']) .
'</option>';
}
#hurry, hurry section, links
$del_cache_link = basename(ADMIN_PATH) . '?cp=r_repair&amp;case=clearc&amp;' . kleeja_add_form_key_get('REPAIR_FORM_KEY');
# get stats filter so we can draw a chart for the user
$stats_chart = false;
$cf_query = array(
'SELECT' => 'f.filter_uid, f.filter_value, f.filter_time',
'FROM' => "{$dbprefix}filters f",
'WHERE' => "f.filter_type = 'stats_for_acp'",
'ORDER BY' => 'f.filter_time DESC',
);
$cf_result = $SQL->build($cf_query);
$cf_num = $SQL->num_rows($cf_result);
if($cf_num > 3)
{
$stats_chart = 'arrayOfDataMulti = new Array(';
$comma = false;
#get currently right now stats
$prv_files = get_actual_stats('files');
$prev_imgs = get_actual_stats('imgs');
$prev_date = date('d-n-Y');
while($row=$SQL->fetch_array($cf_result))
{
#jump today
if($prev_date == $row['filter_uid'])
{
continue;
}
#get this row data
list($s_files, $s_imgs, $s_sizes) = explode(':', $row['filter_value']);
$t_files = $prv_files - $s_files;
$t_imgs = $prev_imgs - $s_imgs;
$day = date('d-n-Y') == $prev_date ? $lang['TODAY'] . ' ~ ' . $lang['NOW'] : $prev_date;
$stats_chart .= ($comma ? ',': '') . "[[$t_files,$t_imgs],'" . ($cf_num > 6 ? str_replace(date('-Y'), '', $day) : $day) . "']";
$comma = true;
$prv_files = $s_files;
$prev_imgs = $s_imgs;
$prev_date = $row['filter_uid'];
}
$stats_chart .= ');';
is_array($plugin_run_result = Plugins::getInstance()->run('stats_start_admin', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$SQL->freeresult($cf_result);
#clean old chart stats
if($cf_num > 10)
{
$query_del = array(
'DELETE' => "{$dbprefix}filters",
'WHERE' => "filter_type = 'stats_for_acp' AND filter_time < " . (time() - (3600 * 24 * 10))
);
$SQL->build($query_del);
}
}

BIN
includes/arial.gdf Executable file

Binary file not shown.

BIN
includes/arial.ttf Executable file

Binary file not shown.

117
includes/auth_integration/api.php Executable file
View File

@@ -0,0 +1,117 @@
<?php
/**
*
* @package auth
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
function kleeja_auth_login ($name, $pass, $hashed = false, $expire, $loginadm = false, $return_username = false)
{
global $lang, $config, $usrcp, $userinfo;
global $script_path, $script_api_key, $script_cp1256;
//URL must be begin with http://
if(empty($script_path) || $script_path[0] != 'h')
{
big_error('Forum URL must be begin with http://', sprintf($lang['SCRIPT_AUTH_PATH_WRONG'], 'API'));
}
//api key is the key to make the query between the remote script and kleeja more secure !
//this must be changed in the real use
if(empty($script_api_key))
{
big_error('api key', 'To connect to the remote script you have to write the API key ...');
}
$pass = empty($script_cp1256) || !$script_cp1256 ? $pass : $usrcp->kleeja_utf8($pass, false);
$name = empty($script_cp1256) || !$script_cp1256 || $hashed ? $name : $usrcp->kleeja_utf8($name, false);
/*
@see file : docs/kleeja_(vb,mysmartbb,phpbb)_api.txt
*/
$api_http_query = 'api_key=' . kleeja_base64_encode($script_api_key) . '&' . ($hashed ? 'userid' : 'username') . '=' . urlencode($name) . '&pass=' . kleeja_base64_encode($pass);
//if only username, let tell him in the query
$api_http_query .= $return_username ? '&return_username=1' : '';
//get it
$remote_data = fetch_remote_file($script_path . '?' . $api_http_query);
//no responde
//empty or can not connect
if ($remote_data == false || empty($remote_data))
{
return false;
}
//see kleeja_api.php file
//split the data , the first one is always 0 or 1
//0 : error
//1: ok
$user_info = explode('%|%', kleeja_base64_decode($remote_data));
//omg, it's 0 , 0 : error, lets die here
if((int)$user_info[0] == 0)
{
return false;
}
//
//if we want username only we have to return it quickly and die here
//
if($return_username)
{
return empty($script_cp1256) || !$script_cp1256 ? $user_info[1] : $usrcp->kleeja_utf8($user_info[1]);
}
//
//when loggin to admin, we just want a check, no data setup ..
//
if(!$loginadm)
{
define('USER_ID', $user_info[1]);
define('GROUP_ID', 3);
define('USER_NAME', empty($script_cp1256) || !$script_cp1256 ? $user_info[2] : $usrcp->kleeja_utf8($user_info[2]));
define('USER_MAIL', $user_info[3]);
define('USER_ADMIN', ((int) $user_info[5] == 1) ? 1 : 0);
}
//user ifo
//and this must be filled with user data comming from url
$userinfo = array();
$userinfo['group_id'] = GROUP_ID;
$user_y = kleeja_base64_encode(serialize(array('id'=>USER_ID, 'name'=>USER_NAME, 'mail'=>USER_MAIL, 'last_visit'=>time())));
//add cookies
if(!$loginadm)
{
$usrcp->kleeja_set_cookie('ulogu', $usrcp->en_de_crypt($user_info[1] . '|' . $user_info[4] . '|' . $expire . '|' . sha1(md5($config['h_key'] . $user_info[4]) . $expire) . '|' . GROUP_ID . '|' . $user_y), $expire);
}
//no need after now
unset($pass);
//yes ! he is a real user
return true;
}
//
//return username
//
function kleeja_auth_username ($user_id)
{
return kleeja_auth_login($user_id, false, false, false, false, true);
}
//<-- EOF

View File

@@ -0,0 +1,58 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256"/>
<title>Powered by Kleeja</title>
<style type="text/css">* {
font-size: 100%;
margin: 0;
padding: 0;
color: #CECFCE;
}
body {
font-family: Tahoma, Arial, sans-serif;
font-size: 100%;
color: #69788E;
margin: 10px 30px;
background: #F7F7F7;
}
a:link, a:visited {
text-decoration: none;
color: #CECFCE;
}
a:active, a:hover {
text-decoration: underline;
color: #111;
}
h1 {
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-size: 1.70em;
font-weight: normal;
color: #333333;
margin-top: 0;
margin-bottom: 10px;
}
.content_box {
border: 1px dashed #CECFCE;
background: #FFFFFF;
padding: 10px;
margin-right: auto;
margin-left: auto;
}</style>
</head>
<body title="&#1603;&#1604;&#1610;&#1580;&#1575;"><br/>
<div class="content_box">
<p>
<a target="_blank" href="http://www.kleeja.com" title="kleeja"></a>
</p>
<br/>
<h1><span style="font-size:250%;color:#D80000;">403 - Access forbidden!</span></h1></div>
<br/>
<div class="content_box"style="font-size: 140%">Powered by Kleeja</div>
</body>
</html>

View File

@@ -0,0 +1,352 @@
<?php
/**
*
* @package auth
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
//
//Path of config file in phpBB3
//
if(!defined('SCRIPT_CONFIG_PATH'))
{
define('SCRIPT_CONFIG_PATH', '/config.php');
}
function kleeja_auth_login ($name, $pass, $hashed = false, $expire, $loginadm = false, $return_name = false)
{
global $lang, $config, $usrcp, $userinfo;
global $script_path, $script_encoding, $script_srv, $script_db, $script_user, $script_pass, $script_prefix;
//check for last slash /
if(isset($script_path))
{
if(isset($script_path[strlen($script_path)]) && $script_path[strlen($script_path)] == '/')
{
$script_path = substr($script_path, 0, strlen($script_path));
}
//get some useful data from phbb config file
if(file_exists(PATH . $script_path . SCRIPT_CONFIG_PATH))
{
include (PATH . $script_path . SCRIPT_CONFIG_PATH);
$forum_srv = $dbhost;
$forum_db = $dbname;
$forum_user = $dbuser;
$forum_pass = $dbpasswd;
$forum_prefix = $table_prefix;
if(empty($dbhost))
{
$forum_srv = 'localhost';
}
if(!empty($dbport))
{
$forum_srv .= ':' . $dbport;
}
}
else
{
big_error('Forum path is not correct', sprintf($lang['SCRIPT_AUTH_PATH_WRONG'], 'phpBB3'));
}
}
else
{
$forum_srv = $script_srv;
$forum_db = $script_db;
$forum_user = $script_user;
$forum_pass = $script_pass;
$forum_prefix = $script_prefix;
}
//if no variables of db
if(empty($forum_srv) || empty($forum_user) || empty($forum_db))
{
return;
}
//conecting ...
$SQLBB = new KleejaDatabase($forum_srv, $forum_user, $forum_pass, $forum_db, true);
$SQLBB->set_names('utf8');
unset($forum_pass); // We do not need this any longer
//get utf tools
global $phpbb_root_path, $phpEx;
$phpbb_root_path = PATH . $script_path . '/';
$phpEx = 'php';
define('IN_PHPBB', true);
include_once (PATH . $script_path . '/includes/utf/utf_tools.' . $phpEx);
$row_leve = 'user_type';
$admin_level = 3;
$query2 = array(
'SELECT' => '*',
'FROM' => "`{$forum_prefix}users`",
);
$query2['WHERE'] = $hashed ? "user_id=" . intval($name) . " AND user_password='" . $SQLBB->real_escape($pass) . "' " : "username_clean='" . $SQLBB->real_escape(utf8_clean_string($name)) . "'";
if($return_name)
{
$query2['SELECT'] = "username";
$query2['WHERE'] = "user_id=" . intval($name);
}
$query = '';
if(!$hashed)
{
$result2 = $SQLBB->build($query2);
while($row=$SQLBB->fetch_array($result2))
{
$SQLBB->freeresult($result2);
if($return_name)
{
return $row['username'];
}
else
{
if(phpbb_check_hash($pass, $row['user_password']))
{
$query = $query2;
}
}
}
}
else
{
$query = $query2;
}
if(empty($query))
{
$SQLBB->close();
return false;
}
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_usrdata_phpbb_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQLBB->build($query);
if ($SQLBB->num_rows($result) != 0)
{
while($row=$SQLBB->fetch_array($result))
{
if($SQLBB->num_rows($SQLBB->query("SELECT ban_userid FROM `{$forum_prefix}banlist` WHERE ban_userid=" . intval($row['user_id']))) == 0)
{
if(!$loginadm)
{
define('USER_ID', $row['user_id']);
define('GROUP_ID', ($row[$row_leve] == $admin_level ? '1' : '3'));
define('USER_NAME', $row['username']);
define('USER_MAIL',$row['user_email']);
if($row[$row_leve] == $admin_level)
{
define('USER_ADMIN', true);
}
}
$userinfo = $row;
$userinfo['group_id'] = ($row[$row_leve] == $admin_level ? '1' : '3');
$user_y = kleeja_base64_encode(serialize(array('id'=>$row['user_id'], 'name'=>$row['username'], 'mail'=>$row['user_email'], 'last_visit'=>time())));
if(!$hashed && !$loginadm)
{
$usrcp->kleeja_set_cookie('ulogu', $usrcp->en_de_crypt(
$row['user_id'] . '|' .
$row['user_password'] . '|' .
$expire . '|' .
sha1(md5($config['h_key'] . $row['user_password']) . $expire) . '|' .
($row[$row_leve] == $admin_level ? '1' : '3') . '|' .
$user_y
), $expire);
}
is_array($plugin_run_result = Plugins::getInstance()->run('qr_while_usrdata_phpbb_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
}
else
{
//he is banned from phpBB
$SQLBB->freeresult($result);
unset($pass);
$SQLBB->close();
return false;
}
}
$SQLBB->freeresult($result);
unset($pass);
$SQLBB->close();
return true;
}
else
{
$SQLBB->freeresult($result);
$SQLBB->close();
return false;
}
//dont know why they come here !
return false;
}
function kleeja_auth_username ($user_id)
{
return kleeja_auth_login ($user_id, false, false, 0, false, true);
}
/**
* Check for correct password
*/
function phpbb_check_hash($password, $hash)
{
$itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if (strlen($hash) == 34)
{
return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
}
return (md5($password) === $hash) ? true : false;
}
/**
* Generate salt for hash generation
*/
function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
{
if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
{
$iteration_count_log2 = 8;
}
$output = '$H$';
$output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
$output .= _hash_encode64($input, 6, $itoa64);
return $output;
}
/**
* Encode hash
*/
function _hash_encode64($input, $count, &$itoa64)
{
$output = '';
$i = 0;
do
{
$value = ord($input[$i++]);
$output .= $itoa64[$value & 0x3f];
if ($i < $count)
{
$value |= ord($input[$i]) << 8;
}
$output .= $itoa64[($value >> 6) & 0x3f];
if ($i++ >= $count)
{
break;
}
if ($i < $count)
{
$value |= ord($input[$i]) << 16;
}
$output .= $itoa64[($value >> 12) & 0x3f];
if ($i++ >= $count)
{
break;
}
$output .= $itoa64[($value >> 18) & 0x3f];
}
while ($i < $count);
return $output;
}
/**
* The crypt function/replacement
*/
function _hash_crypt_private($password, $setting, &$itoa64)
{
$output = '*';
// Check for correct hash
if (substr($setting, 0, 3) != '$H$')
{
return $output;
}
$count_log2 = strpos($itoa64, $setting[3]);
if ($count_log2 < 7 || $count_log2 > 30)
{
return $output;
}
$count = 1 << $count_log2;
$salt = substr($setting, 4, 8);
if (strlen($salt) != 8)
{
return $output;
}
/**
* We're kind of forced to use MD5 here since it's the only
* cryptographic primitive available in all versions of PHP
* currently in use. To implement our own low-level crypto
* in PHP would result in much worse performance and
* consequently in lower iteration counts and hashes that are
* quicker to crack (by non-PHP code).
*/
if (PHP_VERSION >= 5)
{
$hash = md5($salt . $password, true);
do
{
$hash = md5($hash . $password, true);
}
while (--$count);
}
else
{
$hash = pack('H*', md5($salt . $password));
do
{
$hash = pack('H*', md5($hash . $password));
}
while (--$count);
}
$output = substr($setting, 0, 12);
$output .= _hash_encode64($hash, 16, $itoa64);
return $output;
}

220
includes/auth_integration/vb.php Executable file
View File

@@ -0,0 +1,220 @@
<?php
/**
*
* @package auth
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
//
//Path of config file in vb
//
if(!defined('SCRIPT_CONFIG_PATH'))
{
define('SCRIPT_CONFIG_PATH', '/includes/config.php');
}
function kleeja_auth_login ($name, $pass, $hashed = false, $expire, $loginadm = false, $return_name = false)
{
global $lang, $config, $usrcp, $userinfo;
global $script_path, $script_cp1256, $script_srv, $script_db, $script_user, $script_pass, $script_prefix, $script_db_charset;
if(isset($script_path))
{
//check for last slash
if(isset($script_path[strlen($script_path)]) && $script_path[strlen($script_path)] == '/')
{
$script_path = substr($script_path, 0, strlen($script_path));
}
//get some useful data from vb config file
if(file_exists(PATH . $script_path . SCRIPT_CONFIG_PATH))
{
require_once (PATH . $script_path . SCRIPT_CONFIG_PATH);
//
//get config from config file
//
$forum_srv = $config['MasterServer']['servername'];
$forum_db = $config['Database']['dbname'];
$forum_user = $config['MasterServer']['username'];
$forum_pass = $config['MasterServer']['password'];
$forum_prefix= $config['Database']['tableprefix'];
if($config['MasterServer']['port'] != 3306)
{
$forum_srv .= ':' . $config['MasterServer']['port'];
}
//some people change their db charset
if(isset($config['Mysqli']['charset']))
{
$forum_db_charset = $config['Mysqli']['charset'];
}
}
else
{
big_error('Forum path is not correct', sprintf($lang['SCRIPT_AUTH_PATH_WRONG'], 'Vbulletin'));
}
}
else
{
//
//custom config data
//
$forum_srv = $script_srv;
$forum_db = $script_db;
$forum_user = $script_user;
$forum_pass = $script_pass;
$forum_prefix = $script_prefix;
//some people change their db charset
if(isset($script_db_charset))
{
$forum_db_charset = $script_db_charset;
}
}
if(empty($forum_srv) || empty($forum_user) || empty($forum_db))
{
return;
}
$SQLVB = new KleejaDatabase($forum_srv, $forum_user, $forum_pass, $forum_db, true);
if(isset($forum_db_charset))
{ //config
$SQLVB->set_names($forum_db_charset);
}
else //auto
{
$SQLVB->set_names('latin1');
}
unset($forum_pass); // We do not need this any longer
$pass = empty($script_cp1256) || !$script_cp1256 ? $pass : $usrcp->kleeja_utf8($pass, false);
$name = empty($script_cp1256) || !$script_cp1256 || $hashed ? $name : $usrcp->kleeja_utf8($name, false);
$query_salt = array(
'SELECT' => $hashed ? '*' : 'salt',
'FROM' => "`{$forum_prefix}user`",
);
$query_salt['WHERE'] = $hashed ? "userid=" . intval($name) . " AND password='" . $SQLVB->real_escape($pass) . "' AND usergroupid != '8'" : "username='" . $SQLVB->real_escape($name) . "' AND usergroupid != '8'";
//if return only name let's ignore the obove
if($return_name)
{
$query_salt['SELECT'] = "username";
$query_salt['WHERE'] = "userid=" . intval($name);
}
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_usrdata_vb_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result_salt = $SQLVB->build($query_salt);
if ($SQLVB->num_rows($result_salt) > 0)
{
while($row1=$SQLVB->fetch_array($result_salt))
{
if($return_name)
{
return empty($script_cp1256) || !$script_cp1256 ? $row1['username'] : $usrcp->kleeja_utf8($row1['username']);
}
if(!$hashed)
{
$pass = md5(md5($pass) . $row1['salt']); // without normal md5
$query = array(
'SELECT' => '*',
'FROM' => "`{$forum_prefix}user`",
'WHERE' => "username='" . $SQLVB->real_escape($name) . "' AND password='" . $SQLVB->real_escape($pass) . "' AND usergroupid != '8'"
);
$result = $SQLVB->build($query);
if ($SQLVB->num_rows($result) != 0)
{
while($row=$SQLVB->fetch_array($result))
{
if(!$loginadm)
{
define('USER_ID', $row['userid']);
define('GROUP_ID', ($row['usergroupid'] == 6 ? 1 : 3));
define('USER_NAME', empty($script_cp1256) || !$script_cp1256 ? $row['username'] : $usrcp->kleeja_utf8($row['username']));
define('USER_MAIL', $row['email']);
define('USER_ADMIN', ($row['usergroupid'] == 6 ? 1 : 0));
}
//define('LAST_VISIT',$row['last_visit']);
$userinfo = $row;
$userinfo['group_id'] = ($row['usergroupid'] == 6 ? 1 : 3);
$user_y = kleeja_base64_encode(serialize(array('id'=>$row['userid'], 'name'=>USER_NAME, 'mail'=>$row['email'], 'last_visit'=>time())));
$hash_key_expire = sha1(md5($config['h_key'] . $row['password']) . $expire);
if(!$loginadm)
{
$usrcp->kleeja_set_cookie('ulogu', $usrcp->en_de_crypt(
$row['userid'] . '|' .
$row['password'] . '|' .
$expire . '|' .
$hash_key_expire . '|' .
($row['usergroupid'] == 6 ? 1 : 3) . '|' .
$user_y
), $expire);
}
is_array($plugin_run_result = Plugins::getInstance()->run('qr_while_usrdata_vb_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
}
$SQLVB->freeresult($result);
}#nums_sql2
else
{
$SQLVB->close();
return false;
}
}
else
{
if(!$loginadm)
{
define('USER_ID', $row1['userid']);
define('USER_NAME', empty($script_cp1256) || !$script_cp1256 ? $row1['username'] : $usrcp->kleeja_utf8($row1['username']));
define('USER_MAIL',$row1['email']);
define('USER_ADMIN',($row1['usergroupid'] == 6) ? 1 : 0);
define('GROUP_ID',($row1['usergroupid'] == 6) ? 1 : 3);
$userinfo = $row1;
$userinfo['group_id'] = ($row1['usergroupid'] == 6 ? 1 : 3);
}
}
}#whil1
$SQLVB->freeresult($result_salt);
unset($pass);
$SQLVB->close();
return true;
}
else
{
$SQLVB->close();
return false;
}
}
function kleeja_auth_username ($user_id)
{
return kleeja_auth_login ($user_id, false, true, 0, false, true);
}

405
includes/cache.php Executable file
View File

@@ -0,0 +1,405 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit;
}
//we are in cache now ..
define('IN_CACHE', true);
//make sure it's utf8 data
$SQL->set_utf8();
//
//In the future here will be a real cache class
//this codes, it's just a sample and usefull for
//some time ..
//
class cache
{
function get($name)
{
if(defined('DEV_STAGE'))
{
return false;
}
$name = preg_replace('![^a-z0-9_]!', '_', $name);
if (file_exists(PATH . 'cache/' . $name . '.php'))
{
include PATH . 'cache/' . $name . '.php';
return empty($data) ? false : $data;
}
else
{
return false;
}
}
function exists($name)
{
$name = preg_replace('![^a-z0-9_]!', '_', $name);
if (file_exists(PATH . 'cache/' . $name . '.php'))
{
return true;
}
}
function save($name, $data, $time = 86400)
{
//
//We have problems if APC is enabled, so we disable our cache
//system if it's lodoed to prevent those problems, but we will
//try to fix it in the near future .. I hope that.
//
if(defined('APC_CACHE'))
{
//return;
}
$name = preg_replace('![^a-z0-9_]!i', '_', $name);
$data_for_save = '<?' . 'php' . "\n";
$data_for_save .= '//Cache file, generated for Kleeja at ' . gmdate('d-m-Y h:i A') . "\n\n";
$data_for_save .= '//No direct opening' . "\n";
$data_for_save .= '(!defined("IN_COMMON") ? exit("hacking attemp!") : null);' . "\n\n";
$data_for_save .= '//return false after x time' . "\n";
$data_for_save .= 'if(time() > ' . (time() + $time) . ') return false;' . "\n\n";
$data_for_save .= '$data = ' . var_export($data, true) . ";\n\n//end of cache";
if($fd = @fopen(PATH . 'cache/' . $name . '.php', 'w'))
{
@flock($fd, LOCK_EX); // exlusive look
@fwrite($fd, $data_for_save);
@flock($fd, LOCK_UN);
@fclose($fd);
}
return;
}
function clean($name)
{
if(is_array($name))
{
foreach($name as $n)
{
$this->clean($n);
}
return;
}
$name = preg_replace('![^a-z0-9_]!i', '_', $name);
kleeja_unlink(PATH . 'cache/' . $name . '.php');
}
}
$cache = new cache;
//
//get config data from config table ...
//
if (!($config = $cache->get('data_config')))
{
$query = array(
'SELECT' => 'c.name, c.value',
'FROM' => "{$dbprefix}config c",
'WHERE' => 'c.dynamic = 0',
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_config_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
$config[$row['name']] = $row['value'];
}
$SQL->freeresult($result);
$cache->save('data_config', $config);
}
//
//get language terms from lang table ...
//
if (!($olang = $cache->get('data_lang' . $config['language']))) {
$query = array(
'SELECT' => 'l.word, l.trans',
'FROM' => "{$dbprefix}lang l",
'WHERE' => "l.lang_id='" . $SQL->escape($config['language']) . "'",
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_lang_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
$olang[$row['word']] = $row['trans'];
}
$SQL->freeresult($result);
$cache->save('data_lang' . $config['language'], $olang);
}
//
//stats to cache
//
if (!($stats = $cache->get('data_stats')))
{
$query = array(
'SELECT' => 's.files, s.imgs, s.sizes, s.users, s.last_file, s.last_f_del, s.last_google' .
', s.last_bing, s.google_num, s.bing_num, s.lastuser',
'FROM' => "{$dbprefix}stats s"
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_stats_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
$stats = array(
'stat_files' => $row['files'],
'stat_imgs' => $row['imgs'],
'stat_sizes' => $row['sizes'],
'stat_users' => $row['users'],
'stat_last_file' => $row['last_file'],
'stat_last_f_del' => $row['last_f_del'],
'stat_last_google' => $row['last_google'],
'stat_last_bing' => $row['last_bing'],
'stat_google_num' => $row['google_num'],
'stat_bing_num' => $row['bing_num'],
'stat_last_user' => $row['lastuser']
);
is_array($plugin_run_result = Plugins::getInstance()->run('while_fetch_stats_in_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
}
$SQL->freeresult($result);
#save the stats for hour and then refresh them
$cache->save('data_stats', $stats, 3600);
#also, save the data for the charts later
$query = array(
'SELECT' => 'f.filter_uid',
'FROM' => "{$dbprefix}filters f",
'WHERE' => "f.filter_type='stats_for_acp' AND f.filter_uid = '" . date('d-n-Y') . "'"
);
$result = $SQL->build($query);
#if already there is stats for this day, just update it, if not insert a new one
if($SQL->num_rows($result))
{
$f_query = array(
'UPDATE' => "{$dbprefix}filters",
'SET' => "filter_value='" . implode(':', array($stats['stat_files'], $stats['stat_imgs'], $stats['stat_sizes'])) . "'",
'WHERE' => "filter_type='stats_for_acp' AND filter_uid = '" . date('d-n-Y') . "'"
);
}
else
{
$f_query = array(
'INSERT' => 'filter_uid, filter_type ,filter_value ,filter_time',
'INTO' => "{$dbprefix}filters",
'VALUES' => "'" . date('d-n-Y') . "', 'stats_for_acp', '" . implode(':', array($stats['stat_files'], $stats['stat_imgs'], $stats['stat_sizes'])) . "', " . time()
);
}
$SQL->build($f_query);
}
//make them as seperated vars
extract($stats);
unset($stats);
//
//get banned ips data from stats table ...
//
if (!($banss = $cache->get('data_ban')))
{
$query = array(
'SELECT' => 's.ban',
'FROM' => "{$dbprefix}stats s"
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_ban_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
$row = $SQL->fetch_array($result);
$ban1 = $row['ban'];
$SQL->freeresult($result);
$banss = array();
if (!empty($ban1) || $ban1 != ' '|| $ban1 != ' ')
{
//seperate ips ..
$ban2 = explode('|', $ban1);
for ($i=0; $i<sizeof($ban2); $i++)
{
$banss[$i] = $ban2[$i];
}
}
unset($ban1, $ban2, $gt);
$cache->save('data_ban', $banss);
}
//
//get rules data from stats table ...
//
if (!($ruless = $cache->get('data_rules')))
{
$query = array(
'SELECT' => 's.rules',
'FROM' => "{$dbprefix}stats s"
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_rules_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
$row = $SQL->fetch_array($result);
$ruless = $row['rules'];
$SQL->freeresult($result);
$cache->save('data_rules', $ruless);
}
//
//get ex-header-footer data from stats table …
//
if (!($extras = $cache->get('data_extra')))
{
$query = array(
'SELECT' => 's.ex_header, s.ex_footer',
'FROM' => "{$dbprefix}stats s"
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_extra_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
$row = $SQL->fetch_array($result);
$extras = array(
'header' => $row['ex_header'],
'footer' => $row['ex_footer']
);
$SQL->freeresult($result);
$cache->save('data_extra', $extras);
}
//
//Get groups data
//
if (!($d_groups = $cache->get('data_groups')))
{
$d_groups = array();
#data
$query = array(
'SELECT' => 'g.*',
'FROM' => "{$dbprefix}groups g",
'ORDER_BY' => 'g.group_id ASC',
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_groups_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
#Initiating
while($row=$SQL->fetch_array($result))
{
$d_groups[$row['group_id']]['data'] = $row;
$d_groups[$row['group_id']]['configs'] = array();
$d_groups[$row['group_id']]['acls'] = array();
$d_groups[$row['group_id']]['exts'] = array();
}
$SQL->freeresult($result);
#configs
$query = array(
'SELECT' => 'g.group_id, g.name, g.value',
'FROM' => "{$dbprefix}groups_data g",
'ORDER_BY' => 'g.group_id ASC',
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_groups_data_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
$d_groups[$row['group_id']]['configs'][$row['name']] = $row['value'];
}
$SQL->freeresult($result);
#acl
$query2 = array(
'SELECT' => 'g.group_id, g.acl_name, g.acl_can',
'FROM' => "{$dbprefix}groups_acl g",
'ORDER_BY' => 'g.group_id ASC',
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_groups_acls_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result2 = $SQL->build($query2);
while($row=$SQL->fetch_array($result2))
{
$d_groups[$row['group_id']]['acls'][$row['acl_name']] = (int) $row['acl_can'];
}
$SQL->freeresult($result2);
#exts
$query3 = array(
'SELECT' => 'g.group_id, g.ext, g.size',
'FROM' => "{$dbprefix}groups_exts g",
'ORDER_BY' => 'g.group_id ASC',
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_groups_exts_cache', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result3 = $SQL->build($query3);
while($row=$SQL->fetch_array($result3))
{
$d_groups[$row['group_id']]['exts'][$row['ext']] = (int) $row['size'];
}
$SQL->freeresult($result3);
unset($query, $query2, $query3, $result, $result2, $result3);
$cache->save('data_groups', $d_groups);
}
// ummm, does this useful here
is_array($plugin_run_result = Plugins::getInstance()->run('in_cache_page', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook

99
includes/captcha.php Executable file
View File

@@ -0,0 +1,99 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
/*
* Fix bug with path of font When using versions of the GD library lower than 2.0.18
*/
if(function_exists('putenv'))
{
@putenv('GDFONTPATH=' . realpath('.'));
}
else if(function_exists('ini_set'))
{
@ini_set('GDFONTPATH', realpath('.'));
}
/*
* When any body request this file , he will see an image ..
*/
kleeja_cpatcha_image();
exit();
//
//this function will just make an image
//source : http://webcheatsheet.com/php/create_captcha_protection.php
//
function kleeja_cpatcha_image()
{
//Let's generate a totally random string using md5
$md5_hash = md5(rand(0,999));
//I think the bad things in captcha is two things, O and 0 , so let's remove zero.
$security_code = str_replace('0', '', $md5_hash);
//We don't need a 32 character long string so we trim it down to 5
$security_code = substr($security_code, 15, 4);
//Set the session to store the security code
$_SESSION["klj_sec_code"] = $security_code;
//Set the image width and height
$width = 150;
$height = 25;
//Create the image resource
$image = ImageCreate($width, $height);
//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, rand(0, 100), 0, rand(0, 50));
$grey = ImageColorAllocate($image, 204, 204, 204);
//Make the background black
ImageFill($image, 0, 0, $black);
//options
$x = 10;
$y = 14;
$angle = rand(-7, -10);
//Add randomly generated string in white to the image
if(function_exists('imagettftext'))
{
//
// We figure a bug that happens when you add font name without './' before it ..
// he search in the Linux fonts cache , but when you add './' he will know it's our font.
//
imagettftext ($image, 16,$angle , rand(50, $x), $y+rand(1,3), $white, dirname(__FILE__) . '/arial.ttf', $security_code);
#imagettftext ($image, 7, 0, $width-30, $height-4, $white,'./arial.ttf', 'Kleeja');
}
else
{
imagestring ($image, imageloadfont(dirname(__FILE__) . '/arial.gdf'), $x+rand(10,15), $y-rand(10,15), $security_code, $white);
#imagestring ($image, 1, $width-35, $height-10, 'Kleeja', ImageColorAllocate($image, 200, 200, 200));
}
//Throw in some lines to make it a little bit harder for any bots to break
ImageRectangle($image,0,0,$width-1,$height-1,$grey);
imageline($image, 0, $height/2, $width, $height/2, $grey);
imageline($image, $width/2, 0, $width/2, $height, $grey);
//Tell the browser what kind of file is come in
header("Content-Type: image/png");
//Output the newly created image in jpeg format
ImagePng($image);
//Free up resources
ImageDestroy($image);
}
//<--- EOF

364
includes/common.php Executable file
View File

@@ -0,0 +1,364 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
#not for directly open
if (!defined('IN_KLEEJA'))
{
exit();
}
#we are in the common file
define('IN_COMMON', true);
#filename of config.php
define('KLEEJA_CONFIG_FILE', 'config.php');
#plugins folder
define('KLEEJA_PLUGINS_FOLDER', 'plugins');
if(@extension_loaded('apc'))
{
define('APC_CACHE', true);
}
#path
if(!defined('PATH'))
{
if(!defined('__DIR__'))
{
define('__DIR__', dirname(__FILE__));
}
define('PATH', str_replace(DIRECTORY_SEPARATOR . 'includes', '', __DIR__) . DIRECTORY_SEPARATOR);
}
#no config
if (!file_exists(PATH . KLEEJA_CONFIG_FILE))
{
header('Location: ./install/index.php');
exit;
}
#there is a config
require_once PATH . KLEEJA_CONFIG_FILE;
#admin files path
define('ADM_FILES_PATH', PATH . 'includes/adm');
#Report all errors, except notices
error_reporting( defined('DEV_STAGE') ? E_ALL : E_ALL ^ E_NOTICE);
/**
* functions for start
*/
function kleeja_show_error($error_number, $error_string = '', $error_file = '', $error_line = '')
{
switch ($error_number)
{
case E_NOTICE: case E_WARNING: case E_USER_WARNING: case E_USER_NOTICE: case E_STRICT: break;
default:
header('HTTP/1.1 503 Service Temporarily Unavailable');
echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">' . "\n<head>\n";
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' . "\n";
echo '<title>Kleeja Error</title>' . "\n" . '<style type="text/css">' . "\n\t";
echo '.error {color: #333;background:#ffebe8;float:left;width:73%;text-align:left;margin-top:10px;border: 1px solid #dd3c10; padding: 10px;font-family:tahoma,arial;font-size: 12px;}' . "\n";
echo "</style>\n</head>\n<body>\n\t" . '<div class="error">' . "\n\n\t\t<h2>Kleeja error : </h2><br />" . "\n";
echo "\n\t\t<strong> [ " . $error_number . ':' . basename($error_file) . ':' . $error_line . ' ] </strong><br /><br />' . "\n\t\t" . $error_string . "\n\t";
echo "\n\t\t" . '<br /><br /><small>Visit <a href="http://www.kleeja.com/" title="kleeja">Kleeja</a> Website for more details.</small>' . "\n\t";
echo "</div>\n</body>\n</html>";
global $SQL;
if(isset($SQL))
{
@$SQL->close();
}
exit;
break;
}
}
set_error_handler('kleeja_show_error');
#time of start and end and whatever
function get_microtime()
{
list($usec, $sec) = explode(' ', microtime()); return ((float)$usec + (float)$sec);
}
//is bot ?
function is_bot($bots = array('googlebot', 'bing' ,'msnbot'))
{
if(isset($_SERVER['HTTP_USER_AGENT']))
{
return preg_match('/(' . implode('|', $bots) . ')/i', ($_SERVER['HTTP_USER_AGENT'] ? $_SERVER['HTTP_USER_AGENT'] : @getenv('HTTP_USER_AGENT'))) ? true : false;
}
return false;
}
$starttm = get_microtime();
if (!is_bot() && !isset($_SESSION))
{
session_start();
}
#no enough data
if (empty($dbname) || empty($dbuser))
{
header('Location: ./install/index.php');
exit;
}
#include files .. & classes ..
$root_path = PATH;
$db_type = isset($db_type) ? $db_type : 'mysqli';
include PATH . 'includes/functions_alternative.php';
include PATH . 'includes/version.php';
include PATH . 'includes/mysqli.php';
include PATH . 'includes/style.php';
include PATH . 'includes/usr.php';
include PATH . 'includes/pager.php';
include PATH . 'includes/functions.php';
include PATH . 'includes/functions_display.php';
include PATH . 'includes/plugins.php';
if(defined('IN_ADMIN'))
{
include PATH . 'includes/functions_adm.php';
}
#fix integration problems
if(empty($script_encoding))
{
$script_encoding = 'utf-8';
}
#start classes ..
$SQL = new KleejaDatabase($dbserver, $dbuser, $dbpass, $dbname);
#no need after now
unset($dbpass);
$tpl = new kleeja_style;
$usrcp = new usrcp;
//then get caches
include PATH . 'includes/cache.php';
#getting dynamic configs
$query = array(
'SELECT' => 'c.name, c.value',
'FROM' => "{$dbprefix}config c",
'WHERE' => 'c.dynamic = 1',
);
$result = $SQL->build($query);
while($row=$SQL->fetch_array($result))
{
$config[$row['name']] = $row['value'];
}
$SQL->freeresult($result);
#check user or guest
$usrcp->kleeja_check_user();
#+ configs of the current group
$config = array_merge($config, (array) $d_groups[$usrcp->group_id()]['configs']);
#admin path
define('ADMIN_PATH', rtrim($config['siteurl'], '/') . '/admin/index.php');
//no tpl caching in dev stage
if(defined('DEV_STAGE'))
{
$tpl->caching = false;
}
if(isset($config['foldername']))
{
$config['foldername'] = str_replace(
array(
'{year}',
'{month}',
'{week}',
'{day}',
'{username}',
),
array(
date('Y'),
date('m'),
date('W'),
date('d'),
$usrcp->name() ? preg_replace('/[^a-z0-9\._-]/', '', strtolower($usrcp->name())) : 'guest'
),
$config['foldername']
);
}
is_array($plugin_run_result = Plugins::getInstance()->run('boot_common', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
/**
* Set default time zone
* There is no time difference between Coordinated Universal Time (UTC) and Greenwich Mean Time (GMT).
* Kleeja supports the changing of time zone through the admin panel, see functions_display.php/kleeja_date()
*/
date_default_timezone_set('GMT');
//kleeja session id
$klj_session = $SQL->escape(session_id());
//site url must end with /
if($config['siteurl'])
{
$config['siteurl'] = $config['siteurl'][strlen($config['siteurl'])-1] != '/'
? $config['siteurl'] . '/'
: $config['siteurl'];
}
#check lang
if(!$config['language'] || empty($config['language']))
{
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && strlen($_SERVER['HTTP_ACCEPT_LANGUAGE']) > 2)
{
$config['language'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if(!file_exists(PATH . 'lang/' . $config['language'] . '/common.php'))
{
$config['language'] = 'en';
}
}
}
#check style
if(is_null($config['style']) || empty($config['style']))
{
$config['style'] = 'default';
}
#check h_kay, important for kleeja
if(empty($config['h_key']))
{
$h_k = sha1(microtime() . rand(0, 100));
if(!update_config('h_key', $h_k))
{
add_config('h_key', $h_k);
}
}
#current Kleeja admin style
define('ACP_STYLE_NAME', 'Masmak');
#path variables for Kleeja
$STYLE_PATH = $config['siteurl'] . 'styles/' . (trim($config['style_depend_on']) == '' ? $config['style'] : $config['style_depend_on']) . '/';
$THIS_STYLE_PATH = $config['siteurl'] . 'styles/' . $config['style'] . '/';
$THIS_STYLE_PATH_ABS = PATH . 'styles/' . $config['style'] . '/';
$STYLE_PATH_ADMIN = $config['siteurl'] . 'admin/'. (is_browser('mobile') || defined('IN_MOBILE') ? ACP_STYLE_NAME : ACP_STYLE_NAME) . '/';
$STYLE_PATH_ADMIN_ABS = PATH . 'admin/'. (is_browser('mobile') || defined('IN_MOBILE') ? ACP_STYLE_NAME . '/' : ACP_STYLE_NAME . '/');
$DEFAULT_PATH_ADMIN_ABS = PATH . 'admin/' . ACP_STYLE_NAME . '/';
$DEFAULT_PATH_ADMIN = $config['siteurl'] . 'admin/'. ACP_STYLE_NAME . '/';
#get languge of common
get_lang('common');
#run ban system
get_ban();
if(isset($_GET['go']) && $_GET['go'] == 'login')
{
define('IN_LOGIN', true);
}
#install.php exists
if (file_exists(PATH . 'install') && !defined('IN_ADMIN') && !defined('IN_LOGIN') && !defined('DEV_STAGE'))
{
#Different message for admins! delete install folder
kleeja_info((user_can('enter_acp') ? $lang['DELETE_INSTALL_FOLDER'] : $lang['WE_UPDATING_KLEEJA_NOW']), $lang['SITE_CLOSED']);
}
#is site close
$login_page = '';
if ($config['siteclose'] == '1' && !user_can('enter_acp') && !defined('IN_LOGIN') && !defined('IN_ADMIN'))
{
//if download, images ?
if(
( defined('IN_DOWNLOAD') && (ig('img') || ig('thmb') || ig('thmbf') || ig('imgf')) )
|| g('go', 'str', '') == 'queue'
)
{
@$SQL->close();
$fullname = "images/site_closed.jpg";
$filesize = filesize($fullname);
header("Content-length: $filesize");
header("Content-type: image/jpg");
readfile($fullname);
exit;
}
// Send a 503 HTTP response code to prevent search bots from indexing the maintenace message
header('HTTP/1.1 503 Service Temporarily Unavailable');
kleeja_info($config['closemsg'], $lang['SITE_CLOSED']);
}
#exceed total size
if (($stat_sizes >= ($config['total_size'] *(1048576))) && !defined('IN_LOGIN') && !defined('IN_ADMIN'))// convert megabytes to bytes
{
// Send a 503 HTTP response code to prevent search bots from indexing the maintenace message
header('HTTP/1.1 503 Service Temporarily Unavailable');
kleeja_info($lang['SIZES_EXCCEDED'], $lang['STOP_FOR_SIZE']);
}
#detect bots and save stats
kleeja_detecting_bots();
#check for page number
if(empty($perpage) || intval($perpage) == 0)
{
$perpage = 14;
}
#captcha file
$captcha_file_path = $config['siteurl'] . 'ucp.php?go=captcha';
is_array($plugin_run_result = Plugins::getInstance()->run('end_common', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if(function_exists('session_register_shutdown'))
{
session_register_shutdown();
}
else
{
register_shutdown_function('session_write_close');
}

1695
includes/functions.php Executable file

File diff suppressed because it is too large Load Diff

350
includes/functions_adm.php Executable file
View File

@@ -0,0 +1,350 @@
<?php
/**
*
* @package adm
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
/**
* Print cp error function handler
*
* For admin
*/
function kleeja_admin_err($msg, $navigation = true, $title='', $exit = true, $redirect = false, $rs = 3, $style = 'admin_err')
{
global $text, $tpl, $SHOW_LIST, $adm_extensions, $adm_extensions_menu;
global $STYLE_PATH_ADMIN, $lang, $olang, $SQL, $MINI_MENU;
if(is_string($navigation))
{
$redirect = $navigation;
}
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_admin_err_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#Exception for ajax
if(ig('_ajax_'))
{
$text = $msg . ($redirect ? "\n" . '<script type="text/javascript">setTimeout("get_kleeja_link(\'' . str_replace('&amp;', '&', $redirect) . '\');", ' . ($rs * 1000) . ');</script>' : '');
echo_ajax(1, $tpl->display($style));
$SQL->close();
exit();
}
// assign {text} in err template
$text = $msg . ($redirect != false ? redirect($redirect, false, false, $rs, true) : '');
$SHOW_LIST = $navigation;
//header
echo $tpl->display("admin_header");
//show tpl
echo $tpl->display($style);
//footer
echo $tpl->display("admin_footer");
if($exit)
{
$SQL->close();
exit();
}
}
/**
* Print information message on admin panel
*
* @adm
* @param string $msg information message
* @param bool $navigation show navigation menu or not
* @param string $title information heading title
* @param bool $exit if true, then halt after message
* @param bool $redirect redirect after showing the message
* @param int $rs delay the redirect in seconds
*/
function kleeja_admin_info($msg, $navigation=true, $title='', $exit=true, $redirect = false, $rs = 2)
{
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_admin_info_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
kleeja_admin_err($msg, $navigation, $title, $exit, $redirect, $rs, 'admin_info');
}
/**
* generate a filter..
* @adm
* @param string|integer $type filter_id or filter_uid
* @param string $value filter value
* @param bool $time filter time
* @param bool $user user Id
* @param string $status filter status
* @param bool $uid filter unique id
* @return bool|int|string
*/
function insert_filter($type, $value, $time = false, $user = false, $status = '', $uid = false)
{
global $SQL, $dbprefix, $userinfo;
$user = !$user ? $userinfo['id'] : $user;
$time = !$time ? time() : $time;
$uid = $uid ? $uid : uniqid();
$insert_query = array(
'INSERT' => 'filter_uid, filter_type ,filter_value ,filter_time ,filter_user, filter_status',
'INTO' => "{$dbprefix}filters",
'VALUES' => "'" .$uid . "', '" . $SQL->escape($type) . "','" . $SQL->escape($value) . "', " . intval($time) . "," . intval($user) . ",'" . $SQL->escape($status) . "'"
);
is_array($plugin_run_result = Plugins::getInstance()->run('insert_sql_insert_filter_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$SQL->build($insert_query);
return $SQL->insert_id() ? $uid : false;
}
/**
* Update filter value..
*
* @param int|string $id_or_uid Number of filter_id or the unique id string of filter_uid
* @param string $value The modified value of filter
* @param string $filter_type if given, use it with sql where
* @param bool|string $filter_status if given, update the filter status
* @param bool $user_id
* @return bool
*/
function update_filter($id_or_uid, $value, $filter_type = 'general', $filter_status = false, $user_id = false)
{
global $SQL, $dbprefix;
$update_query = array(
'UPDATE' => "{$dbprefix}filters",
'SET' => "filter_value='" . $SQL->escape($value) . "'" . ($filter_status ? ", filter_status='" . $SQL->escape($filter_status) . "'" : ''),
'WHERE' => (strval(intval($id_or_uid)) == strval($id_or_uid) ? 'filter_id=' . intval($id_or_uid) : "filter_uid='" . $SQL->escape($id_or_uid) . "'")
. ($filter_type ? " AND filter_type='" . $SQL->escape($filter_type) . "'" : '')
. ($user_id ? " AND filter_user=" . intval($user_id) . "" : '')
);
is_array($plugin_run_result = Plugins::getInstance()->run('update_filter_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$SQL->build($update_query);
if ($SQL->affected()) {
return true;
}
return false;
}
/**
* Get filter from db..
*
* @param string|int $item The value of $get_by, to get the filter depend on it
* @param bool|string $filter_type if given, use it with sql where
* @param bool $just_value If true the return value should be just filter_value otherwise all filter rows
* @param string $get_by The name of filter column we want to get the filter value from
* @param bool $user_id
* @return mixed
*/
function get_filter($item, $filter_type = false, $just_value = false, $get_by = 'filter_uid', $user_id = false)
{
global $dbprefix, $SQL;
$valid_filter_columns = array('filter_id', 'filter_uid', 'filter_user', 'filter_status');
if (!in_array($get_by, $valid_filter_columns)) {
$get_by = 'filter_uid';
}
$query = array(
'SELECT' => $just_value ? 'f.filter_value' : 'f.*',
'FROM' => "{$dbprefix}filters f",
'WHERE' => "f." . $get_by . " = " . ($get_by == 'filter_id' ? intval($item) : "'" . $SQL->escape($item) . "'")
. ($filter_type ? " AND f.filter_type='" . $SQL->escape($filter_type) . "'" : '')
. ($user_id ? " AND f.filter_user=" . intval($user_id) . "" : '')
);
is_array($plugin_run_result = Plugins::getInstance()->run('get_filter_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
$v = $SQL->fetch($result);
$SQL->free($result);
if ($just_value) {
return $v['filter_value'];
}
return $v;
}
/**
* check if filter exists or not
*
* @param string|int $item The value of $get_by, to find the filter depend on it
* @param string $get_by The name of filter column we want to get the filter from
* @param bool $filter_type
* @param bool $user_id
* @return bool|int
*/
function filter_exists($item, $get_by = 'filter_id', $filter_type = false, $user_id = false)
{
global $dbprefix, $SQL;
$query = array(
'SELECT' => 'f.filter_id',
'FROM' => "{$dbprefix}filters f",
'WHERE' => "f." . $get_by . " = " . ($get_by == 'filter_id' ? intval($item) : "'" . $SQL->escape($item) . "'")
. ($filter_type ? " AND f.filter_type='" . $SQL->escape($filter_type) . "'" : '')
. ($user_id ? " AND f.filter_user=" . intval($user_id) . "" : '')
);
is_array($plugin_run_result = Plugins::getInstance()->run('filter_exists_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
return $SQL->num_rows($result);
}
/**
* costruct a query for the searches..
* @adm
* @param array $search Search options
* @return string
*/
function build_search_query($search)
{
if(!is_array($search))
{
return '';
}
global $SQL;
$search['filename'] = !isset($search['filename']) ? '' : $search['filename'];
$search['username'] = !isset($search['username']) ? '' : $search['username'];
$search['than'] = !isset($search['than']) ? '' : $search['than'];
$search['size'] = !isset($search['size']) ? '' : $search['size'];
$search['ups'] = !isset($search['ups']) ? '' : $search['ups'];
$search['uthan'] = !isset($search['uthan']) ? '' : $search['uthan'];
$search['rep'] = !isset($search['rep']) ? '' : $search['rep'];
$search['rthan'] = !isset($search['rthan']) ? '' : $search['rthan'];
$search['lastdown'] = !isset($search['lastdown']) ? '' : $search['lastdown'];
$search['ext'] = !isset($search['ext']) ? '' : $search['ext'];
$search['user_ip'] = !isset($search['user_ip']) ? '' : $search['user_ip'];
$file_namee = $search['filename'] != '' ? 'AND f.real_filename LIKE \'%' . $SQL->escape($search['filename']) . '%\' ' : '';
$usernamee = $search['username'] != '' ? 'AND u.name LIKE \'%' . $SQL->escape($search['username']) . '%\'' : '';
$size_than = ' f.size ' . ($search['than']!=1 ? '<=' : '>=') . (intval($search['size']) * 1024) . ' ';
$ups_than = $search['ups'] != '' ? 'AND f.uploads ' . ($search['uthan']!=1 ? '<' : '>') . intval($search['ups']) . ' ' : '';
$rep_than = $search['rep'] != '' ? 'AND f.report ' . ($search['rthan']!=1 ? '<' : '>') . intval($search['rep']) . ' ' : '';
$lstd_than = $search['lastdown'] != '' ? 'AND f.last_down =' . (time()-(intval($search['lastdown']) * (24 * 60 * 60))) . ' ' : '';
$exte = $search['ext'] != '' ? "AND f.type IN ('" . implode("', '", @explode(",", $SQL->escape($search['ext']))) . "')" : '';
$ipp = $search['user_ip'] != '' ? 'AND f.user_ip LIKE \'%' . $SQL->escape($search['user_ip']) . '%\' ' : '';
return "$size_than $file_namee $ups_than $exte $rep_than $usernamee $lstd_than $exte $ipp";
}
/**
* To re-count the total files, without making the server goes down haha
* @param bool $files
* @param bool $start
* @return bool|int
*/
function sync_total_files($files = true, $start = false)
{
global $SQL, $dbprefix;
$query = array(
'SELECT' => 'MIN(f.id) as min_file_id, MAX(f.id) as max_file_id',
'FROM' => "{$dbprefix}files f",
);
#!files == images
$img_types = array('gif','jpg','png','bmp','jpeg','GIF','JPG','PNG','BMP','JPEG');
$query['WHERE'] = "f.type" . ($files ? ' NOT' : '') ." IN ('" . implode("', '", $img_types) . "')";
$result = $SQL->build($query);
$v = $SQL->fetch($result);
$SQL->freeresult($result);
#if no data, turn them to number
$min_id = (int) $v['min_file_id'];
// $max_id = (int) $v['max_file_id'];
#every time batch
$batch_size = 1500;
#no start? start = min
$first_loop = !$start ? true : false;
$start = !$start ? $min_id : $start;
$end = $start + $batch_size;
#now lets get this step's files number
unset($v, $result);
$query['SELECT'] = 'COUNT(f.id) as num_files';
$query['WHERE'] .= ' AND f.id BETWEEN ' . $start . ' AND ' . $end;
$result = $SQL->build($query);
$v = $SQL->fetch($result);
$SQL->freeresult($result);
$this_step_count = $v['num_files'];
if($this_step_count == 0)
{
return false;
}
#update stats table
$update_query = array(
'UPDATE' => "{$dbprefix}stats"
);
#make it zero, firstly
if($first_loop)
{
$update_query['SET'] = ($files ? 'files' : 'imgs') . "= 0";
$SQL->build($update_query);
}
$update_query['SET'] = ($files ? 'files' : 'imgs') . "=" . ($files ? 'files' : 'imgs') . '+' . $this_step_count;
$SQL->build($update_query);
return $end;
}
/**
* get the *right* now number of the given stat fro stats table
* @param string $name Stat name
* @return
*/
function get_actual_stats($name)
{
global $dbprefix, $SQL;
$query = array(
'SELECT' => 's.' . $name,
'FROM' => "{$dbprefix}stats s"
);
$result = $SQL->build($query);
$v = $SQL->fetch($result);
is_array($plugin_run_result = Plugins::getInstance()->run('get_actual_stats_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$SQL->freeresult($result);
return $v[$name];
}

View File

@@ -0,0 +1,187 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
/**
* After a lot of work, we faced many hosts who use a old PHP version, or
* they disabled many general functions ...
* so, this file contains those type of functions.
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
if(!function_exists('htmlspecialchars_decode'))
{
function htmlspecialchars_decode($string, $style=ENT_COMPAT)
{
$translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS, $style));
if($style === ENT_QUOTES)
{
$translation['&#039;'] = '\'';
}
return strtr($string, $translation);
}
}
//
//http://us2.php.net/manual/en/function.str-split.php#84891
if(!function_exists('str_split'))
{
function str_split($string, $string_length=1)
{
if(strlen($string) > $string_length || !$string_length)
{
do
{
$c = strlen($string);
$parts[] = substr($string, 0, $string_length);
$string = substr($string, $string_length);
}
while($string !== false);
}
else
{
$parts = array($string);
}
return $parts;
}
}
//Custom base64_* functions
function kleeja_base64_encode($str = ''){ return function_exists('base64_encode') ? base64_encode($str) : base64encode($str); }
function kleeja_base64_decode($str = ''){ return function_exists('base64_decode') ? base64_decode($str) : base64decode($str); }
//http://www.php.net/manual/en/function.base64-encode.php#63270
function base64encode($string = '')
{
if(!function_exists('convert_binary_str'))
{
function convert_binary_str($string)
{
if (strlen($string) <= 0)
return;
$tmp = decbin(ord($string[0]));
$tmp = str_repeat('0', 8-strlen($tmp)) . $tmp;
return $tmp . convert_binary_str(substr($string,1));
}
}
$binval = convert_binary_str($string);
$final = '';
$start = 0;
while ($start < strlen($binval))
{
if (strlen(substr($binval,$start)) < 6)
$binval .= str_repeat("0", 6-strlen(substr($binval,$start)));
$tmp = bindec(substr($binval, $start,6));
if ($tmp < 26)
$final .= chr($tmp+65);
elseif ($tmp > 25 && $tmp < 52)
$final .= chr($tmp+71);
elseif ($tmp == 62)
$final .= "+";
elseif ($tmp == 63)
$final .= "/";
elseif (!$tmp)
$final .= "A";
else
$final .= chr($tmp-4);
$start += 6;
}
if (strlen($final)%4>0)
$final .= str_repeat('=', 4-strlen($final)%4);
return $final;
}
function base64decode($str)
{
$len = strlen($str);
$ret = '';
$b64 = array();
$base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
$len_base64 = strlen($base64);
for ($i = 0; $i < 256; $i++)
$b64[$i] = 0;
for ($i = 0; $i < $len_base64 ; $i++)
$b64[ord($base64[$i])] = $i;
for($j=0;$j<$len;$j+=4)
{
for ($i = 0; $i < 4; $i++)
{
$c = ord($str[$j+$i]);
$a[$i] = $c;
$b[$i] = $b64[$c];
}
$o[0] = ($b[0] << 2) | ($b[1] >> 4);
$o[1] = ($b[1] << 4) | ($b[2] >> 2);
$o[2] = ($b[2] << 6) | $b[3];
if ($a[2] == ord('='))
$i = 1;
else if ($a[3] == ord('='))
$i = 2;
else
$i = 3;
for($k=0;$k<$i;$k++)
$ret .= chr((int) $o[$k] & 255);
if ($i < 3)
break;
}
return $ret;
}
if(!function_exists('filesize'))
{
function kleeja_filesize($filename)
{
$a = fopen($filename, 'r');
fseek($a, 0, SEEK_END);
$filesize = ftell($a);
fclose($a);
return $filesize;
}
}
else
{
function kleeja_filesize($filename)
{
return filesize($filename);
}
}
if(!function_exists("array_column"))
{
function array_column($array, $column_name)
{
return array_map(
function($element) use($column_name)
{
return $element[$column_name];
},
array_values($array)
);
}
}

981
includes/functions_display.php Executable file
View File

@@ -0,0 +1,981 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
/**
* print Kleeja header
* @param string $title
* @param string $extra append html code to head tag
*/
function Saaheader($title = '', $extra = '')
{
global $tpl, $usrcp, $lang, $olang, $user_is, $username, $config;
global $extras, $script_encoding, $errorpage, $userinfo, $charset;
global $STYLE_PATH;
//is user ? and username
$user_is = $usrcp->name() ? true : false;
$username = $usrcp->name() ? $usrcp->name() : $lang['GUST'];
//our default charset
$charset = 'utf-8';
$side_menu = array(
1 => array('name' => 'profile', 'title' => $lang['PROFILE'], 'url' => $config['mod_writer'] ? 'profile.html' : 'ucp.php?go=profile', 'show' => $user_is),
2 => array('name' => 'fileuser', 'title' => $lang['YOUR_FILEUSER'], 'url' => $config['mod_writer'] ? 'fileuser.html' : 'ucp.php?go=fileuser', 'show' => $config['enable_userfile'] && user_can('access_fileuser')),
3 => $user_is
? array('name' => 'logout', 'title' => $lang['LOGOUT'], 'url' => $config['mod_writer'] ? 'logout.html' : 'ucp.php?go=logout', 'show' => true)
: array('name' => 'login', 'title' => $lang['LOGIN'], 'url' => $config['mod_writer'] ? 'login.html' : 'ucp.php?go=login', 'show' => true),
4 => array('name' => 'register', 'title' => $lang['REGISTER'], 'url' => $config['mod_writer'] ? 'register.html' : 'ucp.php?go=register', 'show' => !$user_is && $config['register']),
);
$top_menu = array(
1 => array('name' => 'index', 'title' => $lang['INDEX'], 'url' => $config['siteurl'], 'show' => true),
2 => array('name' => 'rules', 'title' => $lang['RULES'], 'url' => $config['mod_writer'] ? 'rules.html' : 'go.php?go=rules', 'show' => true),
3 => array('name' => 'guide', 'title' => $lang['GUIDE'], 'url' => $config['mod_writer'] ? 'guide.html' : 'go.php?go=guide', 'show' => true),
4 => array('name' => 'stats', 'title' => $lang['STATS'], 'url' => $config['mod_writer'] ? 'stats.html' : 'go.php?go=stats', 'show' => $config['allow_stat_pg'] && user_can('access_stats')),
5 => array('name' => 'report', 'title' => $lang['REPORT'], 'url' => $config['mod_writer'] ? 'report.html' : 'go.php?go=report', 'show' => user_can('access_report')),
6 => array('name' => 'call', 'title' => $lang['CALL'], 'url' => $config['mod_writer'] ? 'call.html' : 'go.php?go=call', 'show' => user_can('access_call')),
);
//check for extra header
$extras['header'] = empty($extras['header']) ? false : $extras['header'];
is_array($plugin_run_result = Plugins::getInstance()->run('Saaheader_links_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
//assign some variables
$tpl->assign("dir", $lang['DIR']);
$tpl->assign("title", $title);
$tpl->assign("side_menu", $side_menu);
$tpl->assign("top_menu", $top_menu);
$tpl->assign("go_current", g('go', 'str', 'index'));
$tpl->assign("go_back_browser", $lang['GO_BACK_BROWSER']);
$tpl->assign("H_FORM_KEYS_LOGIN", kleeja_add_form_key('login'));
$tpl->assign("action_login", 'ucp.php?go=login' . (ig('return') ? '&amp;return=' . g('return') : ''));
$tpl->assign("EXTRA_CODE_META", $extra);
$default_avatar = $STYLE_PATH . 'images/user_avater.png';
if ($user_is)
{
$tpl->assign("user_avatar", 'https://www.gravatar.com/avatar/' .
md5(strtolower(trim($userinfo['mail']))) . '?s=100&amp;d=' . urlencode($default_avatar));
}
else
{
$tpl->assign("user_avatar", $default_avatar);
}
$tpl->assign("is_embedded", ig('embedded'));
$header = $tpl->display('header');
if($config['siteclose'] == '1' && user_can('enter_acp') && !defined('IN_ADMIN'))
{
//add notification bar
$header = preg_replace('/<body([^\>]*)>/i', "<body\\1>\n<!-- site is closed -->\n<p style=\"z-index:999;width: 100%; text-align:center; background:#FFFFA6; color:black; border:thin;top:0;left:0; position:absolute; clear:both;\">" . $lang['NOTICECLOSED'] . "</p>\n<!-- #site is closed -->", $header);
}
is_array($plugin_run_result = Plugins::getInstance()->run('Saaheader_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
header('Content-type: text/html; charset=UTF-8');
header('Cache-Control: private, no-cache="set-cookie"');
header('Pragma: no-cache');
header('x-frame-options: SAMEORIGIN');
header('x-xss-protection: 1; mode=block');
echo $header;
flush();
}
/**
* print kleeja footer
*/
function Saafooter()
{
global $tpl, $SQL, $starttm, $config, $usrcp, $lang, $olang;
global $do_gzip_compress, $script_encoding, $errorpage, $extras, $userinfo;
//show stats ..
$page_stats = '';
if ($config['statfooter'] != 0 || defined('DEV_STAGE'))
{
$gzip = $config['gzip'] == '1' ? "Enabled" : "Disabled";
$hksys = !defined('STOP_PLUGINS') ? "Enabled" : "Disabled";
$endtime = get_microtime();
$loadtime = number_format($endtime - $starttm , 4);
$queries_num= $SQL->query_num;
$time_sql = round($SQL->query_num / $loadtime) ;
$page_url = preg_replace(array('/([\&\?]+)debug/i', '/&amp;/i'), array('', '&'), kleeja_get_page());
$link_dbg = user_can('enter_acp') && defined('DEV_STAGE') ? '[ <a href="' . str_replace('&', '&amp;', $page_url) . (strpos($page_url, '?') === false ? '?' : '&amp;') . 'debug">Debug Info ... </a> ]' : '';
$page_stats = "<strong>[</strong> GZIP : $gzip - Generation Time: $loadtime Sec - Queries: $queries_num - Hook System: $hksys <strong>]</strong> " . $link_dbg ;
}
$tpl->assign("page_stats", $page_stats);
//if admin, show admin in the bottom of all page
$tpl->assign("admin_page", (user_can('enter_acp') ? '<a href="' . ADMIN_PATH . '" class="admin_cp_link"><span>' . $lang['ADMINCP'] . '</span></a>' : ''));
//assign cron
$tpl->assign("run_queue", '<img src="' . $config['siteurl'] . 'go.php?go=queue" width="1" height="1" alt="queue" />');
// if google analytics, new version
//http://www.google.com/support/googleanalytics/bin/answer.py?answer=55488&topic=11126
$googleanalytics = '';
if (strlen($config['googleanalytics']) > 4)
{
$googleanalytics .= '<script type="text/javascript">' . "\n";
$googleanalytics .= '<!--' . "\n";
$googleanalytics .= 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");' . "\n";
$googleanalytics .= 'document.write("\<script src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'>\<\/script>" );' . "\n";
$googleanalytics .= '-->' . "\n";
$googleanalytics .= '</script>' . "\n";
$googleanalytics .= '<script type="text/javascript">' . "\n";
$googleanalytics .= '<!--' . "\n";
$googleanalytics .= 'var pageTracker = _gat._getTracker("' . $config['googleanalytics'] . '");' . "\n";
$googleanalytics .= 'pageTracker._initData();' . "\n";
$googleanalytics .= 'pageTracker._trackPageview();' . "\n";
$googleanalytics .= '-->' . "\n";
$googleanalytics .= '</script>' . "\n";
}
$tpl->assign("googleanalytics", $googleanalytics);
$extras['footer'] = empty($extras['footer']) ? false : $extras['footer'];
is_array($plugin_run_result = Plugins::getInstance()->run('Saafooter_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$footer = $tpl->display('footer');
is_array($plugin_run_result = Plugins::getInstance()->run('print_Saafooter_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
echo $footer;
//page analysis
if (ig('debug') && user_can('enter_acp'))
{
kleeja_debug();
}
//at end, close sql connections
$SQL->close();
}
/**
* return file size in a readable format
* @param int $size in bytes
* @return string
*/
function readable_size($size)
{
$sizes = array(' B', ' KB', ' MB', ' GB', ' TB', 'PB', ' EB');
$ext = $sizes[0];
for ($i=1; (($i < count($sizes)) && ($size >= 1024)); $i++)
{
$size = $size / 1024;
$ext = $sizes[$i];
}
$result = round($size, 2).$ext;
is_array($plugin_run_result = Plugins::getInstance()->run('func_readable_size', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $result;
}
/**
* show an error message
*
* @param $message
* @param string $title
* @param bool $exit
* @param bool|string $redirect a link to redirect after showing the message, or false
* @param int $rs delay in seconds if redirect parameter is set
* @param string $extra_code_header to append a code to head tag
* @param string $style is err or info, set by default, no need to fill
*/
function kleeja_err($message, $title = '', $exit = true, $redirect = false, $rs = 2, $extra_code_header = '', $style = 'err')
{
global $text, $tpl, $SQL;
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_err_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
// assign {text} in err template
$text = $message . ($redirect ? redirect($redirect, false, $exit, $rs, true) : '');
//header
Saaheader($title, $extra_code_header);
//show tpl
echo $tpl->display($style);
//footer
Saafooter();
if($exit)
{
$SQL->close();
exit();
}
}
/**
* show an information message
*
* @param $message
* @param string $title
* @param bool $exit
* @param bool|string $redirect a link to redirect after showing the message, or false
* @param int $rs delay in seconds if redirect parameter is set
* @param string $extra_code_header to append a code to head tag
*/
function kleeja_info($message, $title='', $exit = true, $redirect = false, $rs = 5, $extra_code_header = '')
{
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_info_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
kleeja_err($message, $title, $exit, $redirect, $rs, $extra_code_header, 'info');
}
/**
* Show debug information
*/
function kleeja_debug()
{
global $SQL,$do_gzip_compress, $all_plg_hooks;
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_debug_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$debug_output = '';
//get memory usage ; code of phpbb
if (function_exists('memory_get_usage'))
{
if ($memory_usage = memory_get_usage())
{
$base_memory_usage = 0;
$memory_usage -= $base_memory_usage;
$memory_usage = ($memory_usage >= 1048576) ? round((round($memory_usage / 1048576 * 100) / 100), 2) . ' MB' : (($memory_usage >= 1024) ? round((round($memory_usage / 1024 * 100) / 100), 2) . ' KB' : $memory_usage . ' BYTES');
$debug_output = 'Memory Usage : <em>' . $memory_usage . '</em>';
}
}
//then show it
echo '<div class="debug_kleeja">';
echo '<fieldset dir="ltr"><legend><br /><br /><em style="font-family: Tahoma,serif; color:red">[Page Analysis]</em></legend>';
echo '<p>&nbsp;</p>';
echo '<p><h2><strong>General Information :</strong></h2></p>';
echo '<p>Gzip : <em>' . ($do_gzip_compress !=0 ? "Enabled" : "Disabled") . '</em></p>';
echo '<p>Queries Number :<em> ' . $SQL->query_num . ' </i></p>';
echo '<p>Hook System :<em> ' . ((!defined('STOP_PLUGINS')) ? "Enabled" : "Disabled") . ' </em></p>';
echo '<p>' . $debug_output . '</p>';
echo '<p>&nbsp;</p>';
echo '<p><h2><strong><em>SQL</em> Information :</strong></h2></p> ';
if(is_array($SQL->debugr))
{
foreach($SQL->debugr as $key=>$val)
{
echo '<fieldset name="sql" dir="ltr" style="background:white"><legend><em>Query # [' . ($key+1) . '</em>]</legend> ';
echo '<textarea style="font-family:Courier New,monospace;width:99%; background:#F4F4F4" rows="5" cols="10">' . $val[0] . '';
echo '</textarea> <br />';
echo 'Duration :' . $val[1] . '';
echo '</fieldset>';
echo '<br /><br />';
}
}
else
{
echo '<p><strong>NO SQLs</strong></p>';
}
echo '<p>&nbsp;</p><p><h2><strong><em>Plugins</em> Information :</strong></h2></p> ';
echo '<ul>';
if(sizeof(Plugins::getInstance()->getDebugInfo()) > 0)
{
echo '<textarea style="font-family:\'Courier New\',monospace;width:99%; background:#F4F4F4" rows="20" cols="10">' . var_export(Plugins::getInstance()->getDebugInfo(), true) . '';
echo '</textarea> <br />';
}
else
{
echo '<p><strong>...</strong></p>';
}
echo '</ul>';
echo '</div>';
}
/**
* Show error of critical problem
*
* @param string $error_title title
* @param string $msg_text content
* @param bool $error is it an error or an info message
*/
function big_error($error_title, $msg_text, $error = true)
{
global $SQL;
echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">' . "\n";
echo '<head>' . "\n";
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' . "\n";
echo '<title>' . htmlspecialchars($error_title) . '</title>' . "\n";
echo '<style type="text/css">' . "\n\t";
echo '* { margin: 0; padding: 0; }' . "\n\t";
echo '.error {color: #333;background:#ffebe8;float:left;width:73%;text-align:left;margin-top:10px;border: 1px solid #dd3c10;} .info {color: #333;background:#fff9d7;border: 1px solid #e2c822;}' . "\n\t";
echo '.error,.info {padding: 10px;font-family:"lucida grande", tahoma, verdana, arial, sans-serif;font-size: 12px;}' . "\n";
echo '</style>' . "\n";
echo '</head>' . "\n";
echo '<body>' . "\n\t";
echo '<div class="' . ($error ? 'error' : 'info') . '">' . "\n";
echo "\n\t\t<h2>Kleeja " . ($error ? 'error' : 'information message') . " : </h2><br />" . "\n";
echo "\n\t\t<strong> [ " . $error_title . ' ] </strong><br /><br />' . "\n\t\t" . $msg_text . "\n\t";
echo "\n\t\t" . '<br /><br /><small>Visit <a href="http://www.kleeja.com/" title="kleeja">Kleeja</a> Website for more details.</small>' . "\n\t";
echo '</div>' . "\n";
echo '</body>' . "\n";
echo '</html>';
@$SQL->close();
exit();
}
/**
* Redirect to a url
* @param string $url
* @param bool $header true for header location redirect or false for html meta
* @param bool $exit halt after echoing the redirect code
* @param int $sec delay in seconds
* @param bool $return return the html code only
* @return mixed
*
*/
function redirect($url, $header = true, $exit = true, $sec = 0, $return = false)
{
global $SQL;
is_array($plugin_run_result = Plugins::getInstance()->run('redirect_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if (!headers_sent() && $header && !$return)
{
header('Location: ' . str_replace(array('&amp;'), array('&'), $url));
}
else
{
$gre = '<script type="text/javascript"> setTimeout("window.location.href = \'' . str_replace(array('&amp;'), array('&'), $url) . '\'", ' . $sec*1000 . '); </script>' .
'<noscript><meta http-equiv="refresh" content="' . $sec . ';url=' . $url . '" /></noscript>';
if($return)
{
return $gre;
}
echo $gre;
}
if($exit)
{
$SQL->close();
exit;
}
return null;
}
/**
*
* Prevent CSRF,
*
* This will generate security token for GET request
* @param string $request_id
* @return string
*/
function kleeja_add_form_key_get($request_id)
{
global $config;
$return = 'formkey=' . substr(sha1($config['h_key'] . date('H-d-m') . $request_id), 0, 20);
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_add_form_key_get_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
function kleeja_check_form_key_get($request_id)
{
global $config;
$token = substr(sha1($config['h_key'] . date('H-d-m') . $request_id), 0, 20);
$return = false;
if($token == g('formkey'))
{
$return = true;
}
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_check_form_key_get_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
/**
* This will generate hidden fields for kleeja forms, csrf input
* @param string $form_name
* @return string
*/
function kleeja_add_form_key($form_name)
{
global $config;
$now = time();
$return = '<input type="hidden" name="k_form_key" value="' . sha1($config['h_key'] . $form_name . $now) . '" /><input type="hidden" name="k_form_time" value="' . $now . '" />' . "\n";
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_add_form_key_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
/**
* This will check csrf hidden fields that came from kleeja forms
* @param string $form_name
* @param int $require_time in seconds
* @return bool
*/
function kleeja_check_form_key($form_name, $require_time = 300)
{
global $config;
if(defined('IN_ADMIN'))
{
//we increase it for admin to be a double
$require_time *= 2;
}
$return = false;
if (ip('k_form_key') && ip('k_form_time'))
{
$key_was = trim(p('k_form_key'));
$time_was = p('k_form_time', 'int');
$different = time() - $time_was;
//check time that user spent in the form
if($different && (!$require_time || $require_time >= $different))
{
if(sha1($config['h_key'] . $form_name . $time_was) === $key_was)
{
$return = true;
}
}
}
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_check_form_key_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
/**
* Link generator
* TODO to be edited
* Files can be many links styles, so this will generate the current style of link
* @param $pid
* @param array $extra
* @return string
*/
function kleeja_get_link ($pid, $extra = array())
{
global $config;
$links = array();
//to avoid problems
$config['id_form'] = empty($config['id_form']) ? 'id' : $config['id_form'];
$config['id_form_img'] = empty($config['id_form_img']) ? 'id' : $config['id_form_img'];
//to prevent bug with rewrite
if($config['mod_writer'] && !empty($extra['::NAME::']))
{
if(
(($pid == 'image' || $pid == 'thumb') && $config['id_form_img'] != 'direct') ||
($pid == 'file' && $config['id_form'] != 'direct')
)
{
$extra['::NAME::'] = str_replace('.', '-', $extra['::NAME::']);
}
}
$file_link = array(
'id' => $config['mod_writer'] ? 'download::ID::.html' : 'do.php?id=::ID::',
'filename' => $config['mod_writer'] ? 'downloadf-::NAME::.html' : 'do.php?filename=::NAME::',
'direct' => '::DIR::/::NAME::',
);
$image_link = array(
'id' => $config['mod_writer'] ? 'image::ID::.html' : 'do.php?img=::ID::',
'filename' => $config['mod_writer'] ? 'imagef-::NAME::.html' : 'do.php?imgf=::NAME::',
'direct' => '::DIR::/::NAME::',
);
$thumb_link = array(
'id' => $config['mod_writer'] ? 'thumb::ID::.html' : 'do.php?thmb=::ID::',
'filename' => $config['mod_writer'] ? 'thumbf-::NAME::.html' : 'do.php?thmbf=::NAME::',
'direct' => '::DIR::/thumbs/::NAME::',
);
$del_link = $config['mod_writer'] ? 'del::CODE::.html' : 'go.php?go=del&amp;cd=::CODE::';
$links['file'] = $file_link[$config['id_form']];
$links['image'] = $image_link[$config['id_form_img']];
$links['thumb'] = $thumb_link[$config['id_form_img']];
$links['del'] = $del_link;
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_get_link_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$return_link = $config['siteurl'] . str_replace(array_keys($extra), array_values($extra), $links[$pid]);
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_get_link_func2', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return_link;
}
/**
* Uploading boxes
*
* Parse template of boxes and print them
* @param string $box_name html block name from up_boxes.html file
* @param array $extra variables to pass to the html block
* @return mixed
*/
function get_up_tpl_box($box_name, $extra = array())
{
global $THIS_STYLE_PATH_ABS, $config;
static $boxes = false;
//prevent loads
//also this must be cached in future
if($boxes !== true)
{
$tpl_path = $THIS_STYLE_PATH_ABS . 'up_boxes.html';
if(!file_exists($tpl_path))
{
$depend_on = false;
if(trim($config['style_depend_on']) != '')
{
$depend_on = $config['style_depend_on'];
}
else
{
$depend_on = 'default';
}
$tpl_path = str_replace('/' . $config['style'] . '/', '/' . trim($depend_on) . '/', $tpl_path);
}
$tpl_code = file_get_contents($tpl_path);
$tpl_code = preg_replace("/\n[\n\r\s\t]*/", '', $tpl_code);//remove extra spaces
$matches = preg_match_all('#<!-- BEGIN (.*?) -->(.*?)<!-- END (?:.*?) -->#', $tpl_code, $match);
$boxes = array();
for ($i = 0; $i < $matches; $i++)
{
if (empty($match[1][$i]))
{
continue;//it's empty , let's leave it
}
$boxes[$match[1][$i]] = $match[2][$i];
}
}
//extra value
$extra += array(
'siteurl' => $config['siteurl'],
'sitename' => $config['sitename'],
);
//return compiled value
$return = $boxes[$box_name];
foreach($extra as $var=>$val)
{
$return = preg_replace('/{' . $var . '}/', $val, $return);
}
/*
* We add this hook here so you can substitute you own vars
* and even add your own boxes to this template.
*/
is_array($plugin_run_result = Plugins::getInstance()->run('get_up_tpl_box_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
/**
* Extract info of a style
* @param string $style_name
* @return array|bool
*/
function kleeja_style_info($style_name)
{
$inf_path = PATH . 'styles/' . $style_name . '/info.txt';
//is info.txt exists or not
if(!file_exists($inf_path))
{
return false;
}
$inf_c = file_get_contents($inf_path);
//some ppl will edit this file with notepad or even with office word :)
$inf_c = str_replace(array("\r\n", "\r"), array("\n", "\n"), $inf_c);
//as lines
$inf_l = @explode("\n", $inf_c);
$inf_l = array_map('trim', $inf_l);
$inf_r = array();
foreach($inf_l as $m)
{
//comments
if(isset($m[0]) && $m[0] == '#' || trim($m) == '')
{
continue;
}
$t = array_map('trim', @explode('=', $m, 2));
# ':' mean something secondary as in sub-array
if(strpos($t[0], ':') !== false)
{
$subInfo = explode(':', $t[0]);
$t_t0 = array_map('trim', $subInfo);
$inf_r[$t_t0[0]][$t_t0[1]] = $t[1];
}
else
{
$inf_r[$t[0]] = $t[1];
}
}
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_style_info_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $inf_r;
}
/**
* Browser detection
* returns whether or not the visiting browser is the one specified [part of kleeja style system]
* i.e. is_browser('ie6') -> true or false
* i.e. is_browser('ie, opera') -> true or false
* @param string $b browser name, like mozilla
* @return bool
*/
function is_browser($b)
{
//is there , which mean -OR-
if(strpos($b, ',') !== false)
{
$e = explode(',', $b);
foreach($e as $n)
{
if(is_browser(trim($n)))
{
return true;
}
}
return false;
}
//if no agent, let's take the worst case
$u_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : (function_exists('getenv') ? getenv('HTTP_USER_AGENT') : '');
$t = trim(preg_replace('/[^a-z]/', '', $b));
$r = trim(preg_replace('/[a-z]/', '', $b));
$return = false;
switch($t)
{
case 'ie':
$return = strpos(strtolower($u_agent), trim('msie ' . $r)) !== false ? true : false;
break;
case 'firefox':
$return = strpos(str_replace('/', ' ', strtolower($u_agent)), trim('firefox ' . $r)) !== false ? true : false;
break;
case 'safari':
$return = strpos(strtolower($u_agent), trim('safari/' . $r)) !== false ? true : false;
break;
case 'chrome':
$return = strpos(strtolower($u_agent), trim('chrome ' . $r)) !== false ? true : false;
break;
case 'flock':
$return = strpos(strtolower($u_agent), trim('flock ' . $r)) !== false ? true : false;
break;
case 'opera':
$return = strpos(strtolower($u_agent), trim('opera ' . $r)) !== false ? true : false;
break;
case 'konqueror':
$return = strpos(strtolower($u_agent), trim('konqueror/' . $r)) !== false ? true : false;
break;
case 'mozilla':
$return = strpos(strtolower($u_agent), trim('gecko/' . $r)) !== false ? true : false;
break;
case 'webkit':
$return = strpos(strtolower($u_agent), trim('applewebkit/' . $r)) !== false ? true : false;
break;
/**
* Mobile Phones are so popular those days, so we have to support them ...
* This is still in our test lab.
* @see http://en.wikipedia.org/wiki/List_of_user_agents_for_mobile_phones
**/
case 'mobile':
$mobile_agents = array('iPhone;', 'iPod;', 'blackberry', 'Android', 'HTC' , 'IEMobile', 'LG/', 'LG-',
'LGE-', 'MOT-', 'Nokia', 'SymbianOS', 'nokia_', 'PalmSource', 'webOS', 'SAMSUNG-',
'SEC-SGHU', 'SonyEricsson', 'BOLT/', 'Mobile Safari', 'Fennec/', 'Opera Mini');
$return = false;
foreach($mobile_agents as $agent)
{
if(strpos($u_agent, $agent) !== false)
{
$return = true;
break;
}
}
break;
}
is_array($plugin_run_result = Plugins::getInstance()->run('is_browser_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
/**
* Converting array to JSON format, nested arrays not supported
* @param array $array
* @return string
*/
function generate_json($array)
{
$json = '';
$json_escape = array(
array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')
);
foreach($array as $key=>$value)
{
$json .= ($json != '' ? ', ' : '') . '"' . $key . '":' .
(preg_match('^[0-9]+$', $value) ? $value : '"' . str_replace($json_escape[0], $json_escape[1], $value) . '"');
}
return '{' . $json . '}';
}
/**
* Send an answer for ajax request
* @param int $code_number
* @param string $content
* @param string $menu
*/
function echo_ajax($code_number, $content, $menu = '')
{
global $SQL;
$SQL->close();
exit(generate_json(array('code' => $code_number, 'content' => $content, 'menu' => $menu)));
}
/**
* Send an answer for ajax request [ARRAY]
* @param array $array
*/
function echo_array_ajax($array)
{
global $SQL;
$SQL->close();
//generate_json has some bugs so I will use json_encode instead :[
exit(@json_encode($array));
}
/**
* show date in a human-readable-text
* @param int $time timestamp
* @param bool $human_time return a readable time, like today, 1 hour ago
* @param bool $format date format like d-m-y
* @return string
*/
function kleeja_date($time, $human_time = true, $format = false)
{
global $lang, $config;
if (!defined('TIME_FORMAT')) {
define('TIME_FORMAT', 'd-m-Y h:i a'); # to be moved to configs later
}
if((time() - $time > (86400 * 9)) || $format || !$human_time)
{
$format = !$format ? TIME_FORMAT : $format;
$time = $time + ((int) $config['time_zone']*60*60);
return str_replace(array('am', 'pm'), array($lang['TIME_AM'], $lang['TIME_PM']), gmdate($format, $time));
}
$lengths = array("60","60","24","7","4.35","12","10");
$timezone_diff = (int)$config['time_zone'] * 60 * 60;
$now = time() + $timezone_diff;
$time = $time + $timezone_diff;
$difference = $now > $time ? $now - $time : $time - $now;
$tense = $now > $time ? $lang['W_AGO'] : $lang['W_FROM'];
for($j = 0; $difference >= $lengths[$j] && $j < sizeof($lengths)-1; $j++)
{
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1)
{
if($difference == 2)
{
$return = $lang['W_PERIODS_DP_' . $j];
}
else
{
$return = $difference . ' ' . ($difference > 10 ? $lang['W_PERIODS_' . $j] : $lang['W_PERIODS_P_' . $j]);
}
}
else
{
$return = $lang['W_PERIODS_' . $j];
}
$return = $now > $time ? $return . ' ' . $lang['W_AGO']: $lang['W_FROM'] . ' ' . $return;
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_date_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
/*
* World Time Zones
* @return array
*/
function time_zones()
{
return array(
'Kwajalein' => -12.00,
'Pacific/Midway' => -11.00,
'Pacific/Honolulu' => -10.00,
'America/Anchorage' => -9.00,
'America/Los_Angeles' => -8.00,
'America/Denver' => -7.00,
'America/Tegucigalpa' => -6.00,
'America/New_York' => -5.00,
'America/Caracas' => -4.30,
'America/Halifax' => -4.00,
'America/St_Johns' => -3.30,
'America/Argentina/Buenos_Aires' => -3.00,
'America/Sao_Paulo' => -3.00,
'Atlantic/South_Georgia' => -2.00,
'Atlantic/Azores' => -1.00,
'Europe/Dublin' => 0,
'Europe/Belgrade' => 1.00,
'Europe/Minsk' => 2.00,
'Asia/Riyadh' => 3.00,
'Asia/Buraydah' => 3.01,
'Asia/Tehran' => 3.30,
'Asia/Muscat' => 4.00,
'Asia/Yekaterinburg' => 5.00,
'Asia/Kolkata' => 5.30,
'Asia/Katmandu' => 5.45,
'Asia/Dhaka' => 6.00,
'Asia/Rangoon' => 6.30,
'Asia/Krasnoyarsk' => 7.00,
'Asia/Brunei' => 8.00,
'Asia/Seoul' => 9.00,
'Australia/Darwin' => 9.30,
'Australia/Canberra' => 10.00,
'Asia/Magadan' => 11.00,
'Pacific/Fiji' => 12.00,
'Pacific/Tongatapu' => 13.00
);
}
/**
* generate a config html field to insert to add as an acp option
* @param string $name config name
* @param string $type input type (text, yesno, select)
* @param array $select_options in case of select type, provide options array ([[title=>value], [title=>value]]
* @return string input html
*/
function configField($name, $type = 'text', $select_options = array())
{
switch ($type) {
default:
case 'text':
return '<input type="text" id="kj_meta_seo_home_meta_keywords" name="' . $name . '"' .
' value="{con.' . $name . '}" size="50" />';
case 'yesno':
return '<label>{lang.YES}<input type="radio" id="' . $name . '" name="' . $name . '" ' .
'value="1" <IF NAME="con.' . $name . '==1"> checked="checked"</IF> /></label><label>{lang.NO}' .
'<input type="radio" id="' . $name . '" name="' . $name . '" value="0" ' .
' <IF NAME="con.' . $name . '==0"> checked="checked"</IF> /></label>';
case 'select':
$return_value = '<select id="' . $name . '" name="' . $name . '">' . "\n";
foreach ($select_options as $title => $value) {
$return_value .= '<option <IF NAME="con.' . $name . '==' . $value . '">selected="selected"</IF> value="0">' . $title . '</option>' . "\n";
}
return $return_value . '</select>' . "\n";
}
}
/**
* Shorten A string
*
* @param string $text The strings to shorten
* @param int $until
* @return string Short string
*/
function shorten_text($text, $until = 30)
{
$until = $until < 4 ? 4 : $until;
$chars_len = function_exists('mb_strlen') ? mb_strlen($text, 'UTF-8') : strlen($text);
if ($chars_len >= $until)
{
$return = function_exists('mb_substr')
? (mb_substr($text, 0, $until-4, 'UTF-8'). " ... " . mb_substr($text, -4, null,'UTF-8'))
: substr($text, 0, $until-4). " ... " . substr($text, -4);
}
else
{
$return = $text;
}
is_array($plugin_run_result = Plugins::getInstance()->run('shorten_text_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}

58
includes/index.html Executable file
View File

@@ -0,0 +1,58 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256"/>
<title>Powered by Kleeja</title>
<style type="text/css">* {
font-size: 100%;
margin: 0;
padding: 0;
color: #CECFCE;
}
body {
font-family: Tahoma, Arial, sans-serif;
font-size: 100%;
color: #69788E;
margin: 10px 30px;
background: #F7F7F7;
}
a:link, a:visited {
text-decoration: none;
color: #CECFCE;
}
a:active, a:hover {
text-decoration: underline;
color: #111;
}
h1 {
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-size: 1.70em;
font-weight: normal;
color: #333333;
margin-top: 0;
margin-bottom: 10px;
}
.content_box {
border: 1px dashed #CECFCE;
background: #FFFFFF;
padding: 10px;
margin-right: auto;
margin-left: auto;
}</style>
</head>
<body title="&#1603;&#1604;&#1610;&#1580;&#1575;"><br/>
<div class="content_box">
<p>
<a target="_blank" href="http://www.kleeja.com" title="kleeja"></a>
</p>
<br/>
<h1><span style="font-size:250%;color:#D80000;">403 - Access forbidden!</span></h1></div>
<br/>
<div class="content_box"style="font-size: 140%">Powered by Kleeja</div>
</body>
</html>

491
includes/mysql.php Executable file
View File

@@ -0,0 +1,491 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
if(!defined("SQL_LAYER")):
define("SQL_LAYER","mysql4");
class SSQL
{
var $connect_id = null;
var $result;
var $query_num = 0;
var $in_transaction = 0;
var $debugr = false;
var $show_errors = true;
/*
* initiate the class
* wirth basic data
*/
function __construct($host, $db_username, $db_password, $db_name, $new_link=false)
{
global $script_encoding;
$this->host= $host;
$this->db_username = $db_username;
$this->db_name = $db_name;
$this->db_password = 'hidden';
//no error
if(defined('MYSQL_NO_ERRORS'))
{
$this->show_errors = false;
}
$this->connect_id = @mysql_connect($this->host, $this->db_username, $db_password, $new_link) or die($this->error_msg("we can not connect to the server ..."));
if($this->connect_id)
{
#loggin -> connecting
kleeja_log('[Connected] : ' . kleeja_get_page());
if(!empty($db_name))
{
$dbselect = @mysql_select_db($this->db_name) or die($this->error_msg("we can not select database"));
if ($dbselect)
{
#login -> selecting database
kleeja_log('[Selected Database] :' . $this->connect_id);
if ((!preg_match('/utf/i', strtolower($script_encoding)) && !defined('IN_LOGINPAGE') && !defined('IN_ADMIN_LOGIN') && !defined('DISABLE_INTR')) || ((empty($script_encoding) || preg_match('/utf/i', strtolower($script_encoding)) || defined('DISABLE_INTR'))))
{
if(mysql_query("SET NAMES 'utf8'"))
{
#loggin -> set utf8
kleeja_log('[Set to UTF8] :' . $this->connect_id);
}
}
}
else if(!$dbselect)
{
#loggin -> no database -> close connection
$this->close($this->connect_id);
$this->connect_id = $dbselect;
}
}
return $this->connect_id;
}
else
{
return false;
}
}
/*
* close the connection
*/
function close()
{
if( $this->connect_id )
{
// Commit any remaining transactions
if( $this->in_transaction )
{
mysql_query("COMMIT", $this->connect_id);
}
#loggin -> close connection
kleeja_log('[Closing connection] :' . kleeja_get_page());
return @mysql_close($this->connect_id);
}
else
{
return false;
}
}
/*
* encoding functions
*/
function set_utf8()
{
return $this->set_names('utf8');
}
function set_names($charset)
{
@mysql_query("SET NAMES '" . $charset . "'", $this->connect_id);
}
function client_encoding()
{
return mysql_client_encoding($this->connect_id);
}
function mysql_version()
{
//version of mysql
$vr = $this->query('SELECT VERSION() AS v');
$vs = $this->fetch_array($vr);
$vs = $vs['v'];
return preg_replace('/^([^-]+).*$/', '\\1', $vs);
}
/*
the query func . its so important to do
the quries and give results
*/
function query($query, $transaction = FALSE)
{
//no connection
if(!$this->connect_id)
{
return false;
}
//
// Remove any pre-existing queries
//
unset($this->result);
if(!empty($query))
{
//debug .. //////////////
$srartum_sql = get_microtime();
////////////////
if( $transaction == 1 && !$this->in_transaction )
{
$result = mysql_query("BEGIN", $this->connect_id);
if(!$result)
{
return false;
}
$this->in_transaction = TRUE;
}
$this->result = mysql_query($query, $this->connect_id);
//debug .. //////////////
$this->debugr[$this->query_num+1] = array($query, sprintf('%.5f', get_microtime() - $srartum_sql));
////////////////
if(!$this->result)
{
$this->error_msg('Error In query');
}
else
{
//let's debug it
kleeja_log('[Query] : --> ' . $query);
}
}
else
{
if( $transaction == 2 && $this->in_transaction )
{
$this->result = mysql_query("COMMIT", $this->connect_id);
}
}
//is there any result
if($this->result)
{
if($transaction == 2 && $this->in_transaction)
{
$this->in_transaction = FALSE;
if (!mysql_query("COMMIT", $this->connect_id))
{
mysql_query("ROLLBACK", $this->connect_id);
return false;
}
}
$this->query_num++;
return $this->result;
}
else
{
if( $this->in_transaction )
{
mysql_query("ROLLBACK", $this->connect_id);
$this->in_transaction = FALSE;
}
return false;
}
}
/*
* query build
*/
function build($query)
{
$sql = '';
if (isset($query['SELECT']))
{
$sql = 'SELECT '.$query['SELECT'].' FROM '.$query['FROM'];
if (isset($query['JOINS']))
{
foreach ($query['JOINS'] as $cur_join)
$sql .= ' '.key($cur_join).' '. @current($cur_join).' ON '.$cur_join['ON'];
}
if (!empty($query['WHERE']))
$sql .= ' WHERE '.$query['WHERE'];
if (!empty($query['GROUP BY']))
$sql .= ' GROUP BY '.$query['GROUP BY'];
if (!empty($query['HAVING']))
$sql .= ' HAVING '.$query['HAVING'];
if (!empty($query['ORDER BY']))
$sql .= ' ORDER BY '.$query['ORDER BY'];
if (!empty($query['LIMIT']))
$sql .= ' LIMIT '.$query['LIMIT'];
}
else if (isset($query['INSERT']))
{
$sql = 'INSERT INTO '.$query['INTO'];
if (!empty($query['INSERT']))
$sql .= ' ('.$query['INSERT'].')';
$sql .= ' VALUES('.$query['VALUES'].')';
}
else if (isset($query['UPDATE']))
{
$query['UPDATE'] = $query['UPDATE'];
if (isset($query['PARAMS']['LOW_PRIORITY']))
$query['UPDATE'] = 'LOW_PRIORITY '.$query['UPDATE'];
$sql = 'UPDATE '.$query['UPDATE'].' SET '.$query['SET'];
if (!empty($query['WHERE']))
$sql .= ' WHERE '.$query['WHERE'];
}
else if (isset($query['DELETE']))
{
$sql = 'DELETE FROM '.$query['DELETE'];
if (!empty($query['WHERE']))
$sql .= ' WHERE '.$query['WHERE'];
}
else if (isset($query['REPLACE']))
{
$sql = 'REPLACE INTO '.$query['INTO'];
if (!empty($query['REPLACE']))
$sql .= ' ('.$query['REPLACE'].')';
$sql .= ' VALUES('.$query['VALUES'].')';
}
return $this->query($sql);
}
/*
* free the memmory from the last results
*/
function free($query_id = 0)
{
return $this->freeresult($query_id);
}
function freeresult($query_id = 0)
{
if(!$query_id)
{
$query_id = $this->result;
}
if ($query_id)
{
mysql_free_result($query_id);
return true;
}
else
{
return false;
}
}
/*
* if the result is an arry ,
* this func is so important to order them as a array
*/
function fetch($query_id = 0)
{
return $this->fetch_array($query_id);
}
function fetch_array($query_id = 0)
{
if( !$query_id )
{
$query_id = $this->result;
}
return $query_id ? mysql_fetch_array($query_id, MYSQL_ASSOC) : false;
}
/*
* if we have a result and we have to know
* the number of it , this is a func ..
*/
function num_rows($query_id = 0)
{
if( !$query_id )
{
$query_id = $this->result;
}
return $query_id ? mysql_num_rows($query_id) : false;
}
/*
* last id inserted in sql
*/
function insert_id()
{
return ($this->connect_id) ? mysql_insert_id($this->connect_id) : false;
}
/*
* clean the qurery before insert it
*/
function escape($msg)
{
$msg = htmlspecialchars($msg , ENT_QUOTES);
#$msg = (!get_magic_quotes_gpc()) ? addslashes ($msg) : $msg;
$msg = $this->real_escape($msg);
return $msg;
}
/*
* real escape ..
*/
function real_escape($msg)
{
if (is_array($msg))
{
return '';
}
else if (function_exists('mysql_real_escape_string'))
{
if(!$this-connect_id)
{
return 0;
}
return mysql_real_escape_string($msg, $this->connect_id);
}
else
{
// because mysql_escape_string doesnt escape % & _[php.net/mysql_escape_string]
//return addcslashes(mysql_escape_string($msg),'%_');
return mysql_escape_string($msg);
}
}
/*
* get affected records
*/
function affected()
{
return ( $this->connect_id ) ? mysql_affected_rows($this->connect_id) : false;
}
/*
* get the information of mysql server
*/
function server_info()
{
return 'MySQL ' . $this->mysql_version;
}
/*
error message func
*/
function error_msg($msg)
{
global $dbprefix;
if(!$this->show_errors)
{
return false;
}
$error_no = mysql_errno();
$error_msg = mysql_error();
$error_sql = @current($this->debugr[$this->query_num+1]);
//some ppl want hide their table names, not in develoment stage
if(!defined('DEV_STAGE'))
{
$error_sql = preg_replace("#\s{1,3}`*{$dbprefix}([a-z0-9]+)`*\s{1,3}#e", "' <span style=\"color:blue\">' . substr('$1', 0, 1) . '</span> '", $error_sql);
$error_msg = preg_replace("#{$this->db_name}.{$dbprefix}([a-z0-9]+)#e", "' <span style=\"color:blue\">' . substr('$1', 0, 1) . '</span> '", $error_msg);
$error_sql = preg_replace("#\s{1,3}(from|update|into)\s{1,3}([a-z0-9]+)\s{1,3}#ie", "' $1 <span style=\"color:blue\">' . substr('$2', 0, 1) . '</span> '", $error_sql);
$error_msg = preg_replace("#\s{1,3}(from|update|into)\s{1,3}([a-z0-9]+)\s{1,3}#ie", "' $1 <span style=\"color:blue\">' . substr('$2', 0, 1) . '</span> '", $error_msg);
$error_msg = preg_replace("#\s'([^']+)'@'([^']+)'#ie", "' <span style=\"color:blue\">hidden</span>@$2 '", $error_msg);
$error_sql = preg_replace("#password\s*=\s*'[^']+'#i", "password='<span style=\"color:blue\">hidden</span>'", $error_sql);
}
#is this error related to updating?
$updating_related = false;
if(strpos($error_msg, 'Unknown column') !== false)
{
$updating_related = true;
}
echo "<html><head><title>ERROR IM MYSQL</title>";
echo "<style>BODY{FONT-FAMILY:tahoma;FONT-SIZE:12px;}.error {}</style></head><body>";
echo '<br />';
echo '<div class="error">';
echo " <a href='#' onclick='window.location.reload( false );'>click to Refresh this page ...</a><br />";
echo "<h2>Sorry , There is an error in mysql " . ($msg !='' ? ", error : $msg" : "") ."</h2>";
if($error_sql != '')
{
echo "<br />--[query]-------------------------- <br />$error_sql<br />---------------------------------<br /><br />";
}
echo "[$error_no : $error_msg] <br />";
if($updating_related)
{
global $config;
echo "<br /><strong>Your Kleeja database seems to be old, try to update it now from: " . $config['siteurl'] . "install/</strong>";
}
echo "<br /><br /><strong>Script: Kleeja <br /><a href='http://www.kleeja.com'>Kleeja Website</a></strong>";
echo '</b></div>';
echo '</body></html>';
#loggin -> error
kleeja_log('[SQL ERROR] : "' . $error_no . ' : ' . $error_msg . '" ' . $this->connect_id);
@$this->close();
exit();
}
/*
* return last error
*/
function get_error()
{
return array(mysql_errno(), mysql_error());
}
}#end of class
endif;

489
includes/mysqli.php Executable file
View File

@@ -0,0 +1,489 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
if(!defined("SQL_LAYER")):
define("SQL_LAYER","mysqli");
class KleejaDatabase
{
var $connect_id = null;
var $result;
var $query_num = 0;
var $in_transaction = 0;
var $debugr = false;
var $show_errors = true;
/*
* initiate the class
* with basic data
*/
function __construct($host, $db_username, $db_password, $db_name, $new_link = false)
{
global $script_encoding;
$host .= strpos($host, ':') !== false ? '' : ':';
$this->host = substr($host, 0, strpos($host, ':'));
$this->port = (int) substr($host, strpos($host, ':')+1);
$this->db_username = $db_username;
$this->db_name = $db_name;
$this->db_password = 'hidden';
$this->connect_id = @mysqli_connect($this->host, $this->db_username, $db_password, $this->db_name, (!$this->port ? 3306 : $this->port ));
//no error
if(defined('MYSQL_NO_ERRORS'))
{
$this->show_errors = false;
}
if(!$this->connect_id)
{
#loggin -> no database -> close connection
$this->close();
$this->error_msg("we can not connect to the server ...");
return false;
}
#loggin -> connecting
kleeja_log('[Connected] : ' . kleeja_get_page());
if ((!preg_match('/utf/i', strtolower($script_encoding)) && !defined('IN_LOGINPAGE') && !defined('IN_ADMIN_LOGIN') && !defined('DISABLE_INTR')) || (empty($script_encoding) || preg_match('/utf/i', strtolower($script_encoding)) || defined('DISABLE_INTR')))
{
if(mysqli_set_charset($this->connect_id, 'utf8'))
{
#loggin -> set utf8
kleeja_log('[Set to UTF8] : --> ');
}
}
return $this->connect_id;
}
function is_connected()
{
return !(is_null($this->connect_id) || empty($this->connect_id));
}
/*
* close the connection
*/
function close()
{
if($this->connect_id)
{
// Commit any remaining transactions
if($this->in_transaction)
{
mysqli_commit($this->connect_id);
}
#loggin -> close connection
kleeja_log('[Closing connection] : ' . kleeja_get_page());
return @mysqli_close($this->connect_id);
}
else
{
return false;
}
}
/*
* encoding functions
*/
function set_utf8()
{
$this->set_names('utf8');
}
function set_names($charset)
{
@mysqli_set_charset($this->connect_id, $charset);
}
function client_encoding()
{
return mysqli_character_set_name($this->connect_id);
}
function mysql_version()
{
$vr = $this->query('SELECT VERSION() AS v');
$vs = $this->fetch_array($vr);
$vs = $vs['v'];
return preg_replace('/^([^-]+).*$/', '\\1', $vs);
}
/*
* the query func . its so important to do
* the quries and give results
*/
function query($query, $transaction = false)
{
//no connection
if(!$this->connect_id)
{
return false;
}
//
// Remove any pre-existing queries
//
unset($this->result);
if(!empty($query))
{
//debug .. //////////////
$srartum_sql = get_microtime();
////////////////
if($transaction == 1 && !$this->in_transaction)
{
if(!mysqli_autocommit($this->connect_id, false))
{
return false;
}
$this->in_transaction = TRUE;
}
$this->result = mysqli_query($this->connect_id, $query);
//debug .. //////////////
$this->debugr[$this->query_num+1] = array($query, sprintf('%.5f', get_microtime() - $srartum_sql));
////////////////
if(!$this->result)
{
$this->error_msg('Error In query');
}
else
{
//let's debug it
kleeja_log('[Query] : --> ' . $query);
}
}
else
{
if( $transaction == 2 && $this->in_transaction )
{
$this->result = mysqli_commit($this->connect_id);
}
}
//is there any result
if($this->result)
{
if($transaction == 2 && $this->in_transaction)
{
$this->in_transaction = false;
if (!mysqli_commit($this->connect_id))
{
mysqli_rollback($this->connect_id);
return false;
}
}
$this->query_num++;
return $this->result;
}
else
{
if($this->in_transaction)
{
mysqli_rollback($this->connect_id);
$this->in_transaction = false;
}
return false;
}
}
/*
* query build
*/
function build($query)
{
$sql = '';
if (isset($query['SELECT']))
{
$sql = 'SELECT '.$query['SELECT'].' FROM '.$query['FROM'];
if (isset($query['JOINS']))
{
foreach ($query['JOINS'] as $cur_join)
$sql .= ' '.key($cur_join).' '. @current($cur_join).' ON '.$cur_join['ON'];
}
if (!empty($query['WHERE']))
$sql .= ' WHERE '.$query['WHERE'];
if (!empty($query['GROUP BY']))
$sql .= ' GROUP BY '.$query['GROUP BY'];
if (!empty($query['HAVING']))
$sql .= ' HAVING '.$query['HAVING'];
if (!empty($query['ORDER BY']))
$sql .= ' ORDER BY '.$query['ORDER BY'];
if (!empty($query['LIMIT']))
$sql .= ' LIMIT '.$query['LIMIT'];
}
else if (isset($query['INSERT']))
{
$sql = 'INSERT INTO '.$query['INTO'];
if (!empty($query['INSERT']))
$sql .= ' ('.$query['INSERT'].')';
$sql .= ' VALUES('.$query['VALUES'].')';
}
else if (isset($query['UPDATE']))
{
if (isset($query['PARAMS']['LOW_PRIORITY']))
$query['UPDATE'] = 'LOW_PRIORITY '.$query['UPDATE'];
$sql = 'UPDATE '.$query['UPDATE'].' SET '.$query['SET'];
if (!empty($query['WHERE']))
$sql .= ' WHERE '.$query['WHERE'];
}
else if (isset($query['DELETE']))
{
$sql = 'DELETE FROM '.$query['DELETE'];
if (!empty($query['WHERE']))
$sql .= ' WHERE '.$query['WHERE'];
}
else if (isset($query['REPLACE']))
{
$sql = 'REPLACE INTO '.$query['INTO'];
if (!empty($query['REPLACE']))
$sql .= ' ('.$query['REPLACE'].')';
$sql .= ' VALUES('.$query['VALUES'].')';
}
return $this->query($sql);
}
/*
* free the memmory from the last results
*/
function free($query_id = 0)
{
return $this->freeresult($query_id);
}
function freeresult($query_id = 0)
{
if(!$query_id)
{
$query_id = $this->result;
}
if ($query_id)
{
mysqli_free_result($query_id);
return true;
}
else
{
return false;
}
}
/*
* if the result is an arry ,
* this func is so important to order them as a array
*/
function fetch($query_id = 0)
{
return $this->fetch_array($query_id);
}
function fetch_array($query_id = 0)
{
if(!$query_id)
{
$query_id = $this->result;
}
return $query_id ? mysqli_fetch_array($query_id, MYSQLI_ASSOC) : false;
}
/*
* if we have a result and we have to know
* the number of it , this is a func ..
*/
function num_rows($query_id = 0)
{
if(!$query_id)
{
$query_id = $this->result;
}
return $query_id ? mysqli_num_rows($query_id) : false;
}
/*
* last id inserted in sql
*/
function insert_id()
{
return $this->connect_id ? mysqli_insert_id($this->connect_id) : false;
}
/*
* clean the qurery before insert it
*/
function escape($msg)
{
$msg = htmlspecialchars($msg , ENT_QUOTES);
#$msg = (!get_magic_quotes_gpc()) ? addslashes ($msg) : $msg;
$msg = $this->real_escape($msg);
return $msg;
}
/*
* real escape ..
*/
/**
* @param string|array $msg
* @return int|string
*/
function real_escape($msg)
{
if (is_array($msg) && !$this->connect_id)
{
return $msg;
}
if(!$this->connect_id)
{
return 0;
}
//escaping _ made alot of problems
//return addcslashes(mysqli_real_escape_string($this->connect_id, $msg), '%_');
return mysqli_real_escape_string($this->connect_id, $msg);
}
/*
* get affected records
*/
function affected()
{
return $this->connect_id ? mysqli_affected_rows($this->connect_id) : false;
}
/*
* get the information of mysql server
*/
function server_info()
{
return 'MySQLi ' . $this->mysql_version;
}
/*
* error message func
*/
function error_msg($msg)
{
global $dbprefix;
if(!$this->show_errors)
{
return false;
}
$error_no = $this->connect_id ? @mysqli_errno($this->connect_id) : @mysqli_connect_errno();
$error_msg = $this->connect_id ? @mysqli_error($this->connect_id) : @mysqli_connect_error();
$error_sql = @current($this->debugr[$this->query_num+1]);
//some ppl want hide their table names
if(!defined('DEV_STAGE'))
{
$error_sql = preg_replace("#\s{1,3}`*{$dbprefix}([a-z0-9]+)`*\s{1,3}#e", "' <span style=\"color:blue\">' . substr('$1', 0, 1) . '</span> '", $error_sql);
$error_msg = preg_replace("#{$this->db_name}.{$dbprefix}([a-z0-9]+)#e", "' <span style=\"color:blue\">' . substr('$1', 0, 1) . '</span> '", $error_msg);
$error_sql = preg_replace("#\s{1,3}(from|update|into)\s{1,3}([a-z0-9]+)\s{1,3}#ie", "' $1 <span style=\"color:blue\">' . substr('$2', 0, 1) . '</span> '", $error_sql);
$error_msg = preg_replace("#\s{1,3}(from|update|into)\s{1,3}([a-z0-9]+)\s{1,3}#ie", "' $1 <span style=\"color:blue\">' . substr('$2', 0, 1) . '</span> '", $error_msg);
$error_msg = preg_replace("#\s'([^']+)'@'([^']+)'#ie", "' <span style=\"color:blue\">hidden</span>@$2 '", $error_msg);
$error_sql = preg_replace("#password\s*=\s*'[^']+'#i", "password='<span style=\"color:blue\">hidden</span>'", $error_sql);
}
#is this error related to updating?
$updating_related = false;
if(strpos($error_msg, 'Unknown column') !== false)
{
$updating_related = true;
}
$error_message = "<html><head><title>ERROR IM MYSQL</title>";
$error_message .= "<style>BODY{font-family:'Tahoma',serif;font-size:12px;}.error {}</style></head><body>";
$error_message .= '<br />';
$error_message .= '<div class="error">';
$error_message .= " <a href='#' onclick='window.location.reload( false );'>click to Refresh this page ...</a><br />";
$error_message .= "<h2>Sorry , There is an error in mysql " . ($msg !='' ? ", error : $msg" : "") ."</h2>";
if($error_sql != '')
{
$error_message .= "<br />--[query]-------------------------- <br />$error_sql<br />---------------------------------<br /><br />";
}
$error_message .= "[$error_no : $error_msg] <br />";
if($updating_related)
{
global $config;
$error_message .= "<br /><strong>Your Kleeja database might be old, try to update it now from: " . rtrim($config['siteurl'], '/') . "/install</strong>";
}
$error_message .= "<br /><br /><strong>Script: Kleeja <br /><a href='http://www.kleeja.com'>Kleeja Website</a></strong>";
$error_message .= '</b></div>';
$error_message .= '</body></html>';
print $error_message;
#loggin -> error
kleeja_log('[SQL ERROR] : "' . $error_no . ' : ' . $error_msg . '" -->');
@$this->close();
exit();
}
/*
* return last error
*/
function get_error()
{
if($this->connect_id)
{
return array(@mysqli_errno($this->connect_id), @mysqli_error($this->connect_id));
}
else
{
return array(@mysqli_connect_errno(), @mysqli_connect_error());
}
}
}#end of class
endif;

185
includes/pager.php Executable file
View File

@@ -0,0 +1,185 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
class Pagination
{
protected $totalPages, $startRow , $currentPage;
/**
* @param $rowsPerPage
* @param $numRows
* @param int $currentPage
*/
public function __construct($rowsPerPage, $numRows, $currentPage = 1)
{
// Calculate the total number of pages
$this->setTotalPages(ceil($numRows/$rowsPerPage));
// Check that a valid page has been provided
$this->currentPage = $currentPage < 1 ? 1 : ($currentPage > $this->totalPages ? $this->totalPages : $currentPage);
// Calculate the row to start the select with
$this->startRow = ($this->currentPage - 1) * $rowsPerPage;
}
/**
* Get the total pages
* @return float
*/
public function getTotalPages()
{
return $this->totalPages;
}
/**
* Set the total pages
* @param int $totalPages
* @return int
*/
public function setTotalPages($totalPages = 0)
{
return $this->totalPages = $totalPages;
}
/**
* @return int
*/
public function getCurrentPage()
{
return $this->currentPage;
}
/**
* @param int $currentPage
*/
public function setCurrentPage($currentPage)
{
$this->currentPage = $currentPage;
}
/**
* @return int
*/
public function getStartRow()
{
return $this->startRow;
}
/**
* @param int $startRow
*/
public function setStartRow($startRow)
{
$this->startRow = $startRow;
}
/**
* @param $link
* @param string $link_plus
* @return string
*/
public function print_nums($link, $link_plus = '')
{
global $lang, $config;
//if no page
if($this->totalPages <= 1)
{
return '';
}
$link_plus .= $link_plus != '' ? ' ' : '';
$re = '<nav aria-label="Page navigation example">';
$re = '<ul id="pagination" class="pagination">';
// Add a previous page link
if ($this->totalPages > 1 && $this->currentPage > 1)
{
$re .= '<li class="page-item">';
$re .= $config['mod_writer'] && !defined('IN_ADMIN')
? '<a class="paginate phover page-link" href="' . $link . '-' . ($this->currentPage-1) . '.html"' . $link_plus . '><span>' . $lang['PREV'] . '</span></a>'
: '<a class="paginate phover page-link" href="' . $link . '&amp;page=' . ($this->currentPage-1) . '"' . $link_plus . '><span>' . $lang['PREV'] . '</span></a>';
$re .= '</li>';
}
if ($this->currentPage > 3)
{
$re .= '<li class="page-item">';
$re .= $config['mod_writer'] && !defined('IN_ADMIN')
? '<a class="paginate page-link" href="' . $link . '-1.html"' . $link_plus . '><span>1</span></a>' . ($this->currentPage > 5 ? '<a class="paginate dots"><span>...</span></a>' : '')
: '<a class="paginate page-link" href="' . $link . '&amp;page=1"' . $link_plus . '><span>1</span></a>' . ($this->currentPage > 5 ? '<a class="paginate dots"><span>...</span></a>' : '');
$re .= '</li>';
}
for ($current = ($this->currentPage == 5) ? $this->currentPage - 3 : $this->currentPage - 2, $stop = ($this->currentPage + 4 == $this->totalPages) ? $this->currentPage + 4 : $this->currentPage + 3; $current < $stop; ++$current)
{
if ($current < 1 || $current > $this->totalPages)
{
continue;
}
else if ($current != $this->currentPage)
{
$re .= '<li class="page-item">';
$re .= $config['mod_writer'] && !defined('IN_ADMIN')
? '<a class="paginate page-link" href="' . $link . '-' . $current . '.html"' . $link_plus . '><span>' . $current . '</span></a>'
: '<a class="paginate page-link" href="' . $link . '&amp;page=' . $current . '"' . $link_plus . '><span>' . $current . '</span></a>';
$re .= '</li>';
}
else
{
$re .= '<li class="page-item">';
$re .= '<a class="paginate page-link current"><span>' . $current . '</span></a>';
$re .= '</li>';
}
}
if ($this->currentPage <= ($this->totalPages-3))
{
if ($this->currentPage != ($this->totalPages-3) && $this->currentPage != ($this->totalPages-4))
{
$re .= '<li class="page-item"><a class="paginate page-link dots"><span>...</span></a></li>';
}
$re .= '<li class="page-item">';
$re .= $config['mod_writer'] && !defined('IN_ADMIN')
? '<a class="paginate page-link" href="' . $link . '-' . $this->totalPages . '.html"' . $link_plus . '><span>' . $this->totalPages . '</span></a>'
: '<a class="paginate page-link" href="' . $link . '&amp;page=' . $this->totalPages . '"' . $link_plus . '><span>' . $this->totalPages . '</span></a>';
$re .= '</li>';
}
// Add a next page link
if ($this->totalPages > 1 && $this->currentPage < $this->totalPages)
{
$re .= '<li class="page-item">';
$re .= $config['mod_writer'] && !defined('IN_ADMIN')
? '<a class="paginate page-link phover" href="' . $link . '-' . ($this->currentPage+1) . '.html"' . $link_plus . '><span>' . $lang['NEXT'] . '</span></a>'
: '<a class="paginate phover page-link" href="' . $link . '&amp;page=' . ($this->currentPage+1) . '"' . $link_plus . '><span>' . $lang['NEXT'] . '</span></a>';
$re .= '</li>';
}
$re .= '</ul>';
$re .= '</nav>';
return $re;
}
}

265
includes/phpass.php Executable file
View File

@@ -0,0 +1,265 @@
<?php
#
# Portable PHP password hashing framework.
#
# Version 0.1 / genuine.
#
# Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
# the public domain.
#
# There's absolutely no warranty.
#
# The homepage URL for this framework is:
#
# http://www.openwall.com/phpass/
#
# Please be sure to update the Version line if you edit this file in any way.
# It is suggested that you leave the main version number intact, but indicate
# your project name (after the slash) and add your own revision information.
#
# Please do not change the "private" password hashing method implemented in
# here, thereby making your hashes incompatible. However, if you must, please
# change the hash type identifier (the "$P$") to something different.
#
# Obviously, since this code is in the public domain, the above are not
# requirements (there can be none), but merely suggestions.
#
# @version $Id: phpass.php 1551 2010-07-25 22:09:47Z saanina $
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
class PasswordHash
{
var $itoa64;
var $iteration_count_log2;
var $portable_hashes;
var $random_state;
function __construct($iteration_count_log2, $portable_hashes)
{
$this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
$iteration_count_log2 = 8;
$this->iteration_count_log2 = $iteration_count_log2;
$this->portable_hashes = $portable_hashes;
$this->random_state = microtime() . getmypid();
}
function get_random_bytes($count)
{
$output = '';
if (($fh = @fopen('/dev/urandom', 'rb')))
{
$output = fread($fh, $count);
fclose($fh);
}
if (strlen($output) < $count)
{
$output = '';
for ($i = 0; $i < $count; $i += 16)
{
$this->random_state = md5(microtime() . $this->random_state);
$output .= pack('H*', md5($this->random_state));
}
$output = substr($output, 0, $count);
}
return $output;
}
function encode64($input, $count)
{
$output = '';
$i = 0;
do
{
$value = ord($input[$i++]);
$output .= $this->itoa64[$value & 0x3f];
if ($i < $count)
$value |= ord($input[$i]) << 8;
$output .= $this->itoa64[($value >> 6) & 0x3f];
if ($i++ >= $count)
break;
if ($i < $count)
$value |= ord($input[$i]) << 16;
$output .= $this->itoa64[($value >> 12) & 0x3f];
if ($i++ >= $count)
break;
$output .= $this->itoa64[($value >> 18) & 0x3f];
}
while ($i < $count);
return $output;
}
function gensalt_private($input)
{
$output = '$P$';
$output .= $this->itoa64[min($this->iteration_count_log2 + ((PHP_VERSION >= '5') ? 5 : 3), 30)];
$output .= $this->encode64($input, 6);
return $output;
}
function crypt_private($password, $setting)
{
$output = '*0';
if (substr($setting, 0, 2) == $output)
$output = '*1';
if (substr($setting, 0, 3) != '$P$')
return $output;
$count_log2 = strpos($this->itoa64, $setting[3]);
if ($count_log2 < 7 || $count_log2 > 30)
return $output;
$count = 1 << $count_log2;
$salt = substr($setting, 4, 8);
if (strlen($salt) != 8)
return $output;
# We're kind of forced to use MD5 here since it's the only
# cryptographic primitive available in all versions of PHP
# currently in use. To implement our own low-level crypto
# in PHP would result in much worse performance and
# consequently in lower iteration counts and hashes that are
# quicker to crack (by non-PHP code).
if (PHP_VERSION >= '5')
{
$hash = md5($salt . $password, TRUE);
do {
$hash = md5($hash . $password, TRUE);
} while (--$count);
}
else
{
$hash = pack('H*', md5($salt . $password));
do
{
$hash = pack('H*', md5($hash . $password));
}
while (--$count);
}
$output = substr($setting, 0, 12);
$output .= $this->encode64($hash, 16);
return $output;
}
function gensalt_extended($input)
{
$count_log2 = min($this->iteration_count_log2 + 8, 24);
# This should be odd to not reveal weak DES keys, and the
# maximum valid value is (2**24 - 1) which is odd anyway.
$count = (1 << $count_log2) - 1;
$output = '_';
$output .= $this->itoa64[$count & 0x3f];
$output .= $this->itoa64[($count >> 6) & 0x3f];
$output .= $this->itoa64[($count >> 12) & 0x3f];
$output .= $this->itoa64[($count >> 18) & 0x3f];
$output .= $this->encode64($input, 3);
return $output;
}
function gensalt_blowfish($input)
{
# This one needs to use a different order of characters and a
# different encoding scheme from the one in encode64() above.
# We care because the last character in our encoded string will
# only represent 2 bits. While two known implementations of
# bcrypt will happily accept and correct a salt string which
# has the 4 unused bits set to non-zero, we do not want to take
# chances and we also do not want to waste an additional byte
# of entropy.
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '$2a$';
$output .= chr(ord('0') + $this->iteration_count_log2 / 10);
$output .= chr(ord('0') + $this->iteration_count_log2 % 10);
$output .= '$';
$i = 0;
do
{
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16)
{
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
}
while (1);
return $output;
}
function HashPassword($password)
{
$random = '';
if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes)
{
$random = $this->get_random_bytes(16);
$hash = crypt($password, $this->gensalt_blowfish($random));
if (strlen($hash) == 60)
return $hash;
}
if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) {
if (strlen($random) < 3)
$random = $this->get_random_bytes(3);
$hash = crypt($password, $this->gensalt_extended($random));
if (strlen($hash) == 20)
return $hash;
}
if (strlen($random) < 6)
$random = $this->get_random_bytes(6);
$hash =
$this->crypt_private($password,
$this->gensalt_private($random));
if (strlen($hash) == 34)
return $hash;
# Returning '*' on error is safe here, but would _not_ be safe
# in a crypt(3)-like function used _both_ for generating new
# hashes and for validating passwords against existing hashes.
return '*';
}
function CheckPassword($password, $stored_hash)
{
$hash = $this->crypt_private($password, $stored_hash);
if ($hash[0] == '*')
$hash = crypt($password, $stored_hash);
return $hash == $stored_hash;
}
}

248
includes/plugins.php Executable file
View File

@@ -0,0 +1,248 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license http://www.kleeja.com/license
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
# We are in the plugin system, plugins files won't work outside here
define('IN_PLUGINS_SYSTEM', true);
/**
* Kleeja Plugins System
* @package plugins
*/
class Plugins
{
/**
* List of loaded plugins
*/
private $plugins = array();
/**
* All hooks from all plugins listed in this variable
*/
private $all_plugins_hooks = array();
private $installed_plugins = array();
private $installed_plugins_info = array();
private $plugin_path = '';
private static $instance;
/**
* Initiating the class
*/
public function __construct()
{
global $SQL, $dbprefix;
#if plugins system is turned off, then stop right now!
if (defined('STOP_PLUGINS'))
{
return;
}
$this->plugin_path = PATH . KLEEJA_PLUGINS_FOLDER;
# Get installed plugins
$query = array(
'SELECT' => "plg_name, plg_ver",
'FROM' => "{$dbprefix}plugins",
'WHERE' => "plg_disabled = 0"
);
$result = $SQL->build($query);
while ($row = $SQL->fetch($result))
{
$this->installed_plugins[$row['plg_name']] = $row['plg_ver'];
}
$SQL->free($result);
$this->load_enabled_plugins();
}
/**
* Load the plugins from root/plugins folder
*/
private function load_enabled_plugins()
{
$dh = opendir($this->plugin_path);
while (false !== ($folder_name = readdir($dh)))
{
if (is_dir($this->plugin_path . '/' . $folder_name) && preg_match('/[a-z0-9_.]{3,}/', $folder_name))
{
if (!empty($this->installed_plugins[$folder_name]))
{
if ($this->fetch_plugin($folder_name))
{
array_push($this->plugins, $folder_name);
}
}
}
}
#sort the plugins from high to low priority
krsort($this->plugins);
}
/**
* Get the plugin information and other things
* @param string $plugin_name
* @return bool
*/
private function fetch_plugin($plugin_name)
{
#load the plugin
@include_once $this->plugin_path . '/' . $plugin_name . '/init.php';
if (empty($kleeja_plugin))
{
return false;
}
$priority = $kleeja_plugin[$plugin_name]['information']['plugin_priority'];
$this->installed_plugins_info[$plugin_name] = $kleeja_plugin[$plugin_name]['information'];
#bring the real priority of plugin and replace current one
$plugin_current_priority = array_search($plugin_name, $this->plugins);
unset($this->plugins[$plugin_current_priority]);
$this->plugins[$priority] = $plugin_name;
//update plugin if current loaded version is > than installed one
if ($this->installed_plugins[$plugin_name])
if (version_compare($this->installed_plugins[$plugin_name], $kleeja_plugin[$plugin_name]['information']['plugin_version'], '<'))
{
if (is_callable($kleeja_plugin[$plugin_name]['update']))
{
global $SQL, $dbprefix;
#update plugin
$kleeja_plugin[$plugin_name]['update']($this->installed_plugins[$plugin_name], $kleeja_plugin[$plugin_name]['information']['plugin_version']);
#update current plugin version
$update_query = array(
'UPDATE' => "{$dbprefix}plugins",
'SET' => "plg_ver='" . $SQL->escape($kleeja_plugin[$plugin_name]['information']['plugin_version']) . "'",
'WHERE' => "plg_name='" . $SQL->escape($plugin_name) . "'"
);
$SQL->build($update_query);
}
}
#add plugin hooks to global hooks, depend on its priority
if (!empty($kleeja_plugin[$plugin_name]['functions']))
{
foreach ($kleeja_plugin[$plugin_name]['functions'] as $hook_name => $hook_value)
{
if (empty($this->all_plugins_hooks[$hook_name][$priority]))
{
$this->all_plugins_hooks[$hook_name][$priority] = array();
}
array_push($this->all_plugins_hooks[$hook_name][$priority], $hook_value);
krsort($this->all_plugins_hooks[$hook_name]);
}
}
return true;
}
/**
* get an installed plugin information
* @param string $plugin_name
* @return mixed|null
*/
public function installed_plugin_info($plugin_name)
{
if (!empty($this->installed_plugins_info[$plugin_name]))
{
return $this->installed_plugins_info[$plugin_name];
}
return null;
}
/**
* Bring all codes of this hook
* This function scattered all over kleeja files
* @param string $hook_name
* @param array $args
* @return array|null
*/
public function run($hook_name, $args = array())
{
$return_value = $to_be_returned = array();
if (!empty($this->all_plugins_hooks[$hook_name]))
{
foreach ($this->all_plugins_hooks[$hook_name] as $order => $functions)
{
foreach ($functions as $function)
{
if (is_callable($function))
{
$return_value = $function($args);
if(is_array($return_value))
{
$args = array_merge($args, $return_value);
$to_be_returned = array_merge($to_be_returned, $return_value);
}
}
}
}
}
return sizeof($to_be_returned) ? $to_be_returned : null;
}
public static function getInstance()
{
if (is_null(self::$instance))
{
self::$instance = new self();
}
return self::$instance;
}
/**
* return debug info about plugins system
* @return array
*/
public function getDebugInfo(){
if(!defined('DEV_STAGE'))
{
return array();
}
return array(
'all_plugins_hooks' => $this->all_plugins_hooks,
'installed_plugins' => $this->installed_plugins,
);
}
}

372
includes/style.php Executable file
View File

@@ -0,0 +1,372 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
#no direct access
if (!defined('IN_COMMON'))
{
exit;
}
class kleeja_style
{
protected $vars; #Reference to $GLOBALS
protected $loop = array();
protected $reg = array('var' => '/([{]{1,2})+([A-Z0-9_\.]+)[}]{1,2}/i');
public $caching = true; #save templates as caches to not compiled a lot of times
/**
* Function to load a template file.
* @param $template_name
*/
protected function _load_template($template_name, $style_path = null)
{
global $config, $THIS_STYLE_PATH_ABS, $STYLE_PATH_ADMIN_ABS, $DEFAULT_PATH_ADMIN_ABS;
if (!($template_path = $this->template_exists($template_name, $style_path)))
{
big_error('No Template !', 'Requested "' . $template_path . '" template doesnt exists or an empty !! ');
}
$html = file_get_contents($template_path);
$html = $this->_parse($html, $template_name);
//use 'b' to force binary mode
if ($filename = @fopen(PATH . 'cache/tpl_' . $this->re_name_tpl($template_name, $style_path) . '.php', 'wb'))
{
is_array($plugin_run_result = Plugins::getInstance()->run('style_load_template_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
@flock($filename, LOCK_EX);
@fwrite($filename, $html);
@flock($filename, LOCK_UN);
@fclose($filename);
// Read and write for owner, read for everybody else
@chmod(PATH . 'cache/tpl_' . $this->re_name_tpl($template_name, $style_path) . '.php', 0644);
}
}
/**
* check if a template exists or not
* @param $template_name
* @param null $style_path
*/
public function template_exists($template_name, $style_path = null)
{
global $config, $STYLE_PATH_ADMIN_ABS, $THIS_STYLE_PATH_ABS, $DEFAULT_PATH_ADMIN_ABS;
$is_admin_template = false;
//admin template always begin with admin_
if (substr($template_name, 0, 6) == 'admin_')
{
$current_style_path = !empty($style_path) ? $style_path : $STYLE_PATH_ADMIN_ABS;
$is_admin_template = true;
}
else
{
$current_style_path = !empty($style_path) ? $style_path : $THIS_STYLE_PATH_ABS;
}
$template_path = rtrim($current_style_path, '/') . '/' . $template_name . '.html';
//if template not found and default style is there and not admin tpl
$is_tpl_exist = file_exists($template_path);
if (!$is_tpl_exist)
{
if (trim($config['style_depend_on']) != '')
{
$template_path_alternative = str_replace('/' . $config['style'] . '/', '/' . $config['style_depend_on'] . '/', $template_path);
if (file_exists($template_path_alternative))
{
$template_path = $template_path_alternative;
$is_tpl_exist = true;
}
}
else if ($is_admin_template)
{
$template_path = $DEFAULT_PATH_ADMIN_ABS . $template_name . '.html';
$is_tpl_exist = true;
}
else if ($config['style'] != 'default' && !$is_admin_template)
{
$template_path_alternative = str_replace('/' . $config['style'] . '/', '/default/', $template_path);
if (file_exists($template_path_alternative))
{
$template_path = $template_path_alternative;
$is_tpl_exist = true;
}
}
}
return $is_tpl_exist ? $template_path : false;
}
/**
* Function to parse the Template Tags
*/
protected function _parse($html, $template_name = '')
{
is_array($plugin_run_result = Plugins::getInstance()->run('style_parse_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$html = preg_replace(array('#<([\?%])=?.*?\1>#s', '#<script\s+language\s*=\s*(["\']?)php\1\s*>.*?</script\s*>#s', '#<\?php(?:\r\n?|[ \n\t]).*?\?>#s'), '', $html);
$html = preg_replace_callback('/\(([{A-Z0-9_\.}\s!=<>]+)\?(.*):(.*)\)/iU', array('kleeja_style', '_iif_callback'), $html);
$html = preg_replace_callback('/<(IF|ELSEIF|UNLESS) (.+)>/iU', array('kleeja_style', '_if_callback'), $html);
$html = preg_replace_callback('/<LOOP\s+NAME\s*=\s*(\"|)+([a-z0-9_\.]{1,})+(\"|)\s*>/i', array('kleeja_style', '_loop_callback'), $html);
$html = preg_replace_callback(kleeja_style::reg('var'), array('kleeja_style', '_vars_callback'), $html);
$rep = array
(
'/<\/(LOOP|IF|END|IS_BROWSER|UNLESS)>/i' => "<?php } ?>",
'/<INCLUDE(\s+NAME|)\s*=*\s*"(.+)"\s*>/iU' => '<?php echo $this->display("\\2"); ?>',
'/<IS_BROWSER\s*=\s*"([a-z0-9,]+)"\s*>/iU' => '<?php if(is_browser("\\1")){ ?>',
'/<IS_BROWSER\s*\!=\s*"([a-z0-9,]+)"\s*>/iU' => '<?php if(!is_browser("\\1")){ ?>',
'/(<ELSE>|<ELSE \/>)/i' => '<?php }else{ ?>',
'/<ODD\s*=\s*"([a-zA-Z0-9_\-\+\.\/]+)"\s*>(.*?)<\/ODD\>/is' => "<?php if(intval(\$value['\\1'])%2){?> \\2 <?php } ?>",
'/<EVEN\s*=\s*"([a-zA-Z0-9_\-\+\.\/]+)"\s*>(.*?)<\/EVEN>/is' => "<?php if(intval(\$value['\\1'])% 2 == 0){?> \\2 <?php } ?>",
'/<RAND\s*=\s*"(.*?)\"\s*,\s*"(.*?)"\s*>/is' => "<?php \$KLEEJA_tpl_rand_is=(!isset(\$KLEEJA_tpl_rand_is) || \$KLEEJA_tpl_rand_is==0)?1:0; print((\$KLEEJA_tpl_rand_is==1) ?'\\1':'\\2'); ?>",
'/\{%(key|value)%\}/i' => '<?php echo $\\1; ?>',
);
return preg_replace(array_keys($rep), array_values($rep), $html);
}
/**
* loop tag
* @param $matches
* @return string
*/
protected function _loop_callback($matches)
{
$var = strpos($matches[2], '.') !== false ? str_replace('.', '"]["', $matches[2]) : $matches[2];
return '<?php foreach($this->vars["' . $var . '"] as $key=>$value){ ?>';
}
/**
* if tag
* @param $matches
* @return string
*/
protected function _if_callback($matches)
{
$char = array(' eq ', ' lt ', ' gt ', ' lte ', ' gte ', ' neq ', '==', '!=', '>=', '<=', '<', '>');
$reps = array('==', '<', '>', '<=', '>=', '!=', '==', '!=', '>=', '<=', '<', '>');
$atts = call_user_func(array('kleeja_style', '_get_attributes'), $matches[0]);
$con = trim(!empty($atts['NAME']) ? $atts['NAME'] : (empty($atts['LOOP']) ? '' : $atts['LOOP']));
$con = str_replace('$this->vars', '[----this-vars----]', $con);
if (preg_match('/(.*)(' . implode('|', $char) . ')(.*)/i', $con, $arr))
{
$arr[1] = trim($arr[1]);
$var1 = $arr[1][0] != '$' ? call_user_func(array('kleeja_style', '_var_callback'), (!empty($atts['NAME']) ? '{' . $arr[1] . '}' : '{{' . $arr[1] . '}}')) : $arr[1];
$opr = str_replace($char, $reps, $arr[2]);
$var2 = trim($arr[3]);
#check for type
if ($var2[0] != '$' && !preg_match('/[0-9]/', $var2))
{
$var2 = '"' . str_replace('"', '\"', $var2) . '"';
}
$con = "$var1$opr$var2";
}
elseif ($con[0] !== '$' && strpos($con, '(') === false)
{
$con = call_user_func(array('kleeja_style', '_var_callback'), (!empty($atts['NAME']) ? '{' . $con . '}' : '{{' . $con . '}}'));
}
$con = str_replace( '[----this-vars----]', '$this->vars', $con);
return strtoupper($matches[1]) == 'IF'
? '<?php if(' . $con . '){ ?>'
: (strtoupper($matches[1]) == 'UNLESS' ? '<?php if(!(' . $con . ')){ ?>' : '<?php }elseif(' . $con . '){ ?>');
}
/**
* iif tag, if else /if
* @param $matches
* @return string
*/
protected function _iif_callback($matches)
{
return '<IF NAME="' . $matches[1] . '">' . $matches[2] . '<ELSE>' . $matches[3] . '</IF>';
}
/**
* make variable printable
* @param $matches
* @return string
*/
protected function _vars_callback($matches)
{
return '<?php echo ' . call_user_func(array('kleeja_style', '_var_callback'), $matches) . '?>';
}
/**
* variable replace
* @param $matches
* @return string
*/
protected function _var_callback($matches)
{
if (!is_array($matches))
{
preg_match(kleeja_style::reg('var'), $matches, $matches);
}
$var = !empty($matches[2]) ? str_replace('.', '\'][\'', $matches[2]) : '';
return (!empty($matches[1]) && trim($matches[1]) == '{{') ? '$value[\'' . $var . '\']' : '$this->vars[\'' . $var . '\']';
}
/**
* att variable replace
* @param $matches
* @return string
*/
protected function _var_callback_att($matches)
{
return trim($matches[1]) == '{' ? $this->_var_callback($matches) : '{' . $this->_var_callback($matches) . '}';
}
/**
* get reg var
* @param $var
* @return mixed
*/
protected function reg($var)
{
$vars = get_class_vars(__CLASS__);
return ($vars['reg'][$var]);
}
/**
* get tag attributes
* @param $tag
* @return array
*/
protected function _get_attributes($tag)
{
preg_match_all('/([a-z]+)="(.+)"/iU', $tag, $attribute);
$attributes = array();
for ($i = 0; $i < count($attribute[1]); $i++)
{
$att = strtoupper($attribute[1][$i]);
if (preg_match('/NAME|LOOP/', $att))
{
$attributes[$att] = preg_replace_callback(kleeja_style::reg('var'), array('kleeja_style', '_var_callback'), $attribute[2][$i]);
}
else
{
$attributes[$att] = preg_replace_callback(kleeja_style::reg('var'), array('kleeja_style', '_var_callback_att'), $attribute[2][$i]);
}
}
return $attributes;
}
/**
* Assign Variables
* @param $var
* @param $to
*/
public function assign($var, $to)
{
$GLOBALS[$var] = $to;
}
/**
* load parser and return page content
* @param $template_name
* @param null $style_path optional, good for plugins
* @return mixed|string
*/
public function display($template_name, $style_path = null)
{
global $config;
$this->vars = &$GLOBALS;
$k = '<div sty' . 'le="font-size:12px;di' . 'spl' . 'ay:bl' . 'oc' . 'k !im' . 'po' . 'rt' . 'ant;' . 'backgrou' . 'nd:#ECE' . 'CE' . 'C !im' . 'po' . 'rt' .
'ant;margin:5p' . 'x; padding:2px 3px; position:fi' . 'xed;bottom' . ':0;left:1%' . ';z-index:9' . '9999;text' . '-align:center;">P' .
'owe' . 'red b' . 'y <a style="di' . 'spl' . 'ay:in' . 'li' . 'ne !im' . 'po' . 'rt' . 'ant;' . 'color:#6' .
'66 !im' . 'po' . 'rt' . 'ant;" href="ht' . 'tps:' . '/' . '/ww' . 'w.' . 'kl' . 'ee' . 'ja' . '.c' . 'om/" onclic' . 'k="windo' . 'w.op' . 'en(this.h' .
'ref,' . '\'_b' . 'lank\');retur' . 'n false;" title' . '="K' . 'lee' . 'ja">K' . 'lee' . 'ja</a></div>' . "\n";
//is there ?
if (!file_exists(PATH . 'cache/tpl_' . $this->re_name_tpl($template_name, $style_path) . '.php') || !$this->caching)
{
$this->_load_template($template_name, $style_path);
}
ob_start();
include(PATH . 'cache/tpl_' . $this->re_name_tpl($template_name, $style_path) . '.php');
$page = ob_get_contents();
ob_end_clean();
if ($template_name == strip_tags('<!--it-->he<!--Is-->ad<!--Queen-->er'))
{
$v = @unserialize($config['new_version']);
if ((int)$v[strip_tags('co<!--it-->py<!--made-->ri<!--for-->gh<!--you-->ts<!--yub-->')] == /*kleeja is sweety*/
0/*SO, be sweety*/)
{
$t = strip_tags('<!--y-->b<!--o-->o<!--n-->d<!--b-->y');
$page = preg_replace('/<' . $t . '[^>]*>/', '<' . $t . ">\n" . $k, $page, -1, $c);
if (!$c)
{
$page .= $k;
}
}
}
return $page;
}
/**
* generate admin option block
* @param $html
* @return string
*/
public function admindisplayoption($html)
{
$this->vars = &$GLOBALS;
ob_start();
eval(' ?' . '>' . trim($this->_parse($html)) . '<' . '?php ');
$page = ob_get_contents();
ob_end_clean();
return $page;
}
/**
* change name of template to be valid
* @param $name
* @return mixed
*/
protected function re_name_tpl($name, $style_path = null)
{
return preg_replace("/[^a-z0-9-_]/", "-", strtolower($name)) .
(!empty($style_path) ? md5($style_path) : '');
}
}

160
includes/up_helpers/BMP.php Executable file
View File

@@ -0,0 +1,160 @@
<?php
// Read & Save 24bit BMP files
// Author: de77
// Licence: MIT
// Webpage: de77.com
// Version: 07.02.2010
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
class BMP
{
public static function imagebmp(&$img, $filename = false)
{
return imagebmp($img, $filename);
}
public static function imagecreatefrombmp($filename)
{
return imagecreatefrombmp($filename);
}
}
function imagebmp(&$img, $filename = false)
{
$wid = imagesx($img);
$hei = imagesy($img);
$wid_pad = str_pad('', $wid % 4, "\0");
$size = 54 + ($wid + $wid_pad) * $hei;
//prepare & save header
$header['identifier'] = 'BM';
$header['file_size'] = dword($size);
$header['reserved'] = dword(0);
$header['bitmap_data'] = dword(54);
$header['header_size'] = dword(40);
$header['width'] = dword($wid);
$header['height'] = dword($hei);
$header['planes'] = word(1);
$header['bits_per_pixel'] = word(24);
$header['compression'] = dword(0);
$header['data_size'] = dword(0);
$header['h_resolution'] = dword(0);
$header['v_resolution'] = dword(0);
$header['colors'] = dword(0);
$header['important_colors'] = dword(0);
if ($filename)
{
$f = fopen($filename, "wb");
foreach ($header AS $h)
{
fwrite($f, $h);
}
//save pixels
for ($y=$hei-1; $y>=0; $y--)
{
for ($x=0; $x<$wid; $x++)
{
$rgb = imagecolorat($img, $x, $y);
fwrite($f, byte3($rgb));
}
fwrite($f, $wid_pad);
}
fclose($f);
return true;
}
else
{
foreach ($header AS $h)
{
echo $h;
}
//save pixels
for ($y=$hei-1; $y>=0; $y--)
{
for ($x=0; $x<$wid; $x++)
{
$rgb = imagecolorat($img, $x, $y);
echo byte3($rgb);
}
echo $wid_pad;
}
return false;
}
}
function imagecreatefrombmp($filename)
{
$f = fopen($filename, "rb");
//read header
$header = fread($f, 54);
$header = unpack( 'c2identifier/Vfile_size/Vreserved/Vbitmap_data/Vheader_size/' .
'Vwidth/Vheight/vplanes/vbits_per_pixel/Vcompression/Vdata_size/'.
'Vh_resolution/Vv_resolution/Vcolors/Vimportant_colors', $header);
if ($header['identifier1'] != 66 or $header['identifier2'] != 77)
{
//die('Not a valid bmp file');
return false;
}
if ($header['bits_per_pixel'] != 24)
{
//die('Only 24bit BMP images are supported');
return false;
}
$wid2 = ceil((3*$header['width']) / 4) * 4;
$wid = $header['width'];
$hei = $header['height'];
$img = imagecreatetruecolor($header['width'], $header['height']);
//read pixels
for ($y=$hei-1; $y>=0; $y--)
{
$row = fread($f, $wid2);
$pixels = str_split($row, 3);
for ($x=0; $x<$wid; $x++)
{
imagesetpixel($img, $x, $y, dwordize($pixels[$x]));
}
}
fclose($f);
return $img;
}
function dwordize($str)
{
$a = ord($str[0]);
$b = ord($str[1]);
$c = ord($str[2]);
return $c*256*256 + $b*256 + $a;
}
function byte3($n)
{
return chr($n & 255) . chr(($n >> 8) & 255) . chr(($n >> 16) & 255);
}
function dword($n)
{
return pack("V", $n);
}
function word($n)
{
return pack("v", $n);
}

58
includes/up_helpers/index.html Executable file
View File

@@ -0,0 +1,58 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256"/>
<title>Powered by Kleeja</title>
<style type="text/css">* {
font-size: 100%;
margin: 0;
padding: 0;
color: #CECFCE;
}
body {
font-family: Tahoma, Arial, sans-serif;
font-size: 100%;
color: #69788E;
margin: 10px 30px;
background: #F7F7F7;
}
a:link, a:visited {
text-decoration: none;
color: #CECFCE;
}
a:active, a:hover {
text-decoration: underline;
color: #111;
}
h1 {
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-size: 1.70em;
font-weight: normal;
color: #333333;
margin-top: 0;
margin-bottom: 10px;
}
.content_box {
border: 1px dashed #CECFCE;
background: #FFFFFF;
padding: 10px;
margin-right: auto;
margin-left: auto;
}</style>
</head>
<body title="&#1603;&#1604;&#1610;&#1580;&#1575;"><br/>
<div class="content_box">
<p>
<a target="_blank" href="http://www.kleeja.com" title="kleeja"></a>
</p>
<br/>
<h1><span style="font-size:250%;color:#D80000;">403 - Access forbidden!</span></h1></div>
<br/>
<div class="content_box"style="font-size: 140%">Powered by Kleeja</div>
</body>
</html>

316
includes/up_helpers/others.php Executable file
View File

@@ -0,0 +1,316 @@
<?php
/**
*
* @package Kleeja_up_helpers
* @copyright (c) 2007-2012 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
/**
* checking the safety and validity of sub-extension of given file
*
*/
function ext_check_safe($filename)
{
#bad files extensions
$not_allowed = array('php', 'php3' ,'php5', 'php4', 'asp' ,'shtml' , 'html' ,'htm' ,'xhtml' ,'phtml', 'pl', 'cgi', 'htaccess', 'ini');
#let split the file name, suppose it filename.gif.php
$tmp = explode(".", $filename);
#if it's less than 3, that its means normal
if(sizeof($tmp) < 3)
{
return true;
}
$before_last_ext = $tmp[sizeof($tmp)-2];
#in the bad extenion, return false to tell him
if (in_array(strtolower($before_last_ext), $not_allowed))
{
return false;
}
else
{
return true;
}
}
/**
* create htaccess files for uploading folder
*/
function generate_safety_htaccess($folder)
{
$return = false;
is_array($plugin_run_result = Plugins::getInstance()->run('generate_safety_htaccess_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if($return)
{
return true;
}
#data for the htaccess
$htaccess_data = "<Files ~ \"^.*\.(php|php*|cgi|pl|phtml|shtml|sql|asp|aspx)\">\nOrder allow,deny\nDeny from all\n</Files>\n<IfModule mod_php4.c>\nphp_flag engine off\n</IfModule>\n<IfModule mod_php5.c>\nphp_flag engine off\n</IfModule>\nRemoveType .php .php* .phtml .pl .cgi .asp .aspx .sql";
#generate the htaccess
$fi = @fopen($folder . "/.htaccess", "w");
$fi2 = @fopen($folder . "/thumbs/.htaccess","w");
@fwrite($fi, $htaccess_data);
@fwrite($fi2, $htaccess_data);
}
/**
* create an uploading folder
* @param string $folder
* @return bool
*/
function make_folder($folder)
{
$return = false;
is_array($plugin_run_result = Plugins::getInstance()->run('make_folder_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if($return)
{
return true;
}
$folders = explode('/', $folder);
$path = '';
foreach ($folders as $sub_folder)
{
#try to make a new upload folder
@mkdir($path . $sub_folder);
@mkdir($path . $sub_folder . '/thumbs');
#then try to chmod it to 0755
@chmod($path . $sub_folder, 0755);
@chmod($path . $sub_folder . '/thumbs/', 0755);
#make it safe
generate_safety_htaccess($path . $sub_folder);
#create empty index so nobody can see the contents
$fo = @fopen($path . $sub_folder . "/index.html", "w");
$fo2 = @fopen($path . $sub_folder . "/thumbs/index.html", "w");
@fwrite($fo, '<a href="http://kleeja.com"><p>KLEEJA ..</p></a>');
@fwrite($fo2, '<a href="http://kleeja.com"><p>KLEEJA ..</p></a>');
$path .= $sub_folder . '/';
}
return file_exists($folder);
}
/**
* Change the file name depend on given decoding type
*/
function change_filename_decoding($filename, $i_loop, $ext, $decoding_type = '')
{
global $config;
$return = '';
$decoding_type = empty($decoding_type) ? $config['decode'] : $decoding_type;
#change it, time..
if($decoding_type == "time" || $decoding_type == 1)
{
list($usec, $sec) = explode(" ", microtime());
$extra = str_replace('.', '', (float)$usec + (float)$sec);
$return = $extra . $i_loop . '.' . $ext;
}
# md5
elseif($decoding_type == "md5" || $decoding_type == 2)
{
list($usec, $sec) = explode(" ", microtime());
$extra = md5(((float)$usec + (float)$sec) . $filename);
$extra = substr($extra, 0, 12);
$return = $extra . $i_loop . "." . $ext;
}
# exists before, change it a little
elseif($decoding_type == 'exists')
{
$return = substr($filename, 0, -(strlen($ext)+1)) . '_' . substr(md5( microtime(true) . $i_loop), rand(0, 20), 5) . '.' . $ext;
}
#nothing
else
{
$filename = substr($filename, 0, -(strlen($ext)+1));
$return = preg_replace('/[,.?\/*&^\\\$%#@()_!|"\~\'><=+}{; ]/', '-', $filename) . '.' . $ext;
$return = preg_replace('/-+/', '-', $return);
}
is_array($plugin_run_result = Plugins::getInstance()->run('change_filename_decoding_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $return;
}
/**
* Change the file name depend on used templates {rand:..} {date:..}
*/
function change_filename_templates($filename)
{
#random number...
if (preg_match("/{rand:([0-9]+)}/i", $filename, $m))
{
$filename = preg_replace("/{rand:([0-9]+)}/i", substr(md5(time()), 0, $m[1]), $filename);
}
#current date
if (preg_match("/{date:([a-zA-Z-_]+)}/i", $filename, $m))
{
$filename = preg_replace("/{date:([a-zA-Z-_]+)}/i", date($m[1]), $filename);
}
is_array($plugin_run_result = Plugins::getInstance()->run('change_filename_templates_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return $filename;
}
/**
* check mime type of uploaded file
* @return bool
*/
function check_mime_type($given_file_mime, $file_ext, $file_path)
{
$return = '';
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_check_mime_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if($return !== '')
{
return $return;
}
$mime = '';
if(function_exists('finfo_open') || function_exists('mime_content_type'))
{
if (function_exists('mime_content_type'))
{
$mime = @mime_content_type($file_path);
}
else
{
$f_info = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($f_info, $file_path);
finfo_close($f_info);
}
}
else if(!empty($given_file_mime))
{
$mime = $given_file_mime;
}
if(!empty($mime))
{
$supposed_mime = explode("/", get_mime_for_header($file_ext), 2);
if (is_array($supposed_mime))
{
foreach ($supposed_mime as $s_mime)
{
if (strpos($mime, $s_mime) !== false)
{
return true;
}
}
return false;
}
}
//if normal checks failed!
if(@kleeja_filesize($file_path) > 6*(1000*1024))
{
return true;
}
//check for bad things inside files ...
//<.? i cant add it here cuz alot of files contain it
$maybe_bad_codes_are = array('<' . 'script', 'zend', 'base64_decode', '<' . '?'. 'php', '<' . '?' . '=');
if(!($data = @file_get_contents($file_path)))
{
return true;
}
foreach($maybe_bad_codes_are as $i)
{
if(strpos(strtolower($data), $i) !== false)
{
return false;
}
}
return true;
}
/**
* to prevent flooding at uploading
*/
function user_is_flooding($user_id = '-1')
{
global $SQL, $dbprefix, $config;
$return = 'empty';
is_array($plugin_run_result = Plugins::getInstance()->run('user_is_flooding_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run
if($return != 'empty')
{
return $return;
}
//if the value is zero (means that the function is disabled) then return false immediately
if(($user_id == '-1' && $config['guestsectoupload'] == 0) || $user_id != '-1' && $config['usersectoupload'] == 0)
{
return false;
}
//In my point of view I see 30 seconds is not bad rate to stop flooding ..
//even though this minimum rate sometime isn't enough to protect Kleeja from flooding attacks
$time = time() - ($user_id == '-1' ? $config['guestsectoupload'] : $config['usersectoupload']);
$query = array(
'SELECT' => 'f.time',
'FROM' => "{$dbprefix}files f",
'WHERE' => 'f.time >= ' . $time . ' AND f.user_ip = \'' . $SQL->escape(get_ip()) . '\'',
);
if ($SQL->num_rows($SQL->build($query)))
{
return true;
}
return false;
}

View File

@@ -0,0 +1,66 @@
<?php
/**
*
* @package Kleeja_up_helpers
* @copyright (c) 2007-2012 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
#
# This helper is used to help in remote uploading
#
/**
* bring the file size from remote file; aka url
*/
function get_remote_file_size($url, $method = "GET", $data = "", $redirect = 10)
{
$url = parse_url($url);
$fp = @fsockopen ($url['host'], (!empty($url['port']) ? (int)$url['port'] : 80), $errno, $errstr, 30);
if ($fp)
{
$path = (!empty($url['path']) ? $url['path'] : "/").(!empty($url['query']) ? "?" . $url['query'] : "");
$header = "\r\nHost: ".$url['host'];
if("post" == strtolower($method))
{
$header .= "\r\nContent-Length: " . strlen($data);
}
fputs ($fp, $method." ".$path." HTTP/1.0" . $header . "\r\n\r\n". ("post" == strtolower($method) ? $data : ""));
if(!feof($fp))
{
$scheme = fgets($fp);
list(, $code ) = explode(" ", $scheme);
$headers = array("Scheme" => $scheme);
}
while (!feof($fp))
{
$h = fgets($fp);
if($h == "\r\n" OR $h == "\n") break;
list($key, $value) = explode(":", $h, 2);
$headers[$key] = trim($value);
if($code >= 300 AND $code < 400 AND strtolower($key) == "location" AND $redirect > 0)
{
return get_remote_file_size($headers[$key], $method, $data, --$redirect);
}
}
$body = "";
/*while ( !feof($fp) ) $body .= fgets($fp);*/
fclose($fp);
}
else
{
return (array("error" => array("errno" => $errno, "errstr" => $errstr)));
}
return (string) $headers["Content-Length"];
}

258
includes/up_helpers/thumbs.php Executable file
View File

@@ -0,0 +1,258 @@
<?php
/**
*
* @package Kleeja_up_helpers
* @copyright (c) 2007-2012 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
/**
* Creates a a thumbnail of an image
* @example helper_thumb('pics/apple.jpg','thumbs/tn_apple.jpg',100,100);
* @param string $source_path
* @param string $ext
* @param string $dest_image
* @param int $dw
* @param int $dh
* @return bool|null
*/
function helper_thumb($source_path, $ext, $dest_image, $dw, $dh)
{
#no file, quit it
if(!file_exists($source_path))
{
return null;
}
#check width, height
if(intval($dw) == 0 || intval($dw) < 10)
{
$dw = 100;
}
if(intval($dh) == 0 || intval($dh) < 10)
{
$dh = $dw;
}
#if there is imagick lib, then we should use it
if(function_exists('phpversion') && phpversion('imagick'))
{
helper_thumb_imagick($source_path, $ext, $dest_image, $dw, $dh);
return null;
}
//get file info
list($source_width, $source_height, $source_type) = array(false, false, false);
if(function_exists('getimagesize'))
{
list($source_width, $source_height, $source_type) = getimagesize($source_path);
}
if(!function_exists('imagecreatefromjpeg'))
{
return null;
}
$source_gdim = null;
$ext = strtolower(trim($ext));
if(empty($ext))
{
$ext = strtolower(preg_replace('/^.*\./', '', $source_path));
}
switch($ext)
{
case 'gif':
$source_gdim = imagecreatefromgif( $source_path );
break;
case 'jpg':
case 'jpeg':
$source_gdim = imagecreatefromjpeg( $source_path );
break;
case 'png':
$source_gdim = imagecreatefrompng( $source_path );
break;
case 'bmp':
if(!defined('BMP_CLASS_INCLUDED'))
{
include dirname(__file__) . '/BMP.php';
define('BMP_CLASS_INCLUDED', true);
}
$source_gdim = imagecreatefrombmp( $source_path );
break;
}
$source_width = !$source_width ? ImageSX($source_gdim) : $source_width;
$source_height = !$source_height ? ImageSY($source_gdim) : $source_height;
$source_aspect_ratio = $source_width / $source_height;
$desired_aspect_ratio = $dw / $dh;
if ($source_aspect_ratio > $desired_aspect_ratio)
{
// Triggered when source image is wider
$temp_height = $dh;
$temp_width = (int) ($dh * $source_aspect_ratio);
}
else
{
// Triggered otherwise (i.e. source image is similar or taller)
$temp_width = $dw;
$temp_height = (int) ($dw / $source_aspect_ratio);
}
// Resize the image into a temporary GD image
$temp_gdim = imagecreatetruecolor( $temp_width, $temp_height );
imagecopyresampled(
$temp_gdim,
$source_gdim,
0, 0,
0, 0,
$temp_width, $temp_height,
$source_width, $source_height
);
// Copy cropped region from temporary image into the desired GD image
$x0 = ($temp_width - $dw) / 2;
$y0 = ($temp_height - $dh) / 2;
$desired_gdim = imagecreatetruecolor($dw, $dh);
imagecopy(
$desired_gdim,
$temp_gdim,
0, 0,
$x0, $y0,
$dw, $dh
);
// Create thumbnail
switch(strtolower(preg_replace('/^.*\./', '', $dest_image)))
{
case 'jpg':
case 'jpeg':
$return = @imagejpeg($desired_gdim, $dest_image, 90);
break;
case 'png':
$return = @imagepng($desired_gdim, $dest_image);
break;
case 'gif':
$return = @imagegif($desired_gdim, $dest_image);
break;
case 'bmp':
$return = @imagebmp($desired_gdim, $dest_image);
break;
default:
// Unsupported format
$return = false;
break;
}
@imagedestroy($desired_gdim);
@imagedestroy($source_gdim);
return $return;
}
/**
* generating thumb from image using Imagick
*
*/
function scale_image_imagick($x, $y, $cx, $cy)
{
//Set the default NEW values to be the old, in case it doesn't even need scaling
list($nx, $ny) = array($x, $y);
//If image is generally smaller, don't even bother
if ($x >= $cx || $y >= $cx)
{
$rx = $ry = 0;
//Work out ratios
if ($x > 0)
{
$rx = $cx / $x;
}
if ($y > 0)
{
$ry = $cy / $y;
}
//Use the lowest ratio, to ensure we don't go over the wanted image size
if ($rx > $ry)
{
$r = $ry;
}
else
{
$r = $rx;
}
//Calculate the new size based on the chosen ratio
$nx = intval($x * $r);
$ny = intval($y * $r);
}
//Return the results
return array($nx, $ny);
}
function helper_thumb_imagick($name, $ext, $filename, $new_w, $new_h)
{
#intiating the Imagick lib
$im = new Imagick($name);
#guess the right thumb height, weights
list($thumb_w, $thumb_h) = scale_image_imagick(
$im->getImageWidth(),
$im->getImageHeight(),
$new_w,
$new_h);
#an exception for gif image
#generating thumb with 10 frames only, big gif is a devil
if($ext == 'gif')
{
$i = 0;
//$gif_new = new Imagick();
foreach ($im as $frame)
{
$frame->thumbnailImage($thumb_w, $thumb_h);
$frame->setImagePage($thumb_w, $thumb_h, 0, 0);
// $gif_new->addImage($frame->getImage());
if($i >= 10)
{
# more than 10 frames, quit it
break;
}
$i++;
}
$im->writeImages($filename, true);
return;
}
#and other image extension use one way
$im->thumbnailImage($thumb_w, $thumb_h);
#right it
$im->writeImages($filename, false);
return;
}

191
includes/up_helpers/watermark.php Executable file
View File

@@ -0,0 +1,191 @@
<?php
/**
*
* @package Kleeja_up_helpers
* @copyright (c) 2007-2012 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
/**
* This helper is used to make a watermark on a given image,
* return nothing because if it work then ok , and if not then ok too :)
* @todo text support
*
* @param $name
* @param $ext
* @return bool|void
*/
function helper_watermark($name, $ext)
{
is_array($plugin_run_result = Plugins::getInstance()->run('helper_watermark_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#is this file really exsits ?
if(!file_exists($name))
{
return;
}
$src_logo = $logo_path = false;
if(file_exists(dirname(__FILE__) . '/../../images/watermark.png'))
{
$logo_path= dirname(__FILE__) . '/../../images/watermark.png';
$src_logo = imagecreatefrompng($logo_path);
}
elseif(file_exists(dirname(__FILE__) . '/../../images/watermark.gif'))
{
$logo_path= dirname(__FILE__) . '/../../images/watermark.gif';
$src_logo = imagecreatefromgif($logo_path);
}
#no watermark pic
if(!$src_logo)
{
return;
}
#if there is imagick lib, then we should use it
if(function_exists('phpversion') && phpversion('imagick'))
{
helper_watermark_imagick($name, $ext, $logo_path);
return;
}
#now, lets work and detect our image extension
if (strpos($ext, 'jp') !== false)
{
$src_img = @imagecreatefromjpeg($name);
}
elseif (strpos($ext, 'png') !== false)
{
$src_img = @imagecreatefrompng($name);
}
elseif (strpos($ext, 'gif') !== false)
{
return;
// $src_img = @imagecreatefromgif($name);
}
elseif(strpos($ext, 'bmp') !== false)
{
if(!defined('BMP_CLASS_INCLUDED'))
{
include dirname(__file__) . '/BMP.php';
define('BMP_CLASS_INCLUDED', true);
}
$src_img = imagecreatefrombmp($name);
}
else
{
return;
}
#detect width, height for the image
$bwidth = @imageSX($src_img);
$bheight = @imageSY($src_img);
#detect width, height for the watermark image
$lwidth = @imageSX($src_logo);
$lheight = @imageSY($src_logo);
if ($bwidth > $lwidth+5 && $bheight > $lheight+5)
{
#where exaxtly do we have to make the watermark ..
$src_x = $bwidth - ($lwidth + 5);
$src_y = $bheight - ($lheight + 5);
#make it now, watermark it
@ImageAlphaBlending($src_img, true);
@ImageCopy($src_img, $src_logo, $src_x, $src_y, 0, 0, $lwidth, $lheight);
if (strpos($ext, 'jp') !== false)
{
#no compression, same quality
@imagejpeg($src_img, $name, 100);
}
elseif (strpos($ext, 'png') !== false)
{
#no compression, same quality
@imagepng($src_img, $name, 0);
}
elseif (strpos($ext, 'gif') !== false)
{
@imagegif($src_img, $name);
}
elseif (strpos($ext, 'bmp') !== false)
{
@imagebmp($src_img, $name);
}
}
else
{
#image is not big enough to watermark it
return;
}
}
#
# generate watermarked images by imagick
#
function helper_watermark_imagick($name, $ext, $logo)
{
#Not just me babe, All the places misses you ..
$im = new Imagick($name);
$watermark = new Imagick($logo);
//$watermark->readImage($);
#how big are the images?
$iWidth = $im->getImageWidth();
$iHeight= $im->getImageHeight();
$wWidth = $watermark->getImageWidth();
$wHeight= $watermark->getImageHeight();
if ($iHeight < $wHeight || $iWidth < $wWidth)
{
#resize the watermark
$watermark->scaleImage($iWidth, $iHeight);
#get new size
$wWidth = $watermark->getImageWidth();
$wHeight = $watermark->getImageHeight();
}
#calculate the position
$x = $iWidth - ($wWidth - 5);
$y = $iHeight - ($wHeight - 5);
#an exception for gif image
#generating thumb with 10 frames only, big gif is a devil
if($ext == 'gif')
{
$i = 0;
//$gif_new = new Imagick();
foreach ($im as $frame)
{
$frame->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y);
// $gif_new->addImage($frame->getImage());
if($i >= 10)
{
# more than 10 frames, quit it
break;
}
$i++;
}
$im->writeImages($name, true);
return;
}
$im->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y);
$im->writeImages($name, false);
}

View File

@@ -0,0 +1,812 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
#includes important functions
include_once dirname(__file__) . '/../up_helpers/others.php';
include_once dirname(__file__) . '/../up_helpers/thumbs.php';
include_once dirname(__file__) . '/../up_helpers/watermark.php';
include_once dirname(__file__) . '/../up_helpers/remote_uploading.php';
/*
* uploading class, the most important class in Kleeja
* Where files uploaded by this class, depend on Kleeja settings
*/
class defaultUploader implements KleejaUploader
{
protected $messages = array();
protected $allowed_file_extensions = array();
protected $upload_fields_limit = 0;
protected $total_uploaded_files = 0;
/**
* set the allowed extensions of uploaded files
* @param array $allowed_file_extensions an array of allowed extensions ['gif', 'png' ..]
*/
function setAllowedFileExtensions($allowed_file_extensions)
{
$this->allowed_file_extensions = $allowed_file_extensions;
}
/**
* get the allowed extensions of uploaded files
* @return array
*/
function getAllowedFileExtensions()
{
return $this->allowed_file_extensions;
}
/**
* set the allowed limit of the uploaded files
* @param int $limit
*/
function setUploadFieldsLimit($limit)
{
$this->upload_fields_limit = $limit;
}
/**
* get the allowed limit of the uploaded files
* @return int
*/
function getUploadFieldsLimit()
{
return $this->upload_fields_limit;
}
/**
* add an information message to output it to the user
* @param string $message
* @return void
*/
function addInfoMessage($message)
{
array_push($this->messages, array($message, 'info'));
}
/**
* add an error message to output it to the user
* @param string $message
* @return void
*/
function addErrorMessage($message)
{
array_push($this->messages, array($message, 'error'));
}
/**
* get all the messages
* @return array
*/
function getMessages()
{
return $this->messages;
}
/**
* save the file information to the database
* @param array $fileInfo
* @return void
*/
function saveToDatabase($fileInfo)
{
global $SQL, $dbprefix, $config;
// $fileInfo =
// [
// 'saveToFolder'
// 'originalFileName'
// 'generatedFileName'
// 'fileSize'
// 'currentUserId'
// 'fileExtension
// ];
// + to be added in this method and goes to generateOutputBox
// [
// 'DeleteCode'
// 'insertId'
// [
#sometime cant see file after uploading.. but ..
@chmod($fileInfo['saveToFolder'] . '/' . $fileInfo['generatedFileName'], 0644);
$fileInfo['DeleteCode'] = sha1($fileInfo['generatedFileName'] . uniqid());
$queryValues = array
(
'name' => $fileInfo['generatedFileName'],
'real_filename' => $fileInfo['originalFileName'],
'size' => intval($fileInfo['fileSize']),
'time' => time(),
'folder'=> $fileInfo['saveToFolder'],
'type' => $fileInfo['fileExtension'],
'user' => $fileInfo['currentUserId'],
'code_del' => $fileInfo['DeleteCode'],
'user_ip' => get_ip(),
'id_form' => $config['id_form'],
);
$is_img = in_array($fileInfo['fileExtension'], array('png','gif','jpg','jpeg', 'bmp')) ? true : false;
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_saveToDatabase_qr', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
# insertion query
$insert_query = array(
'INSERT' => '`' . implode('` , `' , array_keys($queryValues)) . '`',
'INTO' => "{$dbprefix}files",
'VALUES' => "'" . implode("', '", array_map(array($SQL, 'escape'), array_values($queryValues))) . "'"
);
# do the query
$SQL->build($insert_query);
# inset id so it can be used in url like in do.php?id={id_for_url}
$fileInfo['insertId'] = $SQL->insert_id();
# update Kleeja stats
$update_query = array(
'UPDATE' => "{$dbprefix}stats",
'SET' => ($is_img ? "imgs=imgs+1" : "files=files+1") . ",sizes=sizes+" . intval($fileInfo['fileSize']) . ""
);
$SQL->build($update_query);
$this->generateOutputBox($fileInfo);
}
/**
* generate a box of the result and add it to addInfoMessage
* @param array $fileInfo
* @return void
*/
function generateOutputBox($fileInfo)
{
global $config, $lang;
// $fileInfo =
// [
// 'saveToFolder'
// 'originalFileName'
// 'generatedFileName'
// 'fileSize'
// 'currentUserId'
// 'fileExtension
// 'DeleteCode'
// 'insertId'
// [
$is_img = in_array($fileInfo['fileExtension'], array('png','gif','jpg','jpeg', 'bmp')) ? true : false;
# information of file, used for generating a url boxes
$file_info = array(
'::ID::' => $fileInfo['insertId'],
'::NAME::' => $fileInfo['generatedFileName'],
'::DIR::' => $fileInfo['saveToFolder'],
'::FNAME::' => $fileInfo['originalFileName'],
);
# show del code link box
$extra_del = '';
if ($config['del_url_file'])
{
$extra_del = get_up_tpl_box('del_file_code',
array(
'b_title' => $lang['URL_F_DEL'],
'b_code_link' => kleeja_get_link('del', array('::CODE::'=>$fileInfo['DeleteCode']))
)
);
}
//show imgs
if($is_img)
{
$img_html_result = '';
# get default thumb dimensions
$thmb_dim_w = $thmb_dim_h = 150;
if(strpos($config['thmb_dims'], '*') !== false)
{
list($thmb_dim_w, $thmb_dim_h) = array_map('trim', explode('*', $config['thmb_dims']));
}
# generate a thumbnail
helper_thumb(
$fileInfo['saveToFolder'] . '/' . $fileInfo['generatedFileName'],
$fileInfo['fileExtension'],
$fileInfo['saveToFolder'] . '/thumbs/' . $fileInfo['generatedFileName'],
$thmb_dim_w,
$thmb_dim_h
);
$img_html_result .= get_up_tpl_box('image_thumb',
array(
'b_title' => $lang['URL_F_THMB'],
'b_url_link'=> kleeja_get_link('image', $file_info),
'b_img_link'=> kleeja_get_link('thumb', $file_info)
)
);
# watermark on image
if($config['write_imgs'] != 0 && in_array($fileInfo['fileExtension'], array('gif', 'png', 'jpg', 'jpeg', 'bmp')))
{
helper_watermark($fileInfo['saveToFolder'] . "/" . $fileInfo['generatedFileName'], $fileInfo['fileExtension']);
}
#then show, image box
$img_html_result .= get_up_tpl_box('image',
array(
'b_title' => $lang['URL_F_IMG'],
'b_bbc_title'=> $lang['URL_F_BBC'],
'b_url_link'=> kleeja_get_link('image', $file_info),
)
);
#add del link box to the result if there is any
$img_html_result .= $extra_del;
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_generateOutputBox_image_result', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#show success message
$this->addInfoMessage(
'<div class="up-box-title">'. $lang['IMG_DOWNLAODED'] . ': ' .
htmlspecialchars($fileInfo['originalFileName']) . '</div>' . "\n" .
$img_html_result
);
}
else
{
#then show other files
$else_html_result = get_up_tpl_box('file',
array(
'b_title' => $lang['URL_F_FILE'],
'b_bbc_title'=> $lang['URL_F_BBC'],
'b_url_link'=> kleeja_get_link('file', $file_info),
)
);
#add del link box to the result if there is any
$else_html_result .= $extra_del;
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_generateOutputBox_file_result', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#show success message
$this->addInfoMessage(
'<div class="up-box-title">'. $lang['FILE_DOWNLAODED']. ': '
. htmlspecialchars($fileInfo['originalFileName']) . '</div>' . "\n" .
$else_html_result
);
}
$this->total_uploaded_files++;
}
/**
* here happens the magic, call this on upload submit
* @param int $uploadType upload from files input or links
*/
function upload($uploadType)
{
global $usrcp, $config, $lang;
# when $uploadType = 1, then we upload from _file input
# if $uploadType = 2, then we uploading from url which is disabled by default and is buggy
#upload to this folder
$current_uploading_folder = $config['foldername'];
#current user id
$current_user_id = $usrcp->name() ? $usrcp->id() : '-1';
#is captcha is on?
$captcha_enabled = intval($config['safe_code']);
$return_now = false;
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_upload_1st', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
# check folder our real folder
if(!file_exists($current_uploading_folder))
{
if(!make_folder($current_uploading_folder))
{
$this->addErrorMessage($lang['CANT_DIR_CRT']);
}
}
if($return_now)
{
return;
}
#no uploading yet, or just go to index.php, so we have make a new session
if(!$uploadType)
{
unset($_SESSION['FIILES_NOT_DUPLI'], $_SESSION['FIILES_NOT_DUPLI_LINKS']);
}
# is captcha on, and there is uploading going on
if($captcha_enabled && $uploadType)
{
#captcha is wrong
if(!kleeja_check_captcha())
{
$this->addErrorMessage($lang['WRONG_VERTY_CODE']);
return;
}
}
# to prevent flooding, user must wait, waiting-time is grapped from Kleeja settings, admin is exceptional
if(! user_can('enter_acp') && user_is_flooding($current_user_id))
{
$this->addErrorMessage(sprintf($lang['YOU_HAVE_TO_WAIT'],
$current_user_id == '-1' ? $config['guestsectoupload'] : $config['usersectoupload']));
return;
}
#detect flooding, TODO fix it or remove it
if ($uploadType == 1 && isset($_SESSION['FIILES_NOT_DUPLI']))
{
if(!empty($_SESSION['FIILES_NOT_DUPLI']) && $_SESSION['FIILES_NOT_DUPLI'] == sha1(serialize(array_column($_FILES, 'name'))))
{
unset($_SESSION['FIILES_NOT_DUPLI']);
// if(!ip('ajax'))
// {
// redirect('./');
// }
$this->addErrorMessage($lang['U_R_FLOODER']);
return;
}
}
if ($uploadType == 2 && isset($_SESSION['FIILES_NOT_DUPLI_LINKS']))
{
if($_SESSION['FIILES_NOT_DUPLI_LINKS'] == sha1(serialize($_POST)))
{
unset($_SESSION['FIILES_NOT_DUPLI_LINKS']);
if(!ip('ajax'))
{
redirect('./');
}
$this->addErrorMessage($lang['U_R_FLOODER']);
return;
}
}
# flooding code, making sure every ok session is cleared
if ($uploadType == 1 && sizeof($_FILES) > 0)
{
$_SESSION['FIILES_NOT_DUPLI'] = sha1(serialize(array_column($_FILES, 'name')));
}
elseif($uploadType == 2)
{
$_SESSION['FIILES_NOT_DUPLI_LINKS'] = sha1(serialize($_POST));
}
#now close session to let user open any other page in Kleeja
session_write_close();
# do upload
switch($uploadType)
{
#uploading from a _files input
default:
case 1:
if(!empty($_FILES['file']['tmp_name']))
{
$_FILES['file'][0] = $_FILES['file'];
}
# loop the uploaded files
for($i=0; $i<=$this->getUploadFieldsLimit(); $i++)
{
//no file!
if(empty($_FILES['file_' . $i . '_']['tmp_name']) && empty($_FILES['file'][$i]['tmp_name']))
{
if(is_null($_FILES['file_' . $i . '_']) && is_null($_FILES['file'][$i]))
{
continue;
}
$error = isset($_FILES['file_' . $i . '_'])
? $_FILES['file_' . $i . '_']['error']
: (isset($_FILES['file'][$i]) ? $_FILES['file'][$i]['error'] : -1);
$filename = isset($_FILES['file'][$i]['name'])
? $_FILES['file'][$i]['name']
: (isset($_FILES['file_' . $i . '_']['name']) ? $_FILES['file_' . $i . '_']['name'] : '....');
$upload_max_size = ini_get('upload_max_filesize');
if ($error !== UPLOAD_ERR_OK)
{
switch ($error)
{
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$this->addErrorMessage(sprintf(
$lang['SIZE_F_BIG'],
htmlspecialchars($filename),
'php.ini/upload_max_filesize: ' . $upload_max_size)
);
break;
case UPLOAD_ERR_PARTIAL:
// $message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
// $message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$this->addErrorMessage('Missing a temporary folder');
break;
case UPLOAD_ERR_CANT_WRITE:
$this->addErrorMessage('Failed to write file to disk');
break;
case UPLOAD_ERR_EXTENSION:
$this->addErrorMessage('File upload stopped by extension');
break;
default:
$this->addErrorMessage(sprintf($lang['CANT_UPLAOD'], htmlspecialchars($filename)));
break;
}
}
continue;
}
$this->uploadTypeFile($i, $current_uploading_folder, $current_user_id);
}
break;
#uploading from a url text-input
case 2:
#if not enabled, quit it
if($config['www_url'] != 1)
{
break;
}
#loop text inputs
for($i=0; $i<=$this->getUploadFieldsLimit(); $i++)
{
$this->uploadTypeUrl($i, $current_uploading_folder, $current_user_id);
}
break;
}
# well, no file uploaded, ask user to choose a file before submit
if($this->total_uploaded_files == 0 && sizeof($this->messages) == 0)
{
$this->addErrorMessage($lang['CHOSE_F']);
}
}
/**
* upload a file from $_FILES
* @param integer $fieldNumber as in file[i]
* @param $current_uploading_folder
* @param $current_user_id
*/
function uploadTypeFile($fieldNumber, $current_uploading_folder, $current_user_id)
{
global $config, $lang;
$fileInfo = array(
'saveToFolder',
'originalFileName',
'generatedFileName',
'fileSize',
'currentUserId',
'fileExtension'
);
$fileInfo['saveToFolder'] = $current_uploading_folder;
$fileInfo['currentUserId'] = $current_user_id;
if(!isset($_FILES['file_' . $fieldNumber . '_']) && isset($_FILES['file'][$fieldNumber]))
{
$_FILES['file_' . $fieldNumber . '_'] = $_FILES['file'][$fieldNumber];
}
# file name
$fileInfo['originalFileName'] = isset($_FILES['file_' . $fieldNumber . '_']['name'])
? htmlspecialchars(str_replace(array(';',','), '', $_FILES['file_' . $fieldNumber . '_']['name']))
: '';
if(empty($fileInfo['originalFileName']))
{
$this->addErrorMessage(sprintf($lang['WRONG_F_NAME'], htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name'])));
return;
}
# get the extension of file
$fileInfo['fileExtension'] = strtolower(array_pop(explode('.', $fileInfo['originalFileName'])));
# them the size
$fileInfo['fileSize'] = !empty($_FILES['file_' . $fieldNumber . '_']['size'])
? intval($_FILES['file_' . $fieldNumber . '_']['size'])
: 0;
# get the other filename, changed depend on kleeja settings
$fileInfo['generatedFileName'] = change_filename_decoding($fileInfo['originalFileName'], $fieldNumber, $fileInfo['fileExtension']);
# filename templates {rand:..}, {date:..}
$fileInfo['generatedFileName'] = change_filename_templates(trim($config['prefixname']) . $fileInfo['generatedFileName']);
# file exists before? change it a little
if(file_exists($current_uploading_folder . '/' . $fileInfo['generatedFileName']))
{
$fileInfo['generatedFileName'] = change_filename_decoding(
$fileInfo['generatedFileName'],
$fieldNumber, $fileInfo['fileExtension'],
'exists'
);
}
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_uploadTypeFile_1st', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
# now, let process it
if(!in_array(strtolower($fileInfo['fileExtension']), array_keys($this->getAllowedFileExtensions())))
{
# guest
if($current_user_id == '-1')
{
$this->addErrorMessage(
sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension'])
. '<br> <a href="' . ($config['mod_writer'] ? "register.html" : "ucp.php?go=register") .
'" title="' . htmlspecialchars($lang['REGISTER']) . '">' . $lang['REGISTER'] . '</a>'
);
}
# a member
else
{
$this->addErrorMessage(sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension']));
}
}
# bad chars in the filename
elseif(preg_match ("#[\\\/\:\*\?\<\>\|\"]#", $fileInfo['generatedFileName']))
{
$this->addErrorMessage(sprintf($lang['WRONG_F_NAME'], htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name'])));
}
# check file extension for bad stuff
elseif(ext_check_safe($_FILES['file_' . $fieldNumber . '_']['name']) == false)
{
$this->addErrorMessage(sprintf($lang['WRONG_F_NAME'], htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name'])));
}
# check the mime-type for the file
elseif(check_mime_type($_FILES['file_' . $fieldNumber . '_']['type'], $fileInfo['fileExtension'], $_FILES['file_' . $fieldNumber . '_']['tmp_name']) == false)
{
$this->addErrorMessage(sprintf($lang['NOT_SAFE_FILE'], htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name'])));
}
# check file size
elseif($this->getAllowedFileExtensions()[$fileInfo['fileExtension']] > 0 && $fileInfo['fileSize'] >= $this->getAllowedFileExtensions()[$fileInfo['fileExtension']])
{
$this->addErrorMessage(sprintf(
$lang['SIZE_F_BIG'],
htmlspecialchars($_FILES['file_' . $fieldNumber . '_']['name']),
readable_size($this->getAllowedFileExtensions()[$fileInfo['fileExtension']]))
);
}
# no errors, so upload it
else
{
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_uploadTypeFile_2nd', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
# now, upload the file
$file = move_uploaded_file($_FILES['file_' . $fieldNumber . '_']['tmp_name'], $current_uploading_folder . "/" . $fileInfo['generatedFileName']);
if ($file)
{
$this->saveToDatabase($fileInfo);
}
else
{
$this->addErrorMessage(sprintf($lang['CANT_UPLAOD'], $fileInfo['originalFileName']));
}
}
}
/**
* upload a file from a URL
* @param $fieldNumber
* @param $current_uploading_folder
* @param $current_user_id
*/
function uploadTypeUrl($fieldNumber, $current_uploading_folder, $current_user_id)
{
global $config, $lang;
$fileInfo = array(
'saveToFolder',
'originalFileName',
'generatedFileName',
'fileSize',
'currentUserId',
'fileExtension'
);
$fileInfo['saveToFolder'] = $current_uploading_folder;
$fileInfo['currentUserId'] = $current_user_id;
if(p('file_' . $fieldNumber . '_') == '' || p('file_' . $fieldNumber . '_') == $lang['PAST_URL_HERE'])
{
return;
}
# get file name
$fileInfo['originalFileName'] = basename(p('file_' . $fieldNumber . '_'));
# file extension, type
$fileExtensions = array_map('strtolower', explode(".", $fileInfo['originalFileName']));
if(sizeof($fileExtensions) > 1 && in_array($fileExtensions[sizeof($fileExtensions)-1], array('html', 'php', 'html')))
{
$fileInfo['fileExtension'] = strtolower($fileExtensions[sizeof($fileExtensions)-2]);
}
else if(sizeof($fileExtensions) > 0)
{
$fileInfo['fileExtension'] = strtolower($fileExtensions[sizeof($fileExtensions)-1]);
}
else
{
$fileInfo['fileExtension'] = ''; //what to do?
}
# change to another filename depend on kleeja settings
$fileInfo['generatedFileName'] = change_filename_decoding($fileInfo['originalFileName'], $fieldNumber, $fileInfo['fileExtension']);
$fileInfo['generatedFileName'] = change_filename_templates(trim($config['prefixname']) . $fileInfo['generatedFileName']);
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_uploadTypeUrl_1st', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#forbbiden type ? quit it
if(!in_array(strtolower($fileInfo['fileExtension']), array_keys($this->getAllowedFileExtensions())))
{
if($current_user_id == '-1')
{
$this->addErrorMessage(
sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension']) .
'<br> <a href="' . ($config['mod_writer'] ? "register.html" : "ucp.php?go=register") . '">' .
$lang['REGISTER'] . '</a>'
);
}
# a member
else
{
$this->addErrorMessage(sprintf($lang['FORBID_EXT'], $fileInfo['fileExtension']));
}
}
# file exists before ? quit it
elseif(file_exists($current_uploading_folder . '/' . $fileInfo['generatedFileName']))
{
$this->addErrorMessage(sprintf($lang['SAME_FILE_EXIST'], htmlspecialchars($fileInfo['generatedFileName'])));
}
# no errors, ok, lets upload now
else
{
is_array($plugin_run_result = Plugins::getInstance()->run('defaultUploader_uploadTypeUrl_2nd', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#no prefix ? http or even ftp, then add one
if(!in_array(strtolower(substr(p('file_' . $fieldNumber . '_'), 0, 4)), array('http', 'ftp:')))
{
$_POST['file_' . $fieldNumber . '_'] = 'http://' . p('file_' . $fieldNumber . '_');
}
#get size, if big quit it
$fileInfo['fileSize'] = get_remote_file_size(p('file_' . $fieldNumber . '_'));
if($this->getAllowedFileExtensions()[$fileInfo['fileExtension']] > 0 && $fileInfo['fileSize'] >= $this->getAllowedFileExtensions()[$fileInfo['fileExtension']])
{
$this->addErrorMessage(sprintf(
$lang['SIZE_F_BIG'],
p('file_' . $fieldNumber . '_'),
readable_size($this->getAllowedFileExtensions()[$fileInfo['fileExtension']])
));
}
else
{
#get remote data, if no data quit it
$data = fetch_remote_file(
p('file_' . $fieldNumber . '_'),
$current_uploading_folder . "/" . $fileInfo['generatedFileName'],
15,
false,
2,
true
);
if($data === false)
{
$this->addErrorMessage($lang['URL_CANT_GET']);
}
else
{
$this->saveToDatabase($fileInfo);
}
}
}
}
}

58
includes/up_methods/index.html Executable file
View File

@@ -0,0 +1,58 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256"/>
<title>Powered by Kleeja</title>
<style type="text/css">* {
font-size: 100%;
margin: 0;
padding: 0;
color: #CECFCE;
}
body {
font-family: Tahoma, Arial, sans-serif;
font-size: 100%;
color: #69788E;
margin: 10px 30px;
background: #F7F7F7;
}
a:link, a:visited {
text-decoration: none;
color: #CECFCE;
}
a:active, a:hover {
text-decoration: underline;
color: #111;
}
h1 {
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-size: 1.70em;
font-weight: normal;
color: #333333;
margin-top: 0;
margin-bottom: 10px;
}
.content_box {
border: 1px dashed #CECFCE;
background: #FFFFFF;
padding: 10px;
margin-right: auto;
margin-left: auto;
}</style>
</head>
<body title="&#1603;&#1604;&#1610;&#1580;&#1575;"><br/>
<div class="content_box">
<p>
<a target="_blank" href="http://www.kleeja.com" title="kleeja"></a>
</p>
<br/>
<h1><span style="font-size:250%;color:#D80000;">403 - Access forbidden!</span></h1></div>
<br/>
<div class="content_box"style="font-size: 140%">Powered by Kleeja</div>
</body>
</html>

629
includes/usr.php Executable file
View File

@@ -0,0 +1,629 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
class usrcp
{
// this function like a traffic sign :)
function data ($name, $pass, $hashed = false, $expire = 86400, $loginadm = false)
{
global $config, $userinfo;
//return user system to normal
if(defined('DISABLE_INTR') || $config['user_system'] == '' || empty($config['user_system']))
{
$config['user_system'] = '1';
}
//expire
$expire = time() + ((int) $expire ? intval($expire) : 86400);
$return_now = $login_status = false;
is_array($plugin_run_result = Plugins::getInstance()->run('data_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if($return_now)
{
return $login_status;
}
if((int) $config['user_system'] != 1)
{
if(file_exists(PATH . 'includes/auth_integration/' . trim($config['user_system']) . '.php'))
{
include_once PATH . 'includes/auth_integration/' . trim($config['user_system']) . '.php';
$login_status = kleeja_auth_login(trim($name), trim($pass), $hashed, $expire, $loginadm);
return $login_status;
}
}
//normal
return $this->normal(trim($name), trim($pass), $hashed, $expire, $loginadm);
}
//get username by id
function usernamebyid($user_id)
{
global $config;
//return user system to normal
if(defined('DISABLE_INTR'))
{
$config['user_system'] = 1;
}
$return_now = $auth_status = false;
is_array($plugin_run_result = Plugins::getInstance()->run('auth_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if($return_now)
{
return $auth_status;
}
if((int) $config['user_system'] != 1)
{
if(file_exists(PATH . 'includes/auth_integration/' . trim($config['user_system']) . '.php'))
{
include_once (PATH . 'includes/auth_integration/' . trim($config['user_system']) . '.php');
return kleeja_auth_username($user_id);
}
}
//normal system
$u = $this->get_data('name', $user_id);
return $u['name'];
}
//now our table, normal user system
function normal ($name, $pass, $hashed = false, $expire, $loginadm = false)
{
global $SQL, $dbprefix, $config, $userinfo;
$userinfo = array(
'id' => 0,
'group_id' => 2,
);
$query = array(
'SELECT' => '*',
'FROM' => "{$dbprefix}users",
'LIMIT' => '1'
);
if($hashed)
{
$query['WHERE'] = "id=" . intval($name) . " and password='" . $SQL->escape($pass) . "'";
}
else
{
$query['WHERE'] = "clean_name='" . $SQL->real_escape($this->cleanusername($name)) . "'";
}
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_usrdata_n_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$result = $SQL->build($query);
if ($SQL->num_rows($result))
{
while($row=$SQL->fetch_array($result))
{
if(empty($row['password'])) //more security
{
return false;
}
$phppass = $hashed ? $pass : $pass . $row['password_salt'];
//CHECK IF IT'S MD5 PASSWORD
if(strlen($row['password']) == '32' && empty($row['password_salt']) && defined('CONVERTED_SCRIPT'))
{
$passmd5 = md5($pass);
////update old md5 hash to phpass hash
if($row['password'] == $passmd5)
{
////new salt
$new_salt = substr(kleeja_base64_encode(pack("H*", sha1(mt_rand()))), 0, 7);
////new password hash
$new_password = $this->kleeja_hash_password(trim($pass) . $new_salt);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_update_usrdata_md5_n_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
////update now !!
$update_query = array(
'UPDATE' => "{$dbprefix}users",
'SET' => "password='" . $new_password . "' ,password_salt='" . $new_salt . "'",
'WHERE' => "id=" . intval($row['id'])
);
$SQL->build($update_query);
}
else //if the password is wrong
{
return false;
}
}
if(($phppass != $row['password'] && $hashed) || ($this->kleeja_hash_password($phppass, $row['password']) != true && $hashed == false))
{
return false;
}
//Avoid dfining constants again for admin panel login
if(!$loginadm)
{
define('USER_ID', $row['id']);
define('GROUP_ID', $row['group_id']);
define('USER_NAME', $row['name']);
define('USER_MAIL', $row['mail']);
define('LAST_VISIT', $row['last_visit']);
}
//all user fileds info
$userinfo = $row;
$user_y = kleeja_base64_encode(serialize(array('id'=>$row['id'], 'name'=>$row['name'], 'mail'=>$row['mail'], 'last_visit'=>$row['last_visit'])));
if(!$hashed && !$loginadm)
{
$hash_key_expire = sha1(md5($config['h_key'] . $row['password']). $expire);
$this->kleeja_set_cookie('ulogu', $this->en_de_crypt($row['id'] . '|' . $row['password'] . '|' . $expire . '|' . $hash_key_expire . '|' . $row['group_id'] . '|' . $user_y), $expire);
}
#if last visit > 1 minute then update it
if(empty($row['last_visit']) || time() - $row['last_visit'] > 60)
{
$update_last_visit = array(
'UPDATE' => "{$dbprefix}users",
'SET' => "last_visit=" . time(),
'WHERE' => "id=" . intval($row['id'])
);
$SQL->build($update_last_visit);
}
is_array($plugin_run_result = Plugins::getInstance()->run('qr_while_usrdata_n_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
}
$SQL->freeresult($result);
unset($pass);
return true;
}
else
{
return false;
}
}
/*
get user data
new function:1rc5+
*/
function get_data($type="*", $user_id = false)
{
global $dbprefix, $SQL;
if(!$user_id)
{
$user_id = $this->id();
}
//todo :
//if type != '*' and contains no , and type in 'name, id, email' return $this->id .. etc
//te get files and update them !!
$query_name = array(
'SELECT' => $type,
'FROM' => "{$dbprefix}users",
'WHERE' => "id=" . intval($user_id)
);
is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_userdata_in_usrclass', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$data_user = $SQL->fetch_array($SQL->build($query_name));
return $data_user;
}
/*
user ids
*/
function id ()
{
is_array($plugin_run_result = Plugins::getInstance()->run('id_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return defined('USER_ID') ? USER_ID : false;
}
/*
group ids
*/
function group_id ()
{
is_array($plugin_run_result = Plugins::getInstance()->run('group_id_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return defined('GROUP_ID') ? GROUP_ID : false;
}
/*
user name
*/
function name ()
{
is_array($plugin_run_result = Plugins::getInstance()->run('name_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return defined('USER_NAME') ? USER_NAME : false;
}
/*
user mail
*/
function mail ()
{
is_array($plugin_run_result = Plugins::getInstance()->run('mail_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return defined('USER_MAIL') ? USER_MAIL : false;
}
/*
logout func
*/
function logout()
{
is_array($plugin_run_result = Plugins::getInstance()->run('logout_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
//acp
if(user_can('enter_acp') && !empty($_SESSION['ADMINLOGIN']))
{
$this->logout_cp();
}
//is ther any cookies
$this->kleeja_set_cookie('ulogu', '', time() - 31536000);//31536000 = year
return true;
}
/*
logut just from acp
*/
function logout_cp()
{
is_array($plugin_run_result = Plugins::getInstance()->run('logout_cp_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
if(!empty($_SESSION['ADMINLOGIN']))
{
unset($_SESSION['ADMINLOGIN'], $_SESSION['USER_SESS'] /*, $_SESSION['LAST_VISIT']*/);
}
return true;
}
//clean usernames
function cleanusername($uname)
{
if(!function_exists('kleeja_base64_decode'))
{
include_once (PATH . 'includes/functions_alternative.php');
}
is_array($plugin_run_result = Plugins::getInstance()->run('cleanusername_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
static $arabic_t = array();
static $latin_t = array(
array('á','à','â','ã','å','Á','À','Â','Ã','Å','é','è','ê','ë','É','È','Ê','í','ì','ï','î','Í','Ì','Î','Ï','ò','ó','ô','õ','º','ø','Ó','Ò','Ô','Õ','Ø','ú','ù','û','Ú','Ù','Û','ç','Ç','Ñ','ñ','ÿ','Ë'),
array('a','a','a','a','a','a','a','a','a','a','e','e','e','e','e','e','e','i','i','i','i','i','i','i','i','o','o','o','o','o','o','o','o','o','o','o','u','u','u','u','u','u','c','c','n','n','y','e')
);
if(empty($arabic_t))
{
//Arabic chars must be stay in utf8 format, so we encoded them
$arabic_t = unserialize(kleeja_base64_decode('YToyOntpOjA7YToxMjp7aTowO3M6Mjoi2KMiO2k6MTtzOjI6ItilIjtpOjI7czoyOiLYpCI7aTozO3M6Mjoi2YAiO2k6NDtzOjI6Itm' .
'LIjtpOjU7czoyOiLZjCI7aTo2O3M6Mjoi2Y8iO2k6NztzOjI6ItmOIjtpOjg7czoyOiLZkCI7aTo5O3M6Mjoi2ZIiO2k6MTA7czoyOiLYoiI7aToxMTtzOjI6ItimIjt9aToxO' .
'2E6MTI6e2k6MDtzOjI6ItinIjtpOjE7czoyOiLYpyI7aToyO3M6Mjoi2YgiO2k6MztzOjA6IiI7aTo0O3M6MDoiIjtpOjU7czowOiIiO2k6NjtzOjA6IiI7aTo3O3M6MDoiIjt' .
'pOjg7czowOiIiO2k6OTtzOjA6IiI7aToxMDtzOjI6ItinIjtpOjExO3M6Mjoi2YkiO319'));
}
$uname = str_replace($latin_t[0], $latin_t[1], $uname); //replace confusable Latin chars
$uname = str_replace($arabic_t[0], $arabic_t[1], $uname); //replace confusable Arabic chars
$uname = preg_replace('#(?:[\x00-\x1F\x7F]+|(?:\xC2[\x80-\x9F])+)#', '', $uname); //un-wanted utf8 control chars
$uname = preg_replace('# {2,}#', ' ', $uname); //2+ spaces with one space
return strtolower($uname);
}
//depand on phpass class
function kleeja_hash_password($password, $check_pass = false)
{
include_once('phpass.php');
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_hash_password_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
$hasher = new PasswordHash(8, true);
$return = $hasher->HashPassword($password);
//return check or hash
return $check_pass != false ? $hasher->CheckPassword($password, $check_pass) : $return;
}
//kleeja cookie
function kleeja_set_cookie($name, $value, $expire)
{
global $config;
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_set_cookie_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
//
//when user add cookie_* in config this will replace the current ones
//
global $config_cookie_name, $config_cookie_domain, $config_cookie_secure, $config_cookie_path;
$config['cookie_name'] = isset($config_cookie_name) ? $config_cookie_name : $config['cookie_name'];
$config['cookie_domain'] = isset($config_cookie_domain) ? $config_cookie_domain : $config['cookie_domain'];
$config['cookie_secure'] = isset($config_cookie_secure) ? $config_cookie_secure : $config['cookie_secure'];
$config['cookie_path'] = isset($config_cookie_path) ? $config_cookie_path : $config['cookie_path'];
//
//when user add define('FORCE_COOKIES', true) in config.php we will make our settings of cookies
//
if(defined('FORCE_COOKIES'))
{
$config['cookie_domain'] = (!empty($_SERVER['HTTP_HOST'])) ? strtolower($_SERVER['HTTP_HOST']) : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : @getenv('SERVER_NAME'));
$config['cookie_domain'] = str_replace('www.', '.', substr($config['cookie_domain'], 0, strpos($config['cookie_domain'], ':')));
$config['cookie_path'] = '/';
$config['cookie_secure'] = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? true : false;
}
// Enable sending of a P3P header
header('P3P: CP="CUR ADM"');
$name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($value);
$rexpire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $expire);
$domain = (!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain'];
header('Set-Cookie: ' . $name_data . (($expire) ? '; expires=' . $rexpire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . '; HttpOnly', false);
}
//encrypt and decrypt any data with our function
function en_de_crypt($data, $type = 1)
{
global $config;
static $txt = array();
if(empty($txt))
{
if(empty($config['h_key']))
{
$config['h_key'] = sha1(microtime());
}
$chars = str_split($config['h_key']);
foreach(range('a', 'z') as $k=>$v)
{
if(!isset($chars[$k]))
{
break;
}
$txt[$v] = $chars[$k] . $k . '-';
}
}
switch($type)
{
case 1:
$data = str_replace('=', '_', kleeja_base64_encode($data));
$data = strtr($data, $txt);
break;
case 2:
$txtx = array_flip($txt);
$txtx = array_reverse($txtx, true);
$data = strtr($data, $txtx);
$data = kleeja_base64_decode(str_replace('_', '=', $data));
break;
}
return $data;
}
//
//get cookie
//
function kleeja_get_cookie($name)
{
global $config;
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_get_cookie_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
return isset($_COOKIE[$config['cookie_name'] . '_' . $name]) ? $_COOKIE[$config['cookie_name'] . '_' . $name] : false;
}
//check if user is admin or not
//return : mean return true or false, but if return is false will show msg
function kleeja_check_user()
{
global $config, $SQL, $dbprefix, $userinfo;
is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_check_user_func_usr_class', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
#to make sure
$userinfo = array(
'id' => -1,
'group_id' => 2,
);
//if login up
if($this->kleeja_get_cookie('ulogu'))
{
$user_data = false;
list($user_id, $hashed_password, $expire_at, $hashed_expire, $group_id, $u_info) = @explode('|', $this->en_de_crypt($this->kleeja_get_cookie('ulogu'), 2));
//if not expire
if(($hashed_expire == sha1(md5($config['h_key'] . $hashed_password) . $expire_at)) && ($expire_at > time()))
{
/* For better performance we will take the risks */
/*
!defined('IN_DOWNLOAD')
*/
//exit(print_r( @explode('|', $this->en_de_crypt($this->kleeja_get_cookie('ulogu'), 2))));
if(user_can('enter_acp', $group_id))
{
$user_data = $this->data($user_id, $hashed_password, true, $expire_at);
}
else
{
if(!empty($u_info))
{
$userinfo = unserialize(kleeja_base64_decode($u_info));
$userinfo['group_id'] = $group_id;
$userinfo['password'] = $hashed_password;
define('USER_ID', $userinfo['id']);
define('GROUP_ID', $userinfo['group_id']);
define('USER_NAME', $userinfo['name']);
define('USER_MAIL', $userinfo['mail']);
define('LAST_VISIT', $userinfo['last_visit']);
$user_data = true;
}
}
}
if($user_data == false)
{
$this->logout();
}
else
{
return $user_data;
}
}
else
{
#guest
define('USER_ID', $userinfo['id']);
define('GROUP_ID', $userinfo['group_id']);
}
return false; //nothing
}
/*
* convert from utf8 to cp1256 and vice versa
*/
function kleeja_utf8($str, $to_utf8 = true)
{
$utf8 = new kleeja_utf8;
if($to_utf8)
{
//return iconv('CP1256', "UTF-8//IGNORE", $str);
return $utf8->to_utf8($str);
}
return $utf8->from_utf8($str);
//return iconv('UTF-8', "CP1256//IGNORE", $str);
}
}#end class
/**
* Deep modifieded by Kleeja team ...
* depend on class by Alexander Minkovsky (a_minkovsky@hotmail.com)
*/
class kleeja_utf8
{
var $ascMap = array();
var $utfMap = array();
//ignore the untranslated char, of you put true we will translate it to html tags
//it's same the action of //IGNORE in iconv
var $ignore = false;
//Constructor
function __construct()
{
static $lines = array();
if(empty($lines))
{
$lines = explode("\n", preg_replace(array("/#.*$/m", "/\n\n/"), '', file_get_contents(PATH . 'includes/CP1256.MAP')));
}
if(empty($this->ascMap))
{
foreach($lines as $line)
{
$parts = explode('0x', $line);
if(sizeof($parts) == 3)
$this->ascMap[hexdec(trim($parts[1]))] = hexdec(trim($parts[2]));
}
$this->utfMap = array_flip($this->ascMap);
}
}
//Translate string ($str) to UTF-8 from given charset
function to_utf8($str)
{
$chars = unpack('C*', $str);
$cnt = sizeof($chars);
for($i=1;$i <= $cnt; ++$i)
$this->_charToUtf8($chars[$i]);
return implode('', $chars);
}
//Translate UTF-8 string to single byte string in the given charset
function from_utf8($utf)
{
$chars = unpack('C*', $utf);
$cnt = sizeof($chars);
$res = ''; //No simple way to do it in place... concatenate char by char
for ($i=1;$i<=$cnt;$i++)
$res .= $this->_utf8ToChar($chars, $i);
return $res;
}
//Char to UTF-8 sequence
function _charToUtf8(&$char)
{
$c = (int) $this->ascMap[$char];
if ($c < 0x80)
$char = chr($c);
else if($c<0x800) // 2 bytes
$char = (chr(0xC0 | $c>>6) . chr(0x80 | $c & 0x3F));
else if($c<0x10000) // 3 bytes
$char = (chr(0xE0 | $c>>12) . chr(0x80 | $c>>6 & 0x3F) . chr(0x80 | $c & 0x3F));
else if($c<0x200000) // 4 bytes
$char = (chr(0xF0 | $c>>18) . chr(0x80 | $c>>12 & 0x3F) . chr(0x80 | $c>>6 & 0x3F) . chr(0x80 | $c & 0x3F));
}
//UTF-8 sequence to single byte character
function _utf8ToChar(&$chars, &$idx)
{
if(($chars[$idx] >= 240) && ($chars[$idx] <= 255))// 4 bytes
$utf = (intval($chars[$idx]-240) << 18) + (intval($chars[++$idx]-128) << 12) + (intval($chars[++$idx]-128) << 6) + (intval($chars[++$idx]-128) << 0);
else if (($chars[$idx] >= 224) && ($chars[$idx] <= 239)) // 3 bytes
$utf = (intval($chars[$idx]-224) << 12) + (intval($chars[++$idx]-128) << 6) + (intval($chars[++$idx]-128) << 0);
else if (($chars[$idx] >= 192) && ($chars[$idx] <= 223))// 2 bytes
$utf = (intval($chars[$idx]-192) << 6) + (intval($chars[++$idx]-128) << 0);
else// 1 byte
$utf = $chars[$idx];
if(array_key_exists($utf, $this->utfMap))
return chr($this->utfMap[$utf]);
else
return $this->ignore ? '' : '&#' . $utf . ';';
}
}
#<-- EOF

24
includes/version.php Executable file
View File

@@ -0,0 +1,24 @@
<?php
/**
*
* @package Kleeja
* @copyright (c) 2007 Kleeja.com
* @license ./docs/license.txt
*
*/
//no for directly open
if (!defined('IN_COMMON'))
{
exit();
}
define('KLEEJA_VERSION', '2.2');
define('KLEEJA_DB_VERSION', '9');