wp-print-friendly.php 32.5 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
	private $query_var = 'print';
35

36
	private $ns = 'wp_print_friendly';
37

38
	private $settings_key = 'wpf';
39
	private $settings_defaults = null; // populated in this::action_plugins_loaded to facilitate translation.
40

41
	private $notice_key = 'wpf_admin_notice_dismissed';
42

Erick Hitter's avatar
Erick Hitter committed
43
	/**
44 45 46 47
	 * Silence is golden!
	 */
	private function __construct() {}

48 49 50 51 52 53 54 55 56 57 58 59
	/**
	 * Since class variables are private as of v0.6, expose them for external reference
	 *
	 * @return mixed
	 */
	public function __get( $name ) {
		if ( property_exists( $this, $name ) )
			return $this->$name;
		else
			return null;
	}

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	/**
	 * 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
78
	 *
Erick Hitter's avatar
Erick Hitter committed
79 80
	 * @uses register_deactivation_hook
	 * @uses add_filter
81 82
	 * @return null
	 */
83
	private function setup() {
84 85 86
		register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
		add_action( 'plugins_loaded', array( $this, 'action_plugins_loaded' ) );
	}
87

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

99 100 101
		delete_option( $this->settings_key );
		delete_option( $this->notice_key );
	}
102

Erick Hitter's avatar
Erick Hitter committed
103
	/**
104
	 * Register actions and filters.
Erick Hitter's avatar
Erick Hitter committed
105
	 *
106
	 * @uses __
Erick Hitter's avatar
Erick Hitter committed
107 108 109
	 * @uses add_action
	 * @uses add_filter
	 * @uses get_option
110 111 112
	 * @action plugins_loaded
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
113
	public function action_plugins_loaded() {
114 115 116 117 118 119 120 121 122 123 124 125 126 127
		// Populate default settings, with translation support
		$this->settings_defaults = array(
			'auto'            => false,
			'placement'       => 'below',
			'post_types'      => array( 'post', 'page' ),
			'print_text'      => __( 'Print this entry', 'wp_print_friendly' ),
			'print_text_page' => __( 'Print this page', 'wp_print_friendly' ),
			'css_class'       => 'print_link',
			'link_target'     => 'same',
			'endnotes'        => true,
			'endnotes_label'  => __( 'Endnotes:', 'wp_print_friendly' ),
		);

		// Register plugin's remaining actions and filters
128 129 130 131 132 133
		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
134
		add_filter( 'redirect_canonical', array( $this, 'filter_redirect_canonical' ) );
135 136 137 138
		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 );
139

Erick Hitter's avatar
Erick Hitter committed
140
		if ( ! get_option( $this->notice_key ) )
141 142
			add_action( 'admin_notices', array( $this, 'action_admin_notices_activation' ) );
	}
143

Erick Hitter's avatar
Erick Hitter committed
144
	/**
145
	 * Add print endpoint and rewrite rules for term taxonomy archives
Erick Hitter's avatar
Erick Hitter committed
146
	 *
Erick Hitter's avatar
Erick Hitter committed
147 148 149 150 151
	 * @global $wp_rewrite
	 * @uses add_rewrite_endpoint
	 * @uses get_taxonomies
	 * @uses add_rewrite_rule
	 * @uses trailingslashit
152 153 154
	 * @action init
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
155
	public function action_init() {
156
		add_rewrite_endpoint( $this->query_var, EP_ALL );
157

158
		global $wp_rewrite;
159 160

		//Taxonomies, since they aren't covered by add_rewrite_endpoint
Erick Hitter's avatar
Erick Hitter committed
161
		if ( $wp_rewrite->permalink_structure ) {
162
			$taxonomies = get_taxonomies( array(), 'objects' );
Erick Hitter's avatar
Erick Hitter committed
163 164
			foreach ( $taxonomies as $taxonomy => $args ) {
				if ( $args->rewrite == false || 'post_format' == $taxonomy )
165
					continue;
166

167
				$taxonomy_slug = '';
Erick Hitter's avatar
Erick Hitter committed
168
				if ( $args->rewrite[ 'with_front' ] && $wp_rewrite->front != '/' ) $taxonomy_slug .= $wp_rewrite->front;
169
				$taxonomy_slug .= $args->rewrite[ 'slug' ];
170

171
				$query_var = $args->query_var ? $args->query_var : 'taxonomy=' . $taxonomy . '&term';
172 173

				add_rewrite_rule( $taxonomy_slug . '/(.+)/' . $this->query_var . '(/([0-9]*))?/?$', $wp_rewrite->index . '?' . $query_var . '=$matches[1]&' . $this->query_var . '=$matches[3]', 'top' );
174 175
			}
		}
176 177 178

		//Extra rules needed if verbose page rules are requested
		if ( $wp_rewrite->use_verbose_page_rules ) {
179
			//Build regex
180 181 182 183
			$regex = substr( str_replace( $wp_rewrite->rewritecode, $wp_rewrite->rewritereplace, $wp_rewrite->permalink_structure ), 1 );
			$regex = trailingslashit( $regex );
			$regex .= $this->query_var . '(/([0-9]*))?/?$';

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
			//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' );
201
		}
202
	}
203

Erick Hitter's avatar
Erick Hitter committed
204
	/**
205
	 * Register plugin option and disable rewrite rule flush warning.
Erick Hitter's avatar
Erick Hitter committed
206
	 *
Erick Hitter's avatar
Erick Hitter committed
207 208
	 * @uses register_setting
	 * @uses update_option
209 210 211
	 * @action admin_init
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
212
	public function action_admin_init() {
213
		register_setting( $this->settings_key, $this->settings_key, array( $this, 'admin_options_validate' ) );
214

Erick Hitter's avatar
Erick Hitter committed
215
		if ( isset( $_GET[ $this->notice_key ] ) )
216 217
			update_option( $this->notice_key, 1 );
	}
218

Erick Hitter's avatar
Erick Hitter committed
219
	/**
220
	 * Determine if print template is being requested.
Erick Hitter's avatar
Erick Hitter committed
221
	 *
222 223
	 * If WordPress determined this request is a 404, do nothing and let the main theme handle things.
	 *
224
	 * @global $wp_query
225
	 * @uses is_404
226 227
	 * @return bool
	 */
