<?php

require_once('database.php');

class User
{
    public  $db;
    private $user_id;
    private $path = 'uploads';

    private $timezones = array(
        '(GMT-12:00) International Date Line West' => 'Pacific/Wake',
        '(GMT-11:00) Midway Island' => 'Pacific/Apia',
        '(GMT-11:00) Samoa' => 'Pacific/Apia',
        '(GMT-10:00) Hawaii' => 'Pacific/Honolulu',
        '(GMT-09:00) Alaska' => 'America/Anchorage',
        '(GMT-08:00) Pacific Time (US &amp; Canada); Tijuana' => 'America/Los_Angeles',
        '(GMT-07:00) Arizona' => 'America/Phoenix',
        '(GMT-07:00) Chihuahua' => 'America/Chihuahua',
        '(GMT-07:00) La Paz' => 'America/Chihuahua',
        '(GMT-07:00) Mazatlan' => 'America/Chihuahua',
        '(GMT-07:00) Mountain Time (US &amp; Canada)' => 'America/Denver',
        '(GMT-06:00) Central America' => 'America/Managua',
        '(GMT-06:00) Central Time (US &amp; Canada)' => 'America/Chicago',
        '(GMT-06:00) Guadalajara' => 'America/Mexico_City',
        '(GMT-06:00) Mexico City' => 'America/Mexico_City',
        '(GMT-06:00) Monterrey' => 'America/Mexico_City',
        '(GMT-06:00) Saskatchewan' => 'America/Regina',
        '(GMT-05:00) Bogota' => 'America/Bogota',
        '(GMT-05:00) Eastern Time (US &amp; Canada)' => 'America/New_York',
        '(GMT-05:00) Indiana (East)' => 'America/Indiana/Indianapolis',
        '(GMT-05:00) Lima' => 'America/Bogota',
        '(GMT-05:00) Quito' => 'America/Bogota',
        '(GMT-04:00) Atlantic Time (Canada)' => 'America/Halifax',
        '(GMT-04:00) Caracas' => 'America/Caracas',
        '(GMT-04:00) La Paz' => 'America/Caracas',
        '(GMT-04:00) Santiago' => 'America/Santiago',
        '(GMT-03:30) Newfoundland' => 'America/St_Johns',
        '(GMT-03:00) Brasilia' => 'America/Sao_Paulo',
        '(GMT-03:00) Buenos Aires' => 'America/Argentina/Buenos_Aires',
        '(GMT-03:00) Georgetown' => 'America/Argentina/Buenos_Aires',
        '(GMT-03:00) Greenland' => 'America/Godthab',
        '(GMT-02:00) Mid-Atlantic' => 'America/Noronha',
        '(GMT-01:00) Azores' => 'Atlantic/Azores',
        '(GMT-01:00) Cape Verde Is.' => 'Atlantic/Cape_Verde',
        '(GMT 0:00) Casablanca' => 'Africa/Casablanca',
        '(GMT 0:00) Edinburgh' => 'Europe/London',
        '(GMT 0:00) Greenwich Mean Time : Dublin' => 'Europe/London',
        '(GMT 0:00) Lisbon' => 'Europe/London',
        '(GMT 0:00) London' => 'Europe/London',
        '(GMT 0:00) Monrovia' => 'Africa/Casablanca',
        '(GMT+01:00) Amsterdam' => 'Europe/Berlin',
        '(GMT+01:00) Belgrade' => 'Europe/Belgrade',
        '(GMT+01:00) Berlin' => 'Europe/Berlin',
        '(GMT+01:00) Bern' => 'Europe/Berlin',
        '(GMT+01:00) Bratislava' => 'Europe/Belgrade',
        '(GMT+01:00) Brussels' => 'Europe/Paris',
        '(GMT+01:00) Budapest' => 'Europe/Belgrade',
        '(GMT+01:00) Copenhagen' => 'Europe/Paris',
        '(GMT+01:00) Ljubljana' => 'Europe/Belgrade',
        '(GMT+01:00) Madrid' => 'Europe/Paris',
        '(GMT+01:00) Paris' => 'Europe/Paris',
        '(GMT+01:00) Prague' => 'Europe/Belgrade',
        '(GMT+01:00) Rome' => 'Europe/Berlin',
        '(GMT+01:00) Sarajevo' => 'Europe/Sarajevo',
        '(GMT+01:00) Skopje' => 'Europe/Sarajevo',
        '(GMT+01:00) Stockholm' => 'Europe/Berlin',
        '(GMT+01:00) Vienna' => 'Europe/Berlin',
        '(GMT+01:00) Warsaw' => 'Europe/Sarajevo',
        '(GMT+01:00) West Central Africa' => 'Africa/Lagos',
        '(GMT+01:00) Zagreb' => 'Europe/Sarajevo',
        '(GMT+02:00) Athens' => 'Europe/Istanbul',
        '(GMT+02:00) Bucharest' => 'Europe/Bucharest',
        '(GMT+02:00) Cairo' => 'Africa/Cairo',
        '(GMT+02:00) Harare' => 'Africa/Johannesburg',
        '(GMT+02:00) Helsinki' => 'Europe/Helsinki',
        '(GMT+02:00) Istanbul' => 'Europe/Istanbul',
        '(GMT+02:00) Jerusalem' => 'Asia/Jerusalem',
        '(GMT+02:00) Kyiv' => 'Europe/Helsinki',
        '(GMT+02:00) Minsk' => 'Europe/Istanbul',
        '(GMT+02:00) Pretoria' => 'Africa/Johannesburg',
        '(GMT+02:00) Riga' => 'Europe/Helsinki',
        '(GMT+02:00) Sofia' => 'Europe/Helsinki',
        '(GMT+02:00) Tallinn' => 'Europe/Helsinki',
        '(GMT+02:00) Vilnius' => 'Europe/Helsinki',
        '(GMT+03:00) Baghdad' => 'Asia/Baghdad',
        '(GMT+03:00) Kuwait' => 'Asia/Riyadh',
        '(GMT+03:00) Moscow' => 'Europe/Moscow',
        '(GMT+03:00) Nairobi' => 'Africa/Nairobi',
        '(GMT+03:00) Riyadh' => 'Asia/Riyadh',
        '(GMT+03:00) St. Petersburg' => 'Europe/Moscow',
        '(GMT+03:00) Volgograd' => 'Europe/Moscow',
        '(GMT+03:30) Tehran' => 'Asia/Tehran',
        '(GMT+04:00) Abu Dhabi' => 'Asia/Muscat',
        '(GMT+04:00) Baku' => 'Asia/Tbilisi',
        '(GMT+04:00) Muscat' => 'Asia/Muscat',
        '(GMT+04:00) Tbilisi' => 'Asia/Tbilisi',
        '(GMT+04:00) Yerevan' => 'Asia/Tbilisi',
        '(GMT+04:30) Kabul' => 'Asia/Kabul',
        '(GMT+05:00) Ekaterinburg' => 'Asia/Yekaterinburg',
        '(GMT+05:00) Islamabad' => 'Asia/Karachi',
        '(GMT+05:00) Karachi' => 'Asia/Karachi',
        '(GMT+05:00) Tashkent' => 'Asia/Karachi',
        '(GMT+05:30) Chennai' => 'Asia/Calcutta',
        '(GMT+05:30) Kolkata' => 'Asia/Calcutta',
        '(GMT+05:30) Mumbai' => 'Asia/Calcutta',
        '(GMT+05:30) New Delhi' => 'Asia/Calcutta',
        '(GMT+05:45) Kathmandu' => 'Asia/Katmandu',
        '(GMT+06:00) Almaty' => 'Asia/Novosibirsk',
        '(GMT+06:00) Astana' => 'Asia/Dhaka',
        '(GMT+06:00) Dhaka' => 'Asia/Dhaka',
        '(GMT+06:00) Novosibirsk' => 'Asia/Novosibirsk',
        '(GMT+06:00) Sri Jayawardenepura' => 'Asia/Colombo',
        '(GMT+06:30) Rangoon' => 'Asia/Rangoon',
        '(GMT+07:00) Bangkok' => 'Asia/Bangkok',
        '(GMT+07:00) Hanoi' => 'Asia/Bangkok',
        '(GMT+07:00) Jakarta' => 'Asia/Bangkok',
        '(GMT+07:00) Krasnoyarsk' => 'Asia/Krasnoyarsk',
        '(GMT+08:00) Beijing' => 'Asia/Hong_Kong',
        '(GMT+08:00) Chongqing' => 'Asia/Hong_Kong',
        '(GMT+08:00) Hong Kong' => 'Asia/Hong_Kong',
        '(GMT+08:00) Irkutsk' => 'Asia/Irkutsk',
        '(GMT+08:00) Kuala Lumpur' => 'Asia/Kuala_Lumpur',
        '(GMT+08:00) Perth' => 'Australia/Perth',
        '(GMT+08:00) Singapore' => 'Asia/Singapore',
        '(GMT+08:00) Taipei' => 'Asia/Taipei',
        '(GMT+08:00) Ulaan Bataar' => 'Asia/Irkutsk',
        '(GMT+08:00) Urumqi' => 'Asia/Hong_Kong',
        '(GMT+09:00) Osaka' => 'Asia/Tokyo',
        '(GMT+09:00) Sapporo' => 'Asia/Tokyo',
        '(GMT+09:00) Seoul' => 'Asia/Seoul',
        '(GMT+09:00) Tokyo' => 'Asia/Tokyo',
        '(GMT+09:00) Yakutsk' => 'Asia/Yakutsk',
        '(GMT+09:30) Adelaide' => 'Australia/Adelaide',
        '(GMT+09:30) Darwin' => 'Australia/Darwin',
        '(GMT+10:00) Brisbane' => 'Australia/Brisbane',
        '(GMT+10:00) Canberra' => 'Australia/Sydney',
        '(GMT+10:00) Guam' => 'Pacific/Guam',
        '(GMT+10:00) Hobart' => 'Australia/Hobart',
        '(GMT+10:00) Melbourne' => 'Australia/Sydney',
        '(GMT+10:00) Port Moresby' => 'Pacific/Guam',
        '(GMT+10:00) Sydney' => 'Australia/Sydney',
        '(GMT+10:00) Vladivostok' => 'Asia/Vladivostok',
        '(GMT+11:00) Magadan' => 'Asia/Magadan',
        '(GMT+11:00) New Caledonia' => 'Asia/Magadan',
        '(GMT+11:00) Solomon Is.' => 'Asia/Magadan',
        '(GMT+12:00) Auckland' => 'Pacific/Auckland',
        '(GMT+12:00) Fiji' => 'Pacific/Fiji',
        '(GMT+12:00) Kamchatka' => 'Pacific/Fiji',
        '(GMT+12:00) Marshall Is.' => 'Pacific/Fiji',
        '(GMT+12:00) Wellington' => 'Pacific/Auckland',
        '(GMT+13:00) Nuku alofa' => 'Pacific/Tongatapu',
    );


