#!/usr/bin/perl
##########################################################################################
# lyrics.mp3s.ru - v.3.0 
# get lyric
#
# Copyright (c) 2000-2018 WebCreator
# Author: Vokhmianin Vladimir
# 	vladimir@webcreator.ru
##########################################################################################

	use lib '/srv/www/vhosts/mp3s.ru/lib';
	use mp3svars qw(%config);
	use mp3s;
	use wclib qw($dbh);
	use keyphrase;
	use ihitex2;
	use memd qw($memd);
	use Encode;
	use url_modify;
	use strict;
	use vars qw(%FORM);

	%FORM = wclib::get_input(); 

#	my $start = wclib::start_times();

#$ENV{'QUERY_STRING'}=qq~hy_7_ZKHzI89Q&1026574~;

	sub utf8 {
		my $unicodeTextHere=shift;
		Encode::from_to($$unicodeTextHere, 'utf-8', 'windows-1251');
	}

#unless ($ENV{'QUERY_STRING'}=~/\D/ && !$ENV{'QUERY_STRING'}) {
	mp3s::not_found if (mp3s::check_user_agent()==2); 

	my ($crypt_word,$lyric_id,$action)=split(/&/,$ENV{'QUERY_STRING'});

	mp3s::not_found() if (!$crypt_word || !$lyric_id || $lyric_id!~/^\d+$/);

	wclib::db_connect();

