<?php
include('include/autoloader.php');
error_reporting(E_ERROR);
switch ($_GET['case']) {
case 'ajax_category_media_items_count';
if (isset($_GET['id'])) {
$id = intval(make_safe(xss_clean($_GET['id'])));
$query_pag_num = "SELECT COUNT(*) AS count FROM media WHERE category_id='$id' AND published='1' AND deleted='0'";
$result_pag_num = $mysqli->query($query_pag_num);
$row = $result_pag_num->fetch_assoc();
$count = $row['count']+0;
echo $count;
}
break;
case 'ajax_search_media_items_count';
if (isset($_GET['word'])) {
$word = make_safe(xss_clean(htmlspecialchars($_GET['word'],ENT_QUOTES)));
$query_pag_num = "SELECT COUNT(*) AS count FROM media WHERE published='1' AND deleted='0' AND (title LIKE '%$word%' OR tags LIKE '%$word%')";
$result_pag_num = $mysqli->query($query_pag_num);
$row = $result_pag_num->fetch_assoc();
$count = $row['count']+0;
echo $count;
}
break;
case 'ajax_reload_votes';
if (isset($_GET['media_id'])) {
$media_id = intval(make_safe(xss_clean($_GET['media_id'])));
$smarty->assign('media_id',$media_id);	
$smarty->display('ajax-reload-votes.html');
}
break;
case 'ajax_remove_from_list';
if (isset($_POST)) {
$id = make_safe(xss_clean($_POST['id']));
$delete = $mysqli->query("DELETE FROM lists_media WHERE id='$id' AND user_id='$_SESSION[media_cms_user]'");
if ($delete) {
echo 1;	
} else {
echo 0;	
}
}
break;
case 'ajax_vote_up';
if (isset($_POST)) {
$media_id = make_safe(xss_clean($_POST['media_id']));
$check = $mysqli->query("SELECT * FROM user_votes WHERE media_id='$media_id' AND user_id='$_SESSION[media_cms_user]'");
if ($check->num_rows == 0) {
$add = $mysqli->query("INSERT INTO user_votes (media_id,user_id,vote_up) VALUES ('$media_id','$_SESSION[media_cms_user]','1')");	
} else {
$add = $mysqli->query("UPDATE user_votes SET vote_down='0', vote_up='1' WHERE media_id='$media_id' AND user_id='$_SESSION[media_cms_user]'");	
}
if ($add) {
echo 1;	
} else {
echo 0;	
}
}
break;
case 'ajax_vote_down';
if (isset($_POST)) {
$media_id = make_safe(xss_clean($_POST['media_id']));
$check = $mysqli->query("SELECT * FROM user_votes WHERE media_id='$media_id' AND user_id='$_SESSION[media_cms_user]'");
if ($check->num_rows == 0) {
$add = $mysqli->query("INSERT INTO user_votes (media_id,user_id,vote_down) VALUES ('$media_id','$_SESSION[media_cms_user]','1')");	
} else {
$add = $mysqli->query("UPDATE user_votes SET vote_down='1', vote_up='0' WHERE media_id='$media_id' AND user_id='$_SESSION[media_cms_user]'");	
}
if ($add) {
echo 1;	
} else {
echo 0;	
}
}
break;
case 'add_to_list_action';
if (isset($_POST)) {
$list_id = intval(make_safe(xss_clean($_POST['list_id'])));
$media_id = intval(make_safe(xss_clean($_POST['media_id'])));
$media_in_list = $general->count_list_media_items($list_id);
if ($general->user_list_media_check($_SESSION['media_cms_user'],$media_id,$list_id) > 0) {
echo notification('danger',"$language[media_listed_before]");	
} elseif ($options['users_max_media_list_number'] != 0 AND $media_in_list == $options['users_max_media_list_number']) {
echo notification('danger',"$language[max_media_reached]");	
} else {
$add = $mysqli->query("INSERT INTO lists_media (list_id,user_id,media_id) VALUES ('$list_id','$_SESSION[media_cms_user]','$media_id')");
if ($add) {
echo 1;		
} else {
echo notification('danger',"$language[error_happened]");
}
} 
} else {
echo notification('danger',"$language[error_happened]");
}
break;
case 'ajax_edit_list_action';
if (isset($_POST)) {
$list_id = intval($_POST['list_id']);
if (!empty($_POST['name'])) {
$name = make_safe(xss_clean($_POST['name']));
} else {
$rand = rand(000000,999999);
$name = "Playlist $rand";	
}
if (!empty($_POST['privacy'])) {
$privacy = intval($_POST['privacy']);
} else {
$privacy = 0;	
}
$add = $mysqli->query("UPDATE lists SET title='$name',privacy='$privacy' WHERE user_id='$_SESSION[media_cms_user]' AND id='$list_id'");
if ($add) {
echo 1;		
} else {
echo notification('danger',"$language[error_happened]");
}
}
break;
case 'ajax_remove_list_action';
if (isset($_POST)) {
$list_id = intval($_POST['list_id']);
$mysqli->query("DELETE FROM lists_media WHERE user_id='$_SESSION[media_cms_user]' AND list_id='$list_id'");
$delete = $mysqli->query("DELETE FROM lists WHERE user_id='$_SESSION[media_cms_user]' AND id='$list_id'");
if ($delete) {
echo 1;		
} else {
echo notification('danger',"$language[error_happened]");
}
}
break;
case 'ajax_create_list_action';
if (isset($_POST)) {
if (!empty($_POST['name'])) {
$name = make_safe(xss_clean($_POST['name']));
} else {
$rand = rand(000000,999999);
$name = "Playlist $rand";	
}
if (!empty($_POST['privacy'])) {
$privacy = intval($_POST['privacy']);
} else {
$privacy = 0;	
}
$datetime = time();
$add = $mysqli->query("INSERT INTO lists (title,user_id,create_datetime,privacy) VALUES ('$name','$_SESSION[media_cms_user]','$datetime','$privacy')");
if ($add) {
$list_id = $mysqli->insert_id;
if (!empty($_POST['media_id'])) {
$media_id = intval($_POST['media_id']);
$addm = $mysqli->query("INSERT INTO lists_media (list_id,user_id,media_id) VALUES ('$list_id','$_SESSION[media_cms_user]','$media_id')");
if ($addm) {
echo 1;	
}	
} else {
echo 1;	
}	
} else {
echo notification('danger',"$language[error_happened]");
}
} else {
echo notification('danger',"$language[error_happened]");
}
break;
case 'ajax_create_list';
$media_id = make_safe(xss_clean($_GET['id']));
$user_lists_number = $general->count_user_lists($_SESSION['media_cms_user']);
$smarty->assign('user_lists_number',$user_lists_number);
$smarty->assign('media_id',$media_id);
$smarty->display('ajax-create-list.html');
break;
case 'ajax_edit_list';
$list_id = make_safe(xss_clean($_GET['id']));
$list = $general->single_list($list_id);
foreach ($list AS $key=>$value) {
	$smarty->assign('list_'.$key,$value);
}
$smarty->display('ajax-edit-list.html');
break;
case 'ajax_remove_list';
$list_id = make_safe(xss_clean($_GET['id']));
$list = $general->single_list($list_id);
foreach ($list AS $key=>$value) {
	$smarty->assign('list_'.$key,$value);
}
$smarty->display('ajax-remove-list.html');
break;
case 'ajax_order_list_media_action';
	$records = $_GET['records'];
	$counter = 1;
	foreach ($records as $record) {
		$sql = "UPDATE lists_media SET media_order='$counter' WHERE id='$record'";
		$query = $mysqli->query($sql);
		$counter = $counter + 1;	
	}
break;
case 'ajax_order_list_media';
$list_id = make_safe(xss_clean($_GET['id']));
$list = $general->single_list($list_id);
foreach ($list AS $key=>$value) {
	$smarty->assign('list_'.$key,$value);
}
$media = $general->lists_media($list_id);
$smarty->assign('media',$media);
$smarty->display('ajax-order-list-media.html');
break;
case 'add_to_list';
$media_id = make_safe(xss_clean($_GET['id']));
$smarty->assign('media_id',$media_id);
$lists = $general->user_lists($_SESSION['media_cms_user']);
$smarty->assign('lists',$lists);
$smarty->display('add-to-list.html');	
break;
case 'ajax_instant_search';
// ajax search for media
if(isset($_POST['queryString'])) {
$queryString = make_safe(xss_clean(htmlspecialchars($_POST['queryString'],ENT_QUOTES)));
$smarty->assign('queryString',$queryString);
if(mb_strlen($queryString,'UTF-8') >= 3) {

$query = $mysqli->query("SELECT * FROM media WHERE published='1' AND deleted='0' AND (title LIKE '%$queryString%' OR tags LIKE '%$queryString%') ORDER BY title ASC LIMIT 6");
$isthere = $query->num_rows;
$smarty->assign('isthere',$isthere);
if ($isthere > 0) {
    while ($result = $query->fetch_assoc()) {
		$media[] = $result;
    }
	$smarty->assign('media',$media);
$smarty->display('ajax-search-media.html');
}
} 
}
break;
case 'ajax_media_items';
// ajax search for author (by first letter) in all authors page
	if(isset($_GET))
	{
	$page = $_GET['page'];
	$cur_page = $page;
	$page -= 1;
	if (isset($options['theme_home_media_number'])) {
	$per_page = $options['theme_home_media_number'];
	} else {
	$per_page = 24;
	}
	if (isset($_GET['order'])) {
		$order = make_safe(xss_clean($_GET['order']));
	} else {
		$order = 'id';
	}
	$smarty->assign('order',$order);
	$smarty->assign('per_page',$per_page);
	$previous_btn = true;
	$next_btn = true;
	$start = $page * $per_page;
	
	$result_pag_data = $mysqli->query("SELECT * FROM media WHERE published='1' AND deleted='0' ORDER BY $order DESC LIMIT $start, $per_page");
	while ($row = $result_pag_data->fetch_assoc()) {
		$media[] = $row;
	}
	$smarty->assign('media',$media);


	$query_pag_num = "SELECT COUNT(*) AS count FROM media WHERE published='1' AND deleted='0'";
	$result_pag_num = $mysqli->query($query_pag_num);
	$row = $result_pag_num->fetch_assoc();
	$count = $row['count'];
	$smarty->assign('count',$count);
	$no_of_paginations = ceil($count / $per_page);

	if ($cur_page >= 7) {
		$start_loop = $cur_page - 3;
		if ($no_of_paginations > $cur_page + 3)
			$end_loop = $cur_page + 3;
		else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
			$start_loop = $no_of_paginations - 6;
			$end_loop = $no_of_paginations;
		} else {
			$end_loop = $no_of_paginations;
		}
	} else {
		$start_loop = 1;
		if ($no_of_paginations > 7)
			$end_loop = 7;
		else
			$end_loop = $no_of_paginations;
	}
	$paginations .= "<div class='paginations'><ul class='pager'>";


	if ($previous_btn && $cur_page > 1) {
		$pre = $cur_page - 1;
		$paginations .= "<li rel='$pre' class='active previous'><a href='javascript:void();'>$language[previous_page]</a></li>";
	} else if ($previous_btn) {
		$paginations .= "<li class='inactive previous disabled'><a href='javascript:void();'>$language[previous_page]</a></li>";
	}

	if ($next_btn && $cur_page < $no_of_paginations) {
		$nex = $cur_page + 1;
		$paginations .= "<li rel='$nex' class='active nextpage next'><a href='javascript:void();'>$language[next_page]</a></li>";
	} else if ($next_btn) {
		$paginations .= "<li class='inactive nextpage next disabled'><a href='javascript:void();'>$language[next_page]</a></li>";
	}

	$pagi .= $paginations . "</ul></div>";  
	$smarty->assign('paginations',$pagi);
	}
	
	$smarty->display('ajax-media-items.html');