    function __construct()
    {
        $this->db = db::Instance();
        $this->user_id = empty($_SESSION['far_user_id']) ? 0 : (int)$_SESSION['far_user_id'];
    }

    public function userid(){
        return $this->user_id;
    }

    public function get_user()
    {
        if(isset($_SESSION['far_user_id'])){
            $user = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users WHERE id = ".(int)$_SESSION['far_user_id']);
            if(empty($user)){
                return false;
            }else{
                $_SESSION['far_user'] = $user;
                return $user;
            }
        }else{
            return false;
        }
    }

    public function is_admin()
    {
        if(isset($_SESSION['far_user_id'])){
            $user = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users WHERE id = ".(int)$_SESSION['far_user_id']);
            return $user['is_admin'];
        }else{
            return false;
        }
    }

    public function getAppSettings()
    {
        $result = false;
        $settings = $this->db->select("SELECT * FROM ".DB_TABLE_PREFIX."global_config");
        if(!empty($settings))
            foreach($settings as $param){
                $result[$param['param']] = $param['value'];
            }

        return $result;
    }

    public function getUserSettings($user_id = 0)
    {
        if($user_id == 0){
            $user_id = $this->user_id;
        }

        if($user_id != $this->user_id && !$this->is_admin()){
            $user_id = $this->user_id;
        }

        $settings = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users u WHERE u.id = '".$user_id."'");
        return $settings;
    }