Erick Hitter's avatar
Erick Hitter committed
228
	public function is_print() {
229
		global $wp_query;
230
		return is_array( $wp_query->query ) && array_key_exists( $this->query_var, $wp_query->query ) && ! is_404();
231
	}
232

Erick Hitter's avatar
Erick Hitter committed
233
	/**
234 235
	 * 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
236
	 *
Erick Hitter's avatar
Erick Hitter committed
237 238 239 240
	 * @uses get_queried_object
	 * @uses is_home
	 * @uses is_front_page
	 * @uses locate_template
241 242
	 * @return array or false
	 */
Erick Hitter's avatar
Erick Hitter committed
243
	public function template_chooser() {
244 245
		//Get queried object to check post type
		$queried_object = get_queried_object();
246

247 248
		//Get plugin path
		$pluginpath = dirname( __FILE__ );
249

Erick Hitter's avatar
Erick Hitter committed
250
		if ( ( is_home() || is_front_page() ) && ( '' !== ( $path = locate_template( 'wpf-home.php', false ) ) ) ) {
251 252 253 254
			$template = array(
				'name' => 'wpf-home',
				'path' => $path
			);
255
		} elseif (
256 257 258
			is_object( $queried_object ) &&
			property_exists( $queried_object, 'taxonomy' ) &&
			property_exists( $queried_object, 'slug' ) &&
259
			( '' !== ( $path = locate_template( array( 'wpf-' . $queried_object->taxonomy . '-' . $queried_object->slug . '.php', 'wpf-' . $queried_object->taxonomy . '.php' ), false ) ) )
260
		) {
261 262 263 264
			$template = array(
				'name' => 'wpf-' . $queried_object->taxonomy,
				'path' => $path
			);
265
		} elseif (
266 267 268 269
			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 ) ) )
