<?php
require_once("clase_sesion.php");
#$sesion_fg = new sesion(); // inicio la sesion
define("NUMCOLHIDE", 1783);

function mensaje($msg, $empresa)
{
    ?>
    <script type="text/javascript">
        jAlert('<?php echo str_replace('@', '\n', $msg) ?>', '<?php echo $empresa ?>', function () {
            $("#salir").trigger("click");
        });
        $("#salir").trigger("click");
    </script>
    <?php
}

function cache()
{
    // NO TOCAR
    header('Accept-Ranges: bytes');
    $ExpStr = 'Expires: ' . gmdate("D, d M Y H:i:s", time() + 14400) . " GMT"; // 14400 = 4 horas
    header($ExpStr);
    header("Cache-Control: maxage=14400");
    header("Cache-Control: public, must-revalidate");
    header("Cache-Control: public");
    header("pragma: public");
    header("Content-Transfer-Encoding:gzip;q=1.0,identity;q=0.5,*;q=0");
    header("Cache-Control: cache");
    //header("Pragma: cache");
    header('Content-Type: text/html; charset=utf-8');

    //setlocale(LC_TIME, 'es_CO'); # Localiza en espaÃ±ol es_Venezuela
    // FIN NO TOCAR
    // elimina los espacios en blanco
    function compress_page($buffer)
    {
        $search = array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s');
        $replace = array('> ', ' <', '\\1');
        return preg_replace($search, $replace, $buffer);
    }

    ob_start("compress_page");
}

function academ_encrip($string, $key = 'Academia!*201$JS')
{
    $string = utf8_encode($string);
    $control = $key; //defino la llave para encriptar la cadena, cambiarla por la que deseamos usar
    $string = $control . $string . $control; //concateno la llave para encriptar la cadena
    $string = base64_encode($string); //codifico la cadena
    return ($string);
}

function rename_win($oldfile, $newfile)
{
    if (!rename($oldfile, $newfile)) {
        if (copy($oldfile, $newfile)) {
            unlink($oldfile);
            return TRUE;
        }
        return FALSE;
    }
    return TRUE;
}

function formatoParrafo()
{
    $frase = "hola juan.me ha gustado mucho.hagámonos público.mañana hablamos.luis";
    $frase2 = "";
    $indice = 0;
    $indicepunto = 0;


    $indicepunto = stripos($frase, ".");

    while ($indicepunto >= 0) {
        // El primer carácter es en mayúsculas
        $frase2 = $frase2 + $frase . substring($indice, $indice + 1) . toUpperCase();
        // Pegamos el resto hasta el primer punto      
        $frase2 = $frase2 + $frase . substring($indice + 1, $indicepunto + 1);

        $indice = $indicepunto + 1;
        $indicepunto = $frase . indexOf('.', $indice);
    }

    // Incluimos el final de la $frase
    $$frase2 = $$frase2 + $frase . substring($indice, $indice + 1) . toUpperCase();
    $$frase2 = $$frase2 + $frase . substring($indice + 1, $frase . length());


    System . out . println($$frase2);
}

function genRutaAbs($ruta, $ndir, $newdir)
{
    $numCarp = substr_count($ruta, '/');
    $array = explode("/", $ruta);
    $ncar = count($array) - $ndir;
    $cad = "";
    for ($i = 0; $i < $ncar; $i++) {
        $cad .= $array[$i] . '/';
    }
    return $cad . $newdir;
}

function nom_periodo($periodon)
{
    switch ($periodon) {
        case 1:
            $periodo = "Primero";
            break;
        case 2:
            $periodo = "Segundo";
            break;
        case 3:
            $periodo = "Tercero";
            break;
        case 4:
            $periodo = "Cuarto";
            break;
        case 5:
            $periodo = "Quinto";
            break;
        case 6:
            $periodo = "Sexto";
            break;
        case 7:
            $periodo = "Séptimo";
            break;
        case 8:
            $periodo = "Octavo";
            break;
        case 9:
            $periodo = "Noveno";
            break;
        case 10:
            $periodo = "Décimo";
            break;
        case 11:
            $periodo = "Décimo Primero";
            break;
        case 12:
            $periodo = "Décimo Segundo";
            break;
    }
    return $periodo;
}

