<?php
/**
 * UCP Export - Import
 */


class UCP_ei extends UCP {
  // creates an export file with UCP options
  static function options_send_export_file() {
    $filename = str_replace(array('http://', 'https://'), '', home_url());
    $filename = str_replace(array('/', '\\', '.'), '-', $filename);
    $filename .= '-' . date('Y-m-d') . '-ucp-pro.txt';

    $options = self::get_options();
    unset($options['license_key'], $options['license_active'], $options['license_expires'], $options['license_type']);

    $out = array('type' => 'UCP PRO export', 'version' => self::$version, 'data' => $options);
    $out = json_encode($out);

    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename=' . $filename);
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . strlen($out));

    @ob_end_clean();
    flush();

    echo $out;
    exit;
  } // options_send_export_file


  // validate import file after upload
  static function options_validate_import_file() {
    if (empty($_POST) || empty($_FILES['ucp_settings_import'])) {
      return new WP_Error(1, 'No import file uploaded.');
    }

    $uploaded_file = $_FILES['ucp_settings_import'];
    $wp_filetype = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name'], false);
    if ($wp_filetype['ext'] != 'txt' && !wp_match_mime_types('txt', $wp_filetype['type'])) {
      return new WP_Error(1, 'Please upload a <i>TXT</i> file generated by UnderConstructionPage PRO.');
    }

    if ($uploaded_file['size'] < 500) {
      return new WP_Error(1, 'Uploaded file is too small. Please verify that you have uploaded the right UCP export file.');
    }

    if ($uploaded_file['size'] > 100000) {
      return new WP_Error(1, 'Uploaded file is too large to process. Please verify that you have uploaded the right UCP export file.');
    }

    $content = file_get_contents($uploaded_file['tmp_name']);
    $content = json_decode($content, true);
    if (!isset($content['type']) || !isset($content['version']) || !isset($content['data']) ||
        $content['type'] != 'UCP PRO export' || !is_array($content['data']) || sizeof($content['data']) < 20) {
      return new WP_Error(1, 'Uploaded file is not an UCP PRO export file. Please verify that you have uploaded the right file.');
    }

    return $content;
  } // validate_import_file
} // class