270
		) {
271 272 273 274
			$template = array(
				'name' => 'wpf-' . $queried_object->post_type,
				'path' => $path
			);
275
		} elseif (
276 277 278
			is_object( $queried_object ) &&
			property_exists( $queried_object, 'post_name' ) &&
			( '' !== ( $path = locate_template( 'wpf-' . $queried_object->post_name . '.php', false ) ) )
279
		) {
280 281 282 283
			$template = array(
				'name' => 'wpf-' . $queried_object->post_name,
				'path' => $path
			);
284
		} elseif ( '' !== ( $path = locate_template( 'wpf.php', false ) ) ) {
285 286 287 288
			$template = array(
				'name' => 'wpf-default',
				'path' => $path
			);
289
		} elseif ( file_exists( $pluginpath . '/default-template.php' ) ) {
290 291 292 293
			$template = array(
				'name' => 'wpf-plugin-default',
				'path' => $pluginpath . '/default-template.php'
			);
294
		}
295

296 297
		return isset( $template ) ? $template : false;
	}
298

Erick Hitter's avatar
Erick Hitter committed
299 300 301
	/**
	 * Detect request for print stylesheet on the homepage and reset query variables.
	 *
302 303 304 305
	 * @param array $qv
	 * @filter request
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
306 307
	public function filter_request( $qv ) {
		if ( array_key_exists( 'pagename', $qv ) && $qv[ 'pagename' ] == $this->query_var ) {
308 309 310 311
			$qv[ $this->query_var ] = '';
			unset( $qv[ 'page' ] );
			unset( $qv[ 'pagename' ] );
		}
312

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

316 317
		return $qv;
	}
318

Erick Hitter's avatar
Erick Hitter committed
319
	/**
320
	 * Filter query when request to print specific page is made.
Erick Hitter's avatar
Erick Hitter committed
321
	 *
322 323 324 325
	 * @param object $query
	 * @action pre_get_posts
	 * @return object
	 */
Erick Hitter's avatar
Erick Hitter committed
326 327
	public function action_pre_get_posts( $query ) {
		if ( array_key_exists( $this->query_var, $query->query_vars ) && ! empty( $query->query_vars[ $this->query_var ] ) ) {
328
			$qv = explode( '/', $query->query_vars[ $this->query_var ] );
329

Erick Hitter's avatar
Erick Hitter committed
330
			if ( array_key_exists( 1, $qv ) && is_numeric( $qv[ 1 ] ) )
331 332
				$query->query_vars[ 'page' ] = (int)$qv[ 1 ];
		}
333

334 335
		return $query;
	}
336

