Plugin Directory

Changeset 2247578


Ignore:
Timestamp:
02/20/2020 12:50:35 PM (6 years ago)
Author:
ottok
Message:

Release 2.1

File:
1 edited

Legend:

Unmodified
Added
Removed
  • wp-nettix-sync/trunk/wp-nettix-sync.php

    r1857240 r2247578  
    44 * Plugin URI: https://github.com/Seravo/wp-nettix-sync
    55 * Description: Automatically import NettiX items to WordPress as posts with custom fields.
    6  * Version: 2.0
     6 * Version: 2.1
    77 * Author: Seravo Oy
    88 * Author URI: https://seravo.com
     
    1010*/
    1111/**
    12  * Copyright 2015–2018 Seravo Oy
     12 * Copyright 2015–2020 Seravo Oy
    1313 * This program is free software; you can redistribute it and/or modify
    1414 * it under the terms of the GNU General Public License, version 3, as
     
    2222 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    2323*/
    24 
    25 /**
    26  * Require options.php for options page
    27  */
    28 require_once dirname( __FILE__ ) .'/options.php' ;
    2924
    3025/**
     
    9590
    9691/**
    97  * Schedule the sync action to be done hourly via WP-Cron
    98  */
    99 register_activation_hook( __FILE__, 'nettix_setup_schedule' );
    100 function nettix_setup_schedule() {
    101   if ( ! wp_next_scheduled( 'wp_nettix_sync_data' ) ) {
    102     wp_schedule_event( time(), 'hourly', 'wp_nettix_sync_data');
    103   }
    104 }
    105 /**
    10692 * Clear schedules on deactivation
    10793 */
     
    11197    wp_clear_scheduled_hook('wp_nettix_sync_data');
    11298}
    113 /**
    114  * Fetches data from NettiX
    115  */
    116 add_action( 'wp_nettix_sync_data', 'nettix_do_data_sync' );
    117 function nettix_do_data_sync() {
    118   // start debug buffer
    119   ob_start();
    12099
    121   // give it some time...
    122   set_time_limit(180);
    123   // this helps with DEBUG
    124   header('Content-Type: text/html; charset=utf-8');
    125   global $nettix_sources;
    126   $nettix_sources = nettix_get_links();
    127   if( !is_array($nettix_sources) ) {
    128     $nettix_sources = array();
    129   }
    130   // wp-config.php:
    131   /*$nettix_sources = 'http://www.nettiauto.com/yritys/{yrityksen_nimi}?id_template=7'*/
    132   // get item links
    133   $links = array();
    134   foreach($nettix_sources as $src) {
    135     $links = array_merge( $links, nettix_parse_links( $src ) );
    136   }
    137 
    138   // HACK: let's shuffle the order of links in order to avoid missing the same ones every time
    139   shuffle($links);
    140 
    141   // store available nettiX ids to keep track of published posts
    142   $available = array();
    143   // keep track of actions
    144   $added = array();
    145   $updated = array();
    146   $deleted = array();
    147 
    148   // Define the storing method before the loop.
    149   $nettix_json = nettix_get_option( 'wp_nettix_json' );
    150   if ( defined( 'NETTIX_JSON' ) && ! empty($nettix_json) ){
    151     nettix_from_config_to_db( 'wp_nettix_json', "1" );
    152     $nettix_json = "1";
    153   }
    154   if ( $nettix_json ){
    155     error_log( "wp-nettix-sync Notice: Using Nettix JSON is depreciated and will be removed in the near future." );
    156   }
    157 
    158   // store the data into wordpress posts
    159   foreach($links as $count => $link) {
    160 
    161     // Check if 'nettiauto' exists in link and assign the post_type accordingly
    162     $post_type = ( false !== strpos($link, 'nettiauto') ) ? 'nettix' : 'nettixvene';
    163 
    164     $meta = nettix_parse_meta( $link );
    165 
    166     if(!$meta) continue; //skip if meta not available
    167 
    168     // make this available
    169     $available[] = $meta['nettixID'];
    170     $post = array(
    171       'post_content'   => '',
    172       'post_name'      => sanitize_title( $meta['title'] ),
    173       'post_title'     => $meta['title'],
    174       'post_status'    => 'publish',
    175           'post_type'      => $post_type,
    176     );
    177     // check if this already exists as a post
    178     $matching = get_posts( array(
    179       'post_type' => $post_type,
    180       'meta_query' => array(
    181         array(
    182           'key' => 'nettixID',
    183           'value' => $meta['nettixID'],
    184         )
    185       )
    186     ));
    187     if( !empty($matching) ) {
    188       // post exists, update it
    189       $updated[] = $post['ID'] = $matching[0]->ID;
    190     }
    191     else {
    192       $added[] = $post_id;
    193     }
    194     $post_id = wp_insert_post( $post );
    195     // add submission data as meta values
    196 
    197 
    198     // This is depreciated.
    199     // Enter the loop by defining NETTIX_JSON in wp-config
    200     if ( $nettix_json ) {
    201       foreach ( $meta as $key => $value ) {
    202         if ( is_array( $value ) ) {
    203           $value = wp_json_encode( $value );
    204         }
    205         update_post_meta( $post_id, trim( $key ), sanitize_text_field( $value ) );
    206       }
    207     }
    208     else {
    209 
    210       //search doesn't work w/o some meta fields
    211       //this is not the best solution though
    212 
    213       $meta_keys = array(
    214           'make'            => 'Valmistaja',
    215           'location'        => 'Sijainti',
    216           'driveType'       => 'Vetotapa',
    217           'gearBoxType'     => 'Vaihteisto',
    218           'fuelType'        => 'Moottori',
    219           'isVatDeductible' => 'ALV',
    220           'price'           => 'Hinta',
    221           'year'            => 'Vuosimalli',
    222           'mileage'         => 'Mittarilukema',
    223           'color'           => 'Väri',
    224           'lengthMeter'     => 'Pituus',
    225           'widthMeter'      => 'Leveys',
    226           'heightMeter'     => 'Korkeus',
    227           'totalOwner'      => 'Omistajat',
    228           'accessory'       => 'Lisävarusteet',
    229           'engineInfo'      => 'Moottorin tiedot',
    230       );
    231 
    232       if ( $post_type == 'nettixvene' ) {
    233         $boat_meta_keys = array(
    234           'make'          => 'Venevalmistaja',
    235           'location'      => 'Venesijainti',
    236           'boatFuelType'  => 'Polttoainetyyppi',
    237           'boatType'      => 'Venetyyppi',
    238           'bodyMaterial'  => 'Runkomateriaali',
    239           'draughtMeter'  => 'Syveys',
    240           'sailInfo'      => 'Purjeen tiedot',
    241         );
    242         $meta_keys = array_merge( $meta_keys, $boat_meta_keys );
    243       }
    244 
    245       foreach ( $meta_keys as $key => $entry ) {
    246         if ( $key == 'location' ) {
    247           update_post_meta($post_id, $entry, sanitize_text_field($meta['locationInfo']['town']) );
    248         } elseif ( $meta[$key] == false ) {
    249           update_post_meta( $post_id, $entry, '');
    250         } elseif ( $key == 'boatFuelType' ) {
    251           if ( is_array( $meta['engineInfo']['engineFuelType'] ) ) {
    252             update_post_meta( $post_id, $entry, sanitize_text_field( $meta['engineInfo']['engineFuelType'][0] ) );
    253           } else {
    254             update_post_meta( $post_id, $entry, sanitize_text_field( $meta['engineInfo']['engineFuelType'] ) );
    255           }
    256         } elseif ( is_array( $meta[ $key ] ) ) {
    257           update_post_meta( $post_id, $entry, $meta[$key] );
    258         } else {
    259           update_post_meta( $post_id, $entry, sanitize_text_field($meta[$key]) );
    260         }
    261       }
    262 
    263       update_post_meta($post_id, 'nettixID', sanitize_text_field($meta['nettixID']) );
    264 
    265       $meta = wp_slash(wp_json_encode($meta));
    266       update_post_meta($post_id, 'xml', $meta );
    267     }
    268   }
    269   // Eliminate only if there were some links to begin with
    270   // For example removing a link from settings would erase everything
    271   if ( $nettix_sources ) {
    272     // find posts to eliminate
    273     $eliminate = get_posts( array(
    274       'posts_per_page' => -1,
    275       'post_type' => ['nettix', 'nettixvene'],
    276       'meta_query' => array(
    277         array(
    278           'key' => 'nettixID',
    279           'compare' => 'NOT IN',
    280           'value' => $available,
    281         )
    282       )
    283     ));
    284   }
    285   // eliminate them
    286   foreach($eliminate as $post) {
    287     wp_delete_post($post->ID, true);
    288     $deleted[] = $post->ID;
    289   }
    290   echo "Added: ";
    291   print_r($added);
    292   echo "Updated: ";
    293   print_r($updated);
    294   echo "Deleted: ";
    295   print_r($deleted);
    296   $output = ob_get_clean();
    297   if(isset($_GET['nettix_do_sync'])) {
    298     print_r('<pre>' . $output . '</pre>');
    299     die();
    300   }
     100function nettix_deprecated() {
     101    ?>
     102    <div class="notice notice-error">
     103      <p>NettiX Oy has shut down their API which the plugin wp-nettix-sync depended on, and thus the plugin cannot function anymore. <em>Please uninstall the wp-nettix-sync plugin.</em></p>
     104    </div>
     105    <?php
    301106}
    302 /**
    303  * Parses item meta from xml
    304  *
    305  *
    306  */
    307 function nettix_parse_meta($item) {
    308 
    309   set_time_limit(180);
    310 
    311   $xml = simplexml_load_file($item);
    312 
    313   if(!$xml) return false; // do nothing if there's a failure
    314 
    315   $meta = nettix_xmlToArray($xml);
    316 
    317   $temp = array();
    318   $temp = $meta['ad'];
    319   unset($meta['ad']);
    320   $meta = array_merge($meta,$temp);
    321 
    322   $meta['source'] = $item;
    323   // get nettix ID
    324   $meta['nettixID'] = (string)$xml->id;
    325   // get item title
    326   $meta['title'] = (string)$xml->make .' '. (string)$xml->model .' '. (string)$xml->year . ' ' . (string)$xml->engineModel;
    327 
    328   $images = array();
    329 
    330   //if theres more than one image
    331   //the array structure is different
    332   if(isset($meta['media']['image'][0])){
    333     foreach($meta['media']['image'] as $image){
    334       if(isset($image['imgUrl'])){
    335         $images[] = $image['imgUrl'];
    336       }
    337     }
    338   }
    339   else{
    340     if(isset($meta['media']['image']['imgUrl'])){
    341       $images[] = $meta['media']['image']['imgUrl'];
    342     }
    343   }
    344 
    345   unset($meta['media']);
    346   $meta['images'] = $images;
    347 
    348   if(empty($meta['images'])) {
    349     $meta['images'] = array();
    350     $meta['images'][] = NETTIX_PLACEHOLDER_IMG;
    351   }
    352 
    353   return $meta;
    354 }
    355 
    356 /*
    357  * Parses item links from a template 7 directory
    358  */
    359 function nettix_parse_links($directory) {
    360   $xml = simplexml_load_file($directory);
    361   $items = array();
    362 
    363   foreach( $xml->children() as $child){
    364     $items[] = (string)$child->adUrl;
    365   }
    366   return $items;
    367 }
    368 function nettix_get_links(){
    369 
    370   $nettix_dealerlist = nettix_get_option( 'wp_nettix_dealerlist' );
    371   $nettix_adlist = nettix_get_option( 'wp_nettix_adlist' );
    372 
    373   if( ! empty( $nettix_dealerlist ) ) {
    374 
    375     $xml = simplexml_load_file( $nettix_dealerlist );
    376     $items = array();
    377 
    378     foreach( $xml->children() as $child){
    379       $items[] = (string)$child->adListUrl;
    380     }
    381   }
    382   else if ( defined('NETTIX_DEALERLIST') ) {
    383 
    384     nettix_from_config_to_db( 'wp_nettix_dealerlist', NETTIX_DEALERLIST );
    385     $xml = simplexml_load_file( NETTIX_DEALERLIST );
    386     $items = array();
    387 
    388     foreach( $xml->children() as $child){
    389       $items[] = (string)$child->adListUrl;
    390     }
    391   }
    392   else if( ! empty( $nettix_adlist && $nettix_adlist != [""] ) ) {
    393     return $nettix_adlist;
    394   }
    395   else if ( defined('NETTIX_ADLIST') ) {
    396     nettix_from_config_to_db( 'wp_nettix_adlist', unserialize( NETTIX_ADLIST ) );
    397     return unserialize( NETTIX_ADLIST );
    398   }
    399   else {
    400     error_log( 'wp-nettix-sync Error: Datapipe URL not defined. Set it in wp-admin Settings->NettiX' );
    401   }
    402 
    403   return $items;
    404 }
    405 
    406 function nettix_from_config_to_db( $optionname, $content ) {
    407   if ( is_array($content) ) {
    408     update_option( $optionname, implode( ',', $content ) );
    409   }
    410   else {
    411     update_option( $optionname, $content );
    412   }
    413 }
    414 
    415 function nettix_get_option( $option ) {
    416   $db_option = get_option( $option );
    417 
    418   if ( $option === 'wp_nettix_adlist') {
    419     // Remove spaces and make an array
    420     $db_option = str_replace( ' ', '', $db_option );
    421     $db_option = explode( ',', $db_option);
    422   } elseif ( $option == 'wp_nettix_json' ) {
    423     if ( $db_option !== "1" ){
    424       $db_option = false;
    425     }
    426   }
    427   return $db_option;
    428 }
    429 
    430 function nettix_xmlToArray($xml, $options = array()) {
    431     $defaults = array(
    432         'namespaceSeparator' => ':',//you may want this to be something other than a colon
    433         'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
    434         'alwaysArray' => array(),   //array of xml tag names which should always become arrays
    435         'autoArray' => true,        //only create arrays for tags which appear more than once
    436         'textContent' => '$',       //key used for the text content of elements
    437         'autoText' => true,         //skip textContent key if node has no attributes or child nodes
    438         'keySearch' => false,       //optional search and replace on tag and attribute names
    439         'keyReplace' => false       //replace values for above search values (as passed to str_replace())
    440     );
    441     $options = array_merge($defaults, $options);
    442     $namespaces = $xml->getDocNamespaces();
    443     $namespaces[''] = null; //add base (empty) namespace
    444 
    445     //get attributes from all namespaces
    446     $attributesArray = array();
    447     foreach ($namespaces as $prefix => $namespace) {
    448         foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
    449             //replace characters in attribute name
    450             if ($options['keySearch']) $attributeName =
    451                     str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
    452             $attributeKey = $options['attributePrefix']
    453                     . ($prefix ? $prefix . $options['namespaceSeparator'] : '')
    454                     . $attributeName;
    455             $attributesArray[$attributeKey] = (string)$attribute;
    456         }
    457     }
    458 
    459     //get child nodes from all namespaces
    460     $tagsArray = array();
    461     foreach ($namespaces as $prefix => $namespace) {
    462         foreach ($xml->children($namespace) as $childXml) {
    463             //recurse into child nodes
    464             $childArray = nettix_xmlToArray($childXml, $options);
    465             list($childTagName, $childProperties) = each($childArray);
    466 
    467             //replace characters in tag name
    468             if ($options['keySearch']) $childTagName =
    469                     str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
    470             //add namespace prefix, if any
    471             if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
    472 
    473             if (!isset($tagsArray[$childTagName])) {
    474                 //only entry with this key
    475                 //test if tags of this type should always be arrays, no matter the element count
    476                 $tagsArray[$childTagName] =
    477                         in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
    478                         ? array($childProperties) : $childProperties;
    479             } elseif (
    480                 is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
    481                 === range(0, count($tagsArray[$childTagName]) - 1)
    482             ) {
    483                 //key already exists and is integer indexed array
    484                 $tagsArray[$childTagName][] = $childProperties;
    485             } else {
    486                 //key exists so convert to integer indexed array with previous value in position 0
    487                 $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
    488             }
    489         }
    490     }
    491 
    492     //get text content of node
    493     $textContentArray = array();
    494     $plainText = trim((string)$xml);
    495     if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
    496 
    497     //stick it all together
    498     $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
    499             ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
    500 
    501     //return node as array
    502     return array(
    503         $xml->getName() => $propertiesArray
    504     );
    505 }
    506 /**
    507  * Run sync via GET parameters
    508  */
    509 if(isset($_GET['nettix_do_sync'])) {
    510   add_action('init', 'nettix_do_data_sync');
    511 }
     107add_action( 'admin_notices', 'nettix_deprecated' );
Note: See TracChangeset for help on using the changeset viewer.