From: Steve Sutton Date: Mon, 28 Sep 2015 13:40:05 +0000 (-0400) Subject: Updates for importers X-Git-Tag: v0.0.2^2~5 X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/?a=commitdiff_plain;h=9947352fcac8336022850939306a2834a3f87930;p=WP-Plugins%2Fglm-wp-importer.git Updates for importers adding Event Image Importer --- diff --git a/controllers/EventImageImport.php b/controllers/EventImageImport.php new file mode 100644 index 0000000..4ffce76 --- /dev/null +++ b/controllers/EventImageImport.php @@ -0,0 +1,445 @@ + + * @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 + * @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 + * @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 '
'; + echo '

'.__('Event Image Importer').'

'; + } + + private function _footer() + { + echo '
'; + } + + 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 '

Confirming Settings...

'; + if (isset($checkErrors) && is_array($checkErrors) && !empty($checkErrors)) { + printf("
Please update empty GLM Import Settings:\n%s
", + 'options-general.php?page=glmwpimporter', + implode("\n", $checkErrors) + ); + } else { + echo '

Event Images

'; + } + } + + 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 '
' . print_r($files, true) . '
'; + //$images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array()); + //$media = array_merge($images, $files); + //echo '
' . print_r($media, true) . '
'; + $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 '
'; + $urlPattern = '%]*)" ?[^>]*>([^>]+)%s'; + if (preg_match_all($urlPattern, $content, $isMatch)) { + $isMatchCount = count($isMatch[0]); + echo '

Matches is0 ' . $isMatchCount . '

'; + for ($index = 0; $index < $isMatchCount; ++$index) { + echo '
'.htmlspecialchars($isMatch[1][$index]).'
'; + //echo '
'.htmlspecialchars(basename($isMatch[1][$index])).'
'; + //echo '
'.print_r(pathinfo($isMatch[1][$index]), true).'
'; + $fileInfo = pathinfo($isMatch[1][$index]); + $fileName = $fileInfo['filename']; + echo '
File Name: ' . print_r($fileName, true)  . '
'; + echo '
File Name: ' . print_r($fileInfo, true)  . '
'; + $fileTitle = $isMatch[2][$index]; + echo '
File Title: ' . print_r($fileTitle, true)  . '
'; + $key = $this->_getAttachmentByName($fileName); + echo '
Key: ' . print_r($key, true)  . '
'; + // 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 '
'.htmlspecialchars($content).'
'; + echo '
'; + } + } + } + + private function replaceIsoUrls() + { + global $wpdb; + $this->_connect(); + echo '

Replace IS0 url\'s

'; + $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 '
'.$sql.'
'; + $results = $wpdb->get_results($sql, OBJECT); + if (count($results) > 0) { + //echo '
' . print_r($results, true) . '
'; + $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 '
' . print_r($post->ID, true) . '
'; + echo '
' . print_r($matches, true) . '
'; + foreach ($matches as $match) { + // process the file as media library + $parsed = parse_url($match); + $filename = basename($parsed['path']); + $rootUrl = str_replace('/' . $filename, '', $match); + echo '
' . print_r($parsed, true) . '
'; + echo '
' . print_r($filename, true) . '
'; + echo '
' . print_r($rootUrl, true) . '
'; + $img_id = $this->_handleMediaFile( + $filename, + '', + $post->ID, + $rootUrl . '/' + ); + echo '
' . print_r($img_id, true) . '
'; + $replaceUrl = wp_get_attachment_url($img_id); + echo '
' . print_r($image, true) . '
'; + $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 '

' . $this->_options['toolbox_image_url'] . '

'; + while( $event = $stmt->fetch() ) { + //echo '
' . print_r($event, true) . '
'; + $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 '
Results: ' . print_r($results, true)  . '
'; + //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 '
Image Id: ' . print_r($img_id, true) . '
'; + //echo '
Results: ' . print_r($ePost['ID'], true)  . '
'; + //if ($img_id) { + //update_post_meta( + //$results[0]['post_id'], + //'_thumbnail_id', + //$img_id + //); + //} + //} + } + sort($images, SORT_NATURAL); + $imgUnique = array_unique($images); + echo '

Number of images ' . count($images) . '

'; + echo '

Number of unique images ' . count($imgUnique) . '

'; + //echo '
' . print_r($images, true) . '
'; + } + 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 '

Import Images

'; + break; + case 1: + //echo '

Weeee!!!!

'; + $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 setup 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 index 43a77fb..0000000 --- a/controllers/Import.php +++ /dev/null @@ -1,1377 +0,0 @@ - - * @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 - * @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 - * @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 '
'; - echo '

'.__('Toolbox Importer').'

'; - } - - private function _footer() - { - echo '
'; - } - - 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 '

Confirming Settings...

'; - if (isset($checkErrors) && is_array($checkErrors) && !empty($checkErrors)) { - printf("
Please update empty GLM Import Settings:\n%s
", - 'options-general.php?page=glmwpimporter', - implode("\n", $checkErrors) - ); - } else { - echo '

All Set!

'; - $this->_connect(); - $WHERE = $this->_getWhereSql(); - $sql = " - SELECT count(*) - FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']} - $WHERE"; - //echo '
' . $sql . '
'; - $totalPages = $this->_dbh->query($sql)->fetchColumn(); - printf('