Erick Hitter's avatar
Erick Hitter committed
337
	/**
338
	 * Filter template include to return print template if requested.
Erick Hitter's avatar
Erick Hitter committed
339
	 *
340 341 342 343
	 * @param string $template
	 * @filter template_include
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
344
	public function filter_template_include( $template ) {
345
		if ( $this->is_print() && ( $print_template = $this->template_chooser() ) )
346
			$template = $print_template[ 'path' ];
347

348 349
		return $template;
	}
350

Erick Hitter's avatar
Erick Hitter committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
	/**
	 * 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;
	}

	/**
367
	 * Filter body classes to include references to print template.
Erick Hitter's avatar
Erick Hitter committed
368
	 *
369 370 371 372
	 * @param array $classes
	 * @filter body_class
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
373 374 375
	public function filter_body_class( $classes ) {
		if ( $this->is_print() && ( $print_template = $this->template_chooser() ) ) {
			if ( $print_template[ 'name' ] == 'default' )
376 377 378 379
				$classes[] = 'wpf';
			else
				$classes[] = $print_template[ 'name' ];
		}
380

381 382
		return $classes;
	}
383

Erick Hitter's avatar
Erick Hitter committed
384
	/**
385
	 * Filter post content to support printing entire post on one page.
Erick Hitter's avatar
Erick Hitter committed
386
	 *
387
	 * @param string $content
388
	 * @uses post_password_required
389 390 391 392
	 * @uses get_query_var
	 * @filter the_content
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
393
	public function filter_the_content( $content ) {
394
		if ( $this->is_print() && ! post_password_required() ) {
395
			$print = get_query_var( $this->query_var );
396

Erick Hitter's avatar
Erick Hitter committed
397
			if ( $print == 'all' || $print == '/all' || empty( $print ) ) {
398
				global $post;
399

400 401 402 403 404 405 406
				$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);
			}
		}
407

408 409
		return $content;
	}
410

Erick Hitter's avatar
Erick Hitter committed
411 412 413
	/**
	 * Filter the content if automatic inclusion is selected.
	 *
Erick Hitter's avatar
Erick Hitter committed
414
	 * @global $post
415
	 * @param string $content
Erick Hitter's avatar
Erick Hitter committed
416 417 418 419
	 * @uses this::get_options
	 * @uses this::print_url
	 * @uses get_query_var
	 * @uses apply_filters
420 421 422
	 * @filter the_content
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
423
	public function filter_the_content_auto( $content ) {
424
		$options = $this->get_options();
425

426
		global $post;
427

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

431 432
			//Basic URL
			$print_url = $this->print_url();
433

434
			//Page URL, if necessary
Erick Hitter's avatar
Erick Hitter committed
435
			if ( ! empty( $print_text_page ) && strpos( $post->post_content, '<!--nextpage-->' ) !== false ) {
436 437
				$page = get_query_var( 'page' );
				$page = $page ? $page : 1;
438

439 440
				$print_url_page = $this->print_url( false, $page );
			}
441

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

Erick Hitter's avatar
Erick Hitter committed
445
			if ( isset( $print_url_page ) ) {
446 447 448
				$link .= ' | ';
				$link .= '<a class="' . $css_class . ' ' . $css_class . '_cur" href="' . $print_url_page . '"' . ( $link_target == 'new' ? ' target="_blank"' : '' ) . '>' . $print_text_page . '</a>';
			}
449

450
			$link .= '</p><!-- .wpf_wrapper -->';
451

452
			//Place link(s)
Erick Hitter's avatar
Erick Hitter committed
453
			if ( $placement == 'above' )
454
				$content = $link . $content;
Erick Hitter's avatar
Erick Hitter committed
455
			elseif ( $placement == 'below' )
456
				$content = $content . $link;
Erick Hitter's avatar
Erick Hitter committed
457
			elseif ( $placement == 'both' )
458 459
				$content = $link . $content . $link;
		}
460

461 462
		return $content;
	}
463

Erick Hitter's avatar
Erick Hitter committed
464 465 466
	/**
	 * Convert links to endnotes if desired.
	 *
467
	 * @param string $content
468 469 470
	 * @uses this::is_print
	 * @uses post_password_required
	 * @uses this::get_options
471 472 473
	 * @filter the_content
	 * @return string
	 */
Erick Hitter's avatar
Erick Hitter committed
474
	public function filter_the_content_late( $content ) {
475
		if ( $this->is_print() && ! post_password_required() ) {
476
			global $post;
477

478
			$options = $this->get_options();
479

480
			//Endnotes
Erick Hitter's avatar
Erick Hitter committed
481
			if ( $options[ 'endnotes' ] ) {
482 483
				$links = array();
				$i = 1;
484

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

Erick Hitter's avatar
Erick Hitter committed
488
				if (
489
					isset( $matches ) && is_array( $matches ) &&
Erick Hitter's avatar
Erick Hitter committed
490 491 492
					array_key_exists( 0, $matches ) && ! empty( $matches[ 0 ] ) &&
					array_key_exists( 2, $matches ) && ! empty( $matches[ 2 ] ) &&
					array_key_exists( 5, $matches ) && ! empty( $matches[ 5 ] )
493 494 495
				) {
					//Format matches for replacement in content
					$replacements = array();
Erick Hitter's avatar
Erick Hitter committed
496
					foreach ( $matches[ 0 ] as $key => $match ) {
497 498 499 500 501
						$replacements[ $match ] = array(
							'url' => $matches[ 2 ][ $key ],
							'title' => $matches[ 5 ][ $key ]
						);
					}
502

503
					//Replace links with endnote markers
Erick Hitter's avatar
Erick Hitter committed
504
					foreach ( $replacements as $match => $args ) {
505 506 507 508
						$content = str_replace( $match, $args[ 'title' ] . '[' . $i . ']', $content );
						$links[ $i ] = $args;
						$i++;
					}
509

510 511 512 513
					//Output endnotes
					$endnotes = '<div class="wpf-endnotes">';
					$endnotes .= '<strong>' . $options[ 'endnotes_label' ] . '</strong>';
					$endnotes .= '<ol>';
Erick Hitter's avatar
Erick Hitter committed
514
					foreach ( $links as $link ) {
515 516 517 518 519
						$endnotes .= '<li>';
						$endnotes .=  preg_replace( '#<img(.*)>#', '[Image]', $link[ 'title' ] ) . ': ' . esc_url( $link[ 'url' ] );
						$endnotes .= '</li>';
					}
					$endnotes .= '</ol></div><!-- .wpf-endnotes -->';
520

521 522 523 524
					$content .= $endnotes;
				}
			}
		}
525

526 527
		return $content;
	}
