PluginProbe
Post Snippets – Custom WordPress Code Snippets Customizer / 1.9.1
Post Snippets – Custom WordPress Code Snippets Customizer v1.9.1
4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.1 1.7.2 1.7.3 1.8 1.8.1 1.8.2 1.8.3 1.8.5 1.8.6 1.8.7 1.8.8 1.8.9 1.8.9.1 1.8.9.2 1.9 1.9.1 1.9.2 1.9.3 1.9.4 1.9.5 All 115 releases
post-snippets / post-snippets.php

post-snippets.php in Post Snippets – Custom WordPress Code Snippets Customizer 1.9.1, at post-snippets.php

864 lines 28.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Plugin Name: Post Snippets
4 Plugin URI: http://wpstorm.net/wordpress-plugins/post-snippets/
5 Description: Stores snippets of HTML code or reoccurring text that you often use in your posts. You can use predefined variables to replace parts of the snippet on insert. All snippets are available in the post editor with a TinyMCE button or Quicktags.
6 Version: 1.9.1
7 Author: Johan Steen
8 Author URI: http://johansteen.se/
9 Text Domain: post-snippets
10
11 Copyright 2009-2012 Johan Steen (email : artstorm [at] gmail [dot] com)
12
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
26 */
27
28 class Post_Snippets {
29 private $tinymce_plugin_name = 'post_snippets';
30 private $plugin_options = 'post_snippets_options';
31
32 // -------------------------------------------------------------------------
33
34 public function __construct() {
35 // Define the domain and path for translations
36 $rel_path = dirname(plugin_basename($this->get_File())).'/languages/';
37 load_plugin_textdomain( 'post-snippets', false, $rel_path );
38
39 $this->init_hooks();
40 }
41
42 /**
43 * Initializes the hooks for the plugin
44 */
45 function init_hooks() {
46
47 // Add TinyMCE button
48 add_action('init', array(&$this, 'add_tinymce_button') );
49
50 # Settings link on plugins list
51 add_filter( 'plugin_action_links', array(&$this, 'plugin_action_links'), 10, 2 );
52 # Options Page
53 add_action( 'admin_menu', array(&$this,'wp_admin') );
54
55 $this->create_shortcodes();
56
57 # Adds the JS and HTML code in the header and footer for the jQuery insert UI dialog in the editor
58 add_action( 'admin_init', array(&$this,'enqueue_assets') );
59 add_action( 'admin_head', array(&$this,'jquery_ui_dialog') );
60 add_action( 'admin_footer', array(&$this,'insert_ui_dialog') );
61
62 # Add Editor QuickTag button
63 // IF WordPress is 3.3 or higher, use the new refactored method to add
64 // the quicktag button.
65 // Start showing a deprecated message from version 1.9 of the plugin for
66 // the old method. And remove it completely when the plugin hits 2.0.
67 global $wp_version;
68 if ( version_compare($wp_version, '3.3', '>=') ) {
69 add_action( 'admin_print_footer_scripts',
70 array(&$this,'add_quicktag_button'), 100 );
71 } else {
72 add_action( 'edit_form_advanced', array(&$this,'add_quicktag_button_pre33') );
73 add_action( 'edit_page_form', array(&$this,'add_quicktag_button_pre33') );
74 }
75 }
76
77
78 /**
79 * Quick link to the Post Snippets Settings page from the Plugins page.
80 *
81 * @return Array with all the plugin's action links
82 */
83 function plugin_action_links( $links, $file ) {
84 if ( $file == plugin_basename( dirname($this->get_FILE()).'/post-snippets.php' ) ) {
85 $links[] = '<a href="options-general.php?page=post-snippets/post-snippets.php">'.__('Settings', 'post-snippets').'</a>';
86 }
87 return $links;
88 }
89
90
91 /**
92 * Enqueues the necessary scripts and styles for the plugins
93 *
94 * @since Post Snippets 1.7
95 */
96 function enqueue_assets() {
97 wp_enqueue_script( 'jquery-ui-dialog' );
98 wp_enqueue_script( 'jquery-ui-tabs' );
99 wp_enqueue_style( 'wp-jquery-ui-dialog');
100
101 # Adds the CSS stylesheet for the jQuery UI dialog
102 $style_url = plugins_url( '/assets/post-snippets.css', __FILE__ );
103 $style_url = plugins_url( '/assets/post-snippets.css', $this->get_FILE() );
104 wp_register_style('post-snippets', $style_url);
105 wp_enqueue_style( 'post-snippets');
106 }
107
108
109 // -------------------------------------------------------------------------
110 // WordPress Editor Buttons
111 // -------------------------------------------------------------------------
112
113 /**
114 * Add TinyMCE button.
115 *
116 * Adds filters to add custom buttons to the TinyMCE editor (Visual Editor)
117 * in WordPress.
118 *
119 * @since Post Snippets 1.8.7
120 */
121 public function add_tinymce_button()
122 {
123 // Don't bother doing this stuff if the current user lacks permissions
124 if ( !current_user_can('edit_posts') &&
125 !current_user_can('edit_pages') )
126 return;
127
128 // Add only in Rich Editor mode
129 if ( get_user_option('rich_editing') == 'true') {
130 add_filter('mce_external_plugins',
131 array(&$this, 'register_tinymce_plugin') );
132 add_filter('mce_buttons',
133 array(&$this, 'register_tinymce_button') );
134 }
135 }
136
137 /**
138 * Register TinyMCE button.
139 *
140 * Pushes the custom TinyMCE button into the array of with button names.
141 * 'separator' or '|' can be pushed to the array as well. See the link
142 * for all available TinyMCE controls.
143 *
144 * @see wp-includes/class-wp-editor.php
145 * @link http://www.tinymce.com/wiki.php/Buttons/controls
146 * @since Post Snippets 1.8.7
147 *
148 * @param array $buttons Filter supplied array of buttons to modify
149 * @return array The modified array with buttons
150 */
151 public function register_tinymce_button( $buttons )
152 {
153 array_push( $buttons, 'separator', $this->tinymce_plugin_name );
154 return $buttons;
155 }
156
157 /**
158 * Register TinyMCE plugin.
159 *
160 * Adds the absolute URL for the TinyMCE plugin to the associative array of
161 * plugins. Array structure: 'plugin_name' => 'plugin_url'
162 *
163 * @see wp-includes/class-wp-editor.php
164 * @since Post Snippets 1.8.7
165 *
166 * @param array $plugins Filter supplied array of plugins to modify
167 * @return array The modified array with plugins
168 */
169 public function register_tinymce_plugin( $plugins )
170 {
171 // Load the TinyMCE plugin, editor_plugin.js, into the array
172 $plugins[$this->tinymce_plugin_name] =
173 plugins_url('/tinymce/editor_plugin.js', $this->get_FILE());
174
175 return $plugins;
176 }
177
178
179 // -------------------------------------------------------------------------
180
181
182 /**
183 * jQuery control for the dialog and Javascript needed to insert snippets into the editor
184 *
185 * @since Post Snippets 1.7
186 */
187 function jquery_ui_dialog() {
188 echo "\n<!-- START: Post Snippets jQuery UI and related functions -->\n";
189 echo "<script type='text/javascript'>\n";
190
191 # Prepare the snippets and shortcodes into javascript variables
192 # so they can be inserted into the editor, and get the variables replaced
193 # with user defined strings.
194 $snippets = get_option($this->plugin_options);
195 foreach ($snippets as $key => $snippet) {
196 if ($snippet['shortcode']) {
197 # Build a long string of the variables, ie: varname1={varname1} varname2={varname2}
198 # so {varnameX} can be replaced at runtime.
199 $var_arr = explode(",",$snippet['vars']);
200 $variables = '';
201 if (!empty($var_arr[0])) {
202 foreach ($var_arr as $var) {
203 $variables .= ' ' . $var . '="{' . $var . '}"';
204 }
205 }
206 $shortcode = $snippet['title'] . $variables;
207 echo "var postsnippet_{$key} = '[" . $shortcode . "]';\n";
208 } else {
209 // To use $snippet is probably not a good naming convention here.
210 // rename to js_snippet or something?
211 $snippet = $snippet['snippet'];
212 # Fixes for potential collisions:
213 /* Replace <> with char codes, otherwise </script> in a snippet will break it */
214 $snippet = str_replace( '<', '\x3C', str_replace( '>', '\x3E', $snippet ) );
215 /* Escape " with \" */
216 $snippet = str_replace( '"', '\"', $snippet );
217 /* Remove CR and replace LF with \n to keep formatting */
218 $snippet = str_replace( chr(13), '', str_replace( chr(10), '\n', $snippet ) );
219 # Print out the variable containing the snippet
220 echo "var postsnippet_{$key} = \"" . $snippet . "\";\n";
221 }
222 }
223 ?>
224
225 jQuery(document).ready(function($){
226 <?php
227 # Create js variables for all form fields
228 foreach ($snippets as $key => $snippet) {
229 $var_arr = explode(",",$snippet['vars']);
230 if (!empty($var_arr[0])) {
231 foreach ($var_arr as $key_2 => $var) {
232 $varname = "var_" . $key . "_" . $key_2;
233 echo "var {$varname} = $( \"#{$varname}\" );\n";
234 }
235 }
236 }
237 ?>
238
239 var $tabs = $("#post-snippets-tabs").tabs();
240
241 $(function() {
242 $( "#post-snippets-dialog" ).dialog({
243 autoOpen: false,
244 modal: true,
245 dialogClass: 'wp-dialog',
246 buttons: {
247 Cancel: function() {
248 $( this ).dialog( "close" );
249 },
250 "Insert": function() {
251 $( this ).dialog( "close" );
252 var selected = $tabs.tabs('option', 'selected');
253 <?php
254 foreach ($snippets as $key => $snippet) {
255 ?>
256 if (selected == <?php echo $key; ?>) {
257 insert_snippet = postsnippet_<?php echo $key; ?>;
258 <?php
259 $var_arr = explode(",",$snippet['vars']);
260 if (!empty($var_arr[0])) {
261 foreach ($var_arr as $key_2 => $var) {
262 $varname = "var_" . $key . "_" . $key_2; ?>
263 insert_snippet = insert_snippet.replace(/\{<?php echo $var; ?>\}/g, <?php echo $varname; ?>.val());
264 <?php
265 echo "\n";
266 }
267 }
268 ?>
269 }
270 <?php
271 }
272 ?>
273
274 if (caller == 'html') {
275 edInsertContent(muppCanv, insert_snippet);
276 } else {
277 muppCanv.execCommand('mceInsertContent', false, insert_snippet);
278 }
279
280 }
281 },
282 width: 500,
283 });
284 });
285 });
286
287 var muppCanv;
288 caller = '';
289
290 <!-- Deprecated -->
291 function edOpenPostSnippets(myField) {
292 muppCanv = myField;
293 caller = 'html';
294 jQuery( "#post-snippets-dialog" ).dialog( "open" );
295 };
296 <?php
297 echo "</script>\n";
298 echo "\n<!-- END: Post Snippets jQuery UI and related functions -->\n";
299 }
300
301
302 /**
303 * Insert Snippet jQuery UI dialog HTML for the post editor
304 *
305 * @since Post Snippets 1.7
306 */
307 function insert_ui_dialog() {
308 echo "\n<!-- START: Post Snippets UI Dialog -->\n";
309 ?>
310 <div class="hidden">
311 <div id="post-snippets-dialog" title="Post Snippets">
312
313 <div id="post-snippets-tabs">
314 <ul>
315 <?php
316 # Create a tab for each available snippet
317 $snippets = get_option($this->plugin_options);
318 foreach ($snippets as $key => $snippet) {
319 ?>
320 <li><a href="#ps-tabs-<?php echo $key; ?>"><?php echo $snippet['title']; ?></a></li>
321 <?php } ?>
322 </ul>
323
324 <?php
325 # Create a panel with form fields for each available snippet
326 foreach ($snippets as $key => $snippet) { ?>
327 <div id="ps-tabs-<?php echo $key; ?>">
328 <?php
329 // Print a snippet description is available
330 if ( isset($snippet['description']) )
331 echo '<p class="howto">' . $snippet['description'] . "</p>\n";
332
333 // Get all variables defined for the snippet and output them as input fields
334 $var_arr = explode(",",$snippet['vars']);
335 if (!empty($var_arr[0])) {
336 foreach ($var_arr as $key_2 => $var) { ?>
337 <label for="var_<?php echo $key; ?>_<?php echo $key_2; ?>"><?php echo($var);?>:</label>
338 <input type="text" id="var_<?php echo $key; ?>_<?php echo $key_2; ?>" name="var_<?php echo $key; ?>_<?php echo $key_2; ?>" style="width: 190px" />
339 <br/>
340 <?php
341 }
342 } else {
343 // If no variables and no description available, output a text to inform the user that it's an insert snippet only
344 if ( empty($snippet['description']) )
345 echo '<p class="howto">' . __('This snippet is insert only, no variables defined.', 'post-snippets') . "</p>";
346 }
347 ?>
348 </div><!-- #ps-tabs-## -->
349 <?php
350 }
351 ?>
352 </div><!-- #post-snippets-tabs -->
353 </div><!-- #post-snippets-dialog -->
354 </div><!-- .hidden -->
355 <?php
356 echo "\n<!-- END: Post Snippets UI Dialog -->\n";
357 }
358
359
360 /**
361 * Adds a QuickTag button to the HTML editor.
362 *
363 * Compatible with WordPress 3.3 and newer.
364 *
365 * @see wp-includes/js/quicktags.dev.js -> qt.addButton()
366 * @since Post Snippets 1.8.6
367 */
368 public function add_quicktag_button() {
369 echo "\n<!-- START: Add QuickTag button for Post Snippets -->\n";
370 ?>
371 <script type="text/javascript" charset="utf-8">
372 QTags.addButton( 'post_snippets_id', 'Post Snippets', qt_post_snippets );
373 function qt_post_snippets() {
374 caller = 'html';
375 jQuery( "#post-snippets-dialog" ).dialog( "open" );
376 }
377 </script>
378 <?php
379 echo "\n<!-- END: Add QuickTag button for Post Snippets -->\n";
380 }
381
382
383 /**
384 * Adds a QuickTag button to the HTML editor
385 *
386 * @see wp-includes/js/quicktags.dev.js
387 * @since Post Snippets 1.7
388 * @deprecated Since 1.8.6
389 */
390 function add_quicktag_button_pre33() {
391 echo "\n<!-- START: Post Snippets QuickTag button -->\n";
392 ?>
393 <script type="text/javascript" charset="utf-8">
394 // <![CDATA[
395 //edButton(id, display, tagStart, tagEnd, access, open)
396 edbuttonlength = edButtons.length;
397 edButtons[edbuttonlength++] = new edButton('ed_postsnippets', 'Post Snippets', '', '', '', -1);
398 (function(){
399 if (typeof jQuery === 'undefined') {
400 return;
401 }
402 jQuery(document).ready(function(){
403 jQuery("#ed_toolbar").append('<input type="button" value="Post Snippets" id="ed_postsnippets" class="ed_button" onclick="edOpenPostSnippets(edCanvas);" title="Post Snippets" />');
404 });
405 }());
406 // ]]>
407 </script>
408 <?php
409 echo "\n<!-- END: Post Snippets QuickTag button -->\n";
410 }
411
412
413 /**
414 * Create the functions for shortcodes dynamically and register them
415 */
416 function create_shortcodes() {
417 $snippets = get_option($this->plugin_options);
418 if (!empty($snippets)) {
419 foreach ($snippets as $snippet) {
420 // If shortcode is enabled for the snippet, and a snippet has been entered, register it as a shortcode.
421 if ( $snippet['shortcode'] && !empty($snippet['snippet']) ) {
422
423 $vars = explode(",",$snippet['vars']);
424 $vars_str = '';
425 foreach ($vars as $var) {
426 $vars_str = $vars_str . '"'.$var.'" => "",';
427 }
428
429 add_shortcode($snippet['title'], create_function('$atts,$content=null',
430 '$shortcode_symbols = array('.$vars_str.');
431 extract(shortcode_atts($shortcode_symbols, $atts));
432
433 $attributes = compact( array_keys($shortcode_symbols) );
434
435 // Add enclosed content if available to the attributes array
436 if ( $content != null )
437 $attributes["content"] = $content;
438
439
440 $snippet = \''. addslashes($snippet["snippet"]) .'\';
441 $snippet = str_replace("&", "&amp;", $snippet);
442
443 foreach ($attributes as $key => $val) {
444 $snippet = str_replace("{".$key."}", $val, $snippet);
445 }
446
447 $php = "'. $snippet["php"] .'";
448 if ($php == true) {
449 $snippet = Post_Snippets::php_eval( $snippet );
450 }
451
452 return do_shortcode(stripslashes($snippet));') );
453 }
454 }
455 }
456 }
457
458 /**
459 * Evaluate a snippet as PHP code.
460 *
461 * @since Post Snippets 1.9
462 * @param string $content The snippet to evaluate
463 * @return string The result of the evaluation
464 */
465 public static function php_eval( $content )
466 {
467 $content = stripslashes($content);
468
469 ob_start();
470 eval ($content);
471 $content = ob_get_clean();
472
473 return addslashes( $content );
474 }
475
476 /**
477 * The Admin Page and all it's functions
478 */
479 function wp_admin() {
480 $option_page = add_options_page( 'Post Snippets Options', 'Post Snippets', 'administrator', $this->get_FILE(), array(&$this, 'options_page') );
481 if ( $option_page and class_exists('Post_Snippets_Help') ) {
482 $help = new Post_Snippets_Help( $option_page );
483 }
484 }
485
486 function admin_message($message) {
487 if ( $message ) {
488 ?>
489 <div class="updated"><p><strong><?php echo $message; ?></strong></p></div>
490 <?php
491 }
492 }
493
494 function options_page() {
495 // Add a new Snippet
496 if (isset($_POST['add-snippet'])) {
497 $snippets = get_option($this->plugin_options);
498 if (empty($snippets)) { $snippets = array(); }
499 array_push($snippets, array (
500 'title' => "Untitled",
501 'vars' => "",
502 'description' => "",
503 'shortcode' => false,
504 'php' => false,
505 'snippet' => ""));
506 update_option($this->plugin_options, $snippets);
507 $this->admin_message( __( 'A snippet named Untitled has been added.', 'post-snippets' ) );
508 }
509
510 // Update Snippets
511 if (isset($_POST['update-post-snippets'])) {
512 $snippets = get_option($this->plugin_options);
513 if (!empty($snippets)) {
514 foreach ($snippets as $key => $value) {
515 $new_snippets[$key]['title'] = trim($_POST[$key.'_title']);
516 $new_snippets[$key]['vars'] = str_replace(" ", "", trim($_POST[$key.'_vars']) );
517 $new_snippets[$key]['shortcode'] = isset($_POST[$key.'_shortcode']) ? true : false;
518 $new_snippets[$key]['php'] = isset($_POST[$key.'_php']) ? true : false;
519
520 $new_snippets[$key]['snippet'] = wp_specialchars_decode( trim(stripslashes($_POST[$key.'_snippet'])), ENT_NOQUOTES);
521 $new_snippets[$key]['description'] = wp_specialchars_decode( trim(stripslashes($_POST[$key.'_description'])), ENT_NOQUOTES);
522 }
523 update_option($this->plugin_options, $new_snippets);
524 $this->admin_message( __( 'Snippets have been updated.', 'post-snippets' ) );
525 }
526 }
527
528 // Delete Snippets
529 if (isset($_POST['delete-selected'])) {
530 $snippets = get_option($this->plugin_options);
531 if (!empty($snippets)) {
532 $delete = $_POST['checked'];
533 $newsnippets = array();
534 foreach ($snippets as $key => $snippet) {
535 if (in_array($key,$delete) == false) {
536 array_push($newsnippets,$snippet);
537 }
538 }
539 update_option($this->plugin_options, $newsnippets);
540 $this->admin_message( __( 'Selected snippets have been deleted.', 'post-snippets' ) );
541 }
542 }
543
544 // Handle import of snippets (Run before the option page is outputted, in case any snippets have been imported, so they are displayed).
545 $import = $this->import_snippets();
546
547
548 // Render the settings screen
549 $settings = new Post_Snippets_Settings();
550 $settings->set_options( get_option($this->plugin_options) );
551 $settings->render();
552
553 ?>
554 <h3><?php _e( 'Import/Export', 'post-snippets' ); ?></h3>
555 <strong><?php _e( 'Export', 'post-snippets' ); ?></strong><br/>
556 <form method="post">
557 <p><?php _e( 'Export your snippets for backup or to import them on another site.', 'post-snippets' ); ?></p>
558 <input type="submit" class="button" name="postsnippets_export" value="<?php _e( 'Export Snippets', 'post-snippets');?>"/>
559 </form>
560 <?php
561 $this->export_snippets();
562 echo $import;
563 }
564
565
566 /**
567 * Check if an export file shall be created, or if a download url should be pushed to the footer.
568 * Also checks for old export files laying around and deletes them (for security).
569 *
570 * @since Post Snippets 1.8
571 *
572 * @return string URL to the exported snippets
573 */
574 function export_snippets() {
575 if ( isset($_POST['postsnippets_export']) ) {
576 $url = $this->create_export_file();
577 if ($url) {
578 define('PSURL', $url);
579 function psnippets_footer() {
580 $export .= '<script type="text/javascript">
581 document.location = \''.PSURL.'\';
582 </script>';
583 echo $export;
584 }
585 add_action('admin_footer', 'psnippets_footer', 10000);
586
587 } else {
588 $export .= 'Error: '.$url;
589 }
590 } else {
591 // Check if there is any old export files to delete
592 $dir = wp_upload_dir();
593 $upload_dir = $dir['basedir'] . '/';
594 chdir($upload_dir);
595 if (file_exists ( './post-snippets-export.zip' ) )
596 unlink('./post-snippets-export.zip');
597 }
598 }
599
600 /**
601 * Create a zipped filed containing all Post Snippets, for export.
602 *
603 * @since Post Snippets 1.8
604 *
605 * @return string URL to the exported snippets
606 */
607 function create_export_file() {
608 $snippets = serialize(get_option($this->plugin_options));
609 $dir = wp_upload_dir();
610 $upload_dir = $dir['basedir'] . '/';
611 $upload_url = $dir['baseurl'] . '/';
612
613 // Open a file stream and write the serialized options to it.
614 if ( !$handle = fopen( $upload_dir.'post-snippets-export.cfg', 'w' ) )
615 die();
616 if ( !fwrite($handle, $snippets) )
617 die();
618 fclose($handle);
619
620 // Create a zip archive
621 require_once (ABSPATH . 'wp-admin/includes/class-pclzip.php');
622 chdir($upload_dir);
623 $zip = new PclZip('./post-snippets-export.zip');
624 $zipped = $zip->create('./post-snippets-export.cfg');
625
626 // Delete the snippet file
627 unlink('./post-snippets-export.cfg');
628
629 if (!$zipped)
630 return false;
631
632 return $upload_url.'post-snippets-export.zip';
633 }
634
635 /**
636 * Handles uploading of post snippets archive and import the snippets.
637 *
638 * @uses wp_handle_upload() in wp-admin/includes/file.php
639 * @since Post Snippets 1.8
640 *
641 * @return string HTML to handle the import
642 */
643 function import_snippets() {
644 $import = '<br/><br/><strong>'.__( 'Import', 'post-snippets' ).'</strong><br/>';
645 if ( !isset($_FILES['postsnippets_import_file']) || empty($_FILES['postsnippets_import_file']) ) {
646 $import .= '<p>'.__( 'Import snippets from a post-snippets-export.zip file. Importing overwrites any existing snippets.', 'post-snippets' ).'</p>';
647 $import .= '<form method="post" enctype="multipart/form-data">';
648 $import .= '<input type="file" name="postsnippets_import_file"/>';
649 $import .= '<input type="hidden" name="action" value="wp_handle_upload"/>';
650 $import .= '<input type="submit" class="button" value="'.__( 'Import Snippets', 'post-snippets' ).'"/>';
651 $import .= '</form>';
652 } else {
653 $file = wp_handle_upload( $_FILES['postsnippets_import_file'] );
654
655 if ( isset( $file['file'] ) && !is_wp_error($file) ) {
656 require_once (ABSPATH . 'wp-admin/includes/class-pclzip.php');
657 $zip = new PclZip( $file['file'] );
658 $dir = wp_upload_dir();
659 $upload_dir = $dir['basedir'] . '/';
660 chdir($upload_dir);
661 $unzipped = $zip->extract();
662
663 if ( $unzipped[0]['stored_filename'] == 'post-snippets-export.cfg' && $unzipped[0]['status'] == 'ok') {
664 // Delete the uploaded archive
665 unlink($file['file']);
666
667 $options = file_get_contents( $upload_dir.'post-snippets-export.cfg' ); // Returns false on failure, else the contents
668 if ($options)
669 update_option($this->plugin_options, unserialize($options));
670
671 // Delete the snippet file
672 unlink('./post-snippets-export.cfg');
673
674 $this->admin_message( __( 'Snippets have been updated.', 'post-snippets' ) );
675
676 $import .= '<p><strong>'.__( 'Snippets successfully imported.').'</strong></p>';
677 } else {
678 $import .= '<p><strong>'.__( 'Snippets could not be imported:').' '.__('Unzipping failed.').'</strong></p>';
679 }
680 } else {
681 if ( $file['error'] || is_wp_error( $file ) )
682 $import .= '<p><strong>'.__( 'Snippets could not be imported:').' '.$file['error'].'</strong></p>';
683 else
684 $import .= '<p><strong>'.__( 'Snippets could not be imported:').' '.__('Upload failed.').'</strong></p>';
685 }
686 }
687 return $import;
688 }
689
690 // -------------------------------------------------------------------------
691 // Helpers
692 // -------------------------------------------------------------------------
693
694 /**
695 * Get __FILE__ with no symlinks.
696 *
697 * For development purposes mainly. Returns __FILE__ without resolved
698 * symlinks to be used when __FILE__ is needed while resolving symlinks
699 * breaks WP functionaly, so the actual WordPress path is returned instead.
700 * This makes it possible for all WordPress versions to point to the same
701 * plugin folder for faster testing of the plugin in different WordPress
702 * versions.
703 *
704 * @since Post Snippets 1.9
705 * @return The __FILE__ constant without resolved symlinks.
706 */
707 private function get_FILE()
708 {
709 $dev_path = 'E:\Code\WordPress';
710 $result = strpos( __FILE__, $dev_path );
711
712 if ( $result === false ) {
713 return __FILE__;
714 } else {
715 return str_replace($dev_path, WP_PLUGIN_DIR, __FILE__);
716 }
717 }
718
719 /**
720 * Allow snippets to be retrieved directly from PHP.
721 *
722 * @since Post Snippets 1.8.9.1
723 *
724 * @param string $snippet_name
725 * The name of the snippet to retrieve
726 * @param string $snippet_vars
727 * The variables to pass to the snippet, formatted as a query string.
728 * @return string
729 * The Snippet
730 */
731 public function get_snippet( $snippet_name, $snippet_vars = '' )
732 {
733 $snippets = get_option($this->plugin_options);
734 for ($i = 0; $i < count($snippets); $i++) {
735 if ($snippets[$i]['title'] == $snippet_name) {
736 parse_str( htmlspecialchars_decode($snippet_vars), $snippet_output );
737 $snippet = $snippets[$i]['snippet'];
738 $var_arr = explode(",",$snippets[$i]['vars']);
739
740 if ( !empty($var_arr[0]) ) {
741 for ($j = 0; $j < count($var_arr); $j++) {
742 $snippet = str_replace("{".$var_arr[$j]."}", $snippet_output[$var_arr[$j]], $snippet);
743 }
744 }
745 }
746 }
747 return $snippet;
748 }
749 }
750
751
752 // -----------------------------------------------------------------------------
753 // Start the plugin
754 // -----------------------------------------------------------------------------
755
756 // Check the host environment
757 $test_post_snippets_host = new Post_Snippets_Host_Environment();
758
759 // If environment is up to date, start the plugin
760 if($test_post_snippets_host->passed) {
761 // Load external classes
762 if (is_admin()) {
763 require plugin_dir_path(__FILE__).'classes/settings.php';
764 require plugin_dir_path(__FILE__).'classes/help.php';
765 }
766
767 add_action(
768 'plugins_loaded',
769 create_function(
770 '',
771 'global $post_snippets; $post_snippets = new Post_Snippets();'
772 )
773 );
774 }
775
776
777 /**
778 * Post Snippets Host Environment.
779 *
780 * Checks that the host environment fulfils the requirements of Post Snippets.
781 * This class is designed to work with PHP versions below 5, to make sure it's
782 * always executed.
783 *
784 * - PHP Version 5.2.4 is on par with the requirements for WordPress 3.3.
785 *
786 * @since Post Snippets 1.8.8
787 */
788 class Post_Snippets_Host_Environment
789 {
790 // Minimum versions required
791 var $MIN_PHP_VERSION = '5.2.4';
792 var $MIN_WP_VERSION = '3.0';
793 var $passed = true;
794
795 /**
796 * Constructor.
797 *
798 * Checks PHP and WordPress versions. If any check failes, a system notice
799 * is added and $passed is set to fail, which can be checked before trying
800 * to create the main class.
801 */
802 function Post_Snippets_Host_Environment()
803 {
804 // Check if PHP is too old
805 if (version_compare(PHP_VERSION, $this->MIN_PHP_VERSION, '<')) {
806 // Display notice
807 add_action( 'admin_notices', array(&$this, 'php_version_error') );
808 $this->passed = false;
809 }
810
811 // Check if WordPress is too old
812 global $wp_version;
813 if ( version_compare($wp_version, $this->MIN_WP_VERSION, '<') ) {
814 add_action( 'admin_notices', array(&$this, 'wp_version_error') );
815 $this->passed = false;
816 }
817 }
818
819 /**
820 * Displays a warning when installed on an old PHP version.
821 */
822 function php_version_error() {
823 echo '<div class="error"><p><strong>';
824 printf(
825 'Error: Post Snippets requires PHP version %1$s or greater.<br/>'.
826 'Your installed PHP version: %2$s',
827 $this->MIN_PHP_VERSION, PHP_VERSION);
828 echo '</strong></p></div>';
829 }
830
831 /**
832 * Displays a warning when installed in an old Wordpress version.
833 */
834 function wp_version_error() {
835 echo '<div class="error"><p><strong>';
836 printf(
837 'Error: Post Snippets requires WordPress version %s or greater.',
838 $this->MIN_WP_VERSION );
839 echo '</strong></p></div>';
840 }
841 }
842
843 // -----------------------------------------------------------------------------
844 // Helper functions
845 // -----------------------------------------------------------------------------
846
847 /**
848 * Allow snippets to be retrieved directly from PHP.
849 * This function is a wrapper for Post_Snippets::get_snippet().
850 *
851 * @since Post Snippets 1.6
852 *
853 * @param string $snippet_name
854 * The name of the snippet to retrieve
855 * @param string $snippet_vars
856 * The variables to pass to the snippet, formatted as a query string.
857 * @return string
858 * The Snippet
859 */
860 function get_post_snippet( $snippet_name, $snippet_vars = '' ) {
861 global $post_snippets;
862 return $post_snippets->get_snippet( $snippet_name, $snippet_vars );
863 }
864