0) {
$minDays = 100000;
$minId = null;
foreach ($packages as $pack) {
$days = ceil(((strtotime($pack['publish_date']) + $pack['days'] * 86400) - time()) / 86400);
if ($days < $minDays && $days > 0) {
$minDays = $days;
$minId = $pack['id'];
}
}
if ($minId) {
$otherPackText = '';
foreach ($packages as $pack) {
$days = ceil(((strtotime($pack['publish_date']) + $pack['days'] * 86400) - time()) / 86400);
$otherDecled = declOfNum($days, array('%d день', '%d дня', '%d дней'));
$otherPackText = $otherPackText . $pack['pack_name'] . ': ' .$otherDecled . ';
';
}
$decled = declOfNum($minDays, array('Остался %d день', 'Осталось %d дня', 'Осталось %d дней'));
if ($minDays >= 1 && $minDays <= 5) {
return '
' .$otherPackText .'';
} elseif ($minDays > 5) {
return '
' .$otherPackText .'';
} else {
return '';
}
} else {
return '';
}
} else {
return '';
}
}
function zipalPackageCountText($objectId, $packageId) {
$ojb = array();
$zipalObj = mysql_fetch_assoc(mysql_query("SELECT id, days, created_at, publish_date, error_text from advertising_package_object_publish where object_id = $objectId and advertising_package_id = $packageId"));
$ojb['zipal_active'] = 0;
if ($zipalObj['publish_date'] == NULL || preg_match("|0000|", $zipalObj['publish_date'])) {
$ojb['zipal_active'] = 1;
}
$ojb['zipal_day'] = ceil(((strtotime($zipalObj['publish_date']) + $zipalObj['days'] * 86400) - time()) / 86400);
if ($ojb['zipal_day'] > 0) {
$ojb['zipal_day_text'] = declOfNum($ojb['zipal_day'], array('Остался %d день', 'Осталось %d дня', 'Осталось %d дней'));
} else {
$ojb['zipal_day_text'] = "";
}
if ($ojb['zipal_day'] >= 1 && $ojb['zipal_day'] <= 5) {
$ojb['zipal_active'] = 1;
$html = ''.$ojb['zipal_day_text'].'';
} elseif ($ojb['zipal_day'] > 5) {
$ojb['zipal_active'] = 1;
$html = ''.$ojb['zipal_day_text'].'';
} else {
$html = '';
if (!$zipalObj && $ojb['add_to_zipal'] == 1) {
$ojb['zipal_active'] = 1;
}
}
$ojb['error_text'] = null;
if (!empty($zipalObj['error_text'])) {
$error = json_decode(str_replace("\n", '', str_replace("\r", '', trim($zipalObj['error_text']))), true);
if ($error['result']['status'] == 'ErrorPropertyResponseType') {
$ojb['error_text'] = (array)$error['result']['error'];
}
}
return [
'html' => $html,
'error_text' => $ojb['error_text'],
'zipal_days' => $ojb['zipal_day'],
'zipal_days_text' => $ojb['zipal_day_text'],
'zipal_active' => $ojb['zipal_active']
];
}
function ZipalCountText($id) {
$ojb = array();
$zipalObj = mysql_fetch_assoc(mysql_query("SELECT id, days, created_at, add_to_zipal_at, error_text from zipal_objects where object_id = $id"));
//Test data
// $zipalObj['add_to_zipal_at'] = "2020-03-05 10:10:10";
// $zipalObj['days'] = 43;
// //unset($zipalObj);
// $ojb['zipal_active'] = 0;
// $ojb['add_to_zipal'] = 1;
$ojb['zipal_active'] = 0;
if ($zipalObj['add_to_zipal_at'] == NULL || preg_match("|0000|",$zipalObj['add_to_zipal_at'])) {
//$zipalObj['add_to_zipal_at'] = $zipalObj['created_at'];
$ojb['zipal_active'] = 1;
}
$ojb['zipal_day'] = ceil(((strtotime($zipalObj['add_to_zipal_at']) + $zipalObj['days'] * 86400) - time()) / 86400);
//$ojb['zipal_day']=10;//exit;
if ($ojb['zipal_day'] > 0) {
$ojb['zipal_day_text'] = declOfNum($ojb['zipal_day'], array('Остался %d день', 'Осталось %d дня', 'Осталось %d дней'));
} else {
$ojb['zipal_day_text'] = "";
}
if ($ojb['zipal_day'] >= 1 && $ojb['zipal_day'] <= 5) {
$ojb['zipal_active'] = 1;
$html = ''.$ojb['zipal_day_text'].'';
} elseif ($ojb['zipal_day'] > 5) {
$ojb['zipal_active'] = 1;
$html = ''.$ojb['zipal_day_text'].'';
} else {
$html = '';
if (!$zipalObj && $ojb['add_to_zipal'] == 1) {
$ojb['zipal_active'] = 1;
}
}
$ojb['error_text'] = null;
if (!empty($zipalObj['error_text'])) {
$error = json_decode(str_replace("\n", '', str_replace("\r", '', trim($zipalObj['error_text']))), true);
if ($error['result']['status'] == 'ErrorPropertyResponseType') {
$ojb['error_text'] = (array)$error['result']['error'];
}
}
return [
'html' => $html,
'error_text' => $ojb['error_text'],
'zipal_days' => $ojb['zipal_day'],
'zipal_days_text' => $ojb['zipal_day_text'],
'zipal_active' => $ojb['zipal_active']
];
}
/**
* https://gist.github.com/Neolot/3964380
* $titles = array('Сидит %d котик', 'Сидят %d котика', 'Сидит %d котиков');
*
* Функция склонения числительных в русском языке
*
* @param int $number Число которое нужно просклонять
* @param array $titles Массив слов для склонения
* @return string
**/
function declOfNum($number, $titles)
{
$cases = array (2, 0, 1, 1, 1, 2);
$format = $titles[ ($number%100 > 4 && $number %100 < 20) ? 2 : $cases[min($number%10, 5)] ];
return sprintf($format, $number);
}
function getNoImage() {
echo '
';
}
function clearInputData($mas) // очистка входящего массива
{
$mas2 = [];
while (list($k, $el) = each($mas)) {
if (!is_array($el)) {
if($k != 'opis'){
$el = strip_tags($el); // от тегов
$el = htmlspecialchars($el); // от кавычек и прочего
$el = str_replace("\n", "
", $el);
$el = str_replace("\r", "", $el);
$el = stripslashes($el); // от слэшей
} else {
$el = str_replace("\n", "", $el);
$el = str_replace("\r", "", $el);
}
$el = mysql_real_escape_string($el); // от MySQL-инъекций
$el = trim($el); // от лишних пробелов
}
$mas2[$k] = $el;
}
return $mas2;
}
/*
для домена joywork.ru:
robot@joywork.ru/Niut3swec[
*/
function mailClientById($userId, $address, $subject, $body, $paths = [], $adresses = [], $test = false)
{
require_once($_SERVER['DOCUMENT_ROOT'] . "/engine/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$user = new User;
$user->get($userId);
$mail->IsSMTP();
$mail->SMTPAuth = true;
if ($user->smtp and $user->smtp_check != 2) {
$mail->Host = $user->smtp;
$mail->Port = $user->smtp_port;
if ($user->smtp_ssl) {
if ($user->smtp == 'smtp.gmail.com') {
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
} else {
$mail->SMTPSecure = 'ssl';
}
}
$lg = $user->smtp_lg;
$pass = $user->smtp_pwd;
$mail->From = $user->smtp_from;
$mail->FromName = $user->smtp_fromname;
$mail->Username = $lg;
$mail->Password = $pass;
} else {
$lg = "robot@joywork.ru";
$mail->From = "robot@joywork.ru";
$mail->FromName = "JoyWork.ru";
$mail->Username = $lg;
$mail->Password = '6@tMRdQbJbllKz#Y';
$mail->Port = 465;
$mail->Host = 'smtp.yandex.ru';
$mail->SMTPSecure = 'ssl';
}
//if($test) $mail->SMTPDebug = 1; // функция с параметром test используется в настройках почты
$mail->isHTML(true);
$mail->AddCustomHeader('X-Mailru-Msgtype: ' . md5($lg) . ';');
$mail->AddCustomHeader('X-Postmaster-Msgtype: ' . md5($lg) . ';');
//$mail->AddCustomHeader('Date: ' . date("D, d M y H:i:s O") . ';');
$mail->CharSet = "utf-8";
$mail->addAddress($address);
$mail->Subject = $subject;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Body = $body;
$mail->AltBody = "Это письмо сгенерировано в формате HTML. Ваш клиент не поддерживает HTML или эта функция выключена.";
$mail->ClearAttachments();
foreach ($paths as $i => $path) {
$num = $i + 1;
$name = "$adresses[$i].pdf";
$mail->AddAttachment($path, $name);
}
if ($test)
if ($mail->Send()) return true; else return $mail->ErrorInfo;
else if ($mail->Send()) return true; else return mailClientPDF($mail->From, $address, $subject, $body, $paths, $adresses);
}
function mailClientByIdWithConfirm($userId, $address, $subject, $body, $paths = [], $adresses = [], $test = false, $pathAsPdf = true)
{
require_once($_SERVER['DOCUMENT_ROOT'] . "/engine/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$user = new User;
$user->get($userId);
$mail->IsSMTP();
$mail->SMTPAuth = true;
if ($user->smtp and $user->smtp_check != 2) {
$mail->Host = $user->smtp;
$mail->Port = $user->smtp_port;
if ($user->smtp_ssl) {
if ($user->smtp == 'smtp.gmail.com') {
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
} else {
$mail->SMTPSecure = 'ssl';
}
}
$lg = $user->smtp_lg;
$pass = $user->smtp_pwd;
$mail->From = $user->smtp_from;
$mail->FromName = $user->smtp_fromname;
$mail->Username = $lg;
$mail->Password = $pass;
} else {
$lg = "robot@joywork.ru";
$mail->From = "robot@joywork.ru";
$mail->FromName = "JoyWork.ru";
$mail->Username = $lg;
$mail->Password = '6@tMRdQbJbllKz#Y';
$mail->Port = 465;
$mail->Host = 'smtp.yandex.ru';
$mail->SMTPSecure = 'ssl';
}
//if($test) $mail->SMTPDebug = 1; // функция с параметром test используется в настройках почты
$mail->isHTML(true);
$mail->AddCustomHeader('X-Mailru-Msgtype: ' . md5($lg) . ';');
$mail->AddCustomHeader('X-Postmaster-Msgtype: ' . md5($lg) . ';');
//$mail->AddCustomHeader('Date: ' . date("D, d M y H:i:s O") . ';');
$mail->CharSet = "utf-8";
$mail->addAddress($address);
$mail->ConfirmReadingTo = $mail->From;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = "Это письмо сгенерировано в формате HTML. Ваш клиент не поддерживает HTML или эта функция выключена.";
$mail->ClearAttachments();
foreach ($paths as $i => $path) {
$num = $i + 1;
if ($pathAsPdf) {
$name = "$adresses[$i].pdf";
} else {
$name = "$adresses[$i]";
}
$mail->AddAttachment($path, $name);
}
if ($test)
if ($mail->Send()) return true; else return $mail->ErrorInfo;
else if ($mail->Send()) return true; else return mailClientPDF($mail->From, $address, $subject, $body, $paths, $adresses);
}
function mailClient($address, $subject, $body, $paths = [], $adresses = [], $test = false)
{
require_once($_SERVER['DOCUMENT_ROOT'] . "/engine/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$user = new User;
$user->get($_SESSION['id']);
$mail->IsSMTP();
$mail->SMTPAuth = true;
if ($user->smtp and $user->smtp_check != 2) {
$mail->Host = $user->smtp;
$mail->Port = $user->smtp_port;
if ($user->smtp_ssl) {
if ($user->smtp == 'smtp.gmail.com') {
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
} else {
$mail->SMTPSecure = 'ssl';
}
}
$lg = $user->smtp_lg;
$pass = $user->smtp_pwd;
$mail->From = $user->smtp_from;
$mail->FromName = $user->smtp_fromname;
$mail->Username = $lg;
$mail->Password = $pass;
} else {
$lg = "robot@joywork.ru";
$mail->From = "robot@joywork.ru";
$mail->FromName = "JoyWork.ru";
$mail->Username = $lg;
$mail->Password = '6@tMRdQbJbllKz#Y';
$mail->Port = 465;
$mail->Host = 'smtp.yandex.ru';
$mail->SMTPSecure = 'ssl';
}
//if($test) $mail->SMTPDebug = 1; // функция с параметром test используется в настройках почты
$mail->isHTML(true);
$mail->AddCustomHeader('X-Mailru-Msgtype: ' . md5($lg) . ';');
$mail->AddCustomHeader('X-Postmaster-Msgtype: ' . md5($lg) . ';');
//$mail->AddCustomHeader('Date: ' . date("D, d M y H:i:s O") . ';');
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->CharSet = "utf-8";
$mail->addAddress($address);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = "Это письмо сгенерировано в формате HTML. Ваш клиент не поддерживает HTML или эта функция выключена.";
$mail->ClearAttachments();
foreach ($paths as $i => $path) {
$num = $i + 1;
$name = "$adresses[$i].pdf";
$mail->AddAttachment($path, $name);
}
if ($test)
if ($mail->Send()) return true; else return $mail->ErrorInfo;
else if ($mail->Send()) return true; else return mailClientPDF($mail->From, $address, $subject, $body, $paths, $adresses);
}
function mailClientFromJoywork($address, $subject, $body, $paths = [], $adresses = [], $test = false)
{
require_once($_SERVER['DOCUMENT_ROOT'] . "/engine/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$lg = "robot@joywork.ru";
$mail->From = "robot@joywork.ru";
$mail->FromName = "JoyWork.ru";
$mail->Username = $lg;
$mail->Password = '6@tMRdQbJbllKz#Y';
$mail->Port = 465;
$mail->Host = 'smtp.yandex.ru';
$mail->SMTPSecure = 'ssl';
if($test) $mail->SMTPDebug = 3; // функция с параметром test используется в настройках почты
$mail->isHTML(true);
$mail->AddCustomHeader('X-Mailru-Msgtype: ' . md5($lg) . ';');
$mail->AddCustomHeader('X-Postmaster-Msgtype: ' . md5($lg) . ';');
//$mail->AddCustomHeader('Date: ' . date("D, d M y H:i:s O") . ';');
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->CharSet = "utf-8";
$mail->addAddress($address);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = "Это письмо сгенерировано в формате HTML. Ваш клиент не поддерживает HTML или эта функция выключена.";
$mail->ClearAttachments();
if (isset($paths) && $paths != null) {
foreach ($paths as $i => $path) {
$num = $i + 1;
$name = "$adresses[$i].pdf";
$mail->AddAttachment($path, $name);
}
}
return true;
/*if ($test)
if ($mail->Send()) return true; else return $mail->ErrorInfo;
else if ($mail->Send()) return true; else return mailClientPDF($mail->From, $address, $subject, $body, $paths, $adresses);*/
}
function mailClientPDF($from, $mail_to, $thema, $html, $paths = [], $adresses = [])
{
$from = '=?utf-8?B?' . base64_encode($from) . '?=';
$thema = '=?utf-8?B?' . base64_encode($thema) . '?=';
$EOL = "\r\n"; // ограничитель строк, некоторые почтовые сервера требуют \n - подобрать опытным путём
$boundary = "--" . md5(uniqid(time())); // любая строка, которой не будет ниже в потоке данных.
$headers = "MIME-Version: 1.0;$EOL";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"$EOL";
$headers .= "From: $from";
$multipart = "--$boundary$EOL";
$multipart .= "Content-Type: text/html; charset=utf-8$EOL";
$multipart .= "Content-Transfer-Encoding: base64$EOL";
$multipart .= $EOL; // раздел между заголовками и телом html-части
$multipart .= chunk_split(base64_encode($html));
foreach ($paths as $i => $path) {
$num = $i + 1;
if ($path) {
$fp = fopen($path, "rb");
$file = fread($fp, filesize($path));
fclose($fp);
}
$name = "$num.pdf"; // в этой переменной надо сформировать имя файла (без всякого пути)
$multipart .= "$EOL--$boundary$EOL";
$multipart .= "Content-Type: application/octet-stream; name=\"$name\"$EOL";
$multipart .= "Content-Transfer-Encoding: base64$EOL";
$multipart .= "Content-Disposition: attachment; filename=\"$name\"$EOL";
$multipart .= $EOL; // раздел между заголовками и телом прикрепленного файла
$multipart .= chunk_split(base64_encode($file));
}
$multipart .= "$EOL--$boundary--$EOL";
if (!mail($mail_to, $thema, $multipart, $headers)) return False;
else return True;
exit;
}
function checkMail($address, $subject, $body)
{
require_once($_SERVER['DOCUMENT_ROOT'] . "/engine/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$user = new User;
$user->get($_SESSION['id']);
if ($_SESSION['id'] == 93) {
$mail->SMTPDebug = 2;
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
}
$lg = $user->smtp_lg;
$mail->IsSMTP();
if ($user->smtp) {
$mail->Host = $user->smtp;
$mail->Port = $user->smtp_port;
if ($user->smtp_ssl) {
if ($user->smtp == 'smtp.gmail.com') {
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
} else {
if ($user->smtp == 'smtp.office365.com') {
$mail->SMTPSecure = 'tls';
} else {
$mail->SMTPSecure = 'ssl';
}
}
}
$mail->From = $user->smtp_from;
$mail->FromName = $user->smtp_fromname;
$mail->SMTPAuth = true;
$mail->Username = $user->smtp_lg;
$mail->Password = $user->smtp_pwd;
$mail->isHTML(true);
$mail->AddCustomHeader('X-Mailru-Msgtype: ' . md5($lg) . ';');
$mail->AddCustomHeader('X-Postmaster-Msgtype: ' . md5($lg) . ';');
//$mail->AddCustomHeader('Date: ' . date("D, d M y H:i:s O") . ';');
$mail->smtpConnect([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->CharSet = "utf-8";
$mail->addAddress($address);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = "Это письмо сгенерировано в формате HTML. Ваш клиент не поддерживает HTML или эта функция выключена.";
logf($mail);
if ($mail->Send()) return true; else return $mail->ErrorInfo;
} else return false;
}
function slugify($string) {
$string = transliterator_transliterate("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();", $string);
$string = preg_replace('/[-\s]+/', '-', $string);
return trim($string, '-');
}
function generatePass()
{
$arr = ['a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k',
'm', 'n', 'p', 'r', 's',
't', 'u', 'v', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'J', 'K', 'L',
'M', 'N', 'P', 'R', 'S',
'T', 'U', 'V', 'X', 'Y', 'Z',
'1', '2', '3', '4', '5', '6',
'7', '8', '9'];
// Генерируем пароль
$pass = "";
for ($i = 0; $i < 10; $i++) {
// Вычисляем случайный индекс массива
$index = rand(0, count($arr) - 1);
$pass .= $arr[$index];
}
return $pass;
}
function num_of_pages($page, $all_pages, $param = false) {
if ($page == 1) {
echo "1";
} else {
$prev = $page - 1;
echo "«";
echo "1";
}
if ($all_pages > 8) {
if ($page > 4) {
$ot = $page - 3;
echo "...";
} else {
$ot = 2;
}
if ($page < $all_pages - 4) {
$do = $page + 3;
} else {
$do = $all_pages;
}
} else {
$ot = 2;
$do = $all_pages;
}
for ($i = $ot; $i < $do; $i++) {
if ($i == $page) $cl = "active"; else $cl = "";
echo "$i";
}
if ($all_pages > 8 and $page < $all_pages - 4) {
echo "...";
}
if ($page == $all_pages)
echo "$all_pages";
else {
echo "$all_pages";
$nxt = $page + 1;
echo "»";
}
}
function num_of_pages_for_ajax_with_class($page, $all_pages, $cssClass = '') {
if ($page == 1) {
echo "1";
} else {
$prev = $page - 1;
echo "«";
echo "1";
}
if ($all_pages > 8) {
if ($page > 4) {
$ot = $page - 3;
echo "...";
} else {
$ot = 2;
}
if ($page < $all_pages - 4) {
$do = $page + 3;
} else {
$do = $all_pages;
}
} else {
$ot = 2;
$do = $all_pages;
}
for ($i = $ot; $i < $do; $i++) {
if ($i == $page) {
$cl = "active";
$clLink = "";
} else {
$clLink = $cssClass;
$cl = "";
}
echo "$i";
}
if ($all_pages > 8 and $page < $all_pages - 4) {
echo "...";
}
if ($page == $all_pages) {
echo "$all_pages";
} else {
echo "$all_pages";
$nxt = $page + 1;
echo "»";
}
}
function num_of_pages_for_ajax($page, $all_pages, $param = false) {
if ($page == 1) {
echo "1";
} else {
$prev = $page - 1;
echo "«";
echo "1";
}
if ($all_pages > 8) {
if ($page > 4) {
$ot = $page - 3;
echo "...";
} else {
$ot = 2;
}
if ($page < $all_pages - 4) {
$do = $page + 3;
} else {
$do = $all_pages;
}
} else {
$ot = 2;
$do = $all_pages;
}
for ($i = $ot; $i < $do; $i++) {
if ($i == $page) $cl = "active"; else $cl = "";
echo "$i";
}
if ($all_pages > 8 and $page < $all_pages - 4) {
echo "...";
}
if ($page == $all_pages)
echo "$all_pages";
else {
echo "$all_pages";
$nxt = $page + 1;
echo "»";
}
}
function search_newbuildings($get)
{
$mas_usl_bd = ["1"];
$mas_url_add = array();
if (isset($get['stoim_ot']) && $get['stoim_ot']) {
$stoim_ot = intval(str_replace(' ', '', $get['stoim_ot']));
$mas_usl_bd[] = "a.price >= " . $stoim_ot;
$mas_url_add[] = "stoim_ot=$stoim_ot";
}
if (isset($get['stoim_do']) && $get['stoim_do']) {
$stoim_do = intval(str_replace(' ', '', $get['stoim_do']));
$mas_usl_bd[] = "a.price <= " . $stoim_do;
$mas_url_add[] = "stoim_do=$stoim_do";
}
if (isset($get['sq_all_ot']) && $get['sq_all_ot']) {
$mas_usl_bd[] = "a.space_total >= " . $get['sq_all_ot'];
$mas_url_add[] = "sq_all_ot=" . $get['sq_all_ot'];
}
if (isset($get['sq_all_do']) && $get['sq_all_do']) {
$mas_usl_bd[] = "a.space_total <= " . $get['sq_all_do'];
$mas_url_add[] = "sq_all_do=" . $get['sq_all_do'];
}
if (isset($get['flat_floor_ot']) && $get['flat_floor_ot']) {
$mas_usl_bd[] = "a.flat_floor >= " . $get['flat_floor_ot'];
$mas_url_add[] = "flat_floor_ot=" . $get['flat_floor_ot'];
}
if (isset($get['flat_floor_do']) && $get['flat_floor_do']) {
$mas_usl_bd[] = "a.flat_floor <= " . $get['flat_floor_do'];
$mas_url_add[] = "flat_floor_do=" . $get['flat_floor_do'];
}
if (isset($get['subway']) && $get['subway']) {
$mas_usl_bd[] = "b.id in (select s.block_id from block_subways s where s.subway_id in (" . implode(",",$get['subway']) . "))";
foreach($get['subway'] as $subway) {
$mas_url_add[] = "subway[]=" . $subway;
}
}
if (isset($get['district']) && $get['district']) {
$mas_usl_bd[] = "b.region_id in (" . implode(",",$get['district']) . ")";
foreach($get['district'] as $district) {
$mas_url_add[] = "district[]=" . $district;
}
}
if (isset($get['block']) && $get['block']) {
$mas_usl_bd[] = "b.id in (" . implode(",",$get['block']) . ")";
foreach($get['block'] as $block) {
$mas_url_add[] = "block[]=" . $block;
}
}
if (isset($get['decoration']) && $get['decoration']) {
$mas_usl_bd[] = "a.decoration_id in (" . implode(",",$get['decoration']) . ")";
foreach($get['decoration'] as $decoration) {
$mas_url_add[] = "decoration[]=" . $decoration;
}
}
if (isset($get['builder']) && $get['builder']) {
$mas_usl_bd[] = "b.builder_id in (" . implode(",",$get['builder']) . ")";
foreach($get['builder'] as $builder) {
$mas_url_add[] = "builder[]=" . $builder;
}
}
if (isset($get['type']) && $get['type']) {
$mas_usl_bd[] = "a.room_type_id in (" . implode(",",$get['type']) . ")";
foreach($get['type'] as $type) {
$mas_url_add[] = "type[]=" . $type;
}
}
if (isset($get['variant']) && $get['variant']) {
$mas_usl_bd[] = "a.flat_type_id in (" . implode(",",$get['variant']) . ")";
foreach($get['variant'] as $variant) {
$mas_url_add[] = "variant[]=" . $variant;
}
}
if (isset($get['bank']) && $get['bank']) {
$mas_usl_bd[] = "a.building_id in (select m.building_id from mortgages m where m.program_id in (select bp.id from bank_programs bp where bank_id in (" . implode(",",$get['bank']) . ")))";
foreach($get['bank'] as $bank) {
$mas_url_add[] = "bank[]=" . $bank;
}
}
if (isset($get['period']) && $get['period'] && $get['period'] > 0) {
$mas_usl_bd[] = "a.building_id in (select bd.id from buildings bd where UNIX_TIMESTAMP(bd.deadline) <=" . $get['period'] . ")";
$mas_url_add[] = "period=" . $get['period'];
}
if (isset($get['adres']) && $get['adres']) {
$get['adres'] = mb_strtolower($get['adres'], "UTF-8");
$mas_usl_bd[] = "b.address LIKE '%".$get['adres']."%'";
$mas_url_add[] = "adres=".$get['adres'];
}
$order = " ORDER BY b.id DESC ";
return [$mas_usl_bd, $mas_url_add, $order];
}
function search($get, $cron = false, $favor = [], $sphinx = false)
{
$mas_usl_bd = ["1"];
$mas_url_add = [];
$mas_usl_sph = [];
if ($get['object_id']) {
$mas_usl_bd[] = "objects.id = " . $get['object_id'];
$mas_url_add[] = "object_id = " . $get['object_id'];
$mas_usl_sph[] = "id = " . $get['object_id'];
}
if ($get['type']) {
$mas_usl_bd[] = "objects.type = " . $get['type'];
$mas_url_add[] = "type=" . $get['type'];
$mas_usl_sph[] = "type=" . $get['type'];
}
if ($_GET['metro']) {
$metro = clearInputData($_GET['metro']);
$usl_metro2 = [];
foreach ($metro as $k => $v) {
$mas_url_add[] = "metro[$k]=$v";
$usl_metro[] = "sp_metro.id_metro=" . $v;
$usl_metro2[] = $v;
}
$usl_metro2 = array_unique($usl_metro2);
$mas_usl_bd[] = "(" . implode(" OR ", $usl_metro) . ")";
$mas_usl_sph[] = "id_metro in (" . implode(",", $usl_metro2) . ")";
}
if ($_GET['raion']) {
$rayon = clearInputData($_GET['raion']);
$usl_rayon2 = [];
foreach ($rayon as $k => $v) {
$mas_url_add[] = "raion[$k]=$v";
if($v == 0){
$usl_rayon[] = "objects.id_rf_region = $_GET[region_type]";
}else{
$usl_rayon[] = "objects.rayon = $v";
}
$usl_rayon2[] = $v;
}
$usl_rayon2 = array_unique($usl_rayon2);
$mas_usl_bd[] = "(" . implode(" OR ", $usl_rayon) . ")";
$mas_usl_sph[] = "rayon_id in (" . implode(",", $usl_rayon2) . ")";
}
if ($_GET['renovation'] && ($get['type'] == 1 || $get['type'] == 3)) {
$renovation = clearInputData($_GET['renovation']);
$usl_renovation2 = [];
foreach ($renovation as $k => $v) {
$mas_url_add[] = "renovation[$k]=$v";
if($v == 0){
$usl_renovation[] = "objects.renovation = $_GET[renovation]";
}else{
$usl_renovation[] = "objects.renovation = $v";
}
$usl_renovation2[] = $v;
}
$usl_renovation2 = array_unique($usl_renovation2);
$mas_usl_bd[] = "(" . implode(" OR ", $usl_renovation) . ")";
$mas_usl_sph[] = "renovation in (" . implode(",", $usl_renovation2) . ")";
}
if($_GET['commission']){
$commission = clearInputData($_GET['commission']);
$mas_usl_bd[] = 'commission > 0';
$mas_usl_sph[] = 'commission > 0';
}
// if($get['region_type']){
// $mas_usl_bd[] = "objects.id_rf_region = $get[region_type]";
// }
if ($get['etazh']) {
$mas_usl_bd[] = "objects.etazh > 1";
$mas_url_add[] = "etazh=1";
$mas_usl_sph[] = "etazh > 1";
$etazh = 1;
}
if ($get['house_type'] && $get['operation_type'] == 1) {
if ($get['house_type'] != -1) {
$mas_usl_bd[] = "sale_objects.house_type = " . $get['house_type'];
$mas_url_add[] = "house_type=" . $get['house_type'];
$mas_usl_sph[] = "house_type=" . $get['house_type'];
}
}
if ($get['house_year'] && $get['operation_type'] == 1) {
$mas_usl_bd[] = "sale_objects.build_year <= ".$get['house_year'];
$mas_url_add[] = "house_year=".$get['house_year'];
$mas_usl_sph[] = "build_year <= ".$get['house_year'];
}
if ($get['adres']) {
$get['adres'] = mb_strtolower($get['adres'], "UTF-8");
$mas_usl_bd[] = "objects.adres LIKE '%".$get['adres']."%'";
$mas_url_add[] = "adres=".$get['adres'];
$mas_url_add[] = "adres=" . $get['adres'];
$adres_mas = explode(" ",$get['adres']);
for($a = 0; $a < count($adres_mas); $a++){
if($adres_mas[$a]) {
$mas_usl_sph['match'][] = "@adres " .trim(str_replace("/","-",$adres_mas[$a]));
}
}
}
if ($get['srok'] && $get['operation_type'] == 0) {
$mas_usl_bd[] = "objects.srok = " . $get['srok'];
$mas_url_add[] = "srok=" . $get['srok'];
$mas_usl_sph[] = "srok=" . $get['srok'];
}
if ($get['minut']) {
$mas_url_add[] = "minut=" . $get['minut'];
$mas_url_add[] = "minut_t=" . $get['minut_t'];
if ($get['minut_t'] == "peshkom") {
$peshkom = $get['minut'];
$mas_usl_bd[] = "objects.peshkom <= " . $get['minut'] . " AND transport = 0";
$mas_usl_sph[] = "peshkom <= " . $get['minut'] . " AND transport = 0";
} else {
$transport = $get['minut'];
$mas_usl_bd[] = "objects.transport <= " . $get['minut'];
$mas_usl_sph[] = "transport <= " . $get['minut'];
}
}
if ($get['sq_all_ot']) {
if($get['type'] == 7) {
$mas_usl_bd[] = "objects.land_area >= " . $get['sq_all_ot'];
$mas_usl_sph[] = "land_area >= " . $get['sq_all_ot'];
} else {
$mas_usl_bd[] = "objects.ploshad >= " . $get['sq_all_ot'];
$mas_usl_sph[] = "ploshad >= " . $get['sq_all_ot'];
}
$mas_url_add[] = "sq_all_ot=" . $get['sq_all_ot'];
}
if ($get['sq_all_do']) {
if($get['type'] == 7) {
$mas_usl_bd[] = "objects.land_area <= " . $get['sq_all_do'];
$mas_usl_sph[] = "land_area <= " . $get['sq_all_do'];
} else {
$mas_usl_bd[] = "objects.ploshad <= " . $get['sq_all_do'];
$mas_usl_sph[] = "ploshad <= " . $get['sq_all_do'];
}
$mas_url_add[] = "sq_all_do=" . $get['sq_all_do'];
}
if ($get['sq_land_ot']) {
$mas_usl_bd[] = "objects.land_area >= " . $get['sq_land_ot'];
$mas_usl_sph[] = "land_area >= " . $get['sq_land_ot'];
$mas_url_add[] = "sq_land_ot=" . $get['sq_land_ot'];
}
if ($get['sq_land_do']) {
$mas_usl_bd[] = "objects.land_area <= " . $get['sq_land_do'];
$mas_usl_sph[] = "land_area <= " . $get['sq_land_do'];
$mas_url_add[] = "sq_land_do=" . $get['sq_land_do'];
}
if ($get['etazh_ot'] || $get['etazh_ot_commerc']) {
$etazh_ot = $get['etazh_ot'];
if($get['etazh_ot_commerc']){
$etazh_ot = $get['etazh_ot_commerc'];
$mas_url_add[] = "etazh_ot_commerc=" . $etazh_ot;
}
$mas_usl_bd[] = "objects.etazh >= " . $etazh_ot;
$mas_usl_sph[] = "etazh >= " . $etazh_ot;
if($get['etazh_ot']) {
$mas_url_add[] = "etazh_ot=" . $etazh_ot;
}
}
if ($get['etazh_do'] || $get['etazh_do_commerc']) {
$etazh_do = $get['etazh_do'];
if($get['etazh_do_commerc']){
$etazh_do = $get['etazh_do_commerc'];
$mas_url_add[] = "etazh_do_commerc=" . $etazh_do;
}
$mas_usl_bd[] = "objects.etazh <= " . $etazh_do;
$mas_usl_sph[] = "etazh <= " . $etazh_do;
if($get['etazh_do']) {
$mas_url_add[] = "etazh_do=" . $etazh_do;
}
}
if ($get['year_ot']) {
$mas_usl_bd[] = "sale_objects.build_year >= " . $get['year_ot'];
$mas_usl_sph[] = "build_year >= " . $get['year_ot'];
if($get['year_ot']) {
$mas_url_add[] = "year_ot=" . $get['year_ot'];
}
}
if ($get['year_do']) {
$mas_usl_bd[] = "sale_objects.build_year <= " . $get['year_do'];
$mas_usl_sph[] = "build_year <= " . $get['year_do'];
if($get['year_do']) {
$mas_url_add[] = "year_do=" . $get['year_do'];
}
}
if ($get['etazh_not_first']) {
$mas_usl_bd[] = "objects.etazh <> 1";
$mas_url_add[] = "etazh_not_first=1";
$mas_usl_sph[] = "etazh <> 1";
}
if ($get['etazh_not_last']) {
$mas_usl_bd[] = "objects.etazh <> objects.etazh_iz";
$mas_url_add[] = "etazh_not_last=1";
$mas_usl_sph[] = "not_last_floor = 1";
}
if ($get['sq_live_ot'] && $get['operation_type'] == 1) {
$mas_usl_bd[] = "objects.ploshad_komn >= " . $get['sq_live_ot'];
$mas_usl_sph[] = "ploshad_komn >= " . $get['sq_live_ot'];
$mas_url_add[] = "sq_live_ot=" . $get['sq_live_ot'];
}
if ($get['sq_live_do'] && $get['operation_type'] == 1) {
$mas_usl_bd[] = "objects.ploshad_komn <= " . $get['sq_live_do'];
$mas_usl_sph[] = "ploshad_komn <= " . $get['sq_live_do'];
$mas_url_add[] = "sq_live_do=" . $get['sq_live_do'];
}
if ($get['sq_kitch_ot'] && $get['operation_type'] == 1) {
$mas_usl_bd[] = "objects.ploshad_k >= " . $get['sq_kitch_ot'];
$mas_usl_sph[] = "ploshad_k >= " . $get['sq_kitch_ot'];
$mas_url_add[] = "sq_kitch_ot=" . $get['sq_kitch_ot'];
}
if ($get['sq_kitch_do'] && $get['operation_type'] == 1) {
$mas_usl_bd[] = "objects.ploshad_k <= " . $get['sq_kitch_do'];
$mas_usl_sph[] = "ploshad_k <= " . $get['sq_kitch_do'];
$mas_url_add[] = "sq_kitch_do=" . $get['sq_kitch_do'];
}
//фильтр в сфинксе - в части SELECT, см search_form.php
if ($get['rn1'] || $get['rn2'] || $get['rn3'] || $get['rn4'] || $get['rnStudio']) {
if (!$get['rnStudio']) {
//ищем только по количеству комнат, не студии
$numKomn = array();
if ($get['rn1']) {
$numKomn[] = 1;
$mas_url_add[] = "rn1=1";
}
if ($get['rn2']) {
$numKomn[] = 2;
$mas_url_add[] = "rn2=1";
}
if ($get['rn3']) {
$numKomn[] = 3;
$mas_url_add[] = "rn3=1";
}
if ($get['rn4']) {
for ($i = 4; $i <= 127; $i++) {
$numKomn[] = $i;
}
$mas_url_add[] = "rn4=1";
}
$mas_usl_bd[] = "objects.komnat in (" .implode(',', $numKomn).")";
} else {
if ($get['rn1'] || $get['rn2'] || $get['rn3'] || $get['rn4']) {
//формируем комнаты
$numKomn = array();
if ($get['rn1']) {
$numKomn[] = 1;
$mas_url_add[] = "rn1=1";
}
if ($get['rn2']) {
$numKomn[] = 2;
$mas_url_add[] = "rn2=1";
}
if ($get['rn3']) {
$numKomn[] = 3;
$mas_url_add[] = "rn3=1";
}
if ($get['rn4']) {
for ($i = 4; $i <= 127; $i++) {
$numKomn[] = $i;
}
$mas_url_add[] = "rn4=1";
}
$mas_usl_bd[] = "(objects.studio_flag=1 OR objects.komnat in (" .implode(',', $numKomn)."))";
} else {
$mas_usl_bd[] = "objects.studio_flag=1";
}
$mas_url_add[] = "rnStudio=1";
}
}
if ($get['komn_ot']) {
$mas_usl_bd[] = "objects.komnat >= " . $get['komn_ot'];
$mas_usl_sph[] = "komnat >= " . $get['komn_ot'];
$mas_url_add[] = "komn_ot=" . $get['komn_ot'];
}
if ($get['komn_do']) {
$mas_usl_bd[] = "objects.komnat <= " . $get['komn_do'];
$mas_usl_sph[] = "komnat <= " . $get['komn_do'];
$mas_url_add[] = "komn_do=" . $get['komn_do'];
}
if ($get['ploshad']) {
$get['ploshad'] = str_replace(",", ".", $get['ploshad']);
$mas_usl_bd[] = "objects.ploshad >= " . $get['ploshad'];
$mas_usl_sph[] = "ploshad >= " . $get['ploshad'];
$mas_url_add[] = "ploshad=" . $get['ploshad'];
}
if ($get['ploshad_k']) {
$get['ploshad_k'] = str_replace(",", ".", $get['ploshad_k']);
$mas_usl_bd[] = "objects.ploshad_k >= " . $get['ploshad_k'];
$mas_usl_sph[] = "ploshad_k >= " . $get['ploshad_k'];
$mas_url_add[] = "ploshad_k=" . $get['ploshad_k'];
}
if ($get['holod']) {
//$mas_usl_bd[] = "objects.holod = 1";
$mas_url_add[] = "holod=1";
$holod = 1;
} else $holod = 0;
if ($get['stirka']) {
///$mas_usl_bd[] = "objects.stirka = 1";
$mas_url_add[] = "stirka=1";
$stirka = 1;
} else $stirka = 0;
if ($get['tv']) {
//$mas_usl_bd[] = "objects.tv = 1";
$mas_url_add[] = "tv=1";
$tv = 1;
} else $tv = 0;
if ($get['mebel']) {
//$mas_usl_bd[] = "objects.mebel = 1";
$mas_url_add[] = "mebel=1";
$mebel = 1;
} else $mebel = 0;
if ($get['holod'] or $get['stirka'] or $get['tv'] or $get['mebel']) {
$mas_usl_bd[] = "objects.mebel = '$mebel' AND objects.tv = '$tv' AND objects.stirka = '$stirka' AND objects.holod = '$holod'";
$mas_usl_sph[] = "mebel = '$mebel' AND tv = '$tv' AND stirka = '$stirka' AND holod = '$holod'";
}
if($get['use_area_price']) {
if ($get['stoim_ot']) {
$stoim_ot = intval(str_replace(' ', '', $get['stoim_ot']));
$mas_usl_bd[] = "objects.stoim / objects.ploshad >= " . $stoim_ot;
$mas_usl_sph[] = "area_price >= " . $stoim_ot;
$mas_url_add[] = "stoim_ot=$stoim_ot";
}
if ($get['stoim_do']) {
$stoim_do = intval(str_replace(' ', '', $get['stoim_do']));
$mas_usl_bd[] = "objects.stoim / objects.ploshad <= " . $stoim_do;
$mas_usl_sph[] = "area_price <= " . $stoim_do;
$mas_url_add[] = "stoim_do=$stoim_do";
}
} else {
if ($get['stoim_ot']) {
$stoim_ot = intval(str_replace(' ', '', $get['stoim_ot']));
$mas_usl_bd[] = "objects.stoim >= " . $stoim_ot;
$mas_usl_sph[] = "price_for_order >= " . $stoim_ot;
$mas_url_add[] = "stoim_ot=$stoim_ot";
}
if ($get['stoim_do']) {
$stoim_do = intval(str_replace(' ', '', $get['stoim_do']));
$mas_usl_bd[] = "objects.stoim <= " . $stoim_do;
$mas_usl_sph[] = "price_for_order <= " . $stoim_do;
$mas_url_add[] = "stoim_do=$stoim_do";
}
}
if ($get['date_add']) {
list($d, $m, $y) = explode(".", $get['date_add']);
$date_tm = mktime(0, 0, 0, $m, $d, $y);
$date_ot = "$y-$m-$d";
$mas_usl_bd[] = "UNIX_TIMESTAMP(objects.date_add) >= " . $date_tm;
$mas_usl_sph[] = "date_add >= " . $date_tm;
$mas_url_add[] = "date_add=" . $get['date_add'];
}
if ($get['date_from']) {
list($d, $m, $y) = explode(".", $get['date_from']);
$date_tm = mktime(0, 0, 0, $m, $d, $y);
$mas_usl_bd[] = "UNIX_TIMESTAMP(objects.date_add) >= " . $date_tm;
$mas_usl_sph[] = "date_add >= " . $date_tm;
$mas_url_add[] = "date_from=" . $get['date_from'];
}
if ($get['credit'] && $get['operation_type'] == 1) {
$mas_usl_bd[] = "objects.stoim_prim like '%ипотека%'";
$mas_usl_sph['match'][] = "@stoim_prim ипотека";
$mas_url_add[] = "credit=1";
}
//&& $get['operation_type'] == 1
if ($get['withCommission']) {
$mas_usl_bd[] = "objects.commission > 0";
$mas_usl_sph[] = "commission > 0";
$mas_url_add[] = "withCommission=1";
}
if ($get['photo']) {
$ph = [];
for ($i = 1; $i <= 20; $i++) $ph[] = "objects.photo$i<>''";
$mas_usl_bd[] = "(" . implode(" OR ", $ph) . ")";
$mas_usl_sph[] = "is_photo=1";
$mas_url_add[] = "photo=1";
$photo = 1;
}
if ($get['favor']) {
if (isset($favor) && count($favor) > 0) {
$mas_usl_bd[] = "(objects.id=" . implode(" OR objects.id=", $favor) . ")";
} else {
$mas_usl_bd[] = "objects.id < 0";
}
$mas_url_add[] = "favor=1";
}
if ($get['compObj']) {
$mas_usl_bd[] = "(objects.id_add_user in (SELECT id FROM `users` WHERE id = '$get[agencyId]' or id_manager = '$get[agencyId]' or id_manager in (select id from users where id_manager = '$get[agencyId]')))";
if($sphinx){
//$users_sp = array();
$depClass = new Department();
$adminDep = false;
$searchUserId = $get['agencyId'];
$agentIds = [];
$user = new User;
$user->get($searchUserId);
$searchUserId = $user->agencyId;
$agentIds[] = $user->agencyId;
/*$dep_user = $depClass->getDepartment((int)$_SESSION['id']);
if($dep_user['role'] == 'manager_office'){
$searchUserId = $dep_user['admin'];
$adminDep = true;
} else if($dep_user['role'] == 'manager_office_menager') {
$searchUserId = $user->id_manager;
$adminDep = true;
}*/
//$agentIds[] = $searchUserId;
$agentsOfAgency = User::getAllAgents($searchUserId);
foreach ($agentsOfAgency as $agent) {
if (!in_array($agent['id'], $agentIds)) {
$agentIds[] = $agent['id'];
}
}
// if ($_SESSION['agency'] || $_SESSION['users_admin'] || $adminDep) {
$agentsOfManager = User::getAllManagers($searchUserId);
foreach ($agentsOfManager as $agent) {
if (!in_array($agent['id'], $agentIds)) {
$agentIds[] = $agent['id'];
}
if((int)$agent['role_id'] > 0 && (int)$agent['department_id'] > 0){
$role_user = $depClass->getRole((int)$agent['role_id']);
if($role_user['role'] == 'admin_department'){
$menagerDep = User::getDepManagers($role_user['department_id']);
foreach($menagerDep as $md){
if(!in_array($md['id'], $agentIds)){
$agentIds[] = $md['id'];
$thisAgents = User::getAgentsOfAgency($md['id'], true);
foreach($thisAgents as $da){
if (!in_array($da['id'], $agentIds)) {
$agentIds[] = $da['id'];
}
}
}
}
}
}
}
//}
/*$sql_usr = "SELECT id FROM `users` WHERE id = '$get[agencyId]' or id_manager = '$get[agencyId]' or id_manager in (select id from users where id_manager = '$get[agencyId]')";
if($_SESSION['id'] == 11583){
echo $sql_usr;
}
$q_usr = mysql_query($sql_usr);
$rows = mysql_num_rows($q_usr);
if($rows > 0){
while($row = mysql_fetch_assoc($q_usr)){
$users_sp[] = $row['id'];
}
}*/
//if(empty($users_sp)) $users_sp[] = $get['agencyId'];
$mas_usl_sph[] = "id_add_user in (".implode(',', $agentIds).")";
}
$mas_url_add[] = "compObj=1";
}
if ($get['compObj'] && $get['inAdvert']) {
$mas_usl_bd[] = "objects.use_in_advert > 0";
$mas_usl_sph[] = "use_in_advert > 0";
$mas_url_add[] = "inAdvert=1";
}
if ($get['compObj'] && $get['search_obj_filter_emp']) {
$empWho = array();
foreach($get['search_obj_filter_emp'] as $empId){
if (strpos($empId, "all_") !== false) {
$agencyId = str_replace('all_', '', $empId);
$sql_u = "SELECT id FROM `users`
WHERE id = $agencyId OR
id_manager = $agencyId OR
id_manager IN (SELECT id FROM users WHERE id_manager = $agencyId)";
$q_u = mysql_query($sql_u);
while($r_u = mysql_fetch_row($q_u)){
$empWho[] = $r_u[0];
}
} else {
$empWho[] = $empId;
}
$mas_url_add[] = "search_obj_filter_emp[]=$empId";
}
if (!empty($empWho)) {
$mas_usl_sph[] = "id_add_user IN (" . implode(", ", $empWho) . ")";
$mas_usl_bd[] = " objects.id_add_user IN (" . implode(", ", $empWho) . ")";
}
}
if ($get['compObj'] && $get['search_filter_object_activities']) {
$activities = $get['search_filter_object_activities'];
// Проверяем наличие "no_tags"
$noTagsKey = array_search('no_tags', $activities);
$hasNoTags = ($noTagsKey !== false);
if ($hasNoTags) {
unset($activities[$noTagsKey]);
}
$db_sphinx_local = new MysqlPdo(hstsph, null, null, null, true, '9306');
if ($hasNoTags && !empty($activities)) {
$objWithTags = array();
if (!empty($activities)) {
$sql_a = "SELECT object_id FROM objects_activities WHERE activity_id IN (" . implode(", ", $activities) . ")";
$q_a = mysql_query($sql_a);
if ($q_a) {
while($r_a = mysql_fetch_row($q_a)){
$objWithTags[] = $r_a[0];
}
}
}
$base_sphinx_conditions = implode(" ", $mas_usl_sph);
$base_sphinx_conditions = trim($base_sphinx_conditions);
$where_clause = "";
if ($base_sphinx_conditions !== '') {
$where_clause = $base_sphinx_conditions . " AND has_activities = 0";
} else {
$where_clause = "has_activities = 0";
}
$sql_no_tags_ids = "SELECT id FROM objects WHERE $where_clause AND has_activities = 0 LIMIT 10000 OPTION max_matches=10000";
$result_no_tags = $db_sphinx_local->query($sql_no_tags_ids, true);
$ids_no_tags = array();
if ($result_no_tags) {
while ($row = $db_sphinx_local->fetch_assoc($result_no_tags)) {
$ids_no_tags[] = $row['id'];
}
}
$allIds = array_merge($ids_no_tags, $objWithTags);
$allIds = array_unique($allIds);
if (!empty($allIds)) {
$mas_usl_sph[] = "id IN (" . implode(", ", $allIds) . ")";
$mas_usl_bd[] = " objects.id IN (" . implode(", ", $allIds) . ")";
} else {
$mas_usl_sph[] = "id IN (0)";
$mas_usl_bd[] = " objects.id IN (0)";
}
} elseif ($hasNoTags) {
$mas_usl_sph[] = "has_activities = 0";
$sql_no_tags_ids_mysql = "SELECT id FROM objects WHERE has_activities = 0 LIMIT 10000 OPTION max_matches=10000";
$result_no_tags_mysql = $db_sphinx_local->query($sql_no_tags_ids_mysql, true);
$ids_no_tags_mysql = array();
if ($result_no_tags_mysql) {
while ($row = $db_sphinx_local->fetch_assoc($result_no_tags_mysql)) {
$ids_no_tags_mysql[] = $row['id'];
}
}
if (!empty($ids_no_tags_mysql)) {
$mas_usl_bd[] = " objects.id IN (" . implode(", ", $ids_no_tags_mysql) . ")";
} else {
$mas_usl_bd[] = " objects.id IN (0)";
}
} elseif (!empty($activities)) {
$a_arr = array();
$sql_a = "SELECT object_id FROM objects_activities WHERE activity_id IN (" . implode(", ", $activities) . ")";
$q_a = mysql_query($sql_a);
if ($q_a) {
while($r_a = mysql_fetch_row($q_a)){
$a_arr[] = $r_a[0];
}
}
if (!empty($a_arr)) {
$mas_usl_sph[] = "id IN (" . implode(", ", $a_arr) . ")";
$mas_usl_bd[] = " objects.id IN (" . implode(", ", $a_arr) . ")";
} else {
$mas_usl_sph[] = "id IN (0)";
$mas_usl_bd[] = " objects.id IN (0)";
}
}
}
if ($get['compObj'] && $get['search_filter_object_villages']) {
$villages = $get['search_filter_object_villages'];
if (!empty($villages)) {
$mas_usl_sph[] = "cottage_village_id IN (" . implode(", ", $villages) . ")";
$mas_usl_bd[] = " objects.cottage_village_id IN (" . implode(", ", $villages) . ")";
}
}
if ($get['compObj'] && $get['search_filter_object_highways']) {
$highways = $get['search_filter_object_highways'];
if (!empty($highways)) {
$mas_usl_sph[] = "highway_id IN (" . implode(", ", $highways) . ")";
$mas_usl_bd[] = " objects.highway_id IN (" . implode(", ", $highways) . ")";
}
}
if ($get['compObj'] && $get['house_category']) {
$house_category = $get['house_category'];
if (!empty($house_category)) {
$mas_usl_sph[] = "house_category IN (" . implode(", ", $house_category) . ")";
$mas_usl_bd[] = " objects.house_category IN (" . implode(", ", $house_category) . ")";
}
}
if($get['parent_region']){
$mas_usl_bd[] = "objects.id_rf_region IN (SELECT id FROM rf_regions WHERE id=$get[parent_region] or parent=$get[parent_region])";
if($get['country']){
if($get['country'] == 171){
$mas_usl_sph['match'][] = "@(id_rf_region,parent) $get[parent_region]";
$mas_usl_sph[] = "country_id = 171";
} else {
$mas_usl_sph['match'][] = "@(id_rf_region,parent) 0";
$mas_usl_sph[] = "country_id = {$get['country']}";
}
$mas_url_add[] = "country=".$get['country'];
} else {
$mas_usl_sph['match'][] = "@(id_rf_region,parent) $get[parent_region]";
$mas_usl_sph[] = "country_id = 171";
}
}
/*if($get['country']){
$listCountry = clearInputData($_GET['country']);
if(!in_array(171, $listCountry)){
$idOBJC = array();
$sql_c = "SELECT object_id FROM object_country WHERE country_id in (".implode(',', $listCountry).")";
$q_c = mysql_query($sql_c);
while($r_c = mysql_fetch_assoc($q_c)){
$idOBJC[] = $r_c['object_id'];
}
if(!empty($idOBJC)){
$mas_usl_sph[] = "id in (".implode(',',$idOBJC).")";
} else {
$mas_usl_sph[] = "id in (0)";
}
}
}*/
if ($get['typeCategory'] && $get['type'] == 4) {
$mas_usl_bd[] = "objects.type_category IN (". implode(", ", $get['typeCategory']) . ")";
$mas_usl_sph[] = "type_category IN (". implode(", ", $get['typeCategory']) . ")";
foreach ($get['typeCategory'] as $category) {
$mas_url_add[] = "typeCategory[]=$category";
}
}
if($get['opis']){
$mas_usl_sph['match'][] = "@opis " . $get['opis'];
$mas_url_add[] = "opis=$get[opis]";
}
if($get['type'] == 4 ){
if($get['tax_number']){
$mas_usl_bd[] = "a.tax_number = " . $get['tax_number'];
$mas_usl_sph['match'][] = "@tax_number " . $get['tax_number'];
}
if($get['legal_address']){
$mas_usl_bd[] = "a.legal_address = " .$get['legal_address'];
$mas_usl_sph[] = "legal_address = " .$get['legal_address'];
}
if($get['etazh']){
$mas_usl_bd[] = "objects.etazh = " . $get['etazh'];
$mas_usl_sph[] = "etazh = " . $get['etazh'];
}
if($get['isOccupied']){
$mas_usl_bd[] = "a.isOccupied = " .($get['isOccupied']-1);
$mas_usl_sph[] = "isOccupied = " .($get['isOccupied']-1);
}
if($get['layout_id']){
$mas_usl_bd[] = "a.layout_id = " .$get['layout_id'];
$mas_usl_sph[] = "layout_id = " .$get['layout_id'];
}
if($get['number_wet_spots']){
$mas_usl_bd[] = "a.number_wet_spots = " .$get['number_wet_spots'];
$mas_usl_sph[] = "number_wet_spots = " .$get['number_wet_spots'];
}
if($get['electricity_power_ot']){
$mas_usl_bd[] = "a.electricity_power >= " .$get['electricity_power_ot'];
$mas_usl_sph[] = "electricity_power >= " .$get['electricity_power_ot'];
}
if($get['electricity_power_do']){
$mas_usl_bd[] = "a.electricity_power <= " .$get['electricity_power_do'];
$mas_usl_sph[] = "electricity_power <= " .$get['electricity_power_do'];
}
if($get['commer_condition']){
$mas_usl_bd[] = "a.commer_condition in (".implode(',',$get['commer_condition']).")";
$mas_usl_sph[] = "commer_condition in (".implode(',',$get['commer_condition']).")";
}
if($get['isFurniture']){
$mas_usl_bd[] = "a.isFurniture = " .($get['isFurniture']-1);
$mas_usl_sph[] = "isFurniture = " .($get['isFurniture']-1);
}
if($get['commer_access']){
$mas_usl_bd[] = "a.commer_access = " .$get['commer_access'];
$mas_usl_sph[] = "commer_access = " .$get['commer_access'];
}
if($get['cadastral_number']){
$mas_usl_bd[] = "objects.cadastral_number = " .$get['cadastral_number'];
$mas_usl_sph['match'][] = "@cadastral_number " .$get['cadastral_number'];
}
if($get['parking_type_id']){
$mas_usl_bd[] = "objects.parking_type_id in (".implode(',',$get['parking_type_id']).")";
$mas_usl_sph[] = "parking_type_id in (".implode(',',$get['parking_type_id']).")";
}
if($get['parking_price']){
$mas_usl_bd[] = "a.parking_price = " .$get['parking_price'];
$mas_usl_sph[] = "parking_price = " .$get['parking_price'];
}
if($get['parkingIsFree']){
$mas_usl_bd[] = "a.parkingIsFree = " .$get['parkingIsFree'];
$mas_usl_sph[] = "parkingIsFree = " .$get['parkingIsFree'];
}
if (isset($get['ceiling_height_ot']) && $get['ceiling_height_ot']) {
$mas_usl_bd[] = "a.ceiling_height >= " . $get['ceiling_height_ot'];
$mas_usl_sph[] = "ceiling_height >= " . $get['ceiling_height_ot'];
$mas_url_add[] = "ceiling_height_ot=" . $get['ceiling_height_ot'];
}
if (isset($get['ceiling_height_do']) && $get['ceiling_height_do']) {
$mas_usl_bd[] = "a.ceiling_height <= " . $get['ceiling_height_do'];
$mas_usl_sph[] = "ceiling_height <= " . $get['ceiling_height_do'];
$mas_url_add[] = "ceiling_height_do=" . $get['ceiling_height_do'];
}
if($get['column_grid']){
$mas_usl_bd[] = "a.column_grid = ".$get['column_grid'];
$mas_usl_sph[] = "column_grid = ".$get['column_grid'];
}
if($get['vat_type_id']){
$mas_usl_bd[] = "a.vat_type_id = ".$get['vat_type_id'];
$mas_usl_sph[] = "vat_type_id = ".$get['vat_type_id'];
}
if($get['commerc_site']){
$mas_usl_bd[] = "a.commerc_site = ".$get['commerc_site'];
$mas_usl_sph[] = "commerc_site = ".$get['commerc_site'];
}
if(isset($get['commerc_owned'])){
$mas_usl_bd[] = "a.commerc_owned = ".$get['commerc_owned'];
$mas_usl_sph[] = "commerc_owned = ".$get['commerc_owned'];
}
if($get['floor_material_id']){
$mas_usl_bd[] = "a.floor_material_id in (".implode(',',$get['floor_material_id']).")";
$mas_usl_sph[] = "floor_material_id in (".implode(',',$get['floor_material_id']).")";
}
if($get['commerc_portal_id']){
$mas_usl_bd[] = "a.commerc_portal_id in (".implode(',',$get['commerc_portal_id']).")";
$mas_usl_sph[] = "commerc_portal_id in (".implode(',',$get['commerc_portal_id']).")";
}
if($get['commerc_land_category_id']){
$mas_usl_bd[] = "a.commerc_land_category_id in (".implode(',',$get['commerc_land_category_id']).")";
$mas_usl_sph[]= "commerc_land_category_id in (".implode(',',$get['commerc_land_category_id']).")";
}
if($get['commerc_permitted_use_id']){
$mas_usl_bd[] = "a.commerc_permitted_use_id in (".implode(',',$get['commerc_permitted_use_id']).")";
$mas_usl_sph[] = "commerc_permitted_use_id in (".implode(',',$get['commerc_permitted_use_id']).")";
}
if($get['commerc_lift1']){
$mas_usl_bd[] = "a.commerc_lift1 = ".$get['commerc_lift1'];
$mas_usl_sph[] = "commerc_lift1 = ".$get['commerc_lift1'];
}
if($get['lift1_carrying']){
$mas_usl_bd[] = "a.lift1_carrying = ".$get['lift1_carrying'];
$mas_usl_sph[] = "lift1_carrying = ".$get['lift1_carrying'];
}
if($get['commerc_lift2']){
$mas_usl_bd[] = "a.commerc_lift2 = ".$get['commerc_lift2'];
$mas_usl_sph[] = "commerc_lift2 = ".$get['commerc_lift2'];
}
if($get['lift2_carrying']){
$mas_usl_bd[] = "a.lift2_carrying = ".$get['lift2_carrying'];
$mas_usl_sph[] = "lift2_carrying = ".$get['lift2_carrying'];
}
if($get['commerc_lift3']){
$mas_usl_bd[] = "a.commerc_lift3 = ".$get['commerc_lift3'];
$mas_usl_sph[] = "commerc_lift3 = ".$get['commerc_lift3'];
}
if($get['lift3_carrying']){
$mas_usl_bd[] = "a.lift3_carrying = ".$get['lift3_carrying'];
$mas_usl_sph[] = "lift3_carrying = ".$get['lift3_carrying'];
}
if($get['commerc_crane1']){
$mas_usl_bd[] = "a.commerc_crane1 = ".$get['commerc_crane1'];
$mas_usl_sph[] = "commerc_crane1 = ".$get['commerc_crane1'];
}
if($get['crane1_carrying']){
$mas_usl_bd[] = "a.crane1_carrying = ".$get['crane1_carrying'];
$mas_usl_sph[] = "crane1_carrying = ".$get['crane1_carrying'];
}
if($get['commerc_crane2']){
$mas_usl_bd[] = "a.commerc_crane2 = ".$get['commerc_crane2'];
$mas_usl_sph[] = "commerc_crane2 = ".$get['commerc_crane2'];
}
if($get['crane2_carrying']){
$mas_usl_bd[] = "a.crane2_carrying = ".$get['crane2_carrying'];
$mas_usl_sph[] = "crane2_carrying = ".$get['crane2_carrying'];
}
if($get['commerc_crane3']){
$mas_usl_bd[] = "a.commerc_crane3 = ".$get['commerc_crane3'];
$mas_usl_sph[] = "commerc_crane3 = ".$get['commerc_crane3'];
}
if($get['crane3_carrying']){
$mas_usl_bd[] = "a.crane3_carrying = ".$get['crane3_carrying'];
$mas_usl_sph[] = "crane3_carrying = ".$get['crane3_carrying'];
}
if($get['commerc_crane4']){
$mas_usl_bd[] = "a.commerc_crane4 = ".$get['commerc_crane4'];
$mas_usl_sph[] = "commerc_crane4 = ".$get['commerc_crane4'];
}
if($get['crane4_carrying']){
$mas_usl_bd[] = "a.crane4_carrying = ".$get['crane4_carrying'];
$mas_usl_sph[] = "crane4_carrying = ".$get['crane4_carrying'];
}
if($get['commerc_electricity_id']){
$mas_usl_bd[] = "a.commerc_electricity_id = ".$get['commerc_electricity_id'];
$mas_usl_sph[] = "commerc_electricity_id = ".$get['commerc_electricity_id'];
}
if($get['commerc_gas_id']){
$mas_usl_bd[] = "a.commerc_gas_id = ".$get['commerc_gas_id'];
$mas_usl_sph[] = "commerc_gas_id = ".$get['commerc_gas_id'];
}
if($get['commerc_water_id']){
$mas_usl_bd[] = "a.commerc_water_id = ".$get['commerc_water_id'];
$mas_usl_sph[] = "commerc_water_id = ".$get['commerc_water_id'];
}
if($get['commerc_sewage_id']){
$mas_usl_bd[] = "a.commerc_sewage_id = ".$get['commerc_sewage_id'];
$mas_usl_sph[] = "commerc_sewage_id = ".$get['commerc_sewage_id'];
}
if($get['commerc_driveways_id']){
$mas_usl_bd[] = "a.commerc_driveways_id = ".$get['commerc_driveways_id'];
$mas_usl_sph[] = "commerc_driveways_id = ".$get['commerc_driveways_id'];
}
if($get['commerc_year_ot']){
$mas_usl_bd[] = "a.commerc_year >= " .$get['commerc_year_ot'];
$mas_usl_sph[] = "commerc_year >= " .$get['commerc_year_ot'];
}
if($get['commerc_year_do']){
$mas_usl_bd[] = "a.commerc_year <= " .$get['commerc_year_do'];
$mas_usl_sph[] = "commerc_year <= " .$get['commerc_year_do'];
}
if($get['commerc_building_type_id']){
$mas_usl_bd[] = "a.commerc_building_type_id in (".implode(',',$get['commerc_building_type_id']).")";
$mas_usl_sph[] = "commerc_building_type_id in (".implode(',',$get['commerc_building_type_id']).")";
}
if($get['commerc_building_class_id']){
$mas_usl_bd[] = "a.commerc_building_class_id in (".implode(',',$get['commerc_building_class_id']).")";
$mas_usl_sph[] = "commerc_building_class_id in (".implode(',',$get['commerc_building_class_id']).")";
}
if($get['commerc_specifications']){
$mas_usl_bd[] = "(commerc_specifications like '%".implode('%\' or commerc_specifications like \'%' ,$get['commerc_specifications'])."%')";
$mas_usl_sph['match'][] = "@commerc_specifications (".implode(' | ', $get['commerc_specifications']).")";
}
if($get['commerc_purpose']){
$mas_usl_bd[] = "(a.commerc_purpose like '%\"".implode('"%\' or commerc_purpose like \'%"' ,$get['commerc_purpose'])."\"%')";
$mas_usl_sph['match'][] = "@commerc_purpose (".implode(' | ' ,$get['commerc_purpose']).")";
}
if($get['commerc_infrastructure']){
$mas_usl_bd[] = "(a.commerc_infrastructure like '%\"".implode('"%\' or commerc_infrastructure like \'%"' ,$get['commerc_infrastructure'])."\"%')";
$mas_usl_sph['match'][] = "@commerc_infrastructure ".implode(' | ',$get['commerc_infrastructure']).")";
}
if($get['commerc_infrastructure1']){
$mas_usl_bd[] = "(a.commerc_infrastructure like '%\"".implode('"%\' or commerc_infrastructure like \'%"' ,$get['commerc_infrastructure1'])."\"%')";
$mas_usl_sph['match'][] = "@commerc_infrastructure ".implode(' | ',$get['commerc_infrastructure']).")";
}
if($get['commerc_infrastructure2']){
$mas_usl_bd[] = "(a.commerc_infrastructure like '%\"".implode('"%\' or commerc_infrastructure like \'%"' ,$get['commerc_infrastructure2'])."\"%')";
$mas_usl_sph['match'][] = "@commerc_infrastructure ".implode(' | ',$get['commerc_infrastructure']).")";
}
if (isset($get['building_area_ot']) && $get['building_area_ot']) {
$mas_usl_bd[] = "a.building_area >= " . $get['building_area_ot'];
$mas_usl_sph[] = "building_area >= " . $get['building_area_ot'];
$mas_url_add[] = "building_area_ot=" . $get['building_area_ot'];
}
if (isset($get['building_area_do']) && $get['building_area_do']) {
$mas_usl_bd[] = "a.building_area <= " . $get['building_area_do'];
$mas_usl_sph[] = "building_area <= " . $get['building_area_do'];
$mas_url_add[] = "building_area_do=" . $get['building_area_do'];
}
if($get['commerc_houseLineType_id']){
$mas_usl_bd[] = "a.commerc_houseLineType_id in (".implode(',',$get['commerc_houseLineType_id']).")";
$mas_usl_sph[] = "commerc_houseLineType_id in (".implode(',',$get['commerc_houseLineType_id']).")";
}
if($get['commerc_building_category_id']){
$mas_usl_bd[] = "a.commerc_building_category_id = ".$get['commerc_building_category_id'];
$mas_usl_sph[] = "commerc_building_category_id = ".$get['commerc_building_category_id'];
}
if($get['commerc_opened_id']){
$mas_usl_bd[] = "a.commerc_opened_id in (".implode(',',$get['commerc_opened_id']).")";
$mas_usl_sph[] = "commerc_opened_id in (".implode(',',$get['commerc_opened_id']).")";
}
if($get['commerc_building_ventilation']){
$mas_usl_bd[] = "a.commerc_building_ventilation = ".$get['commerc_building_ventilation'];
$mas_usl_sph[] = "commerc_building_ventilation = ".$get['commerc_building_ventilation'];
}
if($get['commerc_building_conditioning']){
$mas_usl_bd[] = "a.commerc_building_conditioning = ".$get['commerc_building_conditioning'];
$mas_usl_sph[] = "commerc_building_conditioning = ".$get['commerc_building_conditioning'];
}
if($get['commerc_building_heating']){
$mas_usl_bd[] = "a.commerc_building_heating = ".$get['commerc_building_heating'];
$mas_usl_sph[] = "commerc_building_heating = ".$get['commerc_building_heating'];
}
if($get['commerc_building_fire']){
$mas_usl_bd[] = "a.commerc_building_fire = ".$get['commerc_building_fire'];
$mas_usl_sph[] = "commerc_building_fire = ".$get['commerc_building_fire'];
}
if($get['garage_type_id']){
$mas_usl_bd[] = "a.garage_type_id = ".$get['garage_type_id'];
$mas_usl_sph[] = "garage_type_id = ".$get['garage_type_id'];
}
if($get['garage_vid_id']){
$mas_usl_bd[] = "a.garage_vid_id = ".$get['garage_vid_id'];
$mas_usl_sph[] = "garage_vid_id = ".$get['garage_vid_id'];
}
if($get['boks_vid_id']){
$mas_usl_bd[] = "a.boks_vid_id = ".$get['boks_vid_id'];
$mas_usl_sph[] = "boks_vid_id = ".$get['boks_vid_id'];
}
if($get['commerc_status_id']){
$mas_usl_bd[] = "a.commerc_status_id = ".$get['commerc_status_id'];
$mas_usl_sph[] = "commerc_status_id = ".$get['commerc_status_id'];
}
}
// 1. Дата доб. от нового к старому
// 2. Дата доб. от старого к новому
// 3. Дешевле
// 4. Дороже
switch ($get['order']) {
case '2':
$order = "ORDER BY objects.date_add";
if($sphinx){
$order = "ORDER BY date_add ASC";
}
$mas_url_add[] = "order=2";
break;
case '3':
$order = "ORDER BY objects.stoim";
if($sphinx){
$order = "ORDER BY price_for_order ASC";
}
$mas_url_add[] = "order=3";
break;
case '4':
$order = "ORDER BY objects.stoim";
if($sphinx){
$order = "ORDER BY price_for_order DESC";
}
$mas_url_add[] = "order=4";
break;
default:
$order = "ORDER BY objects.date_add";
if($sphinx){
$order = "ORDER BY date_add DESC";
}
$mas_url_add[] = "order=1";
break;
}
if ($sphinx){
return [$mas_usl_sph, $mas_url_add, $order];
}
return [$mas_usl_bd, $mas_url_add, $order];
}
function getWord($number, $suffix)
{
$keys = [2, 0, 1, 1, 1, 2];
$mod = $number % 100;
$suffix_key = ($mod > 7 && $mod < 20) ? 2 : $keys[min($mod % 10, 5)];
return $suffix[$suffix_key];
}
function padezh($kol, $word)
{
$ost = $kol % 100;
if ($ost > 20) $ost %= 10;
switch ($ost) {
case 1:
$end = "";
break;
case 2:
$end = "а";
break;
case 3:
$end = "а";
break;
case 4:
$end = "а";
break;
default:
$end = "ов";
break;
}
return $word . $end;
}
function padezh2($kol, $word)
{
$ost = $kol % 100;
if ($ost > 20) $ost %= 10;
switch ($ost) {
case 1:
$end = "";
break;
case 2:
$end = "а";
break;
case 3:
$end = "а";
break;
case 4:
$end = "а";
break;
default:
$end = "ев";
break;
}
return $word . $end;
}
function padezh3($kol, $word)
{
$ost = $kol % 100;
if ($ost > 20) $ost %= 10;
switch ($ost) {
case 1:
$end = "а";
break;
case 2:
$end = "ы";
break;
case 3:
$end = "ы";
break;
case 4:
$end = "ы";
break;
default:
$end = "";
break;
}
return $word . $end;
}
function padezh_day($kol)
{
$ost = $kol % 100;
if ($ost > 20) $ost %= 10;
switch ($ost) {
case 1:
$end = "день";
break;
case 2:
$end = "дня";
break;
case 3:
$end = "дня";
break;
case 4:
$end = "дня";
break;
default:
$end = "дней";
break;
}
return $end;
}
function setOnline()
{
$sql = "SELECT * FROM online WHERE id_user = $_SESSION[id]";
$rez = mysql_query($sql);
if (mysql_num_rows($rez)) {
$sql = "UPDATE online SET last_activity = NOW() WHERE id_user = $_SESSION[id]";
} else {
$sql = "INSERT INTO online(id_user, last_activity, entry) VALUES($_SESSION[id], NOW(), NOW())";
}
mysql_query($sql);
}
function to_archive($id,$val)
{
if($val)
{
$sql="UPDATE objects SET archive = '1' WHERE id=$id";
mysql_query($sql);
return true;
} else
{
$sql="UPDATE objects SET archive = '0', phone_search = '$num_search' WHERE id=$id";
mysql_query($sql);
return true;
}
}
function getAdresSearch($insert)
{
$replase = ["Санкт-Петербург" => "",
"СПб" => "",
"ул." => "",
"ул" => "",
"улица" => "",
"/" => " ",
"д." => "",
"д " => "",
" г " => "",
"г " => "",
"г. " => "",
" г. " => "",
"," => " ",
"." => " ",
"пр-кт" => "",
"к." => "",
"ш." => "",
"п." => "",
"пл." => "",
"наб." => "",
];
$insert = strtr($insert, $replase);
$insert = trim(mb_strtolower($insert, 'UTF-8'));
return $insert;
}
function getAdresSearchNoLower($insert)
{
$replase = ["Санкт-Петербург" => "",
"СПб" => "",
"ул." => "",
"ул" => "",
"улица" => "",
"/" => " ",
"д." => "",
"д " => "",
" г " => "",
"г " => "",
"г. " => "",
" г. " => "",
"," => " ",
"." => " ",
"пр-кт" => "",
"к." => "",
"ш." => "",
"п." => "",
"пл." => "",
"наб." => "",
];
$insert = strtr($insert, $replase);
$insert = trim($insert);
return $insert;
}
function img_resize($src, $dest, $width, $height, $rgb = 0xFFFFFF, $quality = 100)
{
if (!file_exists($src)) return false;
$size = getimagesize($src);
if ($size === false) return false;
$format = strtolower(substr($size['mime'], strpos($size['mime'], '/') + 1));
$icfunc = "imagecreatefrom" . $format;
if (!function_exists($icfunc)) return false;
if ($height == 100) {
if ($size[0] > $size[1]) {
$width_temp = $height;
$height = $width;
$width = $width_temp;
}
}
if ($size[0] > $size[1]) {
$size[0] = ($size[1] * $width) / $height;
$size[1] = ($size[0] * $height) / $width;
} else {
$size[1] = ($size[0] * $height) / $width;
$size[0] = ($size[1] * $width) / $height;
}
$x_ratio = $width / $size[0];
$y_ratio = $height / $size[1];
$ratio = min($x_ratio, $y_ratio);
$use_x_ratio = ($x_ratio == $ratio);
$new_width = $use_x_ratio ? $width : floor($size[0] * $ratio);
$new_height = !$use_x_ratio ? $height : floor($size[1] * $ratio);
$new_left = $use_x_ratio ? 0 : floor(($width - $new_width) / 2);
$new_top = !$use_x_ratio ? 0 : floor(($height - $new_height) / 2);
$isrc = $icfunc($src);
$idest = imagecreatetruecolor($width, $height);
imagefill($idest, 0, 0, $rgb);
imagecopyresampled($idest, $isrc, $new_left, $new_top, 0, 0,
$new_width, $new_height, $size[0], $size[1]);
imagejpeg($idest, $dest, $quality);
imagedestroy($isrc);
imagedestroy($idest);
return true;
}
function LoadJpeg($imgname)
{
$im = @imagecreatefromjpeg($imgname); /* Attempt to open */
if (!$im) { /* See if it failed */
$im = imagecreatetruecolor(150, 30); /* Create a black image */
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an errmsg */
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
}
return $im;
}
function LoadPNG($imgname)
{
$im = @imagecreatefrompng($imgname); /* Attempt to open */
if (!$im) { /* See if it failed */
$im = imagecreatetruecolor(150, 30); /* Create a blank image */
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an errmsg */
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
}
return $im;
}
/**
* Обрезка изображения
*
* Функция работает с PNG, GIF и JPEG изображениями.
* Обрезка идёт как с указанием абсоютной длины, так и относительной (отрицательной).
*
* @param string Расположение исходного файла
* @param string Расположение конечного файла
* @param array Координаты обрезки
* @param bool Размеры даны в пискелях или в процентах
* @return bool
*/
function cropLogo($file_input, $file_output, $crop = 'square', $percent = false)
{
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
echo 'Невозможно получить длину и ширину изображения';
return false;
}
$types = ['', 'gif', 'jpeg', 'png'];
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom' . $ext;
$img = $func($file_input);
} else {
echo 'Некорректный формат файла';
return false;
}
if ($crop == 'square') {
$min = $w_i;
if ($w_i > $h_i) $min = $h_i;
$w_o = $h_o = $min;
} else {
list($x_o, $y_o, $w_o, $h_o) = $crop;
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
$x_o *= $w_i / 100;
$y_o *= $h_i / 100;
}
if ($w_o < 0) $w_o += $w_i;
$w_o -= $x_o;
if ($h_o < 0) $h_o += $h_i;
$h_o -= $y_o;
}
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopy($img_o, $img, 0, 0, $x_o, $y_o, $w_o, $h_o);
if ($type == 2) {
return imagejpeg($img_o, $file_output, 100);
} else {
$func = 'image' . $ext;
return $func($img_o, $file_output);
}
}
function getRusMonth($month)
{
$rus_month = ["", "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"];
$month *= 1;
return $rus_month[$month];
}
function cleanHtml($html, $strip_tags = false, $encode = false) {
$html = html_entity_decode(trim($html));
$html = preg_replace('/(
<\/p>)+/', '', $html);
$html = str_replace("
","
", $html);
$html = str_replace("
","", $html);
$html = str_replace(" "," ", $html);
$html = str_replace([
"
",
"
",
"",
"
",
],"", $html);
$html = preg_replace('/(
<\/p>)/', '
', $html);
$html = preg_replace('/(
\s+
)/', '
', $html);
$html = preg_replace('/(
)/', '
', $html);
$html = preg_replace('/(
){3,}/', '
', $html);
$html = str_replace("
","", $html);
$html = str_replace("
","", $html);
$html = str_replace("
","", $html);
$html = str_replace("
","
", $html);
$html = preg_replace('/\r+/u', ' ', $html);
$html = preg_replace('/\n+/u', ' ', $html);
$html = str_replace(" "," ", $html);
if ($strip_tags) {
if (is_scalar($strip_tags) || is_array($strip_tags))
$html = strip_tags($html, $strip_tags);
else
$html = strip_tags($html);
}
if ($encode)
return htmlentities($html);
return $html;
}
function br2nl($html) {
$html = nl2br(strip_tags($html, '
- '));
$html = preg_replace('/(
)/ui', "
", $html);
$html = preg_replace('/(.*?)<\/p>/ui', "$1
", $html);
$html = preg_replace('/
(.*?)<\/ul>/ui', "$1
", $html);
$html = preg_replace('/(.*?)<\/ol>/ui', "$1
", $html);
$html = preg_replace('/- (.*?)<\/li>/ui', "$1
", $html);
$html = str_replace([
"
",
"
",
"
",
"",
"
",
"",
],"", $html);
$html = preg_replace('/(
){2,}/ui', "\n\n", $html);
$html = preg_replace('/(
)/ui', "\n", $html);
return $html;
}
function d($p)
{
echo "
";
var_dump($p);
echo "
";
}
function logf($mixed)
{
file_put_contents('debug.txt', print_r($mixed, true), FILE_APPEND);
}
function square_crop($src_image, $dest_image, $thumb_size = 64, $jpg_quality = 90) {
$image = getimagesize($src_image);
if ($image[0] <= 0 || $image[1] <= 0)
return false;
$image['format'] = strtolower(preg_replace('/^.*?\//', '', $image['mime']));
switch($image['format']) {
case 'jpg':
case 'jpeg':
$image_data = imagecreatefromjpeg($src_image);
break;
case 'png':
$image_data = imagecreatefrompng($src_image);
break;
case 'gif':
$image_data = imagecreatefromgif($src_image);
break;
default:
return false;
break;
}
if ($image_data == false)
return false;
if ($image[0] > $image[1]) {
$x_offset = ($image[0] - $image[1]) / 2;
$y_offset = 0;
$square_size = $image[0] - ($x_offset * 2);
} else {
$x_offset = 0;
$y_offset = ($image[1] - $image[0]) / 2;
$square_size = $image[1] - ($y_offset * 2);
}
$canvas = imagecreatetruecolor($thumb_size, $thumb_size);
if(imagecopyresampled(
$canvas,
$image_data,
0,
0,
$x_offset,
$y_offset,
$thumb_size,
$thumb_size,
$square_size,
$square_size
)) {
switch(strtolower(preg_replace('/^.*\./', '', $dest_image))) {
case 'jpg':
case 'jpeg':
return imagejpeg($canvas, $dest_image, $jpg_quality);
break;
case 'png':
return imagepng($canvas, $dest_image);
break;
case 'gif':
return imagegif($canvas, $dest_image);
break;
default:
return false;
break;
}
} else {
return false;
}
}
function resize_img($newWidth, $targetFile, $originalFile) {
$info = getimagesize($originalFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
//$new_image_ext = 'jpg';
break;
case 'image/png':
$image_create_func = 'imagecreatefrompng';
$image_save_func = 'imagepng';
//$new_image_ext = 'png';
break;
case 'image/gif':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
//$new_image_ext = 'gif';
break;
default:
throw new Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, $targetFile);
}
function num_search($num)
{
$num_search = str_replace("+","",$num);
$num_search = str_replace("(","",$num_search);
$num_search = str_replace(")","",$num_search);
$num_search = str_replace(" ","",$num_search);
$num_search = str_replace("-","",$num_search);
$num_search = trim($num_search);
if(mb_strlen($num_search)>7) $num_search = mb_substr($num_search,1);
return $num_search;
}
/**
* resize method
* Resize, crop and rotate images
*
* @public
* @static
* @param $filename {String} file source
* @param $width {Number} new width
* @param $height {Number} new height
* @param $destination {String} file destination
* @param $crop {boolean, Array} crop property
* @param $quality {Number} quality of destination
* @param $rotation {Number} rotation degrees
* @return {boolean} resizing was successful
*/
function resize($filename, $width = null, $height = null, $destination = null, $crop = false, $quality = 90, $rotation = 0, $flip = 0) {
if (!is_file($filename) || !is_readable($filename))
return false;
$source = null;
$destination = !$destination ? $filename : $destination;
if (file_exists($destination) && !is_writable($destination))
return false;
$imageInfo = getimagesize($filename);
if (!$imageInfo)
return false;
// detect actions
$hasRotation = $rotation;
$hasFlip = $flip;
$hasCrop = is_array($crop) || $crop == true;
$hasResizing = $width || $height;
if (!$hasRotation && !$hasCrop && !$hasResizing && !$hasFlip)
return;
// store image information
list ($imageWidth, $imageHeight, $imageType) = $imageInfo;
$imageRatio = $imageWidth / $imageHeight;
// create GD image
switch($imageType) {
case IMAGETYPE_GIF:
$source = imagecreatefromgif($filename);
break;
case IMAGETYPE_JPEG:
$source = imagecreatefromjpeg($filename);
break;
case IMAGETYPE_PNG:
$source = imagecreatefrompng($filename);
break;
default:
return false;
}
// rotation
if ($hasRotation) {
if ($rotation == 90 || $rotation == 270) {
$cacheWidth = $imageWidth;
$cacheHeight = $imageHeight;
$imageWidth = $cacheHeight;
$imageHeight = $cacheWidth;
}
$rotation = $rotation * -1;
$source = imagerotate($source, $rotation, 0);
}
// flip
if ($hasFlip) {
if ($flip == 1)
imageflip($source, IMG_FLIP_VERTICAL);
elseif ($flip == 2)
imageflip($source, IMG_FLIP_HORIZONTAL);
}
// crop
$crop = array_merge(array(
'left' => 0,
'top' => 0,
'width' => $imageWidth,
'height' => $imageHeight,
'_paramCrop' => $crop
), is_array($crop) ? $crop : array());
if (is_array($crop['_paramCrop'])) {
$crop['left'] = $crop['_paramCrop']['left'];
$crop['top'] = $crop['_paramCrop']['top'];
$crop['width'] = $crop['_paramCrop']['width'];
$crop['height'] = $crop['_paramCrop']['height'];
}
// set default $width and $height
$width = !$width ? $crop['width'] : $width;
$height = !$height ? $crop['height'] : $height;
// resize
if ($crop['width'] < $width && $crop['height'] < $height) {
$width = $crop['width'];
$height = $crop['height'];
$hasResizing = false;
}
if ($hasResizing) {
$ratio = $width/$height;
if ($crop['_paramCrop'] === true) {
if ($imageRatio >= $ratio) {
$crop['newWidth'] = $crop['width'] / ($crop['height'] / $height);
$crop['newHeight'] = $height;
} else {
$crop['newHeight'] = $crop['height'] / ($crop['width'] / $width);
$crop['newWidth'] = $width;
}
$crop['left'] = 0 - ($crop['newWidth'] - $width) / 2;
$crop['top'] = 0 - ($crop['newHeight'] - $height) / 2;
} else {
$newRatio = $crop['width'] / $crop['height'];
if ($ratio > $newRatio) {
$width = $height * $newRatio;
} else {
$height = $width / $newRatio;
}
}
}
// save
$dest = null;
$destExt = strtolower(substr($destination, strrpos($destination, '.') + 1));
if (pathinfo($destination, PATHINFO_EXTENSION)) {
if (in_array($destExt, array('gif', 'jpg', 'jpeg', 'png'))) {
if ($destExt == 'gif')
$imageType = IMAGETYPE_GIF;
if ($destExt == 'jpg' || $destExt == 'jpeg')
$imageType = IMAGETYPE_JPEG;
if ($destExt == 'png')
$imageType = IMAGETYPE_PNG;
}
} else {
$imageType = IMAGETYPE_JPEG;
$destination .= '.jpg';
}
switch($imageType) {
case IMAGETYPE_GIF:
$dest = imagecreatetruecolor($width, $height);
$background = imagecolorallocatealpha($dest, 255, 255, 255, 1);
imagecolortransparent($dest, $background);
imagefill($dest, 0, 0 , $background);
imagesavealpha($dest, true);
break;
case IMAGETYPE_JPEG:
$dest = imagecreatetruecolor($width, $height);
$background = imagecolorallocate($dest, 255, 255, 255);
imagefilledrectangle($dest, 0, 0, $width, $height, $background);
break;
case IMAGETYPE_PNG:
if (!imageistruecolor($source)) {
$dest = imagecreate($width, $height);
$background = imagecolorallocatealpha($dest, 255, 255, 255, 1);
imagecolortransparent($dest, $background);
imagefill($dest, 0, 0 , $background);
} else {
$dest = imagecreatetruecolor($width, $height);
}
imagealphablending($dest, false);
imagesavealpha($dest, true);
break;
default:
return false;
}
imageinterlace($dest, true);
imagecopyresampled(
$dest,
$source,
isset($crop['newWidth']) ? $crop['left'] : 0,
isset($crop['newHeight']) ? $crop['top'] : 0,
!isset($crop['newWidth']) ? $crop['left'] : 0,
!isset($crop['newHeight']) ? $crop['top'] : 0,
isset($crop['newWidth']) ? $crop['newWidth'] : $width,
isset($crop['newHeight']) ? $crop['newHeight'] : $height,
$crop['width'],
$crop['height']
);
switch ($imageType) {
case IMAGETYPE_GIF:
imagegif($dest, $destination);
break;
case IMAGETYPE_JPEG:
imagejpeg($dest, $destination, $quality);
break;
case IMAGETYPE_PNG:
imagepng($dest, $destination, 10-$quality/10);
break;
}
imagedestroy($source);
imagedestroy($dest);
return true;
}
function fix_image_orientation($working_image) {
$orientation = $working_image->getImageOrientation();
if (!empty($orientation)) {
switch ($orientation) {
default:
case imagick::ORIENTATION_TOPLEFT:
break;
case imagick::ORIENTATION_TOPRIGHT:
$working_image->flipImage();
$working_image->rotateImage("#000", 180);
break;
case imagick::ORIENTATION_BOTTOMRIGHT:
$working_image->rotateImage("#000", 180);
break;
case imagick::ORIENTATION_BOTTOMLEFT:
$working_image->flipImage();
break;
case imagick::ORIENTATION_LEFTTOP:
$working_image->rotateImage("#000", -90);
$working_image->flipImage();
break;
case imagick::ORIENTATION_RIGHTTOP:
$working_image->rotateImage("#000", 90);
break;
case imagick::ORIENTATION_RIGHTBOTTOM:
$working_image->rotateImage("#000", 90);
$working_image->flipImage();
break;
case imagick::ORIENTATION_LEFTBOTTOM:
$working_image->rotateImage("#000", -90);
break;
}
}
$working_image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
}
function curl_request_zipal_json($url, $user_id, $user_agent, $post)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CERTINFO, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $_SERVER['DOCUMENT_ROOT'].'/zipal/' . $user_id . '.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, $_SERVER['DOCUMENT_ROOT'].'/zipal/' . $user_id . '.txt'); //Имя файла, содержащего данные cookie
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // запретить проверку сертификата удаленного сервера
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); //"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0"
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HEADER, 0); // При установке этого параметра в 1 результат будет включать полученные заголовки.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // При установке этого параметра в ненулевое значение CURL будет возвращать результат, а не выводить его.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //при получении HTTP заголовка "Location: " будет происходить перенаправление на указанный этим заголовком URL
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 12);
if($post) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
function encode_array($args)
{
if(!is_array($args)) return false;
$c = 0;
$out = '';
foreach($args as $name => $value)
{
if($c++ != 0) $out .= '&';
$out .= urlencode("$name").'=';
if(is_array($value))
{
$out .= urlencode(serialize($value));
}else{
$out .= urlencode("$value");
}
}
return trim($out);
}
if(!function_exists('cal_days_in_month')) {
function cal_days_in_month($calendar, $month, $year) {
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
}
function getPeriod($period, $onDate=null, $offDate = null, $useTimeForDateStart = false){
$mounthArrray = [ "Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь" ];
$treplace = array (
"Январь" => "января",
"Февраль" => "февраля",
"Март" => "марта",
"Апрель" => "апреля",
"Май" => "мая",
"Июнь" => "июня",
"Июль" => "июля",
"Август" => "августа",
"Сентябрь" => "сентября",
"Октябрь" => "октября",
"Ноябрь" => "ноября",
"Декабрь" => "декабря");
$months = array(1,2,3,4,5,6,7,8,9,10,11,12);
$years = array();
$monthsyears = array();
$firstDay = '';
$lastDay = '';
$totalDays = 365;
$readPeriod = '';
$diffDays = 0;
$firstNameMonth = $lastNameMonth = $nameMonth = '';
$years[] = date('Y');
$date_between = "between '1970-01-01 00:00:00' AND '3000-12-31 23:59:59'";
$dateStart = "1970-01-01 00:00:00";
$dateEnd = "3000-12-31 23:59:59";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '1970-01-01 00:00:00' AND '3000-12-31 23:59:59'";
if($period == 'period') $period = 'dates';
switch ($period){
case 'today': {
$months = array();
$months[] = (int)date('m');
$firstDay = date('d');
$totalDays = cal_days_in_month(CAL_GREGORIAN, (int)date('m'), date('Y'));
$readPeriod = $mounthArrray[(int)date('m') - 1].' '.date('Y').' года';
$datetime1 = new DateTime(date('Y-m-d'));
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->d;
$lastDay = $totalDays;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$firstNameMonth = $lastNameMonth = $nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$date_between = "between '".date("Y-m-d")." 00:00:00' AND '".date("Y-m-d")." 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date("Y-m-d")." 00:00:00' AND '".date("Y-m-d")." 23:59:59'";
$dateStart = date("Y-m-d")." 00:00:00";
$dateEnd = date("Y-m-d")." 23:59:59";
$period = new DatePeriod(
new DateTime($dateStart),
new DateInterval('P1D'),
new DateTime($dateEnd)
);
foreach ($period as $key => $value) {
if(!in_array((int)$value->format('m'), $months)){
$months[] = (int)$value->format('m');
}
if(!in_array($value->format('n-Y'),$monthsyears)){
$monthsyears[] = $value->format('n-Y');
}
}
break;
}
case 'month': {
$months = array();
$months[] = (int)date('m');
$firstDay = '01';
$totalDays = cal_days_in_month(CAL_GREGORIAN, (int)date('m'), date('Y'));
$readPeriod = $mounthArrray[(int)date('m') - 1].' '.date('Y').' года';
$datetime1 = new DateTime(date('Y').'-'.date('m').'-01');
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->d;
$lastDay = $totalDays;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$firstNameMonth = $lastNameMonth = $nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$date_between = "between '".date('Y')."-".date('m')."-01 00:00:00' AND '".date('Y')."-".date('m')."-".$lastDay." 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y')."-".date('m')."-01 00:00:00' AND '".date('Y')."-".date('m')."-".$lastDay." 23:59:59'";
$dateStart = date('Y')."-".date('m')."-01 00:00:00";
$dateEnd = date('Y')."-".date('m')."-".$lastDay." 23:59:59";
$period = new DatePeriod(
new DateTime($dateStart),
new DateInterval('P1D'),
new DateTime($dateEnd)
);
foreach ($period as $key => $value) {
if(!in_array((int)$value->format('m'), $months)){
$months[] = (int)$value->format('m');
}
if(!in_array($value->format('n-Y'),$monthsyears)){
$monthsyears[] = $value->format('n-Y');
}
}
break;
}
case 'quarter' : {
$nowMounth = (int)date('m');
if ($nowMounth < 4) {
$months = array();
$months[] = 1;
$months[] = 2;
$months[] = 3;
$years[] = date('Y');
$firstDay = '01';
$lastDay = '31';
$firstNameMonth = $treplace[$mounthArrray[0]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[2]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
$datetime1 = new DateTime(date('Y').'-01-01');
$datetime2 = new DateTime(date('Y').'-03-31');
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date('Y').'-01-01');
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$date_between = "between '".date('Y')."-01-01 00:00:00' AND '".date('Y')."-03-31 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y')."-01-01 00:00:00' AND '".date('Y')."-03-31 23:59:59'";
$dateStart = date('Y')."-01-01 00:00:00";
$dateEnd = date('Y')."-03-31 23:59:59";
} else if($nowMounth >= 4 && $nowMounth < 7){
$months = array();
$months[] = 4;
$months[] = 5;
$months[] = 6;
$years[] = date('Y');
$firstDay = '01';
$lastDay = '30';
$firstNameMonth = $treplace[$mounthArrray[3]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[5]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
$datetime1 = new DateTime(date('Y').'-04-01');
$datetime2 = new DateTime(date('Y').'-06-30');
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date('Y').'-04-01');
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$date_between = "between '".date('Y')."-04-01 00:00:00' AND '".date('Y')."-06-30 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y')."-04-01 00:00:00' AND '".date('Y')."-06-30 23:59:59'";
$dateStart = date('Y')."-04-01 00:00:00";
$dateEnd = date('Y')."-06-30 23:59:59";
} else if ($nowMounth >= 7 && $nowMounth < 10){
$months = array();
$months[] = 7;
$months[] = 8;
$months[] = 9;
$years[] = date('Y');
$firstDay = '01';
$lastDay = '30';
$firstNameMonth = $treplace[$mounthArrray[6]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[8]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
$datetime1 = new DateTime(date('Y').'-07-01');
$datetime2 = new DateTime(date('Y').'-09-30');
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date('Y').'-07-01');
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$date_between = "between '".date('Y')."-07-01 00:00:00' AND '".date('Y')."-09-30 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y')."-07-01 00:00:00' AND '".date('Y')."-09-30 23:59:59'";
$dateStart = date('Y')."-07-01 00:00:00";
$dateEnd = date('Y')."-09-30 23:59:59";
} else if ($nowMounth >= 10 && $nowMounth < 13){
$months = array();
$months[] = 10;
$months[] = 11;
$months[] = 12;
$years[] = date('Y');
$firstDay = '01';
$lastDay = '31';
$firstNameMonth = $treplace[$mounthArrray[9]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[11]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
$datetime1 = new DateTime(date('Y').'-10-01');
$datetime2 = new DateTime(date('Y').'-12-31');
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date('Y').'-10-01');
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$date_between = "between '".date('Y')."-10-01 00:00:00' AND '".date('Y')."-12-31 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y')."-10-01 00:00:00' AND '".date('Y')."-12-31 23:59:59'";
$dateStart = date('Y')."-10-01 00:00:00";
$dateEnd = date('Y')."-12-31 23:59:59";
}
$period = new DatePeriod(
new DateTime($dateStart),
new DateInterval('P1D'),
new DateTime($dateEnd)
);
foreach ($period as $key => $value) {
if(!in_array((int)$value->format('m'), $months)){
$months[] = (int)$value->format('m');
}
if(!in_array($value->format('n-Y'),$monthsyears)){
$monthsyears[] = $value->format('n-Y');
}
}
break;
}
case 'week': {
$months = array();
$months[] = (int)date('m');
$years = array();
$years[] = date('Y');
$firstDay = date("d", strtotime("monday this week"));
$lastDay = date("d", strtotime("sunday this week"));
$firstNameMonth = $treplace[$mounthArrray[(int)date("m", strtotime("monday this week")) - 1]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[(int)date("m", strtotime("sunday this week")) - 1]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
$datetime1 = new DateTime(date("Y-m-d", strtotime("monday this week")));
$datetime2 = new DateTime(date("Y-m-d", strtotime("sunday this week")));
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date("Y-m-d", strtotime("monday this week")));
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$date_between = "between '".date("Y-m-d 00:00:00", strtotime("monday this week"))."' AND '".date("Y-m-d 23:59:59", strtotime("sunday this week"))."'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date("Y-m-d 00:00:00", strtotime("monday this week"))."' AND '".date("Y-m-d 23:59:59", strtotime("sunday this week"))."'";
$dateStart = date("Y-m-d 00:00:00", strtotime("monday this week"));
$dateEnd = date("Y-m-d 23:59:59", strtotime("sunday this week"));
$period = new DatePeriod(
new DateTime($dateStart),
new DateInterval('P1D'),
new DateTime($dateEnd)
);
foreach ($period as $key => $value) {
if(!in_array((int)$value->format('m'), $months)){
$months[] = (int)$value->format('m');
}
if(!in_array($value->format('n-Y'),$monthsyears)){
$monthsyears[] = $value->format('n-Y');
}
}
break;
}
case 'dates' : {
if(empty($offDate)) $offDate = date('Y-m-d 23:59:59');
$months = array();
$years = array();
$years[] = date("Y", strtotime($onDate));
$years[] = date("Y", strtotime($offDate));
$firstDay = date("d", strtotime($onDate));
$lastDay = date("d", strtotime($offDate));
$firstNameMonth = $treplace[$mounthArrray[(int)date("m", strtotime($onDate)) - 1]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[(int)date("m", strtotime($offDate)) - 1]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
$datetime1 = new DateTime(date("Y-m-d", strtotime($onDate)));
$datetime2 = new DateTime(date("Y-m-d", strtotime($offDate)));
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date("Y-m-d", strtotime($onDate)));
$datetime2 = new DateTime(date('Y-m-d'));
if($datetime1 < $datetime2){
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
}
$procentDays = 0;
if ($useTimeForDateStart) {
$date_between = "between '" . date("Y-m-d H:i:s", strtotime($onDate)) . "' AND '" . date("Y-m-d 23:59:59", strtotime($offDate)) . "'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '" . date("Y-m-d H:i:s", strtotime($onDate)) . "' AND '" . date("Y-m-d 23:59:59", strtotime($offDate)) . "'";
$dateStart = date("Y-m-d H:i:s", strtotime($onDate));
$dateEnd = date("Y-m-d 23:59:59", strtotime($offDate));
} else {
$date_between = "between '" . date("Y-m-d 00:00:00", strtotime($onDate)) . "' AND '" . date("Y-m-d 23:59:59", strtotime($offDate)) . "'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '" . date("Y-m-d 00:00:00", strtotime($onDate)) . "' AND '" . date("Y-m-d 23:59:59", strtotime($offDate)) . "'";
$dateStart = date("Y-m-d 00:00:00", strtotime($onDate));
$dateEnd = date("Y-m-d 23:59:59", strtotime($offDate));
}
$period = new DatePeriod(
new DateTime($dateStart),
new DateInterval('P1D'),
new DateTime($dateEnd)
);
foreach ($period as $key => $value) {
if(!in_array((int)$value->format('m'), $months)){
$months[] = (int)$value->format('m');
}
if(!in_array($value->format('n-Y'),$monthsyears)){
$monthsyears[] = $value->format('n-Y');
}
}
break;
}
case '30days': {
$months = array();
$lastDay = date('d');
$totalDays = 30;
$datetime1 = new DateTime(date('Y-m-d', strtotime('-30 day')));
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->d;
$firstDay = date('d', strtotime('-30 day'));
$procentDays = (int)(($diffDays/$totalDays) * 100);
$firstNameMonth = $lastNameMonth = $nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$date_between = "between '".date('Y-m-d', strtotime('-30 day'))." 00:00:00' AND '".date("Y-m-d")." 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y-m-d', strtotime('-30 day'))." 00:00:00' AND '".date("Y-m-d")." 23:59:59'";
$dateStart = date('Y-m-d', strtotime('-30 day'))." 00:00:00";
$dateEnd = date("Y-m-d")." 23:59:59";
$months[] = (int)date('m', strtotime($dateStart));
$months[] = (int)date('m');
$firstNameMonth = $treplace[$mounthArrray[(int)date('m', strtotime($dateStart)) - 1]];
$lastNameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
break;
}
case '90days': {
$months = array();
$lastDay = date('d');
$totalDays = 90;
$datetime1 = new DateTime(date('Y-m-d', strtotime('-30 day')));
//$datetime1 = new DateTime(date('Y-m-d'));
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->d;
$firstDay = date('d', strtotime('-90 day'));
$procentDays = (int)(($diffDays/$totalDays) * 100);
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$date_between = "between '".date('Y-m-d', strtotime('-90 day'))." 00:00:00' AND '".date("Y-m-d")." 23:59:59'";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y-m-d', strtotime('-90 day'))." 00:00:00' AND '".date("Y-m-d")." 23:59:59'";
$dateStart = date('Y-m-d', strtotime('-90 day'))." 00:00:00";
$dateEnd = date("Y-m-d")." 23:59:59";
$monthsFirst = (int)date('m', strtotime($dateStart));
$monthsEnd = (int)date('m');
$firstNameMonth = $treplace[$mounthArrray[(int)date('m', strtotime($dateStart))-1]];
$lastNameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$readPeriod = 'c '.$firstDay.' '.$firstNameMonth. ' по ' . $lastDay . ' ' .$lastNameMonth;
$period = new DatePeriod(
new DateTime($dateStart),
new DateInterval('P1D'),
new DateTime($dateEnd)
);
foreach ($period as $key => $value) {
if(!in_array((int)$value->format('m'), $months)){
$months[] = (int)$value->format('m');
}
if(!in_array($value->format('n-Y'),$monthsyears)){
$monthsyears[] = $value->format('n-Y');
}
}
break;
} case 'year': {
$firstDay = '01';
$lastDay = '31';
$firstNameMonth = $treplace[$mounthArrray[0]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[11]];
$readPeriod = date('Y').' год';
$datetime1 = new DateTime(date('Y').'-01-01');
$datetime2 = new DateTime(date('Y').'-12-31');
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date('Y').'-01-01');
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '".date('Y')."-01-01 00:00:00' AND '".date('Y')."-12-31 23:59:59'";
$date_between = "between '".date('Y')."-01-01 00:00:00' AND '".date('Y')."-12-31 23:59:59'";
$dateStart = date('Y')."-01-01 00:00:00";
$dateEnd = date('Y')."-12-31 23:59:59";
break;
}
default: {
$months = array(1,2,3,4,5,6,7,8,9,10,11,12);
$years[] = date('Y');
$firstDay = '01';
$lastDay = '31';
$firstNameMonth = $treplace[$mounthArrray[0]];
$nameMonth = $treplace[$mounthArrray[(int)date('m') - 1]];
$lastNameMonth = $treplace[$mounthArrray[11]];
$readPeriod = 'Все время';
$datetime1 = new DateTime(date('Y', strtotime('-5 year')).'-01-01');
$datetime2 = new DateTime(date('Y').'-12-31');
$difference = $datetime1->diff($datetime2);
$totalDays = $difference->days + 1;
$datetime1 = new DateTime(date('Y', strtotime('-5 year')).'-01-01');
$datetime2 = new DateTime(date('Y-m-d'));
$difference = $datetime1->diff($datetime2);
$diffDays = $difference->days;
$procentDays = (int)(($diffDays/$totalDays) * 100);
$date_between = "between '1970-01-01 00:00:00' AND '3000-12-31 23:59:59'";
$dateStart = "1970-01-01 00:00:00";
$dateEnd = "3000-12-31 23:59:59";
$whereTasks = " and DATE_FORMAT(schedule_date, '%Y-%m-%d %H:%i:%s') between '1970-01-01 00:00:00' AND '3000-12-31 23:59:59'";
break;
}
}
$result = array('between'=>$date_between, 'whereTasks'=>$whereTasks, 'dateStart'=>$dateStart, 'dateEnd'=>$dateEnd, 'months' => $months, 'years'=>$years, 'readPeriod'=>$readPeriod, 'totalDays'=>$totalDays, 'monthsyears'=>$monthsyears);
return $result;
}
function get_nazv_object($obj){
$title = '';
$temp_title = '';
switch ($obj['type']) {
case 1:
if (($obj['komnat'] == 1 || (int)$obj['komnat'] == 0)&& $obj['studio_flag']) {
$temp_title = "Квартира-студия";
} else {
$temp_title = "{$obj['komnat']}-комнатная квартира";
}
break;
case 2:
$temp_title = "Комната в {$obj['komnat']}-комнатной квартире";
break;
case 3:
/*$temp_title = "{$obj['komnat']}-комнатный дом";
if($obj['komnat'] == 0){
$temp_title = "Дом";
}*/
$temp_title = '';
break;
case 4:
$temp_title = '';
/* if ($obj['komnat'] == 0) {
$temp_title = "Помещение";
} else {
$temp_title = "{$obj['komnat']}-комнатное помещение";
}*/
break;
case 5:
// $temp_title = "Часть дома";
$temp_title = '';
break;
case 6:
$temp_title = "Комплекс";
break;
case 7:
$temp_title = "Участок";
break;
default:
$temp_title = "";
}
//echo $temp_title;
$title = '';
if(!empty($temp_title)){
$title = $temp_title.'. '.str_replace($temp_title, '', $obj['nazv']);
} else {
$title = $obj['nazv'];
}
//echo mb_strtolower($obj['nazv']);
//var_dump(mb_strpos(mb_strtolower($obj['nazv']), 'квартира') !== false);
if(mb_strpos(mb_strtolower($obj['nazv']), 'квартира') !== false){
$title = $obj['nazv'];
} else if (mb_strpos(mb_strtolower($obj['nazv']), 'комната') !== false){
$title = $obj['nazv'];
} else if (mb_strpos(mb_strtolower($obj['nazv']), '-к кв.') !== false){
$title = $obj['nazv'];
} else if (mb_strpos(mb_strtolower($obj['nazv']), 'студия') !== false){
$title = $obj['nazv'];
}
return $title;
}
function removeAllWhitespaceIncludingNbsp($string)
{
return preg_replace("/\s| /",' ',$string);
}
function htmlToTelegramMarkdown($html)
{
$markdown = $html;
$markdown = preg_replace('/<(strong|b)>(.*?)<\/\1>/is', '*$2*', $markdown);
$markdown = preg_replace('/<(em|i)>(.*?)<\/\1>/is', '_$2_', $markdown);
$markdown = preg_replace('/(.*?)<\/u>/is', '*_$1_*', $markdown);
$markdown = preg_replace('/(.*?)<\/a>/is', '[$2]($1)', $markdown);
$markdown = preg_replace('/(.*?)<\/code>/is', '`$1`', $markdown);
$markdown = preg_replace('/(.*?)<\/code><\/pre>/is', '```$1```', $markdown);
$markdown = preg_replace('/
/is', "\n", $markdown);
for ($i = 1; $i <= 6; $i++)
{
$markdown = preg_replace('/(.*?)<\/h' . $i . '>/is', str_repeat('#', $i) . ' $1', $markdown);
}
$markdown = preg_replace('/(.*?)<\/ul>/is', "$1", $markdown);
$markdown = preg_replace('/(.*?)<\/ol>/is', "$1", $markdown);
$markdown = preg_replace('/- (.*?)<\/li>/is', "- $1\n", $markdown);
$markdown = preg_replace('/<\/p>/is', "\n\n", $markdown);
$markdown = preg_replace('/
/is', '', $markdown);
$markdown = removeAllWhitespaceIncludingNbsp($markdown);
$markdown = strip_tags($markdown);
$markdown = trim($markdown);
return $markdown;
}
function is_see($is_no_see, $users_no_see){
$is_see = true;
$tempArrNoSee = json_decode($users_no_see, true);
if($is_no_see == 1 && !empty($users_no_see) && !empty($tempArrNoSee)){
$is_see = false;
$arrNoSeeUsers = array();
foreach($tempArrNoSee as $u){
if(strpos($u, 'all_') !== false){
$manId = str_replace('all_', '', $u);
$sql_u = "SELECT id FROM `users`
WHERE id = $manId OR
id_manager = $manId OR
id_manager IN (SELECT id FROM users WHERE id_manager = $manId)";
$q_u = mysql_query($sql_u);
while($r_u = mysql_fetch_row($q_u)){
$arrNoSeeUsers[] = (int)$r_u[0];
}
} else {
$arrNoSeeUsers[] = (int)$u;
}
}
if(in_array($_SESSION['id'], $arrNoSeeUsers)){
$is_see = true;
}
}
return $is_see;
}
function asset($path) {
if (!defined('ENV')) {
define('ENV', getenv('APP_ENV') ?: 'production');
}
// Режим разработки
if (ENV === 'development') {
return $path . '?t=' . time();
}
// Прод
static $manifest = null;
if ($manifest === null) {
$cacheFile = $_SERVER['DOCUMENT_ROOT'] . '/engine/cache/assets.php';
if (file_exists($cacheFile)) {
$manifest = include $cacheFile;
} else {
// Fallback
$fullPath = $_SERVER['DOCUMENT_ROOT'] . $path;
return $path . '?v=' . (file_exists($fullPath) ? filemtime($fullPath) : time());
}
}
return $path . '?v=' . (isset($manifest[$path]) ? $manifest[$path] : time());
}
function get_time_zone_user($user_id = null){
$gmtmsk = 0;
$id = 0;
if($user_id > 0){
$id = (int)$user_id;
} else
if(isset($_SESSION['id']) && $_SESSION['id'] > 0){
$id = (int)$_SESSION['id'];
}
if($id > 0){
$sql = "SELECT * FROM users WHERE id = {$id}";
$rez = mysql_query($sql);
if (mysql_num_rows($rez)) {
$r = mysql_fetch_assoc($rez);
$gmtmsk = (int)$r['gmtmsk'];
}
}
return $gmtmsk;
}