PageRenderTime 4ms CodeModel.GetById 9ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/types/embedded/common/wplogger.php

https://gitlab.com/hunglion1368/wordpress-boilerplate
PHP | 308 lines | 151 code | 27 blank | 130 comment | 20 complexity | 9d1feb035a02eae71481205695321144 MD5 | raw file
  1<?php
  2/*
  3 * Modified standalone version of the WPLogger class for internal purposes.
  4 * 
  5 * 
  6 * 
  7 Wordpress Logger
  8 http://www.turingtarpit.com/2009/05/wordpress-logger-a-plugin-to-display-php-log-messages-in-safari-and-firefox/
  9 Displays log messages in the browser console in Safari, Firefox and Opera. Useful for plugin and theme developers to debug PHP code.
 10 0.3
 11 Chandima Cumaranatunge
 12 http://www.turingtarpit.com
 13 
 14	 This program is free software; you can redistribute it and/or modify
 15	 it under the terms of the GNU General Public License as published by
 16	 the Free Software Foundation; either version 2 of the License, or
 17	 (at your option) any later version.
 18	 
 19	 This program is distributed in the hope that it will be useful,
 20	 but WITHOUT ANY WARRANTY; without even the implied warranty of
 21	 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 22	 GNU General Public License for more details.
 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	 Code to force the plugin to load before others adapted from the
 28	 WordPress FirePHP plugin developed by Ivan Weiller.
 29	 http://inchoo.net/wordpress/wordpress-firephp-plugin/
 30	 
 31	 Requirements:
 32	 	* PHP 5+
 33	 	* Wordpress 2.5+
 34	 	* JQuery 1.2.6
 35	 	* Firefox browser with firePHP plugin activated OR
 36	 	  Safari browser with Error Console turned on
 37	 
 38	 Usage:
 39	 	$wplogger->log( mixed php_expression [, const message_type] )
 40	 
 41	 	message_type can be: WPLOG_ERR. WPLOG_WARNING, WPLOG_INFO, WPLOG_DEBUG
 42	 	
 43	 Example:
 44	 	if ($wplogger) $wplogger->log( get_option('active_plugins') );
 45	 	
 46	 Output ( from the browser console ):
 47	 	[Information: from line xxx in file somefile.php] array (
 48		  0 => 'wplogger/wplogger.php',
 49		  1 => '12seconds-widget/12seconds-widget.php',
 50		  2 => 'get-the-image/get-the-image.php',
 51		)
 52 */
 53
 54/* Types of log messages */
 55define( 'WPLOG_ERR', 		'error' ); 	/* Error conditions */
 56define( 'WPLOG_WARNING', 	'warn' ); 	/* Warning conditions */
 57define( 'WPLOG_INFO', 		'info' ); 	/* Informational */
 58define( 'WPLOG_DEBUG', 		'debug' ); 	/* Debug-level messages */
 59define( 'WPLOG_OFF', 		'' ); 	/* NO debug enabled */
 60
 61/* New Wordpress Logger instance */
 62global $wplogger;
 63$wplogger = new WPV_WPLogger();
 64
 65function wplogger( $message = '', $msgType = null ) 
 66{
 67	global $wplogger;
 68	$wplogger->log( $message, $msgType );
 69}
 70
 71/* Register function to add logging script */
 72add_action( 'wp_footer', array($wplogger, 'flushLogMessages') ); // log scripts
 73/* Ensure logging works in admin pages as well */
 74add_action ('admin_footer', array ($wplogger, 'flushLogMessages'));
 75
 76/**
 77 * WPV_WPLogger Class
 78 * renamed for compatibility reasons
 79 */
 80class WPV_WPLogger
 81{
 82
 83    /**
 84     * String holding the buffered output.
 85     */
 86    var $_buffer = array();
 87    
 88    /**
 89     * The default priority to use when logging an event.
 90     */
 91    var $_defaultMsgType = WPLOG_INFO;
 92	
 93	/**
 94	 * Long descriptions of debug message types
 95	 */
 96	var $_msgTypeLong = array(
 97            WPLOG_ERR     => 'error',
 98            WPLOG_WARNING => 'warn',
 99            WPLOG_INFO    => 'info',
100            WPLOG_DEBUG   => 'debug'
101        );
102
103    var $_msgStatusPriority = array(
104    		WPLOG_ERR     => '50',
105            WPLOG_WARNING => '40',
106            WPLOG_INFO    => '30',
107            WPLOG_DEBUG   => '20',
108            WPLOG_OFF	  => '10'
109    	);
110    /**
111     * Writes JavaScript to flush all pending ("buffered") data to
112     * the Firefox or Safari console.
113     *
114     * @notes  requires JQuery 1.2.6 for browser detection.
115     *		   browser detection is deprecated in JQuery 1.3
116     * @see    http://docs.jquery.com/Utilities/jQuery.browser
117     */
118    function flushLogMessages()
119    {
120        if ( count( $this->_buffer ) )
121        {           
122            print '<script type="text/javascript">'."\n";
123            print 'var $j=jQuery.noConflict();'."\n";
124            print 'if (($j.browser.safari || $j.browser.webkit) && window.console) {'."\n";
125            foreach ( $this->_buffer as $line )
126            {
127                printf( 'window.console.%s("%s");', $line[0], $line[1] );
128                print "\n";
129            }
130            print '} else if ($j.browser.mozilla && (\'console\' in window)) {'."\n";
131            foreach ( $this->_buffer as $line )
132            {
133                printf( 'console.%s("%s");', $line[0], $line[1] );
134                print "\n";
135            }
136			print '} else if ($j.browser.opera && window.opera && opera.postError) {'."\n";
137            foreach ( $this->_buffer as $line )
138            {
139                printf( 'opera.postError("%s");', $line[1] );
140                print "\n";
141            }
142            print "}\n";
143            print "</script>\n";
144        }
145        ;
146        $this->_buffer = array();
147    }
148	
149	/**
150	 * Buffers $message to be flushed to the Firebug or Safari console.
151	 * 
152	 * Adapted from the PEAR_Log library
153	 * 
154	 * @return boolean true
155	 * @param mixed  $message String or object containing the message to log.
156	 * @param const $msgType[optional] type of message. Valid values are:
157	 * 					WPLOG_ERR. WPLOG_WARNING, WPLOG_INFO, WPLOG_DEBUG
158	 */
159    function log( $message, $msgType = null )
160    {	
161		/* backtrace */
162		$bTrace = debug_backtrace(); // assoc array
163	
164        /* If a log message type hasn't been specified, use the default value. */
165        if ( $msgType === null )
166        {
167            $msgType = $this->_defaultMsgType;
168        }
169        
170        // verify the status type and output only priority messages (based on wp-config setup)
171        if(!$this->isMsgVisible($msgType)) {
172        	return false;
173        }
174        
175        /* Extract the string representation of the message. */
176        $message = $this->_extractMessage( $message );
177        
178        /* normalize line breaks */
179        $message = str_replace( "\r\n", "\n", $message );
180        
181        /* escape line breaks */
182        $message = str_replace( "\n", "\\n\\\n", $message );
183        
184        /* escape quotes */
185        $message = str_replace( '"', '\\"', $message );
186        
187        /* Build the string containing the complete log line. */
188		$line = sprintf('[%s: from line %d in file %s] %s', 
189								$this->_msgTypeLong[ $msgType ], 
190								$bTrace[0]['line'], 
191								basename($bTrace[0]['file']), 
192								$message );
193        
194        // buffer method and line
195        $this->_buffer[] = array($msgType, $line);
196		
197        return true;
198    }
199    
200    /**
201     * Returns the string representation of the message data (from the PEAR_Log library).
202     *
203     * If $message is an object, _extractMessage() will attempt to extract
204     * the message text using a known method (such as a PEAR_Error object's
205     * getMessage() method).  If a known method, cannot be found, the
206     * serialized representation of the object will be returned.
207     *
208     * If the message data is already a string, it will be returned unchanged.
209     * 
210     * Adapted from the PEAR_Log library
211     *
212     * @param  mixed $message   The original message data.  This may be a
213     *                          string or any object.
214     *
215     * @return string           The string representation of the message.
216     * 
217     */
218    function _extractMessage( $message )
219    {
220        /*
221         * If we've been given an object, attempt to extract the message using
222         * a known method.  If we can't find such a method, default to the
223         * "human-readable" version of the object.
224         *
225         * We also use the human-readable format for arrays.
226         */
227        if ( is_object( $message ) )
228        {
229            if ( method_exists( $message, 'getmessage' ) )
230            {
231                $message = $message->getMessage();
232            }
233            else if ( method_exists( $message, 'tostring' ) )
234            {
235                $message = $message->toString();
236            }
237            else if ( method_exists( $message, '__tostring' ) )
238            {
239                if ( version_compare( PHP_VERSION, '5.0.0', 'ge' ) )
240                {
241                    $message = (string) $message;
242                }
243                else
244                {
245                    $message = $message->__toString();
246                }
247            }
248            else
249            {
250                $message = var_export( $message, true );
251            }
252        }
253        else if ( is_array( $message ) )
254        {
255            if ( isset($message['message']) )
256            {
257                if ( is_scalar( $message['message'] ) )
258                {
259                    $message = $message['message'];
260                }
261                else
262                {
263                    $message = var_export( $message['message'], true );
264                }
265            }
266            else
267            {
268                $message = var_export( $message, true );
269            }
270        }
271        else if ( is_bool( $message ) || $message === NULL )
272        {
273            $message = var_export( $message, true );
274        }
275        
276        /* Otherwise, we assume the message is a string. */
277        return $message;
278    }
279    
280    /**
281     * 
282     * Is the message for the logger visible, i.e. is the status approved for output in the config
283     * 
284     * @param status_type $msg_status the status level
285     */
286    function isMsgVisible($msg_status) {
287    	// verify that status for logging is set
288    	if(!defined('WPV_LOGGING_STATUS')) {
289    		return false;
290    	}
291    	
292    	// use default off status if status not in the list
293    	if(!in_array(WPV_LOGGING_STATUS, $this->_msgTypeLong) ||
294    		!in_array($msg_status, $this->_msgTypeLong)) {
295    		return false;
296    	}
297    	
298    	// verify priorities
299		if( $this->_msgStatusPriority[$msg_status] >=  $this->_msgStatusPriority[WPV_LOGGING_STATUS] ) {
300			
301			return true;
302		}  
303		
304		return false;
305    }
306}
307
308?>