Files
crm.clientright.ru/webservice.php
Fedor 01c4fe80b5 chore: snapshot current working tree changes
Save all currently accumulated repository changes as a backup snapshot for Gitea so no local work is lost.
2026-03-26 14:19:01 +03:00

217 lines
7.7 KiB
PHP
Raw 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
/*+*******************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
********************************************************************************/
// Start output buffering to prevent "headers already sent" errors
ob_start();
require_once("config.php");
/**
* URL Verfication - Required to overcome Apache mis-configuration and leading to shared setup mode.
*/
if (file_exists('config_override.php')) {
include_once 'config_override.php';
}
//Overrides GetRelatedList : used to get related query
//TODO : Eliminate below hacking solution
include_once 'include/Webservices/Relation.php';
include_once 'vtlib/Vtiger/Module.php';
include_once 'includes/main/WebUI.php';
require_once("libraries/HTTP_Session2/HTTP/Session2.php");
require_once 'include/Webservices/Utils.php';
require_once("include/Webservices/State.php");
require_once("include/Webservices/OperationManager.php");
require_once("include/Webservices/SessionManager.php");
require_once("include/Zend/Json.php");
require_once('include/logging.php');
require_once('include/Webservices/CreateTGContact.php');
$API_VERSION = "0.22";
// Initialize database connection
require_once('include/database/PearDatabase.php');
global $adb, $seclog, $log;
$adb = PearDatabase::getInstance();
$seclog =& LoggerManager::getLogger('SECURITY');
$log =& LoggerManager::getLogger('webservice');
function getRequestParamsArrayForOperation($operation){
global $operationInput;
return $operationInput[$operation];
}
function setResponseHeaders() {
header('Content-type: application/json');
}
function writeErrorOutput($operationManager, $error){
// Очищаем буфер вывода перед отправкой JSON (убираем любые warnings/notices)
ob_clean();
setResponseHeaders();
$state = new State();
$state->success = false;
$state->error = $error;
unset($state->result);
if ($operationManager) {
$output = $operationManager->encode($state);
echo $output;
} else {
// Fallback when OperationManager is not available
require_once("include/Zend/Json.php");
echo Zend_Json::encode($state);
}
}
function writeOutput($operationManager, $data){
// Очищаем буфер вывода перед отправкой JSON (убираем любые warnings/notices)
ob_clean();
setResponseHeaders();
$state = new State();
$state->success = true;
$state->result = $data;
unset($state->error);
$output = $operationManager->encode($state);
echo $output;
}
$logstring = date('Y-m-d H:i:s').' '.json_encode($_REQUEST).PHP_EOL;
file_put_contents('logs/webservice.log', $logstring, FILE_APPEND);
// Если POST с JSON-телом (например от n8n) — подмешиваем в $_POST и $_REQUEST
$contentType = isset($_SERVER['CONTENT_TYPE']) ? strtolower($_SERVER['CONTENT_TYPE']) : '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (strpos($contentType, 'application/json') !== false)) {
$raw = file_get_contents('php://input');
if ($raw !== '' && $raw !== false) {
$decoded = json_decode($raw, true);
if (is_array($decoded)) {
$_POST = array_merge($_POST, $decoded);
$_REQUEST = array_merge($_REQUEST, $decoded);
// Нормализация имён полей для UpsertContact (n8n присылает first_name, phone и т.д.)
$aliasMap = array(
'first_name' => 'firstname', 'last_name' => 'lastname', 'middle_name' => 'secondname',
'phone' => 'mobile', 'birth_date' => 'birthday', 'birth_place' => 'birthplace',
'mailing_address' => 'mailingstreet'
);
foreach ($aliasMap as $from => $to) {
if (isset($_POST[$from]) && (!isset($_POST[$to]) || $_POST[$to] === '')) {
$_POST[$to] = $_POST[$from];
$_REQUEST[$to] = $_REQUEST[$from];
}
}
}
}
}
// ✅ Очищаем буфер от BOM, который мог появиться при загрузке include файлов
$buffer = ob_get_clean();
if (!empty($buffer) && trim($buffer) !== '') {
// Если в буфере что-то есть (не только пробелы), логируем для отладки
file_put_contents('logs/webservice_buffer.log', date('Y-m-d H:i:s').' Buffer content: '.bin2hex(substr($buffer, 0, 100)).PHP_EOL, FILE_APPEND);
}
ob_start(); // Перезапускаем буферизацию
$operation = vtws_getParameter($_REQUEST, "operation");
$operation = strtolower($operation);
$format = vtws_getParameter($_REQUEST, "format","json");
$sessionId = vtws_getParameter($_REQUEST,"sessionName");
// Для UpsertContact: подставляем firstname, mobile и т.д. из first_name, phone и т.д., если ещё не заданы
if ($operation === 'upsertcontact') {
$aliasMap = array(
'first_name' => 'firstname', 'last_name' => 'lastname', 'middle_name' => 'secondname',
'phone' => 'mobile', 'birth_date' => 'birthday', 'birth_place' => 'birthplace',
'mailing_address' => 'mailingstreet'
);
foreach ($aliasMap as $from => $to) {
if (isset($_REQUEST[$from]) && (!isset($_REQUEST[$to]) || $_REQUEST[$to] === '')) {
$_POST[$to] = $_REQUEST[$from];
$_REQUEST[$to] = $_REQUEST[$from];
}
}
}
$sessionManager = null;
$operationManager = null;
try{
$sessionManager = new SessionManager();
$operationManager = new OperationManager($adb,$operation,$format,$sessionManager);
if(!$sessionId || strcasecmp($sessionId,"null")===0){
$sessionId = null;
}
$input = $operationManager->getOperationInput();
$adoptSession = false;
if(strcasecmp($operation,"extendsession")===0){
if(isset($input['operation'])){
// Workaround fix for PHP 5.3.x: $_REQUEST doesn't have PHPSESSID
if(isset($_REQUEST['PHPSESSID'])) {
$sessionId = vtws_getParameter($_REQUEST,"PHPSESSID");
} else {
// NOTE: Need to evaluate for possible security issues
$sessionId = vtws_getParameter($_COOKIE,'PHPSESSID');
}
// END
$adoptSession = true;
}else{
writeErrorOutput($operationManager,new WebServiceException(WebServiceErrorCode::$AUTHREQUIRED,"Authencation required"));
return;
}
}
$sid = $sessionManager->startSession($sessionId,$adoptSession);
if(!$sessionId && !$operationManager->isPreLoginOperation()){
writeErrorOutput($operationManager,new WebServiceException(WebServiceErrorCode::$AUTHREQUIRED,"Authencation required"));
return;
}
if(!$sid){
writeErrorOutput($operationManager, $sessionManager->getError());
return;
}
$userid = $sessionManager->get("authenticatedUserId");
if($userid){
$seed_user = new Users();
$current_user = $seed_user->retrieveCurrentUserInfoFromFile($userid);
}else{
$current_user = null;
}
$operationInput = $operationManager->sanitizeOperation($input);
$includes = $operationManager->getOperationIncludes();
foreach($includes as $ind=>$path){
checkFileAccessForInclusion($path);
require_once($path);
}
$rawOutput = $operationManager->runOperation($operationInput,$current_user);
writeOutput($operationManager, $rawOutput);
} catch (DuplicateException $e) {
writeErrorOutput($operationManager,new WebServiceException($e->getCode(), $e->getMessage()));
}catch(WebServiceException $e){
writeErrorOutput($operationManager,$e);
}catch(Exception $e){
writeErrorOutput($operationManager,
new WebServiceException(WebServiceErrorCode::$INTERNALERROR,"Unknown Error while processing request"));
}
?>