n) = $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 .= '
'; $return .= $lang_language_selection['choose_language'] . ': '; foreach ($lang_language_data as $language) { $return .= $LINEBREAK . '' . $LINEBREAK; } $return .= '' . $LINEBREAK; $return .= '
'; break; case 'table': $return = 'not yet implemented'; break; default: $return .= $LINEBREAK . '
' . $LINEBREAK . '
' . $LINEBREAK; $return .= '' . $LINEBREAK; $return .= '' . $LINEBREAK; $return .= '
' . $LINEBREAK; $return .= '
' . $LINEBREAK; } // switch $parameter return $return; } // function languageSelect /** * themeSelect() * * @param $parameter * @return **/ function themeSelect($parameter) { global $CONFIG,$lang_theme_selection, $lang_common, $CPG_PHP_SELF, $LINEBREAK; $return = ''; $cpgCurrentTheme = cpgGetScriptNameParams('theme') . 'theme='; // get list of available themes $value = $CONFIG['theme']; $theme_dir = 'themes/'; $dir = opendir($theme_dir); while ( ($file = readdir($dir)) ) { if (is_dir($theme_dir . $file) && $file != "." && $file != ".." && $file != '.svn' && $file != 'sample') { $theme_array[] = $file; } } closedir($dir); natcasesort($theme_array); $return .= $LINEBREAK . '
' . $LINEBREAK . '
' . $LINEBREAK; $return .= '' . $LINEBREAK; $return .= '' . $LINEBREAK; $return .= '
' . $LINEBREAK; $return .= '
' . $LINEBREAK; return $return; } // function themeSelect /** * cpg_has_updates() * * @return **/ function cpg_has_updates() { global $CONFIG; if ((time() - $CONFIG['last_updates_check']) > 86400) { require_once 'include/upgrader.inc.php'; $upgc = new CPG_Updater(true); $has = (bool) count($upgc->getUpdates()); cpg_db_query("UPDATE {$CONFIG['TABLE_CONFIG']} SET value = '".time()."' WHERE name = 'last_updates_check'"); return $has; } return false; } /** * cpg_alert_dev_version() * * @return **/ function cpg_alert_dev_version() { global $lang_version_alert, $CONFIG, $REFERER; $return = ''; if (COPPERMINE_VERSION_STATUS != 'stable' && COPPERMINE_VERSION_STATUS != 'RC') { $return = <<< EOT

{$lang_version_alert['version_alert']}

EOT; $return .= sprintf($lang_version_alert['no_stable_version'], COPPERMINE_VERSION, COPPERMINE_VERSION_STATUS); $return .= '
'; } // check if gallery is offline if ($CONFIG['offline'] == 1 && GALLERY_ADMIN_MODE) { $return .= <<< EOT
{$lang_version_alert['gallery_offline']}
EOT; } // notification about any updates available if (cpg_has_updates()) { $return = <<

{$lang_version_alert['updates_available']}

EOT; $return .= ''.$lang_version_alert['view_updates'].''; $return .= ''; } // display news from coppermine-gallery.net if ($CONFIG['display_coppermine_news'] == 1 && GALLERY_ADMIN_MODE) { $help_news = ' ' . cpg_display_help('f=configuration.htm&as=admin_general_coppermine_news&ae=admin_general_coppermine_news_end&top=1', '600', '300'); $news_icon = cpg_fetch_icon('news_show', 2); $news_icon_hide = cpg_fetch_icon('news_hide', 1); ob_start(); starttable('100%'); print <<< EOT
{$news_icon}{$lang_version_alert['coppermine_news']}{$help_news} {$news_icon_hide}{$lang_version_alert['hide']}
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