break;
case 'ajax_category_media_items';
// ajax search for author (by first letter) in all authors page
	if(isset($_GET))
	{
	$page = $_GET['page'];
	if (isset($_GET['id'])) {
	$id = intval(make_safe(xss_clean($_GET['id'])));
	$smarty->assign('id',$id);
	} else {
		
	}
	$cur_page = $page;
	$page -= 1;
	if (isset($options['theme_category_media_number'])) {
	$per_page = $options['theme_category_media_number'];
	} else {
	$per_page = 24;
	}
	$smarty->assign('per_page',$per_page);
	$previous_btn = true;
	$next_btn = true;
	$start = $page * $per_page;
	$query_pag_num = "SELECT COUNT(*) AS count FROM media WHERE category_id='$id' AND published='1' AND deleted='0'";
	$result_pag_num = $mysqli->query($query_pag_num);
	$row = $result_pag_num->fetch_assoc();
	$count = $row['count'];
	$smarty->assign('count',$count);
	$no_of_paginations = ceil($count / $per_page);
	if ($count > 0) {
	$result_pag_data = $mysqli->query("SELECT * FROM media WHERE category_id='$id' AND published='1' AND deleted='0' ORDER BY id DESC LIMIT $start, $per_page");
	while ($row = $result_pag_data->fetch_assoc()) {
		$media[] = $row;
	}
	$smarty->assign('media',$media);
	}

	

	if ($cur_page >= 7) {
		$start_loop = $cur_page - 3;
		if ($no_of_paginations > $cur_page + 3)
			$end_loop = $cur_page + 3;
		else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
			$start_loop = $no_of_paginations - 6;
			$end_loop = $no_of_paginations;
		} else {
			$end_loop = $no_of_paginations;
		}
	} else {
		$start_loop = 1;
		if ($no_of_paginations > 7)
			$end_loop = 7;
		else
			$end_loop = $no_of_paginations;
	}
	$paginations .= "<div class='paginations'><ul class='pager'>";


	if ($previous_btn && $cur_page > 1) {
		$pre = $cur_page - 1;
		$paginations .= "<li rel='$pre' class='active previous'><a href='javascript:void();'>$language[previous_page]</a></li>";
	} else if ($previous_btn) {
		$paginations .= "<li class='inactive previous disabled'><a href='javascript:void();'>$language[previous_page]</a></li>";
	}

	if ($next_btn && $cur_page < $no_of_paginations) {
		$nex = $cur_page + 1;
		$paginations .= "<li rel='$nex' class='active nextpage next'><a href='javascript:void();'>$language[next_page]</a></li>";
	} else if ($next_btn) {
		$paginations .= "<li class='inactive nextpage next disabled'><a href='javascript:void();'>$language[next_page]</a></li>";
	}

	$pagi .= $paginations . "</ul></div>";  
	$smarty->assign('paginations',$pagi);
	}
	
	$smarty->display('ajax-category-media-items.html');
