commit c8acf0604bce85c8b86f136bb03591c2ac35bd61 Author: Ivan Filipov Date: Mon Apr 10 13:51:00 2023 +0300 Initial commit diff --git a/JSONAPI.php b/JSONAPI.php new file mode 100644 index 0000000..9d61036 --- /dev/null +++ b/JSONAPI.php @@ -0,0 +1,379 @@ + + * + * @version 1.0 + * @date updated Feb 28, 2023 + */ + + namespace wlurep; + + class JSONAPI { + + private static $_instance = null; + private $_types = []; + private $_contractTypes = []; + private $_cities = []; + + /** + * JSONAPI constructor. + * + * Initializing Register json API. + * + * @since 1.0.0 + * @access private + */ + private function __construct() { + add_action('rest_api_init', [$this, 'init']); + } + + public function init() { + register_rest_route('urep', '/update', [ + 'methods' => 'GET', + 'callback' => [$this, 'update'], + 'permission_callback' => '__return_true' + ]); + // if we have to use post method +// register_rest_route('my/v1', '/projects_search', [ +// 'methods' => 'POST', +// 'callback' => [$this, 'post_projects_search'] +// ]); + } + + public function update($params) { + $pluginDir = realpath(dirname(__FILE__) ); + + ini_set('post_max_size', '2048M'); + ini_set('upload_max_filesize', "200M"); + ini_set('max_input_time', 259200); + ini_set('max_execution_time', 259200); + ini_set('memory_limit', "1024M"); + error_reporting(E_ALL & ~E_DEPRECATED); + ini_set('log_errors', true); + ini_set('error_log', $pluginDir . '/ErrorLog.txt'); + set_time_limit(0); + $start = (int)microtime(true); + + // Use this only if you have big Big BIG ... muscle! + set_time_limit(0); + ignore_user_abort(true); + ini_set('memory_limit', '-1'); + + $estateID = $params->get_param('estateid'); + $page = $params->get_param('page'); + $perPage = $params->get_param('perpage'); + $disable_param = $params->get_param('deleted'); + $disable = (!empty($disable_param))?true:false; + + if(!$disable){ + $apiURL = wl_get_option('api_url', ''); + $apiToken = wl_get_option('api_key', ''); + if($apiURL === ''){ + $response = new \WP_REST_Response(["result" => 'failed', 'message' => __('API url is missing').'.']); + $response->set_status(200); + + return $response; + } + if($apiToken === ''){ + $response = new \WP_REST_Response(["result" => 'failed', 'message' => __('API token is missing').'.']); + $response->set_status(200); + + return $response; + } + $apiParams = array( + 'token' => $apiToken + ); + if (!empty($estateID)) { + $apiParams['estateID'] = $estateID; + } + $info = json_decode(\wlurep\SimpleCurl::get($apiURL, $apiParams), true)['properties']; + $this->_types = $this->getTerms('property-type'); + $this->_contractTypes = $this->getTerms('property-contract-type'); + $this->_cities = $this->getTerms('city-type'); + + $istart = 0; + $iend = count($info); + if (isset($page)) { + if (empty($perPage)) { + $perPage = 10; + } + if(($page*$perPage)>$istart && ($page*$perPage)<$iend){ + $istart = (int)$page*$perPage; + } + if((($page+1)*$perPage)<$iend && (($page+1)*$perPage)>$istart){ + $iend = (int)(($page+1)*$perPage); + + } + } + + for ($i = $istart; $i < $iend; $i++) { + $propery = $info[$i]; + $propertyData = array( + 'estateid' => $propery['uid'], + 'title' => (!empty($propery['titleBG']))?$propery['titleBG']:mb_substr($propery['DescriptionBG'], 0, 20), + 'description' => $propery['DescriptionBG'], + 'property-contract-type' => $propery['listing_type_name'], // taxonomy + 'property-type' => $propery['estate_type_name'], // taxonomy + 'city-type' => $propery['region_name'], // taxonomy + 'imic_property_site_address' => $propery['subregion_name'], + 'imic_property_price' => $propery['price'], + 'imic_property_area' => $propery['space_m2'], + 'imic_property_beds' => $propery['bedroomCount'], + 'imic_property_baths' => (!empty($propery['bathCount']) && (int)$propery['bathCount']>0)?$propery['bathCount']:((!empty($propery['bathToiletCount']) && (int)$propery['bathToiletCount']>0)?$propery['bathCount']:0), + 'photos' => $propery['photos'] + ); + $this->updateProperty($propertyData); + } + }else{ + if(!empty($estateID)){ + $this->disableProperty($estateID); + } + } + + $end = (int)microtime(true); + $spend = (int)($end - $start); + + $response = new \WP_REST_Response(["result" => 'done', 'start' => date('d.m.Y H:i:s', $start), 'end' => date('d.m.Y H:i:s', $end), 'total time' => $spend]); + $response->set_status(200); + + return $response; + } + + /** + * + * @param array $propertyData + */ + private function updateProperty($propertyData = []) { + if (!is_array($propertyData) || count($propertyData) < 1) { + return; + } + + $propertyID = $this->getPropertyID($propertyData['estateid'], $propertyData['title'], $propertyData['description']); + $typeID = $this-> getTermID('types', $propertyData['property-type'], 'property-type'); + $contractTypesID = $this-> getTermID('contractTypes', $propertyData['property-contract-type'], 'property-contract-type'); + $cityID = $this-> getTermID('cities', $propertyData['city-type'], 'city-type'); + + //update post + $post = array( + 'ID' => $propertyID, + 'post_title' => $propertyData['title'], + 'post_content' => $propertyData['description'], + 'post_author' => 1, + 'post_status' => 'publish' + ); + wp_update_post($post); + + // update terms + wp_set_post_terms( $propertyID, array( (int) $typeID ), 'property-type', false ); + wp_set_post_terms( $propertyID, array( (int) $contractTypesID ), 'property-contract-type', false ); + wp_set_post_terms( $propertyID, array( (int) $cityID ), 'city-type', false ); + + // update metadata + update_post_meta($propertyID, 'imic_property_site_address', $propertyData['imic_property_site_address']); + update_post_meta($propertyID, 'imic_property_price', $propertyData['imic_property_price']); + update_post_meta($propertyID, 'imic_property_area', $propertyData['imic_property_area']); + update_post_meta($propertyID, 'imic_property_beds', $propertyData['imic_property_beds']); + update_post_meta($propertyID, 'imic_property_baths', $propertyData['imic_property_baths']); + update_post_meta($propertyID, 'imic_featured_property', 0); + + // update photos + $this->updatePhotos($propertyID, $propertyData['photos']); + } + + private function disableProperty($estateid) { + $property = $this->getProperty($estateid); + if(!empty($property)){ + // change visibility to Private + $post = array( + 'ID' => $property[0]->ID, + 'post_status' => 'private' + ); + wp_update_post($post); + } + } + + /** + * + * @param string $estateid + * @return object or null + */ + private function getProperty($estateid) { + $property = get_posts(array( + 'post_type' => 'property', + 'post_status' => array('private', 'publish'), + 'posts_per_page' => 1, + 'meta_query' => array( + array( + 'key' => 'estateid', + 'value' => $estateid, + 'compare' => '=' + ) + ) + )); + return $property; + } + + /** + * + * @param int $estateid + * @param string $title + * @param string $description + * @return int + */ + private function getPropertyID($estateid = null, $title = '', $description = '') { + if (!$estateid) { + return; + } + $property = $this->getProperty($estateid); + if(empty($property)){ + $propertyID = $this->createProperty($estateid, $title, $description); + }else{ + $propertyID = $property[0]->ID; + } + return $propertyID; + } + /** + * + * @param int $estateid + * @param string $title + * @param string $description + * @return int + */ + + private function createProperty($estateid = null, $title = '', $description = '') { + if (!$estateid) { + return; + } + $post = array( + 'post_name' => $title, + 'post_title' => $title, + 'post_content' => $description, + 'post_status' => 'publish', + 'post_type' => 'property' + ); + $property_id = wp_insert_post($post); + update_post_meta($property_id, 'estateid', $estateid); + return $property_id; + } + + /** + * + * @param string $taxonomiName + * @return array + */ + private function getTerms($taxonomiName) { + $terms = []; + $termsObj = get_terms($taxonomiName); + foreach ($termsObj as $term) { + $terms[$term->slug] = array( + 'term_id' => $term->term_id, + 'term_name' => $term->name + ); + } + return $terms; + } + /** + * + * @param string $termType + * @param string $termName + * @param string $taxonomyName + * @return integer + */ + private function getTermID($termType, $termName, $taxonomyName = '') { + $termSlug = sanitize_title($termName); + $terms = $this->{'_'.$termType}; + if(in_array($termSlug, $terms)){ + $termID = $terms[$termSlug]['term_id']; + }else{ + $termID = $this->insertTerm($taxonomyName, $termName); + } + return $termID; + } + /** + * + * @param string $termType + * @param string $termName + * @return type integer + */ + private function insertTerm($termType, $termName){ + if(!function_exists('wp_create_term')){ + require_once(ABSPATH . 'wp-admin/includes/taxonomy.php'); + } + $newTerm = \wp_create_term( $termName, $termType ); + + $termID = $newTerm['term_id']; + + return $termID; + } + + /** + * + * @param type $propertyID + * @param type $photos + */ + private function updatePhotos($propertyID, $photos) { + if(!is_array($photos)){ + return; + } + // Delete old photos + $this->deleteOldPhotos($propertyID); + + $url0 = $photos[0]['url']; + $post_title = get_the_title($propertyID); + if(empty($post_title) || $post_title == ''){ + $post_title = basename($url0); + } + $attachment_data = array( + 'title' => $post_title, + 'caption' => $post_title, + 'alt_text' => $post_title, + 'description' => $post_title, + ); + $download_remote_image = new \wlurep\WlDownloadRemoteImage( $url0, $attachment_data ); + $attachment_id = $download_remote_image->download(); + + + if ( ! $attachment_id ) { + return false; + } + + set_post_thumbnail( $propertyID, $attachment_id ); + unset($photos[0]); + + + foreach ($photos as $phpto) { + $url = $phpto['url']; + $download_remote_image = new \wlurep\WlDownloadRemoteImage( $url, $attachment_data ); + $attachment_id = $download_remote_image->download(); + add_post_meta($propertyID, 'imic_property_sights', $attachment_id); + } + } + + private function deleteOldPhotos($propertyID) { + $oldPhotos = get_post_meta($propertyID , 'imic_property_sights'); + $featuredImageID = get_post_thumbnail_id( $propertyID ); + if(!empty($featuredImageID)){ + $oldPhotos[] = $featuredImageID; + } + foreach ($oldPhotos as $oldPhotoID) { + wp_delete_attachment( $oldPhotoID, true ); + } + delete_post_meta( $propertyID, 'imic_property_sights', null ); + } + + /** + * + * @return \wlurep\JSONAPI + */ + public static function getInstance() { + if (self::$_instance == null) { + self::$_instance = new self; + } + return self::$_instance; + } + + } + \ No newline at end of file diff --git a/Loader.php b/Loader.php new file mode 100644 index 0000000..159de51 --- /dev/null +++ b/Loader.php @@ -0,0 +1,39 @@ + + * + * @version 1.0 + * @date updated Jan 26, 2023 + */ + + namespace wlurep; + + class Loader { + + private static $defaultNamespace = 'wlurep'; + + private function __construct() { + + } + + public static function registerAutoLoad() { + spl_autoload_register(array('\wlurep\Loader', 'autoload')); + } + + public static function autoload($class) { + self::loadClass($class); + } + + public static function loadClass($class) { + $file = realpath(substr_replace(str_replace('\\', DIRECTORY_SEPARATOR, $class), WL_UREP_PATH, 0, strlen(self::$defaultNamespace)) . '.php'); + + if ($file && is_readable($file)) { + include $file; + } + } + + } + \ No newline at end of file diff --git a/Plugin.php b/Plugin.php new file mode 100644 index 0000000..d8ac80f --- /dev/null +++ b/Plugin.php @@ -0,0 +1,158 @@ + + * + * @version 1.0 + * @date updated Feb 26, 2023 + */ + namespace wlurep; + + class Plugin { + private static $_instance = null; + + /** + * Plugin constructor. + * + * Initializing WL update real estates plugin. + * + * @since 1.0.0 + * @access private + */ + + private function __construct() { + $this->register_autoloader(); + $this->register_json_api(); + if(is_admin()){ + $this->register_admin_menu(); + global $pagenow; + if ( $pagenow === 'options.php' || $pagenow === 'options-general.php' && isset($_GET['page']) && $_GET['page'] == 'wl-urep-settings') { + // WL settings page + $this->register_settings_page(); + } + } + } + + /** + * Register autoloader. + * + * WL update real estate autoloader, that loads all the classes needed to run the plugin. + * + * @since 1.6.0 + * @access private + */ + private function register_autoloader() { + require_once WL_UREP_PATH . '/Loader.php'; + + Loader::registerAutoLoad(); + } + /** + * Register json api class. + * + * + * @since 1.6.0 + * @access private + */ + private function register_json_api() { + $jsonAPI = \wlurep\JSONAPI::getInstance(); + } + + /** + * Add function to admin_menu hook + */ + private function register_admin_menu() { + add_action('admin_menu', array($this, 'addSettingsMenu')); + } + /** + * Add function to admin_init hook + */ + private function register_settings_page() { + add_action('admin_init', array($this, 'settingsPage')); + } + + /** + * Add menu + */ + public function addSettingsMenu() { + // Add Role management page to user menu + add_options_page( __('Automatic update real estates', 'wlurep'), __('Automatic update real estates', 'wlurep'), 'manage_options', 'wl-urep-settings', array($this, 'page')); + } + + /* + * Function that generate REST API settings page + */ + public function page() { + if (!current_user_can('manage_options')) { + return; + } + ?> +
+ +
+ '.__('Here you can set all the options for using the REST API that automatic update real estate properties', 'wlurep').'

'; + } + /** + * function that generate API token field + */ + public function wl_urep_setting_api_key() { + $apiKey = wl_get_option('urep_api_key', ''); + echo ""; + } + /** + * function that generate API url field + */ + public function wl_urep_setting_api_url() { + $apiUrl = wl_get_option('urep_api_url', ''); + echo ""; + } + /** + * function that validate saved fields + */ + public function wl_urep_settings_validate($input) { + $api_key = trim($input['urep_api_key']); + if (!preg_match('/^[a-z0-9-]+$/i', $api_key)) { + $input['urep_api_key'] = ''; + add_settings_error('urep_error', 'wl_urep_setting_api_key', __('The API key can contain lower letters, numbers and dash', 'wlurep'), 'error'); + } + $input['urep_api_url'] = sanitize_url($input['urep_api_url']); + + return $input; + } + + /** + * + * @return \wlurep\Plugin + */ + public static function getInstance() { + if (self::$_instance == null) { + self::$_instance = new self; + } + return self::$_instance; + } + } + + Plugin::getInstance(); + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..202d0d1 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# WL Update Real Estate Properties + +*The goal of the plugin is to create API end point and make automatic connection with estateassistant.info API.* + +# Compatible ONLY with theme Real Spaces + +The plugin create following functionality: +1. Create Settings sub-page in administration part of the site, called "Automatic update real estates", where the administrator is able to set external API url and token. +2. Create wordpress API end point: + https://my-site.com/wp-json/urep/update?estateid={xxx} + where the extarnal API send the id of the updated property and the plugin \ No newline at end of file diff --git a/SimpleCurl.php b/SimpleCurl.php new file mode 100644 index 0000000..853b862 --- /dev/null +++ b/SimpleCurl.php @@ -0,0 +1,168 @@ + + * + * @version 1.0 + * @date Feb 02, 2021 + * @date updated Feb 02, 2021 + */ + + namespace wlurep; + + /** + * Sets some default functions and settings. + */ + class SimpleCurl { + + + const defaultTimeout = 5; + /** + * Timeout. + * + * timeout in seconds. Can be overriden + * + * @since 1.0.0 + * @access public + * @static + * + * @var timeout + */ + public static $timeout = self::defaultTimeout; + + /** + * Performs a get request on the chosen link and the chosen parameters + * in the array. + * + * @param string $url + * @param array $params + * + * @return string returns the content of the given url + */ + public static function get($url, $params = []) { + if (is_array($params) && count($params) > 0) { + $url = $url . '?' . http_build_query($params, '', '&'); + } + $ch = curl_init(); + + $options = [ + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CONNECTTIMEOUT => self::$timeout, + CURLOPT_SSL_VERIFYPEER => false, + ]; + curl_setopt_array($ch, $options); + + $response = curl_exec($ch); + curl_close($ch); + + return $response; + } + + /** + * Performs a post request on the chosen link and the chosen parameters + * in the array. + * + * @param string $url + * @param array $fields + * + * @return string returns the content of the given url after post + */ + public static function post($url, $fields = []) { + if (is_array($fields) && count($fields) > 0) { + $postFieldsString = json_encode($fields); + } else { + $postFieldsString = ''; + } + # The maximum execution time, in seconds. If set to zero, no time limit is imposed. + set_time_limit(0); + + # Make sure to keep alive the script when a client disconnect. + ignore_user_abort(true); + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + 'Content-Type: application/json; charset=utf-8', + 'Connection: Keep-Alive', + 'Accept-Encoding: gzip, deflate', + 'Accept-Language: en-US,en;q=0.5', + 'Cache-Control: no-cache', + 'Referer: http://erp.my', //Your referrer address + 'Keep-Alive: timeout=100, max=1000' + )); + curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); + curl_setopt($ch, CURLOPT_KEEP_SENDING_ON_ERROR, true); + curl_setopt($ch, CURLOPT_ENCODING, "gzip"); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout); + curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postFieldsString); + curl_setopt($ch, CURLOPT_POST, 1); // This is a POST request + + $response = curl_exec($ch); + $curlinfo = curl_getinfo($ch); + curl_close($ch); + return $response; + } + + /** + * Performs a put request on the chosen link and the chosen parameters + * in the array. + * + * @param string $url + * @param array $fields + * + * @return string with the contents of the site + */ + public static function put($url, $fields = []) { + if (is_array($fields) && count($fields) > 0) { + $postFieldsString = http_build_query($fields, '', '&'); + } else { + $postFieldsString = ''; + } + $ch = curl_init($url); + + $options = [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CONNECTTIMEOUT => self::$timeout, + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_CUSTOMREQUEST => 'PUT', + CURLOPT_POSTFIELDS => $postFieldsString, + ]; + curl_setopt_array($ch, $options); + + $response = curl_exec($ch); + curl_close($ch); + + return $response; + } + + /** + * Performs a ping request on the chosen link + * in the array. + * + * @param string $url + * + * @return bool + */ + public static function ping($url = '') { + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $data = curl_exec($ch); + $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + if ($httpcode >= 200 && $httpcode < 300) { + return true; + } + + return false; + } + + } + diff --git a/WlDownloadRemoteImage.php b/WlDownloadRemoteImage.php new file mode 100644 index 0000000..9c7b2a5 --- /dev/null +++ b/WlDownloadRemoteImage.php @@ -0,0 +1,362 @@ + + * + * @version 1.0 + * @date updated Mar 9, 2023 + * + * Usage: + * $download_remote_image = new WlDownloadRemoteImage( $url ); + * $attachment_id = $download_remote_image->download(); + */ + + namespace wlurep; + + class WlDownloadRemoteImage { + + /** + * Remote image URL. + * + * @var string + */ + private $url = ''; + /** + * The attachment data, in this format: + * + * array( + * $title = '', + * $caption = '', + * $alt_text = '', + * $description = '', + * ); + * + * @var array + */ + private $attachment_data = array(); + /** + * The attachment ID or false if none. + * + * @var int|bool + */ + private $attachment_id = false; + + /** + * Constructor. + * + * @param string $url The URL for the remote image. + * + * @param array $attachment_data { + * Optional. Data to be used for the attachment. + * + * @type string $title The title. Also used to create the filename. + * @type string $caption The caption. + * @type string $alt_text The alt text. + * @type string $description The description. + * } + */ + public function __construct($url, $attachment_data = array()) { + $this->url = $this->format_url($url); + + if (is_array($attachment_data) && $attachment_data) { + $this->attachment_data = array_map('sanitize_text_field', $attachment_data); + } + } + + /** + * Add a scheme, if missing, to a URL. + * + * Warning: This method defaults to using 'http' when adding a scheme to + * protocol-relative URLs and would need to be modified for remote images + * only available at 'https' URLs. + * + * @param string $url The URL. + * + * @return string The URL, with a scheme possibly prepended. + */ + private function format_url($url) { + + if ($this->has_valid_scheme($url)) { + return $url; + } + + if ($this->does_string_start_with_substring($url, '//')) { + return "http:{$url}"; + } + + return "http://{$url}"; + } + + /** + * Does this URL have a valid scheme? + * + * @param string $url The URL. + * + * @return bool + */ + private function has_valid_scheme($url) { + return $this->does_string_start_with_substring($url, 'https://') || $this->does_string_start_with_substring($url, 'http://'); + } + + /** + * Does this string start with this substring? + * + * @param string $string The string. + * @param string $substring The substring. + * + * @return bool + */ + private function does_string_start_with_substring($string, $substring) { + return 0 === strpos($string, $substring); + } + + /** + * Download a remote image and insert it into the WordPress Media Library as an attachment. + * + * @return bool|int The attachment ID, or false on failure. + */ + public function download() { + + if (!$this->is_url_valid()) { + return false; + } + + // Download remote file and sideload it into the uploads directory. + $file_attributes = $this->sideload(); + + if (!$file_attributes) { + return false; + } + + // Insert the image as a new attachment. + $this->insert_attachment($file_attributes['file'], $file_attributes['type']); + + if (!$this->attachment_id) { + return false; + } + + $this->update_metadata(); + $this->update_post_data(); + $this->update_alt_text(); + + return $this->attachment_id; + } + + /** + * Is this URL valid? + * + * @return bool + */ + private function is_url_valid() { + + $parsed_url = wp_parse_url($this->url); + + return $this->has_valid_scheme($this->url) && $parsed_url && isset($parsed_url['host']); + } + + /** + * Sideload the remote image into the uploads directory. + * + * @return array|bool Associative array of file attributes, or false on failure. + */ + private function sideload() { + + if(!function_exists('wp_handle_sideload')){ + // Gives us access to the download_url() and wp_handle_sideload() functions. + require_once ABSPATH . 'wp-admin/includes/file.php'; + } + // Download file to temp dir. + $temp_file = download_url($this->url, 10); + + if (is_wp_error($temp_file)) { + return false; + } + + $mime_type = mime_content_type($temp_file); + + if (!$this->is_supported_image_type($mime_type)) { + return false; + } + + // An array similar to that of a PHP `$_FILES` POST array + $file = array( + 'name' => $this->get_filename($mime_type), + 'type' => $mime_type, + 'tmp_name' => $temp_file, + 'error' => 0, + 'size' => filesize($temp_file), + ); + + $overrides = array( + // This tells WordPress to not look for the POST form + // fields that would normally be present. Default is true. + // Since the file is being downloaded from a remote server, + // there will be no form fields. + 'test_form' => false, + // Setting this to false lets WordPress allow empty files – not recommended. + 'test_size' => true, + // A properly uploaded file will pass this test. + // There should be no reason to override this one. + 'test_upload' => true, + ); + + // Move the temporary file into the uploads directory. + $file_attributes = wp_handle_sideload($file, $overrides); + + if ($this->did_a_sideloading_error_occur($file_attributes)) { + return false; + } + + return $file_attributes; + } + + /** + * Is this image MIME type supported by the WordPress Media Libarary? + * + * @param string $mime_type The MIME type. + * + * @return bool + */ + private function is_supported_image_type($mime_type) { + return in_array($mime_type, array('image/jpeg', 'image/gif', 'image/png', 'image/x-icon'), true); + } + + /** + * Get filename for attachment, including extension. + * + * @param string $mime_type The MIME type. + * + * @return string The filename. + */ + private function get_filename($mime_type) { + + if (empty($this->attachment_data['title'])) { + return basename($this->url); + } + + $filename = sanitize_title_with_dashes($this->attachment_data['title']); + $extension = $this->get_extension_from_mime_type($mime_type); + + return $filename . $extension; + } + + /** + * Get a file extension, including the preceding '.' from a file's MIME type. + * + * @param string $mime_type The MIME type. + * + * @return string The file extension or empty string if not found. + */ + private function get_extension_from_mime_type($mime_type) { + + $extensions = array( + 'image/jpeg' => '.jpg', + 'image/gif' => '.gif', + 'image/png' => '.png', + 'image/x-icon' => '.ico', + ); + + return isset($extensions[$mime_type]) ? $extensions[$mime_type] : ''; + } + + /** + * Did an error occur while sideloading the file? + * + * @param array $file_attributes The file attribues, or array containing an 'error' key on failure. + * + * @return bool + */ + private function did_a_sideloading_error_occur($file_attributes) { + return isset($file_attributes['error']); + } + + /** + * Insert attachment into the WordPress Media Library. + * + * @param string $file_path The path to the media file. + * @param string $mime_type The MIME type of the media file. + */ + private function insert_attachment($file_path, $mime_type) { + + // Get the path to the uploads directory. + $wp_upload_dir = wp_upload_dir(); + + // Prepare an array of post data for the attachment. + $attachment_data = array( + 'guid' => $wp_upload_dir['url'] . '/' . basename($file_path), + 'post_mime_type' => $mime_type, + 'post_title' => preg_replace('/\.[^.]+$/', '', basename($file_path)), + 'post_content' => '', + 'post_status' => 'inherit', + ); + + $attachment_id = wp_insert_attachment($attachment_data, $file_path); + + if (!$attachment_id) { + return; + } + + $this->attachment_id = $attachment_id; + } + + /** + * Update attachment metadata. + */ + private function update_metadata() { + $file_path = get_attached_file($this->attachment_id); + + if (!$file_path) { + return; + } + if(!function_exists('wp_generate_attachment_metadata')){ + // Gives us access to the wp_generate_attachment_metadata() function. + require_once ABSPATH . 'wp-admin/includes/image.php'; + } + // Generate metadata and image sizes for the attachment. + $attach_data = wp_generate_attachment_metadata($this->attachment_id, $file_path); + wp_update_attachment_metadata($this->attachment_id, $attach_data); + } + + /** + * Update attachment title, caption and description. + */ + private function update_post_data() { + if (empty($this->attachment_data['title']) && empty($this->attachment_data['caption']) && empty($this->attachment_data['description']) + ) { + return; + } + $data = array( + 'ID' => $this->attachment_id, + ); + // Set image title (post title) + if (!empty($this->attachment_data['title'])) { + $data['post_title'] = $this->attachment_data['title']; + } + // Set image caption (post excerpt) + if (!empty($this->attachment_data['caption'])) { + $data['post_excerpt'] = $this->attachment_data['caption']; + } + // Set image description (post content) + if (!empty($this->attachment_data['description'])) { + $data['post_content'] = $this->attachment_data['description']; + } + wp_update_post($data); + } + /** + * Update attachment alt text. + */ + private function update_alt_text() { + if (empty($this->attachment_data['alt_text']) && empty($this->attachment_data['title'])) { + return; + } + // Use the alt text string provided, or the title as a fallback. + $alt_text = !empty($this->attachment_data['alt_text']) ? $this->attachment_data['alt_text'] : $this->attachment_data['title']; + + update_post_meta($this->attachment_id, '_wp_attachment_image_alt', $alt_text); + } + + } + \ No newline at end of file diff --git a/wl-urep.php b/wl-urep.php new file mode 100644 index 0000000..c230d0c --- /dev/null +++ b/wl-urep.php @@ -0,0 +1,62 @@ +"; + empty($var) ? var_dump($var) : print_r($var); + echo ""; + } + + } + + /** + * Load wlsrm textdomain. + * + * Load gettext translate for wlurep text domain. + * + * @since 1.0.0 + * + * @return void + */ + function wlurep_load_plugin_textdomain() { + load_plugin_textdomain('wlurep'); + } + + include 'Plugin.php'; \ No newline at end of file