Updates for importers
authorSteve Sutton <steve@gaslightmedia.com>
Mon, 28 Sep 2015 13:40:05 +0000 (09:40 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Mon, 28 Sep 2015 13:40:05 +0000 (09:40 -0400)
adding Event Image Importer

controllers/EventImageImport.php [new file with mode: 0644]
controllers/Import.php [deleted file]
controllers/ToolboxImport.php [new file with mode: 0644]
index.php

diff --git a/controllers/EventImageImport.php b/controllers/EventImageImport.php
new file mode 100644 (file)
index 0000000..4ffce76
--- /dev/null
@@ -0,0 +1,445 @@
+<?php
+
+/**
+ * EventImageImport.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      <>
+ */
+
+/**
+ * EventImageImport
+ *
+ * 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')) {
+
+    /**
+     * EventImage_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 EventImage_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>'.__('Event 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>Event 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 _getPageTitleById($id)
+        {
+            $this->_connect();
+            if ($this->_options['toolbox_page_table'] == 'pages') {
+                $sql = "
+                SELECT navigation_name
+                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                 WHERE id = :id";
+            } else {
+                $sql = "
+                SELECT category as navigation_name
+                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                 WHERE id = :id";
+            }
+            $stmt = $this->_dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        }
+
+        private function _updateFilesHref()
+        {
+            global $wpdb;
+            $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
+            $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array());
+            echo '<pre>' . print_r($files, true) . '</pre>';
+            //$images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
+            //$media = array_merge($images, $files);
+            //echo '<pre>' . print_r($media, true) . '</pre>';
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_content LIKE '%http://is0.gaslightmedia.com%'
+               AND post_type = 'page'";
+            $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
+            $results = $wpdb->get_results($sql, OBJECT);
+            if (count($results) > 0) {
+                foreach ($results as $post) {
+                    $content = $post->post_content;
+                    echo '<div style="border: 1px solid green; padding: 9px; margin: 10px;">';
+                    $urlPattern = '%<a href="(' . $this->_options['toolbox_image_url'] . '/[^">]*)" ?[^>]*>([^>]+)</a>%s';
+                    if (preg_match_all($urlPattern, $content, $isMatch)) {
+                        $isMatchCount = count($isMatch[0]);
+                        echo '<p>Matches is0 ' . $isMatchCount . '</p>';
+                        for ($index = 0; $index < $isMatchCount; ++$index) {
+                            echo '<pre>'.htmlspecialchars($isMatch[1][$index]).'</pre>';
+                            //echo '<pre>'.htmlspecialchars(basename($isMatch[1][$index])).'</pre>';
+                            //echo '<pre>'.print_r(pathinfo($isMatch[1][$index]), true).'</pre>';
+                            $fileInfo = pathinfo($isMatch[1][$index]);
+                            $fileName = $fileInfo['filename'];
+                            echo '<pre>File Name: ' . print_r($fileName, true)  . '</pre>';
+                            echo '<pre>File Name: ' . print_r($fileInfo, true)  . '</pre>';
+                            $fileTitle = $isMatch[2][$index];
+                            echo '<pre>File Title: ' . print_r($fileTitle, true)  . '</pre>';
+                            $key = $this->_getAttachmentByName($fileName);
+                            echo '<pre>Key: ' . print_r($key, true)  . '</pre>';
+                            // check on format of filename
+                            if (!$key && ($fileName && $fileTitle)) {
+                                $key = $this->_handleMediaFile(
+                                    $fileName,
+                                    $fileTitle,
+                                    '',
+                                    $post->ID,
+                                    $this->_options['site_url'] . '/uploads/'
+                                );
+                            }
+                            if ($key !== false) {
+                                var_dump($key);
+                                $newSrc = wp_get_attachment_url($key);
+                                $content = str_replace($isMatch[1][$index], $newSrc, $content);
+                            }
+                        }
+                        $updatePost = array(
+                            'ID'           => $post->ID,
+                            'post_content' => $content
+                        );
+                        wp_update_post($updatePost);
+                    }
+                    echo '<pre>'.htmlspecialchars($content).'</pre>';
+                    echo '</div>';
+                }
+            }
+        }
+
+        private function replaceIsoUrls()
+        {
+            global $wpdb;
+            $this->_connect();
+            echo '<p>Replace IS0 url\'s</p>';
+            $searchUrl = 'http://is0.gaslightmedia.com';
+            // find all pages with links to site pages
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_content LIKE '%{$searchUrl}%'
+               AND post_type = 'page'";
+            echo '<pre>'.$sql.'</pre>';
+            $results = $wpdb->get_results($sql, OBJECT);
+            if (count($results) > 0) {
+                //echo '<pre>' . print_r($results, true) . '</pre>';
+                $pattern = ';(http://is0.gaslightmedia.com/[^"]+);si';
+                foreach ($results as $post) {
+                    $content = $post->post_content;
+                    preg_match_all($pattern, $post->post_content, $matches);
+                    $matches = array_unique($matches[0]);
+                    echo '<pre>' . print_r($post->ID, true) . '</pre>';
+                    echo '<pre>' . print_r($matches, true) . '</pre>';
+                    foreach ($matches as $match) {
+                        // process the file as media library
+                        $parsed   = parse_url($match);
+                        $filename = basename($parsed['path']);
+                        $rootUrl  = str_replace('/' . $filename, '', $match);
+                        echo '<pre>' . print_r($parsed, true) . '</pre>';
+                        echo '<pre>' . print_r($filename, true) . '</pre>';
+                        echo '<pre>' . print_r($rootUrl, true) . '</pre>';
+                        $img_id = $this->_handleMediaFile(
+                            $filename,
+                            '',
+                            $post->ID,
+                            $rootUrl . '/'
+                        );
+                        echo '<pre>' . print_r($img_id, true) . '</pre>';
+                        $replaceUrl = wp_get_attachment_url($img_id);
+                        echo '<pre>' . print_r($image, true) . '</pre>';
+                        $content = str_replace($match, $replaceUrl, $content);
+                     }
+                    $updatePost = array(
+                        'ID'           => $post->ID,
+                        'post_content' => $content
+                    );
+                    wp_update_post($updatePost);
+                }
+            }
+        }
+
+        private function _fetchAllEventImages()
+        {
+            global $wpdb;
+            $found = $missing = 0;
+            $images = array();
+            $this->_connect();
+            $sql = "
+            SELECT id,header,img
+              FROM events.event
+             WHERE img != ''";
+            $stmt = $this->_dbh->query($sql);
+            echo '<p>' . $this->_options['toolbox_image_url'] . '</p>';
+            while( $event = $stmt->fetch() ) {
+                //echo '<pre>' . print_r($event, true) . '</pre>';
+                $images[] = $event['img'];
+                //$sql = "
+                //SELECT *
+                  //FROM {$wpdb->prefix}ai1ec_events
+                 //WHERE ical_uid = '{$event['id']}@emmetcounty.org'";
+                //$results = $wpdb->get_results($sql, ARRAY_A);
+                //echo '<pre>Results: ' . print_r($results, true)  . '</pre>';
+                //if ($results) {
+                    //$ePost = get_post($results[0]['post_id'], ARRAY_A);
+                    //$img_id = $this->_handleMediaFile(
+                        //$event['img'],
+                        //'',
+                        //'',
+                        //$results[0]['post_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(
+                            //$results[0]['post_id'],
+                            //'_thumbnail_id',
+                            //$img_id
+                        //);
+                    //}
+                //}
+            }
+            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=eventimages&amp;step=1">Import Images</a></p>';
+                break;
+            case 1:
+                //echo '<p>Weeee!!!!</p>';
+                $this->_fetchAllEventImages();
+                break;
+            }
+
+            $this->_footer();
+        }
+    }
+}
+
+$toolbox_import = new EventImage_Import();
+
+register_importer(
+     'eventimages',
+     __('Event Images', 'import-event-images'),
+     sprintf(
+         __('Import the images of Gaslight Events into Time.ly events.
+         Visit <a href="%s">setup</a> first to setup the database options.',
+         'import-event-images'),
+         'options-general.php?page=glmwpimporter'
+     ),
+     array($toolbox_import, 'dispatch')
+);
diff --git a/controllers/Import.php b/controllers/Import.php
deleted file mode 100644 (file)
index 43a77fb..0000000
+++ /dev/null
@@ -1,1377 +0,0 @@
-<?php
-
-/**
- * Import.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      <>
- */
-
-/**
- * GlmWPImporter_Import_Controller
- *
- * 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';
- define('PAGES_PER_LOAD', 5);
-
- 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')) {
-
-    /**
-     * Toolbox_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 Toolbox_Import extends WP_Importer
-    {
-        private $_dbh;
-        private $_post;
-        private $_options;
-        private $_files = array();
-        private $_images = array();
-
-
-        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>'.__('Toolbox 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>All Set!</p>';
-                $this->_connect();
-                $WHERE = $this->_getWhereSql();
-                $sql = "
-                SELECT count(*)
-                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
-                 $WHERE";
-                //echo '<pre>' . $sql . '</pre>';
-                $totalPages = $this->_dbh->query($sql)->fetchColumn();
-                printf('<p>Found %d Pages</p>', $totalPages);
-                //echo '<p><a href="admin.php?import=toolbox&amp;step=2">Part 2</a></p>';
-            }
-        }
-
-        private function _displayImage($data, $alignment)
-        {
-            if (!isset($data['image'])) {
-                return false;
-            }
-            $img_url = $this->_options['toolbox_image_url'] . '/tbs1/' . $data['image'];
-            $content = '';
-            if (isset($data['caption']) && $data['caption']) {
-                $content .= '[caption align="align'.$alignment.'"]<img  src="' . $img_url . '"> ' . $data['caption'] . '[/caption]';
-            } else if (isset($data['imagename']) && $data['imagename']) {
-                $content .= '[caption align="align'.$alignment.'"]<img  src="' . $img_url . '"> ' . $data['imagename'] . '[/caption]';
-            } else {
-                $content .= '<img class="align'.$alignment.'" src="' . $img_url . '">';
-            }
-            return $content;
-        }
-
-        private function _getDescriptionImage($src)
-        {
-            $parsed = parse_url($src);
-            $fileName = basename($parsed['path']);
-            $rootUrl = str_replace('/' . $fileName, '', $src);
-            $img_id = $this->_handleMediaFile(
-                basename($parsed['path']),
-                '',
-                0,
-                $rootUrl . '/'
-            );
-            $image = wp_get_attachment_image_src($img_id, 'medium');
-            return $image[0];
-        }
-
-        private function _displayFile($data)
-        {
-            //if ($this->_options['toolbox_paragraphs_table'] == 'pages') {
-                //$file_id = $this->_handleMediaFile($data['filename']);
-            //} else {
-                //$file_id = $this->_handleMediaFile(
-                    //$data['filename'],
-                    //'',
-                    //0,
-                    //$this->_options['site_url'] . 'uploads/'
-                //);
-            //}
-
-            //if (!$file_id) {
-                //return false;
-            //}
-            //$fileUrl = wp_get_attachment_url($file_id);
-            $fileUrl =$this->_options['toolbox_image_url'] . '/original/' . $data['filename'];
-            $fileName = ($data['urltext']) ? $data['urltext'] : $data['filename'];
-            return "\n".'<a href="'.$fileUrl.'">'.$fileName.'</a>';
-        }
-
-        private function _addMedia($file, $postId)
-        {
-            $fileType = wp_check_filetype(basename($file), null);
-            $wpUploadDir = wp_upload_dir();
-            $attachment = array(
-                'guid'           => $wpUploadDir . '/' . basename($file),
-                'post_mime_type' => $fileType['type'],
-                'post_title'     => basename($file),
-                'post_content'   => '',
-                'post_status'    => 'inherit'
-            );
-            $id = wp_insert_attachment($attachment, $file, $postId);
-            if (!is_wp_error($id)) {
-                $data = wp_generate_attachment_metadata($id, $file);
-                wp_update_attachment_metadata($id, $data);
-            }
-            return ($id) ? $this->_getAttachmentById($id) : false;
-        }
-
-        private function _handleMediaFile(
-            $file,
-            $file_title,
-            $caption = '',
-            $post_id = 0,
-            $baseUrl = null
-        ) {
-            $id = array_search($file, $this->_files);
-            if ($id === false) {
-                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 _getSubPageIds($parent)
-        {
-            $this->_connect();
-            $pageIds = array();
-            $sql = "
-            SELECT id
-              FROM {$this->_options['toolbox_page_table']}
-             WHERE parent = :parent";
-            $stmt = $this->_dbh->prepare($sql);
-            $stmt->bindParam(':parent', $parent, PDO::PARAM_INT);
-            $stmt->execute();
-            while ($page = $stmt->fetch()) {
-                $pageIds[] = $page['id'];
-                $subPageIds = $this->_getSubPageIds($page['id']);
-                if (!empty($subPageIds)) {
-                    $pageIds = array_merge($pageIds, $subPageIds);
-                }
-            }
-            return $pageIds;
-        }
-
-        private function _getWhereSql()
-        {
-            $WHERE = '';
-            $where = array();
-            if ($this->_options['include_pages']) {
-                if (filter_var($this->_options['include_pages'], FILTER_VALIDATE_INT)) {
-                    $subPageIds = $this->_getSubPageIds($this->_options['include_pages']);
-                    if (!empty($subPageIds)) {
-                        $where[] = "(id = {$this->_options['include_pages']}"
-                        . " OR id IN (" . implode(',', $subPageIds) . ") )";
-                    } else {
-                        $where[] = "id = {$this->_options['include_pages']}";
-                    }
-
-                } else {
-                    $where[] = "id IN ({$this->_options['include_pages']})";
-                }
-            }
-            if ($this->_options['exclude_pages']) {
-                $where[] = "id NOT IN ({$this->_options['exclude_pages']})
-                    AND parent NOT IN ({$this->_options['exclude_pages']}) ";
-            }
-            $where[] = "active = true";
-            if (!empty($where)) {
-                $WHERE = ' WHERE ' . implode(' AND ', $where);
-            }
-            return $WHERE;
-        }
-
-        private function _fetchAllPages($limit = null, $offset = 0)
-        {
-            $this->_connect();
-            $WHERE = $this->_getWhereSql();
-            $pageSql = "
-              SELECT *
-                FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
-                $WHERE
-            ORDER BY parent,pos";
-            $pageSql .= ($limit) ? " LIMIT $limit OFFSET $offset" : '';
-            $pageData = $this->_dbh->query($pageSql)->fetchAll(PDO::FETCH_ASSOC);
-            if ($this->_options['toolbox_page_table'] == 'pages') {
-                $paragraphSql = "
-                  SELECT *
-                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_paragraphs_table']}
-                   WHERE page = :page
-                     AND active = true
-                ORDER BY pos";
-                $paraStmt = $this->_dbh->prepare($paragraphSql);
-                $fileSql = "
-                  SELECT *
-                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_files_table']}
-                   WHERE paragraph = :pid
-                ORDER BY pos";
-                $fileStmt = $this->_dbh->prepare($fileSql);
-            } else {
-                $paragraphSql = "
-                  SELECT b.*
-                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_paragraphs_table']} b
-                         LEFT OUTER JOIN bus_category_bus bcb ON (bcb.busid = b.id)
-                   WHERE bcb.catid = :page
-                ORDER BY bcb.pos";
-                $paraStmt = $this->_dbh->prepare($paragraphSql);
-                $fileSql = "
-                  SELECT *
-                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_files_table']}
-                   WHERE bus_id = :pid
-                ORDER BY bus_id,pos";
-                $fileStmt = $this->_dbh->prepare($fileSql);
-            }
-            $data = $this->_dbh->query($pageSql)->fetchAll();
-            //echo '<pre>' . print_r($data, true) . '</pre>';
-            //exit;
-            foreach ($data as &$page) {
-                $page['srcs'] = array();
-                $paraStmt->bindParam(':page', $page['id'], PDO::PARAM_INT);
-                $paraStmt->execute();
-                $paragraphs     = $paraStmt->fetchAll();
-            //echo '<pre>' . print_r($paragraphs, true) . '</pre>';
-            //exit;
-                $primaryAlign   = 'right';
-                $secondaryAlign = 'right';
-                $alternateImg   = false;
-
-                switch ($page['template']) {
-                case 1:
-                    break;
-                case 2:
-                    $primaryAlign   = 'left';
-                    $secondaryAlign = 'left';
-                    break;
-                case 3:
-                    $secondaryAlign = 'left';
-                    $alternateImg   = true;
-                    break;
-                case 4:
-                    $primaryAlign   = 'left';
-                    $alternateImg   = true;
-                    break;
-                case 5:
-                    $primaryAlign   = 'left';
-                    break;
-                case 6:
-                    $secondaryAlign = 'left';
-                    break;
-                }
-                $page['pageContent'] = '';
-                $iterator = 1;
-                if ($this->_options['toolbox_page_table'] == 'bus_category') {
-                    $page['pageContent'] .= '<h1>'.$page['category'].'</h1>';
-                    ++$iterator;
-                    if ($page['image']) {
-                        //$page['images'][]     = $page['image'];
-                        $page['pageContent'] .= $this->_displayImage($page, $primaryAlign);
-                    }
-                    $page['pageContent'] .= $page['description'];
-                }
-
-                foreach ($paragraphs as $paragraph) {
-                    switch ($iterator) {
-                    case 1:
-                        if (isset($paragraph['title']) && $paragraph['title']) {
-                            $page['pageContent'] .= '<h1>'.$paragraph['title'].'</h1>';
-                        }
-                        if (isset($paragraph['image']) && $paragraph['image']) {
-                            //$page['images'][]     = $paragraph['image'];
-                            $page['pageContent'] .= $this->_displayImage($paragraph, $primaryAlign);
-                        }
-                        break;
-                    case 2:
-                        if (isset($paragraph['name']) && $paragraph['name']) {
-                            $page['pageContent'] .= '<h2>'.$paragraph['name'].'</h2>';
-                        }
-                        if (isset($paragraph['title']) && $paragraph['title']) {
-                            $page['pageContent'] .= '<h2>'.$paragraph['title'].'</h2>';
-                        }
-                        if (isset($paragraph['image']) && $paragraph['image']) {
-                            //$page['images'][]     = $paragraph['image'];
-                            $page['pageContent'] .= $this->_displayImage($paragraph, $secondaryAlign);
-                        }
-                        break;
-                    default:
-                        if (isset($paragraph['name']) && $paragraph['name']) {
-                            $page['pageContent'] .= '<h2>'.$paragraph['name'].'</h2>';
-                        }
-                        if (isset($paragraph['title']) && $paragraph['title']) {
-                            $page['pageContent'] .= '<h2>'.$paragraph['title'].'</h2>';
-                        }
-                        if (isset($paragraph['template']) && $alternateImg && $page['template'] == 2) {
-                            $align = ($iterator%2 == 0) ? 'left' : 'right';
-                        } else {
-                            $align = $secondaryAlign;
-                        }
-                        if (isset($paragraph['image']) && $paragraph['image']) {
-                            //$page['images'][]     = $paragraph['image'];
-                            $page['pageContent'] .= $this->_displayImage($paragraph, $align);
-                        }
-                        break;
-                    }
-                    $page['pageContent'] .= $paragraph['description'];
-                    //preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $paragraph['description'], $matches);
-            //echo '<pre>' . print_r($matches, true) . '</pre>';
-
-                    /*
-                    for ($i = 0; $i < count($matches[0]); $i++) {
-                        if ($matches[1][$i]) {
-                            $newSrc  = $this->_getDescriptionImage($matches[1][$i]);
-                            $parsUrl = parse_url($newSrc);
-                            $imgName = basename($parsUrl['path']);
-                            $page['pageContent'] = str_replace($matches[1][$i], $newSrc, $page['pageContent']);
-                            $page['srcs'][] = $imgName;
-                        }
-                    }
-                     */
-                    //var_dump($paragraph['id']);
-                    $fileStmt->bindParam(':pid', $paragraph['id'], PDO::PARAM_INT);
-                    $fileStmt->execute();
-                    while ($file = $fileStmt->fetch()) {
-            //echo '<pre>Files: ' . print_r($file, true) . '</pre>';
-                        //$page['files'][] = $file['filename'];
-                        $page['pageContent'] .= $this->_displayFile($file);
-                    }
-                    ++$iterator;
-                }
-                //echo '<pre>Files: ' . print_r($page['files'], true) . '</pre>';
-            }
-            return $data;
-        }
-
-        private function _readOptions()
-        {
-            echo '<pre>' . print_r($this->_options, true) . '</pre>';
-            echo '<pre>' . print_r(get_option(GLM_WP_IMPORT_POST_OPTION, array()), true) . '</pre>';
-        }
-
-        private function _import()
-        {
-            echo '<p>Fetching Pages</p>';
-            $this->_post = get_option(GLM_WP_IMPORT_POST_OPTION, array());
-            // grab all pages and build the post array
-            $start = filter_var($_REQUEST['start'], FILTER_VALIDATE_INT);
-            //$pages = $this->_fetchAllPages(PAGES_PER_LOAD, $start);
-            $pages = $this->_fetchAllPages();
-            //foreach ($pages as $page) {
-                //echo '<pre>' . print_r(htmlspecialchars($page['pageContent']), true) . '</pre>';
-            //}
-            //echo '<pre>' . print_r($pages, true) . '</pre>';
-            //return;
-            //exit;
-            $numPagesImported = count($pages);
-
-            foreach ($pages as $page) {
-                if ($page['parent']) {
-
-                }
-                $pageName = (isset($page['navigation_name']))
-                    ? $page['navigation_name']
-                    : $page['category'];
-                // if you don't find the parent page id then use the default given or 0
-                $parent = isset($this->_post[$page['parent']])
-                    ? $this->_post[$page['parent']]
-                    : (($this->_options['parent_page']) ? $this->_options['parent_page'] : 0);
-                $post = array(
-                    'post_content'   => $page['pageContent'],
-                    'post_name'      => $pageName,// slug ?
-                    'post_title'     => $pageName,
-                    'post_status'    => 'publish',
-                    'post_type'      => 'page',
-                    'post_author'    => 'steve',
-                    'ping_status'    => 'closed',
-                    'post_parent'    => $parent,
-                    'menu_order'     => $page['pos'],
-                    'comment_status' => 'closed',
-                );
-                $ID = wp_insert_post($post, true);
-                $newPost = get_post($ID, ARRAY_A);
-                $this->_post[$page['id']] = $ID;
-            }
-            $this->_storePost();
-            return $numPagesImported;
-        }
-
-        private function _storePost()
-        {
-            update_option(GLM_WP_IMPORT_POST_OPTION, $this->_post);
-        }
-
-        private function _storeImages()
-        {
-            update_option(GLM_WP_IMPORT_IMAGES_OPTION, $this->_images);
-        }
-
-        private function _storeFiles()
-        {
-            update_option(GLM_WP_IMPORT_FILES_OPTION, $this->_files);
-        }
-
-        private function _replaceKeywords()
-        {
-            global $wpdb;
-            $this->_connect();
-            echo '<p>Replace keywords</p>';
-            if ($this->_options['toolbox_page_table'] == 'pages') {
-                $sql = "
-                  SELECT id,navigation_name,keyword
-                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
-                   WHERE keyword != ''
-                ORDER BY parent,pos";
-            } else {
-                $sql = "
-                  SELECT id,category as navigation_name,keyword
-                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
-                   WHERE keyword != ''
-                ORDER BY parent,pos";
-            }
-            $stmt = $this->_dbh->query($sql);
-            while ($page = $stmt->fetch()) {
-                echo '<pre>' . print_r($page, true) .  '</pre>';
-                // find out which page (wp) this needs to be
-                $wpPost = get_page_by_title($page['navigation_name']);
-                if (!$wpPost) {
-                    continue;
-                }
-                //echo '<pre>' . print_r($wpPost, true) .  '</pre>';
-                echo '<pre>' . print_r(get_permalink($wpPost), true) .  '</pre>';
-                $replaceUrl = '<a href="'.get_permalink($wpPost->ID).'">' . $page['navigation_name'] . '</a>';
-
-                $sql = "
-                SELECT *
-                  FROM {$wpdb->prefix}posts
-                 WHERE post_content LIKE '%\{{$page['keyword']}\}%'
-                   AND post_type = 'page'";
-                $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
-                $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
-                //echo '<pre>' . print_r($sql, true) . '</pre>';
-                $results = $wpdb->get_results($sql, OBJECT);
-                $total = count($results);
-                if ($total > 0) {
-                    foreach ($results as $post) {
-                        //echo '<pre>' . print_r($post, true) . '</pre>';
-                        $content = $post->post_content;
-                        $content = preg_replace("/\{{$page['keyword']}\}/", $replaceUrl, $content);
-                        wp_update_post(array(
-                            'ID'           => $post->ID,
-                            'post_content' => $content
-                        ));
-                    }
-                }
-                echo '<p>Count results: ' . $total . '</p>';
-                //echo '<pre>' . print_r($results, true) . '</pre>';
-            }
-        }
-
-        private function _getPageTitleById($id)
-        {
-            $this->_connect();
-            if ($this->_options['toolbox_page_table'] == 'pages') {
-                $sql = "
-                SELECT navigation_name
-                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
-                 WHERE id = :id";
-            } else {
-                $sql = "
-                SELECT category as navigation_name
-                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
-                 WHERE id = :id";
-            }
-            $stmt = $this->_dbh->prepare($sql);
-            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
-            $stmt->execute();
-            return $stmt->fetchColumn();
-        }
-
-        private function _replaceUrls()
-        {
-            global $wpdb;
-            $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
-        echo '<pre>' . print_r($currentPostArray, true) . '</pre>';
-            $this->_connect();
-            echo '<p>Replace page url\'s</p>';
-            $searchUrl = $this->_options['site_url'];
-            $parsedUrl = parse_url($searchUrl);
-            // find all pages with links to site pages
-            $sql = "
-            SELECT *
-              FROM {$wpdb->prefix}posts
-             WHERE post_content LIKE '%{$searchUrl}%'
-               AND post_type = 'page'";
-            $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
-            $results = $wpdb->get_results($sql, OBJECT);
-            if (count($results) > 0) {
-                $pattern = ';http://' . $parsedUrl['host'] . '/([^"]+);si';
-                echo '<pre>' . print_r($pattern, true) . '</pre>';
-                //echo '<pre>' . print_r($results, true) . '</pre>';
-                foreach ($results as $post) {
-                    $content = $post->post_content;
-                    preg_match_all($pattern, $post->post_content, $matches);
-                    echo '<pre>' . print_r($matches, true) . '</pre>';
-                    foreach ($matches[0] as $match) {
-                        // find the page id for matched url
-                        if (preg_match(';-([0-9]+)/$;', $match, $found)) {
-                            echo '<pre>' . print_r($found, true) . '</pre>';
-                            if ($found && $currentPostArray[$found[1]]) {
-                                $wpPost = get_page($currentPostArray[$found[1]]);
-                                $replaceUrl = get_permalink($wpPost->ID);
-                                echo '<pre>' . print_r($replaceUrl, true) . '</pre>';
-                                $content = str_replace($match, $replaceUrl, $content);
-                            }
-                        }
-                     }
-                    $updatePost = array(
-                        'ID'           => $post->ID,
-                        'post_content' => $content
-                    );
-                    wp_update_post($updatePost);
-                }
-            }
-        }
-
-        function _handleAccents($content)
-        {
-            // from: http://www.php.net/manual/en/domdocument.loadhtml.php#91513
-            if ( !empty( $content ) && function_exists( 'mb_convert_encoding' ) ) {
-                mb_detect_order( "ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15" );
-                if ( empty( $encod ) ) {
-                    $encod = mb_detect_encoding( $content );
-                }
-                $headpos = mb_strpos( $content,'<head>' );
-                if ( FALSE === $headpos ) {
-                    $headpos= mb_strpos( $content,'<HEAD>' );
-                }
-                if ( FALSE !== $headpos ) {
-                    $headpos+=6;
-                    $content = mb_substr( $content,0,$headpos ) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr( $content,$headpos );
-                }
-                $content = mb_convert_encoding( $content, 'HTML-ENTITIES', $encod );
-            }
-            return $content;
-        }
-
-        private function _replaceSrc()
-        {
-            global $wpdb;
-            $files = $filesFound = $filesMissing = $fileDuplicates = array();
-            $this->_connect();
-            echo '<p>Replace Src\'s</p>';
-            $sql = "
-            SELECT *
-              FROM {$wpdb->prefix}posts
-             WHERE post_content LIKE '%<img%'
-               AND post_type = 'page'";
-            //$sql .= " AND post_title = 'Home'";
-            //$sql .= " AND ID = 2101";
-
-            $results = $wpdb->get_results($sql, OBJECT);
-            echo '<p>Number of Pages'.count($results).'</p>';
-            if (count($results) > 0) {
-                $pattern = ';(<img[^>]>);si';
-                foreach ($results as $post) {
-                    $dom = new DOMDocument('1.0', 'UTF-8');
-                    $content = $this->handle_accents($post->post_content);
-                    $dom->encoding = 'UTF-8';
-                    $test = $dom->loadHTML($content);
-                    //var_dump($test);
-                    $images = $dom->getElementsByTagName('img');
-                    foreach ($images as $image) {
-                        $files[] = $image->getAttribute('src');
-                        $width = $height = null;
-                        //echo '<div style="border: 1px solid black; background-color: lightgrey; padding: 15px;width: 600px;margin: 0 10px">';
-                        //echo '<pre>' . print_r($image, true)  . '</pre>';
-                        if ($image->hasAttribute('class')) {
-                            //echo '<pre>' . print_r($image->getAttribute('class'), true)  . '</pre>';
-                            if (preg_match('%wp-image-\d+%', $image->getAttribute('class'))) {
-                                //echo 'Continue';
-                                //echo '</div>';
-                                continue;
-                            }
-                        }
-                        if ($image->hasAttribute('style')) {
-                            $style = $image->getAttribute('style');
-                            //var_dump($style);
-                            //echo '<pre>' . print_r($style, true)  . '</pre>';
-                            if (preg_match('%[^-]width[: ]+(\d+)%', $style, $wMatch)) {
-                                $width = $wMatch[1];
-                                //echo '<pre>wMatch: ' . print_r($wMatch, true)  . '</pre>';
-                            }
-                            if (preg_match('%[^-]height[: ]+(\d+)%', $style, $hMatch)) {
-                                $height = $hMatch[1];
-                            }
-                            //echo '<pre>width: ' . print_r($width, true)  . '</pre>';
-                            //echo '<pre>height: ' . print_r($height, true)  . '</pre>';
-                        }
-                        if ($image->hasAttribute('width')) {
-                            $width = $image->getAttribute('width');
-                        }
-                        if ($image->hasAttribute('height')) {
-                            $height = $image->getAttribute('height');
-                        }
-                        if ($image->hasAttribute('src')) {
-                            //echo '<pre>' . print_r($image->getAttribute('src'), true)  . '</pre>';
-                            $imgName = basename($image->getAttribute('src'));
-                            //echo '<pre>' . print_r($imgName, true)  . '</pre>';
-                            $imgPathInfo = pathinfo($imgName);
-                            //echo '<pre>' . print_r($imgPathInfo, true) . '</pre>';
-                            $wpImage = $this->_getAttachmentByName($imgPathInfo['filename']);
-                            //echo '<pre>' . print_r($wpImage, true) . '</pre>';
-                            //exit;
-                            if (!$wpImage) {
-                                //echo '<p>Image not found as attachment</p>';
-                                //echo '<pre>' . print_r($imgPathInfo, true) . '</pre>';
-                                if (preg_match(';(is\d{2}-\d{10}-\d{5})(\d{1}|[-]\d+x\d+);', $imgPathInfo['filename'], $matches)) {
-                                    //echo '<p>Duplicate Image found</p>';
-                                    //echo '<pre>' . print_r($matches, true) . '</pre>';
-                                    $wpImage = $this->_getAttachmentByName($matches[1]);
-                                    if ($wpImage) {
-                                        //echo '<p>Found Image</p>';
-                                        $fileDuplicates[] = $image->getAttribute('src');
-                                    } else {
-                                        //echo '<p>Image still not found</p>';
-                                        //echo '</div>';
-                                        $filesMissing[] = $image->getAttribute('src');
-                                        continue;
-                                    }
-                                }
-                            }
-                            if (!$wpImage) {
-                                //echo '<p>Image not found as attachment 2</p>';
-                                //echo '<pre>' . print_r($image->getAttribute('src'), true) . '</pre>';
-                                $parsed   = parse_url($image->getAttribute('src'));
-                                $filename = basename($parsed['path']);
-                                if (preg_match(';is\d{2,}-\d{10,}-\d{5,};', $filename)) {
-                                    $rootUrl  = str_replace('/' . $filename, '', $image->getAttribute('src'));
-                                    //echo '<pre>' . print_r($parsed, true) . '</pre>';
-                                    //echo '<pre>' . print_r($filename, true) . '</pre>';
-                                    //echo '<pre>' . print_r($rootUrl, true) . '</pre>';
-                                    //if (preg_match('/(\d{4})\/(\d{2})$/', $rootUrl, $matches)) {
-                                        //echo '<pre>' . print_r($matches, true) . '</pre>';
-                                        //$uploadDir = wp_upload_dir();
-                                        //echo '<pre>' . print_r($uploadDir, true) . '</pre>';
-                                        //$absPath = $uploadDir['basedir'] . '/' . $matches[1] . '/' . $matches[2];
-                                        //echo '<pre>' . print_r($absPath, true) . '</pre>';
-                                        ////$wpImage = $this->_addMedia($absPath . '/' . $filename, $post->ID);
-                                        //echo '<pre>' . print_r($imageId, true) . '</pre>';
-                                    //}
-                                    //$fileExists = file_exists($upload_dir['baseurl'] . '/' . $filename);
-                                    //$wpImage = $this->_handleMediaFile(
-                                        //basename($parsed['path']),
-                                        //'',
-                                        //$post->ID,
-                                        //$rootUrl . '/'
-                                    //);
-                                }
-                            }
-                            if ($wpImage) {
-                                $filesFound[] = $image->getAttribute('src');
-                                //$strToReplace = $dom->saveHTML($image);
-                                //echo '<pre>'.htmlspecialchars($strToReplace).'</pre>';
-                                //echo '<p>Image found: id '.$wpImage->ID.'</p>';
-                                if ($width && $height) {
-                                    //echo '<p>width: ' . $width . '</p>';
-                                    //echo '<p>height: ' . $height . '</p>';
-                                    if ($width > 300 || $height > 300) {
-                                        //echo '<p>Found Large</p>';
-                                        $size = 'large';
-                                        $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
-                                        $image->setAttribute('class', 'alignnone wp-image-' . $wpImage->ID);
-                                        if($newImage) {
-                                            $image->setAttribute('src', $newImage[0]);
-                                        }
-                                    } else if ($width < 150 && $height < 150) {
-                                        //echo '<p>Found Thumbnail</p>';
-                                        $size = 'thumbnail';
-                                        $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
-                                        $image->setAttribute('class', 'alignnone size-' . $size . ' wp-image-' . $wpImage->ID);
-                                        if($newImage) {
-                                            $image->setAttribute('src', $newImage[0]);
-                                        }
-                                    } else {
-                                        //echo '<p>Found Medium</p>';
-                                        $size = 'medium';
-                                        $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
-                                        $image->setAttribute('class', 'alignnone size-' . $size . ' wp-image-' . $wpImage->ID);
-                                        if($newImage) {
-                                            $image->setAttribute('src', $newImage[0]);
-                                        }
-                                    }
-                                } else {
-                                    $size = 'large';
-                                    $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
-                                    $image->setAttribute('class', 'alignnone size-' . $size . ' wp-image-' . $wpImage->ID);
-                                    $width    = $newImage[1];
-                                    $height   = $newImage[2];
-                                    if($newImage) {
-                                        $image->setAttribute('src', $newImage[0]);
-                                    }
-                                }
-                                $image->removeAttribute('style');
-                                $image->setAttribute('width', $width);
-                                $image->setAttribute('height', $height);
-                                //echo htmlspecialchars($dom->saveHTML($image));
-                            } else {
-                                //echo '<p>no media found</p>';
-                                $filesMissing[] = $image->getAttribute('src');
-                            }
-                        }
-                        //echo '</div>';
-                    }
-                    // remove the extra stuff Dom put in
-                    $content = preg_replace(
-                        '/^<!DOCTYPE.+?>/',
-                        '',
-                        str_replace(
-                            array('<html>', '</html>', '<body>', '</body>'),
-                            array('', '', '', ''),
-                            $dom->saveHTML()
-                        )
-                    );
-                    //echo '<pre>'.print_r(htmlspecialchars($content), true).'</pre>';
-                    $updatePost = array(
-                        'ID'           => $post->ID,
-                        'post_content' => $content
-                    );
-                    wp_update_post($updatePost);
-                }
-                //echo '<pre>Files: ' . print_r($files, true) . '</pre>';
-                echo '<pre>Files Found: ' . print_r($filesFound, true) . '</pre>';
-                echo '<pre>Duplicate Files: ' . print_r($fileDuplicates, true) . '</pre>';
-                echo '<pre>Files Missing: ' . print_r($filesMissing, true) . '</pre>';
-            }
-        }
-
-        private function _updateFilesHref()
-        {
-            global $wpdb;
-            $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
-            $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array());
-            echo '<pre>' . print_r($files, true) . '</pre>';
-            //$images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
-            //$media = array_merge($images, $files);
-            //echo '<pre>' . print_r($media, true) . '</pre>';
-            $sql = "
-            SELECT *
-              FROM {$wpdb->prefix}posts
-             WHERE post_content LIKE '%http://is0.gaslightmedia.com%'
-               AND post_type = 'page'";
-            $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
-            $results = $wpdb->get_results($sql, OBJECT);
-            if (count($results) > 0) {
-                foreach ($results as $post) {
-                    $content = $post->post_content;
-                    echo '<div style="border: 1px solid green; padding: 9px; margin: 10px;">';
-                    $urlPattern = '%<a href="(' . $this->_options['toolbox_image_url'] . '/[^">]*)" ?[^>]*>([^>]+)</a>%s';
-                    if (preg_match_all($urlPattern, $content, $isMatch)) {
-                        $isMatchCount = count($isMatch[0]);
-                        echo '<p>Matches is0 ' . $isMatchCount . '</p>';
-                        for ($index = 0; $index < $isMatchCount; ++$index) {
-                            echo '<pre>'.htmlspecialchars($isMatch[1][$index]).'</pre>';
-                            //echo '<pre>'.htmlspecialchars(basename($isMatch[1][$index])).'</pre>';
-                            //echo '<pre>'.print_r(pathinfo($isMatch[1][$index]), true).'</pre>';
-                            $fileInfo = pathinfo($isMatch[1][$index]);
-                            $fileName = $fileInfo['filename'];
-                            echo '<pre>File Name: ' . print_r($fileName, true)  . '</pre>';
-                            echo '<pre>File Name: ' . print_r($fileInfo, true)  . '</pre>';
-                            $fileTitle = $isMatch[2][$index];
-                            echo '<pre>File Title: ' . print_r($fileTitle, true)  . '</pre>';
-                            $key = $this->_getAttachmentByName($fileName);
-                            echo '<pre>Key: ' . print_r($key, true)  . '</pre>';
-                            // check on format of filename
-                            if (!$key && ($fileName && $fileTitle)) {
-                                $key = $this->_handleMediaFile(
-                                    $fileName,
-                                    $fileTitle,
-                                    '',
-                                    $post->ID,
-                                    $this->_options['site_url'] . '/uploads/'
-                                );
-                            }
-                            if ($key !== false) {
-                                var_dump($key);
-                                $newSrc = wp_get_attachment_url($key);
-                                $content = str_replace($isMatch[1][$index], $newSrc, $content);
-                            }
-                        }
-                        $updatePost = array(
-                            'ID'           => $post->ID,
-                            'post_content' => $content
-                        );
-                        wp_update_post($updatePost);
-                    }
-                    echo '<pre>'.htmlspecialchars($content).'</pre>';
-                    echo '</div>';
-                }
-            }
-        }
-
-        private function _updateMediaSrc()
-        {
-            global $wpdb;
-            $images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
-            $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
-            $sql = "
-            SELECT *
-              FROM {$wpdb->prefix}posts
-             WHERE post_content LIKE '%<img%'
-               AND post_type = 'page'";
-            $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
-            $results = $wpdb->get_results($sql, OBJECT);
-            if (count($results) > 0) {
-                foreach ($results as $post) {
-                    $content = $post->post_content;
-                    echo '<pre>Updating Media Src\'s: ' . print_r($post->post_title, true)  . '</pre>';
-                    echo '<div style="border: 1px solid green; padding: 9px; margin: 10px;">';
-                    if (preg_match_all('%\[caption [^\]]+\]<img ([^>]+)>([^\[]*)\[/caption\]%', $content, $cMatch)) {
-                        $captionCount = count($cMatch[0]);
-                        echo '<p>Matches in Caption ' . $captionCount . '</p>';
-                        //echo '<pre>' . print_r($cMatch, true)  . '</pre>';
-                        for ($index = 0; $index < $captionCount; ++$index) {
-                            //echo '<pre>cMatch: ' . print_r($cMatch, true)  . '</pre>';
-                            echo '<pre>'.htmlspecialchars($cMatch[0][$index]).'</pre>';
-                            echo '<pre>Caption Match: ' . print_r($cMatch[1][$index], true)  . '</pre>';
-                            echo '<pre>Caption Text: ' . print_r($cMatch[2][$index], true)  . '</pre>';
-                            if (preg_match('%src="([^"]+)"%', $cMatch[1][$index], $srcMatch)) {
-                                echo '<pre>Sub Src Match: ' . print_r($srcMatch[1], true)  . '</pre>';
-                                $fileInfo = pathinfo($srcMatch[1]);
-                                $fileName = basename($srcMatch[1]);
-                                $fileName = $fileInfo['filename'];
-                                echo '<pre>File Name: ' . print_r($fileName, true)  . '</pre>';
-                                $path = str_replace($fileName, '', $srcMatch[1]);
-                                $path = $filInfo['dirname'];
-                                $imagesKey = $this->_getAttachmentByName($fileName);
-                                var_dump($imagesKey);
-                                if (!$imagesKey) {
-                                    $imagesKey = $this->_handleMediaFile(
-                                        $fileName,
-                                        $fileName,
-                                        '',
-                                        $post->ID,
-                                        $path
-                                    );
-                                }
-                                if ($imagesKey) {
-                                    var_dump($imagesKey);
-                                    $newImage = wp_get_attachment_image_src($imagesKey, 'medium');
-                                    // need to replace the src tags in content with the new image tags
-                                    $caption = str_replace(
-                                        'src="' . $srcMatch[1] . '"',
-                                        'src="' . $newImage[0] . '" width="' . $newImage[1] . '" height="' . $newImage[1] . '"',
-                                        $cMatch[0][$index]);
-                                    $caption = str_replace('<img', '<img class="wp-image-' . $imagesKey . ' size-medium"', $caption);
-                                    $caption = str_replace('[caption',
-                                        '[caption id="attachment_' . $imagesKey . '" width="' . $newImage[1] . '"',
-                                        $caption);
-                                    echo '<pre>'.htmlspecialchars($caption).'</pre>';
-                                    $content = str_replace($cMatch[0][$index], $caption, $content);
-                                }
-                            }
-                        }
-                    }
-                    // In this next part Have to remember the $content is already processed.
-                    // Don't edit src if they alrea,dy have an ID
-                    if (preg_match_all('%<img ([^>]+)>%', $content, $matches)) {
-                        $imageCount = count($matches[0]);
-                        for ($index = 0; $index < $imageCount; ++$index) {
-                            echo '<pre>Image Match: ' . $imageCount  . '</pre>';
-                            echo '<pre>'.htmlspecialchars($matches[0][$index]).'</pre>';
-                            if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
-                                return new WP_Error('upload_error', $uploads['error']);
-                            }
-                            echo '<pre>Uploads Url: ' . print_r($uploads['url'], true)  . '</pre>';
-                            if (preg_match('%src="' . $uploads['url'] . '[^"]+"%', $matches[1][$index], $pMatch)) {
-                                continue;
-                            }
-                            if (preg_match('%src="([^"]+)"%', $matches[1][$index], $srcMatch)) {
-                                echo '<pre>Sub Src Match: ' . print_r($srcMatch[1], true)  . '</pre>';
-                                $fileInfo = pathinfo($srcMatch[1]);
-                                echo '<pre>' . print_r($fileInfo, true) . '</pre>';
-                                $fileName = $fileInfo['filename'];
-                                echo '<pre>File Url: ' . print_r($srcMatch[1], true)  . '</pre>';
-                                echo '<pre>File Name: ' . print_r($fileName, true)  . '</pre>';
-                                $path = $filInfo['dirname'];
-                                echo '<pre>File Path: ' . print_r($path, true)  . '</pre>';
-                                $imagesKey = $this->_getAttachmentByName($fileName);
-                                var_dump($imagesKey);
-                                if (!$imagesKey) {
-                                    $imagesKey = $this->_handleMediaFile(
-                                        $fileName,
-                                        $fileName,
-                                        '',
-                                        $post->ID,
-                                        $path
-                                    );
-                                }
-                                if ($imagesKey) {
-                                    //var_dump($imagesKey);
-                                    $newUrl = wp_get_attachment_url($imagesKey);
-                                    // need to replace the src tags in content with the new image tags
-                                    $imageTag = str_replace($srcMatch[1], $newUrl, $matches[0][$index]);
-                                    if (preg_match('%class="([^"]+)"%', $matches[1][$index], $classMatch)) {
-                                        $imageTag = preg_replace('%class="([^"]+)"%', 'class="wp-image-' . $imagesKey . ' size-medium $1"', $imageTag);
-                                    } else {
-                                        $imageTag = str_replace('<img', '<img class="wp-image-' . $imagesKey . ' size-medium"', $imageTag);
-                                    }
-                                    //echo '<pre>'.htmlspecialchars($imageTag).'</pre>';
-                                    $content = str_replace($matches[0][$index], $imageTag, $content);
-                                }
-                            }
-                        }
-                    }
-                    echo '<pre>'.htmlspecialchars($content).'</pre>';
-                    echo '</div>';
-                    $updatePost = array(
-                        'ID'           => $post->ID,
-                        'post_content' => $content
-                    );
-                    wp_update_post($updatePost);
-                }
-            }
-        }
-
-        private function _getAttachmentByName($name)
-        {
-            global $wpdb;
-            $sql = "
-            SELECT *
-              FROM {$wpdb->prefix}posts
-             WHERE post_type = 'attachment'
-            AND (post_name like '{$name}%' OR post_title like '{$name}%')";
-            $results = $wpdb->get_results($sql, OBJECT);
-            return (!empty($results)) ? $results[0]->ID : false;
-            //return (!empty($results)) ? $results[0] : false;
-        }
-
-        private function _getAttachmentById($id)
-        {
-            global $wpdb;
-            $sql = "
-            SELECT *
-              FROM {$wpdb->prefix}posts
-             WHERE post_type = 'attachment'
-            AND ID = {$id}";
-            $results = $wpdb->get_results($sql, OBJECT);
-            return (!empty($results)) ? $results[0] : false;
-        }
-
-        private function replaceIsoUrls()
-        {
-            global $wpdb;
-            $this->_connect();
-            echo '<p>Replace IS0 url\'s</p>';
-            $searchUrl = 'http://is0.gaslightmedia.com';
-            // find all pages with links to site pages
-            $sql = "
-            SELECT *
-              FROM {$wpdb->prefix}posts
-             WHERE post_content LIKE '%{$searchUrl}%'
-               AND post_type = 'page'";
-            echo '<pre>'.$sql.'</pre>';
-            $results = $wpdb->get_results($sql, OBJECT);
-            if (count($results) > 0) {
-                //echo '<pre>' . print_r($results, true) . '</pre>';
-                $pattern = ';(http://is0.gaslightmedia.com/[^"]+);si';
-                foreach ($results as $post) {
-                    $content = $post->post_content;
-                    preg_match_all($pattern, $post->post_content, $matches);
-                    $matches = array_unique($matches[0]);
-                    echo '<pre>' . print_r($post->ID, true) . '</pre>';
-                    echo '<pre>' . print_r($matches, true) . '</pre>';
-                    foreach ($matches as $match) {
-                        // process the file as media library
-                        $parsed   = parse_url($match);
-                        $filename = basename($parsed['path']);
-                        $rootUrl  = str_replace('/' . $filename, '', $match);
-                        echo '<pre>' . print_r($parsed, true) . '</pre>';
-                        echo '<pre>' . print_r($filename, true) . '</pre>';
-                        echo '<pre>' . print_r($rootUrl, true) . '</pre>';
-                        $img_id = $this->_handleMediaFile(
-                            $filename,
-                            '',
-                            $post->ID,
-                            $rootUrl . '/'
-                        );
-                        echo '<pre>' . print_r($img_id, true) . '</pre>';
-                        $replaceUrl = wp_get_attachment_url($img_id);
-                        echo '<pre>' . print_r($image, true) . '</pre>';
-                        $content = str_replace($match, $replaceUrl, $content);
-                     }
-                    $updatePost = array(
-                        'ID'           => $post->ID,
-                        'post_content' => $content
-                    );
-                    wp_update_post($updatePost);
-                }
-            }
-        }
-
-        private function _getCkImages()
-        {
-            global $wpdb;
-            if ($this->_options['ckeditor_schema'] && $this->_options['ckeditor_images_table']) {
-                $this->_images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
-                $this->_connect();
-                $sql = "
-                SELECT *
-                  FROM {$this->_options['ckeditor_schema']}.{$this->_options['ckeditor_images_table']}";
-                $stmt = $this->_dbh->query($sql);
-                while ($row = $stmt->fetch()) {
-                    echo '<pre>' . print_r($row, true) . '</pre>';
-                    $fileName = $row['name_on_disk'];
-                    $fileTitle = ($row['file_name']) ? $row['file_name'] : $fileName;
-                    $wpImage = $this->_handleMediaFile(
-                        $fileName,
-                        $fileTitle,
-                        '',
-                        0,
-                        $this->_options['toolbox_image_url'] . '/CKImage/'
-                    );
-                    echo '<pre>' . print_r($wpImage, true) . '</pre>';
-                    $this->_images[$wpImage] = $fileName;
-                }
-                $this->_storeImages();
-            } else {
-                return false;
-            }
-        }
-
-        private function _getToolboxFiles()
-        {
-            global $wpdb;
-            echo '<pre>' . print_r($this->_options['toolbox_schema'], true) . '</pre>';
-            echo '<pre>' . print_r($this->_options['toolbox_files_table'], true) . '</pre>';
-            if ($this->_options['toolbox_files_table']) {
-                $this->_files = get_option(GLM_WP_IMPORT_FILES_OPTION, array());
-                $this->_connect();
-                $sql = "
-                SELECT *
-                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_files_table']}";
-                $stmt = $this->_dbh->query($sql);
-                while ($row = $stmt->fetch()) {
-                    echo '<pre>' . print_r($row, true) . '</pre>';
-                    $fileName = $row['filename'];
-                    $fileTitle = ($row['urltext']) ? $row['urltext'] : $fileName;
-                    $wpImage = $this->_handleMediaFile(
-                        $fileName,
-                        $fileTitle,
-                        '',
-                        0,
-                        $this->_options['toolbox_image_url'] . '/_ORIGINAL_/'
-                    );
-                    echo '<pre>' . print_r($wpImage, true) . '</pre>';
-                    $this->_files[$wpImage] = $fileName;
-                }
-                $this->_storeFiles();
-            } else {
-                return false;
-            }
-        }
-
-        private function _getParagraphImages()
-        {
-            global $wpdb;
-            echo '<pre>' . print_r($this->_options['toolbox_schema'], true) . '</pre>';
-            echo '<pre>' . print_r($this->_options['toolbox_paragraphs_table'], true) . '</pre>';
-            if ($this->_options['toolbox_paragraphs_table']) {
-                $this->_images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
-                $this->_connect();
-                $sql = "
-                SELECT image,caption
-                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_paragraphs_table']}
-                 WHERE image != ''";
-                $stmt = $this->_dbh->query($sql);
-                while ($row = $stmt->fetch()) {
-                    echo '<pre>' . print_r($row, true) . '</pre>';
-                    $fileName = $row['image'];
-                    $fileTitle = ($row['caption']) ? $row['caption'] : $fileName;
-                    $wpImage = $this->_handleMediaFile(
-                        $fileName,
-                        $fileTitle,
-                        '',
-                        0,
-                        $this->_options['toolbox_image_url'] . '/tbs1/'
-                    );
-                    echo '<pre>' . print_r($wpImage, true) . '</pre>';
-                    $this->_images[$wpImage] = $fileName;
-                }
-                $this->_storeImages();
-            }
-        }
-
-        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=toolbox&amp;step=1">Begin Import</a></p>';
-                $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
-                echo '<pre>' . print_r($currentPostArray, true) . '</pre>';
-                $images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
-                echo '<pre>' . print_r($images, true) . '</pre>';
-                $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array());
-                echo '<pre>' . print_r($files, true) . '</pre>';
-                if (count($currentPostArray) > 0) {
-                    echo '<p>Pages have been imported</p>';
-                    echo '<p><a href="admin.php?import=toolbox&amp;step=2">Step Two (Importing Images)</a></p>';
-                    echo '<p><a href="admin.php?import=toolbox&amp;step=3">Step Three (Updating Image Ref)</a></p>';
-                } else {
-                    echo '<p><a href="admin.php?import=toolbox&amp;step=1">Begin Import</a></p>';
-                }
-                break;
-            case 1:
-                echo '<p>Reset</p>';
-                $this->_post = $this->_images = $this->_files = array();
-                $this->_storePost();
-                $this->_storeImages();
-                $this->_storeFiles();
-                $numPagesImported = $this->_import();
-                echo '<p>' . $numPagesImported . ' Pages Imported</p>';
-                echo '<p><a href="admin.php?import=toolbox&amp;step=2">Step Two (Importing Images)</a></p>';
-                break;
-            case 2:
-                echo '<p>Done</p>';
-                echo '<p>Now processing the images from old database tables</p>';
-                $this->_images = array();
-                $this->_storeImages();
-                $this->_files = array();
-                $this->_storeFiles();
-                if ($this->_options['toolbox_page_table'] == 'pages') {
-                    $this->_getCkImages();
-                    $this->_getToolboxFiles();
-                    $this->_getParagraphImages();
-                    echo '<p>Done</p>';
-                } else {
-                    echo '<p>No import from images</p>';
-                }
-                echo '<p><a href="admin.php?import=toolbox&amp;step=3">Step Three (Updating Image Ref)</a></p>';
-                break;
-            case 3:
-                echo '<p>Phase Three</p>';
-                $this->_updateMediaSrc();
-                echo '<p>Done</p>';
-                echo '<p><a href="admin.php?import=toolbox&amp;step=4">Step Four (Updating Files Ref)</a></p>';
-                break;
-            case 4:
-                echo '<p>Phase Four</p>';
-                echo '<p>Files</p>';
-                $this->_updateFilesHref();
-                echo '<p>Done</p>';
-                echo '<p><a href="admin.php?import=toolbox&amp;step=5">Step Five (Updating Url\'s and keywords)</a></p>';
-                break;
-            case 5:
-                echo '<p>Phase Five</p>';
-                echo '<p>Site Url</p>';
-                // Replace the page Url's
-                $this->_replaceUrls();
-                // Replace the Keywords
-                $this->_replaceKeywords();
-                echo '<p>Done</p>';
-                break;
-            }
-
-            $this->_footer();
-        }
-    }
-}
-
-$toolbox_import = new Toolbox_Import();
-
-register_importer(
-     'toolbox',
-     __('Toolbox', 'import-toolbox-pages'),
-     sprintf(
-         __('Import the contents of Gaslight Toolbox Pages as pages. Visit <a href="%s">setup</a> first to setup the database options.',
-         'import-toolbox-pages'),
-         'options-general.php?page=glmwpimporter'
-     ),
-     array($toolbox_import, 'dispatch')
-);
diff --git a/controllers/ToolboxImport.php b/controllers/ToolboxImport.php
new file mode 100644 (file)
index 0000000..3d6e320
--- /dev/null
@@ -0,0 +1,1377 @@
+<?php
+
+/**
+ * EventImageImporter.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      <>
+ */
+
+/**
+ * GlmWPImporter_EventImageImport_Controller
+ *
+ * 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';
+ define('PAGES_PER_LOAD', 5);
+
+ 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')) {
+
+    /**
+     * Toolbox_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 Toolbox_Import extends WP_Importer
+    {
+        private $_dbh;
+        private $_post;
+        private $_options;
+        private $_files = array();
+        private $_images = array();
+
+
+        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>'.__('Toolbox 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>All Set!</p>';
+                $this->_connect();
+                $WHERE = $this->_getWhereSql();
+                $sql = "
+                SELECT count(*)
+                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                 $WHERE";
+                //echo '<pre>' . $sql . '</pre>';
+                $totalPages = $this->_dbh->query($sql)->fetchColumn();
+                printf('<p>Found %d Pages</p>', $totalPages);
+                //echo '<p><a href="admin.php?import=toolbox&amp;step=2">Part 2</a></p>';
+            }
+        }
+
+        private function _displayImage($data, $alignment)
+        {
+            if (!isset($data['image'])) {
+                return false;
+            }
+            $img_url = $this->_options['toolbox_image_url'] . '/tbs1/' . $data['image'];
+            $content = '';
+            if (isset($data['caption']) && $data['caption']) {
+                $content .= '[caption align="align'.$alignment.'"]<img  src="' . $img_url . '"> ' . $data['caption'] . '[/caption]';
+            } else if (isset($data['imagename']) && $data['imagename']) {
+                $content .= '[caption align="align'.$alignment.'"]<img  src="' . $img_url . '"> ' . $data['imagename'] . '[/caption]';
+            } else {
+                $content .= '<img class="align'.$alignment.'" src="' . $img_url . '">';
+            }
+            return $content;
+        }
+
+        private function _getDescriptionImage($src)
+        {
+            $parsed = parse_url($src);
+            $fileName = basename($parsed['path']);
+            $rootUrl = str_replace('/' . $fileName, '', $src);
+            $img_id = $this->_handleMediaFile(
+                basename($parsed['path']),
+                '',
+                0,
+                $rootUrl . '/'
+            );
+            $image = wp_get_attachment_image_src($img_id, 'medium');
+            return $image[0];
+        }
+
+        private function _displayFile($data)
+        {
+            //if ($this->_options['toolbox_paragraphs_table'] == 'pages') {
+                //$file_id = $this->_handleMediaFile($data['filename']);
+            //} else {
+                //$file_id = $this->_handleMediaFile(
+                    //$data['filename'],
+                    //'',
+                    //0,
+                    //$this->_options['site_url'] . 'uploads/'
+                //);
+            //}
+
+            //if (!$file_id) {
+                //return false;
+            //}
+            //$fileUrl = wp_get_attachment_url($file_id);
+            $fileUrl =$this->_options['toolbox_image_url'] . '/original/' . $data['filename'];
+            $fileName = ($data['urltext']) ? $data['urltext'] : $data['filename'];
+            return "\n".'<a href="'.$fileUrl.'">'.$fileName.'</a>';
+        }
+
+        private function _addMedia($file, $postId)
+        {
+            $fileType = wp_check_filetype(basename($file), null);
+            $wpUploadDir = wp_upload_dir();
+            $attachment = array(
+                'guid'           => $wpUploadDir . '/' . basename($file),
+                'post_mime_type' => $fileType['type'],
+                'post_title'     => basename($file),
+                'post_content'   => '',
+                'post_status'    => 'inherit'
+            );
+            $id = wp_insert_attachment($attachment, $file, $postId);
+            if (!is_wp_error($id)) {
+                $data = wp_generate_attachment_metadata($id, $file);
+                wp_update_attachment_metadata($id, $data);
+            }
+            return ($id) ? $this->_getAttachmentById($id) : false;
+        }
+
+        private function _handleMediaFile(
+            $file,
+            $file_title,
+            $caption = '',
+            $post_id = 0,
+            $baseUrl = null
+        ) {
+            $id = array_search($file, $this->_files);
+            if ($id === false) {
+                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 _getSubPageIds($parent)
+        {
+            $this->_connect();
+            $pageIds = array();
+            $sql = "
+            SELECT id
+              FROM {$this->_options['toolbox_page_table']}
+             WHERE parent = :parent";
+            $stmt = $this->_dbh->prepare($sql);
+            $stmt->bindParam(':parent', $parent, PDO::PARAM_INT);
+            $stmt->execute();
+            while ($page = $stmt->fetch()) {
+                $pageIds[] = $page['id'];
+                $subPageIds = $this->_getSubPageIds($page['id']);
+                if (!empty($subPageIds)) {
+                    $pageIds = array_merge($pageIds, $subPageIds);
+                }
+            }
+            return $pageIds;
+        }
+
+        private function _getWhereSql()
+        {
+            $WHERE = '';
+            $where = array();
+            if ($this->_options['include_pages']) {
+                if (filter_var($this->_options['include_pages'], FILTER_VALIDATE_INT)) {
+                    $subPageIds = $this->_getSubPageIds($this->_options['include_pages']);
+                    if (!empty($subPageIds)) {
+                        $where[] = "(id = {$this->_options['include_pages']}"
+                        . " OR id IN (" . implode(',', $subPageIds) . ") )";
+                    } else {
+                        $where[] = "id = {$this->_options['include_pages']}";
+                    }
+
+                } else {
+                    $where[] = "id IN ({$this->_options['include_pages']})";
+                }
+            }
+            if ($this->_options['exclude_pages']) {
+                $where[] = "id NOT IN ({$this->_options['exclude_pages']})
+                    AND parent NOT IN ({$this->_options['exclude_pages']}) ";
+            }
+            $where[] = "active = true";
+            if (!empty($where)) {
+                $WHERE = ' WHERE ' . implode(' AND ', $where);
+            }
+            return $WHERE;
+        }
+
+        private function _fetchAllPages($limit = null, $offset = 0)
+        {
+            $this->_connect();
+            $WHERE = $this->_getWhereSql();
+            $pageSql = "
+              SELECT *
+                FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                $WHERE
+            ORDER BY parent,pos";
+            $pageSql .= ($limit) ? " LIMIT $limit OFFSET $offset" : '';
+            $pageData = $this->_dbh->query($pageSql)->fetchAll(PDO::FETCH_ASSOC);
+            if ($this->_options['toolbox_page_table'] == 'pages') {
+                $paragraphSql = "
+                  SELECT *
+                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_paragraphs_table']}
+                   WHERE page = :page
+                     AND active = true
+                ORDER BY pos";
+                $paraStmt = $this->_dbh->prepare($paragraphSql);
+                $fileSql = "
+                  SELECT *
+                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_files_table']}
+                   WHERE paragraph = :pid
+                ORDER BY pos";
+                $fileStmt = $this->_dbh->prepare($fileSql);
+            } else {
+                $paragraphSql = "
+                  SELECT b.*
+                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_paragraphs_table']} b
+                         LEFT OUTER JOIN bus_category_bus bcb ON (bcb.busid = b.id)
+                   WHERE bcb.catid = :page
+                ORDER BY bcb.pos";
+                $paraStmt = $this->_dbh->prepare($paragraphSql);
+                $fileSql = "
+                  SELECT *
+                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_files_table']}
+                   WHERE bus_id = :pid
+                ORDER BY bus_id,pos";
+                $fileStmt = $this->_dbh->prepare($fileSql);
+            }
+            $data = $this->_dbh->query($pageSql)->fetchAll();
+            //echo '<pre>' . print_r($data, true) . '</pre>';
+            //exit;
+            foreach ($data as &$page) {
+                $page['srcs'] = array();
+                $paraStmt->bindParam(':page', $page['id'], PDO::PARAM_INT);
+                $paraStmt->execute();
+                $paragraphs     = $paraStmt->fetchAll();
+            //echo '<pre>' . print_r($paragraphs, true) . '</pre>';
+            //exit;
+                $primaryAlign   = 'right';
+                $secondaryAlign = 'right';
+                $alternateImg   = false;
+
+                switch ($page['template']) {
+                case 1:
+                    break;
+                case 2:
+                    $primaryAlign   = 'left';
+                    $secondaryAlign = 'left';
+                    break;
+                case 3:
+                    $secondaryAlign = 'left';
+                    $alternateImg   = true;
+                    break;
+                case 4:
+                    $primaryAlign   = 'left';
+                    $alternateImg   = true;
+                    break;
+                case 5:
+                    $primaryAlign   = 'left';
+                    break;
+                case 6:
+                    $secondaryAlign = 'left';
+                    break;
+                }
+                $page['pageContent'] = '';
+                $iterator = 1;
+                if ($this->_options['toolbox_page_table'] == 'bus_category') {
+                    $page['pageContent'] .= '<h1>'.$page['category'].'</h1>';
+                    ++$iterator;
+                    if ($page['image']) {
+                        //$page['images'][]     = $page['image'];
+                        $page['pageContent'] .= $this->_displayImage($page, $primaryAlign);
+                    }
+                    $page['pageContent'] .= $page['description'];
+                }
+
+                foreach ($paragraphs as $paragraph) {
+                    switch ($iterator) {
+                    case 1:
+                        if (isset($paragraph['title']) && $paragraph['title']) {
+                            $page['pageContent'] .= '<h1>'.$paragraph['title'].'</h1>';
+                        }
+                        if (isset($paragraph['image']) && $paragraph['image']) {
+                            //$page['images'][]     = $paragraph['image'];
+                            $page['pageContent'] .= $this->_displayImage($paragraph, $primaryAlign);
+                        }
+                        break;
+                    case 2:
+                        if (isset($paragraph['name']) && $paragraph['name']) {
+                            $page['pageContent'] .= '<h2>'.$paragraph['name'].'</h2>';
+                        }
+                        if (isset($paragraph['title']) && $paragraph['title']) {
+                            $page['pageContent'] .= '<h2>'.$paragraph['title'].'</h2>';
+                        }
+                        if (isset($paragraph['image']) && $paragraph['image']) {
+                            //$page['images'][]     = $paragraph['image'];
+                            $page['pageContent'] .= $this->_displayImage($paragraph, $secondaryAlign);
+                        }
+                        break;
+                    default:
+                        if (isset($paragraph['name']) && $paragraph['name']) {
+                            $page['pageContent'] .= '<h2>'.$paragraph['name'].'</h2>';
+                        }
+                        if (isset($paragraph['title']) && $paragraph['title']) {
+                            $page['pageContent'] .= '<h2>'.$paragraph['title'].'</h2>';
+                        }
+                        if (isset($paragraph['template']) && $alternateImg && $page['template'] == 2) {
+                            $align = ($iterator%2 == 0) ? 'left' : 'right';
+                        } else {
+                            $align = $secondaryAlign;
+                        }
+                        if (isset($paragraph['image']) && $paragraph['image']) {
+                            //$page['images'][]     = $paragraph['image'];
+                            $page['pageContent'] .= $this->_displayImage($paragraph, $align);
+                        }
+                        break;
+                    }
+                    $page['pageContent'] .= $paragraph['description'];
+                    //preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $paragraph['description'], $matches);
+            //echo '<pre>' . print_r($matches, true) . '</pre>';
+
+                    /*
+                    for ($i = 0; $i < count($matches[0]); $i++) {
+                        if ($matches[1][$i]) {
+                            $newSrc  = $this->_getDescriptionImage($matches[1][$i]);
+                            $parsUrl = parse_url($newSrc);
+                            $imgName = basename($parsUrl['path']);
+                            $page['pageContent'] = str_replace($matches[1][$i], $newSrc, $page['pageContent']);
+                            $page['srcs'][] = $imgName;
+                        }
+                    }
+                     */
+                    //var_dump($paragraph['id']);
+                    $fileStmt->bindParam(':pid', $paragraph['id'], PDO::PARAM_INT);
+                    $fileStmt->execute();
+                    while ($file = $fileStmt->fetch()) {
+            //echo '<pre>Files: ' . print_r($file, true) . '</pre>';
+                        //$page['files'][] = $file['filename'];
+                        $page['pageContent'] .= $this->_displayFile($file);
+                    }
+                    ++$iterator;
+                }
+                //echo '<pre>Files: ' . print_r($page['files'], true) . '</pre>';
+            }
+            return $data;
+        }
+
+        private function _readOptions()
+        {
+            echo '<pre>' . print_r($this->_options, true) . '</pre>';
+            echo '<pre>' . print_r(get_option(GLM_WP_IMPORT_POST_OPTION, array()), true) . '</pre>';
+        }
+
+        private function _import()
+        {
+            echo '<p>Fetching Pages</p>';
+            $this->_post = get_option(GLM_WP_IMPORT_POST_OPTION, array());
+            // grab all pages and build the post array
+            $start = filter_var($_REQUEST['start'], FILTER_VALIDATE_INT);
+            //$pages = $this->_fetchAllPages(PAGES_PER_LOAD, $start);
+            $pages = $this->_fetchAllPages();
+            //foreach ($pages as $page) {
+                //echo '<pre>' . print_r(htmlspecialchars($page['pageContent']), true) . '</pre>';
+            //}
+            //echo '<pre>' . print_r($pages, true) . '</pre>';
+            //return;
+            //exit;
+            $numPagesImported = count($pages);
+
+            foreach ($pages as $page) {
+                if ($page['parent']) {
+
+                }
+                $pageName = (isset($page['navigation_name']))
+                    ? $page['navigation_name']
+                    : $page['category'];
+                // if you don't find the parent page id then use the default given or 0
+                $parent = isset($this->_post[$page['parent']])
+                    ? $this->_post[$page['parent']]
+                    : (($this->_options['parent_page']) ? $this->_options['parent_page'] : 0);
+                $post = array(
+                    'post_content'   => $page['pageContent'],
+                    'post_name'      => $pageName,// slug ?
+                    'post_title'     => $pageName,
+                    'post_status'    => 'publish',
+                    'post_type'      => 'page',
+                    'post_author'    => 'steve',
+                    'ping_status'    => 'closed',
+                    'post_parent'    => $parent,
+                    'menu_order'     => $page['pos'],
+                    'comment_status' => 'closed',
+                );
+                $ID = wp_insert_post($post, true);
+                $newPost = get_post($ID, ARRAY_A);
+                $this->_post[$page['id']] = $ID;
+            }
+            $this->_storePost();
+            return $numPagesImported;
+        }
+
+        private function _storePost()
+        {
+            update_option(GLM_WP_IMPORT_POST_OPTION, $this->_post);
+        }
+
+        private function _storeImages()
+        {
+            update_option(GLM_WP_IMPORT_IMAGES_OPTION, $this->_images);
+        }
+
+        private function _storeFiles()
+        {
+            update_option(GLM_WP_IMPORT_FILES_OPTION, $this->_files);
+        }
+
+        private function _replaceKeywords()
+        {
+            global $wpdb;
+            $this->_connect();
+            echo '<p>Replace keywords</p>';
+            if ($this->_options['toolbox_page_table'] == 'pages') {
+                $sql = "
+                  SELECT id,navigation_name,keyword
+                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                   WHERE keyword != ''
+                ORDER BY parent,pos";
+            } else {
+                $sql = "
+                  SELECT id,category as navigation_name,keyword
+                    FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                   WHERE keyword != ''
+                ORDER BY parent,pos";
+            }
+            $stmt = $this->_dbh->query($sql);
+            while ($page = $stmt->fetch()) {
+                echo '<pre>' . print_r($page, true) .  '</pre>';
+                // find out which page (wp) this needs to be
+                $wpPost = get_page_by_title($page['navigation_name']);
+                if (!$wpPost) {
+                    continue;
+                }
+                //echo '<pre>' . print_r($wpPost, true) .  '</pre>';
+                echo '<pre>' . print_r(get_permalink($wpPost), true) .  '</pre>';
+                $replaceUrl = '<a href="'.get_permalink($wpPost->ID).'">' . $page['navigation_name'] . '</a>';
+
+                $sql = "
+                SELECT *
+                  FROM {$wpdb->prefix}posts
+                 WHERE post_content LIKE '%\{{$page['keyword']}\}%'
+                   AND post_type = 'page'";
+                $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
+                $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
+                //echo '<pre>' . print_r($sql, true) . '</pre>';
+                $results = $wpdb->get_results($sql, OBJECT);
+                $total = count($results);
+                if ($total > 0) {
+                    foreach ($results as $post) {
+                        //echo '<pre>' . print_r($post, true) . '</pre>';
+                        $content = $post->post_content;
+                        $content = preg_replace("/\{{$page['keyword']}\}/", $replaceUrl, $content);
+                        wp_update_post(array(
+                            'ID'           => $post->ID,
+                            'post_content' => $content
+                        ));
+                    }
+                }
+                echo '<p>Count results: ' . $total . '</p>';
+                //echo '<pre>' . print_r($results, true) . '</pre>';
+            }
+        }
+
+        private function _getPageTitleById($id)
+        {
+            $this->_connect();
+            if ($this->_options['toolbox_page_table'] == 'pages') {
+                $sql = "
+                SELECT navigation_name
+                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                 WHERE id = :id";
+            } else {
+                $sql = "
+                SELECT category as navigation_name
+                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']}
+                 WHERE id = :id";
+            }
+            $stmt = $this->_dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        }
+
+        private function _replaceUrls()
+        {
+            global $wpdb;
+            $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
+        echo '<pre>' . print_r($currentPostArray, true) . '</pre>';
+            $this->_connect();
+            echo '<p>Replace page url\'s</p>';
+            $searchUrl = $this->_options['site_url'];
+            $parsedUrl = parse_url($searchUrl);
+            // find all pages with links to site pages
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_content LIKE '%{$searchUrl}%'
+               AND post_type = 'page'";
+            $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
+            $results = $wpdb->get_results($sql, OBJECT);
+            if (count($results) > 0) {
+                $pattern = ';http://' . $parsedUrl['host'] . '/([^"]+);si';
+                echo '<pre>' . print_r($pattern, true) . '</pre>';
+                //echo '<pre>' . print_r($results, true) . '</pre>';
+                foreach ($results as $post) {
+                    $content = $post->post_content;
+                    preg_match_all($pattern, $post->post_content, $matches);
+                    echo '<pre>' . print_r($matches, true) . '</pre>';
+                    foreach ($matches[0] as $match) {
+                        // find the page id for matched url
+                        if (preg_match(';-([0-9]+)/$;', $match, $found)) {
+                            echo '<pre>' . print_r($found, true) . '</pre>';
+                            if ($found && $currentPostArray[$found[1]]) {
+                                $wpPost = get_page($currentPostArray[$found[1]]);
+                                $replaceUrl = get_permalink($wpPost->ID);
+                                echo '<pre>' . print_r($replaceUrl, true) . '</pre>';
+                                $content = str_replace($match, $replaceUrl, $content);
+                            }
+                        }
+                     }
+                    $updatePost = array(
+                        'ID'           => $post->ID,
+                        'post_content' => $content
+                    );
+                    wp_update_post($updatePost);
+                }
+            }
+        }
+
+        function _handleAccents($content)
+        {
+            // from: http://www.php.net/manual/en/domdocument.loadhtml.php#91513
+            if ( !empty( $content ) && function_exists( 'mb_convert_encoding' ) ) {
+                mb_detect_order( "ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15" );
+                if ( empty( $encod ) ) {
+                    $encod = mb_detect_encoding( $content );
+                }
+                $headpos = mb_strpos( $content,'<head>' );
+                if ( FALSE === $headpos ) {
+                    $headpos= mb_strpos( $content,'<HEAD>' );
+                }
+                if ( FALSE !== $headpos ) {
+                    $headpos+=6;
+                    $content = mb_substr( $content,0,$headpos ) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr( $content,$headpos );
+                }
+                $content = mb_convert_encoding( $content, 'HTML-ENTITIES', $encod );
+            }
+            return $content;
+        }
+
+        private function _replaceSrc()
+        {
+            global $wpdb;
+            $files = $filesFound = $filesMissing = $fileDuplicates = array();
+            $this->_connect();
+            echo '<p>Replace Src\'s</p>';
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_content LIKE '%<img%'
+               AND post_type = 'page'";
+            //$sql .= " AND post_title = 'Home'";
+            //$sql .= " AND ID = 2101";
+
+            $results = $wpdb->get_results($sql, OBJECT);
+            echo '<p>Number of Pages'.count($results).'</p>';
+            if (count($results) > 0) {
+                $pattern = ';(<img[^>]>);si';
+                foreach ($results as $post) {
+                    $dom = new DOMDocument('1.0', 'UTF-8');
+                    $content = $this->handle_accents($post->post_content);
+                    $dom->encoding = 'UTF-8';
+                    $test = $dom->loadHTML($content);
+                    //var_dump($test);
+                    $images = $dom->getElementsByTagName('img');
+                    foreach ($images as $image) {
+                        $files[] = $image->getAttribute('src');
+                        $width = $height = null;
+                        //echo '<div style="border: 1px solid black; background-color: lightgrey; padding: 15px;width: 600px;margin: 0 10px">';
+                        //echo '<pre>' . print_r($image, true)  . '</pre>';
+                        if ($image->hasAttribute('class')) {
+                            //echo '<pre>' . print_r($image->getAttribute('class'), true)  . '</pre>';
+                            if (preg_match('%wp-image-\d+%', $image->getAttribute('class'))) {
+                                //echo 'Continue';
+                                //echo '</div>';
+                                continue;
+                            }
+                        }
+                        if ($image->hasAttribute('style')) {
+                            $style = $image->getAttribute('style');
+                            //var_dump($style);
+                            //echo '<pre>' . print_r($style, true)  . '</pre>';
+                            if (preg_match('%[^-]width[: ]+(\d+)%', $style, $wMatch)) {
+                                $width = $wMatch[1];
+                                //echo '<pre>wMatch: ' . print_r($wMatch, true)  . '</pre>';
+                            }
+                            if (preg_match('%[^-]height[: ]+(\d+)%', $style, $hMatch)) {
+                                $height = $hMatch[1];
+                            }
+                            //echo '<pre>width: ' . print_r($width, true)  . '</pre>';
+                            //echo '<pre>height: ' . print_r($height, true)  . '</pre>';
+                        }
+                        if ($image->hasAttribute('width')) {
+                            $width = $image->getAttribute('width');
+                        }
+                        if ($image->hasAttribute('height')) {
+                            $height = $image->getAttribute('height');
+                        }
+                        if ($image->hasAttribute('src')) {
+                            //echo '<pre>' . print_r($image->getAttribute('src'), true)  . '</pre>';
+                            $imgName = basename($image->getAttribute('src'));
+                            //echo '<pre>' . print_r($imgName, true)  . '</pre>';
+                            $imgPathInfo = pathinfo($imgName);
+                            //echo '<pre>' . print_r($imgPathInfo, true) . '</pre>';
+                            $wpImage = $this->_getAttachmentByName($imgPathInfo['filename']);
+                            //echo '<pre>' . print_r($wpImage, true) . '</pre>';
+                            //exit;
+                            if (!$wpImage) {
+                                //echo '<p>Image not found as attachment</p>';
+                                //echo '<pre>' . print_r($imgPathInfo, true) . '</pre>';
+                                if (preg_match(';(is\d{2}-\d{10}-\d{5})(\d{1}|[-]\d+x\d+);', $imgPathInfo['filename'], $matches)) {
+                                    //echo '<p>Duplicate Image found</p>';
+                                    //echo '<pre>' . print_r($matches, true) . '</pre>';
+                                    $wpImage = $this->_getAttachmentByName($matches[1]);
+                                    if ($wpImage) {
+                                        //echo '<p>Found Image</p>';
+                                        $fileDuplicates[] = $image->getAttribute('src');
+                                    } else {
+                                        //echo '<p>Image still not found</p>';
+                                        //echo '</div>';
+                                        $filesMissing[] = $image->getAttribute('src');
+                                        continue;
+                                    }
+                                }
+                            }
+                            if (!$wpImage) {
+                                //echo '<p>Image not found as attachment 2</p>';
+                                //echo '<pre>' . print_r($image->getAttribute('src'), true) . '</pre>';
+                                $parsed   = parse_url($image->getAttribute('src'));
+                                $filename = basename($parsed['path']);
+                                if (preg_match(';is\d{2,}-\d{10,}-\d{5,};', $filename)) {
+                                    $rootUrl  = str_replace('/' . $filename, '', $image->getAttribute('src'));
+                                    //echo '<pre>' . print_r($parsed, true) . '</pre>';
+                                    //echo '<pre>' . print_r($filename, true) . '</pre>';
+                                    //echo '<pre>' . print_r($rootUrl, true) . '</pre>';
+                                    //if (preg_match('/(\d{4})\/(\d{2})$/', $rootUrl, $matches)) {
+                                        //echo '<pre>' . print_r($matches, true) . '</pre>';
+                                        //$uploadDir = wp_upload_dir();
+                                        //echo '<pre>' . print_r($uploadDir, true) . '</pre>';
+                                        //$absPath = $uploadDir['basedir'] . '/' . $matches[1] . '/' . $matches[2];
+                                        //echo '<pre>' . print_r($absPath, true) . '</pre>';
+                                        ////$wpImage = $this->_addMedia($absPath . '/' . $filename, $post->ID);
+                                        //echo '<pre>' . print_r($imageId, true) . '</pre>';
+                                    //}
+                                    //$fileExists = file_exists($upload_dir['baseurl'] . '/' . $filename);
+                                    //$wpImage = $this->_handleMediaFile(
+                                        //basename($parsed['path']),
+                                        //'',
+                                        //$post->ID,
+                                        //$rootUrl . '/'
+                                    //);
+                                }
+                            }
+                            if ($wpImage) {
+                                $filesFound[] = $image->getAttribute('src');
+                                //$strToReplace = $dom->saveHTML($image);
+                                //echo '<pre>'.htmlspecialchars($strToReplace).'</pre>';
+                                //echo '<p>Image found: id '.$wpImage->ID.'</p>';
+                                if ($width && $height) {
+                                    //echo '<p>width: ' . $width . '</p>';
+                                    //echo '<p>height: ' . $height . '</p>';
+                                    if ($width > 300 || $height > 300) {
+                                        //echo '<p>Found Large</p>';
+                                        $size = 'large';
+                                        $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
+                                        $image->setAttribute('class', 'alignnone wp-image-' . $wpImage->ID);
+                                        if($newImage) {
+                                            $image->setAttribute('src', $newImage[0]);
+                                        }
+                                    } else if ($width < 150 && $height < 150) {
+                                        //echo '<p>Found Thumbnail</p>';
+                                        $size = 'thumbnail';
+                                        $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
+                                        $image->setAttribute('class', 'alignnone size-' . $size . ' wp-image-' . $wpImage->ID);
+                                        if($newImage) {
+                                            $image->setAttribute('src', $newImage[0]);
+                                        }
+                                    } else {
+                                        //echo '<p>Found Medium</p>';
+                                        $size = 'medium';
+                                        $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
+                                        $image->setAttribute('class', 'alignnone size-' . $size . ' wp-image-' . $wpImage->ID);
+                                        if($newImage) {
+                                            $image->setAttribute('src', $newImage[0]);
+                                        }
+                                    }
+                                } else {
+                                    $size = 'large';
+                                    $newImage = wp_get_attachment_image_src($wpImage->ID, $size);
+                                    $image->setAttribute('class', 'alignnone size-' . $size . ' wp-image-' . $wpImage->ID);
+                                    $width    = $newImage[1];
+                                    $height   = $newImage[2];
+                                    if($newImage) {
+                                        $image->setAttribute('src', $newImage[0]);
+                                    }
+                                }
+                                $image->removeAttribute('style');
+                                $image->setAttribute('width', $width);
+                                $image->setAttribute('height', $height);
+                                //echo htmlspecialchars($dom->saveHTML($image));
+                            } else {
+                                //echo '<p>no media found</p>';
+                                $filesMissing[] = $image->getAttribute('src');
+                            }
+                        }
+                        //echo '</div>';
+                    }
+                    // remove the extra stuff Dom put in
+                    $content = preg_replace(
+                        '/^<!DOCTYPE.+?>/',
+                        '',
+                        str_replace(
+                            array('<html>', '</html>', '<body>', '</body>'),
+                            array('', '', '', ''),
+                            $dom->saveHTML()
+                        )
+                    );
+                    //echo '<pre>'.print_r(htmlspecialchars($content), true).'</pre>';
+                    $updatePost = array(
+                        'ID'           => $post->ID,
+                        'post_content' => $content
+                    );
+                    wp_update_post($updatePost);
+                }
+                //echo '<pre>Files: ' . print_r($files, true) . '</pre>';
+                echo '<pre>Files Found: ' . print_r($filesFound, true) . '</pre>';
+                echo '<pre>Duplicate Files: ' . print_r($fileDuplicates, true) . '</pre>';
+                echo '<pre>Files Missing: ' . print_r($filesMissing, true) . '</pre>';
+            }
+        }
+
+        private function _updateFilesHref()
+        {
+            global $wpdb;
+            $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
+            $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array());
+            echo '<pre>' . print_r($files, true) . '</pre>';
+            //$images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
+            //$media = array_merge($images, $files);
+            //echo '<pre>' . print_r($media, true) . '</pre>';
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_content LIKE '%http://is0.gaslightmedia.com%'
+               AND post_type = 'page'";
+            $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
+            $results = $wpdb->get_results($sql, OBJECT);
+            if (count($results) > 0) {
+                foreach ($results as $post) {
+                    $content = $post->post_content;
+                    echo '<div style="border: 1px solid green; padding: 9px; margin: 10px;">';
+                    $urlPattern = '%<a href="(' . $this->_options['toolbox_image_url'] . '/[^">]*)" ?[^>]*>([^>]+)</a>%s';
+                    if (preg_match_all($urlPattern, $content, $isMatch)) {
+                        $isMatchCount = count($isMatch[0]);
+                        echo '<p>Matches is0 ' . $isMatchCount . '</p>';
+                        for ($index = 0; $index < $isMatchCount; ++$index) {
+                            echo '<pre>'.htmlspecialchars($isMatch[1][$index]).'</pre>';
+                            //echo '<pre>'.htmlspecialchars(basename($isMatch[1][$index])).'</pre>';
+                            //echo '<pre>'.print_r(pathinfo($isMatch[1][$index]), true).'</pre>';
+                            $fileInfo = pathinfo($isMatch[1][$index]);
+                            $fileName = $fileInfo['filename'];
+                            echo '<pre>File Name: ' . print_r($fileName, true)  . '</pre>';
+                            echo '<pre>File Name: ' . print_r($fileInfo, true)  . '</pre>';
+                            $fileTitle = $isMatch[2][$index];
+                            echo '<pre>File Title: ' . print_r($fileTitle, true)  . '</pre>';
+                            $key = $this->_getAttachmentByName($fileName);
+                            echo '<pre>Key: ' . print_r($key, true)  . '</pre>';
+                            // check on format of filename
+                            if (!$key && ($fileName && $fileTitle)) {
+                                $key = $this->_handleMediaFile(
+                                    $fileName,
+                                    $fileTitle,
+                                    '',
+                                    $post->ID,
+                                    $this->_options['site_url'] . '/uploads/'
+                                );
+                            }
+                            if ($key !== false) {
+                                var_dump($key);
+                                $newSrc = wp_get_attachment_url($key);
+                                $content = str_replace($isMatch[1][$index], $newSrc, $content);
+                            }
+                        }
+                        $updatePost = array(
+                            'ID'           => $post->ID,
+                            'post_content' => $content
+                        );
+                        wp_update_post($updatePost);
+                    }
+                    echo '<pre>'.htmlspecialchars($content).'</pre>';
+                    echo '</div>';
+                }
+            }
+        }
+
+        private function _updateMediaSrc()
+        {
+            global $wpdb;
+            $images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
+            $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_content LIKE '%<img%'
+               AND post_type = 'page'";
+            $sql .= " AND ID IN (" . implode(',', $currentPostArray) . ")";
+            $results = $wpdb->get_results($sql, OBJECT);
+            if (count($results) > 0) {
+                foreach ($results as $post) {
+                    $content = $post->post_content;
+                    echo '<pre>Updating Media Src\'s: ' . print_r($post->post_title, true)  . '</pre>';
+                    echo '<div style="border: 1px solid green; padding: 9px; margin: 10px;">';
+                    if (preg_match_all('%\[caption [^\]]+\]<img ([^>]+)>([^\[]*)\[/caption\]%', $content, $cMatch)) {
+                        $captionCount = count($cMatch[0]);
+                        echo '<p>Matches in Caption ' . $captionCount . '</p>';
+                        //echo '<pre>' . print_r($cMatch, true)  . '</pre>';
+                        for ($index = 0; $index < $captionCount; ++$index) {
+                            //echo '<pre>cMatch: ' . print_r($cMatch, true)  . '</pre>';
+                            echo '<pre>'.htmlspecialchars($cMatch[0][$index]).'</pre>';
+                            echo '<pre>Caption Match: ' . print_r($cMatch[1][$index], true)  . '</pre>';
+                            echo '<pre>Caption Text: ' . print_r($cMatch[2][$index], true)  . '</pre>';
+                            if (preg_match('%src="([^"]+)"%', $cMatch[1][$index], $srcMatch)) {
+                                echo '<pre>Sub Src Match: ' . print_r($srcMatch[1], true)  . '</pre>';
+                                $fileInfo = pathinfo($srcMatch[1]);
+                                $fileName = basename($srcMatch[1]);
+                                $fileName = $fileInfo['filename'];
+                                echo '<pre>File Name: ' . print_r($fileName, true)  . '</pre>';
+                                $path = str_replace($fileName, '', $srcMatch[1]);
+                                $path = $filInfo['dirname'];
+                                $imagesKey = $this->_getAttachmentByName($fileName);
+                                var_dump($imagesKey);
+                                if (!$imagesKey) {
+                                    $imagesKey = $this->_handleMediaFile(
+                                        $fileName,
+                                        $fileName,
+                                        '',
+                                        $post->ID,
+                                        $path
+                                    );
+                                }
+                                if ($imagesKey) {
+                                    var_dump($imagesKey);
+                                    $newImage = wp_get_attachment_image_src($imagesKey, 'medium');
+                                    // need to replace the src tags in content with the new image tags
+                                    $caption = str_replace(
+                                        'src="' . $srcMatch[1] . '"',
+                                        'src="' . $newImage[0] . '" width="' . $newImage[1] . '" height="' . $newImage[1] . '"',
+                                        $cMatch[0][$index]);
+                                    $caption = str_replace('<img', '<img class="wp-image-' . $imagesKey . ' size-medium"', $caption);
+                                    $caption = str_replace('[caption',
+                                        '[caption id="attachment_' . $imagesKey . '" width="' . $newImage[1] . '"',
+                                        $caption);
+                                    echo '<pre>'.htmlspecialchars($caption).'</pre>';
+                                    $content = str_replace($cMatch[0][$index], $caption, $content);
+                                }
+                            }
+                        }
+                    }
+                    // In this next part Have to remember the $content is already processed.
+                    // Don't edit src if they alrea,dy have an ID
+                    if (preg_match_all('%<img ([^>]+)>%', $content, $matches)) {
+                        $imageCount = count($matches[0]);
+                        for ($index = 0; $index < $imageCount; ++$index) {
+                            echo '<pre>Image Match: ' . $imageCount  . '</pre>';
+                            echo '<pre>'.htmlspecialchars($matches[0][$index]).'</pre>';
+                            if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
+                                return new WP_Error('upload_error', $uploads['error']);
+                            }
+                            echo '<pre>Uploads Url: ' . print_r($uploads['url'], true)  . '</pre>';
+                            if (preg_match('%src="' . $uploads['url'] . '[^"]+"%', $matches[1][$index], $pMatch)) {
+                                continue;
+                            }
+                            if (preg_match('%src="([^"]+)"%', $matches[1][$index], $srcMatch)) {
+                                echo '<pre>Sub Src Match: ' . print_r($srcMatch[1], true)  . '</pre>';
+                                $fileInfo = pathinfo($srcMatch[1]);
+                                echo '<pre>' . print_r($fileInfo, true) . '</pre>';
+                                $fileName = $fileInfo['filename'];
+                                echo '<pre>File Url: ' . print_r($srcMatch[1], true)  . '</pre>';
+                                echo '<pre>File Name: ' . print_r($fileName, true)  . '</pre>';
+                                $path = $filInfo['dirname'];
+                                echo '<pre>File Path: ' . print_r($path, true)  . '</pre>';
+                                $imagesKey = $this->_getAttachmentByName($fileName);
+                                var_dump($imagesKey);
+                                if (!$imagesKey) {
+                                    $imagesKey = $this->_handleMediaFile(
+                                        $fileName,
+                                        $fileName,
+                                        '',
+                                        $post->ID,
+                                        $path
+                                    );
+                                }
+                                if ($imagesKey) {
+                                    //var_dump($imagesKey);
+                                    $newUrl = wp_get_attachment_url($imagesKey);
+                                    // need to replace the src tags in content with the new image tags
+                                    $imageTag = str_replace($srcMatch[1], $newUrl, $matches[0][$index]);
+                                    if (preg_match('%class="([^"]+)"%', $matches[1][$index], $classMatch)) {
+                                        $imageTag = preg_replace('%class="([^"]+)"%', 'class="wp-image-' . $imagesKey . ' size-medium $1"', $imageTag);
+                                    } else {
+                                        $imageTag = str_replace('<img', '<img class="wp-image-' . $imagesKey . ' size-medium"', $imageTag);
+                                    }
+                                    //echo '<pre>'.htmlspecialchars($imageTag).'</pre>';
+                                    $content = str_replace($matches[0][$index], $imageTag, $content);
+                                }
+                            }
+                        }
+                    }
+                    echo '<pre>'.htmlspecialchars($content).'</pre>';
+                    echo '</div>';
+                    $updatePost = array(
+                        'ID'           => $post->ID,
+                        'post_content' => $content
+                    );
+                    wp_update_post($updatePost);
+                }
+            }
+        }
+
+        private function _getAttachmentByName($name)
+        {
+            global $wpdb;
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_type = 'attachment'
+            AND (post_name like '{$name}%' OR post_title like '{$name}%')";
+            $results = $wpdb->get_results($sql, OBJECT);
+            return (!empty($results)) ? $results[0]->ID : false;
+            //return (!empty($results)) ? $results[0] : false;
+        }
+
+        private function _getAttachmentById($id)
+        {
+            global $wpdb;
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_type = 'attachment'
+            AND ID = {$id}";
+            $results = $wpdb->get_results($sql, OBJECT);
+            return (!empty($results)) ? $results[0] : false;
+        }
+
+        private function replaceIsoUrls()
+        {
+            global $wpdb;
+            $this->_connect();
+            echo '<p>Replace IS0 url\'s</p>';
+            $searchUrl = 'http://is0.gaslightmedia.com';
+            // find all pages with links to site pages
+            $sql = "
+            SELECT *
+              FROM {$wpdb->prefix}posts
+             WHERE post_content LIKE '%{$searchUrl}%'
+               AND post_type = 'page'";
+            echo '<pre>'.$sql.'</pre>';
+            $results = $wpdb->get_results($sql, OBJECT);
+            if (count($results) > 0) {
+                //echo '<pre>' . print_r($results, true) . '</pre>';
+                $pattern = ';(http://is0.gaslightmedia.com/[^"]+);si';
+                foreach ($results as $post) {
+                    $content = $post->post_content;
+                    preg_match_all($pattern, $post->post_content, $matches);
+                    $matches = array_unique($matches[0]);
+                    echo '<pre>' . print_r($post->ID, true) . '</pre>';
+                    echo '<pre>' . print_r($matches, true) . '</pre>';
+                    foreach ($matches as $match) {
+                        // process the file as media library
+                        $parsed   = parse_url($match);
+                        $filename = basename($parsed['path']);
+                        $rootUrl  = str_replace('/' . $filename, '', $match);
+                        echo '<pre>' . print_r($parsed, true) . '</pre>';
+                        echo '<pre>' . print_r($filename, true) . '</pre>';
+                        echo '<pre>' . print_r($rootUrl, true) . '</pre>';
+                        $img_id = $this->_handleMediaFile(
+                            $filename,
+                            '',
+                            $post->ID,
+                            $rootUrl . '/'
+                        );
+                        echo '<pre>' . print_r($img_id, true) . '</pre>';
+                        $replaceUrl = wp_get_attachment_url($img_id);
+                        echo '<pre>' . print_r($image, true) . '</pre>';
+                        $content = str_replace($match, $replaceUrl, $content);
+                     }
+                    $updatePost = array(
+                        'ID'           => $post->ID,
+                        'post_content' => $content
+                    );
+                    wp_update_post($updatePost);
+                }
+            }
+        }
+
+        private function _getCkImages()
+        {
+            global $wpdb;
+            if ($this->_options['ckeditor_schema'] && $this->_options['ckeditor_images_table']) {
+                $this->_images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
+                $this->_connect();
+                $sql = "
+                SELECT *
+                  FROM {$this->_options['ckeditor_schema']}.{$this->_options['ckeditor_images_table']}";
+                $stmt = $this->_dbh->query($sql);
+                while ($row = $stmt->fetch()) {
+                    echo '<pre>' . print_r($row, true) . '</pre>';
+                    $fileName = $row['name_on_disk'];
+                    $fileTitle = ($row['file_name']) ? $row['file_name'] : $fileName;
+                    $wpImage = $this->_handleMediaFile(
+                        $fileName,
+                        $fileTitle,
+                        '',
+                        0,
+                        $this->_options['toolbox_image_url'] . '/CKImage/'
+                    );
+                    echo '<pre>' . print_r($wpImage, true) . '</pre>';
+                    $this->_images[$wpImage] = $fileName;
+                }
+                $this->_storeImages();
+            } else {
+                return false;
+            }
+        }
+
+        private function _getToolboxFiles()
+        {
+            global $wpdb;
+            echo '<pre>' . print_r($this->_options['toolbox_schema'], true) . '</pre>';
+            echo '<pre>' . print_r($this->_options['toolbox_files_table'], true) . '</pre>';
+            if ($this->_options['toolbox_files_table']) {
+                $this->_files = get_option(GLM_WP_IMPORT_FILES_OPTION, array());
+                $this->_connect();
+                $sql = "
+                SELECT *
+                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_files_table']}";
+                $stmt = $this->_dbh->query($sql);
+                while ($row = $stmt->fetch()) {
+                    echo '<pre>' . print_r($row, true) . '</pre>';
+                    $fileName = $row['filename'];
+                    $fileTitle = ($row['urltext']) ? $row['urltext'] : $fileName;
+                    $wpImage = $this->_handleMediaFile(
+                        $fileName,
+                        $fileTitle,
+                        '',
+                        0,
+                        $this->_options['toolbox_image_url'] . '/_ORIGINAL_/'
+                    );
+                    echo '<pre>' . print_r($wpImage, true) . '</pre>';
+                    $this->_files[$wpImage] = $fileName;
+                }
+                $this->_storeFiles();
+            } else {
+                return false;
+            }
+        }
+
+        private function _getParagraphImages()
+        {
+            global $wpdb;
+            echo '<pre>' . print_r($this->_options['toolbox_schema'], true) . '</pre>';
+            echo '<pre>' . print_r($this->_options['toolbox_paragraphs_table'], true) . '</pre>';
+            if ($this->_options['toolbox_paragraphs_table']) {
+                $this->_images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
+                $this->_connect();
+                $sql = "
+                SELECT image,caption
+                  FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_paragraphs_table']}
+                 WHERE image != ''";
+                $stmt = $this->_dbh->query($sql);
+                while ($row = $stmt->fetch()) {
+                    echo '<pre>' . print_r($row, true) . '</pre>';
+                    $fileName = $row['image'];
+                    $fileTitle = ($row['caption']) ? $row['caption'] : $fileName;
+                    $wpImage = $this->_handleMediaFile(
+                        $fileName,
+                        $fileTitle,
+                        '',
+                        0,
+                        $this->_options['toolbox_image_url'] . '/tbs1/'
+                    );
+                    echo '<pre>' . print_r($wpImage, true) . '</pre>';
+                    $this->_images[$wpImage] = $fileName;
+                }
+                $this->_storeImages();
+            }
+        }
+
+        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=toolbox&amp;step=1">Begin Import</a></p>';
+                $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array());
+                echo '<pre>' . print_r($currentPostArray, true) . '</pre>';
+                $images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array());
+                echo '<pre>' . print_r($images, true) . '</pre>';
+                $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array());
+                echo '<pre>' . print_r($files, true) . '</pre>';
+                if (count($currentPostArray) > 0) {
+                    echo '<p>Pages have been imported</p>';
+                    echo '<p><a href="admin.php?import=toolbox&amp;step=2">Step Two (Importing Images)</a></p>';
+                    echo '<p><a href="admin.php?import=toolbox&amp;step=3">Step Three (Updating Image Ref)</a></p>';
+                } else {
+                    echo '<p><a href="admin.php?import=toolbox&amp;step=1">Begin Import</a></p>';
+                }
+                break;
+            case 1:
+                echo '<p>Reset</p>';
+                $this->_post = $this->_images = $this->_files = array();
+                $this->_storePost();
+                $this->_storeImages();
+                $this->_storeFiles();
+                $numPagesImported = $this->_import();
+                echo '<p>' . $numPagesImported . ' Pages Imported</p>';
+                echo '<p><a href="admin.php?import=toolbox&amp;step=2">Step Two (Importing Images)</a></p>';
+                break;
+            case 2:
+                echo '<p>Done</p>';
+                echo '<p>Now processing the images from old database tables</p>';
+                $this->_images = array();
+                $this->_storeImages();
+                $this->_files = array();
+                $this->_storeFiles();
+                if ($this->_options['toolbox_page_table'] == 'pages') {
+                    $this->_getCkImages();
+                    $this->_getToolboxFiles();
+                    $this->_getParagraphImages();
+                    echo '<p>Done</p>';
+                } else {
+                    echo '<p>No import from images</p>';
+                }
+                echo '<p><a href="admin.php?import=toolbox&amp;step=3">Step Three (Updating Image Ref)</a></p>';
+                break;
+            case 3:
+                echo '<p>Phase Three</p>';
+                $this->_updateMediaSrc();
+                echo '<p>Done</p>';
+                echo '<p><a href="admin.php?import=toolbox&amp;step=4">Step Four (Updating Files Ref)</a></p>';
+                break;
+            case 4:
+                echo '<p>Phase Four</p>';
+                echo '<p>Files</p>';
+                $this->_updateFilesHref();
+                echo '<p>Done</p>';
+                echo '<p><a href="admin.php?import=toolbox&amp;step=5">Step Five (Updating Url\'s and keywords)</a></p>';
+                break;
+            case 5:
+                echo '<p>Phase Five</p>';
+                echo '<p>Site Url</p>';
+                // Replace the page Url's
+                $this->_replaceUrls();
+                // Replace the Keywords
+                $this->_replaceKeywords();
+                echo '<p>Done</p>';
+                break;
+            }
+
+            $this->_footer();
+        }
+    }
+}
+
+$toolbox_import = new Toolbox_Import();
+
+register_importer(
+     'toolbox',
+     __('Toolbox', 'import-toolbox-pages'),
+     sprintf(
+         __('Import the contents of Gaslight Toolbox Pages as pages. Visit <a href="%s">setup</a> first to setup the database options.',
+         'import-toolbox-pages'),
+         'options-general.php?page=glmwpimporter'
+     ),
+     array($toolbox_import, 'dispatch')
+);
index f8cda2b..c8367b3 100644 (file)
--- a/index.php
+++ b/index.php
@@ -16,7 +16,8 @@ define('GLM_WP_IMPORT_FILES_OPTION', 'glmwp_import_files');
 
 if (is_admin()) {
     require_once 'controllers/Admin.php';
-    require_once 'controllers/Import.php';
+    require_once 'controllers/ToolboxImport.php';
+    require_once 'controllers/EventImageImport.php';
     register_activation_hook(__FILE__, array('GlmWPImporter_Admin_Controller', 'activate_plugin'));
     register_deactivation_hook(__FILE__, array('GlmWPImporter_Admin_Controller', 'deactivate_plugin'));
     register_uninstall_hook(__FILE__, array('GlmWPImporter_Admin_Controller', 'uninstall'));