Añadiendo los plugins base payments y cms_api
This commit is contained in:
205
cms/lib/plugins/cms_api/v3/classes/Api.class.php
Normal file
205
cms/lib/plugins/cms_api/v3/classes/Api.class.php
Normal file
@@ -0,0 +1,205 @@
|
||||
<?
|
||||
class Api {
|
||||
private static $renewToken = null;
|
||||
public static $user;
|
||||
public static $request;
|
||||
public static $responseData;
|
||||
public static $jsonConfig;
|
||||
public static $warnings = [];
|
||||
public static $allowedTranslateFields = null;
|
||||
public static $lang = "";
|
||||
public static $die = false;
|
||||
|
||||
function __construct() {
|
||||
|
||||
}
|
||||
static function setLanguage(){
|
||||
|
||||
$idioma_seleccionado = @substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
|
||||
|
||||
if(@$idioma_seleccionado && !isset($_REQUEST['idioma'])) {
|
||||
$_REQUEST['idioma'] = $idioma_seleccionado;
|
||||
}
|
||||
|
||||
$idioma_seleccionado_forzado = @substr($_SERVER['HTTP_X_ACAI_ACCEPT_LANGUAGE'], 0, 2);
|
||||
|
||||
if(@$idioma_seleccionado_forzado) {
|
||||
$_REQUEST['idioma'] = $idioma_seleccionado_forzado;
|
||||
}
|
||||
|
||||
if(@$_REQUEST['idioma'] === 'www') $_REQUEST['idioma'] = '';
|
||||
|
||||
self::$lang = @$_REQUEST['idioma'];
|
||||
return $idioma_seleccionado;
|
||||
}
|
||||
|
||||
static function t_recursivo($record, $idx=null) {
|
||||
global $TABLE_PREFIX;
|
||||
if(is_null(self::$allowedTranslateFields)) {
|
||||
self::$allowedTranslateFields = array_flip(array_map(function($field) {
|
||||
return $field['fieldName'];
|
||||
}, mysql_query_fetch_all_assoc("SELECT DISTINCT fieldName FROM {$TABLE_PREFIX}traducciones")));
|
||||
}
|
||||
$it = $idx ? $record[$idx] : $record;
|
||||
if (is_array($it)) {
|
||||
foreach ($it as $key => $value) {
|
||||
if (is_array($it[$key])) {
|
||||
$it[$key] = self::t_recursivo($it[$key], null);
|
||||
} else {
|
||||
if (isset(self::$allowedTranslateFields[$key])) {
|
||||
$it[$key] = t($it, $key);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($idx) {
|
||||
$record[$idx] = $it;
|
||||
} else {
|
||||
$record = $it;
|
||||
}
|
||||
} else {
|
||||
if ($idx && isset(self::$allowedTranslateFields[$idx])) {
|
||||
$record[$idx] = t($record, $idx);
|
||||
}
|
||||
}
|
||||
return $record;
|
||||
}
|
||||
|
||||
static function generateJsonConfig($files = []){
|
||||
$jsons = [];
|
||||
foreach($files as $file){
|
||||
if (file_exists($file)){
|
||||
$jsons[] = json_decode(file_get_contents($file),true);
|
||||
}
|
||||
}
|
||||
self::$jsonConfig = self::array_merge_deep_array($jsons);
|
||||
return self::$jsonConfig;
|
||||
|
||||
}
|
||||
private static function array_merge_deep() {
|
||||
$args = func_get_args();
|
||||
return self::array_merge_deep_array($args);
|
||||
}
|
||||
|
||||
private static function array_merge_deep_array($arrays) {
|
||||
$result = array();
|
||||
foreach ($arrays as $array) {
|
||||
if (!is_array($array)) continue;
|
||||
foreach ($array as $key => $value) {
|
||||
if (is_integer($key)) {
|
||||
$result[] = $value;
|
||||
}
|
||||
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
|
||||
$result[$key] = self::array_merge_deep_array(array(
|
||||
$result[$key],
|
||||
$value,
|
||||
));
|
||||
}
|
||||
else {
|
||||
$result[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
static function activity($prevRecord = null,$tableName = '',$newRecord = null,$method = "UPDATE"){
|
||||
if (!$tableName) self::error(new ApiError('No tableName specified'));
|
||||
|
||||
// INICIO REGISTRO DE ACTIVIDAD
|
||||
global $menu;
|
||||
$menu = $tableName;
|
||||
if (!function_exists("generateNotificationPlugin_registro_actividad") && file_exists(__DIR__."/../../cms/lib/plugins/registro_actividad/registro_act.php")){
|
||||
require_once __DIR__."/../../cms/lib/plugins/registro_actividad/registro_act.php";
|
||||
}
|
||||
if (file_exists(__DIR__."/../../cms/lib/plugins/registro_actividad/registro_act.php")){
|
||||
$arrayData = [];
|
||||
$recordNum = 0;
|
||||
if ($prevRecord){
|
||||
$prevRecordResult = @mysql_fetch_assoc(mysql_query("SELECT * FROM ".$TABLE_PREFIX.$tableName." WHERE num=".intval(@$prevRecord)." LIMIT 1"));
|
||||
|
||||
if (!@$prevRecordResult) self::error(new ApiError('No record found!'));
|
||||
|
||||
$arrayData["prevRecord"] = $prevRecordResult;
|
||||
$recordNum = intval($prevRecord);
|
||||
}
|
||||
if ($newRecord){
|
||||
$arrayData["newRecord"] = $newRecord;
|
||||
}
|
||||
|
||||
generateNotificationPlugin_registro_actividad(self::$user["num"],$tableName,$recordNum,$method,$arrayData);
|
||||
}
|
||||
// FIN REGISTRO DE ACTIVIDAD
|
||||
}
|
||||
|
||||
static function error($error) {
|
||||
|
||||
self::log($error->getMessage(), $error->getCode());
|
||||
$result = [
|
||||
'error' => $error->getMessage(),
|
||||
'code' => $error->getCode()
|
||||
];
|
||||
// if (self::$user["isSuperAdmin"]) {
|
||||
// $result["request"] = self::$request;
|
||||
// $result["trace"] = $error->getTraceAsString();
|
||||
// }
|
||||
if (!self::$die) return $result;
|
||||
echo json_encode($result);
|
||||
die();
|
||||
}
|
||||
|
||||
static function addResponseData($data = null){
|
||||
if (!@$data) return false;
|
||||
foreach($data as $key => $value){
|
||||
API::$responseData[$key] = $value;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static function addWarning($string){
|
||||
self::$warnings[] = $string;
|
||||
}
|
||||
static function log($log = null,$code = 200){
|
||||
return false;
|
||||
// mysql_query("INSERT INTO logs SET
|
||||
// createdDate='".date("Y-m-d H:i:s")."',
|
||||
// user=".API::$user['num'].",
|
||||
// website='1',
|
||||
// method='".mysql_real_escape_string($_SERVER["REQUEST_METHOD"])."',
|
||||
// endpoint='".mysql_real_escape_string($_SERVER["REQUEST_URI"])."',
|
||||
// code='".mysql_real_escape_string($code)."',
|
||||
// request='".mysql_real_escape_string(json_encode($_REQUEST))."',
|
||||
// response='".mysql_real_escape_string($log)."'");
|
||||
}
|
||||
|
||||
static function success($data) {
|
||||
$response = [
|
||||
'success' => true,
|
||||
];
|
||||
if (!empty(self::$warnings)){
|
||||
$response["warnings"] = self::$warnings;
|
||||
}
|
||||
if (isset($data[0]) && isset($data[0]["totalRecords"])){
|
||||
$response["meta"] = $data[0];
|
||||
$response["data"] = $data[1];
|
||||
}else{
|
||||
$response["data"] = $data;
|
||||
}
|
||||
|
||||
if (self::$renewToken) {
|
||||
$response['renewToken'] = self::$renewToken;
|
||||
}
|
||||
|
||||
self::log(json_encode($response));
|
||||
|
||||
if (!self::$die) return $response;
|
||||
|
||||
echo json_encode($response);
|
||||
die();
|
||||
}
|
||||
|
||||
static function setToken($token) {
|
||||
if (isset($token['renewToken'])) {
|
||||
self::$renewToken = $token['renewToken'];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
2
cms/lib/plugins/cms_api/v3/classes/ApiError.class.php
Normal file
2
cms/lib/plugins/cms_api/v3/classes/ApiError.class.php
Normal file
@@ -0,0 +1,2 @@
|
||||
<?
|
||||
class ApiError extends Exception {}
|
||||
293
cms/lib/plugins/cms_api/v3/classes/ApiJsonBuilder.php
Normal file
293
cms/lib/plugins/cms_api/v3/classes/ApiJsonBuilder.php
Normal file
@@ -0,0 +1,293 @@
|
||||
<?php
|
||||
class ApiJsonBuilder {
|
||||
static $jsonConfig = [];
|
||||
static $ignoreTables = ["accounts"];
|
||||
static $ignoreSchemaTypes = ["separator", "upload"];
|
||||
|
||||
static function generateBaseConfig($options = []){
|
||||
|
||||
// $options = [
|
||||
// "apartados" => [
|
||||
// "GET" => false,
|
||||
// "GETALL" => true,
|
||||
// "SEARCH" => false,
|
||||
// "POST" => false,
|
||||
// "PATCH" => false,
|
||||
// "DELETE" => false,
|
||||
// "HIDDEN_FIELDS" => "num,breadcrumb",
|
||||
// "NOT_EDITABLE" => "name"
|
||||
// ]
|
||||
// ];
|
||||
$schemaFiles = array_slice(scandir(__DIR__.'/../../../../../data/schema/'), 2);
|
||||
|
||||
self::$jsonConfig = [
|
||||
"host" => "https://".$_SERVER["HTTP_HOST"],
|
||||
"basePath" => "/cms/lib/plugins/cms_api/v3/",
|
||||
"title" => "CMS API de Coco Solution",
|
||||
"info" => [],
|
||||
"variables" => [
|
||||
"baseHeaders" => self::getBaseHeaders()
|
||||
]
|
||||
];
|
||||
|
||||
$endPoints = [];
|
||||
self::generateBaseCustom($endPoints);
|
||||
foreach($schemaFiles as $schemaFile){
|
||||
$tableName = str_replace(".ini.php","",$schemaFile);
|
||||
if(in_array($tableName, self::$ignoreTables)) continue;
|
||||
$schema = loadSchema($tableName);
|
||||
$endPoints[$tableName] = [
|
||||
"title" => @$schema["menuName"]?:"",
|
||||
"description" => @$schema["menuDesc"]?:"",
|
||||
"hiddenFields" => self::explodeFields(@$options[$tableName]['HIDDEN_FIELDS']),
|
||||
"notEditableFields" => self::explodeFields(@$options[$tableName]['NOT_EDITABLE']),
|
||||
"methods" => [
|
||||
"GET" => self::generateBaseMethod($tableName,$schema),
|
||||
"POST" => self::generateBaseMethod($tableName,$schema,["body"], true)
|
||||
],
|
||||
"search" => [
|
||||
"methods" => [
|
||||
"POST" => self::generateBaseSearch($tableName,$schema,["body"])
|
||||
]
|
||||
],
|
||||
":" => [
|
||||
"variable" => "num",
|
||||
"methods" => [
|
||||
"GET" => self::generateBaseMethod($tableName,$schema),
|
||||
"PATCH" => self::generateBaseMethod($tableName,$schema,["body"]),
|
||||
"DELETE" => self::generateBaseMethod($tableName,$schema)
|
||||
]
|
||||
]
|
||||
];
|
||||
if(isset($options[$tableName]) && !$options[$tableName]["GETALL"]) unset($endPoints[$tableName]["methods"]["GET"]);
|
||||
if(isset($options[$tableName]) && !$options[$tableName]["POST"]) unset($endPoints[$tableName]["methods"]["POST"]);
|
||||
if(isset($options[$tableName]) && !$options[$tableName]["GET"]) unset($endPoints[$tableName][":"]["methods"]["GET"]);
|
||||
if(isset($options[$tableName]) && !$options[$tableName]["PATCH"]) unset($endPoints[$tableName][":"]["methods"]["PATCH"]);
|
||||
if(isset($options[$tableName]) && !$options[$tableName]["DELETE"]) unset($endPoints[$tableName][":"]["methods"]["DELETE"]);
|
||||
if(!count($endPoints[$tableName][":"]["methods"])) unset($endPoints[$tableName][":"]);
|
||||
if(isset($options[$tableName]) && !$options[$tableName]["SEARCH"]) unset($endPoints[$tableName]["search"]);
|
||||
}
|
||||
|
||||
|
||||
self::$jsonConfig["endPoints"] = $endPoints;
|
||||
file_put_contents("schemaBase.json", json_encode(self::$jsonConfig));
|
||||
return self::$jsonConfig;
|
||||
}
|
||||
|
||||
private static function explodeFields($fields) {
|
||||
if (!$fields) return [];
|
||||
return array_map('trim', array_values(array_filter(explode(',', $fields))));
|
||||
}
|
||||
|
||||
private static function generateBaseMethod($tableName, $schema, $types = [], $checkRequireds = false){
|
||||
$result = ["headers" => self::getBaseHeaders()];
|
||||
if(in_array("body", $types)) {
|
||||
$fields_from_table = [
|
||||
"options" => [
|
||||
"forceNum" => false,
|
||||
"ignoreSchema" => false,
|
||||
"return_last_id" => false,
|
||||
"dieBeforeQuery" => false,
|
||||
"generate_category_metadata" => false,
|
||||
"prefix" => '$TABLE_PREFIX'
|
||||
]
|
||||
];
|
||||
foreach ($schema as $schemaFieldName => $schemaField) {
|
||||
if(is_array($schemaField)) {
|
||||
if(
|
||||
(isset($schemaField["type"]) && in_array($schemaField["type"], self::$ignoreSchemaTypes))
|
||||
|| isset($schemaField['adminOnly'])
|
||||
|| isset($schemaField['isSystemField'])
|
||||
) { continue; }
|
||||
$field_value = ["value" => "", "required" => false];
|
||||
if(isset($schemaField["type"])) {
|
||||
$field_value["schema"] = $schemaField;
|
||||
switch ($schemaField["type"]) {
|
||||
case 'checkbox':
|
||||
$field_value["default"] = intval($schemaField['checkedByDefault']);
|
||||
break;
|
||||
default:
|
||||
# code...
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(isset($schemaField["defaultValue"]) && !empty($schemaField["defaultValue"])) $field_value["default"] = $schemaField["defaultValue"];
|
||||
if($checkRequireds && isset($schemaField["isRequired"]) && $schemaField["isRequired"]) $field_value["required"] = true;
|
||||
if(isset($schemaField["customColumnType"]) && $schemaField["customColumnType"]) $field_value["field_type"] = $schemaField["customColumnType"];
|
||||
$fields_from_table[$schemaFieldName] = $field_value;
|
||||
}
|
||||
}
|
||||
$result["body"] = ["data" => $fields_from_table];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
private static function generateBaseSearch($tableName, $schema, $types = [], $checkRequireds = false){
|
||||
$result = [
|
||||
"headers" => self::getBaseHeaders(),
|
||||
"body" => [
|
||||
$tableName => [
|
||||
"where" => [
|
||||
//"value" => [
|
||||
// ["column" => "num", "value" => 1, "operator" => "="]
|
||||
//],
|
||||
"required" => false,
|
||||
"docs" => [
|
||||
"Valores posibles de operator: (=, like, !=)"
|
||||
]
|
||||
],
|
||||
"order" => [
|
||||
"value" => "num DESC",
|
||||
"required" => false
|
||||
],
|
||||
"limit" => [
|
||||
//"value" => 25,
|
||||
"required" => false,
|
||||
"docs" => [
|
||||
"Valores posibles: String (Solo limit): 10",
|
||||
"Valores posibles: String (Limit con offset): 0,10",
|
||||
"Valores posibles: Array: ['limit' => 10, 'page' => 1]"
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function generateBaseCustom(&$endPoints) {
|
||||
$endPoints["auth"] = [
|
||||
"title" => "Login",
|
||||
"description" => "Petición de Login. Sólo debe de ser ejecutado la primera vez para obtener el token. Una vez recogido el token se insertará en las cabeceras Authorization:Bearer {{token}}",
|
||||
"methods" => [
|
||||
"POST" => [
|
||||
"headers" => [
|
||||
"Content-length" => [
|
||||
"value" => "0",
|
||||
"description" => "",
|
||||
"required" => true
|
||||
],
|
||||
"Content-type" => [
|
||||
"value" => "application/json",
|
||||
"required" => true
|
||||
],
|
||||
"Authorization" => [
|
||||
"value" => "Login {{BASE64ENCODE(user:pass)}}",
|
||||
"required" => true
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
$endPoints["bulk"] = [
|
||||
"title" => "Registros en masa",
|
||||
"description" => "Se realizan acciones a varios registros de varias tablas",
|
||||
"controller" => "Bulk",
|
||||
"methods" => [
|
||||
"POST" => [
|
||||
"headers" => self::getBaseHeaders(),
|
||||
"body" => [
|
||||
"{tableName}" => [
|
||||
"where" => [
|
||||
"value" => [
|
||||
["column" => "num", "value" => 1, "operator" => "="]
|
||||
],
|
||||
"required" => false,
|
||||
"docs" => [
|
||||
"Valores posibles de operator: (=, like, !=)"
|
||||
]
|
||||
],
|
||||
"order" => [
|
||||
"value" => "num DESC",
|
||||
"required" => false
|
||||
],
|
||||
"limit" => [
|
||||
"value" => 10,
|
||||
"required" => false
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
$endPoints["bulk_sync"] = [
|
||||
"title" => "Sincronización de registros en masa",
|
||||
"description" => "Se realizan acciones de inserción o actualización a varios registros de varias tablas utilizando la clave primaria num como referencia",
|
||||
"controller" => "Bulk",
|
||||
"methods" => [
|
||||
"POST" => [
|
||||
"headers" => self::getBaseHeaders(),
|
||||
"body" => [
|
||||
"{tableName}" => [
|
||||
"records" => []
|
||||
],
|
||||
"{example}" => [
|
||||
"{tableName}" => [
|
||||
"records" => [
|
||||
[
|
||||
"num" => '{num1}',
|
||||
"{field}" => '{value}',
|
||||
"options"=> [
|
||||
"forceNum"=> true
|
||||
]
|
||||
],
|
||||
[
|
||||
"num" => '{num2}',
|
||||
"{field}" => '{value}',
|
||||
],
|
||||
[
|
||||
"{field}" => '{value}',
|
||||
]
|
||||
],
|
||||
"options" => [
|
||||
"generate_category_metadata" => true
|
||||
],
|
||||
"#comentario" => "En este ejemplo el primer es un num forzado, <br> el segundo un update y el tercero una insercion"
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
$endPoints["upload"] = [
|
||||
"title" => "Upload",
|
||||
"description" => "Subida de ficheros al servidor",
|
||||
"controller" => "Files",
|
||||
"methods" => [
|
||||
"POST" => [
|
||||
"headers" => [
|
||||
"Content-type" => [
|
||||
"value" => "multipart/form-data",
|
||||
"required" => true
|
||||
],
|
||||
"Authorization" => [
|
||||
"value" => "Bearer {{TOKEN}}",
|
||||
"required" => true
|
||||
]
|
||||
],
|
||||
"body" => [
|
||||
"field" => ["required" => true,"value" => "file","default" => "file"],
|
||||
"file" => ["required" => false,"value" => "file (blob). O este campo o file_b64 son obligatorios"],
|
||||
"file_b64" => ["required" => false,"value" => "file (base64)"],
|
||||
"filename" => ["required" => false,"value" => "filename, requerido si se envía file_b64"],
|
||||
"options" => ["required" => false,"value" => "array de opciones ( Info : https://github.com/verot/class.upload.php )"]
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
private static function getBaseHeaders() {
|
||||
return [
|
||||
"Content-type" => [
|
||||
"value" => "application/json",
|
||||
"required" => true
|
||||
],
|
||||
"Authorization" => [
|
||||
"value" => "Bearer {{TOKEN}}",
|
||||
"required" => true
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
||||
234
cms/lib/plugins/cms_api/v3/classes/Auth.class.php
Normal file
234
cms/lib/plugins/cms_api/v3/classes/Auth.class.php
Normal file
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
require_once realpath(__DIR__."/../lib/php-jwt/vendor/autoload.php");
|
||||
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
class Auth {
|
||||
public $privateKey = 'wscO4QaF'; // Key de codificación
|
||||
public $expire = 3600; // 3600 Expire time in seconds
|
||||
public $renewTime = 1200; // 1200 Renew time before expired in seconds
|
||||
public $now;
|
||||
/**
|
||||
* @param privateKey: Private Key
|
||||
*/
|
||||
public function __construct($privateKey = null) {
|
||||
if ($privateKey) $this->privateKey = $privateKey;
|
||||
$this->now = time();
|
||||
}
|
||||
|
||||
static function AuthenticateUserLocal($loginAccess){
|
||||
global $TABLE_PREFIX;
|
||||
$user = $loginAccess[0];
|
||||
$pass = $loginAccess[1];
|
||||
|
||||
$userBD = mysql_query_fetch_all_assoc("SELECT *,(neverExpires = '0' AND expiresDate < NOW()) as isExpired FROM ".$TABLE_PREFIX."accounts WHERE `username`='".$user."' and `password`= '".md5($pass)."' LIMIT 1");
|
||||
$userBD = @$userBD[0];
|
||||
return $userBD;
|
||||
}
|
||||
|
||||
static function AuthenticateUser($loginAccess){
|
||||
global $TABLE_PREFIX;
|
||||
if (count($loginAccess)<2) API::error(new ApiError("Las credenciales son incorrectas"));
|
||||
$user = $loginAccess[0];
|
||||
$pass = $loginAccess[1];
|
||||
$curl = curl_init();
|
||||
|
||||
curl_setopt_array($curl, array(
|
||||
CURLOPT_URL => "https://ws.cocosolution.com/api/auth/",
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_ENCODING => "",
|
||||
CURLOPT_MAXREDIRS => 10,
|
||||
CURLOPT_TIMEOUT => 30,
|
||||
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
|
||||
CURLOPT_CUSTOMREQUEST => "POST",
|
||||
CURLOPT_POSTFIELDS => "",
|
||||
CURLOPT_HTTPHEADER => array(
|
||||
"Accept: */*",
|
||||
"Accept-Encoding: gzip, deflate",
|
||||
"Authorization: SimpleAuth ".base64_encode($user.":".$pass),
|
||||
"Cache-Control: no-cache",
|
||||
"Connection: keep-alive",
|
||||
"Content-length: 0",
|
||||
"Content-type: application/json",
|
||||
"Referer: ".$_SERVER["HTTP_HOST"]
|
||||
),
|
||||
));
|
||||
|
||||
$response = curl_exec($curl);
|
||||
$err = curl_error($curl);
|
||||
|
||||
curl_close($curl);
|
||||
|
||||
if ($err) {
|
||||
API::error(new Exception("Login failed"));
|
||||
} else if (@json_decode($response,true)["error"]){
|
||||
API::error(new Exception("Login failed"));
|
||||
}else{
|
||||
$schema = loadINI(__DIR__."/../../custom-schema.ini.php");
|
||||
if (!@$schema["enabled"]) API::error(new Exception("Login failed"));
|
||||
|
||||
try{
|
||||
$resultData = json_decode($response,true);
|
||||
self::validateUserHash($resultData["data"]["userNum"]);
|
||||
return ["num" => $resultData["data"]["userNum"]];
|
||||
}catch(Exception $e){
|
||||
API::error(new ApiError('Login Failed '.$e->getMessage(),403));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static function validateUserHash($num){
|
||||
$schema = loadINI(__DIR__."/../../custom-schema.ini.php");
|
||||
if (!@$schema["enabled"]) API::error(new Exception("Login failed"));
|
||||
if(@$schema['config']["hash"]) {
|
||||
$allowed_users = explode(',', $schema['config']['hash']);
|
||||
if (!in_array(sha1($num), $allowed_users)) API::error(new Exception("Login failed"));
|
||||
} else {
|
||||
API::error(new Exception("Login failed"));
|
||||
}
|
||||
// if (@$schema["config"]["hash"] != sha1($num)) API::error(new Exception("Login failed"));
|
||||
}
|
||||
|
||||
static function updateTokenUserData(){
|
||||
$api = new API();
|
||||
$auth = new self();
|
||||
$token = array(
|
||||
'iat' => $auth->now, // Tiempo que inició el token
|
||||
'exp' => $auth->now+($auth->expire), // Tiempo que expirará el token
|
||||
'data' => API::$user
|
||||
);
|
||||
$jwt = JWT::encode($token, $auth->privateKey);
|
||||
|
||||
API::setToken(["renewToken" => $jwt]);
|
||||
}
|
||||
static function validateMasterKey($requestToken){
|
||||
$schema = loadINI(__DIR__."/../../custom-schema.ini.php");
|
||||
if (!@$schema["enabled"]) API::error(new Exception("Login failed"));
|
||||
if (@$schema["config"]["masterKey"] != $requestToken) return false;
|
||||
return true;
|
||||
}
|
||||
static function authorizeApi($auth = false) {
|
||||
|
||||
$api = new API();
|
||||
$auth = new self();
|
||||
$requestToken = self::getBearerToken();
|
||||
$loginAccess = self::getLoginAccess();
|
||||
|
||||
$tokenData = [];
|
||||
|
||||
if (!$requestToken && !$loginAccess) API::error(new ApiError('No token was sent',403));
|
||||
|
||||
if ($requestToken) {
|
||||
if (self::validateMasterKey($requestToken)) return ["user" => true];
|
||||
try{
|
||||
$data = (object)JWT::decode($requestToken, $auth->privateKey, array('HS256'));
|
||||
$data->data = (array) $data->data;
|
||||
|
||||
API::$user = json_decode(json_encode($data->data), true);
|
||||
|
||||
self::validateUserHash(API::$user["num"]);
|
||||
|
||||
$difference = $data->exp-$auth->now;
|
||||
if ($difference<0){
|
||||
API::error(new ApiError('Token expired',403));
|
||||
}else if($difference >= 0 && $difference < $auth->renewTime){
|
||||
$token = array(
|
||||
'iat' => $auth->now, // Tiempo que inició el token
|
||||
'exp' => $auth->now+($auth->expire), // Tiempo que expirará el token
|
||||
'data' => $data->data
|
||||
);
|
||||
$jwt = JWT::encode($token, $auth->privateKey);
|
||||
// AQUI FALTA CONVALIDAR LOS DATOS DEL USUARIO DEL TOKEN CON LA BBDD PARA
|
||||
// ECHARLO FUERA SI LOS ACCESOS O ALGUN OTRO DATO HA CAMBIADO
|
||||
$tokenData = ["renewToken" => $jwt,"user" => $data->data,"difference" => ($data->exp-$auth->now)];
|
||||
if ($auth) $tokenData["token"] = $jwt;
|
||||
API::addResponseData($tokenData);
|
||||
|
||||
return $tokenData;
|
||||
}else{
|
||||
$tokenData = ["user" => $data->data,"difference" => ($data->exp-$auth->now)];
|
||||
if ($auth) $tokenData["token"] = $requestToken;
|
||||
API::addResponseData($tokenData);
|
||||
return $tokenData;
|
||||
}
|
||||
|
||||
|
||||
}catch (Exception $e) {
|
||||
API::error(new ApiError('Token expired',403));
|
||||
}
|
||||
|
||||
}else if ($loginAccess){
|
||||
|
||||
try{
|
||||
$authenticated = self::AuthenticateUser($loginAccess);
|
||||
|
||||
if ($authenticated){
|
||||
|
||||
$token = array(
|
||||
'iat' => $auth->now, // Tiempo que inició el token
|
||||
'exp' => $auth->now+($auth->expire), // Tiempo que expirará el token
|
||||
'data' => $authenticated
|
||||
);
|
||||
|
||||
$jwt = JWT::encode($token, $auth->privateKey);
|
||||
|
||||
$tokenData = ["token" => $jwt,"expire" => $auth->now+($auth->expire),"user" => ["num" => $authenticated["num"]],"login" => true];
|
||||
|
||||
API::$user = $authenticated;
|
||||
|
||||
return $tokenData;
|
||||
}else{
|
||||
API::error(new ApiError('Login Failed',403));
|
||||
}
|
||||
}catch (Exception $e) {
|
||||
API::error(new ApiError('Login Failed',403));
|
||||
}
|
||||
}else{
|
||||
API::error(new ApiError('Login Failed',403));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static function getAuthorizationHeader(){
|
||||
$headers = null;
|
||||
if (isset($_SERVER['Authorization'])) {
|
||||
$headers = trim($_SERVER["Authorization"]);
|
||||
}
|
||||
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
|
||||
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
|
||||
} elseif (function_exists('apache_request_headers')) {
|
||||
$requestHeaders = apache_request_headers();
|
||||
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
|
||||
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
|
||||
//print_r($requestHeaders);
|
||||
if (isset($requestHeaders['Authorization'])) {
|
||||
$headers = trim($requestHeaders['Authorization']);
|
||||
}
|
||||
}
|
||||
return $headers;
|
||||
}
|
||||
|
||||
static function getBearerToken() {
|
||||
$headers = self::getAuthorizationHeader();
|
||||
if (!empty($headers)) {
|
||||
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static function getLoginAccess() {
|
||||
$headers = self::getAuthorizationHeader();
|
||||
if (!empty($headers)) {
|
||||
if (preg_match('/Login\s(\S+)/', $headers, $matches)) {
|
||||
|
||||
$result = base64_decode($matches[1]);
|
||||
if (!$result) API::error(new ApiError("Invalid Login"));
|
||||
return explode(":",$result);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
174
cms/lib/plugins/cms_api/v3/classes/CmsCRUD.class.php
Normal file
174
cms/lib/plugins/cms_api/v3/classes/CmsCRUD.class.php
Normal file
@@ -0,0 +1,174 @@
|
||||
<?
|
||||
class CmsCRUD {
|
||||
private static $hiddenFields = [];
|
||||
|
||||
static function setHiddenFields($fields){
|
||||
self::$hiddenFields = $fields;
|
||||
}
|
||||
static function listRecordsBulk($request,$throwError = true){
|
||||
global $TABLE_PREFIX;
|
||||
if (!@$request) throw new ApiError('No tableName specified');
|
||||
$data = [];
|
||||
foreach($request as $key => $value){
|
||||
$data[$key] = self::listRecords(@$value["where"],$key,$throwError,@$value["order"],@$value["limit"]);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
static function listRecords($whereArray = null,$tableName = null,$throwError = true,$order = null,$limit = null, $options = []){
|
||||
global $TABLE_PREFIX;
|
||||
if(!$tableName) throw new ApiError("No tableName specified");
|
||||
$data = CocoDB::get($tableName, $whereArray, $order, $limit, $options);
|
||||
return $data;
|
||||
/*$where = "num!=0";
|
||||
|
||||
if ($whereArray && is_array($whereArray)){
|
||||
//$whereArray = $whereArray["where"];
|
||||
|
||||
if (!@$whereArray[0]) $whereArray = [$whereArray];
|
||||
foreach($whereArray as $value){
|
||||
if(!isset($value["column"]) || !isset($value["operator"]) || !isset($value["value"])) {
|
||||
throw new ApiError('Missing parameters');
|
||||
}
|
||||
if(trim($value["column"]) === '') {
|
||||
throw new ApiError('Field parameter cannot be empty');
|
||||
}
|
||||
$where.=" AND `".mysql_real_escape_string($value["column"])."` ";
|
||||
if(!in_array(strtoupper($value["operator"]), ["<",">","=","<=",">=","<=>","LIKE","!=","<>","IN"])) {
|
||||
throw new ApiError('Operator not supported');
|
||||
}
|
||||
$where.=" ".$value["operator"]." ";
|
||||
if($value["operator"] === "IN" && is_array($value["value"])) {
|
||||
$where.= "(".implode(',',array_map(function($each) { return "'".mysql_real_escape_string($each)."'"; }, $value["value"])).")";
|
||||
} else {
|
||||
$where.= is_string($value["value"]) ? "'".mysql_real_escape_string($value["value"])."'" : mysql_real_escape_string($value["value"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$orderString = $order ? " ORDER BY ".$order : '';
|
||||
$limitString = $limit ? " LIMIT ".$limit : '';
|
||||
|
||||
$listRecords_query = mysql_query("SELECT * FROM ".$TABLE_PREFIX.$tableName." WHERE ".$where.$orderString.$limitString);
|
||||
if(!$listRecords_query) throw new ApiError(mysql_error());
|
||||
$hiddenFields = self::$hiddenFields ? array_flip(self::$hiddenFields) : [];
|
||||
$listRecords = [];
|
||||
|
||||
// Uploads
|
||||
$uploadsResult = self::getUploadsResults();
|
||||
$uploadsResult[$tableName] = isset($uploadsResult[$tableName]) ? $uploadsResult[$tableName] : [];
|
||||
$possible_keys_of_uploads = array_filter(array_keys(@$uploadsResult[$tableName]));
|
||||
|
||||
// Records
|
||||
while($record = mysql_fetch_assoc($listRecords_query)){
|
||||
self::parseGetRecord($record,$tableName,@$schemas[$tableName], $options,@$uploadsResult);
|
||||
$listRecords[] = $record;
|
||||
}
|
||||
|
||||
while ($row = mysql_fetch_assoc($listRecords_query)) {
|
||||
if (@$row["num"]){
|
||||
$resultUploads = @mysql_query_fetch_all_assoc("SELECT * FROM ".$TABLE_PREFIX."uploads WHERE tableName = '".$tableName."' AND recordNum=".intval($row["num"]));
|
||||
foreach($resultUploads as $upload){
|
||||
if (!@$row[$upload["fieldName"]]) $row[$upload["fieldName"]] = [];
|
||||
$row[$upload["fieldName"]][] = $upload;
|
||||
}
|
||||
}
|
||||
$row = array_diff_key($row,$hiddenFields);
|
||||
$row["tableName"] = $tableName;
|
||||
$listRecords[] = $row;
|
||||
}
|
||||
|
||||
$listDetails = [
|
||||
"totalRecords" => count($listRecords),
|
||||
"totalMatches" => count($listRecords),
|
||||
"perPage" => 250,
|
||||
"keyword" => "",
|
||||
"totalPages" => 1,
|
||||
"page" => 1,
|
||||
"prevPage" => 1,
|
||||
"nextPage" => 1
|
||||
];
|
||||
|
||||
// if (!@$listRecords && $throwError){
|
||||
// throw new ApiError('No '.$tableName.' were found');
|
||||
// }
|
||||
|
||||
foreach($listRecords as $cont => $record){
|
||||
$listRecords[$cont]["datos"] = @$listRecords[$cont]["datos"] ? json_decode($listRecords[$cont]["datos"],true) : [];
|
||||
}
|
||||
|
||||
$listRecords = array_map(function($r) {
|
||||
return API::t_recursivo($r, null);
|
||||
}, $listRecords);
|
||||
|
||||
$data=[$listDetails,$listRecords];
|
||||
return $data;*/
|
||||
|
||||
}
|
||||
|
||||
static function removeRecord($id = null,$tableName = null){
|
||||
global $TABLE_PREFIX;
|
||||
if(!$tableName) throw new ApiError("No tableName specified");
|
||||
if (!@$id){
|
||||
throw new ApiError('No '.$tableName.' id was sent');
|
||||
}
|
||||
API::activity($id,$tableName,null,"DELETE");
|
||||
// $record = mysql_query_fetch_all_assoc("SELECT * FROM ".$TABLE_PREFIX."usuarios WHERE num = ".intval($id));
|
||||
$record = mysql_query("SELECT * FROM ".$TABLE_PREFIX.$tableName." WHERE num = ".intval($id));
|
||||
if(!$record) throw new ApiError(mysql_error());
|
||||
$record = mysql_fetch_assoc($record);
|
||||
|
||||
if (!@$record){
|
||||
throw new ApiError('No '.$tableName.' was found');
|
||||
}else{
|
||||
mysql_query("DELETE FROM ".$TABLE_PREFIX.$tableName." WHERE num=".intval($record["num"])." LIMIT 1");
|
||||
}
|
||||
|
||||
return ["success" => true];
|
||||
}
|
||||
|
||||
static function getRecord($id = null,$tableName = null){
|
||||
global $TABLE_PREFIX;
|
||||
if(!$tableName) throw new ApiError("No tableName specified");
|
||||
if (!@$id){
|
||||
throw new ApiError('No '.$tableName.' id was sent');
|
||||
}
|
||||
|
||||
// $record = mysql_query_fetch_all_assoc("SELECT * FROM ".$TABLE_PREFIX."usuarios WHERE num = ".intval($id)." LIMIT 1");
|
||||
$record = mysql_query("SELECT * FROM ".$TABLE_PREFIX.$tableName." WHERE num = ".intval($id));
|
||||
if(!$record) throw new ApiError(mysql_error());
|
||||
$record = mysql_fetch_assoc($record);
|
||||
|
||||
if (!@$record){
|
||||
throw new ApiError('No '.$tableName.' was found');
|
||||
}
|
||||
if (@$record["num"]){
|
||||
|
||||
$resultUploads = @mysql_query_fetch_all_assoc("SELECT * FROM ".$TABLE_PREFIX."uploads WHERE tableName = '".$tableName."' AND recordNum=".intval($record["num"]));
|
||||
foreach($resultUploads as $upload){
|
||||
if (!@$record[$upload["fieldName"]]) $record[$upload["fieldName"]] = [];
|
||||
$record[$upload["fieldName"]][] = $upload;
|
||||
}
|
||||
}
|
||||
|
||||
return [$record];
|
||||
}
|
||||
static function tVar($identificador = null,$valor = null){
|
||||
if(!$identificador) throw new ApiError("No key specified");
|
||||
if(!$valor) throw new ApiError("No value specified");
|
||||
|
||||
global $TABLE_PREFIX;
|
||||
$identifier = $identificador;
|
||||
if (defined($identifier)) return $valor;
|
||||
|
||||
$recordtr = mysql_query_fetch_all_assoc("SELECT * FROM {$TABLE_PREFIX}textos_generales WHERE identificador='".$identifier."' LIMIT 1");
|
||||
|
||||
if (@$recordtr){
|
||||
return ["text" => $recordtr[0]["texto"]];
|
||||
}else{
|
||||
CocoDB::insertRecords('textos_generales', ['identificador' => $identifier, 'texto' => $valor]);
|
||||
return ["text" => $valor];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
59
cms/lib/plugins/cms_api/v3/classes/CmsCRUD__Bulk.class.php
Normal file
59
cms/lib/plugins/cms_api/v3/classes/CmsCRUD__Bulk.class.php
Normal file
@@ -0,0 +1,59 @@
|
||||
<?
|
||||
class Bulk extends CmsCRUD {
|
||||
static $defaultMethod = "get";
|
||||
static function get($request){
|
||||
return self::listRecordsBulk($request);
|
||||
}
|
||||
static function bulk_sync($request){
|
||||
global $TABLE_PREFIX;
|
||||
$result = [];
|
||||
foreach($request as $tableName => $values){
|
||||
if (!@$values["records"]) continue;
|
||||
|
||||
$records = $values["records"];
|
||||
|
||||
if (!isset($records[0])) {
|
||||
$records = [$records];
|
||||
}
|
||||
|
||||
list($ignoreFields, $ignoreSchema, $prefix) = CocoDB::parse_options(@$values["options"]);
|
||||
|
||||
if (!$ignoreSchema) {
|
||||
$schema = @loadSchema($tableName);
|
||||
if (!@$schema) die('Error. Tabla no encontrada');
|
||||
}
|
||||
|
||||
$result[$tableName] = [];
|
||||
|
||||
$key = @$values["key"] ?: "num";
|
||||
foreach ($records as $record):
|
||||
$isUpdate = isset($record[$key]) && CocoDB::get($tableName,$key."=".intval($record[$key]),null,1,["ignoreSchema" => true]);
|
||||
|
||||
|
||||
|
||||
if ($isUpdate){
|
||||
|
||||
CocoDB::updateRecords($tableName,$record,$key."=".intval($record[$key]), [], @$record["options"] ?: @$values["options"]);
|
||||
}else{
|
||||
CocoDB::insertRecords($tableName,$record,[],@$record["options"] ?: @$values["options"]);
|
||||
}
|
||||
$preValue = $isUpdate ? $record[$key] : null;
|
||||
/*
|
||||
$record = CocoDB::unsetKeys($record, $ignoreFields,);
|
||||
|
||||
$where = $isUpdate ? "`".$key."`='".$preValue."'" : "";
|
||||
$sqlBase = CocoDB::prepareBaseSQL($prefix, $tableName, @$schema, $isUpdate,[], $record);
|
||||
$contResult = 0;
|
||||
CocoDB::insertOrUpdate($record, $sqlBase, $contResult, $where, $prefix.$tableName, [], $ignoreSchema, @$schema, @$record["options"] ?: @$values["options"]);*/
|
||||
$result[$tableName][] = $isUpdate ? [$key => $preValue,"success" => mysql_affected_rows() ? true : false]: ["num" => mysql_insert_id(),"success" => mysql_affected_rows() ? true : false];
|
||||
endforeach;
|
||||
|
||||
if (@$values['options']['generate_category_metadata']) {
|
||||
CocoDB::updateCategoryMetadata($tableName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
7
cms/lib/plugins/cms_api/v3/classes/Config.class.php
Normal file
7
cms/lib/plugins/cms_api/v3/classes/Config.class.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
class Config {
|
||||
static function get() {
|
||||
$db = Db::getInstance();
|
||||
return $db->executeS('SELECT * FROM configuracion')[0];
|
||||
}
|
||||
}
|
||||
29
cms/lib/plugins/cms_api/v3/classes/Domain.class.php
Normal file
29
cms/lib/plugins/cms_api/v3/classes/Domain.class.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?
|
||||
class Domain {
|
||||
static function parse($domain) {
|
||||
$domain = self::trim($domain);
|
||||
$domain = preg_replace('/([\w-_]+)\.([\w-_]+)\.([\w-_]+)/', '$2.$3', $domain);
|
||||
return strtolower(explode('/', $domain)[0]);
|
||||
}
|
||||
|
||||
static function subdomain($domain) {
|
||||
$domain = self::trim($domain);
|
||||
$subdomain = preg_replace('/([\w-_]+)\.([\w-_]+)\.([\w-_]+)/', '$1', $domain);
|
||||
if ($subdomain === $domain) {
|
||||
$subfolder = array_filter(explode('/', $domain));
|
||||
if (count($subfolder) === 2) {
|
||||
return self::parse($subfolder[1]);
|
||||
}
|
||||
return 'www';
|
||||
}
|
||||
return self::parse($subdomain);
|
||||
}
|
||||
|
||||
static function trim($domain) {
|
||||
$domain = str_replace("http://", "", $domain);
|
||||
$domain = str_replace("https://", "", $domain);
|
||||
$domain = str_replace("www.", "", $domain);
|
||||
$domain = trim(trim($domain), '/');
|
||||
return $domain;
|
||||
}
|
||||
}
|
||||
138
cms/lib/plugins/cms_api/v3/classes/Files.class.php
Normal file
138
cms/lib/plugins/cms_api/v3/classes/Files.class.php
Normal file
@@ -0,0 +1,138 @@
|
||||
<?
|
||||
require_once __DIR__."/../lib/upload/class.upload.php";
|
||||
|
||||
class Files {
|
||||
static $uploadsDir = "/uploads";
|
||||
static $baseUrl = "/cms/uploads";
|
||||
static $allowed = [
|
||||
'application/pdf' => 'pdf',
|
||||
'image/bmp' => 'bmp',
|
||||
'image/gif' => 'gif',
|
||||
'image/jpeg' => ['jpg', 'jpeg'],
|
||||
'image/png' => ['png','ico'],
|
||||
'image/svg+xml' => 'svg',
|
||||
'image/svg' => 'svg',
|
||||
'image/tiff' => 'tiff',
|
||||
'video/x-m4v' => 'm4v',
|
||||
'video/x-ms-wmv' => 'wmv',
|
||||
'video/mpeg' => 'mpeg',
|
||||
'video/mp4' => 'mp4',
|
||||
'video/webm' => 'webm',
|
||||
'video/ogg' => 'ogg',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
|
||||
'application/msword' => 'doc',
|
||||
'application/vnd.ms-excel' => 'xls',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
|
||||
'application/vnd.ms-powerpoint' => 'ppt',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx'
|
||||
];
|
||||
|
||||
static function upload($request){
|
||||
|
||||
$result = [];
|
||||
|
||||
if (isset($_POST["file_b64"])){
|
||||
|
||||
if (!isset($_POST["filename"])) {
|
||||
Api::addWarning("Es necesario añadir el campo filename");
|
||||
}else{
|
||||
$filename = $_POST["filename"];
|
||||
if (!strpos($filename,".")) Api::addWarning("Debes añadir una extensión al filename");
|
||||
$extension = strtolower(trim(@explode(".",$filename)[1]));
|
||||
if (!$extension) Api::addWarning("Debes añadir una extensión al filename 2");
|
||||
$filebase = strtolower(trim(@explode(".",$filename)[0]));
|
||||
if (!$filebase) Api::addWarning("Debes añadir una extensión al filename 3");
|
||||
$fileTemp = time();
|
||||
|
||||
$data = base64_decode($_POST["file_b64"]);
|
||||
$f = finfo_open();
|
||||
$mime_type = finfo_buffer($f, $data, FILEINFO_MIME_TYPE);
|
||||
finfo_close($f);
|
||||
|
||||
if (self::$allowed[$mime_type]){
|
||||
if (file_put_contents(realpath(__DIR__."/../../../../../".self::$uploadsDir)."/".$fileTemp.".".$extension,$data)){
|
||||
$result[] = [
|
||||
"urlPath" => self::$baseUrl."/".$fileTemp.".".$extension,
|
||||
"original" => $_POST["filename"]
|
||||
];
|
||||
}else{
|
||||
Api::addWarning("No ha podido guardarse el archivo ".$filename." en ".realpath(__DIR__."/../../../../../".self::$uploadsDir).". ".json_encode(error_get_last()));
|
||||
}
|
||||
|
||||
}else{
|
||||
Api::addWarning("El mime del archivo no está permitido ");
|
||||
|
||||
}
|
||||
}
|
||||
}else{
|
||||
|
||||
if (!isset($request["field"])) $request["field"] = "file";
|
||||
if (!isset($_FILES[$request['field']])) Api::error(new ApiError('No se encuentra el campo del archivo en el envio'));
|
||||
|
||||
if (!is_array($_FILES[$request["field"]]["name"])) {
|
||||
$files = [$_FILES[$request["field"]]];
|
||||
} else {
|
||||
$files = [];
|
||||
foreach ($_FILES[$request["field"]] as $k => $l) {
|
||||
foreach ($l as $i => $v) {
|
||||
if (!array_key_exists($i, $files)) $files[$i] = array();
|
||||
$files[$i][$k] = $v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($files as $file) {
|
||||
try{
|
||||
$result[] = self::uploadFile($request,$file);
|
||||
}catch(Exception $e){
|
||||
Api::addWarning("Ha ocurrido un error al subir el fichero ".$file["name"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
|
||||
|
||||
}
|
||||
static function uploadFile($request,$file){
|
||||
$handle = new \verot\Upload\Upload($file);
|
||||
if ($handle->uploaded) {
|
||||
|
||||
$handle->file_name_body_add = time();
|
||||
$handle->image_resize = true;
|
||||
$handle->image_x = 800;
|
||||
$handle->image_ratio_y = true;
|
||||
|
||||
if (isset($request["options"])){
|
||||
foreach($request["options"] as $key => $value){
|
||||
if (property_exists($handle,$key)){
|
||||
$handle[$key] = $value;
|
||||
}else{
|
||||
Api::addWarning("La propiedad ".$key." no se puede establecer en uploads");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$handle->allowed = [
|
||||
$handle->mime_types['pdf'],
|
||||
$handle->mime_types['doc'],
|
||||
$handle->mime_types['docx'],
|
||||
$handle->mime_types['xls'],
|
||||
$handle->mime_types['xlsx'],
|
||||
$handle->mime_types['csv'],
|
||||
'image/*'
|
||||
];
|
||||
|
||||
$handle->process(realpath(__DIR__."/../../../../../".self::$uploadsDir."/"));
|
||||
|
||||
if ($handle->processed) {
|
||||
$fileName = self::$baseUrl."/".$handle->file_dst_name;
|
||||
$handle->clean();
|
||||
return ["urlPath" => $fileName,"original" => $file["name"]];
|
||||
} else {
|
||||
throw new ApiError($handle->error);
|
||||
}
|
||||
}else{
|
||||
Api::addWarning("No se ha podido subir el archivo ");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user