    public function auth($username, $password)
    {
        $user = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users u WHERE u.email = '".$this->db->clearInput($username)."'");
        if(empty($user))
            return false;

        if($user['status'] == 0)
            return false;

        if($user['password'] != sha1($password))
            return false;

        $_SESSION['far_user_id'] = $user['id'];

        return true;
    }

    public function fb_logout()
    {

    }

    public function timezones()
    {
        $list = array();
        foreach($this->timezones as $key => $value)
        {
            $list[$value] = $key.' - '.$this->mdate("%h:%i %a", $this->timestamp($value));
        }

        return $list;
    }

    public function timestamp($gmt_zone = 0)
    {

        if(empty($gmt_zone) && $this->user_id)
        {
            $user_tmp = $this->db->selectOne("SELECT timezone FROM ".DB_TABLE_PREFIX."users WHERE id='".$this->user_id."'");
            $gmt_zone = empty($user_tmp['timezone']) ? 0 : $user_tmp['timezone'];
        }

        if($gmt_zone == '0'){
            $gmt_zone = "Europe/London";
        }

        $timezone = new DateTimeZone($gmt_zone);
        $offset   = $timezone->getOffset(new DateTime("now"));

        return strtotime(gmdate("M d Y H:i:s", time())) + $offset;
    }

