Advertisement
Guest User

re-attach unattached images in WP (modded mediatools)

a guest
Apr 11th, 2017
1,336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.42 KB | None | 0 0
  1. <?php
  2. /**
  3. * Plugin Name: Media Tools
  4. * Plugin URI: https://github.com/c3mdigital/media-tools-for-WordPress
  5. * Description: Tools for working with the WordPress media library and converting images to attachments and featured images
  6. * Version: 1.1
  7. * Author: Chris Olbekson
  8. * Author URI: http://c3mdigital.com
  9. * License: GPL v2
  10. *
  11. */
  12.  
  13. /* Copyright 2012 Chris Olbekson (email : [email protected] )
  14.  
  15. This program is free software; you can redistribute it and/or modify
  16. it under the terms of the GNU General Public License, version 2, as
  17. published by the Free Software Foundation.
  18.  
  19. This program is distributed in the hope that it will be useful,
  20. but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. GNU General Public License for more details.
  23.  
  24. You should have received a copy of the GNU General Public License
  25. along with this program; if not, write to the Free Software
  26. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  27. */
  28.  
  29. $c3m_media_tools = new C3M_Media_Tools();
  30. register_activation_hook( __FILE__, array( $c3m_media_tools, 'activate' ) );
  31.  
  32.  
  33. class C3M_Media_Tools {
  34.  
  35. var $media_settings;
  36. var $media_tools;
  37. static $regen;
  38. private $media_tabs_key = 'media_tabs';
  39. private static $thumbnail_support;
  40. private $media_tools_key = 'media_tools';
  41. private $media_settings_key = 'media_options';
  42. private $media_settings_tabs = array();
  43.  
  44.  
  45. function __construct() {
  46. self::$thumbnail_support = current_theme_supports( 'post-thumbnails' ) ? true : add_theme_support( 'post-thumbnails' );
  47. $this->add_image_sizes();
  48. $this->actions();
  49. }
  50.  
  51. /**
  52. * Plugin Activation hook function to check for Minimum PHP and WordPress versions
  53. * @param string $wp Minimum version of WordPress required for this plugin
  54. * @param string $php Minimum version of PHP required for this plugin
  55. */
  56. function activate( $wp = '3.1', $php = '5.2.4' ) {
  57. global $wp_version;
  58. if ( version_compare( PHP_VERSION, $php, '<' ) )
  59. $flag = 'PHP';
  60. elseif
  61. ( version_compare( $wp_version, $wp, '<' ) )
  62. $flag = 'WordPress';
  63. else
  64. return;
  65. $version = 'PHP' == $flag ? $php : $wp;
  66. deactivate_plugins( basename( __FILE__ ) );
  67. wp_die('<p>The <strong>Media Tools</strong> plugin requires'.$flag.' version '.$version.' or greater.</p>','Plugin Activation Error', array( 'response'=>200, 'back_link'=>TRUE ) );
  68. }
  69.  
  70. function actions() {
  71. add_action( 'admin_menu', array ( $this, 'admin_menu' ) );
  72. add_action( 'init', array( $this, 'load_settings' ) );
  73. add_action( 'admin_enqueue_scripts', array ( $this, 'media_tools_js' ) );
  74. add_action( 'wp_ajax_convert-featured', array ( $this, 'ajax_handler' ) );
  75. add_action( 'wp_ajax_process-data', array( $this, 'process_image' ) );
  76. add_action( 'ap_ajax_ajax-done', array( $this, 'ajax_complete') );
  77. add_action( 'admin_init', array( $this, 'register_media_options' ) );
  78. add_action( 'admin_init', array ( $this, 'register_media_tools' ) );
  79. }
  80.  
  81. function load_settings() {
  82. $this->media_tools = (array)get_option( $this->media_tools_key );
  83. $this->media_settings = (array) get_option( $this->media_settings_key );
  84. $this->media_settings = array_merge( array( 'img_handle' => '', 'img_width' => '', 'img_height' => '', 'img_crop' => '' ), $this->media_settings );
  85. $this->media_tools = array_merge( array ( ), $this->media_tools );
  86. }
  87.  
  88. function register_media_tools() {
  89. $this->media_settings_tabs[$this->media_tools_key] = 'Media Tools';
  90. register_setting( $this->media_tools_key, $this->media_tools_key );
  91. }
  92.  
  93. function register_media_options() {
  94. $this->media_settings_tabs[$this->media_settings_key] = 'Media Options';
  95. register_setting( $this->media_settings_key, $this->media_settings_key );
  96. add_settings_section( 'media_options_general', 'Add additional image size', array( $this, 'section_description' ), $this->media_settings_key );
  97. add_settings_field( 'img_handle', 'Image Handle', array( $this, 'field_media_options' ), $this->media_settings_key, 'media_options_general' );
  98. add_settings_field( 'img_width', 'Image Width', array ( $this, 'field_width_options' ), $this->media_settings_key, 'media_options_general' );
  99. add_settings_field( 'img_height', 'Image Height', array ( $this, 'field_height_options' ), $this->media_settings_key, 'media_options_general' );
  100. add_settings_field( 'img_crop', 'Image Crop Factor', array ( $this, 'field_crop_options' ), $this->media_settings_key, 'media_options_general' );
  101. }
  102.  
  103. function section_description() {
  104. echo 'WordPress custom featured image sizes require a handle, height, width, and crop factor';
  105. }
  106. /** @todo Validation function for text input fields */
  107. function field_media_options() { ?>
  108. <input type="text" name="<?php echo $this->media_settings_key; ?>[img_handle]" value=""/><br>
  109. <?php }
  110.  
  111. function field_width_options() { ?>
  112. <input type="text" name="<?php echo $this->media_settings_key; ?>[img_width]" value=""/>
  113. <?php }
  114.  
  115. function field_height_options() { ?>
  116. <input type="text" name="<?php echo $this->media_settings_key; ?>[img_height]" value=""/>
  117. <?php }
  118.  
  119. function field_crop_options() { ?>
  120. <select name="<?php echo $this->media_settings_key; ?>[img_crop]" >
  121. <option value="1"><?php _e( 'Hard Crop' ); ?></option>
  122. <option value="0"><?php _e( 'Soft Crop' ); ?></option>
  123. </select>
  124. <?php }
  125.  
  126. function options_tab( $tab ) {
  127. echo '<form method="post" action="options.php" >';
  128. wp_nonce_field( 'options.php' );
  129. echo '<div style="float:left;width:330px;">';
  130. $this->show_thumb_sizes();
  131. echo '</div>';
  132. echo '<div style="float:left;margin-top:50px;">';
  133. settings_fields( $tab );
  134. do_settings_sections( $tab );
  135. submit_button( 'Add Image Size');
  136. echo '</div>';
  137. echo '</form>';
  138. echo '<div class="clear"></div>';
  139. if ( class_exists( 'RegenerateThumbnails' ) ) {
  140. $regen = new RegenerateThumbnails();
  141. $regen->regenerate_interface();
  142.  
  143. } else {
  144. _e( '<h3>Regenerate Thumbnails</h3>' );
  145. printf( __('<p>Install Regenerate Thumbnails to crop all images that you have uploaded to your blog. This is useful if you\'ve changed any of the thumbnail dimensions above or on the <a href="%s">media settings page</a></p>' ), admin_url( 'options-media.php') );
  146.  
  147. $url = current_user_can( 'install_plugins' ) ? wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=regenerate-thumbnails' ), 'install-plugin_regenerate-thumbnails' ) : 'http://wordpress.org/extend/plugins/regenerate-thumbnails/';
  148. _e( '<a href="'.esc_url( $url ).'" class="button-secondary">Install Regenerate Thumbnails</a>' );
  149. }
  150.  
  151. }
  152.  
  153. function add_image_sizes() {
  154. $ops = (array) get_option( $this->media_settings_key );
  155. if ( ! empty( $ops ) && isset( $ops['img_crop'] ) && isset( $ops['img_handle'] ) && isset( $ops['img_width'] ) && isset( $ops['img_height'] ) ) {
  156. $crop = $ops['img_crop'] == '1' ? true : false;
  157. add_image_size( $ops['img_handle'] , (int) $ops['img_width'], (int) $ops['img_height'], $crop );
  158. }
  159. }
  160.  
  161. function show_thumb_sizes() {
  162. global $_wp_additional_image_sizes; ?>
  163. <h2><?php _e( 'Current Registered Image Sizes' ); ?></h2>
  164. <ul>
  165. <?php foreach( $_wp_additional_image_sizes as $size => $props ) {
  166. $crop = true == $props['crop'] ? 'Hard Crop' : 'Soft Crop';
  167. _e( '<li><h3>'.$size.'</h3>' );
  168. _e( 'Width: '.$props['width'].'<br>' );
  169. _e( 'Height: '.$props['height'].'<br>' );
  170. _e( 'Crop: ' .$crop.'<br>' );
  171. _e( '</li>' );
  172. }
  173. echo '</ul>';
  174. }
  175.  
  176. /**
  177. * Enqueue javascript for media tools admin page
  178. * @param string $hook reference to current admin page
  179. */
  180. function media_tools_js( $hook ) {
  181. if( 'tools_page_media_tabs' != $hook )
  182. return;
  183. wp_enqueue_script( 'media-tools-ajax', plugins_url( 'js/media.tools.ajax.js', __FILE__), array( 'jquery', 'jquery-spin' ), '1.0.1' );
  184. wp_enqueue_script( 'jquery-spin', plugins_url( 'js/spin.js', __FILE__), array('jquery' ) );
  185. wp_enqueue_script( 'jquery-ui-progressbar', plugins_url( 'js/jquery.ui.progressbar.min.js', __FILE__ ), array ( 'jquery-ui-core', 'jquery-ui-widget' ), '1.8.6' );
  186. wp_enqueue_style( 'jquery-ui-redmond', plugins_url( 'js/redmond/jquery-ui-1.7.2.custom.css', __FILE__ ), array (), '1.7.2' );
  187. }
  188.  
  189. function admin_menu() {
  190. add_submenu_page( 'tools.php', 'Media Tools', 'Media Tools', 'manage_options', $this->media_tabs_key, array( $this, 'admin_media_page') );
  191. }
  192.  
  193. function admin_media_page() {
  194. $tab = isset( $_GET['tab'] ) ? $_GET['tab'] : $this->media_tools_key; ?>
  195. <div class="wrap">
  196. <?php $this->menu_tabs( $tab );
  197.  
  198. switch ( $tab ) :
  199. case $this->media_tools_key :
  200. $this->home_tab();
  201. break;
  202. case $this->media_settings_key :
  203. $this->options_tab( $tab );
  204. break;
  205. endswitch; ?>
  206. </div>
  207.  
  208. <?php }
  209.  
  210.  
  211. function menu_tabs() {
  212. $current_tab = isset( $_GET['tab'] ) ? $_GET['tab'] : $this->media_tools_key;
  213. echo '<div id="icon-options-general" class="icon32"><br></div>';
  214. echo '<h2 class="nav-tab-wrapper">';
  215.  
  216. foreach( $this->media_settings_tabs as $tab_key => $tab_caption ) :
  217. $active = $current_tab == $tab_key ? 'nav-tab-active' : '';
  218. echo '<a class="nav-tab '.$active. '" href=?page=' .$this->media_tabs_key. '&tab='.$tab_key. '>' .$tab_caption. '</a>';
  219. endforeach;
  220. echo '</h2>';
  221. }
  222.  
  223. function home_tab() {
  224. global $wpdb;
  225. $title = __( 'WordPress Media Tools' ); ?>
  226.  
  227. <div class="page-description">
  228. <h2><?php echo esc_html( $title ); ?></h2>
  229.  
  230. <p><?php _e( 'WordPress Media Tools are a set of tools to help you manage the media in your posts and pages.<br>' ); ?>
  231. <?php _e( 'You can import external images into the media library, attach media to a post or page, and set images as the featured image.' ); ?></p>
  232.  
  233. </div>
  234. <div>
  235. <div class="set-featured">
  236. <h3><?php _e( 'Set Featured Images' ); ?></h3>
  237. <p><?php _e( 'This tool goes through your posts and sets the first image found as the featured image' ); ?>
  238. <?php _e( 'If the post already has a featured image set it will be skipped.<br>' ); ?>
  239. <?php _e( 'If the first image is from an external source or not attached to the post it will be added to the media library and attached to the post' ); ?></p>
  240. </div>
  241. <div class="convert-media">
  242. <h3><?php _e( 'Import External Images' ); ?></h3>
  243. <p><?php _e( 'This tool goes through your chosen posts or pages and imports external images into the media library' ); ?>
  244. <?php _e( 'The src attribute of any found images are checked against your set uploads dir and will not insert if they match' ); ?>
  245. <?php _e( 'This also changes the img src attribute to reference the new location in your uploads folder' ); ?>
  246. <?php _e( 'You can also choose to make the first image the featured image' ); ?></p>
  247. </div>
  248.  
  249. <h2 id="convert-choose"><?php _e( 'Choose tool to run' ); ?></h2>
  250. <form action="" method="get" id="export-filters">
  251. <p><select id="choose-tool" name="choose-tool">
  252. <option value="set-featured"><?php _e( 'Set Featured Images' ); ?></option>
  253. <option value="import-media"><?php _e( 'Import External Images' ); ?></option>
  254. <option value="convert-import"><?php _e( 'Import External and Set Featured Image' ) ;?></option>
  255. </select></p>
  256.  
  257. <h3 id="convert-title"><?php _e( 'Choose content to run the tool on' ); ?></h3>
  258. <p><label><input type="radio" name="content" value="all" checked="checked"/> <?php _e( 'All content' ); ?></label></p>
  259. <p class="description"><?php _e( 'This will convert the first image from all of your posts, pages, custom posts.' ); ?></p>
  260.  
  261. <p><label><input type="radio" name="content" value="post"/> <?php _e( 'Posts' ); ?></label></p>
  262. <ul id="post-filters" class="export-filters">
  263. <li><label><?php _e( 'Categories:' ); ?></label><?php wp_dropdown_categories( array ( 'show_option_all' => __( 'All' ) ) ); ?></li>
  264. <li><label><?php _e( 'Authors:' ); ?></label><?php $authors = $wpdb->get_col( "SELECT DISTINCT post_author FROM {$wpdb->posts} WHERE post_type = 'post'" );
  265. wp_dropdown_users( array ( 'include' => $authors, 'name' => 'post_author', 'multi' => true, 'show_option_all' => __( 'All' ) ) );?>
  266. </li>
  267. <li><label><?php _e( 'Date range:' ); ?></label>
  268. <select name="post_start_date">
  269. <option value="0"><?php _e( 'Start Date' ); ?></option>
  270. <?php $this->convert_date_options(); ?>
  271. </select>
  272. <select name="post_end_date">
  273. <option value="0"><?php _e( 'End Date' ); ?></option>
  274. <?php $this->convert_date_options(); ?>
  275. </select>
  276. </li>
  277. <li><label><?php _e( 'Status:' ); ?></label>
  278. <select name="post_status">
  279. <option value="0"><?php _e( 'All' ); ?></option>
  280. <?php $post_stati = get_post_stati( array ( 'internal' => false ), 'objects' );
  281. foreach ( $post_stati as $status ) : ?>
  282. <option value="<?php echo esc_attr( $status->name ); ?>"><?php echo esc_html( $status->label ); ?></option>
  283. <?php endforeach; ?>
  284. </select>
  285. </li>
  286. </ul>
  287.  
  288. <p><label><input type="radio" name="content" value="page"/> <?php _e( 'Pages' ); ?></label></p>
  289. <ul id="page-filters" class="export-filters">
  290. <li><label><?php _e( 'Authors:' ); ?></label><?php
  291. $authors = $wpdb->get_col( "SELECT DISTINCT post_author FROM {$wpdb->posts} WHERE post_type = 'page'" );
  292. wp_dropdown_users( array ( 'include' => $authors, 'name' => 'page_author', 'multi' => true, 'show_option_all' => __( 'All' ) ) );?>
  293. </li>
  294. <li><label><?php _e( 'Date range:' ); ?></label>
  295. <select name="page_start_date">
  296. <option value="0"><?php _e( 'Start Date' ); ?></option>
  297. <?php $this->convert_date_options( 'page' ); ?>
  298. </select>
  299. <select name="page_end_date">
  300. <option value="0"><?php _e( 'End Date' ); ?></option>
  301. <?php $this->convert_date_options( 'page' ); ?>
  302. </select>
  303. </li>
  304. <li><label><?php _e( 'Status:' ); ?></label>
  305. <select name="page_status">
  306. <option value="0"><?php _e( 'All' ); ?></option>
  307. <?php foreach ( $post_stati as $status ) : ?>
  308. <option value="<?php echo esc_attr( $status->name ); ?>"><?php echo esc_html( $status->label ); ?></option>
  309. <?php endforeach; ?>
  310. </select>
  311. </li>
  312. </ul>
  313.  
  314. <?php foreach ( get_post_types( array ( '_builtin' => false, 'can_export' => true, 'show_ui' => true ), 'objects' ) as $post_type ) : ?>
  315. <p><label><input type="radio" name="content" value="<?php echo esc_attr( $post_type->name ); ?>"/> <?php echo esc_html( $post_type->label ); ?></label></p>
  316. <?php endforeach; ?>
  317.  
  318. <?php submit_button( __( 'Set Featured Images' ), 'secondary' ); ?>
  319. </form>
  320. <div id="my-message" class="updated fade" style="display:none"></div>
  321. <div id="media-progress" style="position:relative;height:25px; margin-right:100px;">
  322. <div id="media-progress-percent" style="position:absolute;left:50%;top:50%;width:300px;margin-left:-150px;height:25px;margin-top:-9px;font-weight:bold;text-align:center;"></div>
  323. </div>
  324. <div id="featured-ajax-response" style="height:800px; overflow: scroll; padding-left:30px;margin-right:100px; background: #dfdfdf; display: none;"></div>
  325. </div>
  326.  
  327. <?php }
  328.  
  329. /**
  330. * Ajax handler function added to the wp_ajax hook
  331. * @return mixed WP_Error if error encountered | $response is echoed back via ajax on success
  332. */
  333. function ajax_handler() {
  334.  
  335. /** @var object $data The serialized form object */
  336. $data = isset( $_POST['args'] ) ? $_POST['args'] : array();
  337.  
  338. if ( empty( $data ) )
  339. return new WP_Error( 'Error processing the form. Please try again' );
  340.  
  341. $args = array_slice( $data, 1 );
  342.  
  343. if ( 'post' == $args['content'] ) {
  344. if ( $args['cat'] )
  345. $args['category'] = (int)$args['cat'];
  346.  
  347. if ( $args['post_author'] )
  348. $args['author'] = (int)$args['post_author'];
  349.  
  350. if ( $args['post_start_date'] || $args['post_end_date'] ) {
  351. $args['start_date'] = $args['post_start_date'];
  352. $args['end_date'] = $args['post_end_date'];
  353. }
  354.  
  355. if ( $args['post_status'] )
  356. $args['status'] = $args['post_status'];
  357. } elseif ( 'page' == $args['content'] ) {
  358. if ( $args['page_author'] )
  359. $args['author'] = $args['page_author'];
  360.  
  361. if ( $args['page_start_date'] || $args['page_end_date'] ) {
  362. $args['start_date'] = $args['page_start_date'];
  363. $args['end_date'] = $args['page_end_date'];
  364. }
  365.  
  366. if ( $args['page_status'] )
  367. $args['status'] = $args['page_status'];
  368. }
  369. $id_array = array();
  370. $ids = $this->query( $args );
  371. foreach( $ids as $id ) {
  372. $id_array[] = (int)$id;
  373. }
  374.  
  375. die( json_encode( $id_array ) );
  376. }
  377.  
  378. function ajax_complete() {
  379. die( 'Done....');
  380. }
  381.  
  382. function process_image() {
  383. $response = '';
  384. $data[] = '';
  385. $error = 0;
  386. if ( isset( $_POST['ids'] ) )
  387. $ids = $_POST['ids'];
  388.  
  389. $data['choose-tool'] = $_POST['args'];
  390.  
  391. $post = get_post( $ids );
  392. $response .= '<h3><a href="' . esc_url( admin_url( 'post.php?post=' . $post->ID . '&action=edit' ) ) . '" target="_blank">'.get_the_title( $post->ID ) . '</a></h3>';
  393.  
  394. if ( 'import-media' == $data['choose-tool'] ) {
  395. $response .= 'Running import media tool<br>';
  396. $res = $this->extract_multi( $post );
  397. $response .= $res['response'];
  398. $error = $error + (int)$res['error'];
  399. die( sprintf( $response . '<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
  400.  
  401.  
  402. } elseif ( 'convert-import' == $data['choose-tool'] ) {
  403. $response .= 'Running import and set featured image tool<br>';
  404. $res = $this->extract_multi( $post );
  405. $response .= $res['response'];
  406. $error = $error + (int)$res['error'];
  407.  
  408. }
  409. /** If the post already has an attached thumbnail continue with the loop */
  410. if ( has_post_thumbnail( $post->ID ) ) {
  411. $response .= 'Featured image already set <br>';
  412. die( sprintf( $response . '<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
  413. }
  414. /** @var $attachments array of attached images to the post */
  415.  
  416. $attachments = $this->get_attach( $post->ID );
  417.  
  418. if ( ! $attachments ) {
  419. $img = $this->extract_image( $post );
  420. if( empty( $img ) ) {
  421. $response .= 'No images found <br>';
  422. die( sprintf( $response . '<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
  423.  
  424. }
  425.  
  426. /** @var $file string or WP_Error of image attached to the post */
  427. $file = media_sideload_image( $img, (int)$post->ID );
  428. if ( is_wp_error( $file ) ) {
  429. $response .= '<span style="color:red">Upload Error: Could not upload image. Check for malformed img src url</span><br>';
  430. $error++;
  431. } else {
  432.  
  433. $atts = $this->get_attach( $post->ID );
  434. foreach ( $atts as $a ) {
  435. $img = set_post_thumbnail( $post->ID, $a['ID'] );
  436. if ( $img ) {
  437. $thumb = wp_get_attachment_thumb_url( $a['ID'] );
  438. $response .= '<img src="'.esc_url( $thumb ).'" /><br>';
  439. $response .= '<a href="' . wp_nonce_url( get_edit_post_link( $a['ID'], true ) ) . '" >' . get_the_title( $a['ID'] ) . '</a> Set as Featured Image</p><br>';
  440. }
  441. }
  442. unset( $atts );
  443. unset( $a );
  444. }
  445. } else {
  446.  
  447. foreach( $attachments as $a ) {
  448. $img = set_post_thumbnail( $post->ID, $a['ID'] );
  449. if ( $img ) {
  450. $thumb = wp_get_attachment_thumb_url( $a['ID'] );
  451. $response .= '<img src="' . esc_url( $thumb ) . '" /><br>';
  452. $response .= '<a href="' . wp_nonce_url( get_edit_post_link( $a['ID'], true ) ) . '" >' . get_the_title( $a['ID'] ) . '</a> Set as Featured Image</p><br>';
  453. }
  454. }
  455. unset( $attachments );
  456. unset( $a );
  457. }
  458.  
  459. die( sprintf( $response.'<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : 'no' ) );
  460.  
  461.  
  462. }
  463.  
  464.  
  465.  
  466. /**
  467. * Queries for attached images
  468. * @param int $post_id The post id to check if attachments exist
  469. * @return array|bool The 1st attached on success false if no attachments
  470. */
  471. function get_attach( $post_id ) {
  472. return get_children( array (
  473. 'post_parent' => $post_id,
  474. 'post_type' => 'attachment',
  475. 'post_mime_type' => 'image',
  476. 'posts_per_page' => (int)1
  477. ), ARRAY_A );
  478. }
  479.  
  480. /**
  481. * Extracts the first image in the post content
  482. * @param object $post the post object
  483. * @return bool|string false if no images or img src
  484. */
  485. function extract_image( $post ) {
  486. $html = $post->post_content;
  487. if ( stripos( $html, '<img' ) !== false ) {
  488. $regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
  489. preg_match( $regex, $html, $matches );
  490. unset( $regex );
  491. unset( $html );
  492. if ( is_array( $matches ) && ! empty( $matches ) ) {
  493. return $matches[2];
  494.  
  495. } else {
  496. return false;
  497. }
  498. } else {
  499. return false;
  500. }
  501. }
  502.  
  503. /**
  504. * Extracts all images in content adds to media library if external and updates content with new url
  505. * @param object $post The post object
  506. * @return array|bool Post id and images converted on success false if no images found in source
  507. */
  508. function extract_multi( $post ) {
  509. global $wpdb;
  510. $html = $post->post_content;
  511. $path = wp_upload_dir();
  512. $path = $path['baseurl'];
  513. $error = 0;
  514. $response = '';
  515. if ( stripos( $html, '<img' ) !== false ) {
  516.  
  517. $regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
  518. preg_match_all( $regex, $html, $matches );
  519.  
  520. if ( is_array( $matches ) && ! empty( $matches ) ) {
  521. $new = array();
  522. $old = array();
  523. foreach( $matches[2] as $img ) {
  524. /** Compare image source against upload directory to prevent adding same attachment multiple times */
  525.  
  526. if ( stripos( $img, $path ) !== false ) {
  527. $row = $wpdb->query("UPDATE ".$wpdb->prefix."posts SET post_parent = ".$post->ID." WHERE guid = '".$img."' ");
  528. $response .= 'Img already in media library<br>';
  529. continue;
  530. }
  531.  
  532. $tmp = download_url( $img );
  533.  
  534. preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $img, $matches);
  535. $file_array['name'] = basename($matches[0]);
  536. $file_array['tmp_name'] = $tmp;
  537. // If error storing temporarily, unlink
  538. if ( is_wp_error( $tmp ) ) {
  539. @unlink($file_array['tmp_name']);
  540. $file_array['tmp_name'] = '';
  541. continue;
  542. }
  543.  
  544. $id = media_handle_sideload( $file_array, $post->ID );
  545.  
  546. if ( ! is_wp_error( $id ) ) {
  547. $url = wp_get_attachment_url( $id );
  548. $thumb = wp_get_attachment_thumb_url( $id );
  549. array_push( $new, $url );
  550. array_push( $old, $img );
  551.  
  552. $response .= '<p><a href="'. wp_nonce_url( get_edit_post_link( $id, true ) ).'" title="edit-image"><img src="'.esc_url( $thumb ).'" style="max-width:100px;" /></a><br>';
  553. $response .= '<a href="'. wp_nonce_url( get_edit_post_link( $id, true ) ).'" >'.get_the_title( $id ). '</a> Imported and attached</p>';
  554. } else {
  555. $response .= '<span style="color:red">Upload Error: Could not upload image. Check for malformed img src url</span><br>';
  556. $error ++;
  557. }
  558. }
  559. if( !empty( $new ) ) {
  560. $content = str_ireplace( $old, $new, $html );
  561. $post_args = array( 'ID' => $post->ID, 'post_content' => $content, );
  562. if ( !empty( $content ) )
  563. $post_id = wp_update_post( $post_args );
  564. if ( isset( $post_id ) )
  565. $response .= 'Post Content updated for Post: '.esc_html( $post->post_title).'<br>';
  566. return array( 'error' => $error, 'response' => $response );
  567. } else
  568. $response .= 'No external images found for ' . esc_html( $post->post_title ) . '<br>';
  569. return array ( 'error' => $error, 'response' => $response );
  570.  
  571. } else {
  572. $response .= 'Error processing images for '. esc_html( $post->post_title ) .'<br>';
  573. return array ( 'error' => $error, 'response' => $response );
  574. }
  575. } else {
  576. $response .= 'No images found for ' . esc_html( $post->post_title) . '<br>';
  577. return array ( 'error' => $error, 'response' => $response );
  578. }
  579. }
  580.  
  581. /**
  582. * Queries the posts based on the form field data
  583. * The database MySql queries were <del>inspired</del> jacked from the WordPress Export tool
  584. *
  585. * @param array $args The ajax form array formatted for the query
  586. * @return array $post_ids an array of post ids from the query result
  587. */
  588. function query( $args = array() ) {
  589. global $wpdb, $post;
  590.  
  591. $defaults = array( 'content' => 'all', 'author' => false, 'category' => false,
  592. 'start_date' => false, 'end_date' => false, 'status' => false, );
  593. $args = wp_parse_args( $args, $defaults );
  594.  
  595. if ( 'all' != $args['content'] && post_type_exists( $args['content'] ) ) {
  596. $ptype = get_post_type_object( $args['content'] );
  597. if ( ! $ptype->can_export )
  598. $args['content'] = 'post';
  599.  
  600. $where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['content'] );
  601. } else {
  602. $post_types = get_post_types();
  603. $post_types = array_diff( $post_types, array( 'attachment', 'revision', 'nav_menu_item' ) );
  604. $esses = array_fill( 0, count($post_types), '%s' );
  605. $where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types );
  606. }
  607.  
  608. if ( $args['status'] && ( 'post' == $args['content'] || 'page' == $args['content'] ) )
  609. $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] );
  610. else
  611. $where .= " AND {$wpdb->posts}.post_status != 'auto-draft'";
  612.  
  613. $join = '';
  614. if ( $args['category'] && 'post' == $args['content'] ) {
  615. if ( $term = term_exists( $args['category'], 'category' ) ) {
  616. $join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
  617. $where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] );
  618. }
  619. }
  620.  
  621. if ( 'post' == $args['content'] || 'page' == $args['content'] ) {
  622. if ( $args['author'] )
  623. $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $args['author'] );
  624.  
  625. if ( $args['start_date'] )
  626. $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", date( 'Y-m-d', strtotime($args['start_date']) ) );
  627.  
  628. if ( $args['end_date'] )
  629. $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", date( 'Y-m-d', strtotime('+1 month', strtotime($args['end_date'])) ) );
  630. }
  631.  
  632. $post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" );
  633.  
  634. return $post_ids;
  635. }
  636.  
  637. /**
  638. * Converts the data ranges to a string for the query
  639. * @param string $post_type
  640. */
  641. function convert_date_options( $post_type = 'post' ) {
  642. global $wpdb, $wp_locale;
  643.  
  644. $months = $wpdb->get_results( $wpdb->prepare( "
  645. SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
  646. FROM $wpdb->posts
  647. WHERE post_type = %s AND post_status != 'auto-draft'
  648. ORDER BY post_date DESC
  649. ", $post_type
  650. )
  651. );
  652.  
  653. $month_count = count( $months );
  654. if ( ! $month_count || ( 1 == $month_count && 0 == $months[0]->month ) )
  655. return;
  656.  
  657. foreach ( $months as $date ) {
  658. if ( 0 == $date->year )
  659. continue;
  660.  
  661. $month = zeroise( $date->month, 2 );
  662. echo '<option value="' . $date->year . '-' . $month . '">' . $wp_locale->get_month( $month ) . ' ' . $date->year . '</option>';
  663. }
  664. }
  665.  
  666. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement