$browser = 'NetPositive';
} elseif (preg_match('#Shiira#i', $server_agent)) {
$browser = 'Shiira';
} elseif (preg_match('#Shiretoko#i', $server_agent)) {
$browser = 'Firefox';
} elseif (preg_match('#Sleipnir#i', $server_agent)) {
$browser = 'Sleipnir';
} elseif (preg_match('#Stainless#i', $server_agent)) {
$browser = 'Stainless';
} elseif (preg_match('#Sunrise#i', $server_agent)) {
$browser = 'Sunrise';
}
// Information partially taken from http://www.useragentstring.com/
//Code to get the search string if the referrer is any of the following
$search_engines = array(
'google',
'lycos',
'yahoo'
);
$query_array = array();
foreach ($search_engines as $engine) {
if (is_referer_search_engine($engine)) {
$query_array = get_search_query_terms($engine);
break;
}
}
$query_terms = is_array($query_array) ? implode(',', $query_array) : '';
$return_array = array(
'os' => $os,
'browser' => $browser,
'query_terms' => $query_terms
);
return $return_array;
}
// Add 1 everytime a picture is viewed.
/**
* add_hit()
*
* @param $pid
* @return
**/
function add_hit($pid)
{
global $CONFIG, $raw_ip;
if ($CONFIG['count_file_hits']) {
cpg_db_query("UPDATE {$CONFIG['TABLE_PICTURES']} SET hits = hits + 1, lasthit_ip = '$raw_ip', mtime = CURRENT_TIMESTAMP WHERE pid = $pid");
}
/**
* Code to record the details of hits for the picture, if the option is set in CONFIG
*/
if ($CONFIG['hit_details']) {
// Get the details of user browser, IP, OS, etc
$client_details = cpg_determine_client();
$search_phrase = addslashes($client_details['query_terms']);
//Making Cage
$superCage = Inspekt::makeSuperCage();
$time = time();
//Sanitize the referer
if ($superCage->server->keyExists('HTTP_REFERER')) {
$referer = $superCage->server->getEscaped('HTTP_REFERER');
} else {
$referer = '';
}
$hitUserId = USER_ID;
// Insert the record in database
$query = "INSERT INTO {$CONFIG['TABLE_HIT_STATS']} SET"
." pid = $pid,"
." search_phrase = '$search_phrase',"
." Ip = '$raw_ip',"
." sdate = '$time',"
." referer='$referer',"
." browser = '{$client_details['browser']}',"
." os = '{$client_details['os']}',"
." uid ='$hitUserId'";
cpg_db_query($query);
}
}
/**
* add_album_hit()
* Add a hit to the album.
* @param $pid
* @return
**/
function add_album_hit($aid)
{
global $CONFIG;
if ($CONFIG['count_album_hits']) {
$aid = (int) $aid;
cpg_db_query("UPDATE {$CONFIG['TABLE_ALBUMS']} SET alb_hits = alb_hits + 1 WHERE aid = $aid");
}
}
/**
* breadcrumb()
*
* Build the breadcrumb navigation
*
* @param integer $cat
* @param string $breadcrumb
* @param string $BREADCRUMB_TEXT
* @return
**/
function breadcrumb($cat, &$breadcrumb, &$BREADCRUMB_TEXT)
{
global $lang_list_categories, $lang_common;
global $CONFIG,$CURRENT_ALBUM_DATA, $CURRENT_CAT_NAME;
$category_array = array();
// first we build the category path: names and id
if ($cat != 0) { //Categories other than 0 need to be selected
if ($cat >= FIRST_USER_CAT) {
$result = cpg_db_query("SELECT name FROM {$CONFIG['TABLE_CATEGORIES']} WHERE cid = " . USER_GAL_CAT);
$row = $result->fetchAssoc(true);
$category_array[] = array(USER_GAL_CAT, $row['name']);
$user_name = get_username($cat - FIRST_USER_CAT);
if (!$user_name) {
$user_name = $lang_common['username_if_blank'];
}
$category_array[] = array($cat, $user_name);
$CURRENT_CAT_NAME = sprintf($lang_list_categories['xx_s_gallery'], $user_name);
$row['parent'] = 1;
} else {
$result = cpg_db_query("SELECT p.cid, p.name FROM {$CONFIG['TABLE_CATEGORIES']} AS c,
{$CONFIG['TABLE_CATEGORIES']} AS p
WHERE c.lft BETWEEN p.lft AND p.rgt
AND c.cid = $cat
ORDER BY p.lft");
while ( ($row = $result->fetchAssoc()) ) {
$category_array[] = array($row['cid'], $row['name']);
$CURRENT_CAT_NAME = $row['name'];
}
$result->free();
}
}
$breadcrumb_links = array();
$BREADCRUMB_TEXTS = array();
// Add the Home link to breadcrumb
$breadcrumb_links[0] = ''.$lang_list_categories['home'].'';
$BREADCRUMB_TEXTS[0] = $lang_list_categories['home'];
$cat_order = 1;
foreach ($category_array as $category) {
$breadcrumb_links[$cat_order] = "{$category[1]}";
$BREADCRUMB_TEXTS[$cat_order] = $category[1];
$cat_order += 1;
}
//Add Link for album if aid is set
if (isset($CURRENT_ALBUM_DATA['aid'])) {
$breadcrumb_links[$cat_order] = "".$CURRENT_ALBUM_DATA['title']."";
$BREADCRUMB_TEXTS[$cat_order] = $CURRENT_ALBUM_DATA['title'];
}
// Build $breadcrumb,$BREADCRUMB_TEXT from _links and _TEXTS
theme_breadcrumb($breadcrumb_links, $BREADCRUMB_TEXTS, $breadcrumb, $BREADCRUMB_TEXT);
} // function breadcrumb
/**************************************************************************
**************************************************************************/
// Get the configured/available image tool class
function getImageTool ()
{
global $CONFIG;
if ($CONFIG['thumb_method'] == 'imx') {
require_once 'include/imageobject_imx.class.php';
} elseif ($CONFIG['thumb_method'] == 'im') {
require_once 'include/imageobject_im.class.php';
} else {
require_once 'include/imageobject_gd.class.php';
}
}
// Compute image geometry based on max width / height
/**
* compute_img_size()
*
* Compute image geometry based on max, width / height
*
* @param integer $width
* @param integer $height
* @param integer $max
* @return array
**/
function compute_img_size($width, $height, $max, $system_icon = false, $normal = false)
{
global $CONFIG;
$thumb_use = $CONFIG['thumb_use'];
if ($thumb_use == 'ht') {
$ratio = $height / $max;
} elseif ($thumb_use == 'wd') {
$ratio = $width / $max;
} else {
$ratio = max($width, $height) / $max;
}
if ($ratio > 1) {
$image_size['reduced'] = true;
}
$ratio = max($ratio, 1);
$image_size['width'] = (int) ($width / $ratio);
$image_size['height'] = (int) ($height / $ratio);
$image_size['whole'] = 'width="' . $image_size['width'] . '" height="' . $image_size['height'] . '"';
if ($thumb_use == 'ht') {
$image_size['geom'] = ' height="' . $image_size['height'] . '"';
} elseif ($thumb_use == 'wd') {
$image_size['geom'] = 'width="' . $image_size['width'] . '"';
//thumb cropping
} elseif ($thumb_use == 'ex') {
if ($normal == 'normal') {
$image_size['geom'] = 'width="' . $image_size['width'] . '" height="' . $image_size['height'] . '"';
} elseif ($normal == 'cat_thumb') {
$image_size['geom'] = 'width="' . $max . '" height="' . ($CONFIG['thumb_height'] * $max / $CONFIG['thumb_width']) . '"';
} else {
$image_size['geom'] = 'width="' . $CONFIG['thumb_width'] . '" height="' . $CONFIG['thumb_height'] . '"';
}
//if we have a system icon we override the previous calculation and take 'any' as base for the calc
if ($system_icon) {
$image_size['geom'] = 'width="' . $image_size['width'] . '" height="' . $image_size['height'] . '"';
}
} else {
$image_size['geom'] = 'width="' . $image_size['width'] . '" height="' . $image_size['height'] . '"';
}
return $image_size;
} // function compute_img_size
// Prints thumbnails of pictures in an album
/**
* display_thumbnails()
*
* Generates data to display thumbnails of pictures in an album
*
* @param mixed $album Either the album ID or the meta album name
* @param integer $cat Either the category ID or album ID if negative
* @param integer $page Page number to display
* @param integer $thumbcols
* @param integer $thumbrows
* @param boolean $display_tabs
**/
function display_thumbnails($album, $cat, $page, $thumbcols, $thumbrows, $display_tabs)
{
global $CONFIG, $USER, $LINEBREAK;
global $lang_date, $lang_display_thumbnails, $lang_byte_units, $lang_common, $valid_meta_albums;
$superCage = Inspekt::makeSuperCage();
$thumb_per_page = $thumbcols * $thumbrows;
$lower_limit = ($page - 1) * $thumb_per_page;
$pic_data = get_pic_data($album, $thumb_count, $album_name, $lower_limit, $thumb_per_page);
$total_pages = ceil($thumb_count / $thumb_per_page);
$i = 0;
if (is_array($pic_data) && $pic_data) {
foreach ($pic_data as $key => $row) {
$i++;
$pic_title = $lang_common['filename'] . '=' . $row['filename'] . $LINEBREAK .
$lang_common['filesize'] . '=' . ($row['filesize'] >> 10) . $lang_byte_units[1] . $LINEBREAK .
$lang_display_thumbnails['dimensions'] . $row['pwidth'] . "x" . $row['pheight'] . $LINEBREAK .
$lang_display_thumbnails['date_added'] . localised_date($row['ctime'], $lang_date['album']);
list($pic_title) = CPGPluginAPI::filter('thumb_html_title', array($pic_title, $row));
$pic_url = get_pic_url($row, 'thumb');
if (!is_image($row['filename'])) {
$image_info = cpg_getimagesize(urldecode($pic_url));
$row['pwidth'] = $image_info[0];
$row['pheight'] = $image_info[1];
}
// thumb cropping - if we display a system thumb we calculate the dimension by any and not ex
if (array_key_exists('system_icon', $row) && ($row['system_icon'] == true)) {
$image_size = compute_img_size($row['pwidth'], $row['pheight'], $CONFIG['thumb_width'], true);
} else {
$image_size = compute_img_size($row['pwidth'], $row['pheight'], $CONFIG['thumb_width']);
}
$thumb_list[$i]['pos'] = $key < 0 ? $key : $i - 1 + $lower_limit;
$thumb_list[$i]['pid'] = $row['pid'];
$thumb_list[$i]['image'] = '';
$thumb_list[$i]['caption'] = bb_decode($row['caption_text']);
$thumb_list[$i]['admin_menu'] = '';
$thumb_list[$i]['aid'] = $row['aid'];
$thumb_list[$i]['pwidth'] = $row['pwidth'];
$thumb_list[$i]['pheight'] = $row['pheight'];
// cpg1.5: new thumb fields below
$thumb_list[$i]['title'] = $row['title'];
$thumb_list[$i]['description'] = $row['caption'];
$thumb_list[$i]['filepath'] = $row['filepath'];
$thumb_list[$i]['filename'] = $row['filename'];
$thumb_list[$i]['filesize'] = $row['filesize'];
$thumb_list[$i]['msg_id'] = isset($row['msg_id']) ? $row['msg_id'] : ''; // needed for get_pic_pos()
}
// Add a hit to album counter if it is a numeric album
if (is_numeric($album)) {
// Create an array to hold the album id for hits (if not created)
if (!isset($USER['liv_a']) || !is_array($USER['liv_a'])) {
$USER['liv_a'] = array();
}
// Add 1 to album hit counter
if ((!USER_IS_ADMIN && $CONFIG['count_admin_hits'] == 0 || $CONFIG['count_admin_hits'] == 1) && !in_array($album, $USER['liv_a']) && $superCage->cookie->keyExists($CONFIG['cookie_name'] . '_data')) {
add_album_hit($album);
if (count($USER['liv_a']) > 4) {
array_shift($USER['liv_a']);
}
array_push($USER['liv_a'], $album);
user_save_profile();
}
}
//Using getRaw(). The date is sanitized in the called function.
$date = $superCage->get->keyExists('date') ? cpgValidateDate($superCage->get->getRaw('date')) : null;
theme_display_thumbnails($thumb_list, $thumb_count, $album_name, $album, $cat, $page, $total_pages, is_numeric($album), $display_tabs, 'thumb', $date);
} elseif (is_numeric($album) || in_array($album, $valid_meta_albums)) {
theme_no_img_to_display($album_name);
}
}
/**
* cpg_get_system_thumb_list()
*
* Return an array containing the system thumbs in a directory
* @param string $search_folder
* @return array
**/
function cpg_get_system_thumb_list($search_folder = 'images/')
{
global $CONFIG;
static $thumbs = array();
$folder = 'images/thumbs/';
$thumb_pfx =& $CONFIG['thumb_pfx'];
// If thumb array is empty get list from coppermine 'images' folder
if ((count($thumbs) == 0) && ($folder == $search_folder)) {
$dir = opendir($folder);
while (($file = readdir($dir)) !== false) {
if (is_file($folder . $file) && strpos($file, $thumb_pfx) === 0) {
// Store filenames in an array
$thumbs[] = array('filename' => $file);
}
}
closedir($dir);
return $thumbs;
} elseif ($folder == $search_folder) {
// Search folder is the same as coppermine images folder; just return the array
return $thumbs;
} else {
// Search folder is different; check for files in the given folder
$results = array();
foreach ($thumbs as $thumb) {
if (is_file($search_folder . $thumb['filename'])) {
$results[] = array('filename' => $thumb['filename']);
}
}
return $results;
}
}
/**
* cpg_get_system_thumb()
*
* Gets data for system thumbs
*
* @param string $filename
* @param integer $user
* @return array
**/
function& cpg_get_system_thumb($filename, $user = FIRST_USER_CAT)
{
global $CONFIG;
// Correct user_id
if ($user < FIRST_USER_CAT) {
$user += FIRST_USER_CAT;
}
if ($user == FIRST_USER_CAT) {
$user = FIRST_USER_CAT + 1;
}
// Get image data for thumb
$picdata = array(
'filename' => $filename,
'filepath' => $CONFIG['userpics'] . $user . '/',
'url_prefix' => 0,
);
$pic_url = get_pic_url($picdata, 'thumb', true);
$picdata['thumb'] = $pic_url;
$image_info = cpg_getimagesize(urldecode($pic_url));
$picdata['pwidth'] = $image_info[0];
$picdata['pheight'] = $image_info[1];
$image_size = compute_img_size($picdata['pwidth'], $picdata['pheight'], $CONFIG['alb_list_thumb_size']);
$picdata['whole'] = $image_size['whole'];
$picdata['reduced'] = (isset($image_size['reduced']) && $image_size['reduced']);
return $picdata;
} // function cpg_get_system_thumb
/**
* display_film_strip()
*
* gets data for thumbnails in an album for the film strip
*
* @param integer $album
* @param integer $cat
* @param integer $pos
**/
function display_film_strip($album, $cat, $pos,$ajax_call)
{
global $CONFIG, $LINEBREAK;
global $lang_date, $lang_display_thumbnails, $lang_byte_units, $lang_common, $pic_count,$ajax_call,$pos;
$superCage = Inspekt::makeSuperCage();
$max_item = $CONFIG['max_film_strip_items'];
$thumb_width = $CONFIG['thumb_width'];
/** set to variable with to javascript*/
set_js_var('thumb_width', $thumb_width);
set_js_var('thumb_use', $CONFIG['thumb_use']);
if ($CONFIG['max_film_strip_items'] % 2 == 0) {
$max_item = $CONFIG['max_film_strip_items'] + 1;
$pic_count = $pic_count + 1;
}
$max_item_real = $max_item;
/** check the thumb_per_page variable valid to query database*/
if ($pic_count < $max_item_real) {
$max_item_real = $pic_count;
}
/** pass the max_items to the dispalyimage.js file */
set_js_var('max_item', $max_item_real);
$max_block_items = $CONFIG['max_film_strip_items'];
$thumb_per_page = $max_item_real;
/** assign the varible $l_limit diffen */
$l_limit = (int) ($max_item_real / 2);
$l_limit = max(0, $pos - $l_limit);
/** set $l_limit to last images */
if ($l_limit > ($pic_count - $max_item_real)) {
$l_limit = $pic_count - $max_item_real;
}
$pic_data = get_pic_data($album, $thumb_count, $album_name, $l_limit, $thumb_per_page, false, 'filmstrip');
if (count($pic_data) < $max_item) {
$max_item = count($pic_data);
}
$lower_limit = 0;
if ($ajax_call == 2) {
$lower_limit = $max_item_real -1;
$max_item = 1;
} elseif ($ajax_call == 1) {
$lower_limit = 0;
$max_item = 1;
}
$pic_data = array_slice($pic_data, $lower_limit, $max_item);
$i = $l_limit;
set_js_var('count', $pic_count);
$cat_link = is_numeric($album) ? '' : '&cat=' . $cat;
//FIXME: Where does this '$date' come from?
if (isset($date) && $date != '') {
$date_link = '&date=' . $date;
} else {
$date_link = '';
}
if ($superCage->get->getInt('uid')) {
$uid_link = '&uid=' . $superCage->get->getInt('uid');
} else {
$uid_link = '';
}
if (count($pic_data) > 0) {
foreach ($pic_data as $key => $row) {
//$hi is never used
//$hi = (($pos == ($i + $lower_limit)) ? '1': '');
$i++;
$pic_alt = $row['filename'];
$pic_title = $lang_common['filename'] . '=' . $row['filename'] . $LINEBREAK .
$lang_common['filesize'] . '=' . ($row['filesize'] >> 10) . $lang_byte_units[1] . $LINEBREAK .
$lang_display_thumbnails['dimensions'] . $row['pwidth'] . "x" . $row['pheight'] . $LINEBREAK .
$lang_display_thumbnails['date_added'] . localised_date($row['ctime'], $lang_date['album']);
list($pic_title) = CPGPluginAPI::filter('thumb_strip_html_title', array($pic_title, $row));
$pic_url = get_pic_url($row, 'thumb');
/*if (!is_image($row['filename'])) {
$image_info = cpg_getimagesize(urldecode($pic_url));
$row['pwidth'] = $image_info[0];
$row['pheight'] = $image_info[1];
}
//thumb cropping
/*if (array_key_exists('system_icon', $row) && ($row['system_icon'] == true)) {
$image_size = compute_img_size($row['pwidth'], $row['pheight'], $CONFIG['thumb_width'], true);
} else {
$image_size = compute_img_size($row['pwidth'], $row['pheight'], $CONFIG['thumb_width']);
}*/ // values never used
$p = $i - 1 + $lower_limit;
$p = ($p < 0 ? 0 : $p);
$thumb_list[$i]['pos'] = $key < 0 ? $key : $p;
$thumb_list[$i]['image'] = '';
$thumb_list[$i]['admin_menu'] = '';
$thumb_list[$i]['pid'] = $row['pid'];
$thumb_list[$i]['msg_id'] = isset($row['msg_id']) ? $row['msg_id'] : ''; // needed for get_pic_pos()
$msg_id = isset($row['msg_id']) ? '&msg_id='.$row['msg_id'] : '';
$page = isset($row['msg_id']) ? '&page='.cpg_get_comment_page_number($row['msg_id']) : '';
$hash = isset($row['msg_id']) ? '#comment'.$row['msg_id'] : '#top_display_media';
$target = "displayimage.php?album=$album$cat_link$date_link&pid={$row['pid']}$msg_id$page$uid_link$hash";
}
// Get the pos for next and prev links in filmstrip navigation
$filmstrip_next_pos = $pos + 1;
$filmstrip_prev_pos = $pos - 1;
// If next pos is greater then total pics then make it pic_count - 1
$filmstrip_next_pos = $filmstrip_next_pos >= $pic_count ? $pic_count - 1 : $filmstrip_next_pos;
// If prev pos is less than 0 then make it 0
$filmstrip_prev_pos = $filmstrip_prev_pos < 0 ? 0 : $filmstrip_prev_pos;
//Using getRaw(). The date is sanitized in the called function.
$date = $superCage->get->keyExists('date') ? cpgValidateDate($superCage->get->getRaw('date')) : null;
if ($ajax_call == 2 || $ajax_call == 1) {
$setArray = array(
'url' => $pic_url,
'target' => $target,
'alt' => $pic_alt,
'title' => $pic_title,
);
header("Content-Type: text/plain");
echo json_encode($setArray);
} else {
return theme_display_film_strip($thumb_list, $thumb_count, $album_name, $album, $cat, $pos, is_numeric($album), 'thumb', $date, $filmstrip_prev_pos, $filmstrip_next_pos, $max_block_items, $thumb_width);
}
} else {
if ($ajax_call == 2 || $ajax_call == 1) {
$setArray = array(
'url' => 'images/stamp.png',
'target' => 'images/stamp.png',
'alt' => 'stamp.png',
'title' => '',
);
header("Content-Type: text/plain");
echo json_encode($setArray);
} else {
theme_no_img_to_display($album_name);
}
}
}
/**
* display_slideshow()
*
* gets data for thumbnails in an album for the film stript using Ajax call
*
* this added by Nuwan Sameera Hettiarachchi
*
* @param integer $album
* @param integer $cat
* @param integer $pos
**/
function display_slideshow($pos, $ajax_show = 0)
{
global $CONFIG, $album, $pid, $slideshow, $USER;
$superCage = Inspekt::makeSuperCage();
$Pic = array();
$Pid = array();
$Title = array();
$i = 0;
$j = 0;
/** get the pic details by querying database*/
$pic_data = get_pic_data($album, $pic_count, $album_name, $pos, 1, false);
/** calculate total amount of pic a perticular album */
if ($ajax_show == 0) {
set_js_var('Pic_count', $pic_count);
}
foreach ($pic_data as $picture) {
if (is_image($picture['filename'])) {
if ($CONFIG['make_intermediate'] && cpg_picture_dimension_exceeds_intermediate_limit($picture['pwidth'], $picture['pheight'])) {
$picture_url = get_pic_url($picture, 'normal');
} else {
$picture_url = get_pic_url($picture, 'fullsize');
}
$Pic[$i] = htmlspecialchars($picture_url, ENT_QUOTES);
/*if ($picture['pid'] == $pid) {
$j = $i;
$start_img = $picture_url;
}*/ //$j and $start_img are never used
} else {
$pic_url = get_pic_url($picture, 'thumb');
$Pic[$i] = htmlspecialchars($pic_url);
}
$Pid[$i] = $picture['pid'];
$Title[$i] = $picture['title'] ? $picture['title'] : $picture['filename'];
$i++;
}
/** set variables to jquery.slideshow.js */
set_js_var('Time', $slideshow);
set_js_var('Pid', $pid);
/*if (!$i) {
$Pic[0] = 'images/thumb_document.jpg';
}*/
// Add the hit if slideshow hits are enabled in config
if ((!USER_IS_ADMIN && $CONFIG['count_admin_hits'] == 0 || $CONFIG['count_admin_hits'] == 1) && $CONFIG['slideshow_hits'] != 0) {
// Add 1 to hit counter
if (!in_array($Pid['0'], $USER['liv']) && $superCage->cookie->keyExists($CONFIG['cookie_name'] . '_data')) {
add_hit($Pid['0']);
if (count($USER['liv']) > 4) {
array_shift($USER['liv']);
}
array_push($USER['liv'], $Pid['0']);
user_save_profile();
}
}
/** show slide show on first time*/
if ($ajax_show == 0) {
theme_slideshow($Pic['0'], $Title['0']);
}
/** now we make a array to encode*/
$dataArray = array(
'url' => $Pic['0'],
'title' => $Title['0'],
'pid' => $Pid['0'],
);
$dataJson = json_encode($dataArray);
/** send variable to javascript script*/
if ($ajax_show == 1) {
header("Content-Type: text/plain");
echo $dataJson;
}
}
// Return the url for a picture, allows to have pictures spreaded over multiple servers
/**
* get_pic_url()
*
* Return the url for a picture
*
* @param array $pic_row
* @param string $mode
* @param boolean $system_pic
* @return string
**/
function& get_pic_url(&$pic_row, $mode, $system_pic = false)
{
global $CONFIG, $THEME_DIR;
static $pic_prefix = array();
static $url_prefix = array();
if (!count($pic_prefix)) {
$pic_prefix = array(
'thumb' => $CONFIG['thumb_pfx'],
'normal' => $CONFIG['normal_pfx'],
'orig' => $CONFIG['orig_pfx'],
'fullsize' => '',
);
$url_prefix = array(
0 => $CONFIG['fullpath'],
);
}
$mime_content = cpg_get_type($pic_row['filename']);
// If $mime_content is empty there will be errors, so only perform the array_merge if $mime_content is actually an array
if (is_array($mime_content)) {
$pic_row = array_merge($pic_row, $mime_content);
}
$filepathname = null;
// Code to handle custom thumbnails
// If fullsize or normal mode use regular file
if ($mime_content['content'] != 'image' && $mode == 'normal') {
$mode = 'fullsize';
} elseif (($mime_content['content'] != 'image' && $mode == 'thumb') || $system_pic) {
$thumb_extensions = array(
'.gif',
'.png',
'.jpg'
);
// Check for user-level custom thumbnails
// Create custom thumb path and erase extension using filename; Erase filename's extension
if (array_key_exists('url_prefix', $pic_row)) {
$custom_thumb_path = $url_prefix[$pic_row['url_prefix']];
} else {
$custom_thumb_path = '';
}
$custom_thumb_path .= $pic_row['filepath'] . (array_key_exists($mode, $pic_prefix) ? $pic_prefix[$mode] : '');
$file_base_name = str_ireplace('.' . $mime_content['extension'], '', basename($pic_row['filename']));
// Check for file-specific thumbs
foreach ($thumb_extensions as $extension) {
if (file_exists($custom_thumb_path . $file_base_name . $extension)) {
$filepathname = $custom_thumb_path . $file_base_name . $extension;
break;
}
}
if (!$system_pic) {
// Check for extension-specific thumbs
if (is_null($filepathname)) {
foreach ($thumb_extensions as $extension) {
if (file_exists($custom_thumb_path . $mime_content['extension'] . $extension)) {
$filepathname = $custom_thumb_path . $mime_content['extension'] . $extension;
break;
}
}
}
// Check for content-specific thumbs
if (is_null($filepathname)) {
foreach ($thumb_extensions as $extension) {
if (file_exists($custom_thumb_path . $mime_content['content'] . $extension)) {
$filepathname = $custom_thumb_path . $mime_content['content'] . $extension;
break;
}
}
}
}
// Use default thumbs
if (is_null($filepathname)) {
// Check for default theme- and global-level thumbs
$thumb_paths[] = $THEME_DIR.'images/'; // Used for custom theme thumbs
$thumb_paths[] = 'images/thumbs/'; // Default Coppermine thumbs
foreach ($thumb_paths as $default_thumb_path) {
if (is_dir($default_thumb_path)) {
if (!$system_pic) {
foreach ($thumb_extensions as $extension) {
// Check for extension-specific thumbs
if (file_exists($default_thumb_path . $CONFIG['thumb_pfx'] . $mime_content['extension'] . $extension)) {
$filepathname = $default_thumb_path . $CONFIG['thumb_pfx'] . $mime_content['extension'] . $extension;
//thumb cropping - if we display a system thumb we calculate the dimension by any and not ex
$pic_row['system_icon'] = true;
break 2;
}
}
foreach ($thumb_extensions as $extension) {
// Check for media-specific thumbs (movie,document,audio)
if (file_exists($default_thumb_path . $CONFIG['thumb_pfx'] . $mime_content['content'] . $extension)) {
$filepathname = $default_thumb_path . $CONFIG['thumb_pfx'] . $mime_content['content'] . $extension;
//thumb cropping
$pic_row['system_icon'] = true;
break 2;
}
}
} else {
// Check for file-specific thumbs for system files
foreach ($thumb_extensions as $extension) {
if (file_exists($default_thumb_path . $CONFIG['thumb_pfx'] . $file_base_name . $extension)) {
$filepathname = $default_thumb_path . $CONFIG['thumb_pfx'] . $file_base_name . $extension;
//thumb cropping
$pic_row['system_icon'] = true;
break 2;
}
} // foreach $thumb_extensions
} // else $system_pic
} // if is_dir($default_thumb_path)
} // foreach $thumbpaths
} // if is_null($filepathname)
if ($filepathname) {
$filepathname = path2url($filepathname);
}
}
if (is_null($filepathname)) {
$localpath = $pic_row['filepath'] . $pic_prefix[$mode] . $pic_row['filename'];
// Check here that the filename we are going to return exists
// If it doesn't exist we return a placeholder image
// We then log the missing file for the admin's attention
if (file_exists($url_prefix[$pic_row['url_prefix']] . $localpath)) {
$filepathname = $url_prefix[$pic_row['url_prefix']] . path2url($localpath);
} else {
$filepathname = 'images/thumbs/thumb_nopic.png';
$pic_row['system_icon'] = true;
if ($CONFIG['log_mode'] != 0) {
log_write("File {$url_prefix[$pic_row['url_prefix']]}$localpath is missing.");
}
}
}
// Added hack: "&& !isset($pic_row['mode'])" thumb_data filter isn't executed for the fullsize image
if ($mode == 'thumb' && !isset($pic_row['mode'])) {
$pic_row['url'] = $filepathname;
$pic_row['mode'] = $mode;
$pic_row = CPGPluginAPI::filter('thumb_data', $pic_row);
} elseif ($mode != 'thumb') {
$pic_row['url'] = $filepathname;
$pic_row['mode'] = $mode;
} else {
$pic_row['url'] = $filepathname;
}
$pic_row = CPGPluginAPI::filter('picture_url', $pic_row);
return $pic_row['url'];
} // function get_pic_url
/**
* cpg_get_default_lang_var()
*
* Return a variable from the default language file
*
* @param $language_var_name
* @param unknown $override_language
* @return
**/
function& cpg_get_default_lang_var($language_var_name, $override_language = null)
{
global $CONFIG;
if (is_null($override_language)) {
if (isset($CONFIG['default_lang'])) {
$language = $CONFIG['default_lang'];
} else {
global $$language_var_name;
return $$language_var_name;
}
} else {
$language = $override_language;
}
include 'lang/english.php';
include 'lang/'.$language.'.php';
return $$language_var_name;
} // function cpg_get_default_lang_var
// Returns a variable from the current language file
// If variable doesn't exists gets value from english_us lang file
/**
* cpg_lang_var()
*
* @param $varname
* @param unknown $index
* @return
**/
function& cpg_lang_var($varname, $index = null)
{
global $$varname;
$lang_var =& $$varname;
if (isset($lang_var)) {
if (!is_null($index) && !isset($lang_var[$index])) {
include 'lang/english.php';
return $lang_var[$index];
} elseif (is_null($index)) {
return $lang_var;
} else {
return $lang_var[$index];
}
} else {
include 'lang/english.php';
return $lang_var;
}
} // function cpg_lang_var
/**
* cpg_debug_output()
*
* defined new debug_output function here in functions.inc.php instead of theme.php with different function names to avoid incompatibilities with users not updating their themes as required. Advanced info is only output if (GALLERY_ADMIN_MODE == TRUE)
*
**/
function cpg_debug_output()
{
global $USER, $USER_DATA, $CONFIG, $cpg_time_start, $query_stats, $queries, $lang_cpg_debug_output, $CPG_PHP_SELF, $superCage, $CPG_PLUGINS, $LINEBREAK;
if ($CONFIG['performance_timestamp'] == 0 || (date('Y-m-d', $CONFIG['performance_timestamp']) < date('Y-m-d'))) {
// The metering data in the config table are outdated, let's write fresh values.
// Currently happens each day. To extend the metering period to a whole week,
// use 'Y-m-W' for both date functions above. Use 'Y-m' to extend the period over
// one month and subsequently 'Y' for an entire year.
$CONFIG['performance_timestamp'] = time();
cpg_config_set('performance_timestamp', $CONFIG['performance_timestamp']);
$CONFIG['performance_page_generation_time'] = 0;
$CONFIG['performance_page_query_time'] = 0;
$CONFIG['performance_page_query_count'] = 0;
}
$time_end = cpgGetMicroTime();
$time = round(($time_end - $cpg_time_start) * 1000, 2);
if ($CONFIG['performance_page_generation_time'] < $time) {
$CONFIG['performance_page_generation_time'] = $time;
cpg_config_set('performance_page_generation_time', $CONFIG['performance_page_generation_time']);
}
$query_count = count($query_stats);
$total_query_time = round(array_sum($query_stats), 2);
if ($CONFIG['performance_page_query_time'] < $total_query_time) {
$CONFIG['performance_page_query_time'] = $total_query_time;
cpg_config_set('performance_page_query_time', $CONFIG['performance_page_query_time']);
}
if ($CONFIG['performance_page_query_count'] < $query_count) {
$CONFIG['performance_page_query_count'] = $query_count;
cpg_config_set('performance_page_query_count', $CONFIG['performance_page_query_count']);
}
$debug_underline = '
------------------
';
$debug_separate = '
==========================
';
$debug_toggle_link = $lang_cpg_debug_output['debug_output'] . ': '. $lang_cpg_debug_output['show_hide'].'';
$debug_help = ' '. cpg_display_help('f=empty.htm&h=lang_cpg_debug_output%5Bdebug_output_explain%5D&t=lang_cpg_debug_output%5Bcopy_and_paste_instructions%5D', 470, 245);
$debug_phpinfo_link = GALLERY_ADMIN_MODE ? '' . cpg_fetch_icon('phpinfo', 1) . $lang_cpg_debug_output['phpinfo'] . ' ' : '';
echo <<< EOT
';
} // function cpg_debug_output
/**
* cpg_phpinfo_mod()
*
* phpinfo-related functions:
*
* @param $search
* @return
**/
function cpg_phpinfo_mod($search)
{
static $pieces = array();
if (!$pieces) {
// this could be done much better with regexpr - anyone who wants to change it: go ahead
ob_start();
phpinfo(INFO_MODULES);
$string = ob_get_contents();
//$module = $string;
$delimiter = '#cpgdelimiter#';
ob_end_clean();
// find out the first occurence of "
';
}
}
if ($output_type == 'table') {
ob_start();
endtable();
$return .= ob_get_contents();
ob_end_clean();
} else {
$return .= $debug_separate;
}
return $return;
} // function cpg_phpinfo_mod_output
/**
* cpg_phpinfo_mysql_version()
*
* @return
**/
function cpg_phpinfo_mysql_version()
{
$result = cpg_db_query("SELECT VERSION()");
list($version) = $result->fetchRow(true);
return $version;
} // function cpg_phpinfo_mysql_version
function cpg_config_output($key)
{
global $CONFIG, $LINEBREAK;
return $key . ': ' . $CONFIG[$key] . $LINEBREAK;
} // function cpg_config_output
// THEME AND LANGUAGE SELECTION
/**
* languageSelect()
*
* @param $parameter
* @return
**/
function languageSelect($parameter)
{
global $CONFIG, $lang_language_selection, $lang_common, $CPG_PHP_SELF, $LINEBREAK;
$return = '';
// get the current language
//use the default language of the gallery
//$cpgCurrentLanguage = $CONFIG['lang']; //not used
// Forget all the nonsense sanitization code that used to reside here - redefine the variable for the base URL using the function that we already have for that purpose
$cpgChangeUrl = cpgGetScriptNameParams('lang') . 'lang=';
// Make sure that the language table exists in the first place -
// return without return value if the table doesn't exist because
// the upgrade script hasn't been run
$results = cpg_db_query("SHOW TABLES LIKE '{$CONFIG['TABLE_LANGUAGE']}'");
if (!$results->numRows()) {
return;
}
$results->free();
$lang_language_data = [];
// get list of available languages
$results = cpg_db_query("SELECT * FROM {$CONFIG['TABLE_LANGUAGE']}");
while ( ($row = $results->fetchArray()) ) {
if ($row['available'] == 'YES' && $row['enabled'] == 'YES' && file_exists('lang/'.$row['lang_id'].'.php')) {
$lang_language_data[$row['lang_id']] = $row;
}
} // while
$results->free();
// sort the array by English name
ksort($lang_language_data);
$value = strtolower($CONFIG['lang']);
//start the output
switch ($parameter) {
case 'flags':
$return .= '
EOT;
// Try to retrieve the news directly
//$result = cpgGetRemoteFileByURL('http://coppermine-gallery.net/cpg16x_news.htm', 'GET', '', '200'); // disabled, see http://forum.coppermine-gallery.net/index.php/topic,65424.msg325573.html#msg325573
if (empty($result) || strlen($result['body']) < 200) { // retrieving the file failed - let's display it in an iframe then
$cpgurl = COPPERMINE_URL;
print <<< EOT
EOT;
} else { // we have been able to retrieve the remote URL, let's chop the unneeded data and then display it
unset($result['headers']);
unset($result['error']);
// drop everything before the starting body-tag
//$result['body'] = substr($result['body'], strpos($result['body'], ''));
$result['body'] = strstr($result['body'], '');
// drop the starting body tag itself
$result['body'] = str_replace('', '', $result['body']);
// drop the ending body tag and everything after it
$result['body'] = str_replace(strstr($result['body'], ''), '', $result['body']);
// The result should now contain everything between the body tags - let's print it
print $result['body'];
}
print <<< EOT
EOT;
endtable();
print ' ';
$return .= ob_get_contents();
ob_end_clean();
}
return $return;
} // function cpg_alert_dev_version
/**
* cpg_display_help()
*
* @param string $reference
* @param string $width
* @param string $height
* @return
**/
function cpg_display_help($reference = 'f=empty.htm', $width = '600', $height = '350', $icon = 'help')
{
global $CONFIG, $USER, $lang_common;
if ($reference == '' || $CONFIG['enable_help'] == '0') {
return;
}
if ($CONFIG['enable_help'] == '2' && GALLERY_ADMIN_MODE == false) {
return;
}
$help_theme = $CONFIG['theme'];
if (isset($USER['theme'])) {
$help_theme = $USER['theme'];
}
if($icon != '*' && $icon != '?') {
$icon = '';
}
$title_help = $lang_common['help'];
$help_html = '' . $icon . '';
return $help_html;
} // function cpg_display_help
/**
* Multi-dim array sort, with ability to sort by two and more dimensions
* Coded by Ichier2003, available at php.net
* syntax:
* $array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...);
**/
function array_csort()
{
$args = func_get_args();
$marray = array_shift($args);
$msortline = "return(array_multisort(";
$i = 0;
foreach ($args as $arg) {
$i++;
if (is_string($arg)) {
foreach ($marray as $row) {
$sortarr[$i][] = $row[$arg];
}
} else {
$sortarr[$i] = $arg;
}
$msortline .= "\$sortarr[" . $i . "],";
}
$msortline .= "\$marray));";
eval($msortline);
return $marray;
} // function array_csort
function cpg_get_bridge_db_values()
{
global $CONFIG;
// Retrieve DB stored configuration
$results = cpg_db_query("SELECT name, value FROM {$CONFIG['TABLE_BRIDGE']}");
while ( ($row = $results->fetchAssoc()) ) {
$BRIDGE[$row['name']] = $row['value'];
} // while
$results->free();
return $BRIDGE;
} // function cpg_get_bridge_db_values
function cpg_get_webroot_path()
{
global $CPG_PHP_SELF;
$superCage = Inspekt::makeSuperCage();
// get the webroot folder out of a given PHP_SELF of any coppermine page
// what we have: we can say for sure where we are right now: $PHP_SELF (if the server doesn't even have it, there will be problems everywhere anyway)
// let's make those into an array:
if ( ($matches = $superCage->server->getMatched('SCRIPT_FILENAME', '/^[a-z,A-Z0-9_-\/\\:.]+$/')) ) {
$path_from_serverroot[] = $matches[0];
}
/*
$path_from_serverroot[] = $_SERVER["SCRIPT_FILENAME"];
if (isset($_SERVER["PATH_TRANSLATED"])) {
$path_from_serverroot[] = $_SERVER["PATH_TRANSLATED"];
}
*/
if ( ($matches = $superCage->server->getMatched('PATH_TRANSLATED', '/^[a-z,A-Z0-9_-\/\\:.]+$/')) ) {
$path_from_serverroot[] = $matches[0];
}
//$path_from_serverroot[] = $HTTP_SERVER_VARS["SCRIPT_FILENAME"];
//$path_from_serverroot[] = $HTTP_SERVER_VARS["PATH_TRANSLATED"];
// we should be able to tell the current script's filename by removing everything before and including the last slash in $PHP_SELF
$filename = ltrim(strrchr($CPG_PHP_SELF, '/'), '/');
// let's eliminate all those vars that don't contain the filename (and replace the funny notation from windows machines)
foreach ($path_from_serverroot as $key) {
$key = str_replace('\\', '/', $key); // replace the windows notation
$key = str_replace('//', '/', $key); // replace duplicate forwardslashes
if (strstr($key, $filename) != FALSE) { // eliminate all that don't contain the filename
$path_from_serverroot2[] = $key;
}
}
// remove double entries in the array
$path_from_serverroot3 = array_unique($path_from_serverroot2);
// in the best of all worlds, the array is not empty
if (is_array($path_from_serverroot3)) {
$counter = 0;
foreach ($path_from_serverroot3 as $key) {
// easiest possible solution: $PHP_SELF is contained in the array - if yes, we're lucky (in fact we could have done this before, but I was going to leave room for other checks to be inserted before this one)
if (strstr($key, $CPG_PHP_SELF) != FALSE) { // eliminate all that don't contain $PHP_SELF
$path_from_serverroot4[] = $key;
$counter++;
}
}
} else {
// we're f***ed: the array is empty, there's no server var we could actually use
$return = '';
}
if ($counter == 1) { //we have only one entry left - we're happy
$return = $path_from_serverroot4[0];
} elseif ($counter == 0) { // we're f***ed: the array is empty, there's no server var we could actually use
$return = '';
} else { // there is more than one entry, and they differ. For now, let's use the first one. Maybe we could do some advanced checking later
$return = $path_from_serverroot4[0];
}
// strip the content from $PHP_SELF from the $return var and we should (hopefully) have the absolute path to the webroot
$return = str_replace($CPG_PHP_SELF, '', $return);
// the return var should at least contain a slash - if it doesn't, add it (although this is more or less wishfull thinking)
if ($return == '') {
$return = '/';
}
return $return;
} // function cpg_get_webroot_path
/**
* Function to get the search string if the picture is viewed from google, lycos or yahoo search engine
*/
function get_search_query_terms($engine = 'google')
{
$superCage = Inspekt::makeSuperCage();
//Using getRaw(). $referer is sanitized below wherever needed
$referer = urldecode($superCage->server->getRaw('HTTP_REFERER'));
$query_array = array();
switch ($engine) {
case 'google':
// Google query parsing code adapted from Dean Allen's
// Google Hilite 0.3. http://textism.com
$query_terms = preg_replace('/^.*q=([^&]+)&?.*$/i', '$1', $referer);
$query_terms = preg_replace('/\'|"/', '', $query_terms);
$query_array = preg_split('/[\s,\+\.]+/', $query_terms);
break;
case 'lycos':
$query_terms = preg_replace('/^.*query=([^&]+)&?.*$/i', '$1', $referer);
$query_terms = preg_replace('/\'|"/', '', $query_terms);
$query_array = preg_split('/[\s,\+\.]+/', $query_terms);
break;
case 'yahoo':
$query_terms = preg_replace('/^.*p=([^&]+)&?.*$/i', '$1', $referer);
$query_terms = preg_replace('/\'|"/', '', $query_terms);
$query_array = preg_split('/[\s,\+\.]+/', $query_terms);
break;
} // switch $engine
return $query_array;
} // function get_search_query_terms
function is_referer_search_engine($engine = 'google')
{
//$siteurl = get_settings('home');
$superCage = Inspekt::makeSuperCage();
//Using getRaw(). $referer is sanitized below wherever needed
$referer = urldecode($superCage->server->getRaw('HTTP_REFERER'));
if (!$engine) {
return 0;
}
switch ($engine) {
case 'google':
if (preg_match('|^http://(www)?\.?google.*|i', $referer)) {
return 1;
}
break;
case 'lycos':
if (preg_match('|^http://search\.lycos.*|i', $referer)) {
return 1;
}
break;
case 'yahoo':
if (preg_match('|^http://search\.yahoo.*|i', $referer)) {
return 1;
}
break;
} // switch $engine
return 0;
} // end is_referer_search_engine
/**
* cpg_get_custom_include()
*
* @param string $path
* @return
**/
function cpg_get_custom_include($path = '')
{
global $CONFIG, $CPG_PHP_SELF, $REFERER, $CPG_REFERER, $LINEBREAK, $BRIDGE, $USER, $USER_DATA, $THEME_DIR, $ICON_DIR, $FAVPICS, $RESTRICTEDWHERE, $FORBIDDEN_SET_DATA, $CURRENT_ALBUM_KEYWORD, $CURRENT_CAT_DEPTH, $FORBIDDEN_SET, $CURRENT_CAT_NAME, $CPG_PLUGINS, $JS;
$return = '';
// check if path is set in config
if ($path == '') {
return $return;
}
// check if the include file exists
if (!file_exists($path)) {
return $return;
}
ob_start();
include $path;
$return = ob_get_contents();
ob_end_clean();
// crude sub-routine to remove the most basic "no-no" stuff from possible includes
// could need improvement
$return = str_replace('', '', $return);
$return = str_replace('', '', $return);
$return = str_replace('', '', $return);
$return = str_replace('', '', $return);
$return = str_replace('', '', $return);
$return = str_replace('', '', $return);
return $return;
} // function cpg_get_custom_include
/**
* filter_content()
*
* Replace strings that match badwords with tokens indicating it has been filtered.
*
* @param string or array $str
* @return string or array
**/
function filter_content($str)
{
global $lang_bad_words, $CONFIG, $ercp;
if ($CONFIG['filter_bad_words']) {
static $ercp = array();
if (!count($ercp)) {
foreach ($lang_bad_words as $word) {
$ercp[] = '/' . ($word[0] == '*' ? '': '\b') . str_replace('*', '', $word) . ($word[(strlen($word)-1)] == '*' ? '': '\b') . '/i';
}
}
if (is_array($str)) {
$new_str = array();
foreach ($str as $key => $element) {
$new_str[$key] = filter_content($element);
}
$str = $new_str;
} else {
$stripped_str = strip_tags($str);
$str = preg_replace($ercp, '(...)', $stripped_str);
}
}
return $str;
} // function filter_content
function utf_strtolower($str)
{
if (!function_exists('mb_strtolower')) {
require 'include/mb.inc.php';
}
return mb_strtolower($str);
} // function utf_strtolower
function utf_substr($str, $start, $end = null)
{
if (!function_exists('mb_substr')) {
require 'include/mb.inc.php';
}
return mb_substr($str, $start, $end);
} // function utf_substr
function utf_strlen($str)
{
if (!function_exists('mb_strlen')) {
require 'include/mb.inc.php';
}
return mb_strlen($str);
} // function utf_strlen
function utf_ucfirst($str)
{
if (!function_exists('mb_strtoupper')) {
require 'include/mb.inc.php';
}
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
} // function utf_ucfirst
/*
This function replaces special UTF characters to their ANSI equivelant for
correct processing by MySQL, keywords, search, etc. since a bug has been
found: http://coppermine-gallery.net/forum/index.php?topic=17366.0
*/
function utf_replace($str)
{
return preg_replace('#[\xC2][\xA0]|[\xE3][\x80][\x80]#', ' ', $str);
} // function utf_replace
function replace_forbidden($str)
{
static $forbidden_chars;
if (!is_array($forbidden_chars)) {
global $CONFIG, $mb_utf8_regex;
if (function_exists('html_entity_decode')) {
$chars = html_entity_decode($CONFIG['forbiden_fname_char'], ENT_QUOTES, 'UTF-8');
} else {
$chars = str_replace(array('&', '"', '<', '>', ' ', '''), array('&', '"', '<', '>', ' ', "'"), $CONFIG['forbiden_fname_char']);
}
preg_match_all("#$mb_utf8_regex".'|[\x00-\x7F]#', $chars, $forbidden_chars);
}
/**
* $str may also come from $_POST, in this case, all &, ", etc will get replaced with entities.
* Replace them back to normal chars so that the str_replace below can work.
*/
$str = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $str);
$return = str_replace($forbidden_chars[0], '_', $str);
$condition = array (
'transliteration' => true,
'special_chars' => true
);
$condition = CPGPluginAPI::filter('replace_forbidden_conditions', $condition);
/**
* Transliteration
*/
if ($condition['transliteration']) {
require_once 'include/transliteration.inc.php';
$return = transliteration_process($return, '_');
}
/**
* Replace special chars
*/
if ($condition['special_chars']) {
$return = str_replace('%', '', rawurlencode($return));
}
/**
* Fix the obscure, misdocumented "feature" in Apache that causes the server
* to process the last "valid" extension in the filename (rar exploit): replace all
* dots in the filename except the last one with an underscore.
*/
// This could be concatenated into a more efficient string later, keeping it in three
// lines for better readability for now.
$extension = ltrim(substr($return, strrpos($return, '.')), '.');
$filenameWithoutExtension = str_replace('.' . $extension, '', $return);
$return = str_replace('.', '_', $filenameWithoutExtension) . '.' . $extension;
return $return;
} // function replace_forbidden
/**
* resetDetailHits()
*
* Reset the detailed hits stored in hit_stats table for the given pid
*
* @param int or array $pid
**/
function resetDetailHits($pid)
{
global $CONFIG;
if (is_array($pid)) {
if (!count($pid)) {
return;
} else {
$clause = "pid IN (".implode(',', $pid).")";
}
} else {
$clause = "pid = '$pid'";
}
cpg_db_query("DELETE FROM {$CONFIG['TABLE_HIT_STATS']} WHERE $clause");
} // function resetDetailHits
/**
* resetDetailVotes()
*
* Reset the detailed votes stored in vote_stats table for the given pid
*
* @param int or array $pid
**/
function resetDetailVotes($pid)
{
global $CONFIG;
if (is_array($pid)) {
if (!count($pid)) {
return;
} else {
$clause = " IN (".implode(',', $pid).")";
}
} else {
$clause = " = '$pid'";
}
cpg_db_query("DELETE FROM {$CONFIG['TABLE_VOTE_STATS']} WHERE pid $clause");
cpg_db_query("DELETE FROM {$CONFIG['TABLE_VOTES']} WHERE pic_id $clause");
} // function resetDetailVotes
/**
* cpgValidateColor()
*
* Validate a string: is a color code in x11 or hex?
*
* Returns the validated color string (hex with a leading #-sign or x11 color-code, or nothing if not valid)
*
* @param string $color
* @return $color
**/
function cpgValidateColor($color)
{
$x11ColorNames = array('white', 'ivory', 'lightyellow', 'yellow', 'snow', 'floralwhite', 'lemonchiffon', 'cornsilk', 'seashell', 'lavenderblush', 'papayawhip', 'blanchedalmond', 'mistyrose', 'bisque', 'moccasin', 'navajowhite', 'peachpuff', 'gold', 'pink', 'lightpink', 'orange', 'lightsalmon', 'darkorange', 'coral', 'hotpink', 'tomato', 'orangered', 'deeppink', 'fuchsia', 'magenta', 'red', 'oldlace', 'lightgoldenrodyellow', 'linen', 'antiquewhite', 'salmon', 'ghostwhite', 'mintcream', 'whitesmoke', 'beige', 'wheat', 'sandybrown', 'azure', 'honeydew', 'aliceblue', 'khaki', 'lightcoral', 'palegoldenrod', 'violet', 'darksalmon', 'lavender', 'lightcyan', 'burlywood', 'plum', 'gainsboro', 'crimson', 'palevioletred', 'goldenrod', 'orchid', 'thistle', 'lightgrey', 'tan', 'chocolate', 'peru', 'indianred', 'mediumvioletred', 'silver', 'darkkhaki', 'rosybrown', 'mediumorchid', 'darkgoldenrod', 'firebrick', 'powderblue', 'lightsteelblue', 'paleturquoise', 'greenyellow', 'lightblue', 'darkgray', 'brown', 'sienna', 'yellowgreen', 'darkorchid', 'palegreen', 'darkviolet', 'mediumpurple', 'lightgreen', 'darkseagreen', 'saddlebrown', 'darkmagenta', 'darkred', 'blueviolet', 'lightskyblue', 'skyblue', 'gray', 'olive', 'purple', 'maroon', 'aquamarine', 'chartreuse', 'lawngreen', 'mediumslateblue', 'lightslategray', 'slategray', 'olivedrab', 'slateblue', 'dimgray', 'mediumaquamarine', 'cornflowerblue', 'cadetblue', 'darkolivegreen', 'indigo', 'mediumturquoise', 'darkslateblue', 'steelblue', 'royalblue', 'turquoise', 'mediumseagreen', 'limegreen', 'darkslategray', 'seagreen', 'forestgreen', 'lightseagreen', 'dodgerblue', 'midnightblue', 'aqua', 'cyan', 'springgreen', 'lime', 'mediumspringgreen', 'darkturquoise', 'deepskyblue', 'darkcyan', 'teal', 'green', 'darkgreen', 'blue', 'mediumblue', 'darkblue', 'navy', 'black');
if (in_array(strtolower($color), $x11ColorNames) == TRUE) {
return $color;
} else {
$color = ltrim($color, '#'); // strip a leading #-sign if there is one
if (preg_match('/^[a-f\d]+$/i', strtolower($color)) == TRUE && strlen($color) <= 6) {
$color = '#' . strtoupper($color);
return $color;
}
}
} // function cpgValidateColor
/**
* cpgStoreTempMessage()
*
* Store a temporary message to the database to carry over from one page to the other
*
* @param string $message
* @return $message_id
**/
function cpgStoreTempMessage($message)
{
global $CONFIG;
$message = urlencode($message);
// come up with a unique message id
$message_id = md5(uniqid(mt_rand(), true));
// write the message to the database
$user_id = USER_ID;
$time = time();
// Insert the record in database
$query = "INSERT INTO {$CONFIG['TABLE_TEMP_MESSAGES']} "
." SET "
." message_id = '$message_id', "
." user_id = '$user_id', "
." time = '$time', "
." message = '$message'";
cpg_db_query($query);
// return the message_id
return $message_id;
} // function cpgStoreTempMessage
/**
* cpgFetchTempMessage()
*
* Fetch a temporary message from the database and then delete it.
*
*
*
* @param string $message_id
* @return $message
**/
function cpgFetchTempMessage($message_id)
{
global $CONFIG;
//$user_id = USER_ID;
//$time = time();
$message = '';
// Read the record in database
$query = "SELECT message FROM {$CONFIG['TABLE_TEMP_MESSAGES']} "
. " WHERE message_id = '$message_id' LIMIT 1";
$result = cpg_db_query($query);
if ($result->numRows() > 0) {
$row = $result->fetchRow();
$message = urldecode($row[0]);
}
$result->free();
// delete the message once fetched
$query = "DELETE FROM {$CONFIG['TABLE_TEMP_MESSAGES']} WHERE message_id = '$message_id'";
cpg_db_query($query);
// return the message
return $message;
} // function cpgFetchTempMessage
/**
* cpgCleanTempMessage()
*
* Clean up the temporary messages table (garbage collection).
*
* @param string $seconds
* @return void
**/
function cpgCleanTempMessage($seconds = 3600)
{
global $CONFIG;
$time = time() - (int) $seconds;
// delete the messages older than the specified amount
cpg_db_query("DELETE FROM {$CONFIG['TABLE_TEMP_MESSAGES']} WHERE time < $time");
} // function cpgCleanTempMessage
/**
* cpgRedirectPage()
*
* Redirect to the target page or display an info screen first and then redirect
*
* @param string $targetAddress
* @param string $caption
* @param string $message
* @param string $countdown
* @param string $type (possible values: 'info', 'error', 'warning', 'validation', 'success' -> theme_display_message_block
* @return void
**/
function cpgRedirectPage($targetAddress = '', $caption = '', $message = '', $countdown = 0, $type = 'info')
{
global $CONFIG, $USER_DATA, $lang_common;
$logged_in = (USER_ID || (isset($USER_DATA['user_id']) && is_numeric($USER_DATA['user_id'])));
if (!$logged_in && $CONFIG['allow_unlogged_access'] == 0) {
// Anonymous access to site is not allowed, so need to redirect to login page
$targetAddress = 'login.php';
}
if ($CONFIG['display_redirection_page'] == 0) {
$header_location = (@preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE'))) ? 'Refresh: 0; URL=' : 'Location: ';
if (strpos($targetAddress, '?') == FALSE) {
$separator = '?';
} else {
$separator = '&';
}
header($header_location . $targetAddress . $separator . 'message_id=' . cpgStoreTempMessage($message) . '&message_icon=' . $type . '#cpgMessageBlock');
pageheader($caption, "");
msg_box($caption, $message, $lang_common['continue'], $targetAddress, $type);
pagefooter();
exit;
} else {
pageheader($caption, "");
msg_box($caption, $message, $lang_common['continue'], $targetAddress, $type);
pagefooter();
exit;
}
} // function cpgRedirectPage
/**
* cpgGetScriptNameParams()
*
* Returns the script name and all vars except the ones defined in exception (which could be an array or a var).
* Particularly helpful to create links
*
* @param mixed $exception
* @return $return
**/
function cpgGetScriptNameParams($exception = '')
{
$superCage = Inspekt::makeSuperCage();
if (!is_array($exception)) {
$exception = array(0 => $exception);
}
// get the file name first
$match = $superCage->server->getRaw('SCRIPT_NAME'); // We'll sanitize the script path later
$filename = ltrim(strrchr($match, '/'), '/'); // Drop everything untill (and including) the last slash, this results in the file name only
if (!preg_match('/^(([a-zA-Z0-9_\-]){1,})((\.){1,1})(([a-zA-Z]){2,6})+$/', $filename)) { // the naming pattern we check against: an infinite number of lower and upper case alphanumerals plus allowed special chars dash and underscore, then one (and only one!) dot, then between two and 6 alphanumerals in lower or upper case
$filename = 'index.php'; // If this doesn't match, default to the index page
}
$return = $filename . '?';
// Now get the parameters.
// WARNING: as this function is meant to just return the URL parameters
// (minus the one mentioned in $exception), neither the parameter names
// nor the the values should be sanitized, as we simply don't know here
// against what we're supposed to sanitize.
// For now, I have chosen the safe method, sanitizing the parameters.
// Not sure if this is a bright idea for the future.
// So, use the parameters returned from this function here with the same
// caution that applies to anything the user could tamper with.
// The function is meant to help you generate links (in other words:
// something the user could come up with by typing them just as well),
// so don't abuse this function for anything else.
$matches = $superCage->server->getMatched('QUERY_STRING', '/^[a-zA-Z0-9&=_\/.]+$/');
if ($matches) {
$queryString = explode('&', $matches[0]);
} else {
$queryString = array();
}
foreach ($queryString as $val) {
list($key, $value) = explode('=', $val);
if (!in_array($key, $exception)) {
$return .= $key . "=" . $value . "&";
}
}
return $return;
} // function cpgGetScriptNameParams
/**
* cpgValidateDate()
*
* Returns $date if $date contains a valid date string representation (yyyy-mm-dd). Returns an empty string if not.
*
* @param mixed $date
* @return $return
**/
function cpgValidateDate($date)
{
if (Inspekt::isDate($date)) {
return $date;
} else {
return '';
}
} // function cpgValidateDate
/**
* cpgGetRemoteFileByURL()
*
* Returns array that contains content of a file (URL) retrieved by curl, fsockopen or fopen (fallback). Array consists of:
* $return['headers'] = header array,
* $return['error'] = error number and messages array (if error)
* $return['body'] = actual content of the fetched file as string
*
* @param mixed $url, $method, $data, $redirect
* @return array
**/
function cpgGetRemoteFileByURL($remoteURL, $method = "GET", $redirect = 10, $minLength = '0')
{
global $lang_get_remote_file_by_url, $LINEBREAK;
// FSOCK code snippets taken from http://jeenaparadies.net/weblog/2007/jan/get_remote_file
// Initialize some variables first
$url = parse_url($remoteURL); // chop the URL into protocol, domain, port, folder, file, parameter
if (!isset($url['host'])) {
$url['host'] = '';
}
if (!isset($url['scheme'])) {
$url['scheme'] = '';
}
if (!isset($url['port'])) {
$url['port'] = '';
}
$body = '';
$headers = '';
$error = '';
$timeout = 3;
// Let's try CURL first
if (function_exists('curl_init')) { // don't bother to try curl if it isn't there in the first place
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $remoteURL);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$body = curl_exec($curl);
$headers = curl_getinfo($curl);
curl_close($curl);
if (strlen($body) < $minLength) {
// Fetching the data by CURL obviously failed
$error .= sprintf($lang_get_remote_file_by_url['no_data_returned'], $lang_get_remote_file_by_url['curl']) . ' '.$LINEBREAK;
} else {
// Fetching the data by CURL was successfull. Let's return the data
return array("headers" => $headers, "body" => $body);
}
} else {
// Curl is not available
$error .= $lang_get_remote_file_by_url['curl_not_available'] . ' ' . $LINEBREAK;
}
// Now let's try FSOCKOPEN
if ($url['host'] != '') {
$fp = @fsockopen($url['host'], (!empty($url['port']) ? (int)$url['port'] : 80), $errno, $errstr, $timeout);
if ($fp) { // fsockopen file handle success - start
$path = (!empty($url['path']) ? $url['path'] : "/").(!empty($url['query']) ? "?".$url['query'] : "");
$header = $LINEBREAK . 'Host: '.$url['host'];
//FIXME: '$data' is not defined anywhere?
fputs($fp, $method." ".$path." HTTP/1.0".$header.$LINEBREAK.$LINEBREAK.("post" == strtolower($method) ? $data : ""));
if (!feof($fp)) {
$scheme = fgets($fp);
//list(, $code ) = explode(" ", $scheme);
$headers = 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);
$key = strtolower($key);
$value = trim($value);
if (isset($headers[$key])) {
$headers[$key] .= ',' . trim($value);
} else {
$headers[$key] = trim($value);
}
}
$body = '';
while ( !feof($fp) ) {
$body .= fgets($fp);
}
fclose($fp);
if (strlen($body) < $minLength) {
// Fetching the data by FSOCKOPEN obviously failed
$error .= sprintf($lang_get_remote_file_by_url['no_data_returned'], $lang_get_remote_file_by_url['fsockopen']) . ' ' . $LINEBREAK;
} elseif (in_array('404', $headers) == TRUE) {
// We got a 404 error
$error .= sprintf($lang_get_remote_file_by_url['error_number'], '404') . ' ' . $LINEBREAK;
} else {
// Fetching the data by FSOCKOPEN was successfull. Let's return the data
return array("headers" => $headers, "body" => $body, "error" => $error);
}
} else { // fsockopen file handle failure - start
$error .= $lang_get_remote_file_by_url['fsockopen'] . ': ';
$error .= sprintf($lang_get_remote_file_by_url['error_number'], $errno);
$error .= sprintf($lang_get_remote_file_by_url['error_message'], $errstr);
}
} else {
//$error .= 'No Hostname set. In other words: we\'re trying to retrieve a local file';
}
// Finally, try FOPEN
@ini_set('allow_url_fopen', '1'); // Try to override the existing policy
if ($url['scheme'] != '') {
$protocol = $url['scheme'] . '://';
} else {
$protocol = '';
}
if ($url['port'] != '') {
$port = ':' . (int) $url['port'];
} elseif ($url['host'] != '') {
$port = ':80';
} else {
$port = '';
}
@ini_set('default_socket_timeout', $timeout);
$handle = @fopen($protocol . $url['host'] . $port . $url['path'], 'r');
if ($handle) {
while (!feof($handle)) {
$body .= fread($handle, 1024);
}
fclose($handle);
if (strlen($body) < $minLength) {
$error .= sprintf($lang_get_remote_file_by_url['no_data_returned'], $lang_get_remote_file_by_url['fopen']) . ' ' . $LINEBREAK;
} else {
// Fetching the data by FOPEN was successfull. Let's return the data
return array("headers" => $headers, "body" => $body, "error" => $error);
}
} else { // opening the fopen handle failed as well
// if the script reaches this stage, all available methods failed, so let's return the error messages and give up
return array("headers" => $headers, "body" => $body, "error" => $error);
}
} // function cpgGetRemoteFileByURL
/**
* user_is_allowed()
*
* Check if a user is allowed to edit pictures/albums
*
* @return boolean $check_approve
*/
function user_is_allowed($include_upload_permissions = true)
{
if (GALLERY_ADMIN_MODE) {
return true;
}
$check_approve = false;
global $USER_DATA, $CONFIG;
$superCage = Inspekt::makeSuperCage();
//get albums this user can edit
if ($superCage->get->keyExists('album')) {
$album_id = $superCage->get->getInt('album');
} elseif ($superCage->post->keyExists('aid')) {
$album_id = $superCage->post->getInt('aid');
} else {
//workaround when going straight to modifyalb.php and no album is set in superglobals
if (defined('MODIFYALB_PHP')) {
//check if the user has any album available
$result = cpg_db_query("SELECT aid FROM {$CONFIG['TABLE_ALBUMS']} WHERE owner = " . $USER_DATA['user_id'] . " LIMIT 1");
$temp_album_id = $result->fetchAssoc(true);
$album_id = $temp_album_id['aid'];
} else {
$album_id = 0;
}
}
$result = cpg_db_query("SELECT DISTINCT category FROM {$CONFIG['TABLE_ALBUMS']} WHERE owner = '" . $USER_DATA['user_id'] . "' AND aid='$album_id'");
$allowed_albums = cpg_db_fetch_rowset($result, true);
$cat = $allowed_albums ? $allowed_albums[0]['category'] : '';
if ($cat != '') {
$check_approve = true;
}
// We should also whether user has upload permission to the current album. but do this only if album id is set
if ($album_id && $include_upload_permissions) {
$public_albums = cpg_db_query("SELECT aid FROM {$CONFIG['TABLE_ALBUMS']} WHERE category < " . FIRST_USER_CAT . " AND ((uploads='YES' AND (visibility = '0' OR visibility IN ".USER_GROUP_SET." OR alb_password != '')) OR (owner=".USER_ID.")) AND aid=$album_id");
if (count(cpg_db_fetch_rowset($public_albums, true))) {
$check_approve = true;
define('USER_UPLOAD_ALLOWED', 1);
}
}
//check if admin allows editing after closing category
if ($CONFIG['allow_user_edit_after_cat_close'] == 0) {
//Disallowed -> Check if album is in such a category
$result = cpg_db_query("SELECT DISTINCT aid FROM {$CONFIG['TABLE_ALBUMS']} AS alb INNER JOIN {$CONFIG['TABLE_CATMAP']} AS catm ON alb.category=catm.cid WHERE alb.owner = '" . $USER_DATA['user_id'] . "' AND alb.aid='$album_id' AND catm.group_id='" . $USER_DATA['group_id'] . "'");
$allowed_albums = cpg_db_fetch_rowset($result, true);
if ($allowed_albums && $allowed_albums[0]['aid'] == '' && $cat != (FIRST_USER_CAT + USER_ID)) {
$check_approve = false;
} elseif ($cat == (FIRST_USER_CAT + USER_ID)) {
$check_approve = true;
}
}
return $check_approve;
} // function user_is_allowed
/**
* Function to set/output js files to be included.
*
* This function sets a js file to be included in the head section of the html (in theme_javascript_head() function).
* This function should be called before pageheader function since the js files are included in pageheader.
* If the optional second paramter is passed as true then instead of setting it for later use the html for
* js file inclusion is returned right away
*
* @param string $filename Relative path, from the root of cpg, to the js file
* @param boolean $inline If true then the html is returned
* @return mixed Returns the html for js inclusion or null if inline is false
*/
function js_include($filename, $inline = false)
{
global $JS;
// Proceed with inclusion only if the local file exists or it is in the form of a URL
if (!(file_exists($filename) || is_url($filename))) {
return;
}
// If we need to show the html inline then return the required html
if ($inline) {
return '';
} else {
// Else add the file to js includes array which will later be used in head section
$JS['includes'][] = $filename;
}
} // function js_include
/**
* Function to set a js var from php
*
* This function sets a js var in an array. This array is later converted to json string and outputted
* in the head section of html (in theme_javascript_head function).
* All variables which are set using this function can be accessed in js using the json object named js_vars.
*
* Ex: If you set a variable: set_js_var('myvar', 'myvalue')
* then you can access it in js using : js_vars.myvar
*
* @param string $var Name of the variable by which the value will be accessed in js
* @param mixed $val Value which can be string, int, array or boolean
*/
function set_js_var($var, $val)
{
global $JS;
// Add the variable to global array which will be used in theme_javascript_head() function
$JS['vars'][$var] = $val;
} // function set_js_var
/**
* Function to convert php array to json
*
* This function is equivalent to PHP 5.2 's json_encode. PHP's native function will be used if the
* version is greater than equal to 5.2
*
* @param array $arr Array which is to be converted to json string
* @return string json string
*/
if (!function_exists('json_encode')) {
function json_encode($arr)
{
// If the arr is object then gets its variables
if (is_object($arr)) {
$arr = get_object_vars($arr);
}
$out = array();
$keys = array();
// If arr is array then get its keys
if (is_array($arr)) {
$keys = array_keys($arr);
}
$numeric = true;
// Find whether the keys are numeric or not
if (!empty($keys)) {
$numeric = (array_values($keys) === array_keys(array_values($keys)));
}
foreach ($arr as $key => $val) {
// If the value is array or object then call json_encode recursively
if (is_array($val) || is_object($val)) {
$val = json_encode($val);
} else {
// If the value is not numeric and boolean then escape and quote it
if ((!is_numeric($val) && !is_bool($val))) {
// Escape these characters with a backslash:
// " \ / \n \r \t \b \f
$search = array('\\', "\n", "\t", "\r", "\b", "\f", '"', '/');
$replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\"', '\/');
$val = str_replace($search, $replace, $val);
$val = '"' . $val . '"';
}
if ($val === null) {
$val = 'null';
}
if (is_bool($val)) {
$val = $val ? 'true' : 'false';
}
}
// If key is not numeric then quote it
if (!$numeric) {
$val = '"' . $key . '"' . ':' . $val;
}
$out[] = $val;
}
if (!$numeric) {
$return = '{' . implode(', ', $out) . '}';
} else {
$return = '[' . implode(', ', $out) . ']';
}
return $return;
} // function json_encode
} // if !function_exists(json_encode)
/**
* function cpg_getimagesize()
*
* Try to get the size of an image, this is custom built as some webhosts disable this function or do weird things with it
*
* @param string $image
* @param boolean $force_cpg_function
* @return array $size
*/
function cpg_getimagesize($image, $force_cpg_function = false)
{
if (!function_exists('getimagesize') || $force_cpg_function) {
// custom function borrowed from http://www.wischik.com/lu/programmer/get-image-size.html
$f = @fopen($image, 'rb');
if ($f === false) {
return false;
}
fseek($f, 0, SEEK_END);
$len = ftell($f);
if ($len < 24) {
fclose($f);
return false;
}
fseek($f, 0);
$buf = fread($f, 24);
if ($buf === false) {
fclose($f);
return false;
}
if (ord($buf[0]) == 255 && ord($buf[1]) == 216 && ord($buf[2]) == 255 && ord($buf[3]) == 224 && $buf[6] == 'J' && $buf[7] == 'F' && $buf[8] == 'I' && $buf[9] == 'F') {
$pos = 2;
while (ord($buf[2]) == 255) {
if (ord($buf[3]) == 192 || ord($buf[3]) == 193 || ord($buf[3]) == 194 || ord($buf[3]) == 195 || ord($buf[3]) == 201 || ord($buf[3]) == 202 || ord($buf[3]) == 203) {
break; // we've found the image frame
}
$pos += 2 + (ord($buf[4]) << 8) + ord($buf[5]);
if ($pos + 12 > $len) {
break; // too far
}
fseek($f, $pos);
$buf = $buf[0] . $buf[1] . fread($f, 12);
}
}
fclose($f);
// GIF:
if ($buf[0] == 'G' && $buf[1] == 'I' && $buf[2] == 'F') {
$x = ord($buf[6]) + (ord($buf[7])<<8);
$y = ord($buf[8]) + (ord($buf[9])<<8);
$type = 1;
}
// JPEG:
if (ord($buf[0]) == 255 && ord($buf[1]) == 216 && ord($buf[2]) == 255) {
$y = (ord($buf[7])<<8) + ord($buf[8]);
$x = (ord($buf[9])<<8) + ord($buf[10]);
$type = 2;
}
// PNG:
if (ord($buf[0]) == 0x89 && $buf[1] == 'P' && $buf[2] == 'N' && $buf[3] == 'G' && ord($buf[4]) == 0x0D && ord($buf[5]) == 0x0A && ord($buf[6]) == 0x1A && ord($buf[7]) == 0x0A && $buf[12] == 'I' && $buf[13] == 'H' && $buf[14] == 'D' && $buf[15] == 'R') {
$x = (ord($buf[16])<<24) + (ord($buf[17])<<16) + (ord($buf[18])<<8) + (ord($buf[19])<<0);
$y = (ord($buf[20])<<24) + (ord($buf[21])<<16) + (ord($buf[22])<<8) + (ord($buf[23])<<0);
$type = 3;
}
// added ! from source line since it doesn't work otherwise
if (!isset($x, $y, $type)) {
return false;
}
return array($x, $y, $type, 'height="' . $x . '" width="' . $y . '"');
} else {
$size = getimagesize($image);
if (!$size) {
//false was returned
return cpg_getimagesize($image, true/*force the use of custom function*/);
} elseif (!isset($size[0]) || !isset($size[1])) {
//webhost possibly changed getimagesize functionality
return cpg_getimagesize($image, true/*force the use of custom function*/);
} else {
//function worked as expected, return the results
return $size;
}
}
} // function cpg_getimagesize
function check_rebuild_tree()
{
global $CONFIG;
$result = cpg_db_query("SELECT COUNT(*) FROM {$CONFIG['TABLE_PREFIX']}categories WHERE lft = 0");
list($count) = $result->fetchRow(true);
if ($count) {
return rebuild_tree();
} else {
return false;
}
} // function check_rebuild_tree
function rebuild_tree($parent = 0, $left = 0, $depth = 0, $pos = 0)
{
global $CONFIG;
// the right value of this node is the left value + 1
$right = $left + 1;
if ($CONFIG['categories_alpha_sort'] == 1) {
$sort_query = 'name';
} else {
$sort_query = 'pos';
}
$childpos = 0;
// get all children of this node
$result = cpg_db_query("SELECT cid FROM {$CONFIG['TABLE_PREFIX']}categories WHERE parent = $parent ORDER BY $sort_query, cid");
while ($row = $result->fetchAssoc()) {
// recursive execution of this function for each
// child of this node
// $right is the current right value, which is
// incremented by the rebuild_tree function
if ($row['cid']) {
$right = rebuild_tree($row['cid'], $right, $depth + 1, $childpos++);
}
}
$result->free();
// we've got the left value, and now that we've processed
// the children of this node we also know the right value
cpg_db_query("UPDATE {$CONFIG['TABLE_PREFIX']}categories SET lft = $left, rgt = $right, depth = $depth, pos = $pos WHERE cid = $parent LIMIT 1");
// return the right value of this node + 1
return $right + 1;
} // function rebuild_tree
/**
* Function to fetch an icon
*
*
* @param string $icon_name: the name of the icon to fetch
* @param string $title string: to populate the title attribute of the -tag
* @param string $config_level boolean: If populated, the config option that allows toggling icons on/off will be ignored and the icon will be displayed no matter what
* @param string $check boolean: If populated, the icon will be checked first if it exists
* @param string $extension: name of the extension, default being 'png'
* @param string $type: what should the function return, default (0) being the entire HTML-tag . Specify "1" to make the function return the actual image path only without the embedding HTML tag
* @return string: the fully populated -tag
*/
function cpg_fetch_icon($icon_name, $config_level = 0, $title = '', $check = '', $extension = 'png', $type = 0)
{
global $CONFIG, $ICON_DIR;
static $fonticons;
if ($CONFIG['enable_menu_icons'] < $config_level) {
return;
}
$return = '';
// provide themes with a way to use font icons
if (defined('THEME_USES_ICON_FONT')) {
if (empty($fonticons)) include_once $ICON_DIR . 'icons.php';
if (!empty($fonticons[$icon_name])) {
if (!empty($fonticons['_beg'])) $return .= $fonticons['_beg'];
$return .= $fonticons[$icon_name];
if (!empty($fonticons['_end'])) $return .= $fonticons['_end'];
return $return;
}
}
// sanitize extension
if ($extension != 'jpg' && $extension != 'gif') {
$extension = 'png';
}
$relative_path = $ICON_DIR . $icon_name . '.' . $extension;
// check if file exists
if ($check != '') {
if (file_exists($relative_path) != TRUE) {
return;
}
}
// fall back to distribution icons for missing theme icons
if ($ICON_DIR != 'images/icons/' && !file_exists($relative_path)) {
$relative_path = 'images/icons/' . $icon_name . '.' . $extension;
}
$return .= '= 1000) {
$chop = $remainder - (floor($remainder / pow(10, 3)) * pow(10, 3));
$chop = sprintf("%'{$fill}{$fit}s", $chop); // fill the chop with leading zeros if needed
$remainder = floor($remainder / pow(10, 3));
$return = $lang_decimal_separator[0] . $chop . $return;
}
$return = $remainder . $return;
if ($decimal_page) {
$return .= $lang_decimal_separator[1] . $decimal_page;
}
return $return;
}
/**
* Function get the contents of a folder
*
* @param string $foldername: the relative path
* @param string $fileOrFolder: what should be returned: files or sub-folders. Specify 'file' or 'folder'.
* @param string $validextension: What file extension should be filtered. Specify 'gif' or 'html' or similar.
* @param array $exception_array: optional: specify values that should not be taken into account.
* @return array: a list of file names (without extension)
*/
if (!function_exists('form_get_foldercontent')) {
function form_get_foldercontent ($foldername, $fileOrFolder = 'folder', $validextension = '', $exception_array = array(''))
{
$dir = opendir($foldername);
while ( ($file = readdir($dir)) ) {
if ($fileOrFolder == 'file') {
$extension = ltrim(substr($file, strrpos($file, '.')), '.');
$filenameWithoutExtension = str_replace('.' . $extension, '', $file);
if (is_file($foldername . $file) && $extension == $validextension && in_array($filenameWithoutExtension, $exception_array) != TRUE) {
$return_array[$filenameWithoutExtension] = $filenameWithoutExtension;
}
} elseif ($fileOrFolder == 'folder') {
if ($file != '.' && $file != '..' && in_array($file, $exception_array) != TRUE && is_dir($foldername . $file)) {
$return_array[$file] = $file;
}
}
}
closedir($dir);
natcasesort($return_array);
return $return_array;
}
}
/**
* Function get a list of available languages
*
* @return array: an ascotiative array of language file names (without extension) and language names
*/
if (!function_exists('cpg_get_available_languages')) {
function cpg_get_available_languages()
{
global $CONFIG;
// Make sure that the language table exists in the first place -
// return without return value if the table doesn't exist because
// the upgrade script hasn't been run
$results = cpg_db_query("SHOW TABLES LIKE '{$CONFIG['TABLE_LANGUAGE']}'");
if (!$results->numRows()) {
// The update script has not been run - use the "old school" language file lookup and return the contents
$language_array = form_get_foldercontent('lang/', 'file', 'php');
ksort($language_array);
return $language_array;
}
$results->free();
unset($results);
// get list of available languages
$results = cpg_db_query("SELECT lang_id, english_name, native_name, custom_name FROM {$CONFIG['TABLE_LANGUAGE']} WHERE available='YES' AND enabled='YES' ");
while ( ($row = $results->fetchArray()) ) {
if (file_exists('lang/' . $row['lang_id'] . '.php')) {
if ($row['custom_name'] != '') {
$language_array[$row['lang_id']] = $row['custom_name'];
} elseif ($row['english_name'] != '') {
$language_array[$row['lang_id']] = $row['english_name'];
} else {
$language_array[$row['lang_id']] = str_replace('_', ' ', ucfirst($row['lang_id']));
}
if ($row['native_name'] != '' && $row['native_name'] != $language_array[$row['lang_id']]) {
$language_array[$row['lang_id']] .= ' - ' . $row['native_name'];
}
}
} // while
$results->free();
unset($row);
if (empty($language_array)) {
unset($language_array);
$language_array = form_get_foldercontent('lang/', 'file', 'php');
}
// sort the array by English name
ksort($language_array);
return $language_array;
}
}
function array_is_associative($array)
{
if (is_array($array) && ! empty($array)) {
for ($iterator = count($array) - 1; $iterator; $iterator--) {
if (!array_key_exists($iterator, $array)) {
return true;
}
}
return !array_key_exists(0, $array);
}
return false;
}
function cpg_config_set($name, $value, $insert=false)
{
global $CONFIG;
if (!isset($CONFIG[$name])) {
if ($insert) {
$sql = "INSERT INTO {$CONFIG['TABLE_CONFIG']} (name, value) VALUES ('{$name}', '{$value}')";
cpg_db_query($sql);
if ($CONFIG['log_mode'] != 0) {
log_write("Setting for '$name' set to '$value' by user " . USER_NAME, CPG_CONFIG_LOG);
}
}
} else {
if ($CONFIG[$name] === $value) {
return;
}
$sql = "UPDATE {$CONFIG['TABLE_CONFIG']} SET value = '$value' WHERE name = '$name'";
cpg_db_query($sql);
if ($CONFIG['log_mode'] != 0) {
log_write("Setting for '$name' changed from '{$CONFIG[$name]}' to '$value' by user " . USER_NAME, CPG_CONFIG_LOG);
}
}
$CONFIG[$name] = $value;
}
function cpg_format_bytes($bytes)
{
global $lang_byte_units, $lang_decimal_separator;
foreach ($lang_byte_units as $unit) {
if ($bytes < 1024) {
break;
}
$bytes /= 1024;
}
return number_format($bytes, 2, $lang_decimal_separator[1], $lang_decimal_separator[0]) . ' ' . $unit;
}
function cpg_get_type($filename,$filter=null)
{
global $CONFIG, $CPG_PHP_SELF;
static $FILE_TYPES = array();
if (!$FILE_TYPES) {
// Map content types to corresponding user parameters
$content_types_to_vars = array(
'image' => 'allowed_img_types',
'audio' => 'allowed_snd_types',
'movie' => 'allowed_mov_types',
'document' => 'allowed_doc_types',
);
$result = cpg_db_query('SELECT extension, mime, content, player FROM ' . $CONFIG['TABLE_FILETYPES']);
$CONFIG['allowed_file_extensions'] = '';
while ( ($row = $result->fetchAssoc()) ) {
// Only add types that are in both the database and user defined parameter
if ($CONFIG[$content_types_to_vars[$row['content']]] == 'ALL' || is_int(strpos('/' . $CONFIG[$content_types_to_vars[$row['content']]] . '/', '/' . $row['extension'] . '/'))) {
$FILE_TYPES[$row['extension']] = $row;
$CONFIG['allowed_file_extensions'] .= '/' . $row['extension'];
} elseif ($CPG_PHP_SELF == 'displayimage.php') {
$FILE_TYPES[$row['extension']] = $row;
}
}
$CONFIG['allowed_file_extensions'] = substr($CONFIG['allowed_file_extensions'], 1);
$result->free();
}
if (!is_array($filename)) {
$filename = explode('.', $filename);
}
$EOA = count($filename) - 1;
$filename[$EOA] = strtolower($filename[$EOA]);
if (!is_null($filter) && array_key_exists($filename[$EOA], $FILE_TYPES) && ($FILE_TYPES[$filename[$EOA]]['content'] == $filter)) {
return $FILE_TYPES[$filename[$EOA]];
} elseif (is_null($filter) && array_key_exists($filename[$EOA], $FILE_TYPES)) {
return $FILE_TYPES[$filename[$EOA]];
} else {
return null;
}
}
function is_image(&$file)
{
return cpg_get_type($file, 'image');
}
function is_movie(&$file)
{
return cpg_get_type($file, 'movie');
}
function is_audio(&$file)
{
return cpg_get_type($file, 'audio');
}
function is_document(&$file)
{
return cpg_get_type($file, 'document');
}
function is_flash(&$file)
{
return pathinfo($file, PATHINFO_EXTENSION) == 'swf';
}
function is_known_filetype($file)
{
return is_image($file) || is_movie($file) || is_audio($file) || is_document($file);
}
/**
* Check if a plugin is used to display captcha
**/
function captcha_plugin_enabled($section = 'contact')
{
global $CPG_PLUGINS;
if (!empty($CPG_PLUGINS)) {
foreach ($CPG_PLUGINS as $plugin) {
if ($plugin->enabled && isset($plugin->filters['captcha_'.$section.'_print'])) {
return true;
}
}
}
return false;
}
/**
* get_cat_data()
*
* @param integer $parent
* @param string $ident
**/
function get_cat_data()
{
global $CONFIG, $CAT_LIST, $USER_DATA, $cpg_udb;
if (GALLERY_ADMIN_MODE) {
$sql = "SELECT rgt, cid, name FROM {$CONFIG['TABLE_CATEGORIES']} ORDER BY lft ASC";
} else {
$sql = "SELECT rgt, c.cid, name FROM {$CONFIG['TABLE_CATEGORIES']} AS c NATURAL JOIN {$CONFIG['TABLE_CATMAP']} WHERE group_id IN (" . implode(', ', $USER_DATA['groups']) . ") ORDER BY lft ASC";
}
$result = cpg_db_query($sql);
if ($result->numRows() > 0) {
$rowset = cpg_db_fetch_rowset($result, true);
$right = array();
foreach ($rowset as $subcat) {
if (count($right) > 0) {
// check if we should remove a node from the stack
while ($right && $right[count($right) - 1] < $subcat['rgt']) {
array_pop($right);
}
}
$ident = str_repeat(' ', count($right));
$right[] = $subcat['rgt'];
$CAT_LIST[] = array($subcat['cid'], $ident . $subcat['name']);
// add user categories
if ($subcat['cid'] == 1 && GALLERY_ADMIN_MODE) {
global $cpg_udb;
// query via bridge
$result2 = $cpg_udb->query("SELECT {$cpg_udb->field['user_id']} AS user_id, {$cpg_udb->field['username']} AS user_name FROM {$cpg_udb->usertable} ORDER BY user_name");
$rowset2 = cpg_db_fetch_rowset($result2, true);
foreach ($rowset2 as $user) {
$CAT_LIST[] = array(FIRST_USER_CAT + $user['user_id'], ' ' . $user['user_name']);
}
}
}
}
}
// end function get_cat_data
// Returns an html string containing albums for use in a