moDebug - more readable Debugging

Post custom hacks and enhancements for phpwcms here only. Maybe some of these things will be included in official release later.
Post Reply
User avatar
marcus@localhorst
Posts: 815
Joined: Fri 28. May 2004, 11:31
Location: localhorst
Contact:

moDebug - more readable Debugging

Post by marcus@localhorst »

If you work on modules or some other custom scripts for phpwcms you often need to know which variables are set systemwide or whatever.
you may use print_r($_SESSION); or var_dump($foo) to get arrays of let's say your category or stuff like that.
It's very unreadable for larger multi-dimensional arrays and you get lost in structure depth, so I wrote a frontend_render script, to make it easier.
I've posted an first version here, but today I've did some improvements.

Image

paste this script below in a file called zDebug.php in your template/frontend_render folder.
(zDebug.php because I think it will be included as last script from that folder)
then turn debugging on and use $moDebug['my Vars'] = print_r($foo,1); anywhere in your custom frontend_render scripts or frontend_module scripts (if you develop backend modules it won't work ;-))

Code: Select all

<?php

/**
	PHPWCMS moDebug 1.0 beta (24-Nov-2009)
	this use jQuery (optional mootools) to add a debugging control on top of page for admin only
	basically it use the good old print_r($var,TRUE); to output a bunch of variables
	for checking back while development
	
	use:
		$moDebug['All Global Vars'] = print_r($GLOBALS,1);
	or inside functions:
		$GLOBALS['moDebug']['vars_from_function'] = print_r($var,1);
	nearly anywhere in a custom frontend render or module script
	
	!!!! USE AT YOUR OWN RISK !!!!	
	Be careful if you modify the script and print out sensitiv data to your visitors
	Normally the script only print vars
	if(
	logged in as admin &&
	DEBUG Constante set to 1 &&
	$moDebug[] hold some array data !) 
**/

// turn on debugging
define("DEBUG","0"); // set to 1 in debugging state, set to 0 if you publish your site!
define("JQUERY","0"); // set to 1 if you only use jQuery !

// just some simple testcases
# $moDebug['GET'] = print_r($_GET,TRUE);
# $GLOBALS['moDebug']['Session Variablen'] = print_r($_SESSION,TRUE);
# $moDebug['Phpwcms Config Vars'] = print_r($phpwcms,TRUE); // that will printout the complete phpwcms config incl. passwords and stuff - so be careful!


// ------------------------------------------------------------------------------------------

if(($_SESSION['wcs_user_admin'] == 1 && DEBUG == 1) && is_array($moDebug))
{
  ob_start();
  ?>
  <style type="text/css">
  <!-- 
  #debug {
  	padding: 1em;
  	background: #ffffff;
  	border: 3px solid #f3f3f0;
  	font: 12px 'Lucida Console', Consolas, Fixedsys;
  }
  
  #debug h1 {
  	font: 15px 'Lucida Console', Consolas, Fixedsys;
	font-weight:bold;
	margin-bottom:1em;
	color:#004080;
  }
  
  #debugToggle {
  	position: fixed;
  	top: 30px;
  	right: 3px;
  	width: 16px;
  	height: 16px;
  	padding: 3px;
  	display: block;
  	border: 1px solid #003300;
  	background: white url(./img/famfamfam/information.png) no-repeat center center;
  	text-decoration: none;
  	z-index: 10001;
  }
  
  #debug .indent{font-size:15px;color:#a7a7a7;}
  #debug .code {text-align: left;margin:0;padding:0;margin-left: 50px;} 
  #debug .code i {font-style:normal;color:#004080;}
  #debug .code b {font-weight:normal;color:#800000;} 
  #debug .code li.even {background: #f3f3f0;}
  -->
  </style>

<script type="text/javascript">
/* <![CDATA[ */

<?php if(JQUERY == 1): ?>
jQuery(document).ready(function(){
var debugoutput = $("<div id='debug'>{DEBUG}</div>").hide();
var debugtoggle = $('<a id="debugToggle" href="javascript:void(0);">&nbsp;</a>').bind('click',function(){
	$('#debug').slideToggle();
});
$('body').prepend(debugoutput);	
$('body').append(debugtoggle);
});

<?php else: ?>

