Initial commit: plantilla base PHP para webs Acai CMS

This commit is contained in:
Jordan
2026-02-21 21:13:57 +00:00
commit 03acc5b013
321 changed files with 62660 additions and 0 deletions

380
cms/lib/classes/CocoDB-copia.php Executable file
View File

@@ -0,0 +1,380 @@
<?php
class CocoDB {
private static $tableCache = [];
private static $uploadColumns = [];
/**
* Inserta registros en una tabla
* @destacar
* @category DB
* @param table: Tabla de inserción
* @param records: Lista de registros a insertar
* @param functions: Array asociativo con funciones a aplicar a cada key
* @param options: Lista de opciones posibles que pasarle al método
* @return Número de registros insertados
*/
static function insertRecords($table, $records, $functions = [], $options = []) {
if (!isset($records[0])) {
$records = [$records];
}
if (@$options["preSaveTempId"]) {
$preSave = true;
}
list($ignoreFields, $ignoreSchema, $prefix) = self::parse_options($options);
if (!$ignoreSchema) {
$schema = @loadSchema($table);
if (!@$schema) die('Error. Tabla no encontrada');
}
$sqlBase = self::prepareBaseSQL($prefix, $table, @$schema);
$result = 0;
$lastSaved = 0;
foreach ($records as $record):
$record = self::unsetKeys($record, $ignoreFields);
self::insertOrUpdate($record, $sqlBase, $result, null, $prefix.$table, $functions, $ignoreSchema, @$schema);
$lastSaved = mysql_insert_id();
foreach(self::$uploadColumns as $keyColumn => $uploadColumn){
foreach($uploadColumn as $keyCol => $urlPath){
self::insertRecords("uploads",[
"urlPath" => $urlPath,
"filePath" => realpath(__DIR__."/../../../".$urlPath),
"fieldName" => $keyColumn,
"recordNum" => $lastSaved,
"tableName" => $table,
"createdTime" => date("Y-m-d H:i:s"),
"order" => time() + $keyCol,
"width" => 640,
"height" => 480
],[],["ignoreSchema" => true]);
}
}
endforeach;
if (@$preSave) {
$query = "UPDATE {$prefix}uploads "
. " SET recordNum = LAST_INSERT_ID(), preSaveTempId = '' "
. " WHERE tableName = '".mysql_real_escape_string($table)."' AND "
. " preSaveTempId = '".mysql_real_escape_string($options["preSaveTempId"])."'";
mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
$query = "UPDATE {$prefix}traducciones "
. " SET recordNum = LAST_INSERT_ID(), preSaveTempId = '' "
. " WHERE tableName = '".mysql_real_escape_string($table)."' AND "
. " preSaveTempId = '".mysql_real_escape_string($options["preSaveTempId"])."'";
mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
}
if (@$options['return_last_id']) {
return $lastSaved;
}
return $result;
}
/**
* Elimina registros de una tabla
* @destacar
* @category DB
* @param table: Tabla de la que vamos a eliminar registros
* @param where: Array asociativo que recoge campo => valor, operador, or
* @return boolean que indica si se pudo ejecutar la consulta
*/
static function deleteRecords($table, $where, $options = []) {
list($_, $_, $prefix) = self::parse_options($options);
$where = self::parse_where($where, $table);
if (!@$where) return false;
$q = mysql_query("DELETE FROM $prefix$table WHERE $where");
if (!$q) return false;
return true;
}
/**
* Actualiza registros en una tabla
* @destacar
* @category DB
* @param table: Tabla de inserción
* @param records: Lista de registros a insertar
* @param functions: Array asociativo con funciones a aplicar a cada key
* @param options: Lista de opciones posibles que pasarle al método
* @return Número de registros insertados
*/
static function updateRecords($table, $records, $where, $functions = [], $options = []) {
if (!isset($records[0])) {
$records = [$records];
}
list($ignoreFields, $ignoreSchema, $prefix) = self::parse_options($options);
if (!$ignoreSchema) {
$schema = @loadSchema($table);
if (!@$schema) die('Error. Tabla no encontrada');
}
$sqlBase = self::prepareBaseSQL($prefix, $table, @$schema, true);
$result = 0;
foreach ($records as $record):
$record = self::unsetKeys($record, $ignoreFields);
// Está comentado, pero no se si hace falta, si se descomenta se rompe el guardar del Builder (Plugin)
// if (@$schema['menuType'] == 'category' && !isset($record['parentNum'])) {
// continue;
// }
self::insertOrUpdate($record, $sqlBase, $result, $where, $prefix.$table, $functions, $ignoreSchema, @$schema);
endforeach;
return $result;
}
/**
* Hace el insert o update de un único registro
* @param record: Registro con el que vamos a operar
* @param sqlBase: SQL Base
* @param result: Número de registros con los que hemos operado. In-out
* @param where: Where de la operación (solo si es un UPDATE)
* @param table: Tabla de la operación
* @param functions: Lista de funciones con las que podemos parsear un determinado valor
* @param ignoreSchema: Boolean que indica si vamos a ignorar el Schema o no
* @param schema: Schema de la tabla
*/
private static function insertOrUpdate($record, $sqlBase, &$result, $where = null, $table = null, $functions = null, $ignoreSchema = false, $schema = null) {
$sql = $sqlBase;
self::$uploadColumns = [];
foreach ($record as $key => $value):
$column_exists = self::column_exists($key, @$schema, $table);
if (!$column_exists) continue;
if (is_array($column_exists) && $column_exists["type"] === "upload"){
if (!is_array($value)) $value = [$value];
if (!isset(self::$uploadColumns[$key])) self::$uploadColumns[$key] = [];
foreach($value as $val){
self::$uploadColumns[$key][] = $val;
}
continue;
}
if (is_array($functions) && isset($functions[$key]) && is_callable($functions[$key])) {
$value = $functions[$key]($value);
}
else if (!$ignoreSchema) {
$value = self::parse_value_schema($value, $schema, $key);
}
if ($value === null) {
continue;
// return false;
}
if (is_array($value)) {
$value = json_encode($value);
}
$sql .= ", `$key`='".mysql_real_escape_string($value)."'";
endforeach;
if (@$where) {
$where = self::parse_where($where, $table);
$sql .= " WHERE ".$where;
}
if (mysql_query($sql)) {
$result++;
}else{
if(class_exists('API') && class_exists('ApiError'))
API::error(new ApiError(json_encode(["error" => mysql_error(),"sql" => $sql])));
else
die(json_encode(["error" => mysql_error(),"sql" => $sql]));
}
}
/**
* Función que prepara el SQL base dependiendo del schema y de si es INSERT o UPDATE
* @param prefix: Prefijo de la tabla
* @param table: Tabla de la operación
* @param schema: Schema de la tabla
* @param update: Boolean que indica si vamos a actualizar o insertar
* @return sql
*/
private static function prepareBaseSQL($prefix, $table, $schema = null, $update = false) {
$operation = $update ? "UPDATE" : "INSERT INTO";
if (@$schema) {
$d = date('Y-m-d H:i:s');
$t = time();
$sqlBase = "$operation $prefix$table SET updatedDate='$d'";
if (!$update) {
$sqlBase .= ", num=NULL, createdDate='$d', createdByUserNum=1, updatedByUserNum=1";
switch ($schema['menuType']) {
case 'category':
$sqlBase .= ", globalOrder=0, siblingOrder=0, lineage='', depth=0, breadcrumb=''";
break;
case 'multi':
$sqlBase .= ", dragSortOrder='$t'";
break;
default:
break;
}
}
}
else {
$sqlBase = "$operation $prefix$table SET num=".($update ? "num" : "NULL");
}
return $sqlBase;
}
/**
* Parsea las opciones de los métodos
* @return lista con las opciones ignoreFields, ignoreSchema y prefix
*/
private static function parse_options($options) {
global $TABLE_PREFIX;
$ignoreFields = ['num'];
if (@$options['ignoreFields']) {
$ignoreFields = array_merge($ignoreFields, $options['ignoreField']);
}
$ignoreSchema = @$options['ignoreSchema'] ?: false;
$prefix = isset($options["prefix"]) ? $options["prefix"] : $TABLE_PREFIX;
return [$ignoreFields, $ignoreSchema, $prefix];
}
/**
* Comprueba si una columna existe en una tabla
* @return boolean que indica si existe o no la columna
*/
private static function column_exists($key, $schema, $table) {
if (isset(self::$tableCache[$table]) && isset(self::$tableCache[$table][$key])) {
return self::$tableCache[$table][$key];
}
if ($schema && isset($schema[$key])) {
return $schema[$key];
}
$result = mysql_query("SHOW COLUMNS FROM `$table` LIKE '$key'");
$exists = mysql_num_rows($result) > 0;
self::cache_column($table, $key, $exists);
return $exists;
}
/**
* Cachea la comprobación de una columna en una tabla
*/
private static function cache_column($table, $column, $exists) {
if (!isset(self::$tableCache[$table])) {
self::$tableCache[$table] = [];
}
if (!isset(self::$tableCache[$table][$column])) {
self::$tableCache[$table][$column] = $exists;
}
}
/**
* Parsea el valor dependiendo del tipo de campo
* @return valor parseado
*/
private static function parse_value_schema($value, $schema, $key) {
switch($schema[$key]['type']) {
case 'list':
switch ($schema[$key]['listType']) {
case 'pulldownMulti':
if (is_array($value)) {
$value = "\t".join("\t", $value)."\t";
}
break;
default:
break;
}
break;
case 'multitext':
if (is_array($value)) {
$value = json_encode($value);
}
break;
case 'checkbox':
$value = @$value ? 1 : 0;
break;
default:
break;
}
return $value;
}
/**
* Parsea el where pasado por parámetro
* - or: Si se envía a true usa OR como enlace en lugar de AND
* - not: Si se envía a true se usa
* - operador: LIKE, IN, != o =
*
* @param where: String o array
* @return where
*/
private static function parse_where($where, $table) {
$builtWhere = "";
if (is_array($where)) {
foreach ($where as $key => $w):
if (is_array($w)) {
if (!isset($w["value"]) || !isset($w["column"])) return false;
$key = $w["column"];
if (!self::column_exists($key, null, $table)) return false;
$value = $w["value"];
$enlace = @$w["or"] ? "OR" : "AND";
$not = @$w["not"] ? "NOT " : "";
switch (strtoupper(@$w["operator"])) {
case "LIKE":
$value = "'".mysql_real_escape_string($value)."'";
$operador = "LIKE";
break;
case "IN":
if (is_array($value)) {
$value = join(", ", array_map(function($a) {
if (is_int($a)) return intval($a);
if (is_numeric($a)) return floatval($a);
return "'".mysql_real_escape_string($a)."'";
}, $value));
}
$value = "(".$value.")";
$operador = "IN";
break;
case "!=":
$value = "'".mysql_real_escape_string($value)."'";
$operador = "!=";
break;
default:
$value = "'".mysql_real_escape_string($value)."'";
$operador = "=";
}
if (@$builtWhere) $builtWhere .= " $enlace ";
$builtWhere .= "`$key` $not$operador $value";
}
else {
if (@$builtWhere) $builtWhere .= " AND ";
$builtWhere .= "`$key`='".mysql_real_escape_string($w)."'";
}
endforeach;
}
else {
$builtWhere = $where;
}
return $builtWhere;
}
/**
* Elimina del primer array las claves pasadas en el segundo parámetro
* @param array: Array del que vamos a eliminar las keys
* @param keys: Array que contiene las keys que queremos eliminar
* @return nuevo array
*/
private static function unsetKeys($array, $keys) {
$c = $array;
foreach ($keys as $removeKey) {
unset($c[$removeKey]);
}
return $c;
}
}