Found %d Pages

', $totalPages); - //echo '

Part 2

'; - } - } - - 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.'"] ' . $data['caption'] . '[/caption]'; - } else if (isset($data['imagename']) && $data['imagename']) { - $content .= '[caption align="align'.$alignment.'"] ' . $data['imagename'] . '[/caption]'; - } else { - $content .= ''; - } - 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".''.$fileName.''; - } - - 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 '
' . print_r($data, true) . '
'; - //exit; - foreach ($data as &$page) { - $page['srcs'] = array(); - $paraStmt->bindParam(':page', $page['id'], PDO::PARAM_INT); - $paraStmt->execute(); - $paragraphs = $paraStmt->fetchAll(); - //echo '
' . print_r($paragraphs, true) . '
'; - //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'] .= '

'.$page['category'].'

'; - ++$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'] .= '

'.$paragraph['title'].'

'; - } - 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'] .= '

'.$paragraph['name'].'

'; - } - if (isset($paragraph['title']) && $paragraph['title']) { - $page['pageContent'] .= '

'.$paragraph['title'].'

'; - } - 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'] .= '

'.$paragraph['name'].'

'; - } - if (isset($paragraph['title']) && $paragraph['title']) { - $page['pageContent'] .= '

'.$paragraph['title'].'

'; - } - 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("/' . print_r($matches, true) . ''; - - /* - 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 '
Files: ' . print_r($file, true) . '
'; - //$page['files'][] = $file['filename']; - $page['pageContent'] .= $this->_displayFile($file); - } - ++$iterator; - } - //echo '
Files: ' . print_r($page['files'], true) . '
'; - } - return $data; - } - - private function _readOptions() - { - echo '
' . print_r($this->_options, true) . '
'; - echo '
' . print_r(get_option(GLM_WP_IMPORT_POST_OPTION, array()), true) . '
'; - } - - private function _import() - { - echo '

Fetching Pages

'; - $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 '
' . print_r(htmlspecialchars($page['pageContent']), true) . '
'; - //} - //echo '
' . print_r($pages, true) . '
'; - //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 '

Replace keywords

'; - 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 '
' . print_r($page, true) .  '
'; - // find out which page (wp) this needs to be - $wpPost = get_page_by_title($page['navigation_name']); - if (!$wpPost) { - continue; - } - //echo '
' . print_r($wpPost, true) .  '
'; - echo '
' . print_r(get_permalink($wpPost), true) .  '
'; - $replaceUrl = '' . $page['navigation_name'] . ''; - - $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 '
' . print_r($sql, true) . '
'; - $results = $wpdb->get_results($sql, OBJECT); - $total = count($results); - if ($total > 0) { - foreach ($results as $post) { - //echo '
' . print_r($post, true) . '
'; - $content = $post->post_content; - $content = preg_replace("/\{{$page['keyword']}\}/", $replaceUrl, $content); - wp_update_post(array( - 'ID' => $post->ID, - 'post_content' => $content - )); - } - } - echo '

Count results: ' . $total . '

'; - //echo '
' . print_r($results, true) . '
'; - } - } - - 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 '
' . print_r($currentPostArray, true) . '
'; - $this->_connect(); - echo '

Replace page url\'s

'; - $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 '
' . print_r($pattern, true) . '
'; - //echo '
' . print_r($results, true) . '
'; - foreach ($results as $post) { - $content = $post->post_content; - preg_match_all($pattern, $post->post_content, $matches); - echo '
' . print_r($matches, true) . '
'; - foreach ($matches[0] as $match) { - // find the page id for matched url - if (preg_match(';-([0-9]+)/$;', $match, $found)) { - echo '
' . print_r($found, true) . '
'; - if ($found && $currentPostArray[$found[1]]) { - $wpPost = get_page($currentPostArray[$found[1]]); - $replaceUrl = get_permalink($wpPost->ID); - echo '
' . print_r($replaceUrl, true) . '
'; - $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,'' ); - if ( FALSE === $headpos ) { - $headpos= mb_strpos( $content,'' ); - } - if ( FALSE !== $headpos ) { - $headpos+=6; - $content = mb_substr( $content,0,$headpos ) . '' .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 '

Replace Src\'s

'; - $sql = " - SELECT * - FROM {$wpdb->prefix}posts - WHERE post_content LIKE '%get_results($sql, OBJECT); - echo '

Number of Pages'.count($results).'

'; - if (count($results) > 0) { - $pattern = ';(]>);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 '
'; - //echo '
' . print_r($image, true)  . '
'; - if ($image->hasAttribute('class')) { - //echo '
' . print_r($image->getAttribute('class'), true)  . '
'; - if (preg_match('%wp-image-\d+%', $image->getAttribute('class'))) { - //echo 'Continue'; - //echo '
'; - continue; - } - } - if ($image->hasAttribute('style')) { - $style = $image->getAttribute('style'); - //var_dump($style); - //echo '
' . print_r($style, true)  . '
'; - if (preg_match('%[^-]width[: ]+(\d+)%', $style, $wMatch)) { - $width = $wMatch[1]; - //echo '
wMatch: ' . print_r($wMatch, true)  . '
'; - } - if (preg_match('%[^-]height[: ]+(\d+)%', $style, $hMatch)) { - $height = $hMatch[1]; - } - //echo '
width: ' . print_r($width, true)  . '
'; - //echo '
height: ' . print_r($height, true)  . '
'; - } - if ($image->hasAttribute('width')) { - $width = $image->getAttribute('width'); - } - if ($image->hasAttribute('height')) { - $height = $image->getAttribute('height'); - } - if ($image->hasAttribute('src')) { - //echo '
' . print_r($image->getAttribute('src'), true)  . '
'; - $imgName = basename($image->getAttribute('src')); - //echo '
' . print_r($imgName, true)  . '
'; - $imgPathInfo = pathinfo($imgName); - //echo '
' . print_r($imgPathInfo, true) . '
'; - $wpImage = $this->_getAttachmentByName($imgPathInfo['filename']); - //echo '
' . print_r($wpImage, true) . '
'; - //exit; - if (!$wpImage) { - //echo '

Image not found as attachment

'; - //echo '
' . print_r($imgPathInfo, true) . '
'; - if (preg_match(';(is\d{2}-\d{10}-\d{5})(\d{1}|[-]\d+x\d+);', $imgPathInfo['filename'], $matches)) { - //echo '

Duplicate Image found

'; - //echo '
' . print_r($matches, true) . '
'; - $wpImage = $this->_getAttachmentByName($matches[1]); - if ($wpImage) { - //echo '

Found Image

'; - $fileDuplicates[] = $image->getAttribute('src'); - } else { - //echo '

Image still not found

'; - //echo ''; - $filesMissing[] = $image->getAttribute('src'); - continue; - } - } - } - if (!$wpImage) { - //echo '

Image not found as attachment 2

'; - //echo '
' . print_r($image->getAttribute('src'), true) . '
'; - $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 '
' . print_r($parsed, true) . '
'; - //echo '
' . print_r($filename, true) . '
'; - //echo '
' . print_r($rootUrl, true) . '
'; - //if (preg_match('/(\d{4})\/(\d{2})$/', $rootUrl, $matches)) { - //echo '
' . print_r($matches, true) . '
'; - //$uploadDir = wp_upload_dir(); - //echo '
' . print_r($uploadDir, true) . '
'; - //$absPath = $uploadDir['basedir'] . '/' . $matches[1] . '/' . $matches[2]; - //echo '
' . print_r($absPath, true) . '
'; - ////$wpImage = $this->_addMedia($absPath . '/' . $filename, $post->ID); - //echo '
' . print_r($imageId, true) . '
'; - //} - //$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 '
'.htmlspecialchars($strToReplace).'
'; - //echo '

Image found: id '.$wpImage->ID.'

'; - if ($width && $height) { - //echo '

width: ' . $width . '

'; - //echo '

height: ' . $height . '

'; - if ($width > 300 || $height > 300) { - //echo '

Found Large

'; - $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 '

Found Thumbnail

'; - $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 '

Found Medium

'; - $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 '

no media found

'; - $filesMissing[] = $image->getAttribute('src'); - } - } - //echo ''; - } - // remove the extra stuff Dom put in - $content = preg_replace( - '/^/', - '', - str_replace( - array('', '', '', ''), - array('', '', '', ''), - $dom->saveHTML() - ) - ); - //echo '
'.print_r(htmlspecialchars($content), true).'
'; - $updatePost = array( - 'ID' => $post->ID, - 'post_content' => $content - ); - wp_update_post($updatePost); - } - //echo '
Files: ' . print_r($files, true) . '
'; - echo '
Files Found: ' . print_r($filesFound, true) . '
'; - echo '
Duplicate Files: ' . print_r($fileDuplicates, true) . '
'; - echo '
Files Missing: ' . print_r($filesMissing, true) . '
'; - } - } - - private function _updateFilesHref() - { - global $wpdb; - $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array()); - $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array()); - echo '
' . print_r($files, true) . '
'; - //$images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array()); - //$media = array_merge($images, $files); - //echo '
' . print_r($media, true) . '
'; - $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 '
'; - $urlPattern = '%]*)" ?[^>]*>([^>]+)%s'; - if (preg_match_all($urlPattern, $content, $isMatch)) { - $isMatchCount = count($isMatch[0]); - echo '

Matches is0 ' . $isMatchCount . '

'; - for ($index = 0; $index < $isMatchCount; ++$index) { - echo '
'.htmlspecialchars($isMatch[1][$index]).'
'; - //echo '
'.htmlspecialchars(basename($isMatch[1][$index])).'
'; - //echo '
'.print_r(pathinfo($isMatch[1][$index]), true).'
'; - $fileInfo = pathinfo($isMatch[1][$index]); - $fileName = $fileInfo['filename']; - echo '
File Name: ' . print_r($fileName, true)  . '
'; - echo '
File Name: ' . print_r($fileInfo, true)  . '
'; - $fileTitle = $isMatch[2][$index]; - echo '
File Title: ' . print_r($fileTitle, true)  . '
'; - $key = $this->_getAttachmentByName($fileName); - echo '
Key: ' . print_r($key, true)  . '
'; - // 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 '
'.htmlspecialchars($content).'
'; - echo '
'; - } - } - } - - 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 '%get_results($sql, OBJECT); - if (count($results) > 0) { - foreach ($results as $post) { - $content = $post->post_content; - echo '
Updating Media Src\'s: ' . print_r($post->post_title, true)  . '
'; - echo '
'; - if (preg_match_all('%\[caption [^\]]+\]]+)>([^\[]*)\[/caption\]%', $content, $cMatch)) { - $captionCount = count($cMatch[0]); - echo '

Matches in Caption ' . $captionCount . '

'; - //echo '
' . print_r($cMatch, true)  . '
'; - for ($index = 0; $index < $captionCount; ++$index) { - //echo '
cMatch: ' . print_r($cMatch, true)  . '
'; - echo '
'.htmlspecialchars($cMatch[0][$index]).'
'; - echo '
Caption Match: ' . print_r($cMatch[1][$index], true)  . '
'; - echo '
Caption Text: ' . print_r($cMatch[2][$index], true)  . '
'; - if (preg_match('%src="([^"]+)"%', $cMatch[1][$index], $srcMatch)) { - echo '
Sub Src Match: ' . print_r($srcMatch[1], true)  . '
'; - $fileInfo = pathinfo($srcMatch[1]); - $fileName = basename($srcMatch[1]); - $fileName = $fileInfo['filename']; - echo '
File Name: ' . print_r($fileName, true)  . '
'; - $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(''.htmlspecialchars($caption).''; - $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('%]+)>%', $content, $matches)) { - $imageCount = count($matches[0]); - for ($index = 0; $index < $imageCount; ++$index) { - echo '
Image Match: ' . $imageCount  . '
'; - echo '
'.htmlspecialchars($matches[0][$index]).'
'; - if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) { - return new WP_Error('upload_error', $uploads['error']); - } - echo '
Uploads Url: ' . print_r($uploads['url'], true)  . '
'; - if (preg_match('%src="' . $uploads['url'] . '[^"]+"%', $matches[1][$index], $pMatch)) { - continue; - } - if (preg_match('%src="([^"]+)"%', $matches[1][$index], $srcMatch)) { - echo '
Sub Src Match: ' . print_r($srcMatch[1], true)  . '
'; - $fileInfo = pathinfo($srcMatch[1]); - echo '
' . print_r($fileInfo, true) . '
'; - $fileName = $fileInfo['filename']; - echo '
File Url: ' . print_r($srcMatch[1], true)  . '
'; - echo '
File Name: ' . print_r($fileName, true)  . '
'; - $path = $filInfo['dirname']; - echo '
File Path: ' . print_r($path, true)  . '
'; - $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(''.htmlspecialchars($imageTag).''; - $content = str_replace($matches[0][$index], $imageTag, $content); - } - } - } - } - echo '
'.htmlspecialchars($content).'
'; - echo '
'; - $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 '

Replace IS0 url\'s

'; - $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 '
'.$sql.'
'; - $results = $wpdb->get_results($sql, OBJECT); - if (count($results) > 0) { - //echo '
' . print_r($results, true) . '
'; - $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 '
' . print_r($post->ID, true) . '
'; - echo '
' . print_r($matches, true) . '
'; - foreach ($matches as $match) { - // process the file as media library - $parsed = parse_url($match); - $filename = basename($parsed['path']); - $rootUrl = str_replace('/' . $filename, '', $match); - echo '
' . print_r($parsed, true) . '
'; - echo '
' . print_r($filename, true) . '
'; - echo '
' . print_r($rootUrl, true) . '
'; - $img_id = $this->_handleMediaFile( - $filename, - '', - $post->ID, - $rootUrl . '/' - ); - echo '
' . print_r($img_id, true) . '
'; - $replaceUrl = wp_get_attachment_url($img_id); - echo '
' . print_r($image, true) . '
'; - $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 '
' . print_r($row, true) . '
'; - $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 '
' . print_r($wpImage, true) . '
'; - $this->_images[$wpImage] = $fileName; - } - $this->_storeImages(); - } else { - return false; - } - } - - private function _getToolboxFiles() - { - global $wpdb; - echo '
' . print_r($this->_options['toolbox_schema'], true) . '
'; - echo '
' . print_r($this->_options['toolbox_files_table'], true) . '
'; - 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 '
' . print_r($row, true) . '
'; - $fileName = $row['filename']; - $fileTitle = ($row['urltext']) ? $row['urltext'] : $fileName; - $wpImage = $this->_handleMediaFile( - $fileName, - $fileTitle, - '', - 0, - $this->_options['toolbox_image_url'] . '/_ORIGINAL_/' - ); - echo '
' . print_r($wpImage, true) . '
'; - $this->_files[$wpImage] = $fileName; - } - $this->_storeFiles(); - } else { - return false; - } - } - - private function _getParagraphImages() - { - global $wpdb; - echo '
' . print_r($this->_options['toolbox_schema'], true) . '
'; - echo '
' . print_r($this->_options['toolbox_paragraphs_table'], true) . '
'; - 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 '
' . print_r($row, true) . '
'; - $fileName = $row['image']; - $fileTitle = ($row['caption']) ? $row['caption'] : $fileName; - $wpImage = $this->_handleMediaFile( - $fileName, - $fileTitle, - '', - 0, - $this->_options['toolbox_image_url'] . '/tbs1/' - ); - echo '
' . print_r($wpImage, true) . '
'; - $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 '

Begin Import

'; - $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array()); - echo '
' . print_r($currentPostArray, true) . '
'; - $images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array()); - echo '
' . print_r($images, true) . '
'; - $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array()); - echo '
' . print_r($files, true) . '
'; - if (count($currentPostArray) > 0) { - echo '

Pages have been imported

'; - echo '

Step Two (Importing Images)

'; - echo '

Step Three (Updating Image Ref)

'; - } else { - echo '

Begin Import

'; - } - break; - case 1: - echo '

Reset

'; - $this->_post = $this->_images = $this->_files = array(); - $this->_storePost(); - $this->_storeImages(); - $this->_storeFiles(); - $numPagesImported = $this->_import(); - echo '

' . $numPagesImported . ' Pages Imported

'; - echo '

Step Two (Importing Images)

'; - break; - case 2: - echo '

Done

'; - echo '

Now processing the images from old database tables

'; - $this->_images = array(); - $this->_storeImages(); - $this->_files = array(); - $this->_storeFiles(); - if ($this->_options['toolbox_page_table'] == 'pages') { - $this->_getCkImages(); - $this->_getToolboxFiles(); - $this->_getParagraphImages(); - echo '

Done

'; - } else { - echo '

No import from images

'; - } - echo '

Step Three (Updating Image Ref)

'; - break; - case 3: - echo '

Phase Three

'; - $this->_updateMediaSrc(); - echo '

Done

'; - echo '

Step Four (Updating Files Ref)

'; - break; - case 4: - echo '

Phase Four

'; - echo '

Files

'; - $this->_updateFilesHref(); - echo '

Done

'; - echo '

Step Five (Updating Url\'s and keywords)

'; - break; - case 5: - echo '

Phase Five

'; - echo '

Site Url

'; - // Replace the page Url's - $this->_replaceUrls(); - // Replace the Keywords - $this->_replaceKeywords(); - echo '

Done

'; - 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 setup 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 index 0000000..3d6e320 --- /dev/null +++ b/controllers/ToolboxImport.php @@ -0,0 +1,1377 @@ + + * @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 + * @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 + * @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 '
'; + echo '

'.__('Toolbox Importer').'

'; + } + + private function _footer() + { + echo '
'; + } + + 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 '

Confirming Settings...

'; + if (isset($checkErrors) && is_array($checkErrors) && !empty($checkErrors)) { + printf("
Please update empty GLM Import Settings:\n%s
", + 'options-general.php?page=glmwpimporter', + implode("\n", $checkErrors) + ); + } else { + echo '

All Set!

'; + $this->_connect(); + $WHERE = $this->_getWhereSql(); + $sql = " + SELECT count(*) + FROM {$this->_options['toolbox_schema']}.{$this->_options['toolbox_page_table']} + $WHERE"; + //echo '
' . $sql . '
'; + $totalPages = $this->_dbh->query($sql)->fetchColumn(); + printf('

Found %d Pages

', $totalPages); + //echo '

Part 2

'; + } + } + + 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.'"] ' . $data['caption'] . '[/caption]'; + } else if (isset($data['imagename']) && $data['imagename']) { + $content .= '[caption align="align'.$alignment.'"] ' . $data['imagename'] . '[/caption]'; + } else { + $content .= ''; + } + 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".''.$fileName.''; + } + + 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 '
' . print_r($data, true) . '
'; + //exit; + foreach ($data as &$page) { + $page['srcs'] = array(); + $paraStmt->bindParam(':page', $page['id'], PDO::PARAM_INT); + $paraStmt->execute(); + $paragraphs = $paraStmt->fetchAll(); + //echo '
' . print_r($paragraphs, true) . '
'; + //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'] .= '

'.$page['category'].'

'; + ++$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'] .= '

'.$paragraph['title'].'

'; + } + 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'] .= '

'.$paragraph['name'].'

'; + } + if (isset($paragraph['title']) && $paragraph['title']) { + $page['pageContent'] .= '

'.$paragraph['title'].'

'; + } + 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'] .= '

'.$paragraph['name'].'

'; + } + if (isset($paragraph['title']) && $paragraph['title']) { + $page['pageContent'] .= '

'.$paragraph['title'].'

'; + } + 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("/' . print_r($matches, true) . ''; + + /* + 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 '
Files: ' . print_r($file, true) . '
'; + //$page['files'][] = $file['filename']; + $page['pageContent'] .= $this->_displayFile($file); + } + ++$iterator; + } + //echo '
Files: ' . print_r($page['files'], true) . '
'; + } + return $data; + } + + private function _readOptions() + { + echo '
' . print_r($this->_options, true) . '
'; + echo '
' . print_r(get_option(GLM_WP_IMPORT_POST_OPTION, array()), true) . '
'; + } + + private function _import() + { + echo '

Fetching Pages

'; + $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 '
' . print_r(htmlspecialchars($page['pageContent']), true) . '
'; + //} + //echo '
' . print_r($pages, true) . '
'; + //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 '

Replace keywords

'; + 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 '
' . print_r($page, true) .  '
'; + // find out which page (wp) this needs to be + $wpPost = get_page_by_title($page['navigation_name']); + if (!$wpPost) { + continue; + } + //echo '
' . print_r($wpPost, true) .  '
'; + echo '
' . print_r(get_permalink($wpPost), true) .  '
'; + $replaceUrl = '' . $page['navigation_name'] . ''; + + $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 '
' . print_r($sql, true) . '
'; + $results = $wpdb->get_results($sql, OBJECT); + $total = count($results); + if ($total > 0) { + foreach ($results as $post) { + //echo '
' . print_r($post, true) . '
'; + $content = $post->post_content; + $content = preg_replace("/\{{$page['keyword']}\}/", $replaceUrl, $content); + wp_update_post(array( + 'ID' => $post->ID, + 'post_content' => $content + )); + } + } + echo '

Count results: ' . $total . '

'; + //echo '
' . print_r($results, true) . '
'; + } + } + + 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 '
' . print_r($currentPostArray, true) . '
'; + $this->_connect(); + echo '

Replace page url\'s

'; + $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 '
' . print_r($pattern, true) . '
'; + //echo '
' . print_r($results, true) . '
'; + foreach ($results as $post) { + $content = $post->post_content; + preg_match_all($pattern, $post->post_content, $matches); + echo '
' . print_r($matches, true) . '
'; + foreach ($matches[0] as $match) { + // find the page id for matched url + if (preg_match(';-([0-9]+)/$;', $match, $found)) { + echo '
' . print_r($found, true) . '
'; + if ($found && $currentPostArray[$found[1]]) { + $wpPost = get_page($currentPostArray[$found[1]]); + $replaceUrl = get_permalink($wpPost->ID); + echo '
' . print_r($replaceUrl, true) . '
'; + $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,'' ); + if ( FALSE === $headpos ) { + $headpos= mb_strpos( $content,'' ); + } + if ( FALSE !== $headpos ) { + $headpos+=6; + $content = mb_substr( $content,0,$headpos ) . '' .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 '

Replace Src\'s

'; + $sql = " + SELECT * + FROM {$wpdb->prefix}posts + WHERE post_content LIKE '%get_results($sql, OBJECT); + echo '

Number of Pages'.count($results).'

'; + if (count($results) > 0) { + $pattern = ';(]>);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 '
'; + //echo '
' . print_r($image, true)  . '
'; + if ($image->hasAttribute('class')) { + //echo '
' . print_r($image->getAttribute('class'), true)  . '
'; + if (preg_match('%wp-image-\d+%', $image->getAttribute('class'))) { + //echo 'Continue'; + //echo '
'; + continue; + } + } + if ($image->hasAttribute('style')) { + $style = $image->getAttribute('style'); + //var_dump($style); + //echo '
' . print_r($style, true)  . '
'; + if (preg_match('%[^-]width[: ]+(\d+)%', $style, $wMatch)) { + $width = $wMatch[1]; + //echo '
wMatch: ' . print_r($wMatch, true)  . '
'; + } + if (preg_match('%[^-]height[: ]+(\d+)%', $style, $hMatch)) { + $height = $hMatch[1]; + } + //echo '
width: ' . print_r($width, true)  . '
'; + //echo '
height: ' . print_r($height, true)  . '
'; + } + if ($image->hasAttribute('width')) { + $width = $image->getAttribute('width'); + } + if ($image->hasAttribute('height')) { + $height = $image->getAttribute('height'); + } + if ($image->hasAttribute('src')) { + //echo '
' . print_r($image->getAttribute('src'), true)  . '
'; + $imgName = basename($image->getAttribute('src')); + //echo '
' . print_r($imgName, true)  . '
'; + $imgPathInfo = pathinfo($imgName); + //echo '
' . print_r($imgPathInfo, true) . '
'; + $wpImage = $this->_getAttachmentByName($imgPathInfo['filename']); + //echo '
' . print_r($wpImage, true) . '
'; + //exit; + if (!$wpImage) { + //echo '

Image not found as attachment

'; + //echo '
' . print_r($imgPathInfo, true) . '
'; + if (preg_match(';(is\d{2}-\d{10}-\d{5})(\d{1}|[-]\d+x\d+);', $imgPathInfo['filename'], $matches)) { + //echo '

Duplicate Image found

'; + //echo '
' . print_r($matches, true) . '
'; + $wpImage = $this->_getAttachmentByName($matches[1]); + if ($wpImage) { + //echo '

Found Image

'; + $fileDuplicates[] = $image->getAttribute('src'); + } else { + //echo '

Image still not found

'; + //echo ''; + $filesMissing[] = $image->getAttribute('src'); + continue; + } + } + } + if (!$wpImage) { + //echo '

Image not found as attachment 2

'; + //echo '
' . print_r($image->getAttribute('src'), true) . '
'; + $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 '
' . print_r($parsed, true) . '
'; + //echo '
' . print_r($filename, true) . '
'; + //echo '
' . print_r($rootUrl, true) . '
'; + //if (preg_match('/(\d{4})\/(\d{2})$/', $rootUrl, $matches)) { + //echo '
' . print_r($matches, true) . '
'; + //$uploadDir = wp_upload_dir(); + //echo '
' . print_r($uploadDir, true) . '
'; + //$absPath = $uploadDir['basedir'] . '/' . $matches[1] . '/' . $matches[2]; + //echo '
' . print_r($absPath, true) . '
'; + ////$wpImage = $this->_addMedia($absPath . '/' . $filename, $post->ID); + //echo '
' . print_r($imageId, true) . '
'; + //} + //$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 '
'.htmlspecialchars($strToReplace).'
'; + //echo '

Image found: id '.$wpImage->ID.'

'; + if ($width && $height) { + //echo '

width: ' . $width . '

'; + //echo '

height: ' . $height . '

'; + if ($width > 300 || $height > 300) { + //echo '

Found Large

'; + $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 '

Found Thumbnail

'; + $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 '

Found Medium

'; + $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 '

no media found

'; + $filesMissing[] = $image->getAttribute('src'); + } + } + //echo ''; + } + // remove the extra stuff Dom put in + $content = preg_replace( + '/^/', + '', + str_replace( + array('', '', '', ''), + array('', '', '', ''), + $dom->saveHTML() + ) + ); + //echo '
'.print_r(htmlspecialchars($content), true).'
'; + $updatePost = array( + 'ID' => $post->ID, + 'post_content' => $content + ); + wp_update_post($updatePost); + } + //echo '
Files: ' . print_r($files, true) . '
'; + echo '
Files Found: ' . print_r($filesFound, true) . '
'; + echo '
Duplicate Files: ' . print_r($fileDuplicates, true) . '
'; + echo '
Files Missing: ' . print_r($filesMissing, true) . '
'; + } + } + + private function _updateFilesHref() + { + global $wpdb; + $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array()); + $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array()); + echo '
' . print_r($files, true) . '
'; + //$images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array()); + //$media = array_merge($images, $files); + //echo '
' . print_r($media, true) . '
'; + $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 '
'; + $urlPattern = '%]*)" ?[^>]*>([^>]+)%s'; + if (preg_match_all($urlPattern, $content, $isMatch)) { + $isMatchCount = count($isMatch[0]); + echo '

Matches is0 ' . $isMatchCount . '

'; + for ($index = 0; $index < $isMatchCount; ++$index) { + echo '
'.htmlspecialchars($isMatch[1][$index]).'
'; + //echo '
'.htmlspecialchars(basename($isMatch[1][$index])).'
'; + //echo '
'.print_r(pathinfo($isMatch[1][$index]), true).'
'; + $fileInfo = pathinfo($isMatch[1][$index]); + $fileName = $fileInfo['filename']; + echo '
File Name: ' . print_r($fileName, true)  . '
'; + echo '
File Name: ' . print_r($fileInfo, true)  . '
'; + $fileTitle = $isMatch[2][$index]; + echo '
File Title: ' . print_r($fileTitle, true)  . '
'; + $key = $this->_getAttachmentByName($fileName); + echo '
Key: ' . print_r($key, true)  . '
'; + // 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 '
'.htmlspecialchars($content).'
'; + echo '
'; + } + } + } + + 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 '%get_results($sql, OBJECT); + if (count($results) > 0) { + foreach ($results as $post) { + $content = $post->post_content; + echo '
Updating Media Src\'s: ' . print_r($post->post_title, true)  . '
'; + echo '
'; + if (preg_match_all('%\[caption [^\]]+\]]+)>([^\[]*)\[/caption\]%', $content, $cMatch)) { + $captionCount = count($cMatch[0]); + echo '

Matches in Caption ' . $captionCount . '

'; + //echo '
' . print_r($cMatch, true)  . '
'; + for ($index = 0; $index < $captionCount; ++$index) { + //echo '
cMatch: ' . print_r($cMatch, true)  . '
'; + echo '
'.htmlspecialchars($cMatch[0][$index]).'
'; + echo '
Caption Match: ' . print_r($cMatch[1][$index], true)  . '
'; + echo '
Caption Text: ' . print_r($cMatch[2][$index], true)  . '
'; + if (preg_match('%src="([^"]+)"%', $cMatch[1][$index], $srcMatch)) { + echo '
Sub Src Match: ' . print_r($srcMatch[1], true)  . '
'; + $fileInfo = pathinfo($srcMatch[1]); + $fileName = basename($srcMatch[1]); + $fileName = $fileInfo['filename']; + echo '
File Name: ' . print_r($fileName, true)  . '
'; + $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(''.htmlspecialchars($caption).''; + $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('%]+)>%', $content, $matches)) { + $imageCount = count($matches[0]); + for ($index = 0; $index < $imageCount; ++$index) { + echo '
Image Match: ' . $imageCount  . '
'; + echo '
'.htmlspecialchars($matches[0][$index]).'
'; + if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) { + return new WP_Error('upload_error', $uploads['error']); + } + echo '
Uploads Url: ' . print_r($uploads['url'], true)  . '
'; + if (preg_match('%src="' . $uploads['url'] . '[^"]+"%', $matches[1][$index], $pMatch)) { + continue; + } + if (preg_match('%src="([^"]+)"%', $matches[1][$index], $srcMatch)) { + echo '
Sub Src Match: ' . print_r($srcMatch[1], true)  . '
'; + $fileInfo = pathinfo($srcMatch[1]); + echo '
' . print_r($fileInfo, true) . '
'; + $fileName = $fileInfo['filename']; + echo '
File Url: ' . print_r($srcMatch[1], true)  . '
'; + echo '
File Name: ' . print_r($fileName, true)  . '
'; + $path = $filInfo['dirname']; + echo '
File Path: ' . print_r($path, true)  . '
'; + $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(''.htmlspecialchars($imageTag).''; + $content = str_replace($matches[0][$index], $imageTag, $content); + } + } + } + } + echo '
'.htmlspecialchars($content).'
'; + echo '
'; + $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 '

Replace IS0 url\'s

'; + $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 '
'.$sql.'
'; + $results = $wpdb->get_results($sql, OBJECT); + if (count($results) > 0) { + //echo '
' . print_r($results, true) . '
'; + $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 '
' . print_r($post->ID, true) . '
'; + echo '
' . print_r($matches, true) . '
'; + foreach ($matches as $match) { + // process the file as media library + $parsed = parse_url($match); + $filename = basename($parsed['path']); + $rootUrl = str_replace('/' . $filename, '', $match); + echo '
' . print_r($parsed, true) . '
'; + echo '
' . print_r($filename, true) . '
'; + echo '
' . print_r($rootUrl, true) . '
'; + $img_id = $this->_handleMediaFile( + $filename, + '', + $post->ID, + $rootUrl . '/' + ); + echo '
' . print_r($img_id, true) . '
'; + $replaceUrl = wp_get_attachment_url($img_id); + echo '
' . print_r($image, true) . '
'; + $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 '
' . print_r($row, true) . '
'; + $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 '
' . print_r($wpImage, true) . '
'; + $this->_images[$wpImage] = $fileName; + } + $this->_storeImages(); + } else { + return false; + } + } + + private function _getToolboxFiles() + { + global $wpdb; + echo '
' . print_r($this->_options['toolbox_schema'], true) . '
'; + echo '
' . print_r($this->_options['toolbox_files_table'], true) . '
'; + 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 '
' . print_r($row, true) . '
'; + $fileName = $row['filename']; + $fileTitle = ($row['urltext']) ? $row['urltext'] : $fileName; + $wpImage = $this->_handleMediaFile( + $fileName, + $fileTitle, + '', + 0, + $this->_options['toolbox_image_url'] . '/_ORIGINAL_/' + ); + echo '
' . print_r($wpImage, true) . '
'; + $this->_files[$wpImage] = $fileName; + } + $this->_storeFiles(); + } else { + return false; + } + } + + private function _getParagraphImages() + { + global $wpdb; + echo '
' . print_r($this->_options['toolbox_schema'], true) . '
'; + echo '
' . print_r($this->_options['toolbox_paragraphs_table'], true) . '
'; + 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 '
' . print_r($row, true) . '
'; + $fileName = $row['image']; + $fileTitle = ($row['caption']) ? $row['caption'] : $fileName; + $wpImage = $this->_handleMediaFile( + $fileName, + $fileTitle, + '', + 0, + $this->_options['toolbox_image_url'] . '/tbs1/' + ); + echo '
' . print_r($wpImage, true) . '
'; + $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 '

Begin Import

'; + $currentPostArray = get_option(GLM_WP_IMPORT_POST_OPTION, array()); + echo '
' . print_r($currentPostArray, true) . '
'; + $images = get_option(GLM_WP_IMPORT_IMAGES_OPTION, array()); + echo '
' . print_r($images, true) . '
'; + $files = get_option(GLM_WP_IMPORT_FILES_OPTION, array()); + echo '
' . print_r($files, true) . '
'; + if (count($currentPostArray) > 0) { + echo '

Pages have been imported

'; + echo '

Step Two (Importing Images)

'; + echo '

Step Three (Updating Image Ref)

'; + } else { + echo '

Begin Import

'; + } + break; + case 1: + echo '

Reset

'; + $this->_post = $this->_images = $this->_files = array(); + $this->_storePost(); + $this->_storeImages(); + $this->_storeFiles(); + $numPagesImported = $this->_import(); + echo '

' . $numPagesImported . ' Pages Imported

'; + echo '

Step Two (Importing Images)

'; + break; + case 2: + echo '

Done

'; + echo '

Now processing the images from old database tables

'; + $this->_images = array(); + $this->_storeImages(); + $this->_files = array(); + $this->_storeFiles(); + if ($this->_options['toolbox_page_table'] == 'pages') { + $this->_getCkImages(); + $this->_getToolboxFiles(); + $this->_getParagraphImages(); + echo '

Done

'; + } else { + echo '

No import from images

'; + } + echo '

Step Three (Updating Image Ref)

'; + break; + case 3: + echo '

Phase Three

'; + $this->_updateMediaSrc(); + echo '

Done

'; + echo '

Step Four (Updating Files Ref)

'; + break; + case 4: + echo '

Phase Four

'; + echo '

Files

'; + $this->_updateFilesHref(); + echo '

Done

'; + echo '

Step Five (Updating Url\'s and keywords)

'; + break; + case 5: + echo '

Phase Five

'; + echo '

Site Url

'; + // Replace the page Url's + $this->_replaceUrls(); + // Replace the Keywords + $this->_replaceKeywords(); + echo '

Done

'; + 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 setup first to setup the database options.', + 'import-toolbox-pages'), + 'options-general.php?page=glmwpimporter' + ), + array($toolbox_import, 'dispatch') +); diff --git a/index.php b/index.php index f8cda2b..c8367b3 100644 --- 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'));