File: /var/www/samok164/data/www2/mirneboskrebov.ru/rzgn/r4_libs.php
<?php
if (!defined("STATUS_OK")) define("STATUS_OK", "OK");
if (!defined("STATUS_FAIL")) define("STATUS_FAIL", "FAIL");
if (!function_exists('write_logfile')) {
/**
* Записывает посещение робота в log-файл.
*
* @param type $logfile Имя log-файла.
* @param type $logpath Путь до log-файла.
* @param type $uri Значение запрошенного роботом пути сайта.
*
* @return boolean Возвращает TRUE если удалось записать посещение робота, FALSE в противном случае.
*/
function write_logfile($logfile, $logpath, $uri) {
if (is_writable($logfile)) {
$r4_fp = fopen($logfile, 'a');
if ($r4_fp) {
if (!fwrite($r4_fp, date('Y-m-d H:i:s')."\t{$uri}\n")) {
error_log(date("F j, Y, g:i a")." R4: File write failed!\n", 3, "{$logpath}error.log");
}
fclose($r4_fp);
return TRUE;
}
}
return FALSE;
}
}
if (!function_exists('check_logfile')) {
/**
* Проверка лог-файла:
* если файла не существует, то создаёт пустой;
* если существует и размер превышает максимально допустимый, то усекает до половины разрешённого.
*
* @param string $logfile Имя файла.
* @param string $logpath Путь до файла.
* @param int $maxsize Максимально допустимый размер файла в мегабайтах.
*/
function check_logfile($logfile, $logpath, $maxsize) {
if (!file_exists($logfile)) {
touch($logfile);
}
else {
if (filesize($logfile) > $maxsize * 1024 * 1024) {
$tmp_filename = $logpath.md5(time()).'r4.tmp';
$tmp_f = fopen($tmp_filename, 'w');
$f = fopen($logfile, 'r');
$cursor = $maxsize / 2 * 1024 * 1024;
fseek($f, -$cursor, SEEK_END);
while (($buffer = fgets($f, 4096)) !== false) {
if (preg_match('/^\d{4}-\d{2}-\d{2}/', $buffer)) {
fputs($tmp_f, $buffer, 4096);
}
}
fclose($f);
fclose($tmp_f);
if (file_exists($tmp_filename)) {
rename($tmp_filename, $logfile);
}
}
}
}
}
if (!function_exists('rmdir_recursive')) {
/**
* Рекурсивное удаление каталогов и файлов.
*
* @param string $path Путь до удаляемого каталога.
* @param array $exclude Массив каталогов и файлов, которые не следует удалять.
*
* @return boolean
*/
function rmdir_recursive($path, $exclude=array(), $pattern='') {
$path = rtrim($path, '/');
$undeleted_files = array();
if (is_dir($path)) {
if (($dir = opendir($path)) !== FALSE) {
while (($file = readdir($dir)) !== FALSE) {
if ($file != "." && $file != ".." && !in_array("{$path}/{$file}", $exclude)) {
if (is_dir("{$path}/{$file}")) {
$undeleted_files = array_merge($undeleted_files, rmdir_recursive("{$path}/{$file}", $exclude, $pattern));
}
else {
if (empty($pattern) || preg_match("/{$pattern}/", "{$file}")) {
if (!unlink("{$path}/{$file}")) {
$undeleted_files[] = "{$path}/{$file}";
}
}
}
}
}
closedir($dir);
if (!in_array("{$path}", $exclude)) {
if (!rmdir($path)) {
// $undeleted_files[] = $path;
}
}
}
}
elseif (is_file($path)) {
if (!in_array("{$path}", $exclude)) {
if (empty($pattern) || preg_match("/{$pattern}/", "{$file}")) {
if (!unlink($path)) {
$undeleted_files[] = $path;
}
}
}
}
return $undeleted_files;
}
}
if (!function_exists('get_filenames')) {
/**
* Получает список названий всех файлов в директории и поддиректориях
*
* @param string $dir Каталог, в котором рекурсивно производится поиск файлов.
* @param arrya $exclude Массив каталогов и файлов, которые не следует выводить.
* @param string $pattern Маска (регулярное выражение) файлов.
*
* @return array Массив строк, содержащий список файлов по маске.
*/
function get_filenames($dir, $exclude=array(), $pattern='') {
$filenames = array();
$dir = rtrim($dir, '/');
if (is_dir($dir)) {
if (($dh = opendir($dir)) !== FALSE) {
while (($filename = readdir($dh)) !== FALSE) {
if ($filename == '.' || $filename == '..' || in_array("{$dir}/{$filename}", $exclude)) {
continue;
}
if (is_dir("{$dir}/{$filename}")) {
$filenames = array_merge($filenames, get_filenames("{$dir}/{$filename}", $exclude, $pattern));
}
else {
if (is_file("{$dir}/{$filename}") && preg_match("/{$pattern}/", "{$filename}")) {
$filenames[] = "{$dir}/{$filename}";
}
}
}
closedir($dh);
}
}
elseif (is_dir($dir)) {
$filenames[] = $dir;
}
return $filenames;
}
}
if (!function_exists('json_encode')) {
/**
* Returns the JSON representation of a value.
*
* @param resource $value The value being encoded. Can be any type except a resource.
*
* @return string Returns a JSON encoded string on success or FALSE on failure.
*/
function json_encode($value=false) {
if (is_null($value)) {
return 'null';
}
if ($value === false) {
return 'false';
}
if ($value === true) {
return 'true';
}
if (is_scalar($value)) {
if (is_float($value)) {
return floatval(str_replace(",", ".", strval($value)));
}
if (is_string($value)) {
static $json_replaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($json_replaces[0], $json_replaces[1], $value) . '"';
}
else {
return $value;
}
}
$is_list = true;
for ($i = 0, reset($value); $i < count($value); $i++, next($value)) {
if (key($value) !== $i) {
$is_list = false;
break;
}
}
$result = array();
if ($is_list) {
foreach ($value as $v) {
$result[] = json_encode($v);
}
return '[' . join(',', $result) . ']';
}
else {
foreach ($value as $k => $v) {
$result[] = json_encode($k).':'.json_encode($v);
}
return '{' . join(',', $result) . '}';
}
}
}
if (!function_exists('error_get_last')) {
set_error_handler(
create_function(
'$errno,$errstr,$errfile,$errline,$errcontext',
'
global $__error_get_last_retval__;
$__error_get_last_retval__ = array(
\'type\' => $errno,
\'message\' => $errstr,
\'file\' => $errfile,
\'line\' => $errline
);
return false;
'
)
);
/**
* To simulate error_get_last function in a horrid way for PHP 5 < 5.2.0
*
* @global type $__error_get_last_retval__
* @return null
*/
function error_get_last() {
global $__error_get_last_retval__;
if (!isset($__error_get_last_retval__)) {
return null;
}
return $__error_get_last_retval__;
}
}
if (!function_exists('str_split')) {
function str_split($string){
return preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
}
}