Joywork/api/v2/app/src/controllers/AdvertsController.php

2887 lines
95 KiB
PHP
Raw Normal View History

2026-05-22 20:21:54 +02:00
<?php
namespace App\v2\Controller;
use Complex\Exception;
class AdvertsController extends ApiController
{
2026-06-28 09:56:29 +02:00
// Найденный листинг парсера read-only: рекламные действия недоступны
// (паритет с десктопом, где switchAdvert*/addPromotion и т.п. отбивают листинг). Вернёт true + 403, если листинг.
// Offset-free: после снятия смещения id листинга (= реальный external_listings.id) коллизит с objects.id,
// поэтому различить листинг по id нельзя. Признак приходит явным флагом is_external из запроса
// (фронт знает, что действие над найденным листингом). Сервер по id отличить листинг уже не может.
private function _rejectIfExternalListing($app, $is_external)
{
if (!empty($is_external)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(403);
$app->response->setBody(json_encode([
'success' => false,
'errors' => ['Действие недоступно для найденного листинга. Скопируйте объект в свои, чтобы управлять им.'],
], JSON_UNESCAPED_UNICODE));
return true;
}
return false;
}
2026-05-22 20:21:54 +02:00
public function getPublishedPackages($app, $get, $post) {
$error = false;
$errors = [];
$packages = [];
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
if (($user_id = $_SESSION['id']) && !is_null($object_id)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$sql = "SELECT published.days AS days, published.publish_date AS publish_date, packs.name, published.advertising_package_id AS package
FROM advertising_package_object_publish published
JOIN advertising_package packs ON packs.id=published.advertising_package_id
WHERE published.active=1 AND published.object_id=$object_id";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_assoc($query)) {
$left_days = ceil(((strtotime($row['publish_date']) + $row['days'] * 86400) - time()) / 86400);
$status_text = declOfNum($left_days, array('остался %d день', 'осталось %d дня', 'осталось %d дней'));
$packages[] = [
'name' => $row['package'],
'package_id' => $row['advertising_package_id'],
'left_days' => (!empty($left_days)) ? (int)$left_days : false,
'status_text' => (!empty($status_text)) ? $status_text : false,
'is_error' => (!empty($row['error_text'])) ? true : false,
'error_text' => (!empty($row['error_text'])) ? $row['error_text'] : null,
'is_active' => (!empty($row['zipal_active'])) ? true : false,
];
}
}
} else {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'object_id' => $object_id,
'packages' => count($packages) ? $packages : false
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setObjectState($app, $get, $post) {
$sqls = [];
$errors = [];
$sql = null;
$sql_sph = null;
$sql2 = null;
$body = $app->request->getBody();
$data = json_decode(stripcslashes($body), true);
if (($user_id = $_SESSION['id']) && isset($data['object_id']) && isset($data['service']) && isset($data['current'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$object_id = null;
if (isset($data['object_id']))
$object_id = $data['object_id'];
2026-06-28 09:56:29 +02:00
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id)
if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return;
2026-05-22 20:21:54 +02:00
$service = null;
if (isset($data['service']))
$service = $data['service'];
$price = null;
if (isset($data['price']))
$price = (int)$data['price'];
$days = null;
if (isset($data['days']))
$days = (int)$data['days'];
$publish = null;
if (isset($data['publish']))
$publish = $data['publish'];
$is_moderation = false;
if (isset($data['is_moderation']))
$is_moderation = (bool)$data['is_moderation'];
$unpublish = null;
if (isset($data['unpublish']))
$unpublish = $data['unpublish'];
$user = new \User;
$user->get($user_id);
$user->checkPermissions($user_id, false);
$agency_id = $user->agencyId;
$agency_users_ids = \User::getAllAgencyUsers($agency_id);
// Предмодерация рекламы по объектам
$sql = "SELECT * FROM `advert_moderation_agency` WHERE `agency_id` = {$agency_id}";
$adverts_moderator = false; // Рекламый модератор (руковод.)
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$adverts_moderator = true;
}
} else {
$errors[] = mysql_error();
}
$new_state = !boolval($data['current']); // Ивертируем текущее состояние (статус) публикации
if (is_null($publish) && is_null($unpublish)) { // Стандартные способы размещения
// Открываем соединение с БД и Сфинксом
$pdo = $app->container->get('pdo');
$mypdo = $app->container->get('mypdo');
$db_sphinx = $app->container->get('sphinx2');
$set = [];
$destination = null;
$moderation_inst = new \ModerationAdvert($mypdo);
switch ($service) {
case 'global':
if ($new_state) {
$set['use_in_advert'] = "use_in_advert = 1";
} else {
$set['use_in_advert'] = "use_in_advert = 0";
}
break;
case 'yandex':
if ($new_state)
$set['add_to_bn_feed'] = "add_to_bn_feed = 1";
else
$set['add_to_bn_feed'] = "add_to_bn_feed = 0";
$destination = "YANDEX_JW_FEED";
break;
case 'domclick':
if ($new_state)
$set['add_to_domclick_feed'] = "add_to_domclick_feed = 1";
else
$set['add_to_domclick_feed'] = "add_to_domclick_feed = 0";
$destination = "DOMCLICK_JW_FEED";
break;
case 'avito':
if ($new_state)
$set['add_to_avito_feed'] = "add_to_avito_feed = 1";
else
$set['add_to_avito_feed'] = "add_to_avito_feed = 0";
$destination = "AVITO_JW_FEED";
break;
case 'emls':
case 'jcat':
if ($new_state)
$set['add_to_emls_feed'] = "add_to_emls_feed = 1";
else
$set['add_to_emls_feed'] = "add_to_emls_feed = 0";
$destination = "EMLS_JW_FEED";
break;
case 'cian':
if ($new_state)
$set['add_to_cian_feed'] = "add_to_cian_feed = 1";
else
$set['add_to_cian_feed'] = "add_to_cian_feed = 0";
$destination = "CIAN_JW_FEED";
break;
case 'free':
if ($new_state) {
$set['add_to_yandex_feed'] = "add_to_yandex_feed = 1";
} else {
$set['add_to_yandex_feed'] = "add_to_yandex_feed = 0";
}
$destination = "FREE_JW_FEED";
break;
case 'zipal':
if ($new_state) {
$set['add_to_zipal'] = "add_to_zipal = 1";
} else {
$set['add_to_zipal'] = "add_to_zipal = 0";
}
break;
}
$advertBudgets = new \AdvertBudgets();
if ($service === 'global' && !$is_moderation) {
if (!$new_state) {
$set['add_to_bn_feed'] = "add_to_bn_feed = 0";
$set['add_to_domclick_feed'] = "add_to_domclick_feed = 0";
$set['add_to_avito_feed'] = "add_to_avito_feed = 0";
$set['add_to_emls_feed'] = "add_to_emls_feed = 0";
$set['add_to_cian_feed'] = "add_to_cian_feed = 0";
$set['add_to_zipal'] = "add_to_zipal = 0";
$set['add_to_yandex_feed'] = "add_to_yandex_feed = 0";
$results = $advertBudgets->updateObjectCost($object_id, 1);
if (!$results['success']) {
$error = true;
$errors = array_merge($errors, $results['errors']);
}
$results = $advertBudgets->updateObjectCost($object_id, 2);
if (!$results['success']) {
$error = true;
$errors = array_merge($errors, $results['errors']);
}
$results = $advertBudgets->updateObjectCost($object_id, 3);
if (!$results['success']) {
$error = true;
$errors = array_merge($errors, $results['errors']);
}
$results = $advertBudgets->updateObjectCost($object_id, 4);
if (!$results['success']) {
$error = true;
$errors = array_merge($errors, $results['errors']);
}
$results = $advertBudgets->updateObjectCost($object_id, 5);
if (!$results['success']) {
$error = true;
$errors = array_merge($errors, $results['errors']);
}
if (count($set) > 0) {
foreach ($set as $adv_field => $adv_data) {
if (in_array($adv_field, ['add_to_bn_feed', 'add_to_domclick_feed', 'add_to_avito_feed', 'add_to_emls_feed', 'add_to_cian_feed', 'add_to_zipal', 'add_to_yandex_feed'])) {
$moderation_inst->checkAndClear($object_id, $adv_field);
}
}
}
}
// Установка уведомлений в ТГ
$telegram = new \Telegram(true);
if ($new_state)
$telegram->object_ad($object_id);
else
$telegram->object_ad($object_id, 0);
} else {
$error = false;
$no_insert = false;
$service_id = 0;
if (!is_null($destination)) {
$advertBudgets = new \AdvertBudgets();
$service_id = $advertBudgets->getServiceIdByCommonId($destination);
$results = $advertBudgets->getObjectAdvertPrices($object_id, $service_id, $days);
}
if ($new_state) {
// Стоимость размещения за весь период
$price = 0;
if (!is_null($results['price']))
$price = $results['price'];
// Стоимость размещения за 1 период (30 дней)
$price_period = 0;
if (!is_null($results['price_period']))
$price_period = $results['price_period'];
// Если агентство использует рекламный бюджет
if (!is_null($results['budget'])) {
// Если пользователь руковод или у него безлимит
$unlimited = false;
if (isset($results['is_unlimited']))
$unlimited = boolval($results['is_unlimited']);
$budget = $results['budget'];
if ($price > $budget && !$unlimited) { // Если нехватка бюджета - выходим
$error = true;
$errors[] = "Размещение не возможно по причине не достаточного баланса рекламного бюджета.";
}
}
$set['use_in_advert'] = "use_in_advert = 1";
$days = 5000;
if (isset($data['days']) && $data['days'])
$days = $data['days'];
if ($days > 5000)
$days = 5000;
$id_add_user = null;
$sql_obj = "SELECT id, nazv, id_add_user from objects WHERE id = $object_id";
$sth = $pdo->prepare($sql_obj);
if ($sth->execute()) {
if ($object = $sth->fetch(\PDO::FETCH_ASSOC)) {
$id_add_user = $object['id_add_user'];
}
} else {
$error = true;
$errors[] = $sth->pdo->errorInfo();
}
if (!$is_moderation) {
// Обновляем в статистике старую запись объекта из модерации
/*$sqlCheck = "SELECT object_publish_statistic.id AS stat_id
FROM object_publish_statistic
WHERE object_id = '$object_id' AND
destination = '$destination' AND
publish_user_id = (
SELECT moderation.agent_id
FROM objects_moderation_advert AS moderation
LEFT JOIN objects_moderation_advert_user_work AS user_work ON user_work.moderation_id = moderation.id
WHERE moderation.object_id = '$object_id' AND
DATE(moderation.created_at) >= DATE(object_publish_statistic.created_at) AND
moderation.send_moderation = 0
LIMIT 1
)";
if ($sqlCheckRez = mysql_query($sqlCheck)) {
if (mysql_num_rows($sqlCheckRez)) {
$stat_id = mysql_fetch_assoc($sqlCheckRez)['stat_id'];
$sqlUpRc = "UPDATE object_publish_statistic
SET publish_start_date = NOW(),
publish_end_date = DATE_ADD(NOW(), INTERVAL $days DAY),
days_count = '$days',
price = '$price',
publish_user_id = '$user_id',
on_moderation = 0
WHERE id = $stat_id";
mysql_query($sqlUpRc);
$no_insert = true;
}
}*/
}
if (!$no_insert && ($days && !is_null($id_add_user) && !is_null($destination))) {
$sql2 = "INSERT INTO object_publish_statistic (
object_id,
user_owner_id,
publish_user_id,
created_at,
publish_start_date,
publish_end_date,
days_count,
destination,
price,
price_period,
on_moderation
) VALUES (
'$object_id',
'$id_add_user',
'$user_id',
NOW(),
NOW(),
DATE_ADD(NOW(), INTERVAL $days DAY),
'$days',
'$destination',
'$price',
'$price_period',
'".($is_moderation ? 1 : 0)."'
)";
}
} else if (!is_null($destination) && $service_id) {
$results = $advertBudgets->updateObjectCost($object_id, $service_id);
if (!$results['success']) {
$error = true;
$errors = array_merge($errors, $results['errors']);
}
}
if (!empty($sql2)) {
$sth = $pdo->prepare($sql2);
if (!$sth->execute()) {
$error = true;
$errors[] = $sth->pdo->errorInfo();
}
}
}
if (count($set) > 0) {
if (!$is_moderation) {
$sql = "UPDATE objects
SET " . implode(', ', $set) . ", is_main = 0
WHERE id = $object_id";
$sql_sph = "UPDATE objects
SET " . implode(', ', $set) . "
WHERE id = $object_id";
}
if (!$error) {
if ($is_moderation) {
foreach ($set as $adv_field => $adv_data) {
if (in_array($adv_field, ['add_to_bn_feed', 'add_to_domclick_feed', 'add_to_avito_feed', 'add_to_emls_feed', 'add_to_cian_feed', 'add_to_zipal', 'add_to_yandex_feed'])) {
$moderation_inst->addUpdate($user_id, $object_id, [
'field' => $adv_field,
'value' => 1
]);
}
}
} else if (!$is_moderation && $adverts_moderator && !$new_state) {
foreach ($set as $adv_field => $adv_data) {
if (in_array($adv_field, ['add_to_bn_feed', 'add_to_domclick_feed', 'add_to_avito_feed', 'add_to_emls_feed', 'add_to_cian_feed', 'add_to_zipal', 'add_to_yandex_feed'])) {
$sql3 = "UPDATE `objects_moderation_advert` SET `$adv_field` = 0 WHERE `object_id` = {$object_id} AND `agent_id` IN (" . implode(',', $agency_users_ids) . ")";
$sth = $pdo->prepare($sql3);
if (!$sth->execute()) {
$error = true;
$errors[] = $sth->pdo->errorInfo();
}
}
}
}
}
}
if (!$error && !empty($sql)) {
$sth = $pdo->prepare($sql);
if (!$sth->execute()) {
$error = true;
$errors[] = $sth->pdo->errorInfo();
}
}
if (!$error && !empty($sql_sph)) {
if (!$db_sphinx->query($sql_sph)) {
$error = true;
$errors[] = $db_sphinx->pdo->errorInfo();
}
}
}
if ($service === 'packages') { // Пакетное размещение
if (is_array($publish))
$publish = array_unique($publish);
else
$publish = [];
if (is_array($unpublish))
$unpublish = array_unique($unpublish);
else
$unpublish = [];
if (count($publish)) { // постановка в публикацию
foreach ($publish as $data) {
if (is_null($data))
continue;
$package_id = $data['package_id'];
$days = $data['days_count'];
$price = $data['zipal_price'];
$sqlPackData = "SELECT * FROM advertising_package WHERE id = $package_id";
if ($query = mysql_query($sqlPackData)) {
$package = mysql_fetch_assoc($query);
$sql = "SELECT count(id) FROM advertising_package_object_publish WHERE object_id = $object_id AND advertising_package_id = $package_id";
$count = 0;
if ($rez = mysql_query($sql)) {
$count = mysql_result($rez, 0);
} else {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
//если объект уже был, то обновляем, иначе создаем
if ($count > 0) {
$sql = "UPDATE advertising_package_object_publish SET unpublish_user_id = NULL, user_id = '$user_id', sended = 0, published = 0, unpublish = 0, active = 1, publish_date = NOW(), error_text = NULL, price = '$price', days = '$days' WHERE object_id = $object_id AND advertising_package_id = $package_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
} else {
$sql = "INSERT INTO advertising_package_object_publish (object_id, advertising_package_id, user_id, days, price, active, publish_date) VALUES ('$object_id', '$package_id', '$user_id', '$days', '$price', 1, NOW())";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
}
$logText = "Отправлен на публикацию через пакет $package[name] (ID = $package_id) на $days дней";
$sqlLog = "INSERT INTO object_publish_log(object_id, created_at, user_id, log_text) VALUES ('$object_id', NOW(), '$user_id', '$logText')";
if (!mysql_query($sqlLog)) {
$error = true;
$sqls[] = $sqlLog;
$errors[] = mysql_error();
}
$user = new \User;
$user->get($user_id);
if (empty($user->zipal_balance)) {
$newBalance = $user->agencyZipalBalance - $price;
$sql = "UPDATE users SET zipal_balance='$newBalance' WHERE id=" . $user->agencyId;
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
} else {
$newBalance = $user->zipal_balance - $price;
$sql = "UPDATE users SET zipal_balance='$newBalance' WHERE id=$user_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
}
$checked = false;
$published = zipalPackageCountText($object_id, $package_id);
if ($published['zipal_active'] == 1 && (int)$published['zipal_days'] > 0)
$checked = true;
$is_error = (!empty($published['error_text'])) ? true : false;
$error_text = null;
if ($is_error)
$error_text = "Ошибка: " . $published['error_text'][0]['defaultMessage'];
$packages[$package_id] = [
'left_days' => (!empty($published['zipal_day'])) ? (int)$published['zipal_day'] : false,
'status_text' => (!empty($published['zipal_day_text'])) ? $published['zipal_day_text'] : false,
'is_error' => $is_error,
'error_text' => $error_text,
'is_active' => (!empty($published['zipal_active'])) ? true : false,
'is_active' => (!$is_error) ? $checked : false,
];
} else {
$error = true;
$sqls[] = $sqlPackData;
$errors[] = mysql_error();
}
}
} else if (count($unpublish)) { // снятие с публикации
foreach ($unpublish as $data) {
if (is_null($data))
continue;
$package_id = $data['package_id'];
$sqlPackData = "SELECT * FROM advertising_package WHERE id = $package_id";
if ($query = mysql_query($sqlPackData)) {
$package = mysql_fetch_assoc($query);
$count = 0;
$sql = "SELECT count(id) FROM advertising_package_object_publish WHERE zipal_id IS NOT NULL AND object_id = $object_id AND advertising_package_id = $package_id";
if ($query = mysql_query($sql)) {
$count = mysql_result($query,0);
} else {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
//если объект уже был отправлен, то распубликовываем, иначе удаляем
if ($count > 0) {
$sql = "UPDATE advertising_package_object_publish SET sended = 1, published = 1, unpublish = 1, active = 0, unpublish_user_id = $user_id WHERE object_id = $object_id AND advertising_package_id = $package_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
} else {
$sql = "DELETE FROM advertising_package_object_publish WHERE object_id = $object_id AND advertising_package_id = $package_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
}
$logText = "Отправлен на отмену публикации через пакет $package[name] (ID = $package_id)";
$sqlLog = "INSERT INTO object_publish_log(object_id, created_at, user_id, log_text) VALUES ('$object_id', NOW(), '$user_id', '$logText')";
if (!mysql_query($sqlLog)) {
$error = true;
$sqls[] = $sqlLog;
$errors[] = mysql_error();
}
$packages[$package_id] = [
'status_text' => 'Снятие с публикации…',
'is_active' => false
];
} else {
$error = true;
$sqls[] = $sqlPackData;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = 'Не выбран ни один пакет размещения.';
}
} else if ($service === 'zipal') { // Размещение с отчётами
if (!is_array($publish))
$publish = [];
if ($new_state) {
if (count($publish)) { // Постановка в публикацию
$user = new \User;
$user->get($user_id);
$zipalBalance = $user->zipal_balance;
if (empty($zipalBalance)) {
$zipalBalance = $user->agencyZipalBalance;
}
$prices = self::getZipalPrices($app, $get, $post, true);
$destinations = [];
foreach($publish as $data) {
if (is_null($data))
continue;
$destination = trim($data[0]);
$placements = (array)$data[1];
if ($destination && !empty($placements)) {
foreach($placements as $placement) {
$destinations[] = [
'destination' => strtoupper(trim($destination)),
'feed' => (isset($prices[$destination][trim($placement)]['is_feed'])) ? "true" : "false",
'placementType' => strtoupper(trim($placement)),
];
}
}
}
if (count($destinations) && $zipalBalance > $price) {
$sql = "SELECT count(id) FROM zipal_objects WHERE object_id = $object_id";
if ($query = mysql_query($sql)) {
// Постановка в публикацию
$count = mysql_result($query,0);
if ($count > 0) {
$sql = "UPDATE zipal_objects SET unpublish_user_id = NULL, user_id = '$user_id', sended = 0, published = 0, unpublish = 0, error_text = NULL, price = '$price', destinations = '". json_encode($destinations) ."', days = '$days', add_to_zipal_at = NOW() WHERE object_id = $object_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
//var_export($sql) && die();
} else {
$sql = "INSERT into zipal_objects (object_id, user_id, destinations, days, price, add_to_zipal_at) VALUES ('$object_id', '$user_id', '". json_encode($destinations) ."', '$days', '$price', NOW())";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
//var_export($sql) && die();
}
// Обновление статуса объекта В рекламе
$sql = "UPDATE objects SET use_in_advert=1, add_to_zipal=1, is_main = 0 WHERE id=$object_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
// Запись лога
$logText = "Отправлен на публикацию через кнопку С отчетами на $days дней";
$sqlLog = "INSERT INTO object_publish_log(object_id, created_at, user_id, log_text) VALUES ('$object_id', NOW(), '$user_id', '$logText')";
if (!mysql_query($sqlLog)) {
$error = true;
$sqls[] = $sqlLog;
$errors[] = mysql_error();
}
} else {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
// Списание с баланса
if (empty($user->zipal_balance)) {
$newBalance = $user->agencyZipalBalance - $price;
$sql = "UPDATE users SET zipal_balance='$newBalance' WHERE id=" . $user->agencyId;
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
} else {
$newBalance = $user->zipal_balance - $price;
$sql = "UPDATE users SET zipal_balance='$newBalance' WHERE id=$user_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
}
} else {
$error = true;
$errors[] = 'Не достаточно средств на балансе пользователя (агентства).';
}
} else {
$error = true;
$errors[] = 'Не выбрана ни одна плащадка размещения.';
}
} else {
$sql = "SELECT count(id) FROM zipal_objects WHERE zipal_id is not null and object_id = $object_id";
if ($query = mysql_query($sql)) {
$count = mysql_result($query,0);
if ($count > 0) {
$sql = "UPDATE zipal_objects SET sended = 1, published = 1, unpublish = 1, unpublish_user_id = $user_id WHERE object_id = $object_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
} else {
$sql = "DELETE from zipal_objects WHERE object_id = $object_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
}
$sql = "UPDATE objects
SET use_in_advert = IF(
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_cian_feed = 0, 0, 1),
add_to_zipal=0,
is_main = 0
WHERE id=$object_id";
if (!mysql_query($sql)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
$logText = "Отправлен на отмену публикации через кнопку С отчетами";
$sqlLog = "INSERT INTO object_publish_log(object_id, created_at, user_id, log_text) VALUES ('$object_id', NOW(), '$user_id', '$logText')";
if (!mysql_query($sqlLog)) {
$error = true;
$sqls[] = $sql;
$errors[] = mysql_error();
}
}
}
}
if (!$error) {
// Вебхук: смена статуса рекламы
$service_to_button = [
'yandex' => 'add_to_bn_feed',
'domclick' => 'add_to_domclick_feed',
'avito' => 'add_to_avito_feed',
'emls' => 'add_to_emls_feed',
'jcat' => 'add_to_emls_feed',
'cian' => 'add_to_cian_feed',
'free' => 'add_to_yandex_feed',
];
if (isset($service_to_button[$service])) {
$advert_action = $new_state ? 'object_advertise' : 'object_unadvertise';
$w_in = new \WebHookIn(null, $agency_id);
$w_in->check_send([
'action' => $advert_action,
'object_id' => $object_id,
'section' => 'object',
'user_id' => $user_id,
'agency_id' => $agency_id,
'button' => $service_to_button[$service],
]);
} else if ($service === 'global' && !$new_state) {
// Глобальное снятие с рекламы — со всех площадок
$w_in = new \WebHookIn(null, $agency_id);
$w_in->check_send([
'action' => 'object_unadvertise',
'object_id' => $object_id,
'section' => 'object',
'user_id' => $user_id,
'agency_id' => $agency_id,
'button' => 'all',
]);
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'object_id' => $object_id,
'service' => $service,
'state' => $new_state,
'packages' => $packages,
/*'queries' => [
'sql' => $sql,
'sql_sph' => $sql_sph,
'sql2' => $sql2
]*/
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'sqls' => $sqls,
'errors' => $errors,
/*'queries' => [
'sql' => $sql,
'sql_sph' => $sql_sph,
'sql2' => $sql2
]*/
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getZipalPackages($app, $get, $post, $need_return = false) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
global $ZIPAL_TARGETS;
global $ZIPAL_MULTIPLY;
$error = false;
$errors = [];
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$days_num = 0;
if (isset($get['days_num']))
$days_num = intval($get['days_num']);
$package_id = null;
if (isset($get['package_id']))
$package_id = $get['package_id'];
if (($user_id = $_SESSION['id']) && !is_null($object_id)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$package = [];
$packages = [];
$destinations = [];
$obj = null;
$sql = "SELECT objects.* FROM objects WHERE objects.id = $object_id";
if ($query = mysql_query($sql)) {
$obj = mysql_fetch_assoc($query);
} else {
$error = true;
$errors[] = mysql_error();
}
if (!is_null($package_id)) {
$curUser = new \User();
$curUser->get($user_id);
$request = [];
$login = $curUser->zipal_login;
$password = $curUser->zipal_password;
if (empty($login) || empty($password)) {
$login = $curUser->agencyZipalLogin;
$password = $curUser->agencyZipalPassword;
}
$request['login'] = $login;
$request['password'] = $password;
$request['method'] = 'GetPrices';
$request['request'] = [];
$request['request']['requestType'] = 'GetPricesByParamsRequestType';
if ($obj['id_rf_region']) {
$sql = "SELECT code FROM rf_regions WHERE rf_regions.id = ".$obj['id_rf_region'];
if ($query = mysql_query($sql)) {
$request['request']['region'] = mysql_fetch_assoc($query)['code'];
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$request['request']['region'] = 78;
}
$sql = "SELECT * FROM advertising_package WHERE id=$package_id";
if ($query = mysql_query($sql)) {
$package = mysql_fetch_assoc($query);
if (!is_null($package)) {
$sql = "SELECT * FROM advertising_package_destinations WHERE deleted=0 AND advertising_package_id=$package_id";
if ($query = mysql_query($sql)) {
while ($row = mysql_fetch_assoc($query)) {
array_push($destinations, $row);
}
$request['request']['days'] = $days_num;
$request['request']['hasPhotos'] = $package['has_photo'] == 1 ? true : false;
$deal_type_id = $package['advertising_package_deal_type_id'];
$object_type_id = $package['advertising_package_object_type_id'];
$price_type_id = $package['advertising_package_price_type_id'];
$sql = "SELECT * FROM advertising_package_deal_type WHERE id=$deal_type_id";
if ($query = mysql_query($sql)) {
$deal_type = mysql_fetch_assoc($query);
} else {
$error = true;
$errors[] = mysql_error();
}
$sql = "SELECT * FROM advertising_package_object_type WHERE id=$object_type_id";
if ($query = mysql_query($sql)) {
$object_type = mysql_fetch_assoc($query);
} else {
$error = true;
$errors[] = mysql_error();
}
$priceType = null;
if ($deal_type['code'] == 'RENT') {
if (!$price_type_id || $price_type_id == -1) {
$error = true;
$errors[] = "Необходимо указать Тип цены для типа сделки Аренда";
} else {
$sql = "SELECT * FROM advertising_package_price_type WHERE id=$price_type_id";
if ($query = mysql_query($sql)) {
$priceType = mysql_fetch_assoc($query);
} else {
$error = true;
$errors[] = mysql_error();
}
}
}
$request['request']['room'] = $object_type['is_room'] == 1 ? true : false;
$request['request']['dealType'] = $deal_type['code'];
if ($priceType != null)
$request['request']['priceType'] = $priceType['code'];
$request['request']['objectType'] = $object_type['code'];
$jsonResult = [];
try {
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; HTC_Touch_Diamond2_T5353; Windows Phone 6.5)';
$result = curl_request_zipal_json("https://zipal.ru/ws/json", $user_id, $user_agent, json_encode($request));
$jsonResult = json_decode($result, true);
} catch (\Exception $exception) {
$error = true;
$errors[] = $exception->getMessage();
}
if ($jsonResult['resultCode'] == "FAIL") {
$error = true;
if ($res = strpos($jsonResult['result'], "at [Source:"))
$errors[] = substr($jsonResult['result'], $res);
else
$errors[] = $jsonResult['result'];
} else if ($jsonResult['resultCode'] == "OK") {
$zipal_price = $jsonResult['result']['basePrice'] / 100;
$non_zipal_price = 0;
$base_price = ($jsonResult['result']['basePrice'] / 100) * $ZIPAL_MULTIPLY;
foreach ($destinations as $dbDest) {
/*$targetName = $ZIPAL_TARGETS[$dbDest['destination']];
if (!$targetName)
$targetName = $dbDest['destination'];*/
$zipalDest = null;
$zipalDestPrice = null;
foreach ($jsonResult['result']['destination'] as $dest) {
if ($dbDest['destination'] === $dest['destination']) {
$zipalDest = $dest;
foreach ($dest['price'] as $price) {
if ($price['type'] === $dbDest['placement_type']) {
$zipalDestPrice = $price;
}
}
}
}
if ($zipalDest != null && $zipalDestPrice != null) {
/*$priceTypeVal = $ZIPAL_PRICE_TYPES[$zipalDestPrice['type']];
if (!$priceTypeVal)
$priceTypeVal = $zipalDestPrice['type'];*/
$manPrice = 0;
if ($dbDest['manual_price'] > 0) {
if ($zipalDest['destination'] === 'AVITO') {
$manPrice = $dbDest['manual_price'];
} else {
$manPrice = $dbDest['manual_price'] * $days_num;
}
}
if ($zipalDestPrice['price'] > 0)
$zipal_price = $zipal_price + ($zipalDestPrice['price'] / 100);
if ($dbDest['manual_price'] > 0)
$non_zipal_price = $non_zipal_price + $manPrice;
}
$price = $dbDest['manual_price'] > 0 ? $manPrice : $zipalDestPrice['price'] / 100;
/*if ($zipalDest['destination'] === 'AVITO' || $zipalDest['destination'] === 'YANDEX' || $zipalDest['destination'] === 'CIAN' || $zipalDest['destination'] === 'EMLS') {
$non_zipal_price = $non_zipal_price + $price;
} else {
$zipal_price = $zipal_price + $price;
}*/
}
$total_price = ($package) ? (float)$package['price'] : ($jsonResult['result']['basePrice'] / 100) * $ZIPAL_MULTIPLY;
$package = [
'days_count' => $days_num,
'base_price' => $base_price,
'zipal_price' => $zipal_price,
'addition_price' => $non_zipal_price,
'total_price' => $total_price + $base_price,
'_meta' => ($package) ? $package : null
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$error = true;
$errors[] = "Пакет не найден";
}
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$sql = "SELECT objects.* FROM objects WHERE objects.id = $object_id";
$query = mysql_query($sql);
if ($obj = mysql_fetch_assoc($query)) {
$curUser = new \User();
$curUser->get($user_id);
$agency_id = $curUser->agencyId;
if ($obj['operation_type'] == 1) {
$deal_type = 'SELL';
$sql_price = "true";
} else {
$deal_type = 'RENT';
$priceType = 'MONTH';
if ($obj['srok'] == 1)
$priceType = 'DAY';
$sql_price = " advertising_package_price_type_id IN (SELECT id FROM advertising_package_price_type WHERE code = '$priceType') ";
}
$has_photos = 0;
$sql = "SELECT id FROM objects_object_photo oop WHERE oop.object_id = $obj[id] LIMIT 1";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$has_photos = 1;
}
} else {
$error = true;
$errors[] = mysql_error();
}
$is_room = 0;
$object_type = 'FLAT';
switch ($obj['type']) {
case 1:
$object_type = 'FLAT';
break;
case 2:
$object_type = 'FLAT';
$is_room = 1;
break;
case 5:
case 3:
$object_type = 'HOUSE';
break;
case 4:
case 6:
if ($obj['type_category']) {
if ($obj['type_category'] == 1) {
$object_type = 'BUSINESS';
}
if ($obj['type_category'] == 2) {
$object_type = 'WAREHOUSE';
}
if ($obj['type_category'] >= 3) {
$object_type = 'BUSINESS';
}
} else {
$object_type = 'BUSINESS';
}
break;
case 7:
$object_type = 'LAND';
break;
}
if ($obj['id_rf_region'])
$region_id = $obj['id_rf_region'];
else
$region_id = 78;
$sql_a = "SELECT * FROM advertising_package
WHERE is_room=$is_room AND
has_photo = $has_photos AND
advertising_package_deal_type_id IN (SELECT id FROM advertising_package_deal_type WHERE code = '$deal_type') AND
advertising_package_object_type_id IN (SELECT id FROM advertising_package_object_type WHERE code = '$object_type') AND
$sql_price AND
deleted = 0 AND
agency_id = $agency_id AND
(region_rf_id = $region_id OR region_rf_id IN (SELECT parent FROM rf_regions WHERE id = $region_id))";
if ($query = mysql_query($sql_a)) {
if (mysql_num_rows($query)) {
while ($package = mysql_fetch_assoc($query)) {
$checked = false;
$published = \zipalPackageCountText($obj['id'], $package['id']);
if ($published['zipal_active'] == 1 && (int)$published['zipal_days'] > 0)
$checked = true;
$targets = [];
$sql = "SELECT * FROM advertising_package_destinations WHERE advertising_package_id = '$package[id]' AND deleted = 0";
if ($query_d = mysql_query($sql)) {
while ($destination = mysql_fetch_assoc($query_d)) {
$target = $ZIPAL_TARGETS[$destination['destination']];
if (!$target)
$target = $destination['destination'];
$targets[] = $target;
}
} else {
$error = true;
$errors[] = mysql_error();
}
$is_error = (!empty($published['error_text'])) ? true : false;
$error_text = null;
if ($is_error)
$error_text = "Ошибка: " . $published['error_text'][0]['defaultMessage'];
$packages[] = [
'id' => intval($package['id']),
'name' => trim($package['name']),
'days_count' => (int)$package['days_count'],
'days_count_string' => \declOfNum((int)$package['days_count'], ['%d день', '%d дня', '%d дней']),
'targets' => $targets,
'is_active' => (!$is_error) ? $checked : false,
'left_days' => (!empty($published['zipal_days'])) ? (int)$published['zipal_days'] : false,
'status_text' => (!empty($published['zipal_days_text'])) ? $published['zipal_days_text'] : false,
'is_error' => $is_error,
'error_text' => $error_text,
/*'_meta' => $published,
'_meta2' => $package,*/
];
}
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
}
if (!$error && $need_return) {
if (!is_null($package_id))
return $package;
else
return $packages;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
if (!is_null($package_id)) {
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'object_id' => $object_id,
'package' => $package
], JSON_UNESCAPED_UNICODE));
} else {
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'object_id' => $object_id,
'packages' => $packages
], JSON_UNESCAPED_UNICODE));
}
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getBudget($app, $get, $post, $need_return = false) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$error = false;
$errors = [];
$is_agency_summary = false;
$is_department_user = false;
if (isset($get['is_agency']))
$is_agency_summary = boolval($get['is_agency']);
if (($user_id = $_SESSION['id']) && $_SESSION['use_advert_budget']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
// Текущий пользователь
$user = new \User;
$user->get($user_id);
$user->checkPermissions($user_id, false);
$departments_inst = new \Department();
$departments = $departments_inst->getDepartments((int)$user_id);
foreach ($departments as $department) {
if ($department['department_id'] == intval($user->department_id)) {
$is_department_user = true;
}
}
$is_budget_of = null;
$advert_budgets = new \AdvertBudgets();
$budget = [];
if ($is_agency_summary || ($user->agency || $user->users_admin)) {
$is_budget_of = 'agency';
$budgets = $advert_budgets->getAdvertBudgets(null, true);
$budget = $budgets;
} else {
$budgets = $advert_budgets->getAdvertBudgets($user_id);
$budget = $budgets[(int)$user_id];
if ($is_department_user) {
if ($user->agency)
$is_budget_of = "agency";
else if ($departments[$user->role_id]['role'] == 'admin_department')
$is_budget_of = "department_admin";
else if ($departments[$user->role_id]['role'] == 'manager_office_menager')
$is_budget_of = "department_manager_office_manager";
else if ($departments[$user->role_id]['role'] == 'manager_office')
$is_budget_of = "department_manager_office";
else if ($departments[$user->role_id]['role'] == 'agent')
$is_budget_of = "department_agent";
else
$is_department_user = !($is_office_user = true);
} else {
if ($user->agency)
$is_budget_of = "agency";
else if ($user->manager > 0)
$is_budget_of = "manager";
else
$is_budget_of = "agent";
}
}
$label = "Рекламный бюджет";
switch($is_budget_of) {
case 'agency':
$label = "Рекламный бюджет Агентства";
break;
case 'manager':
$label = "Рекламный бюджет менеджера и подчиненных агентов";
break;
case 'agent':
$label = "Рекламный бюджет агента";
break;
case 'department_admin':
$label = "Рекламный бюджет Отдела и подчиненных";
break;
case 'department_manager_office_manager':
$label = "Рекламный бюджет менеджера Офиса и подчиненных агентов";
break;
case 'department_manager_office':
$label = "Рекламный бюджет менеджера Отдела и подчиненных агентов";
break;
case 'department_agent':
$label = "Рекламный бюджет агента Отдела";
break;
}
$data = array_merge([
'avito' => [
'total' => ($budget['avito']) ? $budget['avito'] : 0,
'amount' => ($budget['avito_amount']) ? $budget['avito_amount'] : 0,
'available' => ($budget['avito_available']) ? $budget['avito_available'] : 0,
'is_unlimited' => (int)$budget['avito_unlimited'],
],
'cian' => [
'total' => ($budget['cian']) ? $budget['cian'] : 0,
'amount' => ($budget['cian_amount']) ? $budget['cian_amount'] : 0,
'available' => ($budget['cian_available']) ? $budget['cian_available'] : 0,
'is_unlimited' => (int)$budget['cian_unlimited'],
],
'domclick' => [
'total' => ($budget['domclick']) ? $budget['domclick'] : 0,
'amount' => ($budget['domclick_amount']) ? $budget['domclick_amount'] : 0,
'available' => ($budget['domclick_available']) ? $budget['domclick_available'] : 0,
'is_unlimited' => (int)$budget['domclick_unlimited'],
],
'yandex' => [
'total' => ($budget['yandex']) ? $budget['yandex'] : 0,
'amount' => ($budget['yandex_amount']) ? $budget['yandex_amount'] : 0,
'available' => ($budget['yandex_available']) ? $budget['yandex_available'] : 0,
'is_unlimited' => (int)$budget['yandex_unlimited'],
],
'jcat' => [
'total' => ($budget['jcat']) ? $budget['jcat'] : 0,
'amount' => ($budget['jcat_amount']) ? $budget['jcat_amount'] : 0,
'available' => ($budget['jcat_available']) ? $budget['jcat_available'] : 0,
'is_unlimited' => (int)$budget['jcat_unlimited'],
],
], [
'total' => ($budget['total']) ? $budget['total'] : 0,
'amount' => ($budget['amount']) ? $budget['amount'] : 0,
'balance' => ($budget['balance']) ? $budget['balance'] : 0,
'label' => $label,
'is_budget_of' => $is_budget_of,
'is_department_user' => $is_department_user,
]);
if (!$error && $need_return) {
return $data;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'budget' => $data
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getPrice($app, $get, $post, $need_return = false) {
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$error = false;
$errors = [];
$id = null;
if (isset($get['id']))
$id = intval($get['id']);
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$service = null;
if (isset($get['service']))
$service = trim($get['service']);
$days_num = 0;
if (isset($get['days_num']))
$days_num = intval($get['days_num']);
$price = 0;
$budget = 0;
if (($user_id = $_SESSION['id']) && !is_null($object_id)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$advert_budget = new \AdvertBudgets();
$service_id = $advert_budget->getServiceByName($service);
$results = $advert_budget->getObjectAdvertPrices($object_id, $service_id, $days_num);
if (!is_null($results['price']))
$price = $results['price'];
if (!is_null($results['budget']))
$budget = $results['budget'];
if ($need_return) {
return [
'object_id' => $object_id,
'service_id' => $service_id,
'price' => $price,
'owner_user_id' => $price['owner_user_id'],
'budget' => $budget,
];
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'object_id' => $object_id,
'service_id' => $service_id,
'price' => $price,
'owner_user_id' => $price['owner_user_id'],
'budget' => $budget,
//'_raw' => $results,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getZipalPrices($app, $get, $post, $need_return = false) {
global $ZIPAL_TARGETS;
global $ZIPAL_PRICE_TYPES;
global $ZIPAL_MULTIPLY;
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$error = false;
$errors = [];
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$days_num = 0;
if (isset($get['days_num']))
$days_num = intval($get['days_num']);
if (($user_id = $_SESSION['id']) && !is_null($object_id)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$packages = [];
$request = [];
$sql = "SELECT objects.* FROM objects WHERE objects.id = $object_id";
$query = mysql_query($sql);
if ($obj = mysql_fetch_assoc($query)) {
$curUser = new \User();
$curUser->get($user_id);
$agency_id = $curUser->agencyId;
$login = $curUser->zipal_login;
$password = $curUser->zipal_password;
if (empty($login) || empty($password)) {
$login = $curUser->agencyZipalLogin;
$password = $curUser->agencyZipalPassword;
}
$request['login'] = $login;
$request['password'] = $password;
$request['method'] = 'GetPrices';
$request['request'] = [];
$request['request']['requestType'] = 'GetPricesByParamsRequestType';
$request['request']['days'] = $days_num;
$request['request']['hasPhotos'] = false;
$request['request']['room'] = false;
if ($obj['id_rf_region']) {
$sql = "SELECT code FROM rf_regions WHERE rf_regions.id = ".$obj['id_rf_region'];
if ($query = mysql_query($sql)) {
$request['request']['region'] = mysql_fetch_assoc($query)['code'];
} else {
$error = true;
$errors[] = mysql_error();
}
} else {
$request['request']['region'] = 78;
}
if ($obj['operation_type'] == 1) {
$request['request']['dealType'] = 'SELL';
} else {
$request['request']['dealType'] = 'RENT';
$request['request']['priceType'] = 'MONTH';
if ($obj['srok'] == 1) {
$request['request']['priceType'] = 'DAY';
}
}
$sql = "SELECT oop.sort_order FROM objects_object_photo oop WHERE oop.object_id = $obj[id]";
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$request['request']['hasPhotos'] = true;
}
} else {
$error = true;
$errors[] = mysql_error();
}
switch ($obj['type']) {
case 1:
$request['request']['objectType'] = 'FLAT';
break;
case 2:
$request['request']['objectType'] = 'FLAT';
$request['request']['room'] = true;
break;
case 3:
case 5:
$request['request']['objectType'] = 'HOUSE';
break;
case 4:
case 6:
if ($obj['type_category']) {
if ($obj['type_category'] == 1) {
$request['request']['objectType'] = 'BUSINESS';
}
if ($obj['type_category'] == 2) {
$request['request']['objectType'] = 'WAREHOUSE';
}
if ($obj['type_category'] >= 3) {
$request['request']['objectType'] = 'BUSINESS';
}
} else {
$request['request']['objectType'] = 'BUSINESS';
}
break;
case 7:
$request['request']['objectType'] = 'LAND';
break;
}
$jsonResult = [];
try {
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; HTC_Touch_Diamond2_T5353; Windows Phone 6.5)';
$result = curl_request_zipal_json("https://zipal.ru/ws/json", $user_id, $user_agent, json_encode($request));
$jsonResult = json_decode($result, true);
} catch (\Exception $exception) {
$error = true;
$errors[] = $exception->getMessage();
}
if ($jsonResult['resultCode'] == "FAIL") { // ошибка
$res = strpos($jsonResult['result'], "at [Source:");
if ($res) {
$errors[] = substr($jsonResult['result'], $res);
} else {
$errors[] = $jsonResult['result'];
}
} else {
if ($jsonResult['resultCode'] == "OK") {
$base_price = (($jsonResult['result']['basePrice'] / 100) * $ZIPAL_MULTIPLY);
$groups = [];
$destinations = [];
foreach ($jsonResult['result']['destination'] as $dest) {
$skipped = false;
foreach ($dest['price'] as $price) {
if (!$price['feedOnly'])
$skipped = true;
}
if (!isset($dest['destination']))
continue;
$target_name = $dest['destination'];
if(isset($ZIPAL_TARGETS[$dest['destination']])){
$target_name = $ZIPAL_TARGETS[$dest['destination']];
}
$destination = strtolower(trim($dest['destination']));
if (!isset($groups[$destination]))
$groups[$destination] = $target_name;
if ($dest['destination'] === 'YANDEX')
$skipped = true;
if ($dest['destination'] === 'CIAN')
$skipped = true;
if ($dest['destination'] === 'EMLS')
$skipped = true;
if ($dest['destination'] === 'AVITO')
$skipped = true;
if ($skipped) {
foreach ($dest['price'] as $price) {
$is_feed = false;
if ($price['feedOnly']) {
$is_feed = true;
}
$amount = $price['price'] > 0 ? floatval($price['price']) / 100 : null;
$is_free = false;
if ((floatval($amount) == 0 && !$price['feedOnly']) || $dest['destination'] === 'YANDEX' || $dest['destination'] === 'CIAN' || $dest['destination'] === 'EMLS' || $dest['destination'] === 'AVITO') {
$is_free = true;
}
if ($is_free && floatval($amount) > 0)
$is_free = false;
$type = $price['type'];
$destinations[$destination][$type] = [
'type' => $type,
'price' => $amount,
'description' => (isset($ZIPAL_PRICE_TYPES[$price['type']])) ? $ZIPAL_PRICE_TYPES[$price['type']] : trim($price['type']),
'is_feed' => $is_feed,
'is_free' => $is_free
];
}
}
}
$packages[] = [
'days_count' => $days_num,
'base_price' => $base_price,
'groups' => $groups,
'destinations' => $destinations,
];
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error && $need_return) {
return $packages;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'object_id' => $object_id,
'packages' => count($packages) ? $packages : null,
//'_raw' => $jsonResult
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return false;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public function getPromotion($app, $get, $post) {
$error = false;
$errors = [];
$object_id = null;
if (isset($get['object_id']))
$object_id = $get['object_id'];
2026-06-28 09:56:29 +02:00
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id)
if ($this->_rejectIfExternalListing($app, isset($get['is_external']) ? $get['is_external'] : null)) return;
2026-05-22 20:21:54 +02:00
if (($user_id = $_SESSION['id']) && !is_null($object_id)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$promo = [];
$get = clearInputData($_GET);
$agency_id = \User::getUserAgencyID($user_id);
if ($get['object_id']) {
$sql = "SELECT * FROM `ads_promo`
WHERE `object_id` = '$object_id' AND
`agency_id` = '$agency_id'
LIMIT 1";
if ($query = mysql_query($sql)) {
$promo = mysql_fetch_assoc($query);
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'object_id' => $object_id,
'packages' => count($promo) ? $promo : false
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setPromotion($app, $get, $post) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
$object_id = null;
if (isset($data['object_id']))
$object_id = $data['object_id'];
2026-06-28 09:56:29 +02:00
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id)
if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return;
2026-05-22 20:21:54 +02:00
$packages = null;
if (isset($data['packages']))
$packages = $data['packages'];
if (($user_id = $_SESSION['id']) && !is_null($object_id) && !is_null($packages)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$agency_id = \User::getUserAgencyID($user_id);
$owner_id = (int)mysql_fetch_assoc(mysql_query("SELECT * FROM `objects` WHERE id = '$post[object_id]'"))['id_add_user'];
if (!$owner_id)
$owner_id = (int)$user_id;
$sql = "SELECT `id` FROM `ads_promo` WHERE `object_id` = '$object_id' AND `agency_id` = '$agency_id' LIMIT 1";
$packages = array_map('intval', $packages);
if ($id = (int)mysql_fetch_assoc(mysql_query($sql))['id']) {
$sql = "UPDATE `ads_promo`
SET `avito_highlight` = '$packages[avito_highlight]',
`avito_xl` = '$packages[avito_xl]',
`avito_x2_1` = '$packages[avito_x2_1]',
`avito_x2_7` = '$packages[avito_x2_7]',
`avito_x5_1` = '$packages[avito_x5_1]',
`avito_x5_7` = '$packages[avito_x5_7]',
`avito_x10_1` = '$packages[avito_x10_1]',
`avito_x10_7` = '$packages[avito_x10_7]',
`avito_price` = '$packages[avito_price]',
`cian_highlight` = '$packages[cian_highlight]',
`cian_standard` = '$packages[cian_standard]',
`cian_paid` = '$packages[cian_paid]',
`cian_premium` = '$packages[cian_premium]',
`cian_top3` = '$packages[cian_top3]',
`cian_bet` = '$packages[cian_bet]',
`cian_ignore_pkg` = '$packages[cian_ignore_pkg]',
`cian_price` = '$packages[cian_price]',
`yandex_premium` = '$packages[yandex_premium]',
`yandex_raise` = '$packages[yandex_raise]',
`yandex_promotion` = '$packages[yandex_promotion]',
`yandex_price` = '$packages[yandex_price]',
`domclick_express` = '$packages[domclick_express]',
`domclick_premium` = '$packages[domclick_premium]',
`domclick_top` = '$packages[domclick_top]',
`domclick_price` = '$packages[domclick_price]',
`object_owner_id` = '$owner_id',
`avito_promo_type` = '$packages[avito_promo_type]',
`updated_at` = NOW(),
`updated_by` = '$user_id'
WHERE `id` = '$id'";
} else {
$sql = "INSERT INTO `ads_promo` (
`object_id`,
`agency_id`,
`avito_highlight`,
`avito_xl`,
`avito_x2_1`,
`avito_x2_7`,
`avito_x5_1`,
`avito_x5_7`,
`avito_x10_1`,
`avito_x10_7`,
`avito_price`,
`cian_highlight`,
`cian_standard`,
`cian_paid`,
`cian_premium`,
`cian_top3`,
`cian_bet`,
`cian_ignore_pkg`,
`cian_price`,
`yandex_premium`,
`yandex_raise`,
`yandex_promotion`,
`yandex_price`,
`domclick_express`,
`domclick_premium`,
`domclick_top`,
`domclick_price`,
`object_owner_id`,
`created_at`,
`created_by`,
`updated_at`,
`updated_by`,
`avito_promo_type`
) VALUES(
'$object_id',
'$agency_id',
'$packages[avito_highlight]',
'$packages[avito_xl]',
'$packages[avito_x2_1]',
'$packages[avito_x2_7]',
'$packages[avito_x5_1]',
'$packages[avito_x5_7]',
'$packages[avito_x10_1]',
'$packages[avito_x10_7]',
'$packages[avito_price]',
'$packages[cian_highlight]',
'$packages[cian_standard]',
'$packages[cian_paid]',
'$packages[cian_premium]',
'$packages[cian_top3]',
'$packages[cian_bet]',
'$packages[cian_ignore_pkg]',
'$packages[cian_price]',
'$packages[yandex_premium]',
'$packages[yandex_raise]',
'$packages[yandex_promotion]',
'$packages[yandex_price]',
'$packages[domclick_express]',
'$packages[domclick_premium]',
'$packages[domclick_top]',
'$packages[domclick_price]',
'$owner_id',
NOW(),
'$user_id',
NULL,
NULL,
'$packages[avito_promo_type]'
)";
}
if (!mysql_query($sql)) {
$error = true;
$errors[] = mysql_error();
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'sql' => $sql,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function editAdvertPrice($app, $get, $post) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
$id = null;
if (isset($data['id']))
$id = $data['id'];
$object_id = null;
if (isset($data['object_id']))
$object_id = $data['object_id'];
2026-06-28 09:56:29 +02:00
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id)
if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return;
2026-05-22 20:21:54 +02:00
$price = null;
if (isset($data['price']))
$price = $data['price'];
$old_price_string = null;
if (isset($data['old_price']))
$old_price_string = trim($data['old_price']);
$destination = null;
if (isset($data['destination']))
$destination = $data['destination'];
if (($user_id = $_SESSION['id']) && !is_null($id) && !is_null($object_id) && !is_null($destination) && !is_null($price)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$service_name = '';
if ($destination == 'avito') {
$service_name = ' для Фида Avito';
$destination = 'AVITO_JW_FEED';
}
else if ($destination == 'cian') {
$service_name = ' для Фида ЦИАН';
$destination = 'CIAN_JW_FEED';
}
else if ($destination == 'yandex') {
$service_name = ' для Фида Я.Недвижимость';
$destination = 'YANDEX_JW_FEED';
}
else if ($destination == 'domclick') {
$service_name = ' для Фида ДомКлик';
$destination = 'DOMCLICK_JW_FEED';
}
else if ($destination == 'jcat') {
$service_name = ' для Фида JCat';
$destination = 'EMLS_JW_FEED';
}
$sql = "UPDATE `object_publish_statistic`
SET `price`='$price'
WHERE `id`='$id' AND
`object_id`='$object_id' AND
`destination`='$destination'
LIMIT 1";
if (mysql_query($sql)) {
$price_string = (((float)$price < 1) ? declOfNum((float)$price * 100, ['%d копейка', '%d копейки', '%d копеек']) : declOfNum((float)$price, ['%s рубль', '%s рубля', '%s рублей']));
$message = 'Изменена стоимость продвижения в Рекламе' . $service_name . ' с '. $old_price_string . ' на ' . $price_string;
$sql = "INSERT INTO user_object_events(user_id, object_id, type, comment) VALUES($user_id, $object_id, 'comment', '$message')";
mysql_query($sql);
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'destination' => $destination,
'price' => $price,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function editPromotionPrice($app, $get, $post) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
$id = null;
if (isset($data['id']))
$id = $data['id'];
$object_id = null;
if (isset($data['object_id']))
$object_id = $data['object_id'];
2026-06-28 09:56:29 +02:00
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id)
if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return;
2026-05-22 20:21:54 +02:00
$price = null;
if (isset($data['price']))
$price = $data['price'];
$old_price_string = null;
if (isset($data['old_price']))
$old_price_string = trim($data['old_price']);
$destination = null;
if (isset($data['destination']))
$destination = $data['destination'];
if (($user_id = $_SESSION['id']) && !is_null($id) && !is_null($object_id) && !is_null($destination) && !is_null($price)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$agency_id = \User::getUserAgencyID($user_id);
$service_name = '';
if ($destination == 'avito') {
$service_name = ' для Avito';
$sql = "UPDATE `ads_promo` SET `avito_price`='$price', `updated_by`='$user_id' WHERE `id`='$id' AND `object_id`='$object_id' AND `agency_id`='$agency_id'";
}
else if ($destination == 'cian') {
$service_name = ' для ЦИАН';
$sql = "UPDATE `ads_promo` SET `cian_price`='$price', `updated_by`='$user_id' WHERE `id`='$id' AND `object_id`='$object_id' AND `agency_id`='$agency_id'";
}
else if ($destination == 'yandex') {
$service_name = ' для Я.Недвижимость';
$sql = "UPDATE `ads_promo` SET `yandex_price`='$price', `updated_by`='$user_id' WHERE `id`='$id' AND `object_id`='$object_id' AND `agency_id`='$agency_id'";
}
else if ($destination == 'domclick') {
$service_name = ' для ДомКлик';
$sql = "UPDATE `ads_promo` SET `domclick_price`='$price', `updated_by`='$user_id' WHERE `id`='$id' AND `object_id`='$object_id' AND `agency_id`='$agency_id'";
}
if (mysql_query($sql)) {
$price_string = (((float)$price < 1) ? declOfNum((float)$price * 100, ['%d копейка', '%d копейки', '%d копеек']) : declOfNum((float)$price, ['%s рубль', '%s рубля', '%s рублей']));
$message = 'Изменена стоимость продвижения в Рекламе' . $service_name . ' с '. $old_price_string . ' на ' . $price_string;
$sql = "INSERT INTO user_object_events(user_id, object_id, type, comment) VALUES($user_id, $object_id, 'comment', '$message')";
mysql_query($sql);
} else {
$error = true;
$errors[] = mysql_error();
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'destination' => $destination,
'price' => $price,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getObjectCosts($app, $get = null, $post = null) {
global $PROMO_TARGETS;
global $ZIPAL_TARGETS;
$error = false;
$errors = [];
$object_id = intval($get['object_id']);
if (($user_id = $_SESSION['id']) && $object_id) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('pdo');
/*error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);*/
$user = new \User;
$user->get($user_id);
$gmtmsk =$user->gmtmsk;
$time_zone = '';
if($gmtmsk >= 0){
$time_zone = '+'.$gmtmsk.' hour';
} else {
$time_zone = '-'.$gmtmsk.' hour';
}
$user->checkPermissions($user_id, false);
$results = [];
$today = 0;
$total = 0;
$sql = "SELECT `stats`.*,
`stats`.`id` AS `id`,
`users`.`last_name` AS `last_name`,
`users`.`first_name` AS `first_name`,
`users`.`middle_name` AS `middle_name`,
`users`.`agency` AS `agency`,
`users`.`fio` AS `fio`,
`users`.`manager` AS `manager`
FROM `object_publish_statistic` AS `stats`
LEFT JOIN `users` AS `users` ON `users`.`id` = `stats`.`publish_user_id`
WHERE `stats`.`object_id` = '$object_id' AND `stats`.`on_moderation` = 0
ORDER BY `stats`.`publish_start_date` DESC,
`stats`.`id` ASC";
if ($rez = mysql_query($sql)) {
$date = '';
$new_date = '';
$stats = [];
while ($stat = mysql_fetch_assoc($rez)) {
if (in_array($stat['destination'], array_keys($PROMO_TARGETS)))
$stat['type'] = 'promotion';
else
$stat['type'] = 'regular';
$stats[] = $stat;
}
$num = 0;
$targets = array_merge($PROMO_TARGETS, $ZIPAL_TARGETS);
foreach ($stats as $stat) {
$num++;
$target = $targets[$stat['destination']];
$publisher_id = (int)$stat['publish_user_id'];
$unpublisher_id = null;
$unpublisher_at = null;
if (isset($stat['unpublish_user_id'])) {
$unpublisher_id = (int)$stat['unpublish_user_id'];
$unpublisher_at = strtotime($time_zone, strtotime($stat['updated_at']));
}
$row = mysql_fetch_assoc(mysql_query("SELECT agency, manager, fio FROM users WHERE id=$publisher_id"));
if ($row['agency'])
$publisher = "Агентство $row[fio]";
elseif ($row['manager'])
$publisher = "Менеджер $row[fio]";
else
$publisher = "Агент $row[fio]";
$unpublisher = null;
if ($unpublisher_id) {
$row = mysql_fetch_assoc(mysql_query("SELECT agency, manager, fio FROM users WHERE id=$unpublisher_id"));
if ($row['agency'])
$unpublisher = "Агентство $row[fio]";
elseif ($row['manager'])
$unpublisher = "Менеджер $row[fio]";
else
$unpublisher = "Агент $row[fio]";
}
$publisher_at = strtotime($time_zone, strtotime($stat['publish_start_date']));
$date = date('d', $publisher_at) . ' ' . getRusMonth(date('m', $publisher_at)) . ' ' . date('Y', $publisher_at). ' г.';
$new_date = $date;
if (!$target)
$target = $stat['destination'];
if ($stat['type'] == 'promotion')
$target = 'Продвижение от ' . $target;
else
$target = 'Размещено ' . ((strpos($target, 'Фид') !== false) ? 'в ' : 'на ') . $target;
$price = 0;
if ($stat['price'] > 0) {
$price = (float)$stat['price'] < 1 ? (float)$stat['price'] * 100 : (float)$stat['price'];
$today = $today + $stat['price'];
$total = $total + $stat['price'];
}
$datetime = date('H:i:s', $publisher_at);
$destination = $stat['destination'];
if ($stat['type'] == 'promotion') {
if (strpos($destination, 'AVITO') !== false)
$destination = 'avito';
else if (strpos($destination, 'CIAN') !== false)
$destination = 'cian';
else if (strpos($destination, 'DOMCLICK') !== false)
$destination = 'domclick';
else if (strpos($destination, 'JCAT') !== false)
$destination = 'jcat';
else if (strpos($destination, 'YANDEX') !== false)
$destination = 'yandex';
}
$results['stats'][$date][$datetime][] = [
'id' => (int)$stat['id'],
'target' => $target,
'type' => $stat['type'],
'destination' => $destination,
'publisher' => $publisher,
'publisher_at' => date('d.m.Y в H:i:s', $publisher_at),
'publisher_by' => $publisher_id,
'unpublisher' => $unpublisher,
'unpublished_at' => date('d.m.Y в H:i:s', $unpublisher_at),
'unpublished_by' => $unpublisher_id,
'days' => ($stat['days_count'] < 5000) ? (int)$stat['days_count'] : false,
'expired' => ($stat['days_count'] < 5000) ? date('d.m.Y', strtotime($stat['publish_end_date'])) : false,
'price' => $price,
];
$results['stats'][$date]['amount'] = $price+$results['stats'][$date]['amount'];
if ($date != $new_date) {
$today = 0;
$date = '';
}
}
$results['total'] = (float)$total < 1 ? (float)$total * 100 : (float)$total;
}
$results['stats'] = array_reverse($results['stats']);
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'results' => $results,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getModerators($app, $get = null, $post = null) {
$error = false;
$errors = [];
$section = null;
if (isset($get['section']))
$section = trim($get['section']);
if (($user_id = $_SESSION['id']) && !is_null($section)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$pdo = $app->container->get('mypdo');
/*error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);*/
$employees = [];
$meta = [];
// Текущий пользователь
$user = new \User;
$user->get($user_id);
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
$event_id = null;
if (isset($get['event_id']))
$event_id = intval($get['event_id']);
$sub_id = null;
if (isset($get['sub_id']))
$sub_id = intval($get['sub_id']);
if ($section == 'adverts') {
$users = [];
$this_users = [];
$user = new \User();
$user->get($user_id);
$agency_id = $user->agencyId;
$users_moderation = [];
//Все юзеры агенства
$sql_users = "SELECT * FROM users WHERE id 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 or id_manager in
(select id from users where id_manager=$agency_id)))";
$q_users = $pdo->query($sql_users);
while($r_users = $pdo->fetch_assoc($q_users)) {
$users[$r_users['id']] = $r_users;
if ($r_users['id'] == $user_id) {
$this_users = $r_users;
//$meta['this_users'] = $this_users;
}
}
//Поиск модераций
$sql_modr = "SELECT * FROM objects_moderation_advert WHERE object_id={$object_id} AND agent_id={$user_id}";
$q_modr = $pdo->query($sql_modr);
if ($pdo->num_rows($q_modr) > 0) {
$r_modr = $pdo->fetch_assoc($q_modr);
$sql_modr_users = "SELECT * FROM `objects_moderation_advert_user_work` WHERE moderation_id = {$r_modr['id']}";
$q_modr_users = $pdo->query($sql_modr_users);
if ($pdo->num_rows($q_modr_users) > 0) {
$meta['moderator'] = $r_modr;
while($r_moder_users = $pdo->fetch_assoc($q_modr_users)) {
$users_moderation[] = (int)$r_moder_users['user_id'];
}
}
}
$db_sphinx = $app->container->get('sphinx2');
$obj = $db_sphinx->fetch_assoc($db_sphinx->query("SELECT * FROM objects WHERE id={$object_id}"));
if ($obj)
$meta['object'] = $obj;
$meta['users'] = $users_moderation;
foreach ($users as $emp) {
if ($emp['blocked'] == 0) {
if (($emp['manager'] == 1 || $emp['agency'] == 1 || $emp['users_admin'] == 1) && $emp['show_all_objects_page'] == 1) {
$employees[] = [
'id' => intval($emp['id']),
'name' => htmlspecialchars_decode(trim($emp['last_name'] . ' ' . $emp['first_name'] . ' ' . $emp['middle_name'])),
'is_selected' => (in_array($emp['id'], $users_moderation)),
'is_agent' => boolval($emp['agent']),
'is_manager' => boolval($emp['manager']),
];
}
}
}
} else if ($section == 'events') {
$users = [];
$this_users = [];
$user = new \User();
$user->get($user_id);
$agency_id = $user->agencyId;
//Все юзеры агенства
$sql_users = "SELECT * FROM users WHERE id 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 or id_manager in
(select id from users where id_manager=$agency_id)))";
$q_users = $pdo->query($sql_users);
while($r_users = $pdo->fetch_assoc($q_users)) {
$users[$r_users['id']] = $r_users;
if ($r_users['id'] == $user_id) {
$this_users = $r_users;
//$meta['this_users'] = $this_users;
}
}
$sql_event = "SELECT * FROM user_object_events WHERE id = {$event_id}";
$q_event = $pdo->query($sql_event);
$r_event = $pdo->fetch_assoc($q_event);
if (isset($r_event['object_id']) && $r_event['object_id'] > 0) {
$object_id = (int)$r_event['object_id'];
$meta['object_id'] = $object_id;
}
if ($object_id > 0) {
$db_sphinx = $app->container->get('sphinx2');
//ответственный по объекту
$sql_obj = "SELECT * FROM objects WHERE id={$object_id}";
$q_obj = $db_sphinx->query($sql_obj);
$r_obj = $db_sphinx->fetch_assoc($q_obj);
if (isset($r_obj['id_add_user']) && $r_obj['id_add_user'] > 0) {
$user_add = (int)$r_obj['id_add_user'];
$meta['user_add'] = $user_add;
}
}
$user_for = 0;
if ($sub_id > 0) {
$sql_sub = "SELECT * FROM user_sub_comments WHERE id = {$sub_id}";
$q_sub = $pdo->query($sql_sub);
$r_sub = $pdo->fetch_assoc($q_sub);
$meta['event_id'] = $event_id;
$meta['sub_comment'] = $r_sub['sub_comment'];
$meta['user_for'] = (int)$r_sub['user_for'];
$user_for = (int)$r_sub['user_for'];
}
foreach ($users as $emp) {
if ($emp['blocked'] == 0) {
if (
(($emp['manager'] == 1 || $emp['agency'] == 1 || $emp['users_admin'] == 1) && $emp['show_all_objects_page'] == 1) ||
($user_add > 0 && $emp['id'] == $user_add)
) {
$employees[] = [
'id' => intval($emp['id']),
'name' => htmlspecialchars_decode(trim($emp['last_name'] . ' ' . $emp['first_name'] . ' ' . $emp['middle_name'])),
'is_selected' => ($emp['id'] == $user_for),
'is_agent' => boolval($emp['agent']),
'is_manager' => boolval($emp['manager']),
];
}
}
}
}
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$sources = [
'success' => true,
'user_id' => (int)$user_id,
'list' => $employees,
'meta' => $meta
];
$app->response->setBody(json_encode($sources, JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setConfirmModeration($app, $get, $post) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
$object_id = null;
if (isset($data['object_id']))
$object_id = $data['object_id'];
2026-06-28 09:56:29 +02:00
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id)
if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return;
2026-05-22 20:21:54 +02:00
$services = null;
if (isset($data['services']))
$services = $data['services'];
if (($user_id = $_SESSION['id']) && !is_null($object_id) && !is_null($services)) {
// Открываем соединение с БД
$mypdo = $app->container->get('mypdo');
$moderation_inst = new \ModerationAdvert($mypdo);
$result = $moderation_inst->confirmModeration($object_id);
if (!empty($result['errors']))
$errors = $result['errors'];
//$moderation_inst->checkAndClear($object_id, 'use_in_advert', false);
if (empty($errors)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => ($result['result'] == 'done'),
'user_id' => (int)$user_id,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setModeration($app, $get, $post) {
$error = false;
$errors = [];
$body = $app->request->getBody();
$data = json_decode($body, true);
$object_id = null;
if (isset($data['object_id']))
$object_id = $data['object_id'];
2026-06-28 09:56:29 +02:00
// Признак найденного листинга — явный флаг из запроса (offset-free: id листинга коллизит с objects.id)
if ($this->_rejectIfExternalListing($app, isset($data['is_external']) ? $data['is_external'] : null)) return;
2026-05-22 20:21:54 +02:00
$employee_ids = null;
if (isset($data['employee_ids']))
$employee_ids = $data['employee_ids'];
$comment = '';
if (isset($data['comment']))
$comment = trim($data['comment']);
if (($user_id = $_SESSION['id']) && !is_null($object_id) && is_array($employee_ids)) {
// Открываем соединение с БД
$mypdo = $app->container->get('mypdo');
$mdb = $app->container->get('mysql');
$moderation_inst = new \ModerationAdvert($mypdo);
$result = $moderation_inst->sendModeration($user_id, $object_id, $employee_ids, $comment);
if (!empty($result['errors']))
$errors = $result['errors'];
if (empty($errors)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function unsetModeration($app, $get, $post) {
$error = false;
$errors = [];
$object_id = null;
if (isset($get['object_id']))
$object_id = intval($get['object_id']);
if (($user_id = $_SESSION['id']) && !is_null($object_id)) {
// Открываем соединение с БД
$mypdo = $app->container->get('mypdo');
$mdb = $app->container->get('mysql');
$moderation_inst = new \ModerationAdvert($mypdo);
$result = $moderation_inst->checkAndClear($object_id, 'use_in_advert', true);
if (!empty($result['errors']))
$errors = $result['errors'];
if (empty($errors)) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => $errors
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function checkAdUnique($app, $post) {
$pdo = $app->container->get('mypdo');
$body = $app->request->getBody();
$object_id = $_GET['object_id'];
$agency_id = $_SESSION['agency_id'];
$agents = [$agency_id]; // Добавляем самого главу
$queue = [$agency_id];
while (!empty($queue)) {
$current_id = array_shift($queue);
$sql = "SELECT id FROM users WHERE id_manager = $current_id";
$result = $pdo->query($sql);
while ($row = $pdo->fetch_assoc($result)) {
$agents[] = $row['id'];
$queue[] = $row['id'];
}
}
$all_agents = $agents;
$this_object_sql = "SELECT id FROM objects WHERE id = $object_id AND use_in_advert = 1";
$this_object_query = $pdo->query($this_object_sql);
$this_object = $pdo->fetch_assoc($this_object_query);
$sql_object = "SELECT o.adres, o.cadastral_number, o.cadastral_number_land, o.id_add_user, oai.flat_number, o.id
FROM objects o
LEFT JOIN objects_additional_information oai ON o.id = oai.object_id
WHERE o.id = $object_id";
$result = $pdo->query($sql_object);
$obj_data = $pdo->fetch_assoc($result);
if (!empty($obj_data['cadastral_number'])) {
$cadastral_number_to_check = $obj_data['cadastral_number'];
$cad_column = 'cadastral_number';
} elseif (!empty($obj_data['cadastral_number_land']) && empty($obj_data['cadastral_number'])) {
$cadastral_number_to_check = $obj_data['cadastral_number_land'];
$cad_column = 'cadastral_number_land';
}
if ($cadastral_number_to_check) {
// Проверяем по кадастровому номеру
$cad_sql = "SELECT id FROM objects
WHERE $cad_column = '" . addslashes($cadastral_number_to_check) . "'
AND id != " . intval($obj_data['id']) . "
AND id_add_user IN (" . implode(",", $all_agents) . ")
AND use_in_advert = 1"; // Исключаем текущий ID сразу в SQL
$cad_res = $pdo->query($cad_sql);
$object_ids = [];
while ($cad_obj = $pdo->fetch_assoc($cad_res)) {
$object_ids[] = $cad_obj['id'];
}
if (!empty($object_ids)) {
echo json_encode(["object_in_ads" => true, "object_ids" => $object_ids]);
exit();
}
}
// Если нет кадастрового номера, идем по обычной логике
$sim_sql = "SELECT o.id, o.id_add_user
FROM objects o
LEFT JOIN objects_additional_information oai ON o.id = oai.object_id
WHERE o.id_add_user IN (" . implode(",", $all_agents) . ")";
$conditions = [];
if (!empty($obj_data['adres']) && !empty($obj_data['flat_number'])) {
$conditions[] = "(o.adres = '" . addslashes($obj_data['adres']) . "'
AND oai.flat_number = '" . addslashes($obj_data['flat_number']) . "')";
}
if (empty($conditions)) {
echo json_encode(["object_in_ads" => false]);
exit();
} else {
$sim_sql .= " AND (" . implode(" OR ", $conditions) . ")";
}
$sim_res = $pdo->query($sim_sql);
$matching_objects = [];
while ($row = $pdo->fetch_assoc($sim_res)) {
$matching_objects[$row['id']] = $row['id_add_user'];
}
$filtered_objects = [];
foreach ($matching_objects as $id => $id_add_user) {
if (in_array($id_add_user, $all_agents)) {
$filtered_objects[] = $id;
}
}
$object_in_ads = false;
$objects_in_ads = [];
$this_object_id = intval($this_object['id']);
foreach ($filtered_objects as $obj_id) {
$sql_ad = "SELECT COUNT(*) as count FROM objects WHERE id = $obj_id AND use_in_advert = 1";
$ad_res = $pdo->query($sql_ad);
$ad_row = $pdo->fetch_assoc($ad_res);
if ($ad_row['count'] > 0 && $obj_id !== $this_object_id) {
$objects_in_ads[] = $obj_id;
$object_in_ads = true;
}
}
echo json_encode(["object_in_ads" => $object_in_ads, "object_ids" => $objects_in_ads]);
}
}