wp-print-friendly.php 31.9 KB
Newer Older
1 2 3 4 5
<?php
/*
Plugin Name: WP Print Friendly
Plugin URI: http://www.thinkoomph.com/plugins-modules/wp-print-friendly/
Description: Extends WordPress' template system to support printer-friendly templates. Works with permalink structures to support nice URLs.
6
Author: Erick Hitter, Steven K Word & Oomph, Inc.
7
Version: 0.6
8
Author URI: http://www.thinkoomph.com/
Erick Hitter's avatar
Erick Hitter committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23 24 25
*/

class wp_print_friendly {
26 27 28 29 30 31 32 33
	/**
	 * Singleton
	 */
	private static $__instance = null;

	/**
	 * Class variables
	 */
34
	var $query_var = 'print';
35

36
	var $ns = 'wp_print_friendly';
37

38 39 40 41 42 43 44 45 46 47 48 49
	var $settings_key = 'wpf';
	var $settings_defaults = array(
		'auto' => false,
		'placement' => 'below',
		'post_types' => array( 'post', 'page' ),
		'print_text' => 'Print this entry',
		'print_text_page' => 'Print this page',
		'css_class' => 'print_link',
		'link_target' => 'same',
		'endnotes' => true,
		'endnotes_label' => 'Endnotes:'
	);
50

51
	var $notice_key = 'wpf_admin_notice_dismissed';
52

Erick Hitter's avatar
Erick Hitter committed
53
	/**
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
	 * Silence is golden!
	 */
	private function __construct() {}

	/**
	 * Implement singleton
	 *
	 * @uses self::setup
	 * @return self
	 */
	public static function get_instance() {
		if ( ! is_a( self::$__instance, __CLASS__ ) ) {
			self::$__instance = new self;

			self::$__instance->setup();
		}

		return self::$__instance;
	}