// older mootools JS			
window.addEvent({'domready',function(){
        //create debug block which holds the code
        var debug = new Element('div', {
            'id': 'debug'
        });
        //create toggle
        var debugToggle = new Element('a', {
            'events': {
                'click': function(){
                    return false;
                },
                'mousedown': function(e){
                    e = new Event(e);
                    mySlide.toggle();
                    e.stop();
                    
                }
            },
            'id': 'debugToggle',
            'href': 'javascript:void(0);',
            'title': 'moDebug'
        });
        
        
        debugToggle.inject($('fe-link'), 'after'); // add the togglebutton after <body>
        $('debugToggle').setHTML("&nbsp;"); // fill the added element
        debug.injectTop($E('body'));// add after the switch
        $('debug').setHTML("{DEBUG}"); // fill the element with RT
        // some fancy slide in/out
        var mySlide = new Fx.Slide('debug', {
            duration: 250
        }).hide();
        
    }
});

<?php endif; ?>	
/* ]]> */
</script>
<?php
	// put the HTML above into custom_htmlhead array
	$block['custom_htmlhead']["moDebug"] = ob_get_contents();
	ob_end_clean();

	foreach($moDebug as $key => $value)
		$moDebug_out[] = style_debug($value,$key);

	// glue the styled arrays
	$code = @implode("<hr \/>",$moDebug_out);
	// Render the output into html headsection
	$block['custom_htmlhead']["moDebug"] = str_replace('{DEBUG}',$code , $block['custom_htmlhead']["moDebug"]);
}



function style_debug($code,$info)
// inspired by
// http://shiflett.org/blog/2006/oct/formatting-and-highlighting-php-code-listings
{
    $html = array();   
	/* Normalize Newlines */
	$code = str_replace("\r", "\n", $code);
	$code = preg_replace("!\n\n\n+!", "\n\n", $code);
	    
	$lines = explode("\n", $code);
	/* Output Listing */
	$debugoutput = '<h1>Key: '.$info.'<\/h1>';
	$debugoutput .= "<ol class='code'>";
	foreach ($lines as $key=>$line) {
	    if ( empty($line)) {
	        $line = '    ';
	    }
	      
	    $html['line'] = htmlentities($line, ENT_QUOTES, 'UTF-8');
		
		// -- this is experimental colorization
		$key_value_pair = explode(' => ',$html['line']);
		if(preg_match('#\[(.*?)\]#u',$key_value_pair[0],$found)){
			$html['line']  = '<b>'.$key_value_pair[0].'<\/b>';
		} else {
			$html['line']  = '<i>'.$key_value_pair[0].'<\/i>';
		}		
		$html['line'] .=($key_value_pair[1])?' => <i>'.$key_value_pair[1].'<\/i>':'';
		// -- this is experimental colorization
		
	    $html['line'] = preg_replace('#(\s){4}#','<span class=\'indent\'> &rarr; </span>',$html['line']);  
	    if ($key % 2) {
	        $debugoutput .= "<li class='even'>{$html['line']}<\/li>";
	    } else {
	        $debugoutput .= "<li>{$html['line']}<\/li>";
	    }
	}
	$debugoutput .= "<\/ol>";
	
	return $debugoutput;
}

// just another formatted debug function
// http://php.net/manual/de/function.var-dump.php#92594
function dump($value,$level=0)
{
  if ($level==-1)
  {
    $trans[' ']='&there4;';
    $trans["\t"]='&rArr;';
    $trans["\n"]='&para;;';
    $trans["\r"]='&lArr;';
    $trans["\0"]='&oplus;';
    return strtr(htmlspecialchars($value),$trans);
  }
  if ($level==0) echo '<pre class="debug-detailed">';
  $type= gettype($value);
  echo $type;
  if ($type=='string')
  {
    echo '('.strlen($value).')';
    $value= dump($value,-1);
  }
  elseif ($type=='boolean') $value= ($value?'true':'false');
  elseif ($type=='object')
  {
    $props= get_class_vars(get_class($value));
    echo '('.count($props).') <u>'.get_class($value).'</u>';
    foreach($props as $key=>$val)
    {
      echo "\n".str_repeat("\t",$level+1).$key.' => ';
      dump($value->$key,$level+1);
    }
    $value= '';
  }
  elseif ($type=='array')
  {
    echo '('.count($value).')';
    foreach($value as $key=>$val)
    {
      echo "\n".str_repeat("\t",$level+1).'['.dump($key,-1).'] => ';
      dump($val,$level+1);
    }
    $value= '';
  }
  echo " <b>$value</b>";
  if ($level==0) echo '</pre>';
}