1415
cms/lib/classes/CocoDB.php Executable file

File diff suppressed because it is too large Load Diff

468
cms/lib/classes/CocoEmail.php Executable file
View File

@@ -0,0 +1,468 @@
<?php
if(!defined('COCO_EMAIL_SERVER_HTTP_HOST')) {
define("COCO_EMAIL_SERVER_HTTP_HOST", $_SERVER["HTTP_HOST"]);
}
class CocoEmail {
static $table = 'correos';
static $field_key = 'identificador';
static $field_subject = 'asunto';
static $field_header = 'cabecera';
static $field_content = 'cuerpo';
static $field_footer = 'pie';
static $field_styles = 'estilos';
//Error en clase de phpmailer en la funcion encodeFile() por set_magic_quotes y get_magic_quotes se eliminaron en php 8
//Esto espera un array de filePaths de archivos a adjuntar
static $attach_files = [];
static $encode_with_base64 = false;
static $debug = false;
static $smtp = false;
static $verify = false;
static $show_variables = false;
static $stop_sending_emails = false;
static $webhook_url = "";
static $webhook_function = null;
static $smtp_data = [
"host" => "smtp.gmail.com",
"secure" => "ssl",
"port" => 465,
"username" => "soporte@cocosolution.com",
"password" => "",
"from" => "soporte@cocosolution.com",
"from_name" => "",
];
static $use_dkim = false;
static $dkim = [
'DKIM_domain' => 'cocosolution.com',
'DKIM_selector' => 'default',
'DKIM_private' => __DIR__ . '/default',
'DKIM_identity' => 'soporte@cocosolution.com',
];
static $bloqued_emails = [];
static $mail_data = [
"from" => "",
"from_name" => "",
];
static $replyTo = [
"to" => "",
"to_name" => "",
];
static $send_copy_to = [];
static $send_blind_copy_to = [];
static $template = "
<html>
<head>
<title>{{TITLE}}</title>
<style>{{STYLES}}</style>
</head>
<body>
<div id='contenido'>
{{HEADER}}
{{CONTENIDO}}
{{FOOTER}}
</div>
</body>
</html>
";
static $styles = "
body{font-family:Arial; color:#777; background-color:#F6F8FB;padding:20px;}
#contenido{max-width:640px; margin:0 auto; padding:20px; border: 1px solid #F6F8FB; background-color:#fff; border-radius:25px; -webkit-box-shadow:0px 0px 20px rgba(0,0,0,0.1); box-shadow:0px 0px 20px rgba(0,0,0,0.1);}
#contenido img {max-width: 100%;}
h3{font-weight:normal; color:#111;}
a{color:#CE482F; text-decoration:none;}
table td{border:solid 1px #ddd; padding:5px; width:100%; margin:0px;}
";
static $header = "
<center>
<img alt='' src='https://".COCO_EMAIL_SERVER_HTTP_HOST."/template/estandar/images/logo.png' style='max-width:100%; width:200px;'>
</center>
<br>
";
static $footer = "";
/**
* Envía un correo y parsea su contenido con las variables pasadas por parámetro
*
* @param string $key
* @param array $params
* @param array $to
* @param string $subject
* @param boolean $returnHTML
* @param array options : [
"twig" : Boolean -> Twig Mode,
"base64Decode" : Boolean -> Decode content from base64 to ascii
]
* @return void
*/
static function send($key = null, $params = [], $to = [], $subject = null, $content = null, $returnHTML = false, $options = []) {
global $TABLE_PREFIX;
if ($key) {
$key = mysql_real_escape_string($key);
$record = mysql_fetch_assoc(mysql_query("SELECT * FROM $TABLE_PREFIX".self::$table." WHERE `".self::$field_key."` LIKE '$key'"));
if (!$record) {
throw new Exception('Correo no encontrado');
}
$record["tableName"] = self::$table;
}
else if ($content) {
$record = [
self::$field_subject => $subject,
self::$field_content => $content
];
}
else {
throw new Exception('Tienes que enviar la clave o el contenido');
}
if (!is_array($to)) {
$to = explode(',', $to);
}
$to = array_filter(array_map('trim', $to), function($a) {
return filter_var($a, FILTER_VALIDATE_EMAIL);
});
if (@$options["base64Decode"]) {
$content = base64_decode(t($record,self::$field_content));
}else{
$content = t($record, self::$field_content);
}
$content = self::parse($content, $params,@$options ?: []);
$subject = t($record, self::$field_subject);
$subject = self::parse($subject, $params, $options);
$header = t($record, self::$field_header);
if(@$header) self::$header = self::parse($header, $params);
$footer = t($record, self::$field_footer);
if(@$footer) self::$footer = self::parse($footer, $params);
$styles = t($record, self::$field_styles);
if(@$styles) self::$styles = self::parse($styles, $params);
if ($returnHTML) {
return $content;
}
if (empty($to)) {
throw new Exception('No hay destinatarios válidos');
}
if (!$subject && $record) $subject = t($record, self::$field_subject);
$result = [];
foreach ($to as $destinatario) {
$resultString = self::send_email_coco_proxy($destinatario, $subject, $content);
$result[] = @json_decode($resultString,true) ?: ["success" => false, "message" => "Error decoding response", "raw_response" => $resultString];
}
self::$attach_files = [];
return $result;
}
/*
options : [
"twig" : Boolean -> Twig Mode
]
*/
static function parse($content, $params, $options = []) {
if (@$options["twig"]){
if (!function_exists("compileTWIG") && file_exists(__DIR__."/../plugins/builder_saas")) require_once __DIR__."/../plugins/builder_saas/builder_functions.php";
$tempFolder = sys_get_temp_dir()."/".md5($content);
$content = html_entity_decode($content);
if (!file_exists($tempFolder)) mkdir($tempFolder);
if (!file_exists($tempFolder."/index.twig")){
$php = compileTWIG($content,$tempFolder);
file_put_contents($tempFolder."/index.twig",$php);
}else{
$php = file_get_contents($tempFolder."/index.twig");
}
ob_start();
require($tempFolder."/index.twig");
$acaiResultData->doDisplay($params);
$resultado = ob_get_clean();
return $resultado;
}else{
$params = self::array_change_key_case_recursive($params);
$params_parsed = [];
foreach ($params as $key => $param) {
if (isset($param['tablename'])) {
$params_parsed[strtolower($param['tablename'])] = $param;
}
else {
$key = str_replace(['{', '}'], ['', ''], $key);
$params_parsed[$key] = $param;
}
}
return preg_replace_callback("/{([^}]+)}/", function($matches) use($params_parsed) {
$token = explode(".", strtolower($matches[1]));
// Comprobamos si es un token simple o compuesto
if (count($token) === 1) {
// Token simple. Comprobamos si se refiere a una tabla o un valor fijo
if (isset($params_parsed[$token[0]])) {
if (is_array($params_parsed[$token[0]])) {
// Es un array. Devolvemos su mainField o, en su defecto, el primer campo que encontremos
if (isset($params_parsed[$token[0]]['mainfieldbreadcrumb'])) {
return $params_parsed[$token[0]]['mainfieldbreadcrumb'];
}
reset($params_parsed);
return t($params_parsed, key($params_parsed));
}
else {
// Es un valor fijo
return $params_parsed[$token[0]];
}
}
else {
return self::$show_variables ? '{'.$matches[1].'}' : '-';
}
}
else {
// Es un token compuesto. Lo recorremos hasta que no queden más tokens y devolvemos el resultado
if (!isset($params_parsed[$token[0]]) || !is_array($params_parsed[$token[0]])) return '{'.$matches[1].'}';
$i = 0;
$current = $params_parsed;
do {
$tok = $token[$i];
if (!isset($current[$tok])) return '{'.$matches[1].'}';
$current = $current[$tok];
$i += 1;
} while ($i < count($token));
return $current;
}
}, $content);
}
}
static function array_change_key_case_recursive($arr) {
return array_map(function($item){
if(is_array($item))
$item = self::array_change_key_case_recursive($item);
return $item;
}, array_change_key_case($arr));
}
function encrypt($string, $key) {
$result = '';
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
return base64_encode($result);
}
static function send_email_coco_proxy($destinatario="soporte@cocosolution.com", $asunto="Error al enviar correo", $contenido="", $respuesta="") {
$data = [
"smtp_data" => self::$smtp_data,
"mail_data" => self::$mail_data,
"replyTo" => self::$replyTo,
"send_copy_to" => self::$send_copy_to,
"params" => [
"to" => $destinatario,
"subject" => $asunto,
"body" => $contenido
],
"bloqued_emails" => self::$bloqued_emails,
"encode_with_base64" => self::$encode_with_base64,
"template" => self::$template,
"styles" => self::$styles,
"header" => self::$header,
"footer" => self::$footer
];
//$encryptData = self::encrypt(json_encode($data), "Analiticaempresas17");
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode($data)
)
);
$context = stream_context_create($opts);
$result = file_get_contents("https://cocosolution.com/?sendQuantumEmail=1", false, $context);
return $result;
}
static function send_email($destinatario="soporte@cocosolution.com", $asunto="Error al enviar correo", $contenido="", $respuesta="") {
global $configuracionRecord;
if (in_array($destinatario,self::$bloqued_emails)) die("Testing");
if (!isset($configuracionRecord)){
$configuracionRecord = @CocoDB::get("configuracion","num != 0")[0];
}
require_once __DIR__ . '/../vendor/PHPMailer/PHPMailerAutoload.php';
/*$mensaje = "
<html>
<head>
<title>".$asunto."</title>
<style>
body{font-family:Arial;color:#777;background-color:#F6F8FB}
#contenido{max-width:640px;margin:0 auto;padding:20px;background-color:#fff;border-radius:25px;-webkit-box-shadow:0px 0px 20px rgba(0,0,0,0.1);box-shadow:0px 0px 20px rgba(0,0,0,0.1);}
h3{font-weight:normal;color:#111;}
a{color:#CE482F;text-decoration:none;}
table td{border:solid 1px #ddd;padding:5px;width:100%;margin:0px;}
</style>
</head>
<body>
<div id='contenido'>
<center><img alt='' src='https://".$_SERVER["HTTP_HOST"]."/template/estandar/images/logo.png' style='max-width:100%; width:200px;'></center>
<br>
".$contenido."
</div>
</body>
</html>
";*/
$mensaje = self::$template;
$mensaje = str_replace('{{STYLES}}', self::$styles, $mensaje);
$mensaje = str_replace('{{HEADER}}', self::$header, $mensaje);
$mensaje = str_replace('{{TITLE}}', $asunto, $mensaje);
$mensaje = str_replace('{{CONTENIDO}}', $contenido, $mensaje);
$mensaje = str_replace('{{FOOTER}}', self::$footer, $mensaje);
try {
$mail = new PHPMailer();
// Basic
$mail->CharSet = "UTF-8";
if(self::$encode_with_base64) $mail->Encoding = "base64";
$mail->IsHTML(true);
//Debug
if(self::$debug) {
$mail->SMTPDebug = 4;
echo "<br>";
echo $mensaje;
echo "<br><br>";
var_dump([
'To:' => $destinatario,
'Asunto' => $asunto,
'Contenido' => $mensaje
]);
echo "<br>";
}
// SMTP
if(self::$smtp) {
$mail->Host = self::$smtp_data['host'];
$mail->IsSMTP();
$mail->SMTPAuth = true;
if(self::$smtp_data['secure'])
$mail->SMTPSecure = self::$smtp_data['secure'];
$mail->Helo = @self::$smtp_data['helo'] ?:'webs.cocosolution.com';
$mail->Port = self::$smtp_data['port'];
$mail->Username = self::$smtp_data['username'];
$mail->Password = self::$smtp_data['password'];
$mail->SetFrom(self::$smtp_data['from'], self::$smtp_data['from_name']);
}
// DKIM
if (self::$use_dkim) {
$mail->DKIM_domain = self::$dkim['DKIM_domain'];
$mail->DKIM_private = self::$dkim['DKIM_private'];
$mail->DKIM_selector = self::$dkim['DKIM_selector'];
$mail->DKIM_identity = self::$dkim['DKIM_identity'];
}
// Config
if(!self::$smtp) {
$mail->setFrom(self::$mail_data["from"] ?: $configuracionRecord["correo_admin"], self::$mail_data["from_name"] ?: $configuracionRecord["tienda_nombre_empresa"]);
}
$mail->addReplyTo(self::$replyTo["to"] ?: $configuracionRecord["correo_admin"], self::$replyTo["to_name"] ?: $configuracionRecord["tienda_nombre_empresa"]);
if(self::$verify) {
$mail->AddAddress('check-auth-soporte=cocosolution.com@verifier.port25.com');
} else {
$mail->AddAddress($destinatario);
foreach (self::$send_copy_to as $email) {
$mail->AddCC($email);
}
foreach (self::$send_blind_copy_to as $email) {
$mail->addBCC($email);
}
}
$mail->Subject = $asunto;
$mail->msgHTML($mensaje);
foreach (self::$attach_files as $file) {
$mail->addAttachment($file,basename($file));
}
if(!self::$stop_sending_emails) {
$resultMail = $mail->Send();
try{
if (self::$webhook_url || self::$webhook_function){
$dataMail = [
"from" => $mail->From,
"from_name" => $mail->FromName,
"sender" => $mail->Sender,
"subject" => $mail->Subject,
"to" => $destinatario,
"body" => $mail->Body,
"alt_body" => $mail->AltBody,
"sended" => @$mail->ErrorInfo ? false : true,
"error" => @$mail->ErrorInfo
];
if (!empty(self::$webhook_url) && filter_var(self::$webhook_url, FILTER_VALIDATE_URL)) {
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode($dataMail)
)
);
$context = stream_context_create($opts);
$result = file_get_contents(self::$webhook_url, false, $context);
}
if (is_callable(self::$webhook_function)) {
$resultFunction = call_user_func(self::$webhook_function,$dataMail);
}
}
} catch (Exception $e){
// En caso de error no hacemos nada
}
}
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
}
}

300
cms/lib/classes/CocoEnlace.php Executable file
View File

@@ -0,0 +1,300 @@
<?
class CocoEnlace {
function __construct(){}
static function _seteaCampoEnlace($valores,$sufijoForzado="",$table = null,$generateAlias = true){
global $tableName,$TABLE_PREFIX,$SETTINGS,$CURRENT_USER,$schema;
if (!$table) $table = $tableName;
$enlaceNuevo = "";
$enlaceAnterior = "";
// ESTABLECEMOS CUAL ES EL CAMPO DETERMINANTE
$campo = self::_getTitleField($valores,$table,$schema);
if (@$valores["num"]){
// ALMACENAMOS SI HAY UN REGISTRO ANTERIOR
$registroAnterior = mysql_query("select * from ".$TABLE_PREFIX.$table." where num=".$valores["num"]);
if($registroAnterior) {
$registroAnterior = mysql_fetch_assoc(mysql_query("select * from ".$TABLE_PREFIX.$table." where num=".$valores["num"]));
if (@$registroAnterior) $enlaceAnterior = $registroAnterior["enlace"];
}
}
$prefijo = self::_getLinkPrefix($valores,$table);
$prefijoAnterior = isset($registroAnterior) ? self::_getLinkPrefix($registroAnterior,$table) : null;
$sufijo = "/";
if (!@$valores["enlace"]){
// SI NO HA ESCRITO NADA LO SETEAMOS POR DEFECTO
$estado = "Si no ponemos enlace";
$estadoNum = 0;
$nohay = true;
$valor = (@$campo&&@$valores[$campo]) ? "/".self::parsea_enlace($valores[$campo]) : "/".time();
$enlaceNuevo = $prefijo.$valor.$sufijoForzado.$sufijo;
}else{
// SI EN CAMBIO HA ESCRITO ALGO VAMOS A VER QUE PASA
$nohay = false;
if (@$valores["preSaveTempId"]){
// SI ES UN REGISTRO NUEVO LO DEJAMOS TAL CUAL
$estado = "Si ponemos enlace pero es nuevo registro";
$estadoNum = 1;
$enlaceNuevo = $valores["enlace"];
}else{
// SI ES UN REGISTRO EXISTENTE VAMOS A COMPROBAR SI HA CAMBIADO ALGO
if (@$registroAnterior){
if ($valores["enlace"]!=$registroAnterior["enlace"]){
// SI EL ENLACE ES DISTINTO AL ANTERIOR LO SETEAMOS TAL CUAL
$estado = "Si ponemos enlace, registro existente, enlace distinto";
$estadoNum = 2;
$enlaceNuevo = $valores["enlace"];
}else if ($valores[$campo]!=$registroAnterior[$campo]){
// SI EL ENLACE ES IGUAL AL ANTERIOR COMPROBAMOS EL TITLE ( O CAMPO QUE SEA )
// A VER SI ES DISTINTO
if (strpos($valores["enlace"],self::parsea_enlace($registroAnterior[$campo]))){
// SI EL ANTIGUO TITLE TENIA RELACION CON EL ENLACE LO SISTITUIMOS
// POR EL NUEVO TITLE
$estado = "Si ponemos enlace, registro existente, title distinto con title anterior relacionado con el enlace anterior";
$estadoNum = 3;
$enlaceNuevo = str_replace(self::parsea_enlace($registroAnterior[$campo]),self::parsea_enlace($valores[$campo]),$valores["enlace"]);
$enlaceNuevo = preg_replace("|_([a-zA-z0-9]*)$|","",$enlaceNuevo);
}else{
// SI NO TENIA RELACION LO DEJAMOS TAL CUAL
$estado = "Si ponemos enlace, registro existente, title distinto con title anterior NO relacionado con el enlace anterior";
$estadoNum = 4;
$enlaceNuevo = $valores["enlace"];
}
}else{
$estado = "Si ponemos enlace, registro existente, enlace igual";
$estadoNum = 5;
$enlaceNuevo = $valores["enlace"];
}
if (@$prefijo && @$prefijoAnterior && strpos($enlaceNuevo,$prefijoAnterior) !== false) {
// SI EL ANTIGUO CAMPO BREADCRUMB TENIA RELACION CON EL ENLACE LO SISTITUIMOS
// POR EL NUEVO VALOR DEL CAMPO BREADCRUMB
$estado = "Si ponemos enlace, registro existente, campo breadcrumb distinto con campo breadcrumb anterior relacionado con el enlace anterior";
$estadoNum = 7;
$enlaceNuevo = str_replace($prefijoAnterior,$prefijo,$enlaceNuevo);
$enlaceNuevo = preg_replace("|_([a-zA-z0-9]*)$|","",$enlaceNuevo);
}
}else{
// SI NO ENCUENTRO EL REGISTRO ANTERIOR
$estado = "Si ponemos enlace, registro existente, pero no lo encontramos";
$estadoNum = 6;
$enlaceNuevo = $valores["enlace"];
}
}
}
$idiomasViejo = self::_getEnlaceIdiomas($valores,$enlaceNuevo,$enlaceAnterior,$estadoNum,$table);
$idiomasNuevo = self::_seteaEnlaceIdiomas($valores,$enlaceNuevo,$enlaceAnterior,$estadoNum,$table);
/**************************/
// YA TENEMOS EL CAMPO SETEADO AHORA VAMOS A COMPROBAR SI YA HAY UNO
// AHORA COMPRUEBO SI HAY OTRO IGUAL EN LA BASE DE DATOS
/**************************/
$sql = "
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('enlace')
AND TABLE_SCHEMA='".$SETTINGS["mysql"]["database"]."'
";
$result = mysql_query($sql) or die(mysql_error());
while($record = mysql_fetch_assoc($result)){
if ($record["TABLE_NAME"]==$TABLE_PREFIX.$table){
$cadenaBusqueda = (@$valores["preSaveTempId"]) ? "num!=0" : "num!=".@$valores["num"];
$encontrado = mysql_fetch_assoc(mysql_query("SELECT * FROM ".$record["TABLE_NAME"]." WHERE enlace='".$enlaceNuevo."' AND ".$cadenaBusqueda." LIMIT 1"));
}else{
$encontrado = mysql_fetch_assoc(mysql_query("SELECT * FROM ".$record["TABLE_NAME"]." WHERE enlace='".$enlaceNuevo."' LIMIT 1"));
}
if (@$encontrado){
if ($nohay) {
$enlaceNuevo = self::_seteaCampoEnlace($valores,"_".base_convert(time(),10,36),$table,$generateAlias);
}else{
$enlaceNuevo = $enlaceNuevo."_".base_convert(time(),10,36).$sufijo; // str_replace(".html","_".base_convert(time(),10,36).".html",$enlaceNuevo);
}
}
}
/**************************/
// AHORA CREAMOS LOS ALIAS
/**************************/
if ($generateAlias){
$pruebas = @mysql_fetch_assoc(mysql_query("SELECT pagina_publicada FROM ".$TABLE_PREFIX."configuracion LIMIT 1"));
if (@$pruebas["pagina_publicada"]){
$idiomasViejo["es"] = $enlaceAnterior;
$idiomasNuevo["es"] = $enlaceNuevo;
foreach($idiomasNuevo as $idioma => $idiomaNuevo){
if (isset($idiomasViejo[$idioma]) && isset($idiomasNuevo[$idioma]) && $idiomasViejo[$idioma] != $idiomasNuevo[$idioma]){
$preSQL = "num=null, createdDate='".date("Y-m-d H:i:s")."', updatedDate='".date("Y-m-d H:i:s")."', createdByUserNum=1, updatedByUserNum=1, dragSortOrder=".time();
mysql_query("DELETE FROM ".$TABLE_PREFIX."alias_urls where url_alias='".$idiomasNuevo[$idioma]."'");
mysql_query("DELETE FROM ".$TABLE_PREFIX."alias_urls where url_alias='".$idiomasViejo[$idioma]."' AND url_destino='".$idiomasNuevo[$idioma]."'");
mysql_query("INSERT INTO ".$TABLE_PREFIX."alias_urls set ".$preSQL.", url_alias='".$idiomasViejo[$idioma]."', url_destino='".$idiomasNuevo[$idioma]."'");
mysql_query("UPDATE ".$TABLE_PREFIX."alias_urls set url_destino='".$idiomasNuevo[$idioma]."' where url_destino='".$idiomasViejo[$idioma]."'");
mysql_query("DELETE FROM ".$TABLE_PREFIX."alias_urls where url_alias=''");
}
}
}
}
return $enlaceNuevo;
}
static function _getEnlaceIdiomas($valores,$enlaceNuevo,$enlaceAnterior,$estado=0,$table = null){
global $SETTINGS,$tableName,$TABLE_PREFIX;
$result = [];
if (!$table) $table = $tableName;
$result = mysql_query_fetch_all_assoc("SELECT prefix,fieldValue FROM ".$TABLE_PREFIX."traducciones WHERE tableName='".$table."' and fieldName='enlace' and recordNum='".$valores["num"]."'");
if (!empty($result)) {
$result2 = [];
foreach($result as $rec){
$result2[$rec["prefix"]] = base64_decode($rec["fieldValue"]);
}
return $result2;
}
return $result;
}
static function _seteaEnlaceIdiomas($valores,$enlaceNuevo,$enlaceAnterior,$estado=0,$table = null){
global $SETTINGS,$tableName,$TABLE_PREFIX;
$result = [];
if (!$table) $table = $tableName;
// REINICIAMOS LOS ENLACES DE LOS IDIOMAS
//die("Aun falta establecer los enlaces para los idiomas así que el cdn está inservible hasta que se haga");
switch($estado){
case 5:
case 6:
case 4:
case 2:
// EN ESTE CASO NO HACEMOS NADA
break;
case 1:
// AL PONER ENLACE DE FORMA MANUAL NO HACEMOS NADA EN IDIOMAS
break;
case 3:
default:
mysql_query("DELETE FROM ".$TABLE_PREFIX."traducciones where tableName='".$table."' and fieldName='enlace' and recordNum='".$valores["num"]."'");
foreach($SETTINGS["idiomas"] as $key => $value):
if ($value&&$value!="www"){
$enlace = base64_encode("/".$value.$enlaceNuevo);
$result[$value] = "/".$value.$enlaceNuevo;
mysql_query("INSERT INTO ".$TABLE_PREFIX."traducciones set num=null,prefix='".$value."', tableName='".$table."', fieldName='enlace', fieldValue='".$enlace."', recordNum='".intval(@$valores["num"])."', preSaveTempId='".@$valores["preSaveTempId"]."'") or die(mysql_error());
}
endforeach;
}
return $result;
}
static function _getLinkPrefix($record,$table = null) {
global $tableName, $TABLE_PREFIX;
if (!$table) $table = $tableName;
$enlaces = array();
$record["tableName"] = $table;
$cont = 0;
while (true && $cont++ <= 50) { // Contador de seguridad para evitar el bucle infinito (que en teoría nunca pasará, jaja)
// Comprobamos si la tabla ha cambiado para no volver a cargar el schema
if ($record["tableName"] != @$tabla) {
$tabla = $record["tableName"];
if(class_exists('SchemaAPI')) {
$schema = SchemaAPI::getInstance()->loadSchema($tabla);
} else {
$schema = loadSchema($tabla);
}
$breadcrumbField = @$schema["breadcrumbField"];
if ($breadcrumbField == "parentNum") {
$schema[$breadcrumbField]["optionsTablename"] = $tabla;
$schema[$breadcrumbField]["optionsValueField"] = "num";
}
if (@$schema[$breadcrumbField]["optionsType"] == "query"){
preg_match("/SELECT ([0-9a-z_]*),[\s?]([_0-9a-z]*) FROM ([a-z_]*)/",$schema[$breadcrumbField]["optionsQuery"],$matches);
if (@$matches[1]) $schema[$breadcrumbField]["optionsValueField"] = $matches[1];
if (@$matches[3]) $schema[$breadcrumbField]["optionsTablename"] = str_replace($TABLE_PREFIX,"",$matches[3]);
}
}
if (!@$breadcrumbField || !@$schema[$breadcrumbField]["optionsTablename"]) {
break;
}
$record = @mysql_fetch_assoc(mysql_query("SELECT * FROM ".$TABLE_PREFIX.$schema[$breadcrumbField]["optionsTablename"]." WHERE `".$schema[$breadcrumbField]["optionsValueField"]."`='".$record[$breadcrumbField]."'"));
if (!@$record) break;
$record["tableName"] = $schema[$breadcrumbField]["optionsTablename"];
array_unshift($enlaces, $record);
}
if (!@$enlaces) return "";
$prefix = "/".join("/", array_map(function($a) {
return self::parsea_enlace($a[self::_getTitleField($a, $a["tableName"])]);
}, $enlaces));
return $prefix;
}
static function _getTitleField($record, $tabla, $schema = null) {
if (@$record["name"]) return "name";
if (@$record["title"]) return "title";
if (@$record["titulo"]) return "titulo";
if (@$record["nombre"]) return "nombre";
if (!@$campo) {
if(class_exists('SchemaAPI')) {
if (!@$schemaAux) $schemaAux = SchemaAPI::getInstance()->loadSchema($tabla);
} else {
if (!@$schemaAux) $schemaAux = loadSchema($tabla);
}
foreach ($schemaAux as $key => $value):
if (@$value["type"] == "textfield" && $key != "enlace") {
return $key;
break;
}
endforeach;
}
}
static function parsea_enlace($txt) {
$transliterationTable = array("" => "", ' ' => '',' ' => '','' => '', 'á' => 'a', 'Á' => 'A', 'à' => 'a', 'À' => 'A', 'ă' => 'a', 'Ă' => 'A', 'â' => 'a', 'Â' => 'A', 'å' => 'a', 'Å' => 'A', 'ã' => 'a', 'Ã' => 'A', 'ą' => 'a', 'Ą' => 'A', 'ā' => 'a', 'Ā' => 'A', 'ä' => 'a', 'Ä' => 'A', 'æ' => 'ae', 'Æ' => 'AE', 'ḃ' => 'b', 'Ḃ' => 'B', 'ć' => 'c', 'Ć' => 'C', 'ĉ' => 'c', 'Ĉ' => 'C', 'č' => 'c', 'Č' => 'C', 'ċ' => 'c', 'Ċ' => 'C', 'ç' => 'c', 'Ç' => 'C', 'ď' => 'd', 'Ď' => 'D', 'ḋ' => 'd', 'Ḋ' => 'D', 'đ' => 'd', 'Đ' => 'D', 'ð' => 'dh', 'Ð' => 'Dh', 'é' => 'e', 'É' => 'E', 'è' => 'e', 'È' => 'E', 'ĕ' => 'e', 'Ĕ' => 'E', 'ê' => 'e', 'Ê' => 'E', 'ě' => 'e', 'Ě' => 'E', 'ë' => 'e', 'Ë' => 'E', 'ė' => 'e', 'Ė' => 'E', 'ę' => 'e', 'Ę' => 'E', 'ē' => 'e', 'Ē' => 'E', 'ḟ' => 'f', 'Ḟ' => 'F', 'ƒ' => 'f', 'Ƒ' => 'F', 'ğ' => 'g', 'Ğ' => 'G', 'ĝ' => 'g', 'Ĝ' => 'G', 'ġ' => 'g', 'Ġ' => 'G', 'ģ' => 'g', 'Ģ' => 'G', 'ĥ' => 'h', 'Ĥ' => 'H', 'ħ' => 'h', 'Ħ' => 'H', 'í' => 'i', 'Í' => 'I', 'ì' => 'i', 'Ì' => 'I', 'î' => 'i', 'Î' => 'I', 'ï' => 'i', 'Ï' => 'I', 'ĩ' => 'i', 'Ĩ' => 'I', 'į' => 'i', 'Į' => 'I', 'ī' => 'i', 'Ī' => 'I', 'ĵ' => 'j', 'Ĵ' => 'J', 'ķ' => 'k', 'Ķ' => 'K', 'ĺ' => 'l', 'Ĺ' => 'L', 'ľ' => 'l', 'Ľ' => 'L', 'ļ' => 'l', 'Ļ' => 'L', 'ł' => 'l', 'Ł' => 'L', 'ṁ' => 'm', 'Ṁ' => 'M', 'ń' => 'n', 'Ń' => 'N', 'ň' => 'n', 'Ň' => 'N', 'ñ' => 'n', 'Ñ' => 'N', 'ņ' => 'n', 'Ņ' => 'N', 'ó' => 'o', 'Ó' => 'O', 'ò' => 'o', 'Ò' => 'O', 'ô' => 'o', 'Ô' => 'O', 'ő' => 'o', 'Ő' => 'O', 'õ' => 'o', 'Õ' => 'O', 'ø' => 'o', 'Ø' => 'O', 'ō' => 'o', 'Ō' => 'O', 'ơ' => 'o', 'Ơ' => 'O', 'ö' => 'o', 'Ö' => 'O', 'ṗ' => 'p', 'Ṗ' => 'P', 'ŕ' => 'r', 'Ŕ' => 'R', 'ř' => 'r', 'Ř' => 'R', 'ŗ' => 'r', 'Ŗ' => 'R', 'ś' => 's', 'Ś' => 'S', 'ŝ' => 's', 'Ŝ' => 'S', 'š' => 's', 'Š' => 'S', 'ṡ' => 's', 'Ṡ' => 'S', 'ş' => 's', 'Ş' => 'S', 'ș' => 's', 'Ș' => 'S', 'ß' => 'SS', 'ť' => 't', 'Ť' => 'T', 'ṫ' => 't', 'Ṫ' => 'T', 'ţ' => 't', 'Ţ' => 'T', 'ț' => 't', 'Ț' => 'T', 'ŧ' => 't', 'Ŧ' => 'T', 'ú' => 'u', 'Ú' => 'U', 'ù' => 'u', 'Ù' => 'U', 'ŭ' => 'u', 'Ŭ' => 'U', 'û' => 'u', 'Û' => 'U', 'ů' => 'u', 'Ů' => 'U', 'ű' => 'u', 'Ű' => 'U', 'ũ' => 'u', 'Ũ' => 'U', 'ų' => 'u', 'Ų' => 'U', 'ū' => 'u', 'Ū' => 'U', 'ư' => 'u', 'Ư' => 'U', 'ü' => 'u', 'Ü' => 'U', 'ẃ' => 'w', 'Ẃ' => 'W', 'ẁ' => 'w', 'Ẁ' => 'W', 'ŵ' => 'w', 'Ŵ' => 'W', 'ẅ' => 'w', 'Ẅ' => 'W', 'ý' => 'y', 'Ý' => 'Y', 'ỳ' => 'y', 'Ỳ' => 'Y', 'ŷ' => 'y', 'Ŷ' => 'Y', 'ÿ' => 'y', 'Ÿ' => 'Y', 'ź' => 'z', 'Ź' => 'Z', 'ž' => 'z', 'Ž' => 'Z', 'ż' => 'z', 'Ż' => 'Z', 'þ' => 'th', 'Þ' => 'Th', 'µ' => 'u', 'а' => 'a', 'А' => 'a', 'б' => 'b', 'Б' => 'b', 'в' => 'v', 'В' => 'v', 'г' => 'g', 'Г' => 'g', 'д' => 'd', 'Д' => 'd', 'е' => 'e', 'Е' => 'E', 'ё' => 'e', 'Ё' => 'E', 'ж' => 'zh', 'Ж' => 'zh', 'з' => 'z', 'З' => 'z', 'и' => 'i', 'И' => 'i', 'й' => 'j', 'Й' => 'j', 'к' => 'k', 'К' => 'k', 'л' => 'l', 'Л' => 'l', 'м' => 'm', 'М' => 'm', 'н' => 'n', 'Н' => 'n', 'о' => 'o', 'О' => 'o', 'п' => 'p', 'П' => 'p', 'р' => 'r', 'Р' => 'r', 'с' => 's', 'С' => 's', 'т' => 't', 'Т' => 't', 'у' => 'u', 'У' => 'u', 'ф' => 'f', 'Ф' => 'f', 'х' => 'h', 'Х' => 'h', 'ц' => 'c', 'Ц' => 'c', 'ч' => 'ch', 'Ч' => 'ch', 'ш' => 'sh', 'Ш' => 'sh', 'щ' => 'sch', 'Щ' => 'sch', 'ъ' => '', 'Ъ' => '', 'ы' => 'y', 'Ы' => 'y', 'ь' => '', 'Ь' => '', 'э' => 'e', 'Э' => 'e', 'ю' => 'ju', 'Ю' => 'ju', 'я' => 'ja', 'Я' => 'ja', "!" => "", "|" => "", "'" => "", "\"" => "", "'" => "", "@" => "", "·" => "", "#" => "", "$" => "", "¢" => "", "%" => "", "" => "", "¬" => "", "/" => "", "÷" => "", "(" => "", "" => "", ")" => "", "" => "", "" => "", "?" => "", "'" => "", "¡" => "", "¿" => "", "" => "", "´" => "", "^" => "", "`" => "", "[" => "", "*" => "", "+" => "", "]" => "", "¨" => "", "´" => "", "{" => "", "}" => "", "," => "", ";" => "", "" => "", "." => "", ":" => "", "" => "", "<" => "", ">" => "", "" => "", "" => "", "»" => "", "«" => "", "œ" => "", "æ" => "", "®" => "", "" => "", "¥" => "", "π" => "", "" => "", "" => "", "" => "", "" => "", "§" => "", "~" => "", "Ω" => "", "" => "", "©" => "", "" => "", "µ" => "", "=" => "", "&" => "", " " => "-", "" => "-", "_" => "-", " " => "-", '€' => 'e', 'º' => '', '°' => '', 'ª' => '', '&' => 'y', '\'' => '');
$enlace = trim(strtolower(str_replace(array_keys($transliterationTable), array_values($transliterationTable), $txt)));
$enlace = preg_replace("/([\-]+)/", "-", $enlace);
if (substr($enlace,strlen($enlace)-1) == "-") $enlace = substr($enlace,0,strlen($enlace)-1);
$enlace = str_replace("-/","/",$enlace);
$enlace = str_replace("/-","/",$enlace);
$enlace = urlencode($enlace);
$enlace = str_replace("%C2","",$enlace);
$enlace = str_replace("%A0","",$enlace);
$enlace = str_replace("%250D","",$enlace);
return urlencode($enlace);
}
}

533
cms/lib/classes/CocoParser.php Executable file
View File

@@ -0,0 +1,533 @@
<?php
if (@$_REQUEST["__amp_source_origin"] && @$_REQUEST["dynamicForm"]){
CocoParser::amp();
}
class CocoParser {
static $captchaValido = false;
static $hayCaptcha = false;
static $parseaCodigosEnLinea = true;
static function parsea_codigos_en_linea($cadena,$options=array()){
if (!self::$parseaCodigosEnLinea) return $cadena;
if (is_array($cadena)) return $cadena;
if (is_null($cadena)) $cadena = '';
$cadena = str_replace("ql-align-", "text-", $cadena);
$cadena = str_replace("<ul>", "<ul class='bullet'>", $cadena);
$cadena = str_replace("<ol>", "<ol class='bullet'>", $cadena);
$cadena = preg_replace("/(target=\"_blank\")/", "$1 rel=\"noopener\"", $cadena);
$cadena = preg_replace_callback("|(\{FORMULARIO\_)([A-Z_]*)(\})|",
function($matches) use ($options){
return "<div data-code-replace='".$matches[0]."'>".self::dame_boton_formulario($matches,$options)."</div>";
},$cadena);
$dummy = array("cadena" => $cadena, "options" => $options);
// addPlugins("codigos_en_linea", $dummy);
// Activando este plugin el tiempo de carga aumenta CONSIDERABLEMENTE ya que se pide en cada content
$cadena = $dummy["cadena"];
return $cadena;
}
static function parsea_campo2($txt,$espacio="_") {
$transliterationTable = array('á' => 'a', 'Á' => 'A', 'à' => 'a', 'À' => 'A', 'ă' => 'a', 'Ă' => 'A', 'â' => 'a', 'Â' => 'A', 'å' => 'a', 'Å' => 'A', 'ã' => 'a', 'Ã' => 'A', 'ą' => 'a', 'Ą' => 'A', 'ā' => 'a', 'Ā' => 'A', 'ä' => 'a', 'Ä' => 'A', 'æ' => 'ae', 'Æ' => 'AE', 'ḃ' => 'b', 'Ḃ' => 'B', 'ć' => 'c', 'Ć' => 'C', 'ĉ' => 'c', 'Ĉ' => 'C', 'č' => 'c', 'Č' => 'C', 'ċ' => 'c', 'Ċ' => 'C', 'ç' => 'c', 'Ç' => 'C', 'ď' => 'd', 'Ď' => 'D', 'ḋ' => 'd', 'Ḋ' => 'D', 'đ' => 'd', 'Đ' => 'D', 'ð' => 'dh', 'Ð' => 'Dh', 'é' => 'e', 'É' => 'E', 'è' => 'e', 'È' => 'E', 'ĕ' => 'e', 'Ĕ' => 'E', 'ê' => 'e', 'Ê' => 'E', 'ě' => 'e', 'Ě' => 'E', 'ë' => 'e', 'Ë' => 'E', 'ė' => 'e', 'Ė' => 'E', 'ę' => 'e', 'Ę' => 'E', 'ē' => 'e', 'Ē' => 'E', 'ḟ' => 'f', 'Ḟ' => 'F', 'ƒ' => 'f', 'Ƒ' => 'F', 'ğ' => 'g', 'Ğ' => 'G', 'ĝ' => 'g', 'Ĝ' => 'G', 'ġ' => 'g', 'Ġ' => 'G', 'ģ' => 'g', 'Ģ' => 'G', 'ĥ' => 'h', 'Ĥ' => 'H', 'ħ' => 'h', 'Ħ' => 'H', 'í' => 'i', 'Í' => 'I', 'ì' => 'i', 'Ì' => 'I', 'î' => 'i', 'Î' => 'I', 'ï' => 'i', 'Ï' => 'I', 'ĩ' => 'i', 'Ĩ' => 'I', 'į' => 'i', 'Į' => 'I', 'ī' => 'i', 'Ī' => 'I', 'ĵ' => 'j', 'Ĵ' => 'J', 'ķ' => 'k', 'Ķ' => 'K', 'ĺ' => 'l', 'Ĺ' => 'L', 'ľ' => 'l', 'Ľ' => 'L', 'ļ' => 'l', 'Ļ' => 'L', 'ł' => 'l', 'Ł' => 'L', 'ṁ' => 'm', 'Ṁ' => 'M', 'ń' => 'n', 'Ń' => 'N', 'ň' => 'n', 'Ň' => 'N', 'ñ' => 'n', 'Ñ' => 'N', 'ņ' => 'n', 'Ņ' => 'N', 'ó' => 'o', 'Ó' => 'O', 'ò' => 'o', 'Ò' => 'O', 'ô' => 'o', 'Ô' => 'O', 'ő' => 'o', 'Ő' => 'O', 'õ' => 'o', 'Õ' => 'O', 'ø' => 'o', 'Ø' => 'O', 'ō' => 'o', 'Ō' => 'O', 'ơ' => 'o', 'Ơ' => 'O', 'ö' => 'o', 'Ö' => 'O', 'ṗ' => 'p', 'Ṗ' => 'P', 'ŕ' => 'r', 'Ŕ' => 'R', 'ř' => 'r', 'Ř' => 'R', 'ŗ' => 'r', 'Ŗ' => 'R', 'ś' => 's', 'Ś' => 'S', 'ŝ' => 's', 'Ŝ' => 'S', 'š' => 's', 'Š' => 'S', 'ṡ' => 's', 'Ṡ' => 'S', 'ş' => 's', 'Ş' => 'S', 'ș' => 's', 'Ș' => 'S', 'ß' => 'SS', 'ť' => 't', 'Ť' => 'T', 'ṫ' => 't', 'Ṫ' => 'T', 'ţ' => 't', 'Ţ' => 'T', 'ț' => 't', 'Ț' => 'T', 'ŧ' => 't', 'Ŧ' => 'T', 'ú' => 'u', 'Ú' => 'U', 'ù' => 'u', 'Ù' => 'U', 'ŭ' => 'u', 'Ŭ' => 'U', 'û' => 'u', 'Û' => 'U', 'ů' => 'u', 'Ů' => 'U', 'ű' => 'u', 'Ű' => 'U', 'ũ' => 'u', 'Ũ' => 'U', 'ų' => 'u', 'Ų' => 'U', 'ū' => 'u', 'Ū' => 'U', 'ư' => 'u', 'Ư' => 'U', 'ü' => 'u', 'Ü' => 'U', 'ẃ' => 'w', 'Ẃ' => 'W', 'ẁ' => 'w', 'Ẁ' => 'W', 'ŵ' => 'w', 'Ŵ' => 'W', 'ẅ' => 'w', 'Ẅ' => 'W', 'ý' => 'y', 'Ý' => 'Y', 'ỳ' => 'y', 'Ỳ' => 'Y', 'ŷ' => 'y', 'Ŷ' => 'Y', 'ÿ' => 'y', 'Ÿ' => 'Y', 'ź' => 'z', 'Ź' => 'Z', 'ž' => 'z', 'Ž' => 'Z', 'ż' => 'z', 'Ż' => 'Z', 'þ' => 'th', 'Þ' => 'Th', 'µ' => 'u', 'а' => 'a', 'А' => 'a', 'б' => 'b', 'Б' => 'b', 'в' => 'v', 'В' => 'v', 'г' => 'g', 'Г' => 'g', 'д' => 'd', 'Д' => 'd', 'е' => 'e', 'Е' => 'E', 'ё' => 'e', 'Ё' => 'E', 'ж' => 'zh', 'Ж' => 'zh', 'з' => 'z', 'З' => 'z', 'и' => 'i', 'И' => 'i', 'й' => 'j', 'Й' => 'j', 'к' => 'k', 'К' => 'k', 'л' => 'l', 'Л' => 'l', 'м' => 'm', 'М' => 'm', 'н' => 'n', 'Н' => 'n', 'о' => 'o', 'О' => 'o', 'п' => 'p', 'П' => 'p', 'р' => 'r', 'Р' => 'r', 'с' => 's', 'С' => 's', 'т' => 't', 'Т' => 't', 'у' => 'u', 'У' => 'u', 'ф' => 'f', 'Ф' => 'f', 'х' => 'h', 'Х' => 'h', 'ц' => 'c', 'Ц' => 'c', 'ч' => 'ch', 'Ч' => 'ch', 'ш' => 'sh', 'Ш' => 'sh', 'щ' => 'sch', 'Щ' => 'sch', 'ъ' => '', 'Ъ' => '', 'ы' => 'y', 'Ы' => 'y', 'ь' => '', 'Ь' => '', 'э' => 'e', 'Э' => 'e', 'ю' => 'ju', 'Ю' => 'ju', 'я' => 'ja', 'Я' => 'ja', "!" => "", "|" => "", "'" => "", "\"" => "", "'" => "", "@" => "", "·" => "", "#" => "", "$" => "", "¢" => "", "%" => "", "" => "", "¬" => "", "/" => "", "÷" => "", "(" => "", "" => "", ")" => "", "" => "", "" => "", "?" => "", "'" => "", "¡" => "", "¿" => "", "" => "", "´" => "", "^" => "", "`" => "", "[" => "", "*" => "", "+" => "", "]" => "", "¨" => "", "´" => "", "{" => "", "}" => "", "," => "", ";" => "", "" => "", "." => "", ":" => "", "" => "", "<" => "", ">" => "", "" => "", "" => "", "»" => "", "«" => "", "œ" => "", "æ" => "", "®" => "", "" => "", "¥" => "", "π" => "", "" => "", "" => "", "" => "", "" => "", "§" => "", "~" => "", "Ω" => "", "" => "", "©" => "", "" => "", "µ" => "", "=" => "", "&" => "", " " => "-", "" => "-", "_" => "-", " " => "-", '€' => 'e', 'º' => '', 'ª' => '', '&' => 'y');
$newString = strtolower(str_replace(array_keys($transliterationTable), array_values($transliterationTable), $txt));
$newString = preg_replace("/([\-]+)/", $espacio, $newString);
return urlencode($newString);
}
static function envia_curl($datos){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, protocol()."://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$datos);
curl_setopt($ch, CURLOPT_TIMEOUT,30);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (protocol() == "https"){
curl_setopt($ch,CURLOPT_RESOLVE, [
$_SERVER["HTTP_HOST"].":443:".$_SERVER["SERVER_ADDR"]
]);
}else{
curl_setopt($ch,CURLOPT_RESOLVE, [
$_SERVER["HTTP_HOST"].":80:".$_SERVER["SERVER_ADDR"]
]);
}
$respond = curl_exec ($ch);
curl_close ($ch);
return $respond;
}
static function dame_boton_formulario($matches,$options=array()){
global $configuracionRecord;
$identificador = @$matches[2];
if (!$identificador) return $matches[0];
$result2 = mysql_query("SELECT * FROM cms__formularios where identificador='".$identificador."' limit 1");
$result = "";
if (mysql_num_rows($result2)>0){
$rec = mysql_fetch_assoc($result2);
if (@$options["clases"]) $rec["clase"] = $options["clases"];
$form = $rec;
$form["tableName"] = "cms__formularios";
$form["tipo"] = (@$options["tipo"]) ? $options["tipo"] : $form["tipo"];
$resultPlugin = addPlugins("pre_codigos_en_linea",$form);
echo @$resultPlugin["html"];
$datos = array(
"id" => "form_".$form["identificador"],
"title" => t($form,"title"),
"numForm" => $form["num"],
"formulario" => json_decode($form["campos"],true),
"tipo" => $form["tipo"],
"clase" => $form["clase"],
"widget" => (@$options["widget"]) ? true : false
);
foreach ($options as $index => $option):
$datos[$index] = $option;
endforeach;
if (!@$options["yaPuesto"]) {
if (!@$options["amp"]){
$respond = self::envia_curl("modulo=modal&clave=wscO4QaF&datos=".base64_encode(json_encode($datos)));
}else{
require_once realpath(dirname(__FILE__)."/../../plugins/amp/amp_static functions.php");
$respond = modulo_amp("modal",$datos);
}
}
// ENVIO DE DATOS POR CORREO
if (@$_REQUEST["dynamicForm"]){
if ($form["num"]==@$_REQUEST["numForm"]){
unset($_REQUEST["numForm"]);
// Comprobamos el captcha
self::$captchaValido = true;
if (!@$options["amp"]) {
if ((!isset($options["captcha"]) || @$options["captcha"] == true)) {
if (@hasRecaptcha()) {
$captcha = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$configuracionRecord["secret_key_recaptcha"]."&response=".@$_REQUEST["g-recaptcha-response"]), true);
if (!@$captcha["success"]) self::$captchaValido = false;
}
else {
if (md5(@$_POST["captcha"]) != @$_SESSION["key_captcha"]) self::$captchaValido = false;
}
}
}
if (self::$captchaValido) {
$datosCadena="<ul>";
$correosCliente = array();
$campos = json_decode($form["campos"],true);
$tableName = self::parsea_campo2($form["tablaDestino"]);
$schema = loadSchema($tableName);
foreach(@$_REQUEST["dynamicForm"] as $key => $value):
foreach($campos as $cont => $campo):
if ($campo["tipo"]=="email" && $key == self::parsea_campo2($campo["nombre"],"-") && !in_array($value,$correosCliente)) {
$correosCliente[] = $value;
}
if ($key==self::parsea_campo2($campo["nombre"],"-")) {
$schemaKey = self::parsea_campo2($campo["nombre"]);
$campos[$cont]["datosCliente"] = $value;
}
endforeach;
if (isset($schema[$schemaKey])) {
switch (@$schema[$schemaKey]['type']) {
case 'list':
$options = getListOptions($tableName, $schemaKey);
if (isset($options[$value])) $value = $options[$value];
$datosCadena.="<li><b>".$schema[$schemaKey]['label']."</b>: ".$value."</li>";
break;
case 'checkbox':
$datosCadena.="<li><b>".$schema[$schemaKey]['label']."</b>: ".(@$value ? 'Sí' : 'No')."</li>";
break;
default:
$datosCadena.="<li><b>".$schema[$schemaKey]['label']."</b>: ".$value."</li>";
}
} else {
$datosCadena.="<li><b>".$key."</b>: ".$value."</li>";
}
endforeach;
$datosCadena.="<li><b>URL de solicitud</b>: <a href='https://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]."'>https://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]."</a></li>";
$datosCadena.="</ul>";
$contenido = str_replace("{DATOS}",$datosCadena,$form["contenidoEmail"]);
if (!$form["enviarACliente"]) $correosCliente=array();
if ($form["enviarAEmpresa"]) {
$result = mysql_query("select correo_admin from cms_configuracion limit 1");
$correo = mysql_fetch_assoc($result);
if (strpos($correo["correo_admin"],",")){
$sepp = explode(",",$correo["correo_admin"]);
foreach($sepp as $seppp):
if (@$seppp){
if (!in_array($seppp,$correosCliente)) $correosCliente[]=$seppp;
}
endforeach;
}else{
if (!in_array($correo["correo_admin"],$correosCliente)) $correosCliente[]=$correo["correo_admin"];
}
}
if (@$options['correos'] && is_array($options['correos'])) {
foreach($options['correos'] as $c):
if (filter_var($c, FILTER_VALIDATE_EMAIL)) $correosCliente[] = $c;
endforeach;
}
if (count($correosCliente)>0){
$datos = array(
"destinatarios" => $correosCliente,
"numForm" => $form["num"],
"identificador" => $form["identificador"],
"asunto" => $form["title"],
"contenido" => base64_encode($contenido)
);
$respond2 = self::envia_curl("enviar_correo=1&clave=wscO4QaF&datos=".base64_encode(json_encode($datos)));
$respond = @$respond2.@$respond;
}
// AHORA LO INSERTAMOS EN LA BASE DE DATOS
if (@$form["tablaDestino"]){
$sql = "
INSERT INTO cms_".self::parsea_campo2($form["tablaDestino"])." SET
num=NULL,
createdDate='".date("Y-m-d H:i:s")."',
updatedDate='".date("Y-m-d H:i:s")."',
dragSortOrder='".time()."',
url='https://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]."',
numFormulario='".$form["num"]."'
";
$sql_busqueda = "SELECT num FROM cms_".self::parsea_campo2($form["tablaDestino"])." WHERE numFormulario='".$form["num"]."'";
$sql_busqueda.=" AND url='https://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]."'";
foreach($campos as $campo):
if (@$campo["datosCliente"]){
$sql.=",".self::parsea_campo2($campo["nombre"])."='".$campo["datosCliente"]."'";
$sql_busqueda.=" AND ".self::parsea_campo2($campo["nombre"])."='".$campo["datosCliente"]."'";
}
endforeach;
$result3 = @mysql_fetch_assoc(mysql_query("SHOW TABLES LIKE 'cms_".self::parsea_campo2($form["tablaDestino"])."'"));
if ($result3){
$resultadoBusqueda = mysql_fetch_assoc(mysql_query($sql_busqueda));
if (!@$resultadoBusqueda){
mysql_query($sql) or die(mysql_error());
}
}
}
$resultPlugin = addPlugins("post_codigos_en_linea",$form);
if (!@$options["amp"] && !@$options['sin_gracias']) {
$apartadoGracias = CocoDB::get("otros_contenidos", "controlador='gracias.php'", null, 1, ["ignoreSchema" => true]);
$apartadoGracias = @$apartadoGracias[0];
if (@$apartadoGracias) {
echo '<script>window.location.href = "'.t($apartadoGracias, "enlace").'"</script>';
}
}
echo @$form["html_post"];
}else{
echo "<script>alert('".t_var("El captcha introducido no es válido")."')</script>";
}
}
}
switch ($form["tipo"]){
case "fields":
$result=@$respond;
break;
case "inline":
$result=@$respond;
break;
default:
$result =@$respond;
if (@$options["textoBoton"]){
$result.= "<a href='javascript:void(0)' class='".$rec["clase"]."' data-toggle='modal' data-target='#form_".$rec["identificador"]."'>".$options["textoBoton"]."</a>";
}else{
$result.= "<a href='javascript:void(0)' class='".$rec["clase"]."' data-toggle='modal' data-target='#form_".$rec["identificador"]."'>".$rec["textoBoton"]."</a>";
}
}
}
return $result;
}
static function amp(){
require_once realpath(dirname(__FILE__)."/../../../../funciones.php");
$result2 = @mysql_fetch_assoc(mysql_query("SELECT * FROM cms__formularios where num='".intval(@$_REQUEST["numForm"])."' limit 1"));
$domain_url = protocol()."://".$_SERVER["HTTP_HOST"];
header("Content-type: application/json");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin:" . str_replace('.', '-', $domain_url) .".cdn.ampproject.org");
header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
$apartadoGracias = CocoDB::get("otros_contenidos", "controlador='gracias.php'", null, 1, ["ignoreSchema" => true]);
$apartadoGracias = @$apartadoGracias[0];
if (@$apartadoGracias) {
header("AMP-Redirect-To: " . protocol()."://".$_SERVER["HTTP_HOST"].t($apartadoGracias, "enlace"));
header("Access-Control-Expose-Headers: AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin");
}
else {
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
}
if (@$result2){
$result = self::dame_boton_formulario(array(null,null,$result2["identificador"]),array("amp" => true,"yaPuesto" => true));
die(json_encode(array('successmsg'=>'ok',"result" => @$result)));
}else{
die(json_encode(array('successmsg'=>'Error')));
}
}
static function cocoForm($data = []){
global $configuracionRecord;
$defaults = [
"sendTo" => @$configuracionRecord["correo_admin"],
"messageOK" => t_var("Mensaje enviado"),
"messageKO" => t_var("Los campos son requeridos"),
"attachFiles" => false
];
foreach($data as $key => $value){
if (!is_string($value) || $value != "null") $defaults[$key] = $value;
}
$data = $defaults;
if (@$data["captcha"]) self::$hayCaptcha = true;
if (@$_REQUEST["cocoForm"] && @$_REQUEST["cocoForm"]["form"] == $data["id"]){
try{
$cocoForm = @$_REQUEST["cocoForm"];
if ($cocoForm["form"] !== $data["id"]) return;
if (@$data["captcha"] && !self::cocoFormValidateCaptcha($cocoForm)) throw new Exception(t_var('El Captcha no es válido')); // CAPTCHA
// Anael: Variable estandar que usamos de Honeypot, en caso de que exista es que la ha rellenado un bot.
if (@$cocoForm["full_user_name"]) throw new Exception(t_var('El Captcha no es válido'));
$errors = []; // COMPROBAMOS LOS REQUIRED
foreach($data["variables"] as $key => $value){
if (strpos($key,"[]") !== false) $key = str_replace("[]","",$key);
if ($value["type"]=="file" && @$_FILES["cocoForm"] && array_filter($_FILES["cocoForm"]["name"][$key]) ) {
$uploadFiles = self::upload("cocoForm",$key);
foreach($uploadFiles as $uploadFile){
if ($uploadFile['success'] === false) throw new Exception(t_var('Error en la subida de archivo'));
if (@$cocoForm[$key]) $cocoForm[$key][]=$uploadFile["urlPath"]; else $cocoForm[$key] = [$uploadFile["urlPath"]];
if(!$data["attachFiles"]){
$link = "<a href='https://".$_SERVER["HTTP_HOST"].$uploadFile["urlPath"]."'>".t_var("Descargar")." ".basename($uploadFile["urlPath"])."</a><br>";
// En banana educación hay que arreglarlo poniendo en el correo el _text
if (@$cocoForm[$key."_text"]) $cocoForm[$key."_text"].=$link; else $cocoForm[$key."_text"] = $link;
} else {
CocoEmail::$attach_files[] = $uploadFile["filePath"];
}
}
continue;
}
if (isset($value["required"]) && empty($cocoForm[$key]) && @$cocoForm[$key] !== '0' && @$cocoForm[$key] !== 0) $errors[$key] = $value;
}
if (!empty($errors)) throw new Exception(t_var('Los campos').' '.join(", ",array_map(function($rec){ return t_var($rec); },array_keys($errors))).' '.t_var('son oblitagorios'));
if (isset($data["action"])) return hook($data["action"],$cocoForm); // ACTION A HOOK
if (isset($data["tableName"])) $resultInsert = self::cocoFormInsertRecords($data,$cocoForm); // INSERCION
if (isset($data["mailRecord"]) && count($data["mailRecord"]) == 2) {
if (isset($data["tableName"]) && @$resultInsert){
//$insertedRecord = mysql_insert_id();
$recordInserted = @CocoDB::get($data["tableName"],"num=".intval($resultInsert),null,1,["relationsDepth" => 2])[0];
}
if (@$recordInserted){
self::cocoFormEmail($data, array_merge($cocoForm, $recordInserted)); // EMAIL
}else{
self::cocoFormEmail($data,$cocoForm); // EMAIL
}
}
if (isset($data["redirectTo"])) { // REDIRECT
echo "<script>document.location.href='".$data["redirectTo"]."'</script>";
}
echo strip_tags($data["messageOK"]) == $data["messageOK"] ? "<script>alert('".addslashes($data["messageOK"])."');</script>" : $data["messageOK"];
}catch(Exception $e){
echo strip_tags($data["messageKO"]) == $data["messageKO"] ? "<script>alert('".$e->getMessage()."');</script>" : "<div class='p-12 bg-red-600 rounded-lg'>".$e->getMessage()."</div>";
}
}
}
static function cocoFormValidateCaptcha($cocoForm = []){
global $configuracionRecord;
if (@hasRecaptcha()) {
$captcha = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$configuracionRecord["secret_key_recaptcha"]."&response=".@$_REQUEST["g-recaptcha-response"]), true);
if (!@$captcha["success"]) return false;
}
else {
if (md5(@$_POST["captcha"]) != @$_SESSION["key_captcha"]) return false;
}
return true;
}
static function cocoFormInsertRecords($data = [],$cocoForm = []){
if (!@loadSchema($data["tableName"])) throw new Exception(t_var('La tabla de destino no existe'));
$cocoForm["url"] = $_SERVER["REQUEST_URI"];
return CocoDB::insertRecords($data["tableName"],$cocoForm,[],['return_last_id' => true]);
}
static function cocoFormEmail($data = [],$cocoForm = []){
if (@$data["header"]) CocoEmail::$header = @$data["header"];
if (@$data["footer"]) CocoEmail::$footer = @$data["footer"];
if (@$data["styles"]) CocoEmail::$styles = @$data["styles"];
$recipients = [];
if (isset($data["sendToClient"]) && isset($cocoForm[$data["sendToClient"]])) $recipients[] = $cocoForm[$data["sendToClient"]];
if (isset($data["sendTo"])){
foreach(array_filter(explode(",",$data["sendTo"])) as $email){
$recipients[] = trim($email);
}
}
if (empty($recipients)) throw new Exception(t_var('No se encuentran destinatarios para el envío del correo'));
if (!empty($recipients) && $data["mailRecord"][1]){
if (!@loadSchema($data["mailRecord"][0])) throw new Exception(t_var('La tabla de correos no existe'));
$auxTableCocoEmail = CocoEmail::$table;
if (@loadSchema($data["mailRecord"][0])){
CocoEmail::$table = $data["mailRecord"][0];
}
$options = [];
if (trim(strtolower(@$data["emailMode"]?:'')) == "twig") $options["twig"] = true;
if (@$data["emailB64"]) $options["base64Decode"] = true;
//CocoEmail::$debug = true;
CocoEmail::send($data["mailRecord"][1],$cocoForm,$recipients,null,null,false,$options ?: []);
CocoEmail::$table = $auxTableCocoEmail;
}
return null;
}
static function slugify($text) {
// replace non letter or digits by -
$text = preg_replace('~[^\pL\d]+~u', '-', $text);
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
// trim
$text = trim($text, '-');
// remove duplicate -
$text = preg_replace('~-+~', '-', $text);
// lowercase
$text = strtolower($text);
if (empty($text)) {
return substr(str_shuffle(MD5(microtime())), 0, 10);
}
return $text;
}
static function check_if_file_exist_and_get_new_name(&$file_info, $path, $count = 0) {
if(!$count) {
if(file_exists($path . $file_info['filename'] . '.' . $file_info['extension'])) {
return self::check_if_file_exist_and_get_new_name($file_info, $path, $count + 1);
}
} else {
if(file_exists($path . $file_info['filename'] . '-' . $count . '.' . $file_info['extension'])) {
return self::check_if_file_exist_and_get_new_name($file_info, $path, $count + 1);
}
}
if($count) $file_info['filename'] .= '-' . $count;
}
static function upload($prefix = null,$file = 'file') {
$arrayFiles = $prefix ? $_FILES[$prefix] : $_FILES;
if(!isset($arrayFiles["error"][$file])) return [];
$allowed = [
'application/pdf' => 'pdf',
'audio/x-aac' => 'aac',
'application/vnd.amazon.ebook' => 'azw',
'audio/x-aiff' => 'aiff',
'audio/mp3' => 'mp3',
'audio/mpeg' => 'mp3',
'image/bmp' => 'bmp',
'text/css' => 'css',
'text/csv' => 'csv',
'text/plain' => 'csv',
'application/epub+zip' => 'epub',
'image/gif' => 'gif',
'image/x-icon' => 'ico',
'image/jpeg' => ['jpg', 'jpeg'],
'image/png' => 'png',
'image/heic' => 'heic',
'image/svg+xml' => 'svg',
'image/tiff' => 'tiff',
'image/webp' => 'webp',
'video/x-m4v' => 'm4v',
'video/x-ms-wmv' => 'wmv',
'video/mpeg' => 'mpeg',
'video/mp4' => 'mp4',
'video/webm' => 'webm',
'video/ogg' => 'ogg',
'application/vnd.oasis.opendocument.text' => 'odt',
'application/vnd.oasis.opendocument.graphics' => 'odg',
'application/vnd.oasis.opendocument.spreadsheet' => 'ods',
'application/vnd.oasis.opendocument.presentation' => 'odp',
'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'
];
$countfiles = count($arrayFiles['name'][$file]);
$files_to_upload = [];
// $uploads_dir = __DIR__ . '/../../../../../uploads/';
$uploads_dir = __DIR__ . '/../../uploads/';
// Loop de archivos.
for($i=0;$i<$countfiles;$i++){
$files_to_upload[$i] = ['urlPath' => '', 'filePath' => '', 'success' => false];
// Si hay un error saltamos el archivo.
if($arrayFiles['error'][$file][$i] !== 0 || !$arrayFiles['name'][$file][$i]) continue;
// Obtenemos la info del archivo.
$file_name = $arrayFiles['name'][$file][$i];
$tmp_file = $arrayFiles['tmp_name'][$file][$i];
$file_info = pathinfo($file_name);
// Obtenemos el mime_type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $tmp_file);
finfo_close($finfo);
// Si este archivo no está permitod continuamos.
if (!isset($allowed[$mime_type])) continue;
// Comprobamos si existe ya el archivo con este nombre para cambiarlo en tal caso.
$file_info['filename'] = self::slugify($file_info['filename']);
self::check_if_file_exist_and_get_new_name($file_info, $uploads_dir);
// Movemos el archivo porque ha sido validado
$new_name = $file_info['filename'] . '.' . $file_info['extension'];
move_uploaded_file($tmp_file, $uploads_dir.$new_name);
$filePath = realpath($uploads_dir.$new_name);
$urlPath = '/cms/uploads/'.$new_name;
$files_to_upload[$i] = ['urlPath' => $urlPath, 'filePath' => $filePath, 'success' => true];
}
return $files_to_upload;
}
}

282
cms/lib/classes/CocoWS.php Executable file
View File

@@ -0,0 +1,282 @@
<?php
class CocoWS {
private static $_instances = array();
static $endpoint = "";
static $token = "";
static $cacheSchemaTables = [];
static $cacheSchemas = [];
public static function getInstance() {
$class = get_called_class();
if (!isset(self::$_instances[$class])) {
self::$_instances[$class] = new $class();
}
return self::$_instances[$class];
}
private function __construct() {}
static function request($api_method, $data = null, $method = 'GET') {
$url = rtrim(self::$endpoint, "/")."/".trim($api_method, "/")."/";
$header = array();
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: Bearer '.self::$token;
$result = self::curl($url,$header,$method,$data);
return $result;
}
static function validateUploadToken($token) {
$response = self::request('upload_token', ['action' => 'validate', 'token' => $token], 'POST');
return isset($response['success']) && $response['success'];
}
/**
* Actualiza la configuracion de la pagina
* @destacar
* @category WS
* @param settings: Actualiza los settings
* @return boolean que indica el exito
*/
static function updateSettings($settings) {
return true;
}
/**
* Actualiza un Schema
* @destacar
* @category WS
* @param tableName: Identificador del schema
* @param path: ruta del archivo
* @return boolean que indica el exito
*/
static function insertOrUpdateSchema($tableName,$path,$schemaNew = null) {
if (!$schemaNew) { $schemaNew = CocoWS::loadSchema($tableName);}
saveINI($path."/".$tableName.".ini.php",$schemaNew);
return true;
}
/**
* Inserta un modulo dado en la carpeta de modulos
* @destacar
* @category WS
* @param id: Identificador del módulo
* @param zipFile: archivo Zip
* @return boolean que indica el exito
*/
static function insertOrUpdateModule($id, $zipFile) {
return true;
}
/**
* Inserta un plugin dado en la carpeta de plugins
* @destacar
* @category WS
* @param id: Identificador del plugin
* @param zipFile: archivo Zip
* @return boolean que indica el exito
*/
static function insertOrUpdatePlugin($id, $zipFile) {
return true;
}
/**
* Ejecuta un curl contra el servidor
* @destacar
* @category WS
* @param url: url del servidor
* @param header: cabeceras
* @param method: metodo utilizado
* @param data: datos que se transfieren en la consulta
* @return boolean que indica el exito
*/
static function curl($url,$header,$method = "GET",$data = null){
$ch = curl_init();
switch (strtoupper($method)) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, 1);
case 'PUT':
case "DELETE":
if ($data) {
if (is_array($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
else {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
}
break;
default:
$url .= "?".http_build_query($data);
break;
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER["HTTP_HOST"]);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
//curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
if (!$response) {
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
$error = "Verbose information:\n<pre>".htmlspecialchars($verboseLog)."</pre>\n";
$error.= sprintf("cUrl error (#%d): %s<br>\n", curl_errno($ch),
htmlspecialchars(curl_error($ch)));
curl_close($ch);
return self::parseError(["error" => $error,"code" => 418]);
}
$json = json_decode($response,true);
if (json_last_error() !== JSON_ERROR_NONE){
curl_close($ch);
return self::parseError(["error" => "Data response error, not a object","message" => $response]);
}
if (isset($json["error"])){
curl_close($ch);
return self::parseError($json);
}
curl_close($ch);
return $json;
}
/**
* Parsea el error de respuesta
* @destacar
* @category WS
* @param data: Datos del error
* @return devuelve los datos
*/
public static function parseError($data){
switch (@$data["code"]){
case 403:
break;
case 600:
break;
default:
throw new Exception(json_encode($data));
}
return $data;
}
/**
* Hacer Login en el servidor
* @destacar
* @category WS
* @param user: usuario
* @param pass: password
* @param domain: dominio
* @param token: token
* @param method: método utilizado
* @return devuelve el token y el usuario
*/
static function login($user=null,$pass=null,$domain=null,$token=null,$method = "POST"){
$userPass = $user && $pass ? base64_encode($user.':'.$pass.':'.$domain) : $token;
$authorization = $token ? "Bearer" : "Login";
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: '.$authorization.' '.$userPass;
$url = rtrim(self::$endpoint,"/")."/auth/";
$result = self::curl($url,$header,$method);
if (@$result["error"]) return self::parseError($result);
return [$result["data"]["token"],$result["data"]["user"]];
}
static function setEndpoint($endpoint) {
self::$endpoint = $endpoint;
}
static function setToken($token) {
self::$token = $token;
}
static function getToken() {
return self::$token;
}
static function getSchemaTables($dir = '',$type = '') {
$respuesta = self::request("schemas",["action" => "getSchemaTables","dir" => $dir,"type" => $type]);
if (isset($respuesta["error"])){
return self::parseError($respuesta);
}else{
self::$cacheSchemaTables = $respuesta["data"];
return $respuesta["data"];
}
}
static function loadSchema($tableName, $schemaDir = '') {
if (isset(self::$cacheSchemas[$tableName])) return self::$cacheSchemas[$tableName];
if (!$tableName) { die(__FUNCTION__ . ": no tableName specified!"); }
$tableNameWithoutPrefix = getTableNameWithoutPrefix($tableName);
$respuesta = self::request("schemas",["id" => $tableNameWithoutPrefix,"dir" => $schemaDir]);
if (isset($respuesta["error"])){
return self::parseError($respuesta);
}else{
self::$cacheSchemas[$tableName] = $respuesta["data"];
return $respuesta["data"];
}
}
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)) {
return explode(":",base64_decode($matches[1]));
}
}
return null;
}
}