528

Erick Hitter's avatar
Erick Hitter committed
529 530 531
	/**
	 * Generate URL for post's printer-friendly format.
	 *
Erick Hitter's avatar
Erick Hitter committed
532 533
	 * @global $post
	 * @global $wp_rewrite
534 535
	 * @param int $post_id
	 * @param int $page
Erick Hitter's avatar
Erick Hitter committed
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
	 * @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
556 557
	 * @return string or bool
	 */
Erick Hitter's avatar
Erick Hitter committed
558 559
	public function print_url( $post_id = false, $page = false ) {
		if ( $page === true )
560
			return false;
561

Erick Hitter's avatar
Erick Hitter committed
562
		if ( function_exists( 'is_view_all' ) && is_view_all() )
563
			$page = false;
564

565
		$link = false;
566

567
		//Get link base specific to page type being viewed
Erick Hitter's avatar
Erick Hitter committed
568 569
		if ( is_singular() || in_the_loop() ) {
			if ( $post_id == false ) {
570 571 572
				global $post;
				$post_id = $post->ID;
			}
573

Erick Hitter's avatar
Erick Hitter committed
574
			if ( ! $post_id )
575
				return false;
576

577 578
			$link = get_permalink( $post_id );
		}
Erick Hitter's avatar
Erick Hitter committed
579
		elseif ( is_home() || is_front_page() )
580
			$link = home_url( '/' );
Erick Hitter's avatar
Erick Hitter committed
581
		elseif ( is_category() )
582
			$link = get_category_link( get_query_var( 'cat' ) );
Erick Hitter's avatar
Erick Hitter committed
583
		elseif ( is_tag() )
584 585
			$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
586
		elseif ( is_date() ) {
587 588 589
			$year = get_query_var( 'year' );
			$monthnum = get_query_var( 'monthnum' );
			$day = get_query_var( 'day' );
590

Erick Hitter's avatar
Erick Hitter committed
591
			if ( $day )
592
				$link = get_day_link( $year, $monthnum, $day );
Erick Hitter's avatar
Erick Hitter committed
593
			elseif ( $monthnum )
594 595 596 597
				$link = get_month_link( $year, $monthnum );
			else
				$link = get_year_link( $year );
		}*/
Erick Hitter's avatar
Erick Hitter committed
598
		elseif ( is_tax() ) {
599
			$queried_object = get_queried_object();
600

Erick Hitter's avatar
Erick Hitter committed
601
			if ( is_object( $queried_object ) && property_exists( $queried_object, 'taxonomy' ) && property_exists( $queried_object, 'term_id' ) )
602 603
				$link = get_term_link( (int)$queried_object->term_id, $queried_object->taxonomy );
		}
604

605
		//If link base is set, build link
Erick Hitter's avatar
Erick Hitter committed
606
		if ( $link !== false ) {
607
			global $wp_rewrite;
608

609
			$page = intval( $page );
610

Erick Hitter's avatar
Erick Hitter committed
611
			if ( $wp_rewrite->using_permalinks() ) {
612
				$link = path_join( $link, $this->query_var );
613

Erick Hitter's avatar
Erick Hitter committed
614
				if ( $page )
615
					$link = path_join( $link, intval( $page ) );
616

Erick Hitter's avatar
Erick Hitter committed
617
				if ( $wp_rewrite->use_trailing_slashes )
618 619 620 621
					$link = trailingslashit( $link );
			}
			else {
				$link = add_query_arg( $this->query_var, is_numeric( $page ) ? intval( $page ) : 'all', $link );
622

Erick Hitter's avatar
Erick Hitter committed
623
				if ( $page )
624 625 626
					$link = add_query_arg( 'page', is_numeric( $page ) ? intval( $page ) : 'all', $link );
			}
		}
627

628 629
		return $link;
	}