function academ_decrip($string, $key = 'Academia!*201$JS')
{
    $string = base64_decode($string); //decodifico la cadena
    $control = $key;
    $string = str_replace($control, "", "$string");
    return $string;
}

function eCr($lcCadena)
{
    $cr = array(" ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "*", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "'", "(", ")", "=", "_", "|", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ",");
    $v1 = 7;
    $v2 = 1;
    $tam = count($cr);
    $lcCadena = trim(strtoupper($lcCadena));
    $cryp = "";

    for ($i = 0; $i < strlen($lcCadena); $i++) {
        $numx = 0;
        $let = substr($lcCadena, $i, 1);
        $numx = array_search($let, $cr);
        $resop = $v1 * $numx + $v2;
        $md = $resop % $tam;
        //echo "lp: ".$let ." - id: ".$numx. " - md: ".$md. " - lf: ".$cr[$md]."<br>" ;
        $cryp = $cryp . "" . $cr[$md];
    }
    return $cryp;
}

function normaliza($cadena)
{
    $originales = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ';
    $modificadas = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
    $cadena = utf8_decode($cadena);
    $cadena = strtr($cadena, utf8_decode($originales), $modificadas);
    $cadena = strtolower($cadena);
    return utf8_encode($cadena);
}

function parseString($string)
{
    $string = str_replace("\b", "", $string);
    $string = str_replace("\t", " ", $string);
    $string = str_replace("\n", "<br>", $string);
    $string = str_replace("\f", "", $string);
    $string = str_replace("\r", "", $string);
    $string = str_replace("\u", "", $string);
    $sustituye = array("\r\n", "\n\r", "\n", "\r");
    $string = str_replace($sustituye, "", $string);
    return $string;
}

function formatoPalabras($text, $form)
{
    switch ($form) {
        case 0:
            return ucwords(mb_strtolower($text));
            break;
        case 1:
            return mb_strtoupper($text, 'UTF-8');
            break;
        case 2:
            return ucfirst($text);
            break;
        default:
            return ucwords( mb_strtolower($text));
    }
}

function zerofill($entero, $largo = 4, $car = '0')
{
    // Limpiamos por si se encontraran errores de tipo en las variables
    $entero = (int)$entero;
    $largo = (int)$largo;
    $relleno = '';
    if (strlen($entero) < $largo) {
        $relleno = str_repeat($car, $largo - strlen($entero));
    }
    return $relleno . $entero;
}

function dCr($lcCadena)
{
    $cr = array(" ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "*", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "'", "(", ")", "=", "_", "|", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ",");
    $v1 = 7;
    $v2 = 1;
    $tam = count($cr);
    $inv = 33;
    $dcryp = "";
    for ($i = 0; $i < strlen($lcCadena); $i++) {
        $numx = 0;
        $let = substr($lcCadena, $i, 1);
        $numx = array_search($let, $cr);
        $resop = ($numx - $v2) * $inv;
        $md = $resop % $tam;

        if ($md < 0) {
            while ($md < 0) {
                $md = $md + $tam;
            }
        }

        //echo "lp: ".$let. " - id: ". $numx. " - md: ".$md ." - lf: ".$cr[$md]."<br>" ;
        $dcryp = $dcryp . "" . $cr[$md];
    }
    return $dcryp;
}

function isAjax()
{
    return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function hashCripPwd($password = false, $key = 'Academia!*201&JS')
{
    if ($password === false) {
        return false;
    }
    //$salt_length=30;
    //$salt=substr(md5(uniqid(rand(), true)), 0, $salt_length);
    //$password=hash($password,$key);
    //$password = $salt . substr(sha1($salt . $password), 0, -$salt_length);
    return md5($password);
}

//funciones genereales
function comprobar_sesion()
{
    $sesion_fg = new sesion(); // inicio la sesion
    if ($sesion_fg->isValid()) {

        if ($sesion_fg->get('academia_in') != "SI") {
            return false;
            exit();
        } else {
            $fechaGuardada = $sesion_fg->get("ultimoAcceso");
            $ahora = date("Y-n-j H:i:s");
            $tiempo_transcurrido = (strtotime($ahora) - strtotime($fechaGuardada));
            if ($tiempo_transcurrido >= 3600) {
                $sesion_fg->borrarsesion(); // destruyo la sesión
                return false;
            } else {
                $sesion_fg->set('ultimoAcceso', $ahora);
                return true;
            }
        }
    } else {
        return false;
    }
}

function escapar($cadena, $theType = 'text')
{
    /* 	if (PHP_VERSION < 6) {
      $cadena = get_magic_quotes_gpc() ? stripslashes($cadena) : $cadena;
      }
      $cadena= function_exists("mysql_real_escape_string") ? mysql_real_escape_string($cadena) : mysql_escape_string($cadena);
     */
    return $cadena;
}

function GetSQLValueString($theValue, $theType = 'text')
{
    if (PHP_VERSION < 6) {
        $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    }
    $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

    switch ($theType) {
        case "text":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
        case "long":
        case "int":
            $theValue = ($theValue != "") ? (int)($theValue) : "NULL";
            break;
        case "double":
            $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
            break;
        case "date":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
    }
    return $theValue;
}

function getError($lug_err, $nerr, $sep)
{
    $arc = ruta_abs . '/includes/mensajes.xml';
    $datos = simplexml_load_file($arc);
    $mensaje = '';
    foreach ($datos->$lug_err as $msg) {
        $mensaje = $msg->$nerr;
    }
    if ($sep) {
        $mensaje = str_replace('\n', '<br>', $mensaje);
    }
    return $mensaje;
}

//-------------------------------------------------------------------------------------------------
function mostrar_cont_selec($cmps, $tabla, $cmpcnd, $ord, $default, $mos_cod, $cmpaux, $grid, $mselc = 1, $capital = 0)
{
    require_once("clase_sesion.php");
    require_once("MySQL.php");
    $ses = new sesion();

    $academia = new Servidor_Base_Datos(AC_CONN_HOST, AC_CONN_USER, AC_CONN_PASS, AC_CONN_DB . '' . $ses->get('anio'));

    $ord = (strpos(strtolower($ord), 'order') !== FALSE) ? $ord : ' order by ' . $ord;

    if (trim($cmpaux) == '') {
        $cons = "select $cmps  from $tabla WHERE 1=1 $cmpcnd $ord";
    } else {
        $cons = "select $cmps, $cmpaux  from $tabla WHERE 1=1 $cmpcnd $ord";
    }

    //echo "<option value='0xsq'>$cons</option>";
    $academia->instruccion($cons);
    $cadena = ($mselc == 1) ? "<option value='0x'>Seleccionar...</option>" : "";
    if ($grid == 0)
        echo $cadena;
    else
        echo "<select>";

    while ($reg = $academia->extraer_registro_num()) {
        $codigo = $reg[0];
        $cmpaux2 = $reg[2];
        $campo_ver = ($mos_cod) ? $reg[0] . " - " . $reg[1] : $reg[1];
        $campo_ver = ($capital == 1) ? ucwords($campo_ver) : $campo_ver;
        if ($default == $reg[0]) {
            echo "<option value='" . $codigo . "' selected='selected' aux='$cmpaux2'>" . $campo_ver . "</option>";
        } else {
            echo "<option value='" . $codigo . "' aux='$cmpaux2' >" . $campo_ver . "</option>";
        }
    }
    if ($grid == 1)
        echo "</select>";

    $academia->liberar();
    $academia->cerrar();
}

//---------------------------------------------------------------------------------------------------
function mostrar_cont_selec2($codigo, $cod_cnds, $default, $mos_cod, $cmpaux, $grid, $mselc = 1, $capital = 0, $cmpgen = '', $limi = 0, $grb = '')
{
    /*
      ampaux en caso de que se quiera llevar otro campo en el combo (true - false)
     */
    try {


        require_once("MySQL.php");
        $ses = new sesion();

        $academia = new Servidor_Base_Datos(AC_CONN_HOST, AC_CONN_USER, AC_CONN_PASS, AC_CONN_DB . '' . $ses->get('anio'));
        #echo 'hola';
        if (trim($cmpaux) == 1) {
            $cons = "call consultas('$codigo','$cod_cnds',1,'$cmpgen',$limi,'$grb')";
        } else {
            $cons = "call consultas('$codigo','$cod_cnds',0,'$cmpgen',$limi,'$grb')";
        }
#echo $cons;
        #echo "<option value='0xsq'>'$cons'</option>";
        $academia->instruccion($cons);

        echo ($grid != 0) ? "<select>" : '';
        echo ($mselc == 1) ? "<option value='0x'>Seleccionar...</option>" : "";
        if ($academia->extraer_error() > 0) {
            echo "<option value='0x' style='color:red'>" . $academia->extraer_error_msg() . "</option>";
        }
        while ($reg = $academia->extraer_registro_num()) {
            $codigo = $reg[0];
            $cmpaux2 = $reg[2];
            $campo_ver = ($mos_cod) ? $reg[0] . " - " . $reg[1] : $reg[1];
            $campo_ver = ($capital == 1) ? ucwords($campo_ver) : $campo_ver;

            if ($default == $reg[0]) {
                echo "<option value='" . $codigo . "' selected='selected' aux='$cmpaux2'>" . $campo_ver . "</option>";
            } else {
                echo "<option value='" . $codigo . "' aux='$cmpaux2' >" . $campo_ver . "</option>";
            }
        }
        if ($grid != 0) {
            echo "</select>";
        }

        $academia->liberar();
        $academia->cerrar();
    } catch (Exception $e) {
        var_dump($e);
    }
}

//-------------------------------------------

function let_per($n)
{
    switch ($n) {
        case 1:
            $l = 'A';
            break;
        case 2:
            $l = 'M';
            break;
        case 3:
            $l = 'E';
            break;
        case 4:
            $l = 'S';
            break;
        case 5:
            $l = 'P'; //imprimir doc o generar docs
            break;
        default:
            $l = '';
    }
    return $l;
}

//-------------------------------------------
function permisos($n_per)
{
    $num = 0;
    $vl = $n_per;
    $cad = "";
    for ($i = 5; $i >= 0; $i--) {
        $div = pow(2, $i);
        if (($vl / $div) > 1) {
            $cad = let_per($i) . $cad;
            $vl = $vl - $div;
        }
    }
    return $cad;
}

//-------------------------------------------
function permisos2($permiso)
{
    switch ($permiso) {
        case 3:
            $per = "A";
            break;
        case 5:
            $per = "M";
            break;
        case 7:
            $per = "AM";
            break;
        case 9:
            $per = "E";
            break;
        case 11:
            $per = "AE";
            break;
        case 13:
            $per = "ME";
            break;
        case 15:
            $per = "AME";
            break;
    }
    return $per;
}

function compara_fechas($fecha1, $fecha2)
{
    if (preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/([0-9][0-9]){1,2}/", $fecha1))
        list($dia1, $mes1, $año1) = split("/", $fecha1);

    if (preg_match("/[0-9]{1,2}-[0-9]{1,2}-([0-9][0-9]){1,2}/", $fecha1))
        list($dia1, $mes1, $año1) = split("-", $fecha1);

    if (preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/([0-9][0-9]){1,2}/", $fecha2))
        list($dia2, $mes2, $año2) = split("/", $fecha2);

    if (preg_match("/[0-9]{1,2}-[0-9]{1,2}-([0-9][0-9]){1,2}/", $fecha2))
        list($dia2, $mes2, $año2) = split("-", $fecha2);

    $dif = mktime(0, 0, 0, $mes1, $dia1, $año1) - mktime(0, 0, 0, $mes2, $dia2, $año2);

    return ($dif);
}

function calcular_edad($fech_nac, $fec_com)
{
    $fecha_hoy = split("-", $fec_com);

    $anioac = $fecha_hoy[0];
    $mesac = $fecha_hoy[1];
    $diaac = $fecha_hoy[2];

    $fn = split("-", $fech_nac);
    $anionac = $fn[0];
    $mesnac = $fn[1];
    $dianac = $fn[2];

    $diff_year = $anioac - $anionac;
    $diff_month = $mesac - $mesnac;
    $diff_day = $diaac - $dianac;

    if ($diff_month < 0 || ($diff_month == 0 && $diff_day < 0))
        $diff_year = $diff_year - 1; //no aparecían los dos guiones del postincremento :|

    return $diff_year;
}

function fechaTexto($fec = false, $array = false)
{
    if (!$fec)
        $fec = date("Y-m-d");
    $fec = strtotime($fec . " 00:00:00");
    $mes = date("n", $fec);

    $mesArray = array(
        1 => "Enero",
        2 => "Febrero",
        3 => "Marzo",
        4 => "Abril",
        5 => "Mayo",
        6 => "Junio",
        7 => "Julio",
        8 => "Agosto",
        9 => "Septiembre",
        10 => "Octubre",
        11 => "Noviembre",
        12 => "Diciembre"
    );

    $nombreDia = date("w", $fec);
    //echo $nombreDia;
    $nombreDiaArray = array(
        1 => "Lunes",
        2 => "Martes",
        3 => "Miercoles",
        4 => "Jueves",
        5 => "Viernes",
        6 => "Sabado",
        7 => "Domingo",
    );
    $mesReturn = $mesArray[$mes];
    $nombreDiaReturn = $nombreDiaArray[$nombreDia];
    $dia = date("d", $fec);
    $anio = date("Y", $fec);
    if (!$array)
        return $nombreDiaReturn . " " . $dia . " de " . $mesReturn . " de " . $anio;
    else
        return array("anio" => $anio, "nommes" => $mesReturn, "mes" => $mes, "nomdia" => $nombreDiaReturn, "dia" => $dia);
}

function getFotter($izquierda = "", $centro = "", $derecha = "")
{
    $pie = '<footer class="print-pie">'
        . '<div class="izquierda">' . $izquierda . '</div>'
        . '<div class="centro">' . $centro . '</div>'
        . '<div class="derecha">' . $derecha . '</div>'
        . '</footer>';
    return $pie;
}

function getFotter_ant($izquierda = "", $centro = "", $derecha = "")
{
    $pie = '<footer class="print-pie">'
        . '<table width="100%">'
        . '<tr>'
        . '<td width="20%" class="izquierda">' . $izquierda . '</td>'
        . '<td class="centro">' . $centro . '</td>'
        . '<td width="20%" class="derecha">' . $derecha . '</td>'
        . '</tr>'
        . '</table>'
        . '</footer>';
    return $pie;
}


function numberFormat($num, $dec = 1, $sep_dec = '.', $sep_miles = '')
{
    return number_format(round($num, $dec), $dec, $sep_dec, $sep_miles);
}

function jsonError(){
    switch(json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - Sin errores';
            break;
        case JSON_ERROR_DEPTH:
            echo ' - Excedido tamaño máximo de la pila';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Desbordamiento de buffer o los modos no coinciden';
            break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Encontrado carácter de control no esperado';
            break;
        case JSON_ERROR_SYNTAX:
            echo ' - Error de sintaxis, JSON mal formado';
            break;
        case JSON_ERROR_UTF8:
            echo ' - Caracteres UTF-8 malformados, posiblemente codificados de forma incorrecta';
            break;
        default:
            echo ' - Error desconocido';
            break;
    }
}