<?php

 function obtnerToken(){
  $CI = & get_instance();
  if(isset($_SERVER['HTTP_AUTHORIZATION'])){
    return $_SERVER['HTTP_AUTHORIZATION'];
   }
  $Header =  $CI->input->request_headers();
  if(isset($Header['Authorization'])){
   return  $Header['Authorization'];
 }
 if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])){
  return $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
 }
 if(isset($_SERVER['HTTP_AUTHORIZATION'])){
  return $_SERVER['HTTP_AUTHORIZATION'];
 }
 return FALSE;
 }

 function Excel($libros,$Titulos,$Leyenda){


    if(!empty($libros)) {
     $filename = "libros.xls";
     header("Content-Type: application/vnd.ms-excel"); 
     header("Content-Disposition: attachment; filename=".$filename); 
     $mostrar_columnas = false; 
     echo utf8_decode(utf8_decode($Leyenda. "\n"));
     foreach($libros as $libro) {
      if(!$mostrar_columnas) {
       echo utf8_decode(utf8_decode(implode("\t", array_values($Titulos)) . "\n"));
      
        $mostrar_columnas = true;
         } echo utf8_decode(utf8_decode(implode("\t", get_object_vars($libro)) . "\n")); 
          
       } 
     }else{
      echo 'No hay datos a exportar'; 
    } exit; 
   
   }

   function Random($Db = ""){
    $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if($Db==""){
      return substr(str_shuffle($permitted_chars), 0, 16);
    }else{
      return substr(str_shuffle($permitted_chars), 0, 16).".".$Db ;
    }
    
    // Output: video-g6swmAP8X5VG4jCi.mp4
    
   }
   function Raiz(){
    return  $_SERVER['DOCUMENT_ROOT'];
   }
   function Existe($nombre_fichero){
    if (file_exists($nombre_fichero)) {
      return true;
  } else {
      return false;
  }
   }
   function CrearCarpeta($Carpeta){
    mkdir($Carpeta, 0700,true);
   }
   function EmailHtml($Correos,$Titulo,$htmlContent,$Documento= null){
    $CI = & get_instance();
    $CI->load->library('email');
    $CI->load->model('ConfigModels');
    $User = $CI->ConfigModels->Value("smtp_user",TRUE);
    /*
    $config['protocol'] = 'smtp';
    $config['mailtype'] = 'html';
    $config['smtp_host'] = 'bl000366.ferozo.com';
    $config['smtp_port']='465'; //587
    $config['smtp_timeout'] = '10';
    $config['charset']='utf-8';
    $config['smtp_crypto']='ssl';
    $config['smtp_user']='certificados@segmarind.com';
    $config['smtp_pass']='AGNK/T68mL';
    $config['wordwrap'] = TRUE;
    $config['validate'] = TRUE;
    $CI->email->initialize($config);
    $CI->email->set_newline("\r\n");
    $CI->email->to($Correos);
    $CI->email->from('certificados@segmarind.com');
    $CI->email->subject($Titulo);


        $config['protocol'] = 'smtp';
    $config['mailtype'] = 'html';
    $config['smtp_host'] = 'smtp.googlemail.com';
    $config['smtp_port']='465' ;//465; //25; //587
    $config['smtp_timeout'] = '10';
    $config['charset']='utf-8';
    $config['smtp_crypto']='ssl';
    $config['smtp_user']='soporteAulaVirtual9@gmail.com';
    $config['smtp_pass']='gzuldejsxzsvbgke';
    */
  
    $config['protocol'] = 'smtp';
    $config['mailtype'] = 'html';
    $config['smtp_host'] = $CI->ConfigModels->Value("smtp_host",TRUE);
    $config['smtp_port']=$CI->ConfigModels->Value("smtp_port",TRUE);//465; //25; //587
    $config['smtp_timeout'] = '10';
    $config['charset']='utf-8';
    $config['smtp_crypto']='ssl';
    $config['smtp_user']=$User;
    $config['smtp_pass']=$CI->ConfigModels->Value("smtp_pass",TRUE);
    $config['wordwrap'] = TRUE;
    $config['validate'] = TRUE;
    $CI->email->initialize($config);
    $CI->email->set_newline("\r\n");
    $CI->email->to($Correos);
    $CI->email->from($User);
    $CI->email->subject($Titulo);
    $CI->email->message($htmlContent);
    if($Documento != null){
      $CI->email->attach($Documento);
    }
    $CI->email->send(FALSE);
    
    //echo $CI->email->print_debugger();
     return true;
   }

   function AddFechaActual($Dias){
    date_default_timezone_set('America/Santiago');
    $FechaActual = new  DateTime(date("Y-m-d"));
    $FechaActual->add(new DateInterval('P'.$Dias.'D'));
    return $FechaActual->format('Y-m-d');
    }
    function AddHoras($Horas){
      date_default_timezone_set('America/Santiago');
      $FechaActual = new  DateTime(date("Y-m-d H:i:s"));
     
      $FechaActual->add(new DateInterval('PT0'.$Horas.'H'));
      return $FechaActual->format('Y-m-d H:i:s');
      }
    function Vencido($Fecha){
      date_default_timezone_set('America/Santiago');
      $FechaComparar = strtotime(date($Fecha));
      $fecha_actual = strtotime(date("d-m-Y H:i:00",time()));
    
       //print_r(date("d-m-Y H:i:00 a",time()));
   
      if($fecha_actual>$FechaComparar){
        return true;
      }else{
        return false;
      }
    }
    function ExistePalabra($Palabra,$Texto){
      if($Texto === ""){
        return false;
      }
      $P = strtolower($Palabra);
      $T = strtolower($Palabra);
      $posicion_coincidencia = strpos($T, $P);
      if ($posicion_coincidencia === false) 
      {
        return false;
      }
      return true;
      }
      function BuscarNum($Texto){
          if($Texto==""){
            return 0;
          }
        $P = strtolower($Texto);
   
        $posicion_coincidencia = strrpos("reemplazo", $P);
        if ($posicion_coincidencia === false) 
        {
          $posicion_coincidencia = strrpos("remplazo", $P);
        }
        if ($posicion_coincidencia === false) 
        {
          $posicion_coincidencia = strrpos("reemplazar", $P);
        }
        if ($posicion_coincidencia === false) 
        {
          $posicion_coincidencia = strrpos("remplazar", $P);
        }
        if($posicion_coincidencia = false){
          return 0;
        }
        $Valor = "";
        for ($i = $posicion_coincidencia+1 ; $i< strlen($P);$i++   ){
       
           if($P[$i] == "0"||
              $P[$i] == "1"||
              $P[$i] == "2"||
              $P[$i] == "3"||
              $P[$i] == "4"||
              $P[$i] == "5"||
              $P[$i] == "6"||
              $P[$i] == "7"||
              $P[$i] == "8"||
              $P[$i] == "9"
              ){
                $Valor .= $P[$i];
              }else{
                if( $Valor!= ""){
                  break;
                }  
              }
               
        }
        if( $Valor== ""){
        return 0;
        }else{
          return intval($Valor);
        }
        }

  
 
    function Digitos($Cant,$N){
      $Cant2=strval($Cant);
      $Num = $N-strlen($Cant);
      $Cd="";
      for($i = 0; $i < $Num;$i++){
      $Cd=$Cd."0";
      }
      $Cd=$Cd.$Cant;
      return $Cd;
      }
      function myUrlEncode($string) {

	
        return urlencode($string);
    }

    function configDB($host,$user,$pass,$DB){

   
      $db = array(
        'dsn'	=> 'mysql:host='.$host.';dbname='.$DB.';charset=utf8',
        'hostname' => 'localhost',
        'username' => $user,
        'password' => $pass,
        'database' => $DB,
        'dbdriver' => 'pdo',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => TRUE,
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
      );
    return $db;

    }
    function restoreDatabaseTables($dbHost, $dbUsername, $dbPassword, $dbName, $filePath){
      // Connect & select the database
      $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
  
      // Temporary variable, used to store current query
      $templine = '';
      
      // Read in entire file
      $lines = file($filePath);
      
      $error = '';
      
      // Loop through each line
      foreach ($lines as $line){
          // Skip it if it's a comment
          if(substr($line, 0, 2) == '--' || $line == ''){
              continue;
          }
          
          // Add this line to the current segment
          $templine .= $line;
          
          // If it has a semicolon at the end, it's the end of the query
          if (substr(trim($line), -1, 1) == ';'){
              // Perform the query
              if(!$db->query($templine)){
                  $error .= 'Error performing query "<b>' . $templine . '</b>": ' . $db->error . '<br /><br />';
              }
              
              // Reset temp variable to empty
              $templine = '';
          }
      }
      return !empty($error)?$error:true;
  }

  
  // funcion que indica si una base de datos exist
  function existDb($host,$user,$pass,$DB){
    @$db = new mysqli($host, $user, $pass, $DB); 
    if ($db->connect_errno != null) {
      return FALSE;
    }
    $db->close();
    return TRUE;

  }
?>