630

Erick Hitter's avatar
Erick Hitter committed
631 632 633
	/**
	 * Add menu item for options page.
	 *
634 635 636 637
	 * @uses add_options_page
	 * @action admin_menu
	 * @return null
	 */
Erick Hitter's avatar
Erick Hitter committed
638
	public function action_admin_menu() {
639 640
		add_options_page( 'WP Print Friendly Options', 'WP Print Friendly', 'manage_options', $this->ns, array( $this, 'admin_options' ) );
	}
641

Erick Hitter's avatar
Erick Hitter committed
642 643 644
	/**
	 * Render options page.
	 *
Erick Hitter's avatar
Erick Hitter committed
645 646 647 648 649
	 * @uses settings_fields
	 * @uses this::get_options
	 * @uses _e
	 * @uses checked
	 * @uses esc_attr
650 651
	 * @return html
	 */
Erick Hitter's avatar
Erick Hitter committed
652
	public function admin_options() {
653 654 655
	?>
		<div class="wrap">
			<h2>WP Print Friendly</h2>
656

657 658 659 660
			<form action="options.php" method="post">
				<?php
					settings_fields( $this->settings_key );
					$options = $this->get_options();
661

662 663
					$post_types = $this->post_types_array();
				?>
664

665
				<h3>Display Options</h3>
666

667 668
				<table class="form-table">
					<tr>
Erick Hitter's avatar
Erick Hitter committed
669
						<th scope="row"><?php _e( 'Automatically add print links based on settings below?', 'wp_print_friendly' ); ?></th>
670
						<td>
Erick Hitter's avatar
Erick Hitter committed
671 672
							<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>
673 674 675
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
676
						<th scope="row"><?php _e( 'Automatically place link:', 'wp_print_friendly' ); ?></th>
677
						<td>
Erick Hitter's avatar
Erick Hitter committed
678 679 680
							<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>
681 682 683
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
684
						<th scope="row"><?php _e( 'Display automatically on:', 'wp_print_friendly' ); ?></th>
685
						<td>
Erick Hitter's avatar
Erick Hitter committed
686 687
							<?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 />
688 689 690 691
							<?php endforeach; ?>
						</td>
					</tr>
				</table>
692

693
				<h3>Link Options</h3>
694

695 696
				<table class="form-table">
					<tr>
Erick Hitter's avatar
Erick Hitter committed
697
						<th scope="row"><?php _e( 'Text for link to print entire item:', 'wp_print_friendly' ); ?></th>
698
						<td>
699
							<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%;" />
700 701 702
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
703
						<th scope="row"><?php _e( 'Text for link to print current page:', 'wp_print_friendly' ); ?></th>
704
						<td>
705 706
							<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
707 708
							<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>
709 710 711
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
712
						<th scope="row"><?php _e( 'CSS for print links:', 'wp_print_friendly' ); ?></th>
713
						<td>
714 715
							<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
716 717
							<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>
718 719 720
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
721
						<th scope="row"><?php _e( 'Open print-friendly views:', 'wp_print_friendly' ); ?></th>
722
						<td>
Erick Hitter's avatar
Erick Hitter committed
723 724
							<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>
725 726 727
						</td>
					</tr>
				</table>
728

729
				<h3>Endnote Options</h3>
730

731 732
				<table class="form-table">
					<tr>
Erick Hitter's avatar
Erick Hitter committed
733
						<th scope="row"><?php _e( 'Include endnotes for links found in content?', 'wp_print_friendly' ); ?></th>
734
						<td>
Erick Hitter's avatar
Erick Hitter committed
735
							<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>
736

Erick Hitter's avatar
Erick Hitter committed
737
							<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>
738 739 740
						</td>
					</tr>
					<tr>
Erick Hitter's avatar
Erick Hitter committed
741
						<th scope="row"><label for="endnotes-label"><?php _e( 'Endnotes heading:', 'wp_print_friendly' ); ?></label></th>
742
						<td>
743 744
							<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
745
							<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>
746 747 748
						</td>
					</tr>
				</table>
749

750 751 752 753
				<p class="submit">
					<input type="submit" class="button-primary" value="Save Changes" />
				</p>
			</form>
754

755 756 757
		</div><!-- .wrap -->
	<?php
	}