    private function mdate($datestr = '', $time = '')
    {
        if ($datestr == '')
            return '';

        if ($time == '')
            $time = now();

        $datestr = str_replace('%\\', '', preg_replace("/([a-z]+?){1}/i", "\\\\\\1", $datestr));
        return date($datestr, $time);
    }

    public function set_fb_app($app_id, $app_secret)
    {
        $settings = $this->getUserSettings();
        $upd_data['app_id']     = $app_id;
        $upd_data['app_secret'] = $app_secret;

        if(empty($settings['id'])){
            $upd_data['id_user']    = $this->user_id;
            $this->db->insert(DB_TABLE_PREFIX.'users',$upd_data);
        }else{
            $this->db->update(DB_TABLE_PREFIX.'users',$upd_data,$settings['id']);
        }
    }

    private function get_cron_last_run(){
        $cron = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."global_config WHERE `param` = 'last_cron_run'");
        if(empty($cron['value']))
            return 0;

        return $cron['value'];
    }

    public function get_cron_info()
    {
        $last_run           = $this->get_cron_last_run();
        $timestamp          = $this->timestamp('');

        if($last_run){
            $time_zone = $this->get_user_timezone();

            $last_run = $this->convert_to_timezone($last_run, 'Europe/London', $time_zone['zone']);

            $data['last_cron_run']  = $last_run;
            if($timestamp - $last_run <= 300){
                $data['class']      = 'success';
                $data['message']    = 'Cron job is running successfully. Last time it ran at ' . date('H:i',$last_run) . ' on ' . date('d/m/Y',$last_run);
            }else{
                $data['class']      = 'danger';
                $data['message']    = 'Last time cron job ran at ' . date('H:i',$last_run) . ' on ' . date('d/m/Y',$last_run);
            }
        }else{
            $data['class']      = 'danger';
            $data['message']    = 'System did not detect cron job. Please make sure cron job is set up correctly. <br> (Url for cron job : ' . baseUrl('cron.php') . ')';
        }

        return $data;
    }

    function convert_to_timezone($timestamp, $from_timezone, $to_timezone)
    {
        if($from_timezone == $to_timezone)
            return $timestamp;

        $date = date_create(date('Y-m-d H:i:s',$timestamp), timezone_open($from_timezone));
        date_timezone_set($date, timezone_open($to_timezone));

        return strtotime(date_format($date, 'Y-m-d H:i:s'));
    }

    function get_user_timezone()
    {
        $timezone = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users WHERE id = ".$this->user_id);
        if(empty($timezone))
            $timezone = 'Europe/London';
        else
            $timezone = $timezone['timezone'];

        $result = array('gmt' => '', 'zone' => '');
        foreach($this->timezones as $key => $value)
        {
            if($value == $timezone){
                $result['zone'] = $value;
                $result['gmt']  = $key;
            }
        }

        if(strpos($result['gmt'],')') > 0){
            $result['gmt_zone'] = substr($result['gmt'],0,strpos($result['gmt'],')'));
            $result['gmt_zone'] = trim($result['gmt_zone']);
            $result['gmt_zone'] = trim($result['gmt_zone'],'(');
            $result['gmt_zone'] = trim($result['gmt_zone'],'');
        }else {
            $result['gmt_zone'] = 'GMT 0:00';
        }

        return $result;
    }

    public function check_username($username)
    {
        $users = $this->db->select("SELECT * FROM ".DB_TABLE_PREFIX."users u WHERE u.id <> ".$this->user_id." AND u.name = '".$this->db->clearInput($username)."'");
        if(empty($users))
            return true;
        else
            return false;
    }

    public function check_email($email, $any = false, $user_id = 0)
    {
        if($user_id == 0 && !$any)
            $user_id = $this->user_id;

        $users = $this->db->select("SELECT * FROM ".DB_TABLE_PREFIX."users u WHERE u.id <> ".$user_id." AND u.email = '".$this->db->clearInput($email)."'");
        if(empty($users))
            return true;
        else
            return false;
    }

    public function get_user_by_email($email)
    {
        $email = $this->db->clearInput($email);
        $user = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users WHERE `email` = '".$email."'");
        if(empty($user))
            return false;
        else
            return $user;
    }

    public function get_user_by_token($token)
    {
        $token = $this->db->clearInput($token);
        $user = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users WHERE `token` = '".$token."'");
        if(empty($user))
            return false;
        else
            return $user;
    }

    public function change_password($password)
    {
        $upd_data['password'] = sha1($password);
        $this->db->update(DB_TABLE_PREFIX.'users',$upd_data,$this->user_id);
    }

    public function change_user_data($upd_data)
    {
        $this->db->update(DB_TABLE_PREFIX.'users',$upd_data,$this->user_id);
        return $this->get_user();
    }

    public function set_general_settings($upd_data)
    {
        $gen_settings = $this->getAppSettings();
        if(!isset($gen_settings[$upd_data['param']])){
            $this->db->insert(DB_TABLE_PREFIX.'global_config',$upd_data);
        }else{
            $this->db->update(DB_TABLE_PREFIX.'global_config',$upd_data,$upd_data['param'],'param');
        }
    }

    public function getAllUsers($username, $status)
    {
        $where_admin    = " AND u.id = '".$this->user_id."'";
        $where_username = "";
        $where_status   = "";

        if($this->is_admin() > 0)
            $where_admin = " AND u.is_admin <= '" . $this->is_admin()."' ";

        if($username != ''){
            $where_username = " AND (lower(u.name) like '%".$this->db->clearInput(strtolower($username))."%' OR lower(u.fb_user_name) like '%".$this->db->clearInput(strtolower($username))."%' OR lower(u.email) like '%".$this->db->clearInput(strtolower($username))."%')";
        }

        if($status != 'all'){
            $where_status = " AND u.status = '".(int)$status."'";
        }

        $all_users = $this->db->select("SELECT * FROM ".DB_TABLE_PREFIX."users u WHERE 1=1".$where_admin.$where_username.$where_status);

        return $all_users;
    }

    public function delete_user($user_id)
    {
        $user_id = (int)$user_id;

        if(!$this->is_admin()){
            return false;
        }else{
            $this->db->delete(DB_TABLE_PREFIX.'users', $user_id);
            return true;
        }
    }

    public function change_status($user_id)
    {
        $user_id = (int)$user_id;
        if(!$this->is_admin()){
            return false;
        }else{
            $this->db->query("UPDATE ".DB_TABLE_PREFIX."users SET `status` = (`status` + 1) % 2 WHERE id = '".$user_id."'");
            return true;
        }

    }

    public function create($name, $email, $password, $rpassword, $fb_pages_limit = 1, $timezone = 'Europe/London', $id = 0)
    {
        $result = array();
        if($name == ''){
            $result['error'] = "Field Name is required.";
        }

        if($email == ''){
            $result['error'] = "Field Email is required.";
        }

        if(!FILTER_VAR($email,FILTER_VALIDATE_EMAIL)){
            $result['error'] = "Email is not valid.";
        }

        if($id == 0) {
            if ($password == '') {
                $result['error'] = "Password can not be empty.";
            }

            if ($password != $rpassword) {
                $result['error'] = "Passwords mismatch.";
            }

            if (!$this->check_email($email, true)) {
                $result['error'] = "Email already in use.";
            }
        }else{
            if($password != '' || $rpassword != ''){
                if ($password == '') {
                    $result['error'] = "Password can not be empty.";
                }

                if ($password != $rpassword) {
                    $result['error'] = "Passwords mismatch.";
                }
            }

            if (!$this->check_email($email, false, $id)) {
                $result['error'] = "Email already in use.";
            }
        }

        if(empty($result['error'])) {
            $result['success']      = true;

            $ins_data['name']       = $name;
            $ins_data['email']      = $email;
            $ins_data['is_admin']   = 0;
            $ins_data['status']     = 1;
            $ins_data['timezone']   = $timezone;
            $ins_data['fb_pages_limit'] = $fb_pages_limit;

            if($id == 0) {
                $ins_data['password']   = sha1($password);
                $ins_data['created_at'] = $this->timestamp('Europe/London');
                $this->db->insert(DB_TABLE_PREFIX . 'users', $ins_data);
            }else{
                if($password != '')
                    $ins_data['password']   = sha1($password);
                $this->db->update(DB_TABLE_PREFIX.'users',$ins_data,$id);
            }
        }

        return $result;
    }

    public function set_user($user_data, $id = 0)
    {
        $user_data['created_at'] = $this->timestamp('Europe/London');
        if($id == 0){
            $this->db->insert(DB_TABLE_PREFIX.'users',$user_data);
        }else{
            $this->db->update(DB_TABLE_PREFIX.'users',$user_data,$id);
        }
    }

    public function get_user_data($id)
    {
        $user = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."users WHERE id = '".(int)$id."'");
        return $user;
    }

    public function check_activation(){
        $activation = $this->db->selectOne("SELECT * FROM ".DB_TABLE_PREFIX."license");
        if(empty($activation))
            return false;

        if(base64_decode($activation['key']) != 'activation_key')
            return false;

        return true;
    }

    public function activate($key, $license)
    {
        $errors_activation = "";
        if($key == "trial" && $license == "trial"){
            $activation = $this->db->selectOne(DB_TABLE_PREFIX.'license');
            if(empty($activation['id'])){
                $data['key']    = base64_encode('activation_key');
                $data['value']  = $_POST['activation_key'];
                $this->db->insert(DB_TABLE_PREFIX.'license',$data);
            }else{
                $data['key']    = base64_encode('activation_key');
                $data['value']  = $license;
                $this->db->update(DB_TABLE_PREFIX.'license',$data,$activation['id']);
            }

            return array('success' => 'Activated');
        }

        $ch = curl_init();
        $domain = $_SERVER['HTTP_HOST'];
        $productid = PRODUCTID;
        curl_setopt($ch, CURLOPT_URL,"http://henoz.com/dev/ali/autoresponder/envatoapi/index.php");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,"activation_key=$key&licence=$license&domain=$domain&productid=$productid");
        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $server_output = curl_exec ($ch);
        $server_response = json_decode($server_output);

        if(empty($server_response) && !empty($server_output)){
            return $server_output;
        }

        if ($server_response->success) {
            $activation = $this->db->selectOne(DB_TABLE_PREFIX.'license');
            if(empty($activation['id'])){
                $data['key']    = base64_encode('activation_key');
                $data['value']  = $key;
                $this->db->insert(DB_TABLE_PREFIX.'license',$data);
            }else{
                $data['key']    = base64_encode('activation_key');
                $data['value']  = $key;
                $this->db->update(DB_TABLE_PREFIX.'license',$data,$activation['id']);
            }
            return array('success' => $server_response->msg);
        }else{
            // There is some sort of error with key
            $errors_activation = $server_response->msg;
        }

        curl_close ($ch);

        return array('error' => $errors_activation);
    }

    public function send_mail($to, $subject, $message, $from = 'support@henoz.com')
    {
        $headers = 'From: '. $from . "\r\n" .
            'Reply-To: webmaster@example.com' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

        mail($to, $subject, $message, $headers);
        return true;
    }

    public function update_user_data($data, $user_id)
    {
        $this->db->update(DB_TABLE_PREFIX.'users',$data,$user_id);
    }

    public function generate_random_string($len){
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $token = "";
        $chars_length = (strlen($chars) - 1);

        for($i=1; $i<=$len; $i++){
            $r = $chars{rand(0, $chars_length)};
            $token .= $r;
        }

        return $token;
    }

    public function upload_file($file)
    {
        $result = false;
        if($file['size'] > 0){
            $file_name = $this->path . '/' . $this->user_id . time();
            if(@move_uploaded_file($file['tmp_name'],$file_name)){
                $result = $file_name;
            }
        }

        return $result;
    }

    public function file_upload_max_size() {
        static $max_size = -1;

        if ($max_size < 0) {
            // Start with post_max_size.
            $max_size = $this->parse_size(ini_get('post_max_size'));

            // If upload_max_size is less, then reduce. Except if upload_max_size is
            // zero, which indicates no limit.
            $upload_max = $this->parse_size(ini_get('upload_max_filesize'));
            if ($upload_max > 0 && $upload_max < $max_size) {
                $max_size = $upload_max;
            }
        }
        return $max_size;
    }

    private function parse_size($size) {
        $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
        $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
        if ($unit) {
            // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
            return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
        }
        else {
            return round($size);
        }
    }

    public function check_db1()
    {
        $columns = $this->db->select("SHOW COLUMNS FROM ".DB_TABLE_PREFIX."user_groups");
        $need_change = false;
        if(!empty($columns))
            foreach($columns as $column)
            {
                if($column['Field'] == 'groups' && $column['Type'] != 'longtext'){
                    $need_change = true;
                }
            }

        if($need_change) {
            $delete = "ALTER TABLE `" . DB_TABLE_PREFIX . "user_groups`   DROP COLUMN `groups`;";
            $add = "ALTER TABLE `" . DB_TABLE_PREFIX . "user_groups` ADD COLUMN `groups` LONGTEXT NULL AFTER `user_id`;";

            $this->db->query($delete);
            $this->db->query($add);
        }
    }
}