Adding coupon image importer
authorSteve Sutton <steve@gaslightmedia.com>
Tue, 26 Jan 2016 20:22:10 +0000 (15:22 -0500)
committerSteve Sutton <steve@gaslightmedia.com>
Tue, 26 Jan 2016 20:22:10 +0000 (15:22 -0500)
controllers/CouponImageImport.php [new file with mode: 0644]
index.php

diff --git a/controllers/CouponImageImport.php b/controllers/CouponImageImport.php
new file mode 100644 (file)
index 0000000..74765dd
--- /dev/null
@@ -0,0 +1,326 @@
+<?php
+
+/**
+ * CouponImageImport.php
+ *
+ * PHP version 5.3
+ *
+ * @category  Importer
+ * @package   GLM WP Importer
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2013 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.0.1)
+ * @link      <>
+ */
+
+/**
+ * CouponImageImport
+ *
+ * Main Controller for the Gaslight WP Importer Plugin
+ *
+ * @category  Importer
+ * @package   GLM WP Importer
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2013 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.0.1)
+ * @link      <>
+ */
+ if (!defined('WP_LOAD_IMPORTERS')) {
+   return;
+ }
+ require_once ABSPATH . 'wp-admin/includes/import.php';
+
+ if ( !class_exists( 'WP_Importer' ) ) {
+    $class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
+    if ( file_exists( $class_wp_importer ) ) {
+        require_once $class_wp_importer;
+     }
+ }
+
+ if (class_exists('WP_Importer')) {
+
+    /**
+     * CouponImage_Import
+     *
+     * @uses WP_Importer
+     * @package Webdav
+     * @version //autogen//
+     * @copyright Copyright (c) 2010 All rights reserved.
+     * @author  Steve Sutton <steve@gaslightmedia.com>
+     * @license PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
+     */
+    class CouponImage_Import extends WP_Importer
+    {
+        private $_dbh;
+        private $_post;
+        private $_options;
+
+
+        public function __construct()
+        {
+            $this->_getOptions();
+        }
+
+        private function _getOptions()
+        {
+            // read options for the import and if they aren't set then give a warning.
+            $this->_options = get_option(GLM_WP_IMPORT_SETTINGS);
+        }
+
+        private function _connect()
+        {
+            if ($this->_dbh) {
+                return;
+            }
+            // try making a postgres connection to the database
+            $connString  = 'dbname=' . $this->_options['db_name'];
+            $connString .= ' host=' . $this->_options['db_host'];
+            $connString .= ' user=' . $this->_options['db_user'];
+            $driverOptions = array(
+                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
+            );
+            $this->_dbh = new PDO('pgsql:'.$connString, null, null, $driverOptions);
+            $this->_dbh->setAttribute(
+                PDO::ATTR_ERRMODE,
+                PDO::ERRMODE_EXCEPTION
+            );
+        }
+
+        private function _header()
+        {
+            echo '<div class="wrap">';
+            echo '<h2>'.__('Coupon Image Importer').'</h2>';
+        }
+
+        private function _footer()
+        {
+            echo '</div>';
+        }
+
+        private function _checkRequiredOptions()
+        {
+            $errors = array();
+            if (!$this->_options['site_url']) {
+                $errors[] = 'Site URL';
+            }
+            if (!$this->_options['db_host']) {
+                $errors[] = 'Database Host';
+            }
+            if (!$this->_options['db_name']) {
+                $errors[] = 'Database Name';
+            }
+            if (!$this->_options['db_user']) {
+                $errors[] = 'Database Usecr';
+            }
+            if (!$this->_options['toolbox_schema']) {
+                $errors[] = 'Toolbox Schema';
+            }
+            if (!$this->_options['toolbox_page_table']) {
+                $errors[] = 'Toolbox Page Table';
+            }
+            if (!$this->_options['toolbox_paragraphs_table']) {
+                $errors[] = 'Toolbox Paragraph Table';
+            }
+            if (!$this->_options['toolbox_files_table']) {
+                $errors[] = 'Toolbox Files Table';
+            }
+            return $errors;
+        }
+
+        private function _greet()
+        {
+            // Verify that everything is setup
+            $checkErrors = $this->_checkRequiredOptions();
+                echo '<p>Confirming Settings...</p>';
+            if (isset($checkErrors) && is_array($checkErrors) && !empty($checkErrors)) {
+                printf("<pre>Please update empty GLM Import <a href=\"%s\">Settings</a>:\n%s</pre>",
+                    'options-general.php?page=glmwpimporter',
+                    implode("\n", $checkErrors)
+                );
+            } else {
+                echo '<p>Coupon Images</p>';
+            }
+        }
+
+        private function _handleMediaFile(
+            $file,
+            $file_title,
+            $caption = '',
+            $post_id = 0,
+            $baseUrl = null
+        ) {
+            set_time_limit(120);
+            if ($post_id) {
+                $post = get_post($post_id);
+            }
+            if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
+                return new WP_Error('upload_error', $uploads['error']);
+            }
+            $filename = $this->_fetchRemoteImage($file, $uploads['path'], $baseUrl);
+            $new_file = $uploads['path'] . '/' . $filename;
+            $url      = $uploads['url'] . '/' . $filename;
+            $return   = apply_filters('wp_handle_upload', array('file' => $new_file, 'url' => $url, 'type' => wp_check_filetype($file, null)));
+            $new_file = $return['file'];
+            $url      = $return['url'];
+            $type     = $return['type'];
+
+            $title = preg_replace('!\.[^.]+$!', '', basename($file));
+            $content = '';
+            // use image exif/iptc data for title and caption defaults if possible
+            if ($image_meta = wp_read_image_metadata($new_file)) {
+                if ('' != trim( $image_meta['title'])) {
+                    $title = trim( $image_meta['title']);
+                }
+                if ('' != trim( $image_meta['caption'])) {
+                    $content = trim($image_meta['caption']);
+                }
+            }
+            $post_date     = current_time('mysql');
+            $post_date_gmt = current_time('mysql', 1);
+            // Construct the attachment array
+            $wp_filetype = wp_check_filetype(basename($filename), null);
+            $attachment = array(
+                'post_mime_type' => $wp_filetype['type'],
+                'guid'           => $url,
+                'post_parent'    => $post_id,
+                'post_title'     => $file_title,
+                'post_name'      => $title,
+                'post_content'   => $content,
+                'post_excerpt'   => $caption,
+                'post_date'      => $post_date,
+                'post_date_gmt'  => $post_date_gmt
+             );
+            // Insert attachment
+            $id = wp_insert_attachment($attachment, $new_file, $post_id);
+            if (!is_wp_error($id)) {
+                $data = wp_generate_attachment_metadata($id, $new_file);
+                wp_update_attachment_metadata($id, $data);
+                $this->_files[$id] = $file;
+            }
+            return $id;
+        }
+
+        private function _fetchRemoteImage($file, $path, $baseUrl = null)
+        {
+            $filename = wp_unique_filename($path, $file);
+
+            $fp = fopen($path . '/' . $filename, 'w+');
+            $fileUrl = ($baseUrl) ? $baseUrl . '/' . $file : $this->_options['toolbox_image_url'] . $file;
+            $ch = curl_init($fileUrl);
+            curl_setopt($ch, CURLOPT_TIMEOUT, 50);
+            curl_setopt($ch, CURLOPT_FILE, $fp);
+            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+            $imgData = curl_exec($ch);
+            $httpCode = curl_getinfo($ch);
+            curl_close($ch);
+            fclose($fp);
+            // Set correct file permissions
+            $oldUmask = umask(0);
+            chmod( $path . '/' . $filename, 0660 );
+            umask($oldUmask);
+            return $filename;
+        }
+
+        private function _fetchAllCouponImages()
+        {
+            global $wpdb;
+            $found = $missing = 0;
+            $images = array();
+            $this->_connect();
+            $sql = "
+            SELECT *
+              FROM coupons.coupons
+             WHERE image != ''";
+            $stmt = $this->_dbh->query($sql);
+            echo '<p>toolbox_image_url: ' . $this->_options['toolbox_image_url'] . '</p>';
+            while( $coupon = $stmt->fetch() ) {
+                //echo '<pre>coupon: ' . print_r($coupon, true) . '</pre>';
+                $images[] = $coupon['img'];
+                $sql = "
+                SELECT *
+                  FROM {$wpdb->prefix}posts
+                 WHERE post_title = '{$coupon['title']}'
+                   AND post_type = 'glm_coupons'";
+                $results = $wpdb->get_results($sql, ARRAY_A);
+                //echo '<pre>Results: ' . print_r($results, true)  . '</pre>';
+                if ($results) {
+                    foreach( $results as $rPost ) {
+                        $ePost = get_post($rPost['ID'], ARRAY_A);
+                        // get the post meta
+                        $post_custom = get_post_custom($rPost['ID']);
+                        //echo '<pre>post_custom: ' . print_r($post_custom, true)  . '</pre>';
+                        $sdate  = $post_custom['glm_coupons_startdate'][0];
+                        $edate  = $post_custom['glm_coupons_enddate'][0];
+                        $expire = $post_custom['glm_coupons_expdate'][0];
+                        $url    = $post_custom['glm_coupons_url'][0];
+                        if ( $url == $coupon['url'] ) {
+                            $img_id = $this->_handleMediaFile(
+                                $coupon['image'],
+                                '',
+                                '',
+                                $rPost['ID'],
+                                $this->_options['toolbox_image_url'] . '/CKImage'
+                            );
+                            //echo '<pre>Image Id: ' . print_r($img_id, true) . '</pre>';
+                            //echo '<pre>Results: ' . print_r($ePost['ID'], true)  . '</pre>';
+                            if ($img_id) {
+                                update_post_meta(
+                                    $rPost['ID'],
+                                    '_thumbnail_id',
+                                    $img_id
+                                );
+                            }
+                        }
+                        //echo '<p>sdate: ' . $sdate . '</p>';
+                        //echo '<p>edate: ' . $edate . '</p>';
+                        //echo '<p>expire: ' . $expire . '</p>';
+                        //echo '<p>url: ' . $url . '</p>';
+
+                    }
+                }
+            }
+            sort($images, SORT_NATURAL);
+            $imgUnique = array_unique($images);
+            echo '<p>Number of images ' . count($images) . '</p>';
+            //echo '<p>Number of unique images ' . count($imgUnique) . '</p>';
+            echo '<pre>' . print_r($images, true) . '</pre>';
+        }
+        public function dispatch()
+        {
+            $this->_header();
+
+            if (empty($_GET['step'])) {
+                $step = 0;
+            } else {
+                $step = filter_var($_GET['step'], FILTER_VALIDATE_INT);
+            }
+            switch($step) {
+            case 0:
+                $this->_greet();
+                echo '<p><a href="admin.php?import=couponimages&amp;step=1">Import Images</a></p>';
+                break;
+            case 1:
+                $this->_fetchAllCouponImages();
+                break;
+            }
+
+            $this->_footer();
+        }
+    }
+}
+
+$toolbox_import = new CouponImage_Import();
+
+register_importer(
+     'couponimages',
+     __('Coupon Images', 'import-coupon-images'),
+     sprintf(
+         __('Import the images of Gaslight Coupons into Time.ly coupons.
+         Visit <a href="%s">setup</a> first to setup the database options.',
+         'import-coupon-images'),
+         'options-general.php?page=glmwpimporter'
+     ),
+     array($toolbox_import, 'dispatch')
+);
index 2d81679..42aebfc 100644 (file)
--- a/index.php
+++ b/index.php
@@ -18,6 +18,7 @@ if (is_admin()) {
     require_once 'controllers/Admin.php';
     require_once 'controllers/ToolboxImport.php';
     require_once 'controllers/EventImageImport.php';
+    require_once 'controllers/CouponImageImport.php';
     require_once 'controllers/BlogImageImport.php';
     register_activation_hook(__FILE__, array('GlmWPImporter_Admin_Controller', 'activate_plugin'));
     register_deactivation_hook(__FILE__, array('GlmWPImporter_Admin_Controller', 'deactivate_plugin'));