758

Erick Hitter's avatar
Erick Hitter committed
759
	/**
760
	 * Validate options
Erick Hitter's avatar
Erick Hitter committed
761
	 *
762
	 * @param array $options
Erick Hitter's avatar
Erick Hitter committed
763 764 765 766
	 * @uses this::get_options
	 * @uses this::post_types_array
	 * @uses delete_option
	 * @uses sanitize_text_field
767 768
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
769
	public function admin_options_validate( $options ) {
770 771 772
		$new_options = array(
			'endnotes' => false
		);
773

Erick Hitter's avatar
Erick Hitter committed
774 775
		if ( is_array( $options ) ) {
			foreach ( $options as $key => $value ) {
776 777 778 779 780
				switch( $key ) {
					case 'auto':
					case 'endnotes':
						$new_options[ $key ] = (bool)$value;
					break;
781

782 783 784 785 786 787
					case 'placement':
						$placements = array(
							'above',
							'below',
							'both'
						);
788

789 790
						$new_options[ $key ] = in_array( $value, $placements ) ? $value : 'below';
					break;
791

792 793
					case 'post_types':
						$post_types = $this->post_types_array();
794

795
						$new_options[ $key ] = array();
796

Erick Hitter's avatar
Erick Hitter committed
797 798 799
						if ( is_array( $value ) && is_array( $post_types ) ) {
							foreach ( $post_types as $post_type ) {
								if ( in_array( $post_type->name, $value ) )
800 801 802 803
									$new_options[ $key ][] = $post_type->name;
							}
						}
					break;
804

805 806 807 808 809
					case 'print_text':
					case 'print_text_page':
					case 'css_class':
					case 'endnotes_label':
						$value = sanitize_text_field( $value );
810

Erick Hitter's avatar
Erick Hitter committed
811
						if ( $key == 'print_text' && empty( $value ) )
812
							$value = 'Print this entry';
813

814 815
						$new_options[ $key ] = $value;
					break;
816

817 818 819
					case 'link_target':
						$new_options[ $key ] = $value == 'new' ? 'new' : 'same';
					break;
820

821 822 823 824 825 826
					default:
						continue;
					break;
				}
			}
		}
827

828 829
		return $new_options;
	}
830

Erick Hitter's avatar
Erick Hitter committed
831 832 833
	/**
	 * Return plugin options array parsed with default options.
	 *
Erick Hitter's avatar
Erick Hitter committed
834 835
	 * @uses wp_parse_args
	 * @uses get_option
836 837
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
838
	public function get_options() {
839
		$options = get_option( $this->settings_key, $this->settings_defaults );
840

Erick Hitter's avatar
Erick Hitter committed
841
		if ( ! array_key_exists( 'post_types', $options ) )
842
			$options[ 'post_types' ] = array();
843

844 845
		return wp_parse_args( $options, $this->settings_defaults );
	}
846

Erick Hitter's avatar
Erick Hitter committed
847 848 849
	/**
	 * Build array of available post types, excluding all builtin ones except 'post' and 'page'.
	 *
850 851 852
	 * @uses get_post_types
	 * @return array
	 */
Erick Hitter's avatar
Erick Hitter committed
853
	public function post_types_array() {
854
		$post_types = array();
Erick Hitter's avatar
Erick Hitter committed
855 856
		foreach ( get_post_types( array(), 'objects' ) as $post_type ) {
			if ( $post_type->_builtin == false || $post_type->name == 'post' || $post_type->name == 'page' )
857 858
				$post_types[] = $post_type;
		}
859

860 861
		return $post_types;
	}