?>
cheers m.
User avatar
Oliver Georgi
Site Admin
Posts: 9918
Joined: Fri 3. Oct 2003, 22:22
Contact:

Re: moDebug - more readable Debugging

Post by Oliver Georgi »

Das CMS hat eine simple eigene Variante einer debugging Funktion. Diese kann den Wert direkt in die Ausgabe schreiben oder aber auch als Text zurückgeben.

Code: Select all

// echo
dumpVar($value);

// get string
$dump = dumpVar($string, 2);
echo $dump;
Oliver
Oliver Georgi | phpwcms Developer | GitHub | LinkedIn | Систрон
User avatar
markus s
Moderator
Posts: 654
Joined: Sat 16. Dec 2006, 19:21
Location: Radfeld / Tirol
Contact:

Re: moDebug - more readable Debugging

Post by markus s »

wie ist das einzubauen ?
moderator
propelled by fresh air from tirol
XING|FACEBOOK|OMENTO
User avatar
marcus@localhorst
Posts: 815
Joined: Fri 28. May 2004, 11:31
Location: localhorst
Contact:

Re: moDebug - more readable Debugging

Post by marcus@localhorst »

markus s wrote:wie ist das einzubauen ?
in den frontend_render !

und man kann auch dumpVar() nutzen oder print_r() oder var_dump() ganz ohne den formatierten JavaScript quatsch.
User avatar
markus s
Moderator
Posts: 654
Joined: Sat 16. Dec 2006, 19:21
Location: Radfeld / Tirol
Contact:

Re: moDebug - more readable Debugging

Post by markus s »

danke sagt die community...

eine datei erstellen mit dem namen "z_debugg.php".
dann den obigen code einfügen.

Code: Select all

<?php
// echo
dumpVar($value);

// get string
$dump = dumpVar($string, 2);
echo $dump;
?>
dann diese datei in den ordner - template\inc_script\frontend_render kopieren.
moderator
propelled by fresh air from tirol
XING|FACEBOOK|OMENTO
User avatar
Heiko H.
Posts: 868
Joined: Thu 27. Oct 2005, 11:41
Location: Dresden
Contact:

Re: moDebug - more readable Debugging

Post by Heiko H. »

hmmm,...
...so anstrengend hab ich das nie gestaltet

Code: Select all

<pre>
[PHP]var_dump($GLOBALS);[/PHP]
</pre>
funzt in jedem Template, CP, etc...
Das <pre></pre> ist zur Formatierung, in der "zermatschten" Ausgabe von var_dump() sieht ja kein Schwein durch...
$GLOBALS ist freilich nur ein Beispiel... :wink:

Heiko...
Not longer here - sorry...

Haubner-IT GbR Dresden
User avatar
Oliver Georgi
Site Admin
Posts: 9918
Joined: Fri 3. Oct 2003, 22:22
Contact:

Re: moDebug - more readable Debugging

Post by Oliver Georgi »

VORSICHT!!!! Nutzt $GLOBALS, $phpwcms bitte NIEMALS!!! in einer Liveumgebung.

Mit $GLOBALS, $phpwcms werden auch alle Kennwortinformationen sichtbar!!!

Außerdem wrappt dumpVar() bereits die Ausgabe in <pre> Tag. Die Ausgabe erfolgt auch so, dass HTML Sonderzeichen (<> usw.) als HTML Entity ausgegeben werden.

Es würde bei Nutzung von [PHP] also reichen:

Code: Select all

[PHP]dumpVar($GLOBALS['varname']);[/PHP]
Oliver
Oliver Georgi | phpwcms Developer | GitHub | LinkedIn | Систрон
User avatar
Heiko H.
Posts: 868
Joined: Thu 27. Oct 2005, 11:41
Location: Dresden
Contact:

Re: moDebug - more readable Debugging

Post by Heiko H. »

okay, war'n SEHR unglückliches Beispiel... :oops: :oops: :oops:
Not longer here - sorry...

Haubner-IT GbR Dresden
User avatar
juergen
Moderator
Posts: 4556
Joined: Mon 10. Jan 2005, 18:10
Location: Weinheim
Contact:

Re: moDebug - more readable Debugging

Post by juergen »

<!--LOGGED_IN_START//-->
var_dump ($_wichtig)
....
Post Reply