#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - bin/update_php_mime_types           Copyright (C) 2012 cPanel, Inc.
#                                                          All rights Reserved.
# copyright@cpanel.net                                        http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
#

use Getopt::Long;
use Pod::Usage;
use File::Find;
use Cpanel::Config::LoadUserDomains      ();
use Cpanel::AccessIds::ReducedPrivileges ();
use Cpanel::PwCache                      ();
use Cpanel::FileUtils::Move;
use IO::File;
use IO::Handle;
use Carp qw{confess};

my $help;
my $man;
my $recurse_default = 2;
my $recurse_depth   = $recurse_default;
my $strip;
my $only_user;
my $verbose = 0;
my $force_version;
my $target_directory;
my @php_versions = qw{52 53 54 55 56 70 71 edge stable cur};    # Should support PHP6 seamlessly by adding it here

# collect and check arguments
GetOptions(
    'recurse=i'   => \$recurse_depth,
    'strip'       => \$strip,
    'verbose'     => \$verbose,
    'help'        => \$help,
    'man'         => \$man,
    'user=s'      => \$only_user,
    'directory=s' => \$target_directory,
    'force=s'     => \$force_version,
);

if ( $force_version && !$only_user ) {
    die "Error: The --user flag must be used when --force is specified\n";
}

if ( !$force_version && $target_directory && ( ( $recurse_depth != 0 ) || !$only_user ) ) {
    die "Error: The --user and --force flags must be used when --directory is specified\n";
}

unless ( $recurse_depth >= 0 && $recurse_depth <= 100 ) {
    die "Invalid recurse depth ${recurse_depth}";
}

pod2usage(1) if $help;
pod2usage( -exitstatus => 0, -verbose => 2 ) if $man;

# Setup MIME type map

my $php_mime_types = {};
my $found_all      = 1;
print "Determining which MIME types to use\n" if $verbose;
if ( !$strip ) {
    foreach my $php_version (@php_versions) {
        my $example_file = '/usr/local/apache/conf/php' . $php_version . '.htaccess';
        if ( !-e $example_file ) {
            $found_all = 0;
            next;
        }
        local $/ = undef;
        open my $htaccess_fh, '<', $example_file || die "Could not open ${example_file}: $!";
        my $htaccess_text = <$htaccess_fh>;
        close $htaccess_fh;
        if ( $htaccess_text =~ /^AddHandler\s+(\S+)\s+/m ) {
            $php_mime_types->{$php_version} = $1;
            print 'PHP' . $php_version . ': ' . $php_mime_types->{$php_version} . "\n" if $verbose;
        }
        else {
            $found_all = 0;
            print "PHP' . $php_version . ': unknown\n" if $verbose;
        }
    }
}

if ( $strip || !$found_all ) {
    print "Resetting PHP MIME type mappings\n" if $verbose;
    foreach my $php_version (@php_versions) {
        $php_mime_types->{$php_version} = undef;
    }
}

Cpanel::PwCache::no_uid_cache();    #uid cache only needed if we are going to make lots of getpwuid calls
Cpanel::PwCache::init_passwdless_pwcache();
my $pwcache_ref = Cpanel::PwCache::fetch_pwcache();

# setup user list
my %users;
if ($only_user) {
    %users = ( $only_user => 1 );
}
else {
    Cpanel::Config::LoadUserDomains::loadtrueuserdomains( \%users, 1 );
}

print "Beginning iteration over cPanel users list\n" if $verbose;

my $start_depth;
my $user;
my $user_uid;
my $user_gid;
my $homedir;
my $depth_limit;

chdir '/';