	/**
	 * Register deactivation hook and tie balance of plugin hooks to `plugins_loaded`.
Erick Hitter's avatar
Erick Hitter committed
76
	 *
Erick Hitter's avatar
Erick Hitter committed
77 78
	 * @uses register_deactivation_hook
	 * @uses add_filter
79 80
	 * @return null
	 */
81
	private function setup() {
82 83 84
		register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
		add_action( 'plugins_loaded', array( $this, 'action_plugins_loaded' ) );
	}
85

Erick Hitter's avatar
Erick Hitter committed
86
	/**
87
	 * Clean up after plugin deactivation.
Erick Hitter's avatar
Erick Hitter committed
88
	 *
Erick Hitter's avatar
Erick Hitter committed
89 90
	 * @uses flush_rewrite_rules
	 * @uses delete_option
91 92 93
	 * @action register_deactivation_hook
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
94
	public function deactivation_hook() {
95
		flush_rewrite_rules();
96

97 98 99
		delete_option( $this->settings_key );
		delete_option( $this->notice_key );
	}
100

Erick Hitter's avatar
Erick Hitter committed
101
	/**
102
	 * Register actions and filters.
Erick Hitter's avatar
Erick Hitter committed
103
	 *
Erick Hitter's avatar
Erick Hitter committed
104 105 106
	 * @uses add_action
	 * @uses add_filter
	 * @uses get_option
107 108 109
	 * @action plugins_loaded
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
110
	public function action_plugins_loaded() {
111 112 113 114 115 116
		add_action( 'init', array( $this, 'action_init' ), 20 );
		add_action( 'admin_init', array( $this, 'action_admin_init' ) );
		add_action( 'admin_menu', array( $this, 'action_admin_menu' ) );
		add_filter( 'request', array( $this, 'filter_request' ) );
		add_action( 'pre_get_posts', array( $this, 'action_pre_get_posts' ) );
		add_filter( 'template_include', array( $this, 'filter_template_include' ) );
Erick Hitter's avatar
Erick Hitter committed
117
		add_filter( 'redirect_canonical', array( $this, 'filter_redirect_canonical' ) );
118 119 120 121
		add_filter( 'body_class', array( $this, 'filter_body_class' ) );
		add_filter( 'the_content', array( $this, 'filter_the_content' ), 0 );
		add_filter( 'the_content', array( $this, 'filter_the_content_auto' ) );
		add_filter( 'the_content', array( $this, 'filter_the_content_late' ), 99 );
122

Erick Hitter's avatar
Erick Hitter committed
123
		if ( ! get_option( $this->notice_key ) )
124 125
			add_action( 'admin_notices', array( $this, 'action_admin_notices_activation' ) );
	}
126

Erick Hitter's avatar
Erick Hitter committed
127
	/**
128
	 * Add print endpoint and rewrite rules for term taxonomy archives
Erick Hitter's avatar
Erick Hitter committed
129
	 *
Erick Hitter's avatar
Erick Hitter committed
130 131 132 133 134
	 * @global $wp_rewrite
	 * @uses add_rewrite_endpoint
	 * @uses get_taxonomies
	 * @uses add_rewrite_rule
	 * @uses trailingslashit
135 136 137
	 * @action init
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
138
	public function action_init() {
139
		add_rewrite_endpoint( $this->query_var, EP_ALL );
140

141
		global $wp_rewrite;
142 143

		//Taxonomies, since they aren't covered by add_rewrite_endpoint
Erick Hitter's avatar
Erick Hitter committed
144
		if ( $wp_rewrite->permalink_structure ) {
145
			$taxonomies = get_taxonomies( array(), 'objects' );
Erick Hitter's avatar
Erick Hitter committed
146 147
			foreach ( $taxonomies as $taxonomy => $args ) {
				if ( $args->rewrite == false || 'post_format' == $taxonomy )
148
					continue;
149

150
				$taxonomy_slug = '';
Erick Hitter's avatar
Erick Hitter committed
151
				if ( $args->rewrite[ 'with_front' ] && $wp_rewrite->front != '/' ) $taxonomy_slug .= $wp_rewrite->front;
152
				$taxonomy_slug .= $args->rewrite[ 'slug' ];
153

154
				$query_var = $args->query_var ? $args->query_var : 'taxonomy=' . $taxonomy . '&term';
155 156

				add_rewrite_rule( $taxonomy_slug . '/(.+)/' . $this->query_var . '(/([0-9]*))?/?$', $wp_rewrite->index . '?' . $query_var . '=$matches[1]&' . $this->query_var . '=$matches[3]', 'top' );
157 158
			}
		}
159 160 161

		//Extra rules needed if verbose page rules are requested
		if ( $wp_rewrite->use_verbose_page_rules ) {
162
			//Build regex
163 164 165 166
			$regex = substr( str_replace( $wp_rewrite->rewritecode, $wp_rewrite->rewritereplace, $wp_rewrite->permalink_structure ), 1 );
			$regex = trailingslashit( $regex );
			$regex .= $this->query_var . '(/([0-9]*))?/?$';

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
			//Build corresponding query string
			$query = substr( str_replace( $wp_rewrite->rewritecode, $wp_rewrite->queryreplace, $wp_rewrite->permalink_structure ), 1 );
			$query = explode( '/', $query );
			$query = array_filter( $query );

			$i = 1;
			foreach ( $query as $key => $qv ) {
				$query[ $key ] .= '$matches[' . $i . ']';
				$i++;
			}

			$query[] = $this->query_var . '=$matches[' . ( $i + 1 ) . ']';

			$query = implode( '&', $query );

			//Add rule
			add_rewrite_rule( $regex, $wp_rewrite->index . '?' . $query, 'top' );
184
		}
185
	}
186

Erick Hitter's avatar
Erick Hitter committed
187
	/**
188
	 * Register plugin option and disable rewrite rule flush warning.
Erick Hitter's avatar
Erick Hitter committed
189
	 *
Erick Hitter's avatar
Erick Hitter committed
190 191
	 * @uses register_setting
	 * @uses update_option
192 193 194
	 * @action admin_init
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
195
	public function action_admin_init() {
196
		register_setting( $this->settings_key, $this->settings_key, array( $this, 'admin_options_validate' ) );
197

Erick Hitter's avatar
Erick Hitter committed
198
		if ( isset( $_GET[ $this->notice_key ] ) )
199 200
			update_option( $this->notice_key, 1 );
	}
201

Erick Hitter's avatar
Erick Hitter committed
202
	/**
203
	 * Determine if print template is being requested.
Erick Hitter's avatar
Erick Hitter committed
204
	 *
205 206
	 * If WordPress determined this request is a 404, do nothing and let the main theme handle things.
	 *
207
	 * @global $wp_query
208
	 * @uses is_404
209 210
	 * @return bool
	 */
Erick Hitter's avatar
Erick Hitter committed
211
	public function is_print() {
212
		global $wp_query;
213
		return is_array( $wp_query->query ) && array_key_exists( $this->query_var, $wp_query->query ) && ! is_404();
214
	}
215

Erick Hitter's avatar
Erick Hitter committed
216
	/**
217 218
	 * Select appropriate template based on post type and available templates.
	 * Returns an array with name and path keys for available template or false if no template is found.
Erick Hitter's avatar
Erick Hitter committed
219
	 *
Erick Hitter's avatar
Erick Hitter committed
220 221 222 223
	 * @uses get_queried_object
	 * @uses is_home
	 * @uses is_front_page
	 * @uses locate_template
224 225
	 * @return array or false
	 */
Erick Hitter's avatar
Erick Hitter committed
226
	public function template_chooser() {
227 228
		//Get queried object to check post type
		$queried_object = get_queried_object();
229

230 231
		//Get plugin path
		$pluginpath = dirname( __FILE__ );
232

Erick Hitter's avatar
Erick Hitter committed
233
		if ( ( is_home() || is_front_page() ) && ( '' !== ( $path = locate_template( 'wpf-home.php', false ) ) ) ) {
234 235 236 237
			$template = array(
				'name' => 'wpf-home',
				'path' => $path
			);
238
		} elseif (
239 240 241
			is_object( $queried_object ) &&
			property_exists( $queried_object, 'taxonomy' ) &&
			property_exists( $queried_object, 'slug' ) &&
242
			( '' !== ( $path = locate_template( array( 'wpf-' . $queried_object->taxonomy . '-' . $queried_object->slug . '.php', 'wpf-' . $queried_object->taxonomy . '.php' ), false ) ) )
243
		) {
244 245 246 247
			$template = array(
				'name' => 'wpf-' . $queried_object->taxonomy,
				'path' => $path
			);
248
		} elseif (
249 250 251 252
			is_object( $queried_object ) &&
			property_exists( $queried_object, 'post_type' ) &&
			property_exists( $queried_object, 'post_name' ) &&
			( '' !== ( $path = locate_template( array( 'wpf-' . $queried_object->post_type . '-' . $queried_object->post_name . '.php', 'wpf-' . $queried_object->post_type . '.php' ), false ) ) )
253
		) {
254 255 256 257
			$template = array(
				'name' => 'wpf-' . $queried_object->post_type,
				'path' => $path
			);
258
		} elseif (
259 260 261
			is_object( $queried_object ) &&
			property_exists( $queried_object, 'post_name' ) &&
			( '' !== ( $path = locate_template( 'wpf-' . $queried_object->post_name . '.php', false ) ) )
262
		) {
263 264 265 266
			$template = array(
				'name' => 'wpf-' . $queried_object->post_name,
				'path' => $path
			);
267
		} elseif ( '' !== ( $path = locate_template( 'wpf.php', false ) ) ) {
268 269 270 271
			$template = array(
				'name' => 'wpf-default',
				'path' => $path
			);
272
		} elseif ( file_exists( $pluginpath . '/default-template.php' ) ) {
273 274 275 276
			$template = array(
				'name' => 'wpf-plugin-default',
				'path' => $pluginpath . '/default-template.php'
			);
277
		}
278

279 280
		return isset( $template ) ? $template : false;
	}
281

Erick Hitter's avatar
Erick Hitter committed
282 283 284
	/**
	 * Detect request for print stylesheet on the homepage and reset query variables.
	 *
285 286 287 288
	 * @param array $qv
	 * @filter request
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
289 290
	public function filter_request( $qv ) {
		if ( array_key_exists( 'pagename', $qv ) && $qv[ 'pagename' ] == $this->query_var ) {
291 292 293 294
			$qv[ $this->query_var ] = '';
			unset( $qv[ 'page' ] );
			unset( $qv[ 'pagename' ] );
		}
295

Erick Hitter's avatar
Erick Hitter committed
296
		if ( array_key_exists( $this->query_var, $qv ) && is_numeric( $qv[ $this->query_var ] ) )
297
			$qv[ 'page' ] = intval( $qv[ $this->query_var ] );
298

299 300
		return $qv;
	}
301

Erick Hitter's avatar
Erick Hitter committed
302
	/**
303
	 * Filter query when request to print specific page is made.
Erick Hitter's avatar
Erick Hitter committed
304
	 *
305 306 307 308
	 * @param object $query
	 * @action pre_get_posts
	 * @return object
	 */
Erick Hitter's avatar
Erick Hitter committed
309 310
	public function action_pre_get_posts( $query ) {
		if ( array_key_exists( $this->query_var, $query->query_vars ) && ! empty( $query->query_vars[ $this->query_var ] ) ) {
311
			$qv = explode( '/', $query->query_vars[ $this->query_var ] );
312

Erick Hitter's avatar
Erick Hitter committed
313
			if ( array_key_exists( 1, $qv ) && is_numeric( $qv[ 1 ] ) )
314 315
				$query->query_vars[ 'page' ] = (int)$qv[ 1 ];
		}
316

317 318
		return $query;
	}
319

Erick Hitter's avatar
Erick Hitter committed
320
	/**
321
	 * Filter template include to return print template if requested.
Erick Hitter's avatar
Erick Hitter committed
322
	 *
323 324 325 326
	 * @param string $template
	 * @filter template_include
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
327
	public function filter_template_include( $template ) {
328
		if ( $this->is_print() && ( $print_template = $this->template_chooser() ) )
329
			$template = $print_template[ 'path' ];
330

331 332
		return $template;
	}
333

Erick Hitter's avatar
Erick Hitter committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
	/**
	 * Prevent canonical redirect if print URL is requested.
	 *
	 * @param string $url
	 * @uses this::is_print
	 * @filter redirect_canonical
	 * @return string or false
	 */
	public function filter_redirect_canonical( $url ) {
		if ( $this->is_print() )
			$url = false;

		return $url;
	}

