| @@ -14,18 +14,21 @@ | ||
| 14 | 14 | |
| 15 | 15 | /** |
| 16 | 16 | * Content render |
| 17 | 17 | * |
| 18 | - * @param array $attr | |
| 19 | - * @param string $content | |
| 20 | - * @param string $tag | |
| 18 | + * @param array $attr Shortcode attributes. | |
| 19 | + * @param string $content Enclosed shortcode content. | |
| 20 | + * @param string $tag Shortcode tag. | |
| 21 | + * @return mixed Rendered snippet output, if any. | |
| 21 | 22 | */ |
| 22 | 23 | public function html( $attr, $content, $tag ) { |
| 23 | 24 | $id = $this->get_snippet_id( $attr, WINP_SNIPPET_TYPE_PHP ); |
| 24 | 25 | |
| 25 | 26 | if ( ! $id ) { |
| 26 | - /* translators: %s: Shortcode tag name */ | |
| 27 | - echo '<span style="color:red">' . sprintf( esc_html__( '[%s]: PHP snippets error (not passed the snippet ID)', 'insert-php' ), esc_html( $tag ) ) . '</span>'; | |
| 27 | + if ( current_user_can( 'manage_options' ) || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) { | |
| 28 | + /* translators: %s: Shortcode tag name */ | |
| 29 | + echo '<span style="color:red">' . sprintf( esc_html__( '[%s]: PHP snippets error (not passed the snippet ID)', 'insert-php' ), esc_html( $tag ) ) . '</span>'; | |
| 30 | + } | |
| 28 | 31 | |
| 29 | 32 | return; |
| 30 | 33 | } |
| 31 | 34 | |
| @@ -60,7 +63,35 @@ | ||
| 60 | 63 | |
| 61 | 64 | // Track shortcode execution. |
| 62 | 65 | WINP_Plugin::app()->get_execute_object()->track_shortcode_snippet( $id ); |
| 63 | 66 | |
| 64 | - eval( $snippet_content ); | |
| 67 | + // Initialize error handler. | |
| 68 | + WINP_Error_Handler::init(); | |
| 69 | + | |
| 70 | + // Set current snippet context for error handler. | |
| 71 | + WINP_Error_Handler::set_current_snippet( $id, $snippet->post_title, $snippet_content ); | |
| 72 | + | |
| 73 | + $buffer_level = ob_get_level(); | |
| 74 | + ob_start(); | |
| 75 | + | |
| 76 | + try { | |
| 77 | + eval( $snippet_content ); | |
| 78 | + | |
| 79 | + // Preserve output from buffers opened by the snippet itself. | |
| 80 | + while ( ob_get_level() > $buffer_level + 1 ) { | |
| 81 | + ob_end_flush(); | |
| 82 | + } | |
| 83 | + | |
| 84 | + $snippet_output = ob_get_clean(); | |
| 85 | + return false !== $snippet_output ? $snippet_output : ''; | |
| 86 | + } catch ( Throwable $exception ) { | |
| 87 | + while ( ob_get_level() > $buffer_level ) { | |
| 88 | + ob_end_clean(); | |
| 89 | + } | |
| 90 | + | |
| 91 | + return WINP_Error_Handler::handle_exception( $exception ); | |
| 92 | + } finally { | |
| 93 | + // Clear snippet context after execution. | |
| 94 | + WINP_Error_Handler::clear_current_snippet(); | |
| 95 | + } | |
| 65 | 96 | } |
| 66 | 97 | } |