break;
case 'ajax_search_media_items';
	if(isset($_GET))
	{
	$page = intval($_GET['page']);
	$word = make_safe(xss_clean(htmlspecialchars($_GET['word'],ENT_QUOTES)));
	$smarty->assign('word',$word);
	if (!empty($word)) {
	$cur_page = $page;
	$page -= 1;
	if (isset($options['theme_search_media_number'])) {
	$per_page = $options['theme_search_media_number'];
	} else {
	$per_page = 24;
	}
	$smarty->assign('per_page',$per_page);
	$previous_btn = true;
	$next_btn = true;
	$start = $page * $per_page;
	$query_pag_num = "SELECT COUNT(*) AS count FROM media WHERE published='1' AND deleted='0' AND (title LIKE '%$word%' OR tags LIKE '%$word%')";
	$result_pag_num = $mysqli->query($query_pag_num);
	$row = $result_pag_num->fetch_assoc();
	$count = $row['count'];
	$smarty->assign('count',$count);
	$no_of_paginations = ceil($count / $per_page);
	if ($count > 0) {
	$result_pag_data = $mysqli->query("SELECT * FROM media WHERE published='1' AND deleted='0' AND (title LIKE '%$word%' OR tags LIKE '%$word%') ORDER BY id DESC LIMIT $start, $per_page");
	while ($row = $result_pag_data->fetch_assoc()) {
		$media[] = $row;
	}
	$smarty->assign('media',$media);
	}

	

	if ($cur_page >= 7) {
		$start_loop = $cur_page - 3;
		if ($no_of_paginations > $cur_page + 3)
			$end_loop = $cur_page + 3;
		else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
			$start_loop = $no_of_paginations - 6;
			$end_loop = $no_of_paginations;
		} else {
			$end_loop = $no_of_paginations;
		}
	} else {
		$start_loop = 1;
		if ($no_of_paginations > 7)
			$end_loop = 7;
		else
			$end_loop = $no_of_paginations;
	}
	$paginations .= "<div class='paginations'><ul class='pager'>";


	if ($previous_btn && $cur_page > 1) {
		$pre = $cur_page - 1;
		$paginations .= "<li rel='$pre' class='active previous'><a href='javascript:void();'>$language[previous_page]</a></li>";
	} else if ($previous_btn) {
		$paginations .= "<li class='inactive previous disabled'><a href='javascript:void();'>$language[previous_page]</a></li>";
	}

	if ($next_btn && $cur_page < $no_of_paginations) {
		$nex = $cur_page + 1;
		$paginations .= "<li rel='$nex' class='active nextpage next'><a href='javascript:void();'>$language[next_page]</a></li>";
	} else if ($next_btn) {
		$paginations .= "<li class='inactive nextpage next disabled'><a href='javascript:void();'>$language[next_page]</a></li>";
	}

	$pagi .= $paginations . "</ul></div>";  
	$smarty->assign('paginations',$pagi);
	}
	}
	$smarty->display('ajax-search-media-items.html');
