/lib/API.php
PHP | 313 lines | 237 code | 75 blank | 1 comment | 40 complexity | be574c301e9b9f5c429114564469812f MD5 | raw file
- <?php namespace Dorigo\FireFish;
- class API {
- private static $instance;
- private $path = 'rss/adverts/all.aspx';
- private $settings;
- private $postType;
- private $directory = 'drgo_firefish';
- private $cacheExpiry = 3600;
- private $cachePath;
- private $url;
- private $curl;
- public static function Init() {
- if(is_null(self::$instance)) {
- self::$instance = new self();
- }
- return self::$instance;
- }
- private function __construct() {
- $this->settings = Settings::Init();
- $this->postType = PostType::Init()->getPostType();
- $this->url = $this->settings->getOption('site_url');
- if(!$this->cachePath) {
- $uploads = wp_upload_dir();
- $cache = [
- $uploads['basedir'],
- $this->directory
- ];
- $this->cachePath = implode(DIRECTORY_SEPARATOR, [$uploads['basedir'], $this->directory]);
- }
- if(!file_exists($this->cachePath) || !is_dir($this->cachePath)) {
- mkdir($this->cachePath);
- }
- }
- public function getListings() {
- $listing = $this->request();
- if(!$listing || !isset($listing->channel) || !isset($listing->channel->item)) { return false; }
- $ids = [];
- $taxonomies = [
- 'job_type' => [],
- 'disipline' => [],
- 'role' => [],
- 'location_area' => [],
- 'location' => [],
- 'remuneration' => []
- ];
- global $wpdb;
- $query = "SELECT ID FROM {$wpdb->posts} INNER JOIN {$wpdb->postmeta} on {$wpdb->postmeta}.post_id = {$wpdb->posts}.ID WHERE meta_key='_drgo_firefish_reference_number' AND meta_value = '%s'";
- foreach($listing->channel->item as $item) {
- $advert = $item->children('ffAdvert', true);
- $reference = (string) $advert->ReferenceNumber;
- $ids[] = $reference;
- $jobs = $wpdb->get_results(sprintf($query, $reference), OBJECT);
- $content = html_entity_decode((string) $item->description);
- $content = strip_tags($content, "<p><a><h1><h2><h3><h4><h5><h6><strong><em><br><b><i><ol><ul><li><dl><dd><dt>");
- if(empty($jobs)) {
- $date = strtotime((string) $item->pubDate);
- $title = (string) $advert->Title;
- $post_id = wp_insert_post([
- 'post_title' => $title,
- 'post_name' => sanitize_title("{$title} {$reference}"),
- 'post_type' => $this->postType,
- 'post_status' => 'publish',
- 'post_content' => $content,
- 'post_date' => date('Y-m-d H:i:s', $date)
- ]);
- if(is_wp_error($post_id)) {
- wp_die('An error occurred');
- }
- } else {
- $post_id = $jobs[0]->ID;
- }
- $taxonomies['job_type'][$post_id] = (string) $advert->JobType ?: false;
- $taxonomies['discipline'][$post_id] = (string) $advert->Discipline ?: false;
- $taxonomies['role'][$post_id] = (string) $advert->Role ?: false;
- $taxonomies['location_area'][$post_id] = (string) $advert->LocationArea ?: false;
- $taxonomies['location'][$post_id] = (string) $advert->Location ?: false;
- //$taxonomies['remuneration'][$post_id] = (string) $advert->Remuneration ?: false;
- $closing = strtotime((string) $advert->ClosingDate);
- update_post_meta($post_id, '_drgo_firefish_reference_number', $reference ?: false);
- update_post_meta($post_id, '_drgo_firefish_company_reference', (string) $advert->CompanyReferenceNumber ?: false);
- update_post_meta($post_id, '_drgo_firefish_link', (string) $item->link ?: false);
- update_post_meta($post_id, '_drgo_firefish_closing_date', date('Y-m-d H:i:s', $closing));
- update_post_meta($post_id, '_drgo_firefish_remuneration', (string) $advert->Remuneration);
- $oldContentHash = get_post_meta($post_id, '_drgo_firefish_content_hash', true);
- $oldTitleHash = get_post_meta($post_id, '_drgo_firefish_title_hash', true);
- $contentHash = md5((string) $content);
- $titleHash = md5((string) $advert->Title);
- $updatePost = [];
- if($titleHash !== $oldTitleHash) {
- $updatePost['post_title'] = (string) $advert->Title;
- update_post_meta($post_id, '_drgo_firefish_title_hash', $titleHash);
- }
- if($contentHash !== $oldContentHash) {
- $updatePost['post_content'] = $content;
- update_post_meta($post_id, '_drgo_firefish_content_hash', $contentHash);
- }
- if(!empty($updatePost)) {
- wp_update_post(array_merge(['ID' => $post_id], $updatePost));
- }
- $location = (string) $advert->Location ?: (string) $advert->LocationArea;
- if($location) {
- $this->getLatLng($post_id, $location);
- }
- }
- array_unique($ids);
- foreach($taxonomies as $name => $posts) {
- $taxonomy = "{$this->postType}_{$name}";
- foreach($posts as $post_id => $term) {
- update_post_meta($post_id, "_drgo_firefish_{$name}", $term);
- if(!$term) { continue; }
- $term_id = term_exists(sanitize_title($term), $taxonomy);
- if(!$term_id || $term_id === 0) {
- $term_id = wp_insert_term($term, $taxonomy, [
- 'slug' => sanitize_title($term)
- ]);
- if(is_wp_error($term_id)) {
- continue;
- }
- }
- $term_id = is_array($term_id) ? $term_id['term_id'] : $term_id;
- wp_set_object_terms($post_id, (int) $term_id, $taxonomy);
- }
- }
- $old_jobs = get_posts([
- 'post_type' => $this->postType,
- 'posts_per_page' => 1,
- 'post_status' => 'publish',
- 'meta_query' => [
- 'relation' => 'OR',
- [
- 'key' => '_drgo_firefish_reference_number',
- 'value' => $ids,
- 'compare' => 'NOT IN'
- ],
- [
- 'key' => '_drgo_firefish_reference_number',
- 'value' => '',
- 'compare' => 'NOT EXISTS'
- ]
- ]
- ]);
- foreach($old_jobs as $old_job) {
- wp_delete_post($old_job->ID);
- }
- return true;
- }
- private function getLatLng($post_id, $location = null) {
- if(!$post_id || !$location) { return false; }
- $apiKey = apply_filters('Dorigo\FireFish\GoogleAPI', '');
- if(!$apiKey) { return false; }
- $data = [
- 'address' => $location,
- 'region' => apply_filters('Dorigo\FireFish\GoogleRegion', 'uk'),
- 'key' => $apiKey
- ];
- $location = $this->request('maps/api/geocode/json', $data, $method="get", -1, 'https://maps.googleapis.com', 'json');
- if($location && isset($location->results) && !empty($location->results)) {
- $results = $location->results[0];
- update_post_meta($post_id, "_drgo_firefish_lat_lng", (array) $results->geometry->location);
- }
- }
- private function request($path = null, $data = [], $method = 'get', $cache = false, $url = null, $format = 'xml') {
- $path = $path ?: $this->path;
- $url = $url ?: $this->url;
- if(!$url || !$path) { return false; }
- $filename = $this->getFileName($path, $url, $data, $method);
- if($cache !== false && $cache !== null && $this->isInCache($filename, $cache)) {
- return $this->getFromCache($filename, $format);
- }
- $url = rtrim($url, '/').'/'.ltrim($path, '/');
- $this->curl = curl_init();
- switch($method) {
- case 'get':
- $url = $url.'?'.http_build_query($data);
- break;
- case 'post':
- curl_setopt($this->curl, CURLOPT_POST, true);
- curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
- break;
- }
- curl_setopt($this->curl, CURLOPT_URL, $url);
- curl_setopt($this->curl, CURLINFO_HEADER_OUT, false);
- curl_setopt($this->curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
- curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($this->curl, CURLOPT_HEADER, false);
- $response = curl_exec($this->curl);
- if($cache) {
- file_put_contents($this->cachePath.DIRECTORY_SEPARATOR.$filename, $response);
- }
- if($response) {
- switch($format) {
- case 'xml':
- return new \SimpleXMLElement($response);
- break;
- case 'json':
- return json_decode($response);
- break;
- default:
- return $response;
- break;
- }
- } else {
- return false;
- }
- }
- protected function getFromCache($filename, $format = 'xml') {
- $filepath = $this->cachePath.DIRECTORY_SEPARATOR.$filename;
- if(file_exists($filepath)) {
- $contents = file_get_contents($filepath);
- switch($format) {
- case 'xml':
- return new \SimpleXMLElement($contents);
- break;
- case 'json':
- return json_decode($contents);
- break;
- default:
- return $contents;
- break;
- }
- } else {
- return [];
- }
- }
- protected function isInCache($filename, $expiry = null) {
- $filepath = $this->cachePath.DIRECTORY_SEPARATOR.$filename;
- if(!$expiry === null || $expiry === true || $expiry === false) {
- $expiry = $this->cacheExpiry;
- } else if($expiry < 0) {
- $expiry = PHP_INT_MAX;
- }
- return file_exists($filepath) && filemtime($filepath) > time() - $expiry;
- }
- protected function getFileName($path, $url, $data = [], $method = "get") {
- return md5($url.$path.json_encode($data).$method).".json";
- }
- }