	/**
350
	 * Filter body classes to include references to print template.
Erick Hitter's avatar
Erick Hitter committed
351
	 *
352 353 354 355
	 * @param array $classes
	 * @filter body_class
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
356 357 358
	public function filter_body_class( $classes ) {
		if ( $this->is_print() && ( $print_template = $this->template_chooser() ) ) {
			if ( $print_template[ 'name' ] == 'default' )
359 360 361 362
				$classes[] = 'wpf';
			else
				$classes[] = $print_template[ 'name' ];
		}
363

364 365
		return $classes;
	}
366

Erick Hitter's avatar
Erick Hitter committed
367
	/**
368
	 * Filter post content to support printing entire post on one page.
Erick Hitter's avatar
Erick Hitter committed
369
	 *
370
	 * @param string $content
371
	 * @uses post_password_required
372 373 374 375
	 * @uses get_query_var
	 * @filter the_content
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
376
	public function filter_the_content( $content ) {
377
		if ( $this->is_print() && ! post_password_required() ) {
378
			$print = get_query_var( $this->query_var );
379

Erick Hitter's avatar
Erick Hitter committed
380
			if ( $print == 'all' || $print == '/all' || empty( $print ) ) {
381
				global $post;
382

383 384 385 386 387 388 389
				$content = $post->post_content;
				$content = str_replace("\n<!--nextpage-->\n", "\n\n", $content);
				$content = str_replace("\n<!--nextpage-->", "\n", $content);
				$content = str_replace("<!--nextpage-->\n", "\n", $content);
				$content = str_replace("<!--nextpage-->", ' ', $content);
			}
		}
390

391 392
		return $content;
	}
393

Erick Hitter's avatar
Erick Hitter committed
394 395 396
	/**
	 * Filter the content if automatic inclusion is selected.
	 *
Erick Hitter's avatar
Erick Hitter committed
397
	 * @global $post
398
	 * @param string $content
Erick Hitter's avatar
Erick Hitter committed
399 400 401 402
	 * @uses this::get_options
	 * @uses this::print_url
	 * @uses get_query_var
	 * @uses apply_filters
403 404 405
	 * @filter the_content
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
406
	public function filter_the_content_auto( $content ) {
407
		$options = $this->get_options();
408

409
		global $post;
410

Erick Hitter's avatar
Erick Hitter committed
411
		if ( is_array( $options ) && array_key_exists( 'auto', $options ) && $options[ 'auto' ] == true && in_array( $post->post_type, $options[ 'post_types' ] ) && ! $this->is_print() ) {
412
			extract( $options );
413

414 415
			//Basic URL
			$print_url = $this->print_url();
416

417
			//Page URL, if necessary
Erick Hitter's avatar
Erick Hitter committed
418
			if ( ! empty( $print_text_page ) && strpos( $post->post_content, '<!--nextpage-->' ) !== false ) {
419 420
				$page = get_query_var( 'page' );
				$page = $page ? $page : 1;
421

422 423
				$print_url_page = $this->print_url( false, $page );
			}
424

425 426
			//Build link(s)
			$link = '<p class="wpf_wrapper"><a class="' . $css_class . '" href="' . $print_url . '"' . ( $link_target == 'new' ? ' target="_blank"' : '' ) . '>' . $print_text . '</a>';
427

Erick Hitter's avatar
Erick Hitter committed
428
			if ( isset( $print_url_page ) ) {
429 430 431
				$link .= ' | ';
				$link .= '<a class="' . $css_class . ' ' . $css_class . '_cur" href="' . $print_url_page . '"' . ( $link_target == 'new' ? ' target="_blank"' : '' ) . '>' . $print_text_page . '</a>';
			}
432

433
			$link .= '</p><!-- .wpf_wrapper -->';
434

435
			//Place link(s)
Erick Hitter's avatar
Erick Hitter committed
436
			if ( $placement == 'above' )
437
				$content = $link . $content;
Erick Hitter's avatar
Erick Hitter committed
438
			elseif ( $placement == 'below' )
439
				$content = $content . $link;
Erick Hitter's avatar
Erick Hitter committed
440
			elseif ( $placement == 'both' )
441 442
				$content = $link . $content . $link;
		}
443

444 445
		return $content;
	}
446

Erick Hitter's avatar
Erick Hitter committed
447 448 449
	/**
	 * Convert links to endnotes if desired.
	 *
450
	 * @param string $content
451 452 453
	 * @uses this::is_print
	 * @uses post_password_required
	 * @uses this::get_options
454 455 456
	 * @filter the_content
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
457
	public function filter_the_content_late( $content ) {
458
		if ( $this->is_print() && ! post_password_required() ) {
459
			global $post;
460

461
			$options = $this->get_options();
462

463
			//Endnotes
Erick Hitter's avatar
Erick Hitter committed
464
			if ( $options[ 'endnotes' ] ) {
465 466
				$links = array();
				$i = 1;
467

468 469
				//Build array of links
				preg_match_all( '#<a href=(["\'{1}])([^"\']+)(["\'{1}])([^>]*)>(.*?)</a>#i', $content, $matches );
470

Erick Hitter's avatar
Erick Hitter committed
471
				if (
472
					isset( $matches ) && is_array( $matches ) &&
Erick Hitter's avatar
Erick Hitter committed
473 474 475
					array_key_exists( 0, $matches ) && ! empty( $matches[ 0 ] ) &&
					array_key_exists( 2, $matches ) && ! empty( $matches[ 2 ] ) &&
					array_key_exists( 5, $matches ) && ! empty( $matches[ 5 ] )
476 477 478
				) {
					//Format matches for replacement in content
					$replacements = array();
Erick Hitter's avatar
Erick Hitter committed
479
					foreach ( $matches[ 0 ] as $key => $match ) {
480 481 482 483 484
						$replacements[ $match ] = array(
							'url' => $matches[ 2 ][ $key ],
							'title' => $matches[ 5 ][ $key ]
						);
					}
485

486
					//Replace links with endnote markers
Erick Hitter's avatar
Erick Hitter committed
487
					foreach ( $replacements as $match => $args ) {
488 489 490 491
						$content = str_replace( $match, $args[ 'title' ] . '[' . $i . ']', $content );
						$links[ $i ] = $args;
						$i++;
					}
492

493 494 495 496
					//Output endnotes
					$endnotes = '<div class="wpf-endnotes">';
					$endnotes .= '<strong>' . $options[ 'endnotes_label' ] . '</strong>';
					$endnotes .= '<ol>';
Erick Hitter's avatar
Erick Hitter committed
497
					foreach ( $links as $link ) {
498 499 500 501 502
						$endnotes .= '<li>';
						$endnotes .=  preg_replace( '#<img(.*)>#', '[Image]', $link[ 'title' ] ) . ': ' . esc_url( $link[ 'url' ] );
						$endnotes .= '</li>';
					}
					$endnotes .= '</ol></div><!-- .wpf-endnotes -->';
503

504 505 506 507
					$content .= $endnotes;
				}
			}
		}
508

509 510
		return $content;
	}
511

Erick Hitter's avatar
Erick Hitter committed
512 513 514
	/**
	 * Generate URL for post's printer-friendly format.
	 *
Erick Hitter's avatar
Erick Hitter committed
515 516
	 * @global $post
	 * @global $wp_rewrite
517 518
	 * @param int $post_id
	 * @param int $page
Erick Hitter's avatar
Erick Hitter committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
	 * @uses is_view_all
	 * @uses is_home
	 * @uses is_front_page
	 * @uses home_url
	 * @uses get_permalink
	 * @uses is_category
	 * @uses get_category_link
	 * @uses is_tag
	 * @uses get_tag_link
	 * @uses is_date
	 * @uses get_query_var
	 * @uses get_day_link
	 * @uses get_month_link
	 * @uses get_year_link
	 * @uses is_tax
	 * @uses get_queried_object
	 * @uses get_term_link
	 * @uses path_join
	 * @uses trailingslashit
	 * @uses add_query_arg
539 540
	 * @return string or bool
	 */
Erick Hitter's avatar
Erick Hitter committed
541 542
	public function print_url( $post_id = false, $page = false ) {
		if ( $page === true )
543
			return false;
544

Erick Hitter's avatar
Erick Hitter committed
545
		if ( function_exists( 'is_view_all' ) && is_view_all() )
546
			$page = false;
547

548
		$link = false;
549

550
		//Get link base specific to page type being viewed
Erick Hitter's avatar
Erick Hitter committed
551 552
		if ( is_singular() || in_the_loop() ) {
			if ( $post_id == false ) {
553 554 555
				global $post;
				$post_id = $post->ID;
			}
556

Erick Hitter's avatar
Erick Hitter committed
557
			if ( ! $post_id )
558
				return false;
559

560 561
			$link = get_permalink( $post_id );
		}
Erick Hitter's avatar
Erick Hitter committed
562
		elseif ( is_home() || is_front_page() )
563
			$link = home_url( '/' );
Erick Hitter's avatar
Erick Hitter committed
564
		elseif ( is_category() )
565
			$link = get_category_link( get_query_var( 'cat' ) );
Erick Hitter's avatar
Erick Hitter committed
566
		elseif ( is_tag() )
567 568
			$link = get_tag_link( get_query_var( 'tag_id' ) );
		/* DISABLED FOR NOW AS PRINTING OF DATE-BASED ARCHIVES DOESN'T WORK YET
Erick Hitter's avatar
Erick Hitter committed
569
		elseif ( is_date() ) {
570 571 572
			$year = get_query_var( 'year' );
			$monthnum = get_query_var( 'monthnum' );
			$day = get_query_var( 'day' );
573

Erick Hitter's avatar
Erick Hitter committed
574
			if ( $day )
575
				$link = get_day_link( $year, $monthnum, $day );
Erick Hitter's avatar
Erick Hitter committed
576
			elseif ( $monthnum )
577 578 579 580
				$link = get_month_link( $year, $monthnum );
			else
				$link = get_year_link( $year );
		}*/
Erick Hitter's avatar
Erick Hitter committed
581
		elseif ( is_tax() ) {
582
			$queried_object = get_queried_object();
583

Erick Hitter's avatar
Erick Hitter committed
584
			if ( is_object( $queried_object ) && property_exists( $queried_object, 'taxonomy' ) && property_exists( $queried_object, 'term_id' ) )
585 586
				$link = get_term_link( (int)$queried_object->term_id, $queried_object->taxonomy );
		}
587

588
		//If link base is set, build link
Erick Hitter's avatar
Erick Hitter committed
589
		if ( $link !== false ) {
590
			global $wp_rewrite;
591

592
			$page = intval( $page );
593

Erick Hitter's avatar
Erick Hitter committed
594
			if ( $wp_rewrite->using_permalinks() ) {
595
				$link = path_join( $link, $this->query_var );
596

Erick Hitter's avatar
Erick Hitter committed
597
				if ( $page )
598
					$link = path_join( $link, intval( $page ) );
599

Erick Hitter's avatar
Erick Hitter committed
600
				if ( $wp_rewrite->use_trailing_slashes )
601 602 603 604
					$link = trailingslashit( $link );
			}
			else {
				$link = add_query_arg( $this->query_var, is_numeric( $page ) ? intval( $page ) : 'all', $link );
605

Erick Hitter's avatar
Erick Hitter committed
606
				if ( $page )
607 608 609
					$link = add_query_arg( 'page', is_numeric( $page ) ? intval( $page ) : 'all', $link );
			}
		}
610

611 612
		return $link;
	}
613

Erick Hitter's avatar
Erick Hitter committed
614 615 616
	/**
	 * Add menu item for options page.
	 *
617 618 619 620
	 * @uses add_options_page
	 * @action admin_menu
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
621
	public function action_admin_menu() {
622 623
		add_options_page( 'WP Print Friendly Options', 'WP Print Friendly', 'manage_options', $this->ns, array( $this, 'admin_options' ) );
	}
624

Erick Hitter's avatar
Erick Hitter committed
625 626 627
	/**
	 * Render options page.
	 *
Erick Hitter's avatar
Erick Hitter committed
628 629 630 631 632
	 * @uses settings_fields
	 * @uses this::get_options
	 * @uses _e
	 * @uses checked
	 * @uses esc_attr
633 634
	 * @return html
	 */
Erick Hitter's avatar
Erick Hitter committed
635
	public function admin_options() {
636 637 638
	?>
		<div class="wrap">
			<h2>WP Print Friendly</h2>
639

640 641 642 643
			<form action="options.php" method="post">
				<?php
					settings_fields( $this->settings_key );
					$options = $this->get_options();
644

645 646
					$post_types = $this->post_types_array();
				?>
647

648
				<h3>Display Options</h3>
649

650 651
				<table class="form-table">
					<tr>
Erick Hitter's avatar
Erick Hitter committed
652
						<th scope="row"><?php _e( 'Automatically add print links based on settings below?', 'wp_print_friendly' ); ?></th>
653
						<td>
Erick Hitter's avatar
Erick Hitter committed
654 655
							<input type="radio" name="<?php echo esc_attr( $this->settings_key ); ?>[auto]" id="auto-true" value="1"<?php checked( $options[ 'auto' ], true, true ); ?> /> <label for="auto-true"><?php _e( 'Yes', 'wp_print_friendly' ); ?></label><br />
							<input type="radio" name="<?php echo esc_attr( $this->settings_key ); ?>[auto]" id="auto-false" value="0"<?php checked( $options[ 'auto' ], false, true ); ?> /> <label for="auto-false"><?php _e( 'No', 'wp_print_friendly' ); ?></label>
656 657 658
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
659
						<th scope="row"><?php _e( 'Automatically place link:', 'wp_print_friendly' ); ?></th>
660
						<td>
Erick Hitter's avatar
Erick Hitter committed
661 662 663
							<input type="radio" name="<?php echo esc_attr( $this->settings_key ); ?>[placement]" id="placement-above" value="above"<?php checked( $options[ 'placement' ], 'above', true ); ?> /> <label for="placement-above"><?php _e( 'Above content', 'wp_print_friendly' ); ?></label><br />
							<input type="radio" name="<?php echo esc_attr( $this->settings_key ); ?>[placement]" id="placement-below" value="below"<?php checked( $options[ 'placement' ], 'below', true ); ?> /> <label for="placement-below"><?php _e( 'Below content', 'wp_print_friendly' ); ?></label><br />
							<input type="radio" name="<?php echo esc_attr( $this->settings_key ); ?>[placement]" id="placement-both" value="both"<?php checked( $options[ 'placement' ], 'both', true ); ?> /> <label for="placement-both"><?php _e( 'Above and below content', 'wp_print_friendly' ); ?></label>
664 665 666
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
667
						<th scope="row"><?php _e( 'Display automatically on:', 'wp_print_friendly' ); ?></th>
668
						<td>
Erick Hitter's avatar
Erick Hitter committed
669 670
							<?php foreach ( $post_types as $post_type ): ?>
								<input type="checkbox" name="<?php echo esc_attr( $this->settings_key ); ?>[post_types][]" id="pt-<?php echo $post_type->name; ?>" value="<?php echo $post_type->name; ?>"<?php if ( in_array( $post_type->name, $options[ 'post_types' ] ) ) echo ' checked="checked"'; ?> /> <label for="pt-<?php echo $post_type->name; ?>"><?php echo $post_type->labels->name; ?></label><br />
671 672 673 674
							<?php endforeach; ?>
						</td>
					</tr>
				</table>
675

676
				<h3>Link Options</h3>
677

678 679
				<table class="form-table">
					<tr>
Erick Hitter's avatar
Erick Hitter committed
680
						<th scope="row"><?php _e( 'Text for link to print entire item:', 'wp_print_friendly' ); ?></th>
681
						<td>
682
							<input type="text" name="<?php echo esc_attr( $this->settings_key ); ?>[print_text]" id="print_text" value="<?php echo esc_attr( $options[ 'print_text' ] ); ?>" style="width: 40%;" />
683 684 685
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
686
						<th scope="row"><?php _e( 'Text for link to print current page:', 'wp_print_friendly' ); ?></th>
687
						<td>
688 689
							<input type="text" name="<?php echo esc_attr( $this->settings_key ); ?>[print_text_page]" id="print_text_page" value="<?php echo esc_attr( $options[ 'print_text_page' ] ); ?>" style="width: 40%;" />

Erick Hitter's avatar
Erick Hitter committed
690 691
							<p class="description"><?php _e( 'If viewing a multipage post (set by using the &lt;!--nextpage--&gt; tag), the text above is used for a link to print just the current page.', 'wp_print_friendly' ); ?></p>
							<p class="description"><?php _e( '<strong>To hide this link,</strong> clear the field\'s contents.', 'wp_print_friendly' ); ?></p>
692 693 694
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
695
						<th scope="row"><?php _e( 'CSS for print links:', 'wp_print_friendly' ); ?></th>
696
						<td>
697 698
							<input type="text" name="<?php echo esc_attr( $this->settings_key ); ?>[css_class]" id="css_class" value="<?php echo esc_attr( $options[ 'css_class' ] ); ?>" style="width: 40%;" />

Erick Hitter's avatar
Erick Hitter committed
699 700
							<p class="description"><?php _e( 'For page-specific print links, a second class, created by appending <strong>_cur</strong> to the above text, is added to each link.', 'wp_print_friendly' ); ?></p>
							<p class="description"><?php _e( 'Be aware that Internet Explorer will only interpret the first two CSS classes, so if multiple classes are entered above, the page-specific class may not be available in IE.', 'wp_print_friendly' ); ?></p>
701 702 703
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
704
						<th scope="row"><?php _e( 'Open print-friendly views:', 'wp_print_friendly' ); ?></th>
705
						<td>
Erick Hitter's avatar
Erick Hitter committed
706 707
							<input type="radio" name="<?php echo esc_attr( $this->settings_key ); ?>[link_target]" id="target-same" value="same"<?php checked( $options[ 'link_target' ], 'same', true ); ?> /> <label for="target-same"><?php _e( 'In the same window', 'wp_print_friendly' ); ?></label><br />
							<input type="radio" name="<?php echo esc_attr( $this->settings_key ); ?>[link_target]" id="target-new" value="new"<?php checked( $options[ 'link_target' ], 'new', true ); ?> /> <label for="target-new"><?php _e( 'In a new window', 'wp_print_friendly' ); ?></label>
708 709 710
						</td>
					</tr>
				</table>
711

712
				<h3>Endnote Options</h3>
713

714 715
				<table class="form-table">
					<tr>
Erick Hitter's avatar
Erick Hitter committed
716
						<th scope="row"><?php _e( 'Include endnotes for links found in content?', 'wp_print_friendly' ); ?></th>
717
						<td>
Erick Hitter's avatar
Erick Hitter committed
718
							<input type="checkbox" name="<?php echo esc_attr( $this->settings_key ); ?>[endnotes]" id="endnotes" value="1"<?php checked( $options[ 'endnotes' ], true, true ); ?> /> <label for="endnotes"><?php _e( 'Yes', 'wp_print_friendly' ); ?></label>
719

Erick Hitter's avatar
Erick Hitter committed
720
							<p class="description"><?php _e( 'If enabled, content is automatically scanned for links and an endnote is added for each link found. This can be helpful for users if your content includes many links.', 'wp_print_friendly' ); ?></p>
721 722 723
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
724
						<th scope="row"><label for="endnotes-label"><?php _e( 'Endnotes heading:', 'wp_print_friendly' ); ?></label></th>
725
						<td>
726 727
							<input type="text" name="<?php echo esc_attr( $this->settings_key ); ?>[endnotes_label]" class="regular-text code" id="endnotes-label" value="<?php echo esc_attr( $options[ 'endnotes_label' ] ); ?>" />

Erick Hitter's avatar
Erick Hitter committed
728
							<p class="description"><?php _e( 'If endnotes are enabled, the text entered above will be output above the list of links.', 'wp_print_friendly' ); ?></p>
729 730 731
						</td>
					</tr>
				</table>
732

733 734 735 736
				<p class="submit">
					<input type="submit" class="button-primary" value="Save Changes" />
				</p>
			</form>
737

738 739 740
		</div><!-- .wrap -->
	<?php
	}
741

Erick Hitter's avatar
Erick Hitter committed
742
	/**
743
	 * Validate options
Erick Hitter's avatar
Erick Hitter committed
744
	 *
745
	 * @param array $options
Erick Hitter's avatar
Erick Hitter committed
746 747 748 749
	 * @uses this::get_options
	 * @uses this::post_types_array
	 * @uses delete_option
	 * @uses sanitize_text_field
750 751
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
752
	public function admin_options_validate( $options ) {
753 754 755
		$new_options = array(
			'endnotes' => false
		);
756

Erick Hitter's avatar
Erick Hitter committed
757 758
		if ( is_array( $options ) ) {
			foreach ( $options as $key => $value ) {
759 760 761 762 763
				switch( $key ) {
					case 'auto':
					case 'endnotes':
						$new_options[ $key ] = (bool)$value;
					break;
764

765 766 767 768 769 770
					case 'placement':
						$placements = array(
							'above',
							'below',
							'both'
						);
771

772 773
						$new_options[ $key ] = in_array( $value, $placements ) ? $value : 'below';
					break;
774

775 776
					case 'post_types':
						$post_types = $this->post_types_array();
777

778
						$new_options[ $key ] = array();
779

Erick Hitter's avatar
Erick Hitter committed
780 781 782
						if ( is_array( $value ) && is_array( $post_types ) ) {
							foreach ( $post_types as $post_type ) {
								if ( in_array( $post_type->name, $value ) )
783 784 785 786
									$new_options[ $key ][] = $post_type->name;
							}
						}
					break;
787

788 789 790 791 792
					case 'print_text':
					case 'print_text_page':
					case 'css_class':
					case 'endnotes_label':
						$value = sanitize_text_field( $value );
793

Erick Hitter's avatar
Erick Hitter committed
794
						if ( $key == 'print_text' && empty( $value ) )
795
							$value = 'Print this entry';
796

797 798
						$new_options[ $key ] = $value;
					break;
799

800 801 802
					case 'link_target':
						$new_options[ $key ] = $value == 'new' ? 'new' : 'same';
					break;
803

804 805 806 807 808 809
					default:
						continue;
					break;
				}
			}
		}
810

811 812
		return $new_options;
	}
813

Erick Hitter's avatar
Erick Hitter committed
814 815 816
	/**
	 * Return plugin options array parsed with default options.
	 *
Erick Hitter's avatar
Erick Hitter committed
817 818
	 * @uses wp_parse_args
	 * @uses get_option
819 820
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
821
	public function get_options() {
822
		$options = get_option( $this->settings_key, $this->settings_defaults );
823

Erick Hitter's avatar
Erick Hitter committed
824
		if ( ! array_key_exists( 'post_types', $options ) )
825
			$options[ 'post_types' ] = array();
826

827 828
		return wp_parse_args( $options, $this->settings_defaults );
	}
829

Erick Hitter's avatar
Erick Hitter committed
830 831 832
	/**
	 * Build array of available post types, excluding all builtin ones except 'post' and 'page'.
	 *
833 834 835
	 * @uses get_post_types
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
836
	public function post_types_array() {
837
		$post_types = array();
Erick Hitter's avatar
Erick Hitter committed
838 839
		foreach ( get_post_types( array(), 'objects' ) as $post_type ) {
			if ( $post_type->_builtin == false || $post_type->name == 'post' || $post_type->name == 'page' )
840 841
				$post_types[] = $post_type;
		}
842

843 844
		return $post_types;
	}
845

Erick Hitter's avatar
Erick Hitter committed
846
	/**
847
	 * Display admin notice regarding rewrite rules flush.
Erick Hitter's avatar
Erick Hitter committed
848
	 *
Erick Hitter's avatar
Erick Hitter committed
849 850 851 852 853
	 * @uses get_option
	 * @uses _e
	 * @uses __
	 * @uses admin_url
	 * @uses add_query_arg
854 855 856
	 * @action admin_notices
	 * @return html or null
	 */
Erick Hitter's avatar
Erick Hitter committed
857 858
	public function action_admin_notices_activation() {
		if ( ! get_option( $this->notice_key ) ):
859
		?>
860

861
		<div id="wpf-rewrite-flush-warning" class="error fade">
Erick Hitter's avatar
Erick Hitter committed
862
			<p><strong><?php _e( 'WP Print Friendly', 'wp_print_friendly' ); ?></strong></p>
863

Erick Hitter's avatar
Erick Hitter committed
864
			<p><?php printf( __( 'You must refresh your site\'s permalinks before WP Print Friendly is fully activated. To do so, go to <a href="%s">Permalinks</a> and click the <strong><em>Save Changes</em></strong> button at the bottom of the screen.', 'wp_print_friendly' ), admin_url( 'options-permalink.php' ) ); ?></p>
865

Erick Hitter's avatar
Erick Hitter committed
866
			<p><?php printf( __( 'When finished, click <a href="%s">here</a> to hide this message.', 'wp_print_friendly' ), admin_url( add_query_arg( $this->notice_key, 1, 'index.php' ) ) ); ?></p>
867
		</div>
868

869 870 871
		<?php
		endif;
	}
872

Erick Hitter's avatar
Erick Hitter committed
873
	/**
874
	 * Render page numbers, such as "Page 1 of 5."
Erick Hitter's avatar
Erick Hitter committed
875
	 *
876 877 878 879
	 * @param int $post_id
	 * @param string $before
	 * @param string $separator
	 * @param string $after
880 881 882 883
	 * @uses this::is_print
	 * @uses post_password_required
	 * @uses get_query_var
	 * @uses get_post_field
884 885
	 * @return string or false
	 */
Erick Hitter's avatar
Erick Hitter committed
886
	public function page_numbers( $post_id = false, $before = 'Page ', $separator = ' of ', $after = '' ) {
887
		if ( ! $this->is_print() || post_password_required() )
888
			return false;
889

890 891
		//Don't display on views that include all pages of a post
		$print = get_query_var( $this->query_var );
Erick Hitter's avatar
Erick Hitter committed
892
		if ( $print == 'all' || $print == '/all' || empty( $print ) )
893
			return false;
894

895 896
		//Get post ID and post content, or return false it either fails validation
		$post_id = intval( $post_id );
897

Erick Hitter's avatar
Erick Hitter committed
898
		if ( ! $post_id ) {
899 900 901 902
			global $post;
			$post_id = $post->ID;
			$post_content = $post->post_content;
		}
903

904
		$post_id = intval( $post_id );
905

Erick Hitter's avatar
Erick Hitter committed
906
		if ( ! $post_id )
907
			return false;
908

Erick Hitter's avatar
Erick Hitter committed
909
		if ( ! isset( $post_content ) || empty( $post_content ) )
910
			$post_content = get_post_field( 'post_content', $post_id );
911

Erick Hitter's avatar
Erick Hitter committed
912
		if ( ! is_string( $post_content ) || empty( $post_content ) || strpos( $post_content, '<!--nextpage-->' ) === false )
913
			return false;
914

915 916 917
		//Get current page
		$page = get_query_var( $this->query_var );
		$page = $page ? $page : 1;
918

919 920
		//Get total number of pages, or return false if total cannot be determined
		$num_pages = substr_count( $post_content, '<!--nextpage-->' );
921

Erick Hitter's avatar
Erick Hitter committed
922
		if ( is_int( $num_pages ) && $num_pages > 0 )
923 924 925
			$num_pages = $num_pages + 1;
		else
			return false;
926

927 928 929 930
		//Having made it this far, return the specified string
		return $before . $page . $separator . $num_pages . $after;
	}
}
931 932 933 934 935 936
wp_print_friendly::get_instance();