break;
case 'register';
	if (isset($_POST)) {
		$username = make_safe($_POST['username']);
		$password = make_safe($_POST['password']);
		$challenge_recaptcha = xss_clean($_POST["recaptcha_challenge_field"]);
		$response_recaptcha = xss_clean($_POST["recaptcha_response_field"]);
		$confirm_password = make_safe($_POST['confirm_password']);
		$email = make_safe($_POST['email']);
		$check_username = $general->check_username($username);
		$check_email = $general->check_email($email);
		$validemail = "^([[:alnum:]_.\-]{1,64})@([[:alnum:]_.\-]{2,40})(\.[a-z]{2,6})$";
		$check_capatcha = checkRecaptcha($challenge_recaptcha,$response_recaptcha,$options['api_recaptcha_private']);
		if (empty($username)) {
		echo notification('warning',"$language[insert_username]");
		} elseif (mb_strlen($username,'UTF-8') < 5 OR mb_strlen($username,'UTF-8') > 24) {
		echo notification('warning',"$language[username_min_max]");
		} elseif ($check_username != 0) {
		echo notification('warning',"$language[username_existed_before]");
		} elseif (empty($email)) {
		echo notification('warning',"$language[insert_email]");
		} elseif (ereg($validemail, $email) === false) {
		echo notification('warning',"$language[insert_valid_email]");
		} elseif ($check_email != 0) {
		echo notification('warning',"$language[email_exists_before]");
		} elseif (empty($password)) {
		echo notification('warning',"$language[insert_password]");
		} elseif (mb_strlen($password,'UTF-8') < 6) {
		echo notification('warning',"$language[password_min_max]");
		} elseif (empty($confirm_password)) {
		echo notification('warning',"$language[insert_password_confirm]");
		} elseif ($password != $confirm_password) {
		echo notification('warning',"$language[password_no_match]");
		} elseif ($check_capatcha == false) {
		echo notification('warning',"$language[invalid_captcha]");
		} else {
		$datetime = time();
		$encoded_password = hash('sha256', md5($password));
		$activation_code = genRandomString(24);
		$day = date('j');
		$month = date('n');
		$year = date('Y');
		$ip_address = getRealIpAddr();
				if ($options['users_activate_new_users'] == 'direct') {
					$active = 1;	
				} else {
					$active = 0;
					$confirmation = $options['general_siteurl'].'/user-activation/'.md5($email).'/'.$activation_code;
					$escape = str_replace('//','/',$confirmation);
					$confirmation_link = str_replace(':/','://',$escape);
					$title = "$language[user_confirmation_link]";
					$body = '<p>'.$language['hello'].' '.$username.' : <br />'.$language['to_confirm_membership'].' '.$options['general_seo_title'].' '.$language['click_below_link'].' <br /><br />
					<a href="'.$confirmation_link.'">'.$language['confirmation_link'].'</a>
					</p>';
					if ($options['mail_mail_method'] == 'mail') {	
					$send_email = send_simple_mail($options['mail_send_email'],$email,$title,$body);
					} else {
					$send_email = send_smtp_mail($options['mail_smtp_host'],$options['mail_smtp_port'],$options['mail_smtp_username'],$options['mail_smtp_password'],$email,$username,$title,$body,$options['general_seo_title']);	
					}
				}
		$add = $mysqli->query("INSERT INTO users (username,password,email,provider,activation_code,ip_address,datetime,last_login,day,month,year,active) VALUES ('$username','$encoded_password','$email','site','$activation_code','$ip_address','$datetime','$datetime','$day','$month','$year','$active')");
		if ($add) {
		if ($options['users_activate_new_users'] == 'direct') {
		echo notification('success',"$language[successfully_registered]");
		} else {
		echo notification('success',$language['activation_link_sent']. ' <b>'.$email.'</b>');	
		}
		} else {
		echo notification('danger',"$language[error_happened]");
		}
		}
	}
	break;
	case 'forget_password';
	if (isset($_POST)) {
		$challenge_recaptcha = xss_clean($_POST["recaptcha_challenge_field"]);
		$response_recaptcha = xss_clean($_POST["recaptcha_response_field"]);
		$email = make_safe($_POST['email']);
		$check_email = $general->check_email($email);
		$validemail = "^([[:alnum:]_.\-]{1,64})@([[:alnum:]_.\-]{2,40})(\.[a-z]{2,6})$";
		$check_capatcha = checkRecaptcha($challenge_recaptcha,$response_recaptcha,$options['api_recaptcha_private']);
		if (empty($email)) {
		echo notification('warning',"$language[insert_email]");
		} elseif (ereg($validemail, $email) === false) {
		echo notification('warning',"$language[insert_valid_email]");
		} elseif ($check_email == 0) {
		echo notification('warning',"$language[email_not_exists]");
		} elseif ($check_capatcha == false) {
		echo notification('warning',"$language[invalid_captcha]");
		} else {
				$get = $mysqli->query("SELECT activation_code,email,username FROM users WHERE email='$email'");
				$row = $get->fetch_assoc();
				$reset_password = $options['general_siteurl'].'/reset-password/'.md5($email).'/'.$row['activation_code'];
				$escape = str_replace('//','/',$reset_password);
				$reset_password_link = str_replace(':/','://',$escape);
				$title = 'Reset Password Link';
				$body = '<p>'.$language['hello'].' : <br />'.$language['reset_password_sent_message'].' '.$options['general_seo_title'].' '.$language['reset_password_click'].' <br /><br />
				<a href="'.$reset_password_link.'">'.$language['reset_password'].'</a>
				</p>';
				if ($options['mail_mail_method'] == 'mail') {	
				$send_email = send_simple_mail($options['mail_send_email'],$email,$title,$body);
				} else {
				$send_email = send_smtp_mail($options['mail_smtp_host'],$options['mail_smtp_port'],$options['mail_smtp_username'],$options['mail_smtp_password'],$email,$row['username'],$title,$body,$options['general_seo_title']);	
				}
				if ($send_email) {
					echo 1;
				} else {
					echo notification('danger',"$language[error_happened]");
				}
		}
	}
	break;
	case 'reset_password';
	if (isset($_POST)) {
		$new_password = make_safe($_POST['new_password']);
		$confirm_new_password = make_safe($_POST['confirm_new_password']);
		$user_id = intval(make_safe(xss_clean($_POST['user_id'])));
		if (empty($new_password)) {
		echo notification('warning',"$language[insert_password]");
		} elseif (mb_strlen($new_password,'UTF-8') < 6) {
		echo notification('warning',"$language[password_min_max]");
		} elseif (empty($confirm_new_password)) {
		echo notification('warning',"$language[insert_password_confirm]");
		} elseif ($new_password != $confirm_new_password) {
		echo notification('warning',"$language[password_no_match]");
		} else {
		$encoded_password = hash('sha256', md5($new_password));
		$activation_code = genRandomString(24);	
		$update = $mysqli->query("UPDATE users SET password='$encoded_password',activation_code='$activation_code' WHERE id='$user_id'");
		if ($update) {
		echo 1;	
		} else {
		echo notification('danger',"$language[error_happened]");	
		}
		}
	}
	break;
	case 'login';
	if (isset($_POST) AND count($_POST) > 0) {
		$username = xss_clean($_POST["username"]);
		$password = xss_clean($_POST["password"]);
		$remember = xss_clean($_POST["remember"]);
		if (empty($username)) {
		echo notification('warning',"$language[insert_username]");
		} elseif (empty($password)) {
		echo notification('warning',"$language[insert_password]");
		} else {
		$sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
		$query = $mysqli->query($sql);
		if ($query->num_rows == 0) {
		echo notification('warning',"$language[incorrect_login_details]");	
		} else {
		$row = $query->fetch_assoc();
		if ($row['password'] == hash('sha256', md5($password))) {
		if ($row['active'] == 0) {
		echo notification('warning',"$language[not_active_user]");	
		} else {
		$_SESSION['media_cms_user'] = $row['id'];
		$_SESSION['super_admin'] = $row['super_admin'];
		$datetime = time();
		$mysqli->query("UPDATE users SET last_login='$datetime' WHERE id='$row[id]'");
		if ($remember == 1 AND isset($options['users_cookie_name'])) {
		setcookie("$options[users_cookie_name]", "$row[username]_$row[password]", time()+(60*60*24*$options['users_cookie_expiration_time']), '/'); 
		}
		echo 1;
		}
		} else {
		echo notification('warning',"$language[incorrect_login_details]");	
		}
		}
		}

	}
	break;
	case 'logout';
	if (!isset($_SESSION['media_cms_user'])) {
			die('you can not access this page');
		} else {
			if (isset($_POST)) {
			if ($_POST['logout'] == 1) {
				unset($_SESSION['media_cms_user']);
				if (isset($_SESSION['super_admin'])) {
					unset($_SESSION['super_admin']);
				}
			if (isset($_COOKIE["$options[users_cookie_name]"])) {
				setcookie("$options[users_cookie_name]", '', time()-(60*60*24*7), '/');
			}
				echo 1;
			}
			}
		}
	break;
	case 'fetch_single_video';
		if (isset($_POST)) {
		$video_site = make_safe(xss_clean($_POST['video_site']));
		$category = make_safe(xss_clean(intval($_POST['category'])));	
		$link = make_safe(xss_clean($_POST['link']));
		$datetime = time();
		$day = date('j');
		$month = date('n');
		$year = date('Y');
		if (empty($video_site) OR empty($category) OR empty($link)) {
		echo 1;	
		} elseif (strpos($link,$video_site) === FALSE) {
		echo 2;	
		} else {
			switch ($video_site) {
				case 'youtube';
				$u = parse_url($link);
				$youtube_id = str_replace('v=','',$u['query']);
				if (check_video_id($youtube_id) > 0) {
				echo 4;
				} else {
				$baseUrl = 'https://www.googleapis.com/youtube/v3/';
				$apiKey = $options['api_youtube_apikey'];
				$url = $baseUrl.'videos?'.
						'id='.$youtube_id.
						'&part=snippet'. 
						'&key='.$apiKey;
				$json = json_decode(file_get_contents($url), true);
				if (count($json['items']) == 0) {
				echo 3;
				} else {
				$video_title = htmlspecialchars($json['items'][0]['snippet']['title'],ENT_QUOTES);
				$video_details = htmlspecialchars($json['items'][0]['snippet']['description'],ENT_QUOTES);
				if (!empty($json['items'][0]['snippet']['thumbnails']['standard']['url'])) {
				$video_thumbnail = $json['items'][0]['snippet']['thumbnails']['standard']['url'];
				} else {
				$video_thumbnail = $json['items'][0]['snippet']['thumbnails']['high']['url'];	
				}
				$video_youtube_url = 'http://www.youtube.com/watch?v='.$youtube_id;
				$videt = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/videos?id='.$youtube_id.'&part=contentDetails&key='.$apiKey), true);
				$video_duration = $videt['items'][0]['contentDetails']['duration'];
				$duration = youtube_duration($video_duration);
				if (!empty($video_thumbnail)) {
				$thumb = 'youtube_'.$youtube_id.'.jpg';
				$up = file_put_contents('upload/media/'.$thumb,file_get_contents($video_thumbnail));	
				} else {
				$thumb = '';	
				}
				if (count($json['items'][0]['snippet']['tags']) > 0) {
					$tags = implode(',',$json['items'][0]['snippet']['tags']);
				} else {
					$tags = title_to_keywords($json['items'][0]['snippet']['title']);
				}
				if (isset($options['users_media_publishing']) AND $options['users_media_publishing'] == 1) {
					$published = 1;
				} else {
					$published = 0;
				}
				$publish_time = youtube_date_to_unix($json['items'][0]['snippet']['publishedAt']);
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('youtube','$youtube_id','$_SESSION[media_cms_user]','$category','$video_title','$video_details','$video_youtube_url','$datetime','$thumb','$duration','$day','$month','$year','$published','$tags','$publish_time')");
				if ($insert) {
					echo 0;
				} else {
					echo 5;
				}
				} 
				}
				break;
				
				
				case 'facebook';
				$u = parse_url($link);
				$paths = explode('/',$u['path']);
				$video_id = $paths[3];
				if (check_video_id($video_id) > 0) {
				echo 4;
				} else {
				$token = $options['api_facebook_extended_token'];
				$graph = 'https://graph.facebook.com/v2.0/'.$video_id.'?fields=embed_html,tags,length,picture,description,name,source,id,created_time,from,icon,thumbnails,updated_time&access_token='.$token;
				$url = json_decode(file_get_contents($graph),true);
				if (!isset($url['id'])) {
				echo 3;
				} else {
				if (isset($url['name'])) {
				$video_title = htmlspecialchars($url['name'],ENT_QUOTES);
				$tags = title_to_keywords($video_title);
				} else {
				if (isset($url['description'])) {
				$video_title = htmlspecialchars(mb_substr($url['description'],0,100,'UTF-8'),ENT_QUOTES);
				$tags = title_to_keywords($video_title);
				} else {
				$video_title = $url['id'];	
				$tags = '';
				}
				}
				if (isset($url['description'])) {
				$video_details = htmlspecialchars($url['description'],ENT_QUOTES);
				} else {
				$video_details = '';	
				}
				
				$video_thumbnail = $url['picture'];
				$video_facebook_url = 'https://www.facebook.com/'.$url['from']['id'].'/videos/'.$url['id'].'/';
				$duration = round($url['length']);
				if (!empty($video_thumbnail)) {
				$thumb = 'facebook_'.$video_id.'.jpg';
				$up = file_put_contents('upload/media/'.$thumb,file_get_contents($video_thumbnail));	
				} else {
				$thumb = '';	
				}
				if (isset($options['users_media_publishing']) AND $options['users_media_publishing'] == 1) {
					$published = 1;
				} else {
					$published = 0;
				}
				$publish_time = youtube_date_to_unix($url['created_time']);
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('facebook','$video_id','$_SESSION[media_cms_user]','$category','$video_title','$video_details','$video_facebook_url','$datetime','$thumb','$duration','$day','$month','$year','$published','$tags','$publish_time')");
				if ($insert) {
					echo 0;
				} else {
					echo 5;
				}
				} 
				}
				break;
				
				
				case 'vimeo';
				$u = parse_url($link);
				$vimeo_id = str_replace('/','',$u['path']);
				if (check_video_id($vimeo_id) > 0) {
				echo 4;
				} else {
				$video = simplexml_load_string(curl_get('http://vimeo.com/api/v2/video/'.$vimeo_id.'.xml'));
				if (!isset($video->video->id)) {				
					echo 3;
				} else {
					$video_id = $video->video->id;
					$video_title = htmlspecialchars($video->video->title,ENT_QUOTES);
					$video_details = htmlspecialchars($video->video->description,ENT_QUOTES);
					$video_thumbnail = $video->video->thumbnail_large;
					$video_url = $video->video->url;
					$duration = $video->video->duration;
					if (!empty($video->video->tags)) {
						$tags = $video->video->tags;
					} else {
						$tags = title_to_keywords($video->video->title);
					}
					$publish_time = vimeo_date_to_unix($video->video->upload_date);
					if (!empty($video_thumbnail)) {
					$thumb = 'vimeo_'.$video_id.'.jpg';
					$up = file_put_contents('upload/media/'.$thumb,file_get_contents($video_thumbnail));	
					} else {
					$thumb = '';	
					}
					if (isset($options['users_media_publishing']) AND $options['users_media_publishing'] == 1) {
					$published = 1;
					} else {
					$published = 0;
					}
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('vimeo','$video_id','$_SESSION[media_cms_user]','$category','$video_title','$video_details','$video_url','$datetime','$thumb','$duration','$day','$month','$year','$published','$tags','$publish_time')");
				if ($insert) {
					echo 0;
				} else {
					echo 5;
				}
				}
				}
				break;
				case 'dailymotion';
				$u = parse_url($link);
				$dm_path = str_replace('/video/','',$u['path']);
				if (count(explode('_',$dm_path)) > 0) {
					$dm_ex = explode('_',$dm_path);
					$dm_id = $dm_ex[0];
				} else {
					$dm_id = $dm_path;
				}
				if (check_video_id($dm_id) > 0) {
				echo 4;
				} else {
				$url = 'https://api.dailymotion.com/video/'.$dm_id.'?fields=allow_embed,description,duration,embed_url,id,thumbnail_720_url,thumbnail_url,title,created_time,tags,url';
				$video = json_decode(file_get_contents($url), true);
				if (count($video) == 0) {
					echo 3;
				} else {
					$video_id = $video['id'];
					$video_title = htmlspecialchars($video['title'],ENT_QUOTES);
					$video_details = htmlspecialchars($video['description'],ENT_QUOTES);
					if (!empty($video['thumbnail_720_url'])) {
					$video_thumbnail = $video['thumbnail_720_url'];
					} else {
					$video_thumbnail = $video['thumbnail_url'];	
					}
					$video_url = $video['url'];
					$duration = $video['duration'];
					if (count($video['tags']) > 0) {
						$tags = implode(',',$video['tags']);
					} else {
						$tags = title_to_keywords($video['title']);
					}
					$publish_time = $video['created_time'];
					if (!empty($video_thumbnail)) {
					$thumb = 'dailymotion_'.$video_id.'.jpg';
					$up = file_put_contents('upload/media/'.$thumb,file_get_contents($video_thumbnail));	
					} else {
					$thumb = '';	
					}
					if (isset($options['users_media_publishing']) AND $options['users_media_publishing'] == 1) {
						$published = 1;
					} else {
						$published = 0;
					}
				$insert = $mysqli->query("INSERT INTO media (video_site,video_id,user_id,category_id,title,details,permalink,datetime,thumbnail,duration,day,month,year,published,tags,publish_time) VALUES ('dailymotion','$video_id','$_SESSION[media_cms_user]','$category','$video_title','$video_details','$video_url','$datetime','$thumb','$duration','$day','$month','$year','$published','$tags','$publish_time')");
				if ($insert) {
					echo 0;
				} else {
					echo 5;
				}
				}
				}
				break;
				default;
			}
		}	 	
		}
	
	break;
default;
}
?>