#!/usr/bin/php
<?php

   
/*
    *   PHP source code fixer
    *   ---------------------
    *
    *   Copyright (C) 2006, Daniel Rozsnyo <daniel@rozsnyo.com>
    *
    *   Fixes:
    *           <?         ->   <?php
    *           <?=$foo?>  ->   <?php echo $foo; ?>
    *
    *   Usage:
    *
    *           ./fixphp.php source.php
    *
    *           Will backup the file to source.php.bak and then modify the original file.
    *
    *   Advanced usage (for bash or similar shells):
    *
    *           for i in *.php ; do fixphp.php $i ; done
    *
    *           This will fix all the files in the directory
    *
    */

    // parameer checks
    
if (!isset($argv[1]))   die("Filename required\n");
    if (!
is_file($argv[1])) die("Not a file.\n");

    
// get input
    
$lines file($argv[1]);    
    
    
// create backup
    
file_put_contents($argv[1].'.bak',implode($lines));

    
// process all lines
    
foreach($lines as $k=>$v) {

        
// fix <?=$foo
        
while(1) {
            
$orig $v;
            if (
ereg('(<[?][=])([^?]*)([?]>)',$v,$x)) {
                
$v str_replace($x[1].$x[2].$x[3],'<?php echo '.$x[2].'; ?>',$v);
            }
            if (
$orig===$v) break;
        }

        
// fix <?
        
while(1) {
            
$orig $v;
            if (
ereg('(<[?])([^p])',$v,$x)) {
                
$v str_replace($x[1].$x[2],'<?php'.$x[2],$v);
            }
            if (
$orig===$v) break;
        }
    
        
// fix line ending \r\n -> \n
        
$v str_replace("\r",'',$v);
        
        
// line done.
        
$lines[$k] = $v;
    }

    
// save modified source
    
file_put_contents($argv[1],implode($lines));    

?>