#	my $ADM=($ENV{'REMOTE_ADDR'} eq "78.107.248.119" || $ENV{'REMOTE_ADDR'} eq "185.16.138.216")?1:0;
	my $ADM=($ENV{'REMOTE_ADDR'} eq "78.107.248.119")?1:0;

	if ($ENV{'HTTP_X_REQUESTED_WITH'} eq 'XMLHttpRequest' && $ADM==1) {
			print "Status: 200 OK\n";
			print "Content-Type: text/plain; charset=windows-1251\n\n";
			my $ssdd = qq~lyric_id=$FORM{'lyric_id'}\nf_the=$FORM{'f_the'}\nexec=$FORM{'exec'}\ncomp=$FORM{'comp'}\n~;
			utf8(\$ssdd);
			print qq~$ssdd\n~;

		if ($FORM{'action'} eq "save" && $FORM{'lyric_id'}=~m/^\d+$/) {

			memd::memd_connect();

			my $query = qq!
				SELECT EXEC_ID, COMP_ID
				FROM Lyrics
				WHERE LYRIC_ID=?
		 	!;
		 	my $sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		 	$sth -> execute($FORM{'lyric_id'}) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
			my ($_exec_id,$_comp_id) = $sth -> fetchrow_array;
		 	$sth -> finish;

			print qq~select ($_exec_id,$_comp_id)\n~;

		 	my $form_exec=$FORM{'exec'};
		 	utf8(\$form_exec);
			my $form_exec_nospace=$form_exec;
			url_modify::nospace(\$form_exec_nospace);

			my $ch_exec=mp3s::get_ch($form_exec);

			my $f_the=($FORM{'f_the'} eq "true")?1:0;

			# my $find_exec_id = url_modify::find_clone(\$form_exec_nospace);
			my $find_exec_id = url_modify::find_clone(\$form_exec);
			if ($find_exec_id) {

				if ($FORM{'all_exec'} eq "true") {

					$query = qq!
						UPDATE Compositions
						SET EXEC_ID=?
						WHERE EXEC_ID=?
				 	!;
				 	$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				 	$sth -> execute($find_exec_id,$_exec_id) || wclib::panic("Соединение с базой невозможно", $sth->errstr.":".$query);
					$sth -> finish;

					$query = qq!
						SELECT LYRIC_ID
						FROM Lyrics
						WHERE EXEC_ID=?
				 	!;
				 	$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				 	$sth -> execute($_exec_id) || wclib::panic("Соединение с базой невозможно", $sth->errstr.":".$query);
					while (my ($_lyric_id) = $sth->fetchrow_array) {
						isearch3_memcached::set_status(id=>$_lyric_id,scheme=>'LYRICS',status=>'update');
					}
					$sth -> finish;

					$query = qq!
						UPDATE Lyrics
						SET EXEC_ID=?
						WHERE EXEC_ID=?
					!;
					$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> execute($find_exec_id,$_exec_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> finish;

					my $_form_exec=dblib::select_query("NAME","Executors","EXEC_ID=$find_exec_id");
					$query = qq!
						UPDATE NEW_LYRICS
						SET EXEC_ID=?, EXEC_NAME=?
						WHERE EXEC_ID=?
					!;
					$sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> execute($find_exec_id,$_form_exec,$_exec_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> finish;

				}

				$_exec_id = $find_exec_id;
			} else {

				my ($form_exec_v,$form_exec_v_nospace,$ch_exec_v)=("","",$ch_exec);

				my $exec_one=1;
				if ($f_the==1) {
					$ch_exec_v=mp3s::get_ch($form_exec);
					$form_exec_v=$form_exec.", The";
					$form_exec_v_nospace=$form_exec_v;
					url_modify::nospace(\$form_exec_v_nospace);
					$exec_one=0;
				}
				print qq~update exec ($form_exec,$form_exec_nospace,$exec_one,$form_exec_v,$form_exec_v_nospace,$ch_exec,$ch_exec_v,$f_the,$_exec_id)\n~;

				if ($FORM{'all_exec'} eq "true") {

					$query = qq!
						UPDATE Executors
						SET NAME=?, NAME_NOSPACE=?, name_one=?, name_view=?, NAME_VIEW_NOSPACE=?, ch=?, cch=?, f_the=?
						WHERE EXEC_ID=?
					!;
					$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> execute($form_exec,$form_exec_nospace,$exec_one,$form_exec_v,$form_exec_v_nospace,$ch_exec,$ch_exec_v,$f_the,$_exec_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> finish;

					isearch3_memcached::set_status(id=>$_exec_id,scheme=>'ARTISTS',status=>'update');

					$query = qq!
						SELECT LYRIC_ID
						FROM Lyrics
						WHERE EXEC_ID=?
				 	!;
				 	$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				 	$sth -> execute($_exec_id) || wclib::panic("Соединение с базой невозможно", $sth->errstr.":".$query);
					while (my ($_lyric_id) = $sth->fetchrow_array) {
						isearch3_memcached::set_status(id=>$_lyric_id,scheme=>'LYRICS',status=>'update');
					}
					$sth -> finish;

					$query = qq!
						UPDATE NEW_LYRICS
						SET EXEC_NAME=?
						WHERE EXEC_ID=?
					!;
					$sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> execute($form_exec,$_exec_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> finish;

					$memd->delete('exec_'.$form_exec);

				} else {

					$_exec_id = wclib::seq_next("Executors");

					$query = qq!
						INSERT INTO Executors
						(CUST_ID, EXEC_ID, name, NAME_NOSPACE, name_one, name_view, NAME_VIEW_NOSPACE, ch, cch, f_the, c_lyr, date_reg)
						VALUES (200, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, sysdate()) 
					!;
					$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> execute($_exec_id,$form_exec,$form_exec_nospace,$exec_one,$form_exec_v,$form_exec_v_nospace,$ch_exec,$ch_exec_v,$f_the) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
					$sth -> finish;

					isearch3_memcached::create_id(id=>$_exec_id,scheme=>'ARTISTS');

				}

			}

			my $form_comp=$FORM{'comp'};
			utf8(\$form_comp);
			my $form_comp_nospace=$form_comp;
			url_modify::nospace(\$form_comp_nospace);

			my $ch_comp=mp3s::get_ch($form_comp);

			$query = qq!
				SELECT COMP_ID
				FROM Compositions
				WHERE EXEC_ID=? AND NAME_NOSPACE=?
		 	!;
		 	$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		 	$sth -> execute($_exec_id,$form_comp_nospace) || wclib::panic("Соединение с базой невозможно", $sth->errstr.":".$query);
			my ($find_comp_id) = $sth->fetchrow_array;
			$sth -> finish;

			if ($find_comp_id) {
				$_comp_id = $find_comp_id;

				$query = qq!
					UPDATE Compositions
					SET name=?, NAME_NOSPACE=?, ch=?
					WHERE COMP_ID=?
				!;
				$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				$sth -> execute($form_comp,$form_comp_nospace,$ch_comp,$_comp_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				$sth -> finish;

			} else {

				print qq~update comp ($form_comp,$form_comp_nospace,$ch_comp,$_comp_id)\n~;

				$_comp_id = wclib::seq_next("Compositions");

				$query = qq!
					INSERT INTO Compositions
					(CUST_ID, EXEC_ID, COMP_ID, name, NAME_NOSPACE, ch, lyric, date_reg)
					VALUES (200, ?, ?, ?, ?, ?, 1, sysdate()) 
				!;
				$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				$sth -> execute($_exec_id,$_comp_id,$form_comp,$form_comp_nospace,$ch_comp) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				$sth -> finish;

				# isearch3_memcached::create_id(id=>$_comp_id,scheme=>'LYRICS');

			}

			print qq~update lyr ($_exec_id,$_comp_id,$FORM{'lyric_id'})\n~;
			print qq~update new_lyr ($_exec_id,$form_exec,$_comp_id,$form_comp,$FORM{'lyric_id'})\n~;

			$query = qq!
				UPDATE Lyrics
				SET EXEC_ID=?, COMP_ID=?
				WHERE LYRIC_ID=?
			!;
			$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
			$sth -> execute($_exec_id,$_comp_id,$FORM{'lyric_id'}) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
			$sth -> finish;

			$query = qq!
				UPDATE NEW_LYRICS
				SET EXEC_ID=?, EXEC_NAME=?, COMP_ID=?, COMP_NAME=?
				WHERE LYRIC_ID=?
			!;
			$sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
			$sth -> execute($_exec_id,$form_exec,$_comp_id,$form_comp,$FORM{'lyric_id'}) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
			$sth -> finish;

			isearch3_memcached::set_status(id=>$FORM{'lyric_id'},scheme=>'LYRICS',status=>'update');

		} else {
			print "error\n";
			print qq~$ssdd\n~;
		}

		wclib::db_disconnect;
		wclib::exit();
	}

#	unless ($ENV{'HTTP_REFERER'}) { $ENV{'HTTP_REFERER'}="http://lyrics.mp3s.ru"; }
	my $useragent="$ENV{'HTTP_USER_AGENT'}";
	my $useragent_q = $dbh -> quote($useragent);
	my $via="$ENV{'HTTP_VIA'}";
	my $via_q = $dbh -> quote($via);
	my $httpx="$ENV{'HTTP_X_FORWARDED_FOR'}";
	my $httpx_q = $dbh -> quote($httpx);

	my $ip="$ENV{'REMOTE_ADDR'}";
#	if ($httpx =~ /unknown/ || $httpx eq "") {
#		$ip=$ENV{'REMOTE_ADDR'};
#	} else {
#		$ip=$httpx;
#	}

	## ищем символьное соответсвие по ip
	my @numbers = split(/\./, $ip);
	my $ip_number = pack("C4", @numbers);
	my $dns = (gethostbyaddr($ip_number, 2))[0];
	$dns ||= "";
	my $dns_q = $dbh -> quote($dns);

	my $query = qq!
		SELECT l.Info, l.EXEC_ID, e.ch, e.NAME, e.C_REC, l.COMP_ID, c.NAME, c.C_REC, l.LEN, l.date_reg, e.f_the
		FROM Lyrics l
			JOIN Compositions c
			ON c.COMP_ID=l.COMP_ID
			JOIN Executors e
			ON e.EXEC_ID=l.EXEC_ID
		WHERE l.LYRIC_ID=?
 	!;
 	my $sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
 	$sth -> execute($lyric_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	my ($lyric,$exec_id,$exec_ch,$exec_name,$exec_rec,$comp_id,$comp_name,$comp_rec,$len,$date_reg,$f_the) = $sth -> fetchrow_array;
 	$sth -> finish;

	# MemCached connect
	# memd::memd_connect();

	# my ($comp_name,$comp_rec)=();
	# my $key_preload = "comp_rec_".$comp_id;
	# my $memd_preload = $memd->get($key_preload);
	# if (${$memd_preload}[0]) {
	# 	($comp_name,$comp_rec)=@{$memd_preload};
	# } else {
	# 	$query = qq!
	# 		SELECT NAME, C_REC
	# 		FROM Compositions
	# 		WHERE COMP_ID=?
 # 		!;
 # 		$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	#  	$sth -> execute($comp_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	# 	($comp_name,$comp_rec) = $sth->fetchrow_array;
	#  	$sth -> finish;
	# 	my @array = ($comp_name,$comp_rec);
	# 	$memd->set($key_preload, \@array, 3600*24);
	# 	undef @array;
	# }

	# my ($exec_name,$exec_rec)=();
	# $key_preload = "exec_rec_".$exec_id;
	# $memd_preload = $memd->get($key_preload);
	# if (${$memd_preload}[0]) {
	# 	($exec_name,$exec_rec)=@{$memd_preload};
	# } else {
	# 	$query = qq!
	# 		SELECT NAME, C_REC
	# 		FROM Executors
	# 		WHERE EXEC_ID=?
 # 		!;
	#  	$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
 # 		$sth -> execute($exec_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	# 	($exec_name,$exec_rec) = $sth->fetchrow_array;
 # 		$sth -> finish;
	# 	my @array = ($exec_name,$exec_rec);
	# 	$memd->set($key_preload, \@array, 3600*24);
	# 	undef @array;
	# }

	my $crypt_comp_name=mp3s::get_crypt_name($comp_name.$exec_id);
#	$crypt_comp_name=~s/[^a-zA-Z0-9]/_/g;

	my $crypt_comp_name2=$crypt_comp_name;
	$crypt_comp_name2=~s/[^a-zA-Z0-9]/_/;
	$crypt_comp_name=~s/[^a-zA-Z0-9]/_/g;

	unless ($crypt_word eq $crypt_comp_name) {
		mp3s::redirect_301("http://lyrics.mp3s.ru/perl/lyric.pl?$crypt_comp_name&$lyric_id") if ($crypt_comp_name2 ne $crypt_comp_name);
	}

	mp3s::not_found() unless ($crypt_word eq $crypt_comp_name);

#			$query = qq!
#  	 		SELECT COUNT(*)
#				FROM URL_Log
#   			WHERE ip=? AND dns=? AND DATE_SUB(sysdate(),INTERVAL 10 SECOND)<=date_reg
#	 		!;
# 			$sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
# 			$sth -> execute($ip,$dns_q) || wclib::panic("Соединение с базой невозможно", $sth->errstr.":".$query);
#			my ($count) = $sth -> fetchrow_array;
# 			$sth -> finish;

#  INSERT DELAYED IGNORE INTO
			## заносим все в логи
			# $query = qq!
			# 	INSERT IGNORE INTO Lyric_Log
			# 	(LYRIC_ID, COMP_ID, EXEC_ID, ip, LEN, date_add, date_reg)
			# 	VALUES ($lyric_id, $comp_id, $exec_id, '$ip', '$len', '$date_reg', sysdate())
			# !;
			# $dbh -> do($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);

#			if ($count>10) {
#				print "Location: $ENV{'HTTP_REFERER'}\n\n";
#			} else {

#				$query = qq!
#					UPDATE URL
#					SET dl_count=dl_count+1
#					WHERE URL_ID=$url_id
#				!;
#				$dbh -> do($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);

				### > insert into rating
				#wclib::in_rating($url_id,'url');

#				wclib::db_disconnect;
#				print "Location: $url\n\n";

	my $title="текст песни ";
	my $desc="текст песни ";
	my $keyw="текст песни, ";

	my $comp_name_q=wclib::encode_track($comp_name);
	my $exec_name_q=wclib::encode_track($exec_name);
	my $exec_ch_q=wclib::encode_track($exec_ch);

# 	use Encode;
# 	my $cont = "Ленинград - Экспонат";
# #	$cont=~s/\s+/\+/g;
# 	Encode::from_to($cont, 'windows-1251', 'utf-8');
# 	my $track_name_q=wclib::url_encode($cont); #("$exec_name - $comp_name");
	my $track_name_q="";

	my $translate=wclib::url_encode("http://lyrics.mp3s.ru/perl/lyric.pl?$crypt_word&$lyric_id");

	my $flyric=$lyric;
	$flyric=~s/\s+?<br>/\. /ig;

	my ($tdesc,$tkeyw)=keyphrase::keyphrase($flyric,"",25,1);
#	my $ttitle=qq~$exec_name - $comp_name~;

	$title.= "$exec_name - $comp_name";
	$desc.= "$exec_name - $comp_name: $tdesc";
	$keyw.= "$exec_name, $comp_name, lyrics, $tkeyw, ноты, tab, tabs, слова песни";

	# $title.= " | слова песни $comp_name - lyrics.mp3s.ru";
	$title.= " - lyrics.mp3s.ru";

	$title=~s#"##g;
	$desc=~s#"##g;
	$keyw=~s#"##g;

	$lyric=~s/%0D%0A/<br>/sg;
	if ($lyric!~/<br>/) {
		$lyric=~s/\n/<br>/g;
	}
#	$lyric=~s/<br>/\n/ig;
#	$lyric=~s/<//ig;
#	$lyric=~s/>//ig;

	if ($action eq "print") {
		wclib::send_header();
		print qq~
<!DOCTYPE html>
<html>
<head>
    <META NAME="ROBOTS" CONTENT="NOINDEX,NOFOLLOW">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Текст песни $exec_name - $comp_name</title> 
    <style>body {font-family: 'Roboto', sans-serif;font-weight: 300;}</style>
</head>
<body>
<h1>$exec_name - $comp_name</h1>
<div style="display: block;unicode-bidi: embed;font-family: monospace;white-space: pre;">$lyric</div>
<script>print();</script>
</body>
</html>
		~;
		wclib::db_disconnect;
		wclib::exit();
	} elsif ($action eq "save") {
		my $filename="$exec_name - $comp_name.txt";
		$filename=~s/\s+/_/g;
		$lyric=~s/<br ?\/>|<br>/\r\n/g;
		print "Content-type: application/force-download\n";
		print "Content-Disposition: attachment; filename=\"$filename\"\n";
		print "\n";
#		binmode(STDOUT);
		print "Текст песни $exec_name - $comp_name\r\n\r\n$lyric";
		wclib::db_disconnect;
		wclib::exit();
	}


	# MemCached connect
	memd::memd_connect();

	my ($comp_list,$exec_list)=();
	my $key_preload = "lyr_rel_".$lyric_id;
	my $memd_preload = $memd->get($key_preload);
	if (${$memd_preload}[0]) {
		($comp_list,$exec_list)=@{$memd_preload};
	} else {
		$comp_list=get_comp($lyric_id,$exec_id,$exec_name,$exec_name_q);
		$exec_list=get_exec($lyric_id,$comp_id,$comp_name,$comp_name_q);
		my @array = ($comp_list,$exec_list);
		$memd->set($key_preload, \@array, 3600*24);
		undef @array;
	}

	my %src=();
	$query = qq!
		SELECT VID, SRC_ID
		FROM LyricsVideo
		WHERE COMP_ID=?
 	!;
 	$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
 	$sth -> execute($comp_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	while (my ($vid,$src_id) = $sth->fetchrow_array) {
		$src{$src_id}=$vid;
	}
 	$sth -> finish;

# 	my $video2=qq~
# <ul id="tabs_menu">
# <li id="emb_link_1" class="sel"><a href="" onclick="show_emb_tube('kffacxfA7G4');return false;"><img src="/images/_i_youtube.png">&nbsp;YouTube</a> </li> 
# <li id="emb_link_2" class="nonsel"><a href="" onclick="show_emb_dm('xcapwo');return false;"><img src="/images/_i_dailymotion.png">&nbsp;DailyMotion</a> </li>
# <li><span><img id="wait_gif" src="/i/wait.gif" style="visibility:hidden; display:none;">&nbsp;</span></li></ul>
# 	~;

	my $video=(exists $src{'youtube'})?qq~<div class="row-fluid"><div class="col-md-12 mb-4"><h2 class="lyr-title">Видео</h2><div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="https://www.youtube.com/embed/$src{'youtube'}?enablejsapi=1&origin=http://lyrics.mp3s.ru" allowfullscreen></iframe></div></div></div>~:"";
# 	$video.=(exists $src{'youtube'})?qq~
# <div style="padding-top:5px;">
# 	<div id="big_em_span" style="padding:0px;margin:0px;background-color:#FAFAFA;"><object width="500" height="303"><param name="movie" value="http://www.youtube.com/v/$src{'youtube'}&amp;hl=en_US&amp;fs=1&amp;color1=DEEDFB&amp;color2=A2B6CB"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$src{'youtube'}&amp;hl=en_US&amp;fs=1&amp;color1=DEEDFB&amp;color2=A2B6CB" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="500" height="303" ></embed></object></div>
# </div>
# 	~:qq~
# <div id="big_em_span" style="padding:0px;margin:0px">
# 	<div id="videoResultsDiv"></div><script>searchClicked("~.wclib::url_encode("$exec_name - $comp_name").qq~");</script>
# </div>~;
# 	$video.=qq~</div>~;

# 	my $lyric_link = qq~<a href="/view/exec/$exec_name_q/" class="lyric"> Все тексты песен <b>$exec_name</b></a><br><a href="/view/comp/$comp_name_q/" class="lyric"> Все тексты песен с названием <b>$comp_name</b></a>~;
#	$lyric_link .= qq~<br><a href="http://mp3.mp3s.ru/view/track/$exec_name_q/$comp_name_q/" class="lyric"><strong>$exec_name - $comp_name</strong> mp3</a> <span class="more">($comp_rec mp3's)</span>~ if ($comp_rec>0);

	$f_the=($f_the==1)?" checked":"";

	my $edit_adm = qq~
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Edit Lyric
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Edit lyric</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

<form>
  <input type="hidden" name="lyric_id" id="lyric_id" value="$lyric_id">
  <div class="form-group form-check">
    <input type="checkbox" class="form-check-input" id="f_the" name="f_the" value="1"$f_the>
    <label class="form-check-label" for="f_the">The</label>
  </div>
  <div class="form-group">
    <label for="exec">Исполнитель</label>
    <input type="text" class="form-control" name="exec" id="exec" placeholder="Исполнитель" value="$exec_name">
  </div>
  <div class="form-group form-check">
    <input type="checkbox" class="form-check-input" id="all_exec" name="all_exec" value="1">
    <label class="form-check-label" for="all_exec">Для всех Исполнителей</label>
  </div>
  <div class="form-group">
    <label for="comp">Композиция</label>
    <input type="text" class="form-control" name="comp" id="comp" placeholder="Композиция" value="$comp_name">
  </div>

<!--  <button type="submit" class="btn btn-primary">Submit</button> -->
</form>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="edit_save">Save changes</button>
      </div>
    </div>
  </div>
</div>
	~;
	my $script = qq~ 
<script>
\$(document).ready(function(){ 
	\$('#edit_save').on('click', function (e) { 
//		alert('lyric_id:'+\$('#lyric_id').val()+'ch:'+\$('#ch').val()+" / exec: "+\$('#exec').val()+" / comp: "+\$('#comp').val());
		\$.ajax({
            type: "GET",
//            url: "/cgi-bin/lyric.pl",
            data: {
            	action: "save",
                lyric_id: \$('#lyric_id').val(),
                f_the: \$('#f_the').prop("checked"),
                all_exec: \$('#all_exec').prop("checked"),
                exec: \$('#exec').val(),
                comp: \$('#comp').val()
            }
        }).done(function(e) {
            \$("#exampleModal").modal('hide');
        });
	});
});
</script>
	~;
	$edit_adm="" if ($ADM==0);
	$script="" if ($ADM==0);

#	my ($script,$body)=mp3s::set_openwin();

# ------------------------
# Send them a page 
	wclib::send_header();

	# Output
	open(OUT,"$config{'blank_lyrics'}/cgi-bin/blank/lyrics-n.html");
	while(<OUT>) {
		# s/%banner\((\d*)\)%/ihitex2::get_banner($1)/e;
		# s/%bottom_banner%/mp3s::set_bottom_banner2/e;

		s/%title%/$title/g;
		s/%desc%/$desc/g;
		s/%keyw%/$keyw/g;

		s/%edit%/$edit_adm/;
		s/%script%/$script/;

		s/%param%/$crypt_word&$lyric_id/g;
		s/%translate%/$translate/;

#		s/(<!--#if expr="\$HTTP_COOKIE = \/view\\=1\/" -->.*?<!--#endif -->)/mp3s::setting()/e;
		if (s/<!--#include virtual=\"\/(.*).txt\" -->//g ) {
			print $`;
			my $end=$';
			my $blank=($1 ne "banner3")?$1:mp3s::set_banner();
			if ($blank eq "top") {
				print ihitex2::get_banner(3);
				print ihitex2::get_banner(1);
			} elsif ($blank eq "mtop") {
				print ihitex2::get_banner(7);
			} elsif ($blank eq "banner_120x240") {
				print ihitex2::get_banner(5);
				print ihitex2::get_banner(6);
			} elsif ($blank eq "banner3_adv") {
				print ihitex2::get_banner(4);
				print ihitex2::get_banner(2);
			} else {
				open (TEMPL,"$config{'blank_lyrics'}/$blank.txt");
				while (<TEMPL>) { print; } 
				close (TEMPL);
			}
			if ($blank eq "top-counter" && length($ENV{'HTTP_USER_AGENT'})>20 && $ENV{'HTTP_USER_AGENT'}!~m/bot/i) {
				print qq~
<script src="http://lyrics.mp3s.ru/fp.js"></script>
<script type="text/javascript">
    var postAjax2 = function (url, data, success) {
        var params = typeof data == 'string' ? data : Object.keys(data).map(
            function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]); }
        ).join('&');

        var xhr = new XMLHttpRequest();
        xhr.open('POST', url);
        xhr.onreadystatechange = function () {
            if (xhr.readyState > 3 && +xhr.status === 200) { success(xhr.responseText); }
        };
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(params);
        return xhr;
    }

	if (!navigator.zzz) {
	if (window.requestIdleCallback) {
	    requestIdleCallback(function () {
	        Fingerprint2.get(function (components) {
			    var values = components.map(function (component) { return (component.key === 'webglmy')?component.value:"" })
			    var murmur = Fingerprint2.x64hash128(values.join(''), 31)
	          postAjax2('http://lyrics.mp3s.ru/track/finger', {
                data: JSON.stringify(components),
                fp: JSON.stringify(murmur)
              }, function (e) {});
	        })
	    })
	} else {
	    setTimeout(function () {
	        Fingerprint2.get(function (components) {
			    var values = components.map(function (component) { return (component.key === 'webglmy')?component.value:"" })
			    var murmur = Fingerprint2.x64hash128(values.join(''), 31)
	          postAjax2('http://lyrics.mp3s.ru/track/finger', {
                data: JSON.stringify(components),
                fp: JSON.stringify(murmur)
              }, function (e) {});
	        })  
	    }, 500)
	}
	}
</script>
<script>
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = false;
s.src =  "http://lyrics.mp3s.ru/js/track/muslite_d.js";
document.getElementsByTagName('head')[0].appendChild(s);
</script>
				~;
			}
			print $end;
			next;
		}

#		s/%script%/$script/;
#		s/%body%/$body/;

		s/%exec_ch%/$exec_ch/g;
		s/%exec_ch_q%/$exec_ch_q/g;

		s/%exec_name%/$exec_name/g;
		s/%exec_name_q%/$exec_name_q/g;
		s/%comp_name%/$comp_name/g;
		s/%comp_name_q%/$comp_name_q/g;

#		s/%comp_name%/Текст песни &laquo;$exec_name - $comp_name&raquo;/;
		s/%track_name%/$exec_name - $comp_name/g;
		s/%track_name_q%/$track_name_q/g;
#		s/%track_name_q%/wclib::url_encode("$exec_name - $comp_name")/e;
		s/%video%/$video/;
		s/%lyric%/$lyric/;

		s/%comp_list%/$comp_list/;
		s/%exec_list%/$exec_list/;

		s/%right_side%/get_related_products($comp_id,$exec_id,$exec_name)/e;


	# if (s/%list%//) {

	# print qq~
	# 	<div>
	# 		<div class="block-cont text-song">
	# 			<div class="wrap">
	# 				$lyric
	# 			</div>
	# 		</div>

	# 		<br>&nbsp;<br>
	# 	</div>
	# 	<div>
	# 		<a href="/view/exec/$exec_name_q/" class="lyric"> Все песни <b>$exec_name</b></a><br>
	# 		<a href="/view/comp/$comp_name_q/" class="lyric"> Все песни с названием <b>$comp_name</b></a>
	# 	</div>
	# ~;

	# print qq~
	# 	<div>
	# 		<div class="block-cont text-song">
	# 			<div class="wrap"><form method="get" class="selects">
	# 				<label>Размер текста: <select id="sizes" onChange="ChangeDivSize()"><option value="0" selected>Smallest</option><option value="1">Small</option><option value="2" selected>Normal</option><option value="3">Large</option><option value="4">Largest</option></select></label>						<label>Перевести на:
	# 				<select id="tr_select"><option value="sq">Albanian</option><option value="ar">Arabic</option><option value="be">Belarusian</option><option value="bg">Bulgarian</option><option value="ca">Catalan</option><option value="zh">Chinese</option><option value="hr">Croatian</option><option value="cs">Czech</option><option value="da">Danish</option><option value="nl">Dutch</option><option value="en">English</option><option value="et">Estonian</option><option value="tl">Filipino</option><option value="fi">Finnish</option><option value="fr">French</option><option value="gl">Galician</option><option value="de">German</option><option value="el">Greek</option><option value="hi">Hindi</option><option value="hu">Hungarian</option><option value="is">Icelandic</option><option value="id">Indonesian</option><option value="ga">Irish</option><option value="it">Italian</option><option value="ja">Japanese</option><option value="ko">Korean</option><option value="lv">Latvian</option><option value="lt">Lithuanian</option><option value="no">Norwegian</option><option value="pl">Polish</option><option value="pt">Portuguese</option><option value="ro">Romanian</option><option value="ru" selected>Russian</option><option value="sr">Serbian</option><option value="sk">Slovak</option><option value="sl">Slovenian</option><option value="es">Spanish</option><option value="sv">Swedish</option><option value="th">Thai</option><option value="tr">Turkish</option><option value="uk">Ukrainian</option><option value="vi">Vietnamese</option></select></label>
	# 				<input type="submit" onclick="javascript:start_translate();return false;" value="ok" /></form>

	# 				<div class="song" id="songlyrics" style="font-size:13px;">
	# 					<div id="backto" style="visibility:hidden;display:none;"><a href="#" onclick="back_to_default();return false;"><< Исходный текст песни</a><br></div>
	# 					<br>
	# 					текст песни &nbsp;<b>$exec_name - $comp_name</b><br><br>
	# 					<div id="from_pre">$lyric</div>
	# 					<div id="to_pre" style="display:none;visibility:hidden;">Translation in progress. Please wait...<br><br><img src="http://img.mp3s.ru/i/ajax-loader.gif"></div>
	# 				</div>
	# 			</div>
	# 		</div>

	# 		<br>&nbsp;<br>
	# 	</div>
	# 	<div>
	# 		<a href="/view/exec/$exec_name_q/" class="lyric"> Все песни <b>$exec_name</b></a><br>
	# 		<a href="/view/comp/$comp_name_q/" class="lyric"> Все песни с названием <b>$comp_name</b></a>
	# 	</div>
	# ~;

	# }
		# s/%lyric_link%/$lyric_link/;

		print;
	}
	close(OUT);

	wclib::db_disconnect;
#	print "<font color=white>that took ". wclib::end_times($start) ." CPU seconds</font>\n";

		# } else {
		# 	print "Location: $ENV{'HTTP_REFERER'}\n\n";
		# }

#} else {
#	print "Location: $ENV{'HTTP_REFERER'}\n\n";
#}

sub get_comp {
	my ($lyric_id,$exec_id,$exec_name,$exec_name_q)=@_;

	my $query = qq!
		SELECT SQL_CALC_FOUND_ROWS l.COMP_ID, c.Name, l.LYRIC_ID
		FROM Compositions c, Lyrics l
		WHERE c.COMP_ID=l.COMP_ID AND l.EXEC_ID=?
		ORDER BY c.NAME
		LIMIT 6
	!;
	my $sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	my $rows = $sth -> execute($exec_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);

	return if ($rows eq "0E0" || $rows==1);

	my $dd=wclib::select_query("FOUND_ROWS()");

	my $temp=qq~
<div class="row-fluid">
    <div class="second-counter alfa mb-3">
    <h3 class="mb-4"><a href="/view/exec/$exec_name_q">Другие песни «$exec_name» <span class="rec-num">все $dd</span></a></h3>
	~;
	my $ii=0;
	my $crypt_comp_name;
	while ( my ($comp_id,$comp_name,$url_id) = $sth->fetchrow_array) {
		next if ($url_id==$lyric_id);
		$ii++;
		$crypt_comp_name=mp3s::get_crypt_name($comp_name.$exec_id);
		$crypt_comp_name=~s/[^a-zA-Z0-9]/_/g;
		$temp.=qq~<div class="col-12 mb-2"><a href="/perl/lyric.pl?$crypt_comp_name&$url_id" class="h4">$exec_name - $comp_name</a></div>~;
		last if ($ii==5);
	}
	$sth -> finish;
	$temp.=qq~</div></div>~;
	return $temp;
}

sub get_exec {
	my ($lyric_id,$comp_id,$comp_name,$comp_name_q)=@_;

	my $query = qq!
		SELECT SQL_CALC_FOUND_ROWS l.EXEC_ID, e.Name, l.LYRIC_ID
		FROM Lyrics l
			JOIN Executors e
			ON e.EXEC_ID=l.EXEC_ID 
			JOIN Compositions c
			ON c.COMP_ID=l.COMP_ID
		WHERE c.NAME=?
		ORDER BY e.NAME
		LIMIT 6
	!;
	my $sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	my $rows = $sth -> execute($comp_name) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);

	return if ($rows eq "0E0" || $rows==1);

	my $dd=wclib::select_query("FOUND_ROWS()");

	my $temp=qq~
<div class="row-fluid">
    <div class="second-counter alfa mb-3">
    <h3 class="mb-4"><a href="/view/comp/$comp_name_q">Песня «$comp_name» других исполнителей <span class="rec-num">все $dd</span></a></h3>
	~;
	my $ii=0;
	my $crypt_comp_name;
	while ( my ($exec_id,$exec_name,$url_id) = $sth->fetchrow_array) {
		next if ($url_id==$lyric_id);
		$ii++;
		$crypt_comp_name=mp3s::get_crypt_name($comp_name.$exec_id);
		$crypt_comp_name=~s/[^a-zA-Z0-9]/_/g;
		$temp.=qq~<div class="col-12 mb-2"><a href="/perl/lyric.pl?$crypt_comp_name&$url_id" class="h4">$exec_name - $comp_name</a></div>~;
		last if ($ii==5);
	}
	$sth -> finish;
	$temp.=qq~</div></div>~;
	return $temp;
}

sub get_related_products {
	my ($cur_comp_id,$exec_id,$exec_name) = @_;

#	Формируем основной запрос, который возвращает порядковый номер записи в отсортированном и отфильрованном наборе, и id записи
	my $query = qq!
		SELECT sr2.* FROM (
		SELECT \@rownumb := \@rownumb+1 AS rownumb, src.* FROM ( 
			SELECT l.COMP_ID, c.Name, l.LYRIC_ID
			FROM Compositions c, Lyrics l
			WHERE c.COMP_ID=l.COMP_ID AND l.EXEC_ID=$exec_id
			ORDER BY c.NAME
		) AS src, (SELECT \@rownumb := 0) al) sr2
	!;
#	Получем порядковый номер текущей записи в выборке
 	my $sth = $dbh -> prepare ($query." WHERE COMP_ID = $cur_comp_id") || uselib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	my $rows = $sth -> execute() || uselib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
	my ($rowNumber,$comp_id,$comp_name,$url_id) = $sth -> fetchrow_array;
	$sth -> finish;

#	Обрабатываем результат запроса
	return if ($rows eq "0E0");

	my $ii=0;
	my $right_side="";
	my $crypt_comp_name;

	if ($rowNumber > 1) { # Если $rowNumber > 1 значит есть как минимум предыдущая запись (текущая не в начале)
		# Выбираем предыдущую и последующую записи относительно текущей по rownumb
	 	$sth = $dbh -> prepare ($query." WHERE COMP_ID <> $cur_comp_id LIMIT ".($rowNumber - 2).",2") || uselib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		$sth -> execute() || uselib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		while (($rowNumber,$comp_id,$comp_name,$url_id) = $sth -> fetchrow_array) {

			$ii++;
			$crypt_comp_name=mp3s::get_crypt_name($comp_name.$exec_id);
			$crypt_comp_name=~s/[^a-zA-Z0-9]/_/g;

			if ($ii==1) {
				$right_side.=qq~<a class="link prev-next__item prev-next__prev waves-effect waves-effect" tabindex="0" href="/perl/lyric.pl?$crypt_comp_name&$url_id"><div class="prev-next__direction">Предыдущая песня</div><div class="prev-next__title">$exec_name - $comp_name</div></a>~;
			} else {
				$right_side.=qq~<a class="link prev-next__item prev-next__next waves-effect waves-effect" tabindex="0" href="/perl/lyric.pl?$crypt_comp_name&$url_id"><div class="prev-next__direction">Следующая песня</div><div class="prev-next__title">$exec_name - $comp_name</div></a>~;
			}

		}
		$sth -> finish;

	} else { # Если $rowNumber == 1 значит есть текущая запись стоит в начале набора данных и есть только следующая запись
		# Выбираем последующую запись относительно текущей
	 	$sth = $dbh -> prepare ($query." WHERE rownumb > $rowNumber LIMIT 1") || uselib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		$sth -> execute() || uselib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		($rowNumber,$comp_id,$comp_name,$url_id) = $sth -> fetchrow_array;
		$crypt_comp_name=mp3s::get_crypt_name($comp_name.$exec_id);
		$crypt_comp_name=~s/[^a-zA-Z0-9]/_/g;
		$right_side.=qq~<a class="link prev-next__item prev-next__next waves-effect waves-effect" tabindex="0" href="/perl/lyric.pl?$crypt_comp_name&$url_id"><div class="prev-next__direction">Следующая</div><div class="prev-next__title">$exec_name - $comp_name</div></a>~ if $url_id;
		$sth -> finish;
	}

#	return "  $cur_comp_id / $rows / $rowNumber / $limit";

	# my $ii=0;
	# while (($rowNumber,$comp_id,$comp_name,$url_id) = $sth -> fetchrow_array) {

	# 	$ii++;
	# 	$crypt_comp_name=mp3s::get_crypt_name($comp_name.$exec_id);
	# 	$crypt_comp_name=~s/[^a-zA-Z0-9]/_/g;

	# 	if ($rowNumber>1 && $ii==1) {
	# 		$right_side.=qq~<a class="link prev-next__item prev-next__prev waves-effect waves-effect" tabindex="0" href="/perl/lyric2.pl?$crypt_comp_name&$url_id"><div class="prev-next__direction">Предыдущая</div><div class="prev-next__title">$exec_name - $comp_name</div></a>~;
	# 	} else {
	# 		$right_side.=qq~<a class="link prev-next__item prev-next__next waves-effect waves-effect" tabindex="0" href="/perl/lyric2.pl?$crypt_comp_name&$url_id"><div class="prev-next__direction">Следующая</div><div class="prev-next__title">$exec_name - $comp_name</div></a>~;
	# 	}

	# }
	# $sth -> finish;

	if ($right_side) {
		$right_side=qq~<div id="prev-next" class="prev-next content__prev-next2 py-3 pl-3">$right_side</div>~;
	}

	return $right_side;
}