/**
 * Alias global variable used to hold instantiated plugin prior to singleton's introduction in version 0.6.
 */
$GLOBALS['wpf'] = wp_print_friendly::get_instance();
937

Erick Hitter's avatar
Erick Hitter committed
938
/**
939
 * Shortcut to function for generating post's printer-friendly format URL
Erick Hitter's avatar
Erick Hitter committed
940
 *
941 942
 * @param int $post_id
 * @param int $page
943
 * @uses wp_print_friendly::get_instance
944 945 946
 * @return string or bool
 */
function wpf_get_print_url( $post_id = false, $page = false ) {
947
	return wp_print_friendly::get_instance()->print_url( intval( $post_id ), intval( $page ) );
948 949
}

Erick Hitter's avatar
Erick Hitter committed
950
/**
951
 * Output link to printer-friendly post format.
Erick Hitter's avatar
Erick Hitter committed
952
 *
Erick Hitter's avatar
Erick Hitter committed
953
 * @global $post
954 955 956 957 958 959 960
 * @param string $link_text
 * @param string $class
 * @param int $post_id
 * @param bool $page_link
 * @param string $page_link_separator
 * @param string $page_link_text
 * @param string $link_target
Erick Hitter's avatar
Erick Hitter committed
961 962 963 964
 * @uses wpf_get_print_url
 * @uses esc_attr
 * @uses esc_url
 * @uses get_query_var
965 966 967 968
 * @return string or null
 */
function wpf_the_print_link( $page_link = false, $link_text = 'Print this post', $class = 'print_link', $page_link_separator = ' | ', $page_link_text = 'Print this page', $link_target = 'same' ) {
	global $post;
969

970
	$url = wpf_get_print_url( $post->ID );
971

972
	$page_link = (bool)$page_link;
973

Erick Hitter's avatar
Erick Hitter committed
974
	if ( function_exists( 'is_view_all' ) && is_view_all() )
975
		$page_link = false;
976

Erick Hitter's avatar
Erick Hitter committed
977
	if ( $url ) {
978
		$link = '<a ' . ( $class ? 'class="' . esc_attr( $class ) . '"' :