//////////////////////////////////////////////////////////////////////////////// /// AQUI DEBEN IR LOS DEFINES DE LA APLICACION ///////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function gentime() { static $a; if($a == 0) $a = microtime(true); else return (string)(microtime(true)-$a); } gentime(); // Configuración del correo //define('MAIL_FROM_EMAIL', 'responsablecomercial@circuloamistad.com'); define('MAIL_FROM_EMAIL', 'info@puracepacatering.es'); define('MAIL_FROM_NAME', 'Pura Cepa Catering'); define('MAIL_SMTP_DEBUG', 0); // 0 = no, 1 = poco, 2 = mucho define('MAIL_SMTP_AUTH', true); if( MAIL_SMTP_AUTH ){ define('MAIL_SMTP_HOST', 'mail.puracepacatering.es'); define('MAIL_SMTP_PORT', 25); define('MAIL_SMTP_USER', 'info@puracepacatering.es'); define('MAIL_SMTP_PASS', 'puracepa2012'); } // Permisos define("SUPER", 1); define("ADMIN", 2); //define("EMPRESA", 3); //define("PROVEEDOR", 4); //define("RETA", 5); // Tipos de formularios define('FORM_TIPO_1', 1); define('FORM_TIPO_2', 2); define('FORM_TIPO_3', 3); // Configuración del plano de las empresas define('PLANO_EMPRESAS_WIDTH', 920); define('PLANO_EMPRESAS_HEIGHT', 635); define('PLANO_EMPRESAS_PATH', 'pub/img/empresas/plano/plano.jpg'); // Módulos define('MOD_TEXTO_E_IMAGENES', 100); define('MOD_LISTA_NOTICIAS', 200); define('MOD_LISTA_DESCARGAS', 300); define('MOD_GALERIA_DE_IMAGENES', 400); define('MOD_FORMULARIO', 500); define('MOD_LISTA_EVENTOS', 600); // POSICIONES DE LOS BANNERS //define('BAN_POS_LEFT', 1); // BANNER EN COLUMNA IZQUIERDA define('BAN_POS_TOP', 2); // BANNER EN COLUMNA CENTRAL ARRIBA define('BAN_POS_RIGHT', 3); // BANNER EN COLUMNA DERECHA define('BAN_POS_OTHER', 4); // BANNER EN CUALQUIER OTRA POSICION define('BAN_POS_BOTTOM', 5); // BANNER EN COLUMNA CENTRAL ABAJO define('ID_NOTICIAS_RETA', 4); define('ID_DESCARGAS_RETA', 18); define('TEXTO_POLITICA', 'Sí, me considero informado y acepto la política de privacidad y aviso legal.'); //////////////////////////////////////////////////////////////////////////////// /// HASTA AQUI LOS DEFINES ///////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// define('_ROOT', dirname(__FILE__)); // Configuramos que las sesiones se guarden donde deben session_name('SESS' . md5($_SERVER['SCRIPT_NAME'])); // Con esto evito que se comparta la sesión entre proyectos. session_start(); ini_set('default_charset', 'UTF-8'); header('Content-Type: text/html; charset=utf-8'); // Define si se recibe por POST la petición. USO: if(POST){ ... } define('POST', getenv('REQUEST_METHOD') == 'POST'); // Define si se recibe por GET la petición. USO: if(GET){ ... } define('GET', getenv('REQUEST_METHOD') == 'GET'); // Define la ruta de la carpeta LIB define('LIB', 'pub/lib/'); // Define si estamos en modo depuración. USO: if(DEBUG){ ... } define('DEBUG', false); // Establecemos el timezone por defecto para la aplicación date_default_timezone_set('Europe/Madrid'); if( DEBUG) { ini_set('display_errors', 'on'); ini_set('display_startup_errors', 'on'); ini_set('error_reporting', '8191'); } ini_set('magic_quotes_gpc', 'Off'); ini_set('magic_quotes_runtime', 'Off'); ini_set('magic_quotes_sybase', 'Off'); ini_set('upload_max_filesize', '10M'); ini_set('safe_mode', 'Off'); set_magic_quotes_runtime(0); // Autoload solo se utiliza para automatizar la carga de las librerías function __autoload($classname){ if(file_exists('libraries/' . $classname . '.php')) require_once 'libraries/' . $classname . '.php'; elseif( function_exists('DOMPDF_autoload') ) DOMPDF_autoload($classname); } // depura y eso function depurar(){ echo "
"; print_r(func_get_args()); echo ""; die(); } // Valida si un email es correcto function valid_email($str){ return (bool) preg_match('/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix', $str); } function get_first_email($str){ $matches = array(); if( preg_match('/(([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6})/ix', $str, $matches) ){ return $matches[1]; } } // Convierte una fecha de español a ingles function convert_date_es_en($date){ $pat = '/^(\d{1,2})[\/-_.,](\d{1,2})[\/-_.,](\d{4})/'; return preg_replace($pat, '\\3-\\2-\\1', $date); } function hfilesize($path){ if( !file_exists($path) ) return 0; $bytes = filesize($path); $b = (int) $bytes; $s = array('B', 'kB', 'MB', 'GB', 'TB'); if($b <= 0) return "0 " . $s[0]; $con = 1024; $e = (int)(log($b,$con)); return number_format($b/pow($con,$e),2,',','.').' '.$s[$e]; } function get_domain(){ $array = parse_url($_SERVER["REQUEST_URI"]); $str = "http://" . $array["host"] . $array["path"]; if(substr($str, -1) != "/") $str .= "/"; return $str; } // Envia un correo electrónico usando la librería email // $from, $to, $subject, $message estan claro para que son. // $subject es opcional, si no se recibe pone el subject por defecto // $bccs debe ser un array con la lista de correos para bcc // $attachments debe ser un array con la lista de ficheros para adjuntar (con ruta relativa) function enviar_email($from, $from_name, $to, $message, $subject = '', $bccs = null, $attachments = null){ if(empty($from)) return new Rn(false, "No se ha recibido el 'from'"); if(empty($to)) return new Rn(false, "No se ha recibido el 'to'"); if(!valid_email($to)) return new Rn(false, "El email de destino no es válido"); if(empty($message)) return new Rn(false, "No se ha recibido mensaje"); $log = array(); if(empty($subject)){ $subject = "Mensaje desde www.puracepacatering.es"; $log["Falta Subject"] = "Se ha tenido que usar el subject por defecto, porque no se ha recibido subject."; } if(!empty($bccs)){ foreach($bccs as $k=>$v){ if(!valid_email($v)){ $log["bcc".$k] = "El e-mail $v no es correcto y ha sido eliminado de la lista de bccs"; unset($bccs[$k]); } } } if(!empty($attachments)){ foreach($attachments as $k => $attachment){ if(!file_exists($attachment)){ unset($attachments[$k]); } } } require_once('libraries/3th/PHPMailer_v5.0.0/class.phpmailer.php'); $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch try { $mail->IsHTML(); $mail->CharSet = 'utf-8'; $mail->SMTPDebug = MAIL_SMTP_DEBUG; // enables SMTP debug information (for testing) if( MAIL_SMTP_AUTH ){ $mail->IsSMTP(); // telling the class to use SMTP $mail->SMTPAuth = true; // enable SMTP authentication $mail->Host = MAIL_SMTP_HOST; // sets the SMTP server $mail->Port = MAIL_SMTP_PORT; // set the SMTP port for the GMAIL server $mail->Username = MAIL_SMTP_USER; // SMTP account username $mail->Password = MAIL_SMTP_PASS; // SMTP account password } $mail->SetFrom($from, $from_name); $mail->AddAddress(DEBUG ? 'info@puracepacatering.es' : $to); $mail->Subject = $subject; $mail->AltBody = 'Para ver este mensaje necesita un cliente compatible con mensajes HTML!'; // optional - MsgHTML will create an alternate automatically $mail->Body = $message; if(!empty($bccs)) foreach($bccs as $bcc) $mail->AddBCC($bcc); if(!empty($attachments)) foreach($attachments as $attachment) $mail->AddAttachment($attachment); $mail->Send(); $success = true; } catch (phpmailerException $e) { $log["Excepcion phpmailer"] = $e->errorMessage(); $success = false; } catch (Exception $e) { $log["Exception phpmailer2"] = $e->getMessage(); $success = false; } $log["correcto"] = "Mensaje Enviado"; $core = Core::instance(); $core->log($log); if( $success ){ return new Rn(true, "Se ha enviado el correo correctamente", $log); }else{ return new Rn(false, "No se ha podido enviar el correo", $log); } } function enviar_mail_custom($from, $from_name, $to, $message, $subject = ''){ require_once('libraries/3th/PHPMailer_v5.0.0/class.phpmailer.php'); $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch try { $mail->IsHTML(); $mail->CharSet = 'utf-8'; $mail->SMTPDebug = MAIL_SMTP_DEBUG; // enables SMTP debug information (for testing) $mail->SetFrom($from, $from_name); $mail->AddAddress(DEBUG ? 'info@puracepacatering.es' : $to); $mail->Subject = $subject; $mail->AltBody = 'Para ver este mensaje necesita un cliente compatible con mensajes HTML!'; // optional - MsgHTML will create an alternate automatically $mail->Body = $message; $mail->Send(); $success = true; } catch (phpmailerException $e) { $log["Excepcion phpmailer"] = $e->errorMessage(); $success = false; } catch (Exception $e) { $log["Exception phpmailer2"] = $e->getMessage(); $success = false; } $core = Core::instance(); $core->log($log); return $success; } function procesar_email($desde = "", $subject = "", $to = ""){ $core = Core::instance(); if( POST && !empty($_POST["datos"])){ $datos = $_POST["datos"]; $message = $core->load_view("emails/generico", array( 'desde' => $desde, 'datos' => $datos, )); //$from = "responsablecomercial@circuloamistad.com"; $from = "info@puracepacatering.es"; $from_name = "Pura Cepa Catering"; //$to = !empty($to) ? $to : "responsablecomercial@circuloamistad.com"; $to = !empty($to) ? $to : "info@puracepacatering.es"; if(DEBUG) $to = "info@puracepacatering.es"; enviar_email($from, $from_name, $to, $message, $subject); return new Rn(true, "El mensaje ha sido enviado con éxito. Nos pondremos en contacto con usted lo antes posible."); } } function file_log($filename, $texto){ $file = 'tmp/log/' . $filename; $texto = "[" . date('Y-m-d H:i:s') . "] " . $texto; $texto = strip_tags($texto); $texto = str_replace("\n", " ", $texto); file_put_contents($file, $texto . "\n", FILE_APPEND); if( filesize($file) > 1048576 ) rename($file, date('Y-m-d_$file')); } // Convierte en absoluta una ruta relativa function abs_uri($rel_uri){ if( substr($rel_uri, 0, 1) != '/' ) $rel_uri = '/' . $rel_uri; return 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . $rel_uri; } //////////////////////////////////////////////////////////////////////////// /////////////// VALIDACION DE USUARIOS Y PERMISOS ////////////////////////// //////////////////////////////////////////////////////////////////////////// // Verifica si hay un usuario identificado en el sistema. function check_login(){ return !empty($_SESSION["usr"]) && is_object($_SESSION["usr"]); } // Devuelve: true o false // Valida si un usuario dispone del permiso requerido function tiene_permiso($permiso_requerido){ return check_login() && !empty($_SESSION["usr"]->id_permiso) && $_SESSION["usr"]->id_permiso <= intval($permiso_requerido); } // Valida si un usuario tiene un permiso en concreto o no function permiso_es($permiso){ return !empty($_SESSION["usr"]) && is_object($_SESSION["usr"]) && $permiso > 0 && $_SESSION["usr"]->id_permiso > 0 && $_SESSION["usr"]->id_permiso == $permiso; } // Valida si el usuario actual tiene algún permiso entre los recibidos function permiso_es_alguno(){ if( ! check_login() ) return false; $perms = func_get_args(); foreach($perms as $id_permiso){ if( permiso_es($id_permiso) ) return true; } return false; } // inicializo la base de datos $db = new Db(array( 'dbhost' => 'localhost', //'dbuser' => 'mysql', 'dbuser' => 'puracepa', //'dbpass' => '', 'dbpass' => 'Rapu1112*pa', 'dbname' => 'cepapura' /*'dbhost' => 'localhost', //'dbuser' => 'mysql', 'dbuser' => 'root', //'dbpass' => '', 'dbpass' => '', 'dbname' => 'puracepa_bd'*/ )); // intento conectar a la bd if( ! $db->conectar() ) die('
No se ha podido conectar al servidor de datos
'); // Establezco la codificacion UTF-8 para la base de datos $db->query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'"); // La primera aplicación será la por defecto. // El controlador por defecto es main y el método index // - 1º Parametro: el array con las aplicaciones disponibles // - 2º Parametro: el controlador por defecto [main] // - 3º Parametro: el metodo por defecto [index] $core = new Core(array( 'w' => 'web', 'c' => 'control', )); // Este index ahora es la configuración de la aplicación. // No es obligatorio crear el fichero index.php dentro de cada aplicación if( file_exists($core->get_application() . '/index.php') ) include $core->get_application() . '/index.php'; // Habilitar siguiente línea para problar la funcion de emails. // enviar_email("no-reply@parquejoyero.es", "Angel", "desoinsl@gmail.com", "Hola que tal", "hola que tal subject"); // Ultima linea del programa: ejecutar la web $core->run(); // Aquí pueden ir funciones globales para todas las aplicaciones aunque prefiero // que no se ponga aquí nada.