Joywork/engine/classes/Yandex.php
2026-05-22 21:21:54 +03:00

633 lines
26 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
set_time_limit(0);
class Yandex {
public static function create_feed($mdb) {
$db = new MysqlPdo(hstsph, null, null, null, true, '9306');
$html = '';
$result = '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n";
$result .= '<realty-feed xmlns="http://webmaster.yandex.ru/schemas/feed/realty/2010-06">' . "\r\n";
$result .= '<generation-date>' . date('c') . '</generation-date>' . "\r\n";
// временный файл - из него потом копируем в основной в конце
$file = $_SERVER['DOCUMENT_ROOT'].'/feeds/yandex_realty_temp1.xml';
$f = @fopen($file, "r+");
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}
file_put_contents($file, $result, FILE_APPEND | LOCK_EX);
// счетчик - будем писать по 30 в файл
$i = 0;
$sqlAgency="SELECT * from users where id <> 4135 and now() <= DATE_ADD(date_tarif, INTERVAL (select t.period FROM tariffs t where t.id=id_tarif LIMIT 1) DAY) and blocked = 0";
$rezAgency = mysql_query($sqlAgency, $mdb);
while($agency = mysql_fetch_assoc($rezAgency)) {
$sqlUsers = "SELECT id FROM `users` WHERE id=$agency[id] or id_manager=$agency[id] or id_manager in (select id from users where id_manager=$agency[id])";
$users_sp = [];
$rezUsers = mysql_query($sqlUsers);
$rowsUsers = mysql_num_rows($rezUsers);
if($rowsUsers > 0){
while($row = mysql_fetch_assoc($rezUsers)){
$users_sp[] = $row['id'];
}
}
if(empty($users_sp)) {
$users_sp[] = $agency['id'];
}
$sql = "SELECT objects.* FROM objects objects WHERE objects.archive <> 1 and objects.use_in_advert < 1 and objects.id_add_user in
(SELECT id FROM `users` WHERE id=$agency[id] or id_manager=$agency[id] or id_manager in
(select id from users where id_manager=$agency[id])) and add_to_yandex_feed > 0";
/*$sql = "SELECT * FROM objects, objects_delta WHERE archive = 0 and use_in_advert = 0 and add_to_yandex_feed = 1 and
id_add_user in (".implode(',', $users_sp).") LIMIT 0,2000 OPTION max_matches=3000";*/
//$rez = $db->query($sql, true);
$rez = mysql_query($sql, $mdb);
//while ($object = $db->fetch_assoc($rez)) {
while ($object = mysql_fetch_assoc($rez)) {
$sqlAddInfo = "SELECT apartments, video_url, balcony, loggias, separate_wcs, combined_wcs, passenger_lifts, cargo_lifts, house_category, flat_number FROM objects_additional_information WHERE object_id=$object[id]";
$rezAddInfo = mysql_query($sqlAddInfo);
if (mysql_num_rows($rezAddInfo) > 0) {
$objAddInfo = mysql_fetch_assoc($rezAddInfo);
//дополнительные поля
$object['apartments'] = $objAddInfo['apartments'];
$object['video_url'] = $objAddInfo['video_url'];
$object['balcony'] = $objAddInfo['balcony'];
$object['loggias'] = $objAddInfo['loggias'];
$object['separate_wcs'] = $objAddInfo['separate_wcs'];
$object['combined_wcs'] = $objAddInfo['combined_wcs'];
$object['passenger_lifts'] = $objAddInfo['passenger_lifts'];
$object['cargo_lifts'] = $objAddInfo['cargo_lifts'];
$object['house_category'] = $objAddInfo['house_category'];
$object['flat_number'] = $objAddInfo['flat_number'];
} else {
$object['apartments'] = 0;
$object['video_url'] = null;
$object['balcony'] = null;
$object['loggias'] = null;
$object['separate_wcs'] = null;
$object['combined_wcs'] = null;
$object['passenger_lifts'] = null;
$object['cargo_lifts'] = null;
$object['house_category'] = null;
$object['flat_number'] = null;
}
$sqlPhotoInfo = "SELECT oop.sort_order, p.photo FROM objects_object_photo oop, object_photo p WHERE p.id = oop.object_photo_id AND oop.object_id = $object[id] ORDER BY oop.sort_order";
$rezPhotoInfo = mysql_query($sqlPhotoInfo);
if (mysql_num_rows($rezPhotoInfo) > 0) {
while ($photoInfo = mysql_fetch_assoc($rezPhotoInfo)) {
$object['photo' . $photoInfo['sort_order']] = $photoInfo['photo'];
}
}
$sqlRayonInfo = "SELECT rayon FROM rayon WHERE id=$object[rayon]";
//$sqlRayonInfo = "SELECT rayon FROM rayon WHERE id=$object[rayon_id]";
$rezRayonInfo = mysql_query($sqlRayonInfo);
if (mysql_num_rows($rezRayonInfo) > 0) {
$objRayonInfo = mysql_fetch_assoc($rezRayonInfo);
$object['rayon'] = $objRayonInfo['rayon'];
} else {
$object['rayon'] = null;
}
$sqlSaleInfo = "SELECT * FROM sale_objects WHERE object_id=$object[id]";
$rezSaleInfo = mysql_query($sqlSaleInfo);
if (mysql_num_rows($rezSaleInfo) > 0) {
$objSaleInfo = mysql_fetch_assoc($rezSaleInfo);
$object['house_type'] = $objSaleInfo['house_type'];
$object['house_material'] = $objSaleInfo['house_material'];
$object['deal_type'] = $objSaleInfo['deal_type'];
$object['build_year'] = $objSaleInfo['build_year'];
$sqlHmInfo = "SELECT name FROM house_material WHERE id=$object[house_material]";
$rezHmInfo = mysql_query($sqlHmInfo);
if (mysql_num_rows($rezHmInfo) > 0) {
$objHmInfo = mysql_fetch_assoc($rezHmInfo);
$object['house_material_name'] = $objHmInfo['name'];
} else {
$object['house_material_name'] = null;
}
$sqlHtInfo = "SELECT name FROM house_type WHERE id=$object[house_type]";
$rezHtInfo = mysql_query($sqlHtInfo);
if (mysql_num_rows($rezHtInfo) > 0) {
$objHtInfo = mysql_fetch_assoc($rezHtInfo);
$object['house_type_name'] = $objHtInfo['name'];
} else {
$object['house_type_name'] = null;
}
$sqlDtInfo = "SELECT name FROM deal_type WHERE id=$object[deal_type]";
$rezDtInfo = mysql_query($sqlDtInfo);
if (mysql_num_rows($rezDtInfo) > 0) {
$objDtInfo = mysql_fetch_assoc($rezDtInfo);
$object['deal_type_name'] = $objDtInfo['name'];
} else {
$object['deal_type_name'] = null;
}
} else {
$object['house_material'] = null;
$object['house_type'] = null;
$object['deal_type'] = null;
$object['build_year'] = null;
$object['deal_type_name'] = null;
$object['house_type_name'] = null;
$object['house_material_name'] = null;
}
/** GET PLAN */
$plan = '';
$sqlP = "SELECT * FROM objects_plan WHERE object_id = $object[id]";
$rez_plan = mysql_query($sqlP);
if(mysql_num_rows($rez_plan) > 0){
$obj_plan = mysql_fetch_assoc($rez_plan);
if($obj_plan['img_plan'] != ''){
if (stripos($obj_plan['img_plan'], "http://") === false && stripos($obj_plan['img_plan'], "https://") === false) {
$obj_plan['img_plan'] = "https://joywork.ru/photos/" . $obj_plan['img_plan'];
}
$plan = $obj_plan['img_plan'];
}
}
$operationType = 'аренда';
$mortgage = '';
$buildingType = '';
$builtYear = '';
if ($object['operation_type'] == 1) {
$operationType = 'продажа';
$buildingType = $object['house_material_name'];
$builtYear = $object['build_year'];
$mortgage = (strpos($object['stoim_prim'], "ипотека") === false) ? 'нет' : 'да';
}
$typeCategory = '';
if ($object['type'] == 6 || $object['type'] == 4) {
if ($object['type_category']) {
if ($object['type_category'] == 1) {
$typeCategory = 'office';
}
if ($object['type_category'] == 2) {
$typeCategory = 'warehouse';
}
if ($object['type_category'] == 3) {
$typeCategory = 'retail';
}
if ($object['type_category'] == 4) {
$typeCategory = 'manufacturing';
}
if ($object['type_category'] == 5) {
$typeCategory = 'free purpose';
}
} else {
$typeCategory = 'free purpose';
}
}
$common = array(
'type' => $operationType,
'cadastral-number' => $object['cadastral_number'],
'property-type' => 'жилая',
'category' => 'квартира',
'commercial-type' => $typeCategory,
'mortgage' => $mortgage,
'building-type' => $buildingType,
'built-year' => $builtYear,
'creation-date' => Yandex::getRealtyDate($object['date_really_add']),
'last-update-date' => Yandex::getRealtyDate($object['date_add'])
);
switch ($object['type']) {
case 1:
$common['category'] = 'квартира';
break;
case 2:
$common['category'] = 'комната';
break;
case 3:
$common['category'] = 'дом';
break;
case 4:
$common['category'] = 'коммерческая';
break;
case 5:
$common['category'] = 'часть дома';
break;
case 6:
$common['category'] = 'коммерческая';
break;
}
$sql = "SELECT metro.metro FROM metro, sp_metro WHERE sp_metro.id_metro = metro.id AND sp_metro.id_obj = $object[id]";
$result = mysql_query($sql);
$m = mysql_fetch_row($result);
$mtr = $m[0];
$location = [];
$sql = "SELECT * FROM object_location WHERE object_id = $object[id]";
$result = mysql_query($sql);
if ($result) {
$location = mysql_fetch_assoc($result);
}
$city = null;
if (!empty($location['city'])) {
$city = $location['city'];
}
$regionRayon = null;
$rayon = null;
if (!empty($location['rf_region_rayon'])) {
$regionRayon = $location['rf_region_rayon'];
}
if (!empty($object['rayon'])) {
$rayon = $object['rayon'];
}
//$address = $object['adres'];
$address = '';
if (!empty($location['street'])) {
$address = $location['street'];
if ($object['dom']) {
$address = $address . ", " . $object['dom'];
}
if ($object['korpus']) {
$address = $address . ", корпус " . $object['korpus'];
}
if ($object['litera']) {
$address = $address . ", литера" . $object['litera'];
}
}
if (isset($objRayonInfo) && $objRayonInfo['is_lo'] == 1) {
$location = array(
'country' => 'Россия',
'region' => 'Ленинградская область',
'sub-locality-name' => $object['rayon']
);
if (!empty($address))
$location['address'] = $address;
} else if($object['id_rf_region']){
$sql_rf = "SELECT `id`, `name` FROM `rf_regions` where id=$object[id_rf_region]";
$q_rf = mysql_query($sql_rf);
$r_rf = mysql_fetch_assoc($q_rf);
if ($object['id_rf_region'] == 1) {
$r_rf['name'] = 'Москва';
}
if (isset($location) && $location['address'] && strpos($location['address'], "Московская") !== false && strpos($location['address'], "ул Московская") === false) {
$r_rf['name'] = 'Московская область';
}
if ($object['id_rf_region'] == 2) {
$r_rf['name'] = 'Санкт-Петербург';
}
if (isset($location) && $location['address'] && strpos($location['address'], "Ленинградская") !== false) {
$r_rf['name'] = 'Ленинградская область';
}
$location = array(
'country' => 'Россия',
'region' => $r_rf['name'],
'district' => $regionRayon,
'sub-locality-name' => $rayon,
);
if ($city)
$location['locality-name'] = $city;
if (!empty($address))
$location['address'] = $address;
if (isset($object['flat_number']))
$location['apartment'] = $object['flat_number'];
/*if (strpos($address, $r_rf['name']) === false) {
$address = $r_rf['name'].", ". $address;
}*/
/*if ($object['id'] == '4631450') {
var_export($object);
die();
}*/
} else {
$location = array(
'country' => 'Россия',
'locality-name' => 'Санкт-Петербург',
'sub-locality-name' => $object['rayon']
);
if (!empty($address))
$location['address'] = $address;
}
$sql = "SELECT * FROM object_location WHERE object_id = $object[id]";
if ($result = mysql_query($sql)) {
$locationInfo = mysql_fetch_assoc($result);
if ($locationInfo['latitude'] && $locationInfo['longitude']) {
$location['latitude'] = $locationInfo['latitude'];
$location['longitude'] = $locationInfo['longitude'];
}
}
$metro = array();
if ($mtr) {
$metro = array(
'name' => $mtr,
'time-on-foot' => $object['peshkom'],
'time-on-transport' => $object['transport']
);
}
if ($object['operation_type'] == 0) {
$period = 'месяц';
if ($object['srok'] == 1) {
$period = 'день';
}
$price = array(
'value' => $object['stoim'],
'currency' => 'RUB',
'period' => $period
);
} else {
$price = array(
'value' => $object['stoim'],
'currency' => 'RUB'
);
}
$userOwner = new User;
$userOwner->get($object['id_add_user']);
$secondPhone = "";
if ($userOwner->user_logo) {
$sales = array(
'name' => htmlspecialchars_decode(trim($userOwner->last_name . ' ' . $userOwner->first_name . ' ' . $userOwner->middle_name)),
'category' => 'агентство',
'organization' => isset($userOwner->agencyName) ? $userOwner->agencyName : "",
'url' => isset($userOwner->site) ? $userOwner->site : "",
'email' => $userOwner->email,
'photo' => "https://" . $_SERVER['SERVER_NAME'] . "/photos/agency/" . $userOwner->user_logo
);
} else {
$sales = array(
'name' => htmlspecialchars_decode(trim($userOwner->last_name . ' ' . $userOwner->first_name . ' ' . $userOwner->middle_name)),
'category' => 'агентство',
'organization' => isset($userOwner->agencyName) ? $userOwner->agencyName : "",
'url' => isset($userOwner->site) ? $userOwner->site : "",
'email' => $userOwner->email
);
}
if (stripos($object['phone'], ",") === false) {
$sales['phone'] = $object['phone'];
} else {
$res = explode(",", $object['phone']);
$sales['phone'] = $res[0];
$secondPhone = $res[1];
}
$studio = 0;
if ($object['studio_flag'] == 1) {
$studio = 1;
}
$living = array(
'floor' => $object['etazh'],
'floors-total' => $object['etazh_iz'],
'rooms' => $object['komnat'],
'television' => $object['tv'],
'washing-machine' => $object['stirka'],
'refrigerator' => $object['holod'],
'room-furniture' => $object['mebel']
);
if ($studio == 1) {
$living = array(
'floor' => $object['etazh'],
'floors-total' => $object['etazh_iz'],
'studio' => 1,
'television' => $object['tv'],
'washing-machine' => $object['stirka'],
'refrigerator' => $object['holod'],
'room-furniture' => $object['mebel']
);
}
$html .= '<offer internal-id="' . $object['id'] . '">' . "\r\n";
$html .= Yandex::getXmlFields($common);
$html .= '<location>' . "\r\n";
$html .= Yandex::getXmlFields($location);
if ($mtr) {
$html .= '<metro>' . "\r\n";
$html .= Yandex::getXmlFields($metro);
$html .= '</metro>' . "\r\n";
}
$html .= '</location>' . "\r\n";
$html .= '<price>' . "\r\n";
$html .= Yandex::getXmlFields($price);
$html .= '</price>' . "\r\n";
if ($object['operation_type'] == 0) {
$html .= '<commission>' . $object['commission'] . '</commission>' . "\r\n";
}
if($plan != '') {
$html .= '<image>'.$plan.'</image>'. "\r\n";
}
for ($k = 1; $k <= 30; $k++) {
if (isset($object['photo' . $k]) && $object['photo' . $k]) {
$srcFile = $object['photo' . $k];
if (stripos($object['photo' . $k], "http://") === false && stripos($object['photo' . $k], "https://") === false) {
$srcFile = $ph_url = "https://" . $_SERVER['SERVER_NAME'] . "/photos/" . $object['photo' . $k];
}
if ($srcFile != null) {
$html .= '<image>' . $srcFile . '</image>' . "\r\n";
}
}
}
$html .= '<sales-agent>' . "\r\n";
$html .= Yandex::getXmlFields($sales);
if ($secondPhone) {
$html .= '<phone>' . $secondPhone . '</phone>';
}
$html .= '</sales-agent>' . "\r\n";
if (!empty($object['opis'])) {
$html .= '<description>' . htmlspecialchars(br2nl($object['opis']), ENT_QUOTES) . '</description>' . "\r\n";
}
if (!empty($object['ploshad']) && $object['ploshad'] > 0) {
$html .= '<area>' . "\r\n";
$html .= '<value>' . $object['ploshad'] . '</value>' . "\r\n";
$html .= '<unit>кв.м</unit>' . "\r\n";
$html .= '</area>' . "\r\n";
}
if (!empty($object['ploshad_komn']) && $object['ploshad_komn'] > 0) {
$sq = $object['ploshad_komn'];
if (strpos($object['ploshad_komn'], "+")) {
$sqTemp = 0;
$res = explode("+", $object['ploshad_komn']);
foreach ($res as $str) {
$sqTemp = $sqTemp + intval(trim($str));
}
$sq = $sqTemp;
}
$html .= '<living-space>' . "\r\n";
$html .= '<value>' . $sq . '</value>' . "\r\n";
$html .= '<unit>кв.м</unit>' . "\r\n";
$html .= '</living-space>' . "\r\n";
if ($object['type'] == 2) {
$html .= '<room-space>' . "\r\n";
$html .= '<value>' . $sq . '</value>' . "\r\n";
$html .= '<unit>кв.м</unit>' . "\r\n";
$html .= '</room-space>' . "\r\n";
}
}
if (!empty($object['ploshad_k']) && $object['ploshad_k'] > 0) {
$html .= '<kitchen-space>' . "\r\n";
$html .= '<value>' . $object['ploshad_k'] . '</value>' . "\r\n";
$html .= '<unit>кв.м</unit>' . "\r\n";
$html .= '</kitchen-space>' . "\r\n";
}
$html .= Yandex::getXmlFields($living);
if ($object['type'] == 2) {
$html .= '<rooms-offered>1</rooms-offered>' . "\r\n";
}
if ($object['operation_type'] == 1) {
if ($object['deal_type'] == 1) {
$html .= '<deal-status>прямая продажа</deal-status>' . "\r\n";
}
if ($object['deal_type'] == 2) {
$html .= '<deal-status>встречная продажа</deal-status>' . "\r\n";
}
}
$html .= '</offer>' . "\r\n";
$i = $i + 1;
if ($i == 30) {
file_put_contents($file, $html, FILE_APPEND | LOCK_EX);
$html = '';
$i = 0;
}
}
}
if ($i > 0) {
file_put_contents($file, $html, FILE_APPEND | LOCK_EX);
}
//копируем данные из фида https://f-rent.com/3bita/load/yandex2.xml
$fileStream = new SplFileObject("https://f-rent.com/3bita/load/yandex2.xml");
// Loop until we reach the end of the file.
while (!$fileStream->eof()) {
// Echo one line from the file.
$line = $fileStream->fgets();
if (strpos($line, "realty-feed") !== false) {
continue;
}
if (strpos($line, "generation-date") !== false) {
continue;
}
if (strpos($line, "version=\"1.0\"") !== false) {
continue;
}
file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}
// Unset the file to call __destruct(), closing the file handle.
$fileStream = null;
file_put_contents($file, '</realty-feed>', FILE_APPEND | LOCK_EX);
if (!copy($file, $_SERVER['DOCUMENT_ROOT'].'/feeds/yandex_realty.xml')) {
// если не удалось скопировать файл - пробуем еще раз
sleep(10);
copy($file, $_SERVER['DOCUMENT_ROOT'].'/feeds/yandex_realty.xml');
}
}
static function curl_r($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CERTINFO, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // запретить проверку сертификата удаленного сервера
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0");
curl_setopt($ch, CURLOPT_REFERER, "https://joywork.ru/");
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, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
static function getRealtyDate($date, $cur_format='Y-m-d H:i:s') {
return ($date != '0000-00-00 00:00:00') ? Yandex::convertDate($date, $cur_format, 'c') : '';
}
static function convertDate($date, $cur_format, $new_format) {
$date = DateTime::createFromFormat($cur_format, $date);
$result = ($date instanceof DateTime) ? $date->format($new_format) : '';
return $result;
}
static function getXmlFields($data) {
if (empty($data)) return '';
$result = '';
foreach ($data as $key => $val) {
if (!empty($val)) $result .= "<$key>" . htmlspecialchars(strip_tags($val), ENT_QUOTES) . "</$key>\r\n";
}
return $result;
}
}