<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Defa extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
         var $menu;
         var $contactus;
        public function __construct()
        {
            parent::__construct();
            $this->load->model('Section', 'section_model');
            $this->menu = $this->section_model->buildTopMenuItem();
            $this->breadcrumbs = [];
            $this->load->model('ContactDetails', 'contactdetails_model');
            $this->contactus = $this->contactdetails_model->getContactus();

            $this->load->model('BackendUser', 'backenduser_model');
            $this->load->library(array('form_validation','session'));
            $this->load->helper(array('url','html','form'));
            $this->load->model('FileModel', 'file_model');
        }

        public function successpage(){
                // $this->load->view('successpage');
                // echo "1";
                redirect('/adminmain', 'refresh');
        }
               
        function logout(){
                $this->session->sess_destroy();
                redirect('/test');
        }


        public function index()
	{
        //$this->load->view('welcome_message');
        // $this->load->view('echofile');

        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
        // echo "1";
        ob_start();
        // $crc = filter_var($_GET['crc']);
        $this->load->helper('url');
        $crc=$this->uri->segment(3);
        $file = $_SESSION['defaprotect' . $crc];
        // $file = "application/controllers/small.mp4";
        $file = "upload/small.mp4";
        if ($headerurl = @get_headers($file, 1)['Location']) {
           
            if (!empty($headerurl)) {
                $file = $headerurl;
            }

        }
        if (isset($_SERVER['HTTP_RANGE'])) {
            $opts['http']['header'] = "Range: " . $_SERVER['HTTP_RANGE'];
            $opts['http']['method'] = "GET";
            $cong = stream_context_create($opts);
            ob_end_clean();
            readfile($file, false, $cong);
            exit();
        }
        return $file;


        // $contactusdata = $this->contactdetails_model->getContactus();
        //     $this->breadcrumbs[] = array (
        //         'label' => '聯絡我們',
        //         'link' => ''
        //     );
        //     $this->twig->display('main', array(
        //         'path' => array(
        //             'vendor' => $this->config->item('vendor_path'),
        //             'script' => $this->config->item('script_path'),
        //             'css' => $this->config->item('css_path'),
        //             'image' => $this->config->item('image_path')
        //         ),
        //         'breadcrumbs' => $this->breadcrumbs,
        //         'menus' => $this->menu,
        //         'contactusdata'=>$contactusdata,
        //         'session' => 'contact',
        //         'contactus' => $this->contactus,
        //         'page' => 'index'
        //     ));
        }
        public function code(){
             if (session_status() == PHP_SESSION_NONE) {
                    session_start();
                }
                // echo "1";
                ob_start();
                // $crc = filter_var($_GET['crc']);
                $this->load->helper('url');
                $crc=$this->uri->segment(3);
                $file = $_SESSION['defaprotect' . $crc];
                // $file = "application/controllers/small.mp4";
                // $file = "upload/small.mp4";
                if ($headerurl = @get_headers($file, 1)['Location']) {
                   
                    if (!empty($headerurl)) {
                        $file = $headerurl;
                    }

                }
                if (isset($_SERVER['HTTP_RANGE'])) {
                    // $opts['http']['header'] = "Range: " . $_SERVER['HTTP_RANGE'];
                    // $opts['http']['method'] = "GET";

                    //new option headed added
                    $opts = array(
                      'http'=>array(
                        'method'=>"GET",
                        'header'=>"Range:". $_SERVER['HTTP_RANGE']."\r\n" .
                                  "HTTP/1.1 206 Partial Content\r\n"
                      )
                    );
                    //end new option headed added


                    $cong = stream_context_create($opts);
                    ob_end_clean();
                    readfile($file, false, $cong);
                    exit();
                }
                return $file;







                //echo mp4
                //try to modified safari cannot play video problem
                // $path=$file;

// $fp = @fopen($file, 'rb');
// $size   = filesize($file); // File size
// $length = $size;           // Content length
// $start  = 0;               // Start byte
// $end    = $size - 1;       // End byte
// header('Content-type: video/mp4');
// //header("Accept-Ranges: 0-$length");
// header("Accept-Ranges: bytes");
// if (isset($_SERVER['HTTP_RANGE'])) {
//     $c_start = $start;
//     $c_end   = $end;
//     list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
//     if (strpos($range, ',') !== false) {
//         header('HTTP/1.1 416 Requested Range Not Satisfiable');
//         header("Content-Range: bytes $start-$end/$size");
//         exit;
//     }
//     if ($range == '-') {
//         $c_start = $size - substr($range, 1);
//     }else{
//         $range  = explode('-', $range);
//         $c_start = $range[0];
//         $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
//     }
//     $c_end = ($c_end > $end) ? $end : $c_end;
//     if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
//         header('HTTP/1.1 416 Requested Range Not Satisfiable');
//         header("Content-Range: bytes $start-$end/$size");
//         exit;
//     }
//     $start  = $c_start;
//     $end    = $c_end;
//     $length = $end - $start + 1;
//     fseek($fp, $start);
//     header('HTTP/1.1 206 Partial Content');
// }
// header("Content-Range: bytes $start-$end/$size");
// header("Content-Length: ".$length);
// $buffer = 1024 * 8;
// while(!feof($fp) && ($p = ftell($fp)) <= $end) {
//     if ($p + $buffer > $end) {
//         $buffer = $end - $p + 1;
//     }
//     set_time_limit(0);
//     echo fread($fp, $buffer);
//     flush();
// }
// fclose($fp);
// exit();

                //end echo mp4
                
                //new mp4 video
                // $fp = @fopen($file, 'rb');
                // $size   = filesize($file); // File size
                // $length = $size;           // Content length
                // $start  = 0;               // Start byte
                // $end    = $size - 1;       // End byte
                // header('Content-type: video/mp4');
                // //header("Accept-Ranges: 0-$length");
                // header("Accept-Ranges: bytes");
                // if (isset($_SERVER['HTTP_RANGE'])) {
                //     $c_start = $start;
                //     $c_end   = $end;
                //     list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
                //     if (strpos($range, ',') !== false) {
                //         header('HTTP/1.1 416 Requested Range Not Satisfiable');
                //         header("Content-Range: bytes $start-$end/$size");
                //         exit;
                //     }
                //     if ($range == '-') {
                //         $c_start = $size - substr($range, 1);
                //     }else{
                //         $range  = explode('-', $range);
                //         $c_start = $range[0];
                //         $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
                //     }
                //     $c_end = ($c_end > $end) ? $end : $c_end;
                //     if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
                //         header('HTTP/1.1 416 Requested Range Not Satisfiable');
                //         header("Content-Range: bytes $start-$end/$size");
                //         exit;
                //     }
                //     $start  = $c_start;
                //     $end    = $c_end;
                //     $length = $end - $start + 1;
                //     fseek($fp, $start);
                //     header('HTTP/1.1 206 Partial Content');
                // }
                // header("Content-Range: bytes $start-$end/$size");
                // header("Content-Length: ".$length);    
                // return $file;
                //end new mp4 video

                //new mp4 file 1

                // header("X-Sendfile: http://notesvision.at-webs.hk/".$file);
                // header("Content-Type: application/octet-stream");
                // header("Content-Disposition: attachment; file=\"123\"");
                // return $file;
                //end new mp4 file 1



                //test3 mp4 in safari
                // header("Content-Type: application/vnd.apple.mpegurl");
                // header("Access-Control-Allow-Origin: *");
                // header("Access-Control-Expose-Headers: Content-Length,Content-Range");
                // header("Access-Control-Allow-Headers: Range");
                // header("Accept-Ranges: bytes");
                // $opts = [
                //     "http" => [
                //         "method" => "GET",
                //         "header" => "User-Agent: oxoo/1.0.5 (Linux;Android 7.1.2) ExoPlayerLib/2.7.3\r\n" 


                //     ]
                // ];
                // $url="http://example.com/tizen112/bmaster.php?c=". $_REQUEST["c"] . "&q="
                //  . $_REQUEST["q"] . "&e=.m3u8";
                // $cx = stream_context_create($opts);


                // $hs = file_get_contents($file,false,$cx);
                // echo $hs;

                //end test3 mp4 in safari

        }
        public function moviecontrol(){
            if (session_status() == PHP_SESSION_NONE) {
                    session_start();
                }
                // echo "1";
                ob_start();
                // $crc = filter_var($_GET['crc']);
                $this->load->helper('url');
                $crc=$this->uri->segment(3);
                $file = $_SESSION['defaprotect' . $crc];
                // $file = "application/controllers/small.mp4";
                // $file = "upload/small.mp4";
                if ($headerurl = @get_headers($file, 1)['Location']) {
                   
                    if (!empty($headerurl)) {
                        $file = $headerurl;
                    }

                }
                // if (isset($_SERVER['HTTP_RANGE'])) {
                //     // $opts['http']['header'] = "Range: " . $_SERVER['HTTP_RANGE'];
                //     // $opts['http']['method'] = "GET";

                //     //new option headed added
                //     $opts = array(
                //       'http'=>array(
                //         'method'=>"GET",
                //         'header'=>"Range:". $_SERVER['HTTP_RANGE']."\r\n" .
                //                   "HTTP/1.1 206 Partial Content\r\n"
                //       )
                //     );
                //     //end new option headed added


                //     $cong = stream_context_create($opts);
                //     ob_end_clean();
                //     readfile($file, false, $cong);
                //     exit();
                // }

                //new file content
                if (isset($_SERVER['HTTP_RANGE'])) {
                $start=floatval(3355902253);

                // bytes to read, 100 KB
                $len=floatval(100*1024);

                // set up the http byte range headers
                $opts = array('http'=>array('method'=>'GET','header'=>"Range: bytes=$start-".($start+$len-1)));
                $cong = stream_context_create($opts);
                    ob_end_clean();
                    readfile($file, false, $cong);
                    exit();
                }
                
                //end new file content

                return $file;
        }
        public function pdfurl(){

            // echo base_url().'/upload/28d03b185ed64753be8c784f8fc1cfc6.pdf';
            // $this->load->helper('file');

            // $file = base_url().'/upload/28d03b185ed64753be8c784f8fc1cfc6.pdf';
            // $file= base_url().'/upload/28d03b185ed64753be8c784f8fc1cfc6.pdf';
            // EDIT: I added some permission/file checking.
            // if (!file_exists($filepath)) {
            //     throw new Exception("File $filepath does not exist");
            // }
            // if (!is_readable($filepath)) {
            //     throw new Exception("File $filepath is not readable");
            // }
            // $contents = read_file($file);
            // $this->output
            // ->set_status_header(200)
            // ->set_content_type('application/pdf')
            // ->set_output($contents)
            // ->_display();
            // exit;

            // $this->load->library('pdf');


            // $this->pdf->load_view('mypdf');
            // $this->pdf->render();


            // $this->pdf->stream("/upload/28d03b185ed64753be8c784f8fc1cfc6.pdf");
           //  $this->output
           // ->set_content_type('application/pdf')
           // ->set_output(file_get_contents("http://notesvision.at-webs.hk/upload/28d03b185ed64753be8c784f8fc1cfc6.pdf"));

            // $string = readfile('../upload/28d03b185ed64753be8c784f8fc1cfc6.pdf');

   //          $handle = fopen(FCPATH . 'upload/28d03b185ed64753be8c784f8fc1cfc6.pdf', "r");

   // echo $handle;

        $this->load->helper('url');
        $level1data="";
        if(!empty($this->uri->segment(3))){
            $level1data = $this->uri->segment(3);  
        }
 
            $data['showfileList']=$this->file_model->getFiledataByid($level1data);    

            header('Content-type: application/pdf');
            header('Content-Disposition: inline; filename="document"');
            header('Content-Transfer-Encoding: binary');
            header('Accept-Ranges: bytes');
             // @readfile('upload/28d03b185ed64753be8c784f8fc1cfc6.pdf');
             @readfile('upload/'.$data['showfileList']->name);

        }
        public function ppurl(){
            // $this->load->helper('url');
            $this->load->helper('url');
            $level1data="";
            if(!empty($this->uri->segment(3))){
                $level1data = $this->uri->segment(3);  
            }
 
            $data['showfileList']=$this->file_model->getFiledataByid($level1data);    

            header('Content-type: application/vnd.oasis.opendocument.presentation');
            header('Content-Disposition: inline; filename="document"');
            header('Content-Transfer-Encoding: binary');
            header('Accept-Ranges: bytes');
             // @readfile('upload/28d03b185ed64753be8c784f8fc1cfc6.pdf');
             @readfile('upload/'.$data['showfileList']->name);

    

        }//    


        public function signin(){
                // echo "sigin";
                // $this->successpage();
                $userName= trim($this->input->post('userName'));
                $password= trim($this->input->post('password'));
                // echo $userName;
                // echo $password;
                $query = $this->backenduser_model->processLogin($userName,$password);
                // $query2 = $query->result();
                // echo "login";
                // echo  $query2[0]->login;
                // echo "num row";
                // echo $query->num_rows();
                // $this->form_validation->set_rules('userName', '名稱', 'required|callback_validateUser[' . $query->num_rows() . ']');
                // $this->form_validation->set_rules('password', '密碼', 'required');
                
                // $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
                // $this->form_validation->set_message('validateUser', '錯誤名稱或密碼');
                // $this->form_validation->set_message('required', '請輸入 %s');
                
                //echo query result
              
                //end echo query result

                
                if (empty($userName)|| empty($password) || ($query->num_rows()!=1)) {
                        $data['msg']="登入名稱或密碼錯誤";
                        $this->load->view('testview',$data);
                        
                        // echo "testview";
                }else{
                        if($query){
                                $query = $query->result();
                                $user = array(
                                'USER_ID' => $query[0]->id,
                                'USER_NAME' => $query[0]->login,
                                'FULL_NAME' => $query[0]->fullName
                                
                                );
                        
                        $this->session->set_userdata($user);
                        // redirect('index.php/successpage');
                                $this->successpage();
                                // echo "success";
                        }
                }

        }//public function signin(){
        public function test2()
	{
        //$this->load->view('welcome_message');
        $this->load->view('test1');
        // $contactusdata = $this->contactdetails_model->getContactus();
        //     $this->breadcrumbs[] = array (
        //         'label' => '聯絡我們',
        //         'link' => ''
        //     );
        //     $this->twig->display('main', array(
        //         'path' => array(
        //             'vendor' => $this->config->item('vendor_path'),
        //             'script' => $this->config->item('script_path'),
        //             'css' => $this->config->item('css_path'),
        //             'image' => $this->config->item('image_path')
        //         ),
        //         'breadcrumbs' => $this->breadcrumbs,
        //         'menus' => $this->menu,
        //         'contactusdata'=>$contactusdata,
        //         'session' => 'contact',
        //         'contactus' => $this->contactus,
        //         'page' => 'index'
        //     ));
        }
}