862

Erick Hitter's avatar
Erick Hitter committed
863
	/**
864
	 * Display admin notice regarding rewrite rules flush.
Erick Hitter's avatar
Erick Hitter committed
865
	 *
Erick Hitter's avatar
Erick Hitter committed
866 867 868 869 870
	 * @uses get_option
	 * @uses _e
	 * @uses __
	 * @uses admin_url
	 * @uses add_query_arg
871 872 873
	 * @action admin_notices
	 * @return html or null
	 */
Erick Hitter's avatar
Erick Hitter committed
874 875
	public function action_admin_notices_activation() {
		if ( ! get_option( $this->notice_key ) ):
876
		?>
877

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

Erick Hitter's avatar
Erick Hitter committed
881
			<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>
882

Erick Hitter's avatar
Erick Hitter committed
883
			<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>
884
		</div>
885

886 887 888
		<?php
		endif;
	}
889

Erick Hitter's avatar
Erick Hitter committed
890
	/**
891
	 * Render page numbers, such as "Page 1 of 5."
Erick Hitter's avatar
Erick Hitter committed
892
	 *
893 894 895 896
	 * @param int $post_id
	 * @param string $before
	 * @param string $separator
	 * @param string $after
897 898 899 900
	 * @uses this::is_print
	 * @uses post_password_required
	 * @uses get_query_var
	 * @uses get_post_field
901 902
	 * @return string or false
	 */
Erick Hitter's avatar
Erick Hitter committed
903
	public function page_numbers( $post_id = false, $before = 'Page ', $separator = ' of ', $after = '' ) {
904
		if ( ! $this->is_print() || post_password_required() )
905
			return false;
906

907 908
		//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
909
		if ( $print == 'all' || $print == '/all' || empty( $print ) )
910
			return false;
911

912 913
		//Get post ID and post content, or return false it either fails validation
		$post_id = intval( $post_id );
914

Erick Hitter's avatar
Erick Hitter committed
915
		if ( ! $post_id ) {
916 917 918 919
			global $post;
			$post_id = $post->ID;
			$post_content = $post->post_content;
		}
920

921
		$post_id = intval( $post_id );
922

Erick Hitter's avatar
Erick Hitter committed
923
		if ( ! $post_id )
924
			return false;
925

Erick Hitter's avatar
Erick Hitter committed
926
		if ( ! isset( $post_content ) || empty( $post_content ) )
927
			$post_content = get_post_field( 'post_content', $post_id );
928

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

932 933 934
		//Get current page
		$page = get_query_var( $this->query_var );
		$page = $page ? $page : 1;
935

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

Erick Hitter's avatar
Erick Hitter committed
939
		if ( is_int( $num_pages ) && $num_pages > 0 )
940 941 942
			$num_pages = $num_pages + 1;
		else
			return false;
943

944 945 946 947
		//Having made it this far, return the specified string
		return $before . $page . $separator . $num_pages . $after;
	}
}
948 949 950 951 952 953
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();
954

Erick Hitter's avatar
Erick Hitter committed
955
/**
956
 * Shortcut to function for generating post's printer-friendly format URL
Erick Hitter's avatar
Erick Hitter committed
957
 *
958 959
 * @param int $post_id
 * @param int $page
960
 * @uses wp_print_friendly::get_instance
961 962 963
 * @return string or bool
 */
function wpf_get_print_url( $post_id = false, $page = false ) {
964
	return wp_print_friendly::get_instance()->print_url( intval( $post_id ), intval( $page ) );
965 966
}

Erick Hitter's avatar
Erick Hitter committed
967
/**
968
 * Output link to printer-friendly post format.
Erick Hitter's avatar
Erick Hitter committed
969
 *
Erick Hitter's avatar
Erick Hitter committed
970
 * @global $post
971 972 973 974 975 976 977
 * @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
978 979 980 981
 * @uses wpf_get_print_url
 * @uses esc_attr
 * @uses esc_url
 * @uses get_query_var
982 983 984 985
 * @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;
986