foreach my $pw (@$pwcache_ref) {
    next unless exists $users{ $pw->[0] };
    ( $user, $user_uid, $user_gid, $homedir ) = @{$pw}[ 0, 2, 3, 7 ];
    $homedir =~ s/\/+$//;
    print "---\n"               if $verbose;
    print "User: $user\n"       if $verbose;
    print "Homedir: $homedir\n" if $verbose;
    if ( !$homedir || $homedir eq '/root' ) {
        print "Invalid homedir.  Bad username?  Skipping...\n" if $verbose;
        next unless $only_user;
        die "Invalid user: ${only_user}\n";
    }

    eval {
        my $code = sub {
        if ( $only_user && $strip && ( $recurse_depth == 0 )) {
           # print Dumper ( $target_file );
           strip_single_htaccess();
           }
            if ($force_version) {
                my $target_file = $homedir . '/.htaccess';
                if ($target_directory) {
                    if ( -l $target_directory ) {
                        print "Skipping symlinked ${target_directory}\n" if $verbose;
                        next;
                    }
                    if ( !-d _ ) {
                        die "$target_directory does not exist";
                    }
                    if ( ( stat(_) )[4] != $user_uid ) {
                        die "$target_directory not owned by $user";
                    }
                    $target_file = $target_directory . '/.htaccess';
                }
                print "Updating ${target_file}\n" if $verbose;
                if ( -l $target_file ) {
                    print "Skipping symlinked ${target_file}\n" if $verbose;
                    next;
                }
                if ( !-e _ ) {
                    $target_file =~ /(.*)/;
                    $target_file = $1;
                    open my $new_fh, '>', $target_file;
                    close $new_fh;
                }
                elsif ( ( stat(_) )[4] != $user_uid ) {
                    die "${target_file} not owned by $user";
                }
		update_htaccess_file( $target_file, $php_mime_types, 0, $force_version );
                php_phpini ( $target_file, $force_version );
                next;
            }
            $start_depth = $homedir =~ tr{/}{};
            $depth_limit = $start_depth + $recurse_depth;
            File::Find::find(
                {
                    'preprocess' => \&find_preprocess,
                    'wanted'     => \&find_wanted,
                    'no_chdir'   => 1,
                },
                $homedir
            );
            return;
        };
        if ( $> == $user_uid ) {
            $code->();
        }
        else {
            Cpanel::AccessIds::ReducedPrivileges::call_as_user( $code, $user_uid, $user_gid );
        }
    };
    warn $@ if $@;
}

print "Finished processing\n" if $verbose;

sub find_preprocess {

    # Check depth
    my $depth = $File::Find::dir =~ tr{/}{};
    return grep { $_ eq '.htaccess' || !/^(?:mail|tmp|\..*)$/ } @_ if ( $File::Find::dir eq $homedir );
    return @_ if ( $depth < $depth_limit );
    return grep { $_ eq '.htaccess' } @_ if ( $depth == $depth_limit );
    return;
}

sub find_wanted {
    return unless ( $File::Find::name =~ /\/\.htaccess$/ && !-l $File::Find::name && -f _ );
    my ($file_uid) = ( stat(_) )[4];
    return unless ( $file_uid == $user_uid );
    print 'Checking ' . $File::Find::name . "\n" if $verbose;
    update_htaccess_file( $File::Find::name, $php_mime_types, $strip );
}

