<?php
defined('BASEPATH') or exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{

    public $is_mobile;

    public function __construct()
    {
        parent::__construct();

        $this->load->config('yggconfig');
        $this->load->library(array('Mobile_Detect', 'pagination', 'recaptcha', 'user_agent'));
        $this->load->helper('string', 'tools');
        $this->load->model(array('users_model' => 'users', 'torrents_model' => 'torrents'));
        $this->load->driver('cache');

        $md = new Mobile_Detect();
        $this->is_mobile = $md->isMobile() || $md->isTablet() || $md->isAndroidOS();

        $full_segment = $this->uri->segment(1) . '/' . $this->uri->segment(2);

        $this->form_validation->set_error_delimiters('<span class="error-form">', '</span>');

        if ($this->session->logged) {

            if (!$this->session->phantom) {
                //$this->db->query('UPDATE users SET last_activity_date = ' . now() . ' WHERE id = ' . $this->session->id . ' ');
            }
            $data_user = $this->db->select('email, id, forum_id, premium_until, adult_content_banned, is_donator, tracker_id, settings, unread_pm, torrent_pass, join_date, end_freeleech, age, notified, rank, notifications, sanctions, status_auto_messages, uploaded, downloaded, download_multiplier, can_leech')->where('id', $this->session->id)->get('users')->row_array();
        
            $settings = json_decode($data_user['settings'], JSON_OBJECT_AS_ARRAY);
            
            if (
                (isset($data_user['adult_content_banned']) && $data_user['adult_content_banned'] == 1) ||
                ($data_user['id'] > 13358103)
            ) {
                //$data_user['adult_content_banned'] = true;
                //$settings['enable_at_content'] = false;

                $data_user['adult_content_banned'] = false;
            }
            
            $data_user['settings'] = $settings;
            $this->session->set_userdata($data_user);
            

            if (!$this->session->phantom) {
                // Check session
                $sanctions = (array) json_decode($this->session->sanctions);

                // Si le mec est ban
                $diffUpdateLeech = now() - (int) $this->session->check_redir_disabled;

                if (array_key_exists('sanction_5', $sanctions)) {
                    if ($sanctions['sanction_5'] > now() || $sanctions['sanction_5'] == 'oo') {
                        if ($sanctions['sanction_5'] == 'oo') {
                            $resp['duration'] = 'Jamais';
                        } else {
                            $diff = $sanctions['sanction_5'] - now();
                            $dtF = new \\DateTime('@0');
                            $dtT = new \\DateTime("@$diff");
                            $resp['duration'] = $dtF->diff($dtT)->format('%a jours, %h heures, %i minutes et %s secondes');
                        }
                        $resp['reason_key'] = $this->encrypt($this->session->id);
                        $this->session->set_flashdata('banned_account', $resp);
                        if ($this->uri->segment(1)) {
                            redirect(base_url());
                        } else {
                            $this->session->sess_destroy();
                        }
                    }
                } else if ($this->session->upgrade_security == true) {
                    if ($full_segment != 'user/upgrade_security' && $full_segment != 'user/logout') {
                        redirect('/user/upgrade_security');
                    }
                } else if ($this->session->can_leech == 0) {
                    if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
                        if ($full_segment != 'user/ajax_usermenu' && $full_segment != 'user/ajax_notifications') {
                            $segs = array('user/disabled', 'user/donate', 'user/disabled', 'user/create_donation_bill', 'donation/bonus', 'donation/create_order', 'donation/buy_crypto', 'donation/wp_processor_limit', 'user/logout');
                            if (!in_array($full_segment, $segs) && $this->session->rank == 0) {
                                redirect(base_url() . 'donation/bonus');
                            }
                        }
                    }
                    /*  if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
                          if ($full_segment != 'user/ajax_usermenu' && $full_segment != 'user/ajax_notifications') {
                              $segs = array('user/disabled', 'user/donate', 'user/disabled', 'user/create_donation_bill', 'donation/bonus', 'donation/create_order');
                              if (in_array($full_segment, $segs)) {
                                  $this->session->check_redir_disabled = now();
                              }
                              if ($diffUpdateLeech > 180 && in_array($full_segment, $segs) == false) {
                                  redirect('/donation/bonus');
                              }
                          }
                      }**/
                }
            }

            $diffUpdate = now() - (int) $this->session->check_rank_uploader;

            if ($diffUpdate > 1800 && in_array($this->session->rank, array('0', '4'))) {
                $num_uploads = $this->db->select('id')->where('uploader', $this->session->id)->get('torrents')->num_rows();

                if ($num_uploads >= 15 && $this->session->uploaded >= 268435318500) {
                    $this->db->set('rank', 4)->where('id', $this->session->id)->update('users');
                    $this->session->rank = 4;
                    $this->session->check_rank_uploader = now();
                } else {
                    $this->db->set('rank', 0)->where('id', $this->session->id)->update('users');
                    $this->session->rank = 0;
                    $this->session->check_rank_uploader = now();
                }
            }
        } else {
            if (!in_array($this->uri->segment(1), ['api', 'reseller', 'auth', 'user', 'pages', 'privacy', 'copyright', 'payment_api', 'ipn'])) {
                redirect('/auth/login');
            }
        }
    }

    protected function show_error($error_msg, $error_code = 403)
    {
        $this->output->set_content_type('application/json')->set_output(json_encode(array('error' => $error_msg)))->set_status_header($error_code)->_display();
        die();
    }

    protected function show_json($message)
    {
        $this->output->set_content_type('application/json')->set_output(json_encode(array('message' => $message)))->_display();
        die();
    }

    public function get_col_index($column_name)
    {
        $cols = array(
            'type' => 0,
            'name' => 1,
            'nfo' => 2,
            'comments' => 3,
            'publish_date' => 4,
            'size' => 5,
            'completed' => 6,
            'seed' => 7,
            'leech' => 8,
        );
        return empty($column_name) ? $cols['publish_date'] : $cols[$column_name];
    }

    protected function getSettings($setting = false)
    {
        if (!$this->cache->file->get('global_settings')) {
            $settingsdb = $this->db->select('*')->from('settings')->get()->result();
            $settings = array();
            foreach ($settingsdb as $s) {
                $settings[$s->name] = json_decode($s->value);
            }
            $this->cache->file->save('global_settings', $settings, 1800);
        } else {
            $settings = $this->cache->file->get('global_settings');
        }
        return !$setting ? $settings : $settings[$setting];
    }

    protected function encrypt($k = '', $action = 'encrypt')
    {
        $key = $this->config->item('encryption_key');
        $key = hash('sha256', $key);
        $e = md5($key);
        $i = substr(hash('sha256', $e), 0, 16);
        $o = openssl_encrypt($k, 'AES-256-CBC', $key, 0, $i);
        $o = base64_encode($o);
        return $action == 'encrypt' ? base64_encode(openssl_encrypt($k, 'AES-256-CBC', $key, 0, $i)) : openssl_decrypt(base64_decode($k), 'AES-256-CBC', $key, 0, $i);
    }

    protected function getSettingsOffCache($setting = false)
    {
        $settingsdb = $this->db->select('*')->from('settings')->get()->result();
        $settings = array();
        foreach ($settingsdb as $s) {
            $settings[$s->name] = json_decode($s->value);
        }
        return !$setting ? $settings : $settings[$setting];
    }

    protected function _escape($string)
    {
        if ((gettype($string) == 'integer') || (gettype($string) == 'double') || (gettype($string) == 'boolean') || (gettype($string) == 'NULL')) {
            return $string;
        } else {
            $string = strip_tags($string);
            $string = trim($string);
            $from = array('\\\\', '(', ')', '|', '-', '!', '@', '~', '"', '&', '/', '^', '$', '=', ';', '\\'');
            $to = array('\\\\\\\\', '\\(', '\\)', '\\|', '\\-', '\\!', '\\@', '\\~', '\\"', '\\&', '\\/', '\\^', '\\$', '\\=', '\\;', '\\\\\\'');
            $string = str_replace($from, $to, $string);
            $string = str_replace(array("\\r", "\\r\
", "\
"), ' ', $string);
            $string = preg_replace('/(?:(?)|(?))(\\s+)(?=\\<\\/?)/', ' ', $string);
            return "\\"" . (string) $string . "\\"";
        }
    }

    protected function _get_pagination_config()
    {
        $config['page_query_string'] = true;
        $config['query_string_segment'] = 'page';
        $get_vars = $this->input->get();
        unset($get_vars['page']);
        $config['first_url'] = current_url();
        $config['base_url'] = current_url();
        $config['num_links'] = 8;
        $config = array_merge($config, pagination_html());
        return $config;
    }
}