131
cms/lib/classes/Db.php Executable file
View File

@@ -0,0 +1,131 @@
<?php
class Db {
private $host; // Db Host
private $user; // Db User
private $password; // Db Password
private $db; // Db Name
private $link; // MySQLi Link
private static $instance = false; // Db Class Instance
/**
* @param host: DB Host
* @param user: DB user
* @param password: DB Password
* @param db: DB Name
*/
public function __construct($host, $user, $password, $db) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->db = $db;
$this->link = $this->connect();
}
/**
* @param host: DB Host
* @param user: DB user
* @param password: DB Password
* @param db: DB Name
*/
public static function getInstance($host='', $user='', $password='', $db='') {
if (self::$instance) {
return self::$instance;
}
self::$instance = new Db($host, $user, $password, $db);
return self::$instance;
}
public function escape($str) {
return $this->link->quote($str);
}
/**
* Connects to the database. Returns HTTP Error Code 500 in case of error
*/
private function connect() {
$dsn = "mysql:host=".$this->host.";dbname=".$this->db.";charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="TRADITIONAL"'
];
try {
$link = new PDO($dsn, $this->user, $this->password, $options);
return $link;
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
return false;
}
/**
* Executes a SQL Query
*
* @param sql: SQL Query
* @param params: List of variables to be binded
*
* @return bool
*/
public function execute($sql, $params = null) {
if ($params) {
$stmt = $this->link->prepare($sql);
try {
$stmt->execute($params);
}
catch(Exception $e) {
return false;
}
}
else {
$stmt = $this->link->query($sql);
}
return $stmt->rowCount();
}
/**
* Executes a SQL Select Query
*
* @param sql: SQL Select Query
* @param params: List of variables to be binded
* @param indexed: If set to true, returns the indexed array instead of associative
*
* @return array
*/
public function executeS($sql, $params = null, $indexed = false) {
if ($params) {
$stmt = $this->link->prepare($sql);
$stmt->execute($params);
}
else {
$stmt = $this->link->query($sql);
}
if ($indexed) {
$result = $stmt->fetchAll(PDO::FETCH_ARRAY);
}
else {
$result = $stmt->fetchAll();
}
return $result;
}
/**
* Executes a SQL Select Query of one element
*
* @param sql: SQL Select Query
* @param params: List of variables to be binded
* @param indexed: If set to true, returns the indexed array instead of associative
*
* @return array
*/
public function fetch($sql, $params = null, $indexed = false) {
$result = $this->executeS($sql, $params, $indexed);
return empty($result) ? null : $result[0];
}
public function foundRows() {
$foundRows = $this->link->query('SELECT FOUND_ROWS()')->fetchColumn();
return $foundRows;
}
}