sub update_htaccess_file {
    my $htaccess_file = shift || die "No input specified";
    my $mime_map      = shift || die "No mime map specified";
    my $strip         = shift;
    my $forced_version = shift;

    $htaccess_file =~ /(.*)/;
    $htaccess_file = $1;
    open my $htaccess_fh, '+<', $htaccess_file
      || die "Could not open ${htaccess_file}: $!";
    my @htaccess = <$htaccess_fh>;

    # quick check if anything will be changed
    unless ( $forced_version
        || grep( /^\s*#?\s*AddHandler\s+\S+\s+.*\.php\b/i, @htaccess )
        || grep( /^\s*#?\s*AddType\s+\S+\s+.*\.php\b/i, @htaccess )
        || grep( /^\s*#\s*Use PHP(cur|edge|stable|\d{1,2})(?: as default)?\s*$/i,      @htaccess ) ) {
        print "No PHP MIME mapping found\n" if $verbose;
        close $htaccess_fh;
        return;
    }

    seek( $htaccess_fh, 0, 0 );
    my $configured_php_version;
    my $written;
    foreach my $line (@htaccess) {
        if ( $line =~ /\s*#\s*Use PHP(cur|edge|stable|\d{1,2})(?: as default)?\s*$/i ) {

            # Found the marker comment
            $configured_php_version = $1;
            if ($strip) {
                undef $configured_php_version;
                next;
            }
            if ($forced_version) {
                $configured_php_version = $forced_version;
                print $htaccess_fh "# Use PHP${forced_version} as default\n";
                next;
            }
            if ( exists $mime_map->{$configured_php_version} ) {
                print $htaccess_fh $line;
                next;
            }
            undef $configured_php_version;
        }
        if (( $line =~ /^\s*#?\s*AddHandler\s+(\S+)\s+(.*\.php\b.*)$/i ) || ( $line =~ /^\s*#?\s*AddType\s+(\S+)\s+(.*\.php\b.*)$/i )) {

            # Found a PHP AddHandler mapping
            my $mime_type  = $1;
            my $extensions = $2;
            chomp $extensions;
            if ($strip) {
                print "Removing AddHandler line\n" if $verbose;
            }
            elsif ( $configured_php_version && defined $mime_map->{$configured_php_version} ) {
                print "Updating AddHandler line for PHP${configured_php_version}\n" if $verbose;
                print $htaccess_fh 'AddHandler ' . $mime_map->{$configured_php_version} . ' ' . $extensions . "\n";
            }
            elsif ( $line =~ /^\s*#/ ) {
                print "Leaving disabled AddHandler comment\n" if $verbose;
                print $htaccess_fh $line;
            }
            else {
                if ( $mime_type =~ /x-httpd-php(\d+)/ ) {
                    $configured_php_version = $1;
                }
                if ($forced_version) {
                    $configured_php_version = $forced_version;
                }
                if ( $configured_php_version && defined $mime_map->{$configured_php_version} ) {
                    print "Updating AddHandler line for PHP${configured_php_version}\n" if $verbose;
                    print $htaccess_fh "# Use PHP${configured_php_version} as default\n";
                    print $htaccess_fh 'AddHandler ' . $mime_map->{$configured_php_version} . ' ' . $extensions . "\n";
                }
                else {
                    print "Disabling AddHandler line\n" if $verbose;
                    print $htaccess_fh '# ' . $line;
                }
            }
            $written = 1 if $configured_php_version;
            undef $configured_php_version;
            next;
        }
        if ($configured_php_version) {

            # last line was a marker comment but no AddHandler line was after it
            if ( defined $mime_map->{$configured_php_version} ) {
                print "Creating new AddHandler line\n" if $verbose;
                print $htaccess_fh 'AddHandler ' . $mime_map->{$configured_php_version} . " .php\n";
            }
            $written = 1;
            undef $configured_php_version;
        }
        print $htaccess_fh $line;
    }

    # Reached end of file
    if ( $configured_php_version && defined $mime_map->{$configured_php_version} ) {

        # last line was the marker comment
        print "Creating new AddHandler line\n" if $verbose;
        if ( $htaccess[-1] !~ /\n$/s ) {
            print $htaccess_fh "\n";
        }
        print $htaccess_fh 'AddHandler ' . $mime_map->{$configured_php_version} . " .php\n";
        $written = 1;
    }
    if ( $forced_version && !$written ) {

        # Add a new marker comment and handler
        print "Creating new AddHandler line\n" if $verbose;
        if ( scalar @htaccess && $htaccess[-1] !~ /\n$/s ) {
            print $htaccess_fh "\n";
        }
        print $htaccess_fh "# Use PHP${forced_version} as default\n";
        if ( defined $mime_map->{$forced_version} ) {
            print $htaccess_fh 'AddHandler ' . $mime_map->{$forced_version} . " .php\n";
        }
    }

    #cleanup
    truncate( $htaccess_fh, tell($htaccess_fh) );
    close $htaccess_fh;
}


sub strip_single_htaccess {
                # print Dumper ( $target_target_directory );
                # if ( undef $target_directory ) {
		# $target_directory = Cpanel::Homedir;
		if ($target_directory) {
                    if ( -l $target_directory ) {
                        print "Skipping symlinked ${target_directory}\n" if $verbose;
                        next;
                    }
                    if ( !-d _ ) {
                        die "$target_directory does not exist";
                    }
                    if ( ( stat(_) )[4] != $user_uid ) {
                        die "$target_directory not owned by $user";
                    }
                    $target_file = $target_directory . '/.htaccess';
                }
                print "Updating ${target_file}\n" if $verbose;
                if ( -l $target_file ) {
                    print "Skipping symlinked ${target_file}\n" if $verbose;
                    next;
                }
                if ( !-e _ ) {
                    $target_file =~ /(.*)/;
                    $target_file = $1;
                    open my $new_fh, '>', $target_file;
                    close $new_fh;
                }
                elsif ( ( stat(_) )[4] != $user_uid ) {
                    die "${target_file} not owned by $user";
                }
                update_htaccess_file( $target_file, $php_mime_types, $strip );
		php_phpini ( $target_file );
                next;
}

sub php_phpini {
my ( $target_file, $php_version ) = @_;
my $phpiniconf = <<"INI_FILE";
<IfModule mod_suphp.c>
    suPHP_ConfigPath /opt/php${php_version}/lib
</IfModule>
INI_FILE

sub first_index {
    my $args = shift;
  INDEXLOOP:
    foreach my $index ( 0 .. scalar @{$args} ) {
            if ( $args->[$index] =~ /^(\#\ BEGIN\ custom\ php\.ini|<IfModule\ mod_suphp\.c>)/ismx ) {
            return $index;
        }
    }
    return;
}

sub second_index {
    my $args2 = shift;
    INDEXLOOP2:
    foreach my $index2 ( 0 .. scalar @{$args2} ) {
	if ( $args2->[$index2] =~ /^AddHandler application\/x-httpd/i ) {
            return $index2;
        }
    }
    return;
}

# $target_file is a file I used for testing that had mod_suphp randomly placed.
if ( ! -e $target_file ){
   Cpanel::FileUtils::TouchFile::touchfile ( $target_file );
   }

my $htaccess_io = IO::File->new( $target_file, O_RDONLY );

if ( !defined $htaccess_io || !$htaccess_io->opened() ) {
    confess("Cannot open $target_file. Please check and ensure it has the correct permissions" );
}

chomp( my @lines = $htaccess_io->getlines() );

# Close file after reading lines into @lines.
$htaccess_io->close();

# Finds the first index of mod_suphp or undef if unfound.
my $start = first_index( \@lines );
my $stop  = undef;
my $start2 = undef;

if ( defined $start ){

LINECHECK:
       foreach my $index ( $start .. $#lines ) {
            if ( $lines[$index] =~ /(?i)<\/ifmodule>(?-i)/xms ) {
                if ( $lines[ $index + 1 ] =~ /^#\ END\ custom\ php.ini/ixms ) {
                    $stop = $index + 2;
                    last LINECHECK;
                }
                else {
                    $stop = $index + 1;
                    last LINECHECK;
                }
            }
        }

# Splice removes the existing lines and replaces them with $phpiniconf.
if ( !defined $php_version ) {
   my $phpini_file = "$target_directory/php.ini";
   splice @lines, $start, ( $stop - $start );
   if ( -e $phpini_file ) {
      Cpanel::FileUtils::Move::safemv( "$phpini_file", "$phpini_file-" . time() );
      }  
   }
else {
     splice @lines, $start, ( $stop - $start ), $phpiniconf;
     }

}
else {
     if ( defined $php_version ){
            $start2 = second_index( \@lines );
            if ( $start2 == 0 ) {
                splice @lines, ($start2), 0, $phpiniconf;
            }
            else {
                splice @lines, ( $start2 + 1 ), 0, $phpiniconf;
            }
        }
    }

# Re-open the file for writing with automatic truncating.
$htaccess_io = IO::File->new( $target_file, O_WRONLY | O_CREAT | O_TRUNC );
if ( !defined $htaccess_io || !$htaccess_io->opened() ) {
    confess('Cannot update .htaccess. Please check and ensure it has the correct permissions');
}

# Write the new lines to the file.
$htaccess_io->write( join qq{\n}, @lines );
$htaccess_io->close();

}

__END__

=head1 NAME

update_php_mime_types - Update user level PHP-MIME mappings

=head1 SYNOPSIS

update_php_mime_types [options]

  Options:
    -help            Brief help message
    -man             Full documentation
    -recurse=#       Recurse depth for finding .htaccess files
    -strip           Remove all PHP AddHandler directives
    -user=<user>     Only check the specified user
    -force=<4|5>     Force the PHP version to the one specified
    -directory=<dir> Force the PHP version in this directory
    -verbose         Display actions as they are performed

=head1 EXAMPLES

=over 8

=item update_php_mime_types --verbose

Update all user .htaccess files that already contain PHP mime mappings.

=item update_php_mime_types --user=fred --force=4 --verbose

Set Fred's main .htaccess file to use PHP 4 by default.

=item update_php_mime_types --user=fred --strip --verbose

Remove all PHP AddHandler lines and marker comments from Fred's .htaccess files.

=back

=head1 OPTIONS

=over 8

=item B<-help>

Display a brief help message and exit.

=item B<-man>

Display the manual page and exit.

=item B<-recurse>

Depth to recurse inside home directories.  The default recurse depth is 2,
meaning that subdirectories within public_html will be checked.

Valid range is 0 to 100.

=item B<-strip>

Remove any PHP AddHandler directives that are found rather than updating them.

=item B<-user>

Only check the .htaccess files of the specified user.

=item B<-force>

Set the main .htaccess file for the user to the specified PHP version.  No changes
will be made to .htaccess files in subdirectories.  The --user flag must be specified in
conjunction with this one.

To reverse this operation without changing any of the PHP MIME mapping in subdirectories, use --user=<user> --strip --recurse=0

=item B<-directory>

Used in conjunction with --force and --user.

Set the PHP MIME type in the specified directory instead of globally for the user.
See CAVEATS for information on maintenance problems this may create.

=item B<-verbose>

Display information about each action performed during the execution of this script.

=back

=head1 DESCRIPTION

This program will read the contents of /usr/local/apache/conf/php4.htaccess and
/usr/local/aapche/conf/php5.htaccess to determine the current MIME type mappings for
PHP 4 and 5.  It will then go through each account's home directory updating their
specified preferences to the correct current MIME types.

This program will NOT update any .htaccess files that are symlinks.  It will also
comment out any PHP AddHandler lines that are not immediately proceeded by the marker
comment:

# Use PHP# as default

The mime type used is based on this comment.

This program may also use this program to set the global PHP mime mapping for an account by
specifying the --user and --force flags together.  This will not change any PHP MIME types
in subdirectories, only the .htaccess file in the user's home directory.

=head1 CAVEATS

If you need to setup a single deeply nested directory to parse .php files with a particular version
of PHP, the preferred method is to symlink /usr/local/apache/conf/php#.htaccess to .htaccess in that
directory.  This will ensure that the MIME type will always be correct one when it is possible to select
between PHP4 and PHP5.  If using a symlink for the .htaccess file is not possible, use the marker comment
specified above and run this program with a suitable -recurse argument each time you change the PHP
configuration in the WebHostManager or via rebuild_phpconf.

=cut
