load->helper(array('form', 'url'));
		// Load language files
		$this->lang->load('lotw');
	}
	/*
	|--------------------------------------------------------------------------
	| Function: index
	|--------------------------------------------------------------------------
	|
	| Default function for the controller which loads when doing /lotw
	| this shows all the uploaded lotw p12 certificates the user has uploaded
	|
	*/
	public function index() {
		$this->load->model('user_model');
		if(!$this->user_model->authorize(2)) { $this->session->set_flashdata('notice', 'You\'re not allowed to do that!'); redirect('dashboard'); }
		// Fire OpenSSL missing error if not found
		if (!extension_loaded('openssl')) {
			echo "You must install php OpenSSL for LoTW functions to work";
		}
		// Load required models for page generation
		$this->load->model('LotwCert');
		// Get Array of the logged in users LOTW certs.
		$data['lotw_cert_results'] = $this->LotwCert->lotw_certs($this->session->userdata('user_id'));
		// Set Page Title
		$data['page_title'] = "Logbook of the World";
		// Load Views
		$this->load->view('interface_assets/header', $data);
		$this->load->view('lotw_views/index');
		$this->load->view('interface_assets/footer');
	}
	/*
	|--------------------------------------------------------------------------
	| Function: cert_upload
	|--------------------------------------------------------------------------
	|
	| Nothing fancy just shows the cert_upload form for uploading p12 files
	|
	*/
	public function cert_upload() {
		$this->load->model('user_model');
		$this->load->model('dxcc');
		if(!$this->user_model->authorize(2)) { $this->session->set_flashdata('notice', 'You\'re not allowed to do that!'); redirect('dashboard'); }
		// Load DXCC Countrys List
		$data['dxcc_list'] = $this->dxcc->list();
		// Set Page Title
		$data['page_title'] = "Logbook of the World";
		// Load Views
		$this->load->view('interface_assets/header', $data);
		$this->load->view('lotw_views/upload_cert', array('error' => ' ' ));
		$this->load->view('interface_assets/footer');
	}
	/*
	|--------------------------------------------------------------------------
	| Function: do_cert_upload
	|--------------------------------------------------------------------------
	|
	| do_cert_upload is called from cert_upload form submit and handles uploading
	| and processing of p12 files and storing the data into mysql
	|
	*/
	public function do_cert_upload()
    {
		$this->load->model('user_model');
		$this->load->model('dxcc');
		if(!$this->user_model->authorize(2)) { $this->session->set_flashdata('notice', 'You\'re not allowed to do that!'); redirect('dashboard'); }
		// Fire OpenSSL missing error if not found
		if (!extension_loaded('openssl')) {
			echo "You must install php OpenSSL for LoTW functions to work";
		}
    	// create folder to store certs while processing
    	if (!file_exists('./uploads/lotw/certs')) {
		    mkdir('./uploads/lotw/certs', 0755, true);
		}
		$config['upload_path']          = './uploads/lotw/certs';
    	$config['allowed_types']        = 'p12';
		$this->load->library('upload', $config);
        if ( ! $this->upload->do_upload('userfile'))
        {
        	// Upload of P12 Failed
            $error = array('error' => $this->upload->display_errors());
			// Load DXCC Countrys List
			$data['dxcc_list'] = $this->dxcc->list();
			// Set Page Title
			$data['page_title'] = "Logbook of the World";
			// Load Views
			$this->load->view('interface_assets/header', $data);
			$this->load->view('lotw_views/upload_cert', $error);
			$this->load->view('interface_assets/footer');
        }
        else
        {
        	// Load database queries
        	$this->load->model('LotwCert');
        	//Upload of P12 successful
        	$data = array('upload_data' => $this->upload->data());
        	$info = $this->decrypt_key($data['upload_data']['full_path']);
			// Check to see if certificate is already in the system
			$new_certificate = $this->LotwCert->find_cert($info['issued_callsign'], $info['dxcc-id'], $this->session->userdata('user_id'));
        	if($new_certificate == 0) {
        		// New Certificate Store in Database
        		// Store Certificate Data into MySQL
        		$this->LotwCert->store_certificate($this->session->userdata('user_id'), $info['issued_callsign'], $info['dxcc-id'], $info['validFrom'], $info['validTo_Date'], $info['qso-first-date'], $info['qso-end-date'], $info['pem_key'], $info['general_cert']);
        		// Cert success flash message
        		$this->session->set_flashdata('Success', $info['issued_callsign'].' Certificate Imported.');
        	} else {
        		// Certificate is in the system time to update
				$this->LotwCert->update_certificate($this->session->userdata('user_id'), $info['issued_callsign'], $info['dxcc-id'], $info['validFrom'], $info['validTo_Date'], $info['qso-first-date'], $info['qso-end-date'], $info['pem_key'], $info['general_cert']);
        		// Cert success flash message
        		$this->session->set_flashdata('Success', $info['issued_callsign'].' Certificate Updated.');
        	}
        	// p12 certificate processed time to delete the file
        	unlink($data['upload_data']['full_path']);
			// Get Array of the logged in users LOTW certs.
			$data['lotw_cert_results'] = $this->LotwCert->lotw_certs($this->session->userdata('user_id'));
	        // Set Page Title
			$data['page_title'] = "Logbook of the World";
			// Load Views
			$this->load->view('interface_assets/header', $data);
			$this->load->view('lotw_views/index');
			$this->load->view('interface_assets/footer');
        }
    }
    /*
	|--------------------------------------------------------------------------
	| Function: lotw_upload
	|--------------------------------------------------------------------------
	|
	| This function Uploads to LOTW
	|
	*/
	public function lotw_upload() {
		$this->load->model('user_model');
		$this->user_model->authorize(2);
		// Fire OpenSSL missing error if not found
		if (!extension_loaded('openssl')) {
			echo "You must install php OpenSSL for LoTW functions to work";
		}
		// Get Station Profile Data
		$this->load->model('Stations');
		if ($this->user_model->authorize(2)) {
			$station_profiles = $this->Stations->all_of_user($this->session->userdata('user_id'));
			$sync_user_id=$this->session->userdata('user_id');
		} else {
			$station_profiles = $this->Stations->all();
			$sync_user_id=null;
		}
		// Array of QSO IDs being Uploaded
		$qso_id_array = array();
		// Build TQ8 Outputs
		if ($station_profiles->num_rows() >= 1) {
			foreach ($station_profiles->result() as $station_profile) {
				// Get Certificate Data
				$this->load->model('LotwCert');
				$data['station_profile'] = $station_profile;
				$data['lotw_cert_info'] = $this->LotwCert->lotw_cert_details($station_profile->station_callsign, $station_profile->station_dxcc);
				// If Station Profile has no LOTW Cert continue on.
				if(!isset($data['lotw_cert_info']->cert_dxcc_id)) {
					continue;
				}
				// Check if LoTW certificate itself is valid
				// Validty of QSO dates will be checked later
				$current_date = date('Y-m-d H:i:s');
				if ($current_date <= $data['lotw_cert_info']->date_created) {
					echo $data['lotw_cert_info']->callsign.": LoTW certificate not valid yet!";
					continue;
				}
				if ($current_date >= $data['lotw_cert_info']->date_expires) {
					echo $data['lotw_cert_info']->callsign.": LoTW certificate expired!";
					continue;
				}
				// Get QSOs
				$this->load->model('Logbook_model');
				$data['qsos'] = $this->Logbook_model->get_lotw_qsos_to_upload($data['station_profile']->station_id, $data['lotw_cert_info']->qso_start_date, $data['lotw_cert_info']->qso_end_date);
				// Nothing to upload
				if(empty($data['qsos']->result())){
					if ($this->user_model->authorize(2)) {	// Only be verbose if we have a session
						echo $station_profile->station_callsign." (".$station_profile->station_profile_name.") No QSOs to Upload 
";
					}
					continue;
				}
				foreach ($data['qsos']->result() as $temp_qso) {
					array_push($qso_id_array, $temp_qso->COL_PRIMARY_KEY);
				}
				// Build File to save
				$adif_to_save = $this->load->view('lotw_views/adif_views/adif_export', $data, TRUE);
				// create folder to store upload file
				if (!file_exists('./uploads/lotw')) {
					mkdir('./uploads/lotw', 0775, true);
				}
				// Build Filename
				$filename_for_saving = './uploads/lotw/'.preg_replace('/[^a-z0-9]+/', '-', strtolower($data['lotw_cert_info']->callsign))."-".date("Y-m-d-H-i-s")."-cloudlog.tq8";
				$gzdata = gzencode($adif_to_save, 9);
				$fp = fopen($filename_for_saving, "w");
				fwrite($fp, $gzdata);
				fclose($fp);
				//The URL that accepts the file upload.
				$url = 'https://lotw.arrl.org/lotw/upload';
				//The name of the field for the uploaded file.
				$uploadFieldName = 'upfile';
				//The full path to the file that you want to upload
				$filePath = realpath($filename_for_saving);
				//Initiate cURL
				$ch = curl_init();
				//Set the URL
				curl_setopt($ch, CURLOPT_URL, $url);
				//Set the HTTP request to POST
				curl_setopt($ch, CURLOPT_POST, true);
				//Tell cURL to return the output as a string.
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				//If the function curl_file_create exists
				if(function_exists('curl_file_create')){
					//Use the recommended way, creating a CURLFile object.
					$filePath = curl_file_create($filePath);
				} else{
					//Otherwise, do it the old way.
					//Get the canonicalized pathname of our file and prepend
					//the @ character.
					$filePath = '@' . realpath($filePath);
					//Turn off SAFE UPLOAD so that it accepts files
					//starting with an @
					curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
				}
				//Setup our POST fields
				$postFields = array(
					$uploadFieldName => $filePath
				);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
				//Execute the request
				$result = curl_exec($ch);
				//If an error occured, throw an exception
				//with the error message.
				if(curl_errno($ch)){
					throw new Exception(curl_error($ch));
				}
				$pos = strpos($result, "");
				if ($pos === false) {
					// Upload of TQ8 Failed for unknown reason
					echo $station_profile->station_callsign." (".$station_profile->station_profile_name.") Upload Failed"."
";
				} else {
					// Upload of TQ8 was successfull
					echo "Upload Successful - ".$filename_for_saving."
";
					$this->LotwCert->last_upload($data['lotw_cert_info']->lotw_cert_id);
					// Mark QSOs as Sent
					foreach ($qso_id_array as $qso_number) {
						$this->Logbook_model->mark_lotw_sent($qso_number);
					}
				}
				// Delete TQ8 File - This is done regardless of whether upload was succcessful
				unlink(realpath($filename_for_saving));
			}
		} else {
			echo "No Station Profiles found to upload to LOTW";
		}
			/*
			|	Download QSO Matches from LoTW
			 */
		if ($this->user_model->authorize(2)) {
			echo "
";
			$sync_user_id=$this->session->userdata('user_id');
		} else {
			$sync_user_id=null;
		}
		echo $this->lotw_download($sync_user_id);
	}
	/*
	|--------------------------------------------------------------------------
	| Function: delete_cert
	|--------------------------------------------------------------------------
	|
	| Deletes LOTW certificate from the MySQL table
	|
	*/
    public function delete_cert($cert_id) {
    	$this->load->model('user_model');
		if(!$this->user_model->authorize(2)) { $this->session->set_flashdata('notice', 'You\'re not allowed to do that!'); redirect('dashboard'); }
    	$this->load->model('LotwCert');
    	$this->LotwCert->delete_certificate($this->session->userdata('user_id'), $cert_id);
    	$this->session->set_flashdata('Success', 'Certificate Deleted.');
    	redirect('/lotw/');
    }
	/*
	|--------------------------------------------------------------------------
	| Function: decrypt_key
	|--------------------------------------------------------------------------
	|
	| Accepts p12 file and optional password and encrypts the file returning
	| the required fields for LOTW and the PEM Key
	|
	*/
	public function decrypt_key($file, $password = "") {
		$this->load->model('user_model');
		if(!$this->user_model->authorize(2)) { $this->session->set_flashdata('notice', 'You\'re not allowed to do that!'); redirect('dashboard'); }
		$results = array();
		$password = $password; // Only needed if 12 has a password set
		$filename = file_get_contents('file://'.$file);
		$worked = openssl_pkcs12_read($filename, $results, $password);
		$data['general_cert'] = $results['cert'];
		if($worked) {
			// Reading p12 successful
		    $new_password = "cloudlog"; // set default password
			$result = null;
			$worked = openssl_pkey_export($results['pkey'], $result, $new_password);
			if($worked) {
				// Store PEM Key in Array
			    $data['pem_key'] = $result;
			} else {
				// Error Log Error Message
			    log_message('error', openssl_error_string());
			    // Set warning message redirect to LOTW main page
			    $this->session->set_flashdata('Warning', openssl_error_string());
				redirect('/lotw/');
			}
		} else {
			// Reading p12 failed log error message
			log_message('error', openssl_error_string());
			// Set warning message redirect to LOTW main page
			$this->session->set_flashdata('Warning', openssl_error_string());
			redirect('/lotw/');
		}
		// Read Cert Data
		$certdata= openssl_x509_parse($results['cert'],0);
		
		// Store Variables
		$data['issued_callsign'] = $certdata['subject']['undefined'];
		$data['issued_name'] = $certdata['subject']['commonName'];
		$data['validFrom'] = date('Y-m-d H:i:s', $certdata['validFrom_time_t']);
		$data['validTo_Date'] = date('Y-m-d H:i:s', $certdata['validTo_time_t']);
		// https://oidref.com/1.3.6.1.4.1.12348.1
		$data['qso-first-date'] = $certdata['extensions']['1.3.6.1.4.1.12348.1.2'];
		$data['qso-end-date'] = $certdata['extensions']['1.3.6.1.4.1.12348.1.3'];
		$data['dxcc-id'] = $certdata['extensions']['1.3.6.1.4.1.12348.1.4'];
		return $data;
	}
	/*
	|--------------------------------------------------------------------------
	| Function: loadFromFile
	|--------------------------------------------------------------------------
	|
	|	$filepath is the ADIF file, $display_view is used to hide the output if its internal script
	|
	|	Internal function that takes the LoTW ADIF and imports into the log
	|
	*/
	private function loadFromFile($filepath, $display_view = "TRUE")
	{
		// Figure out how we should be marking QSLs confirmed via LoTW
		$query = $query = $this->db->query('SELECT lotw_rcvd_mark FROM config');
		$q = $query->row();
		$config['lotw_rcvd_mark'] = $q->lotw_rcvd_mark;
		ini_set('memory_limit', '-1');
		set_time_limit(0);
		$this->load->library('adif_parser');
		$this->adif_parser->load_from_file($filepath);
		$this->adif_parser->initialize();
		$tableheaders = "
| Station Callsign"; $tableheaders .= " | QSO Date"; $tableheaders .= " | Call"; $tableheaders .= " | Mode"; $tableheaders .= " | LoTW QSL Received"; $tableheaders .= " | Date LoTW Confirmed"; $tableheaders .= " | State"; $tableheaders .= " | Gridsquare"; $tableheaders .= " | IOTA"; $tableheaders .= " | Log Status"; $tableheaders .= " | LoTW Status"; $tableheaders .= " | 
| ".$record['station_callsign'].""; $table .= " | ".$time_on.""; $table .= " | ".$record['call'].""; $table .= " | ".$record['mode'].""; $table .= " | ".$record['qsl_rcvd'].""; $table .= " | ".$qsl_date.""; $table .= " | ".$state.""; $table .= " | ".($qsl_gridsquare != '' ? $qsl_gridsquare : $qsl_vucc_grids).""; $table .= " | ".$iota.""; $table .= " | QSO Record: ".$status[0].""; $table .= " | LoTW Record: ".$lotw_status.""; $table .= " | 
| ".$record['station_callsign'].""; $table .= " | ".$time_on.""; $table .= " | ".$record['call'].""; $table .= " | ".$record['mode'].""; $table .= " | ".$record['qsl_rcvd'].""; $table .= " | "; $table .= " | "; $table .= " | "; $table .= " | "; $table .= " | QSO Record: ".$status[0].""; $table .= " | "; $table .= " |