From 9947352fcac8336022850939306a2834a3f87930 Mon Sep 17 00:00:00 2001 From: Steve Sutton Date: Mon, 28 Sep 2015 09:40:05 -0400 Subject: [PATCH] Updates for importers adding Event Image Importer --- controllers/EventImageImport.php | 445 ++++++++++++++++++ controllers/{Import.php => ToolboxImport.php} | 4 +- index.php | 3 +- 3 files changed, 449 insertions(+), 3 deletions(-) create mode 100644 controllers/EventImageImport.php rename controllers/{Import.php => ToolboxImport.php} (99%) 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/ToolboxImport.php similarity index 99% rename from controllers/Import.php rename to controllers/ToolboxImport.php index 43a77fb..3d6e320 100644 --- a/controllers/Import.php +++ b/controllers/ToolboxImport.php @@ -1,7 +1,7 @@