PluginProbe
Post Snippets – Custom WordPress Code Snippets Customizer / 1.8.1
Post Snippets – Custom WordPress Code Snippets Customizer v1.8.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.8.1, at post-snippets.php

711 lines 26.9 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.8.1
7 Author: Johan Steen
8 Author URI: http://wpstorm.net/
9 Text Domain: post-snippets
10
11 Copyright 2009-2011 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 var $plugin_options = "post_snippets_options";
30
31 /**
32 * Constructor
33 *
34 */
35 function post_snippets() {
36 // define URL
37 define('post_snippets_ABSPATH', WP_PLUGIN_DIR.'/'.plugin_basename( dirname(__FILE__) ).'/' );
38 define('post_snippets_URLPATH', WP_PLUGIN_URL.'/'.plugin_basename( dirname(__FILE__) ).'/' );
39
40 // Define the domain for translations
41 load_plugin_textdomain( 'post-snippets', false, dirname(plugin_basename(__FILE__)) . '/languages/');
42
43 // Check installed Wordpress version.
44 global $wp_version;
45 if ( version_compare($wp_version, '2.7', '<') ) {
46 add_action( 'admin_notices', array(&$this, 'version_warning') );
47 } else {
48 include_once (dirname (__FILE__)."/tinymce/tinymce.php");
49 $this->init_hooks();
50 }
51 }
52
53 /**
54 * Initializes the hooks for the plugin
55 *
56 * @returns Nothing
57 */
58 function init_hooks() {
59 # Settings link on plugins list
60 add_filter( 'plugin_action_links', array(&$this, 'plugin_action_links'), 10, 2 );
61 # Options Page
62 add_action( 'admin_menu', array(&$this,'wp_admin') );
63
64 $this->create_shortcodes();
65
66 # Adds the JS and HTML code in the header and footer for the jQuery insert UI dialog in the editor
67 add_action( 'admin_init', array(&$this,'enqueue_assets') );
68 add_action( 'admin_head', array(&$this,'jquery_ui_dialog') );
69 add_action( 'admin_footer', array(&$this,'insert_ui_dialog') );
70
71 # Add Editor QuickTag button
72 add_action( 'edit_form_advanced', array(&$this,'add_quicktag_button') );
73 add_action( 'edit_page_form', array(&$this,'add_quicktag_button') );
74 }
75
76
77 /**
78 * Quick link to the Post Snippets Settings page from the Plugins page.
79 *
80 * @returns Array with all the plugin's action links
81 */
82 function plugin_action_links( $links, $file ) {
83 if ( $file == plugin_basename( dirname(__FILE__).'/post-snippets.php' ) ) {
84 $links[] = '<a href="options-general.php?page=post-snippets/post-snippets.php">'.__('Settings', 'post-snippets').'</a>';
85 }
86 return $links;
87 }
88
89 /**
90 * Displays a warning when installed in an old Wordpress Version
91 *
92 * @returns Nothing
93 */
94 function version_warning() {
95 echo '<div class="updated fade"><p><strong>'.__('Post Snippets requires WordPress version 3.0 or higher.', 'post-snippets').'</strong></p></div>';
96 }
97
98 /**
99 * Enqueues the necessary scripts and styles for the plugins
100 *
101 * @since Post Snippets 1.7
102 *
103 * @returns Nothing
104 */
105 function enqueue_assets() {
106 wp_enqueue_script( 'jquery-ui-dialog' );
107 wp_enqueue_script( 'jquery-ui-tabs' );
108 wp_enqueue_style( 'wp-jquery-ui-dialog');
109
110 # Adds the CSS stylesheet for the jQuery UI dialog
111 $style_url = plugins_url( '/assets/post-snippets.css', __FILE__);
112 wp_register_style('post-snippets', $style_url);
113 wp_enqueue_style( 'post-snippets');
114 }
115
116 /**
117 * jQuery control for the dialog and Javascript needed to insert snippets into the editor
118 *
119 * @since Post Snippets 1.7
120 *
121 * @returns Nothing
122 */
123 function jquery_ui_dialog() {
124 echo "\n<!-- START: Post Snippets jQuery UI and related functions -->\n";
125 echo "<script type='text/javascript'>\n";
126
127 # Prepare the snippets and shortcodes into javascript variables
128 # so they can be inserted into the editor, and get the variables replaced
129 # with user defined strings.
130 $snippets = get_option($this->plugin_options);
131 for ($i = 0; $i < count($snippets); $i++) {
132 if ($snippets[$i]['shortcode']) {
133 # Build a long string of the variables, ie: varname1={varname1} varname2={varname2}
134 # so {varnameX} can be replaced at runtime.
135 $var_arr = explode(",",$snippets[$i]['vars']);
136 $variables = '';
137 if (!empty($var_arr[0])) {
138 for ($j = 0; $j < count($var_arr); $j++) {
139 $variables .= ' ' . $var_arr[$j] . '="{' . $var_arr[$j] . '}"';
140 }
141 }
142 $shortcode = $snippets[$i]['title'] . $variables;
143 echo "var postsnippet_{$i} = '[" . $shortcode . "]';\n";
144 } else {
145 $snippet = $snippets[$i]['snippet'];
146 # Fixes for potential collisions:
147 /* Replace <> with char codes, otherwise </script> in a snippet will break it */
148 $snippet = str_replace( '<', '\x3C', str_replace( '>', '\x3E', $snippet ) );
149 /* Escape " with \" */
150 $snippet = str_replace( '"', '\"', $snippet );
151 /* Remove CR and replace LF with \n to keep formatting */
152 $snippet = str_replace( chr(13), '', str_replace( chr(10), '\n', $snippet ) );
153 # Print out the variable containing the snippet
154 echo "var postsnippet_{$i} = \"" . $snippet . "\";\n";
155 }
156 }
157 ?>
158
159 jQuery(document).ready(function($){
160 <?php
161 # Create js variables for all form fields
162 for ($i = 0; $i < count($snippets); $i++) {
163 $var_arr = explode(",",$snippets[$i]['vars']);
164 if (!empty($var_arr[0])) {
165 for ($j = 0; $j < count($var_arr); $j++) {
166 $varname = "var_" . $i . "_" . $j;
167 echo "var {$varname} = $( \"#{$varname}\" );\n";
168 }
169 }
170 }
171 ?>
172
173 var $tabs = $("#post-snippets-tabs").tabs();
174
175 $(function() {
176 $( "#post-snippets-dialog" ).dialog({
177 autoOpen: false,
178 modal: true,
179 dialogClass: 'wp-dialog',
180 buttons: {
181 Cancel: function() {
182 $( this ).dialog( "close" );
183 },
184 "Insert": function() {
185 $( this ).dialog( "close" );
186 var selected = $tabs.tabs('option', 'selected');
187 <?php
188 for ($i = 0; $i < count($snippets); $i++) {
189 ?>
190 if (selected == <?php echo $i; ?>) {
191 insert_snippet = postsnippet_<?php echo $i; ?>;
192 <?php
193 $var_arr = explode(",",$snippets[$i]['vars']);
194 if (!empty($var_arr[0])) {
195 for ($j = 0; $j < count($var_arr); $j++) {
196 $varname = "var_" . $i . "_" . $j; ?>
197 insert_snippet = insert_snippet.replace(/\{<?php echo $var_arr[$j]; ?>\}/g, <?php echo $varname; ?>.val());
198 <?php
199 echo "\n";
200 }
201 }
202 ?>
203 }
204 <?php
205 }
206 ?>
207 edInsertContent(muppCanv, insert_snippet);
208 }
209 },
210 width: 500,
211 });
212 });
213 });
214
215
216 var muppCanv;
217
218
219 function edOpenPostSnippets(myField) {
220 muppCanv = myField;
221 jQuery( "#post-snippets-dialog" ).dialog( "open" );
222 };
223
224
225 <?php
226 echo "</script>\n";
227 echo "\n<!-- END: Post Snippets jQuery UI and related functions -->\n";
228 }
229
230
231
232 /**
233 * Insert Snippet jQuery UI dialog HTML for the post editor
234 *
235 * @since Post Snippets 1.7
236 *
237 * @returns Nothing
238 */
239 function insert_ui_dialog() {
240 echo "\n<!-- START: Post Snippets UI Dialog -->\n";
241 ?>
242 <div class="hidden">
243 <div id="post-snippets-dialog" title="Post Snippets">
244
245 <div id="post-snippets-tabs">
246 <ul>
247 <?php
248 # Create a tab for each available snippet
249 $snippets = get_option($this->plugin_options);
250 for ($i = 0; $i < count($snippets); $i++) { ?>
251 <li><a href="#ps-tabs-<?php echo $i; ?>"><?php echo $snippets[$i]['title']; ?></a></li>
252 <?php } ?>
253 </ul>
254
255 <?php
256 # Create a panel with form fields for each available snippet
257 for ($i = 0; $i < count($snippets); $i++) { ?>
258 <div id="ps-tabs-<?php echo $i; ?>">
259 <?php
260 // Print a snippet description is available
261 if ( isset($snippets[$i]['description']) )
262 echo '<p class="howto">' . $snippets[$i]['description'] . "</p>\n";
263
264 // Get all variables defined for the snippet and output them as input fields
265 $var_arr = explode(",",$snippets[$i]['vars']);
266 if (!empty($var_arr[0])) {
267 for ($j = 0; $j < count($var_arr); $j++) { ?>
268 <label for="var_<?php echo $i; ?>_<?php echo $j; ?>"><?php echo($var_arr[$j]);?>:</label>
269 <input type="text" id="var_<?php echo $i; ?>_<?php echo $j; ?>" name="var_<?php echo $i; ?>_<?php echo $j; ?>" style="width: 190px" />
270 <br/>
271 <?php
272 }
273 } else {
274 // If no variables and no description available, output a text to inform the user that it's an insert snippet only
275 if ( empty($snippets[$i]['description']) )
276 echo '<p class="howto">' . __('This snippet is insert only, no variables defined.', 'post-snippets') . "</p>";
277 }
278 ?>
279 </div><!-- #ps-tabs-## -->
280 <?php
281 }
282 ?>
283 </div><!-- #post-snippets-tabs -->
284 </div><!-- #post-snippets-dialog -->
285 </div><!-- .hidden -->
286 <?php
287 echo "\n<!-- END: Post Snippets UI Dialog -->\n";
288 }
289
290 /**
291 * Adds a QuickTag button to the HTML editor
292 *
293 * @see wp-includes/js/quicktags.dev.js
294 * @since Post Snippets 1.7
295 *
296 * @returns Nothing
297 */
298 function add_quicktag_button() {
299 echo "\n<!-- START: Post Snippets QuickTag button -->\n";
300 ?>
301 <script type="text/javascript" charset="utf-8">
302 // <![CDATA[
303 //edButton(id, display, tagStart, tagEnd, access, open)
304 edbuttonlength = edButtons.length;
305 edButtons[edbuttonlength++] = new edButton('ed_postsnippets', 'Post Snippets', '', '', '', -1);
306 (function(){
307 if (typeof jQuery === 'undefined') {
308 return;
309 }
310 jQuery(document).ready(function(){
311 jQuery("#ed_toolbar").append('<input type="button" value="Post Snippets" id="ed_postsnippets" class="ed_button" onclick="edOpenPostSnippets(edCanvas);" title="Post Snippets" />');
312 });
313 }());
314 // ]]>
315 </script>
316 <?php
317 echo "\n<!-- END: Post Snippets QuickTag button -->\n";
318 }
319
320
321 /**
322 * Create the functions for shortcodes dynamically and register them
323 *
324 */
325 function create_shortcodes() {
326 $snippets = get_option($this->plugin_options);
327 if (!empty($snippets)) {
328 for ($i=0; $i < count($snippets); $i++) {
329 // If shortcode is enabled for the snippet, and a snippet has been entered, register it as a shortcode.
330 if ( $snippets[$i]['shortcode'] && !empty($snippets[$i]['snippet']) ) {
331
332 $vars = explode(",",$snippets[$i]['vars']);
333 $vars_str = '';
334 for ($j=0; $j < count($vars); $j++) {
335 $vars_str = $vars_str . '"'.$vars[$j].'" => "",';
336
337 }
338 add_shortcode($snippets[$i]['title'], create_function('$atts',
339 '$shortcode_symbols = array('.$vars_str.');
340 extract(shortcode_atts($shortcode_symbols, $atts));
341
342 $newArr = compact( array_keys($shortcode_symbols) );
343
344 $snippet = "'. addslashes($snippets[$i]["snippet"]) .'";
345 $snippet = str_replace("&", "&amp;", $snippet);
346
347 foreach ($newArr as $key => $val) {
348 $snippet = str_replace("{".$key."}", $val, $snippet);
349 }
350
351 return do_shortcode(stripslashes($snippet));') );
352 }
353 }
354 }
355 }
356
357
358 /**
359 * The Admin Page and all it's functions
360 *
361 */
362 function wp_admin() {
363 add_action( 'contextual_help', array(&$this,'add_help_text'), 10, 3 );
364 add_options_page( 'Post Snippets Options', 'Post Snippets', 'administrator', __FILE__, array(&$this, 'options_page') );
365 }
366
367 function admin_message($message) {
368 if ( $message ) {
369 ?>
370 <div class="updated"><p><strong><?php echo $message; ?></strong></p></div>
371 <?php
372 }
373 }
374
375 /**
376 * Display contextual help in the help drop down menu at the options page.
377 *
378 * @since Post Snippets 1.7.1
379 *
380 * @returns string The Contextual Help
381 */
382 function add_help_text($contextual_help, $screen_id, $screen) {
383 //$contextual_help .= var_dump($screen); // use this to help determine $screen->id
384 if ( $screen->id == 'settings_page_post-snippets/post-snippets' ) {
385 $contextual_help =
386 '<p><strong>' . __('Title', 'post-snippets') . '</strong></p>' .
387 '<p>' . __('Give the snippet a title that helps you identify it in the post editor. If you make it into a shortcode, this is the name of the shortcode as well.', 'post-snippets') . '</p>' .
388
389 '<p><strong>' . __('Variables', 'post-snippets') . '</strong></p>' .
390 '<p>' . __('A comma separated list of custom variables you can reference in your snippet.<br/><br/>Example:<br/>url,name', 'post-snippets') . '</p>' .
391
392 '<p><strong>' . __('Snippet', 'post-snippets') . '</strong></p>' .
393 '<p>' . __('This is the block of text or HTML to insert in the post when you select the snippet from the insert button in the TinyMCE panel in the post editor. If you have entered predefined variables you can reference them from the snippet by enclosing them in {} brackets.<br/><br/>Example:<br/>To reference the variables in the example above, you would enter {url} and {name}.<br/><br/>So if you enter this snippet:<br/><i>This is the website of &lt;a href="{url}"&gt;{name}&lt;/a&gt;</i><br/>You will get the option to replace url and name on insert if they are defined as variables.', 'post-snippets') . '</p>' .
394
395 '<p><strong>' . __('Description', 'post-snippets') . '</strong></p>' .
396 '<p>' . __('An optional description for the Snippet. If entered it will be displayed in the snippets popup window in the post editor.', 'post-snippets') . '</p>' .
397
398 '<p><strong>' . __('SC', 'post-snippets') . '</strong></p>' .
399 '<p>' . __('Treats the snippet as a shortcode. The name for the shortcode is the same as the title of the snippet (spaces not allowed) and will be used on insert.', 'post-snippets') . '</p>' .
400
401 '<p><strong>' . __('Advanced', 'post-snippets') . '</strong></p>' .
402 '<p>' . __('The snippets can be retrieved directly from PHP, in a theme for instance, with the get_post_snippet() function. Visit the Post Snippets link under more information for instructions.', 'post-snippets') . '</p>' .
403
404 '<p><strong>' . __('For more information:', 'post-snippets') . '</strong></p>' .
405 '<p>' . __('Visit my <a href="http://wpstorm.net/wordpress-plugins/post-snippets/">Post Snippets</a> page for additional information.', 'post-snippets') . '</p>';
406 }
407 return $contextual_help;
408 }
409
410
411 function options_page() {
412 // Add a new Snippet
413 if (isset($_POST['add-snippet'])) {
414 $snippets = get_option($this->plugin_options);
415 if (empty($snippets)) { $snippets = array(); }
416 array_push($snippets, array (
417 'title' => "Untitled",
418 'vars' => "",
419 'description' => "",
420 'shortcode' => false,
421 'quicktag' => false,
422 'php' => false,
423 'snippet' => ""));
424 update_option($this->plugin_options, $snippets);
425 $this->admin_message( __( 'A snippet named Untitled has been added.', 'post-snippets' ) );
426 }
427
428 // Update Snippets
429 if (isset($_POST['update-post-snippets'])) {
430 $snippets = get_option($this->plugin_options);
431 if (!empty($snippets)) {
432 for ($i=0; $i < count($snippets); $i++) {
433 $snippets[$i]['title'] = trim($_POST[$i.'_title']);
434 $snippets[$i]['vars'] = str_replace(" ", "", trim($_POST[$i.'_vars']) );
435 $snippets[$i]['shortcode'] = isset($_POST[$i.'_shortcode']) ? true : false;
436 $snippets[$i]['quicktag'] = isset($_POST[$i.'_quicktag']) ? true : false;
437 $snippets[$i]['php'] = isset($_POST[$i.'_php']) ? true : false;
438 /* Check if the plugin runs on PHP below version 5.1.0
439 Because of a bug in WP 2.7.x in includes/compat.php the htmlspecialchars_decode
440 don't revert back to a PHP 4.x compatible version. So this is a workaround to make
441 the plugin work correctly on PHP versions below 5.1.
442 This problem is fixed in WP 2.8.
443 */
444 if (version_compare(PHP_VERSION, '5.1.0', '<')) {
445 $snippets[$i]['snippet'] = htmlspecialchars_decode( trim(stripslashes($_POST[$i.'_snippet'])), ENT_NOQUOTES);
446 $snippets[$i]['description'] = htmlspecialchars_decode( trim(stripslashes($_POST[$i.'_description'])), ENT_NOQUOTES);
447 } else {
448 $snippets[$i]['snippet'] = wp_specialchars_decode( trim(stripslashes($_POST[$i.'_snippet'])), ENT_NOQUOTES);
449 $snippets[$i]['description'] = wp_specialchars_decode( trim(stripslashes($_POST[$i.'_description'])), ENT_NOQUOTES);
450 }
451 }
452 update_option($this->plugin_options, $snippets);
453 $this->admin_message( __( 'Snippets have been updated.', 'post-snippets' ) );
454 }
455 }
456
457 // Delete Snippets
458 if (isset($_POST['delete-selected'])) {
459 $snippets = get_option($this->plugin_options);
460 if (!empty($snippets)) {
461 $delete = $_POST['checked'];
462 $newsnippets = array();
463 for ($i=0; $i < count($snippets); $i++) {
464 if (in_array($i,$delete) == false) {
465 array_push($newsnippets,$snippets[$i]);
466 }
467 }
468 update_option($this->plugin_options, $newsnippets);
469 $this->admin_message( __( 'Selected snippets have been deleted.', 'post-snippets' ) );
470 }
471 }
472
473 // Handle import of snippets (Run before the option page is outputted, in case any snippets have been imported, so they are displayed).
474 $import = $this->import_snippets();
475 ?>
476 <div class=wrap>
477 <h2>Post Snippets</h2>
478
479 <form method="post" action="">
480 <?php wp_nonce_field('update-options'); ?>
481
482 <div class="tablenav">
483 <div class="alignleft actions">
484 <input type="submit" name="add-snippet" value="<?php _e( 'Add New Snippet', 'post-snippets' ) ?>" class="button-secondary" />
485 <input type="submit" name="delete-selected" value="<?php _e( 'Delete Selected', 'post-snippets' ) ?>" class="button-secondary" />
486 <span class="description"><?php _e( '(Use the help dropdown button above for additional information.)', 'post-snippets' ); ?></span>
487 </div>
488 </div>
489 <div class="clear"></div>
490
491 <table class="widefat fixed" cellspacing="0">
492 <thead>
493 <tr>
494 <th scope="col" class="check-column"><input type="checkbox" /></th>
495 <th scope="col" style="width: 180px;"><?php _e( 'Title', 'post-snippets' ) ?></th>
496 <th scope="col" style="width: 180px;"><?php _e( 'Variables', 'post-snippets' ) ?></th>
497 <th scope="col"><?php _e( 'Snippet', 'post-snippets' ) ?></th>
498 </tr>
499 </thead>
500
501 <tfoot>
502 <tr>
503 <th scope="col" class="check-column"><input type="checkbox" /></th>
504 <th scope="col"><?php _e( 'Title', 'post-snippets' ) ?></th>
505 <th scope="col"><?php _e( 'Variables', 'post-snippets' ) ?></th>
506 <th scope="col"><?php _e( 'Snippet', 'post-snippets' ) ?></th>
507 </tr>
508 </tfoot>
509
510 <tbody>
511 <?php
512 $snippets = get_option($this->plugin_options);
513 if (!empty($snippets)) {
514 for ($i=0; $i < count($snippets); $i++) { ?>
515 <tr class='recent'>
516 <th scope='row' class='check-column'><input type='checkbox' name='checked[]' value='<?php echo $i; ?>' /></th>
517 <td class='row-title'>
518 <input type='text' name='<?php echo $i; ?>_title' value='<?php echo $snippets[$i]['title']; ?>' />
519 </td>
520 <td class='name'>
521 <input type='text' name='<?php echo $i; ?>_vars' value='<?php echo $snippets[$i]['vars']; ?>' /><br/>
522 <input type='checkbox' name='<?php echo $i; ?>_shortcode' value='true'<?php if ($snippets[$i]['shortcode'] == true) { echo " checked"; }?> /> <?php _e( 'Shortcode', 'post-snippets' ) ?><br/>
523 <input type='checkbox' name='<?php echo $i; ?>_quicktag' value='true'<?php if ($snippets[$i]['quicktag'] == true) { echo " checked"; }?> /> <?php _e( 'Quicktag', 'post-snippets' ) ?><br/>
524 <!-- <input type='checkbox' name='< ?php echo $i; ? >_php' value='true'< ?php if ($snippets[$i]['php'] == true) { echo " checked"; }? > /> < ?php _e( 'PHP Code', 'post-snippets' ) ? ><br/> -->
525 </td>
526 <td class='desc'>
527 <textarea name="<?php echo $i; ?>_snippet" class="large-text" style='width: 100%;' rows="5"><?php echo htmlspecialchars($snippets[$i]['snippet'], ENT_NOQUOTES); ?></textarea>
528 <?php _e( 'Description', 'post-snippets' ) ?>:
529 <input type='text' style='width: 100%;' name='<?php echo $i; ?>_description' value='<?php if (isset( $snippets[$i]['description'] ) ) echo esc_html($snippets[$i]['description']); ?>' /><br/>
530 </td>
531 </tr>
532 <?php
533 }
534 }
535 ?>
536 </tbody>
537 </table>
538 <div class="submit">
539 <input type="submit" name="update-post-snippets" value="<?php _e( 'Update Snippets', 'post-snippets' ) ?>" class="button-primary" /></div>
540 </form>
541 </div>
542
543 <h3><?php _e( 'Import/Export', 'post-snippets' ); ?></h3>
544 <strong><?php _e( 'Export', 'post-snippets' ); ?></strong><br/>
545 <form method="post">
546 <p><?php _e( 'Export your snippets for backup or to import them on another site.', 'post-snippets' ); ?></p>
547 <input type="submit" class="button" name="postsnippets_export" value="<?php _e( 'Export Snippets', 'post-snippets');?>"/>
548 </form>
549 <?php
550 $this->export_snippets();
551 echo $import;
552 }
553
554
555 /**
556 * Check if an export file shall be created, or if a download url should be pushed to the footer.
557 * Also checks for old export files laying around and deletes them (for security).
558 *
559 * @since Post Snippets 1.8
560 *
561 * @returns string URL to the exported snippets
562 */
563 function export_snippets() {
564 if ( isset($_POST['postsnippets_export']) ) {
565 $url = $this->create_export_file();
566 if ($url) {
567 define('PSURL', $url);
568 function psnippets_footer() {
569 $export .= '<script type="text/javascript">
570 document.location = \''.PSURL.'\';
571 </script>';
572 echo $export;
573 }
574 add_action('admin_footer', 'psnippets_footer', 10000);
575
576 } else {
577 $export .= 'Error: '.$url;
578 }
579 } else {
580 // Check if there is any old export files to delete
581 $dir = wp_upload_dir();
582 $upload_dir = $dir['basedir'] . '/';
583 chdir($upload_dir);
584 if (file_exists ( './post-snippets-export.zip' ) )
585 unlink('./post-snippets-export.zip');
586 }
587 }
588
589 /**
590 * Create a zipped filed containing all Post Snippets, for export.
591 *
592 * @since Post Snippets 1.8
593 *
594 * @returns string URL to the exported snippets
595 */
596 function create_export_file() {
597 $snippets = serialize(get_option($this->plugin_options));
598 $dir = wp_upload_dir();
599 $upload_dir = $dir['basedir'] . '/';
600 $upload_url = $dir['baseurl'] . '/';
601
602 // Open a file stream and write the serialized options to it.
603 if ( !$handle = fopen( $upload_dir.'post-snippets-export.cfg', 'w' ) )
604 die();
605 if ( !fwrite($handle, $snippets) )
606 die();
607 fclose($handle);
608
609 // Create a zip archive
610 require_once (ABSPATH . 'wp-admin/includes/class-pclzip.php');
611 chdir($upload_dir);
612 $zip = new PclZip('./post-snippets-export.zip');
613 $zipped = $zip->create('./post-snippets-export.cfg');
614
615 // Delete the snippet file
616 unlink('./post-snippets-export.cfg');
617
618 if (!$zipped)
619 return false;
620
621 return $upload_url.'post-snippets-export.zip';
622 }
623
624 /**
625 * Handles uploading of post snippets archive and import the snippets.
626 *
627 * @uses wp_handle_upload() in wp-admin/includes/file.php
628 * @since Post Snippets 1.8
629 *
630 * @returns string HTML to handle the import
631 */
632 function import_snippets() {
633 $import = '<br/><br/><strong>'.__( 'Import', 'post-snippets' ).'</strong><br/>';
634 if ( !isset($_FILES['postsnippets_import_file']) || empty($_FILES['postsnippets_import_file']) ) {
635 $import .= '<p>'.__( 'Import snippets from a post-snippets-export.zip file. Importing overwrites any existing snippets.', 'post-snippets' ).'</p>';
636 $import .= '<form method="post" enctype="multipart/form-data">';
637 $import .= '<input type="file" name="postsnippets_import_file"/>';
638 $import .= '<input type="hidden" name="action" value="wp_handle_upload"/>';
639 $import .= '<input type="submit" class="button" value="'.__( 'Import Snippets', 'post-snippets' ).'"/>';
640 $import .= '</form>';
641 } else {
642 $file = wp_handle_upload( $_FILES['postsnippets_import_file'] );
643
644 if ( isset( $file['file'] ) && !is_wp_error($file) ) {
645 require_once (ABSPATH . 'wp-admin/includes/class-pclzip.php');
646 $zip = new PclZip( $file['file'] );
647 $dir = wp_upload_dir();
648 $upload_dir = $dir['basedir'] . '/';
649 chdir($upload_dir);
650 $unzipped = $zip->extract();
651
652 if ( $unzipped[0]['stored_filename'] == 'post-snippets-export.cfg' && $unzipped[0]['status'] == 'ok') {
653 // Delete the uploaded archive
654 unlink($file['file']);
655
656 $options = file_get_contents( $upload_dir.'post-snippets-export.cfg' ); // Returns false on failure, else the contents
657 if ($options)
658 update_option($this->plugin_options, unserialize($options));
659
660 // Delete the snippet file
661 unlink('./post-snippets-export.cfg');
662
663 $this->admin_message( __( 'Snippets have been updated.', 'post-snippets' ) );
664
665 $import .= '<p><strong>'.__( 'Snippets successfully imported.').'</strong></p>';
666 } else {
667 $import .= '<p><strong>'.__( 'Snippets could not be imported:').' '.__('Unzipping failed.').'</strong></p>';
668 }
669 } else {
670 if ( $file['error'] || is_wp_error( $file ) )
671 $import .= '<p><strong>'.__( 'Snippets could not be imported:').' '.$file['error'].'</strong></p>';
672 else
673 $import .= '<p><strong>'.__( 'Snippets could not be imported:').' '.__('Upload failed.').'</strong></p>';
674 }
675 }
676 return $import;
677 }
678
679 }
680 add_action( 'plugins_loaded', create_function( '', 'global $post_snippets; $post_snippets = new post_snippets();' ) );
681
682
683 /**
684 * Allow snippets to be retrieved directly from PHP
685 *
686 * @since Post Snippets 1.6
687 *
688 * @param string $snippet_name The name of the snippet to retrieve
689 * @param string $snippet_vars The variables to pass to the snippet, formatted as a query string.
690 * @returns string The Snippet
691 */
692 function get_post_snippet( $snippet_name, $snippet_vars = '' ) {
693 global $post_snippets;
694 $snippets = get_option($post_snippets -> plugin_options);
695 for ($i = 0; $i < count($snippets); $i++) {
696 if ($snippets[$i]['title'] == $snippet_name) {
697 parse_str( htmlspecialchars_decode($snippet_vars), $snippet_output );
698 $snippet = $snippets[$i]['snippet'];
699 $var_arr = explode(",",$snippets[$i]['vars']);
700
701 if ( !empty($var_arr[0]) ) {
702 for ($j = 0; $j < count($var_arr); $j++) {
703 $snippet = str_replace("{".$var_arr[$j]."}", $snippet_output[$var_arr[$j]], $snippet);
704 }
705 }
706 }
707 }
708 return $snippet;
709 }
710
711 ?>