<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is part of DotClear.
# Copyright (c) 2006 Olivier Meunier and contributors. All rights
# reserved.
#
# DotClear is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# DotClear is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with DotClear; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ***** END LICENSE BLOCK *****

require dirname(__FILE__).'/../inc/admin/prepend.php';

dcPage::checkSuper();

$default_tab = !empty($_REQUEST['tab']) ? html::escapeHTML($_REQUEST['tab']) : 'plugins';

$p_paths = explode(PATH_SEPARATOR, DC_PLUGINS_ROOT);
$p_path = array_pop($p_paths);
unset($p_paths);

$is_writable = false;
if (is_dir($p_path) && is_writeable($p_path)) {
	$is_writable = true;
	$p_path_pat = preg_quote($p_path);
}

if ($is_writable) {
	# Plugin deletion
	if (!empty($_POST['plugin_del']) && is_array($_POST['plugin_del']))
	{
		foreach ($_POST['plugin_del'] as $plugin_id => $v)
		{
			try
			{
				if (!$is_writable) {
					throw new Exception(__('Plugins root is not writable.'));
				}
				
				if (!$core->plugins->moduleExists($plugin_id)) {
					throw new Exception(__('No such plugin.'));
				}
				
				$plugin = $core->plugins->getModules($plugin_id);
				$plugin['id'] = $plugin_id;
				
				if (!preg_match('!^'.$p_path_pat.'!', $plugin['root'])) {
					throw new Exception(__('You don\'t have permissions to delete this plugin.'));
				}
				
				# --BEHAVIOR-- pluginBeforeDelete
				$core->callBehavior('pluginsBeforeDelete', $plugin);
				
				$core->plugins->deleteModule($plugin_id);
				
				# --BEHAVIOR-- pluginAfterDelete
				$core->callBehavior('pluginsAfterDelete', $plugin);
			}
			catch (Exception $e)
			{
				$core->error->add(
					sprintf(__('An error occured while deleting %s plugin:'),html::escapeHTML($plugin['name'])).
					' '.$e->getMessage()
				);
				continue;
			}
		}
		
		if (!$core->error->flag()) {
			http::redirect('plugins.php?removed=1');
		}
	}
	# Plugin upload
	elseif ((!empty($_POST['upload_pkg']) && !empty($_FILES['pkg_file'])) ||
		(!empty($_POST['fetch_pkg']) && !empty($_POST['pkg_url'])))
	{
		try
		{
			if (empty($_POST['your_pwd']) || !$core->auth->checkPassword(crypt::hmac(DC_MASTER_KEY,$_POST['your_pwd']))) {
				throw new Exception(__('Password verification failed'));
			}
			
			if (!empty($_POST['upload_pkg']))
			{
				files::uploadStatus($_FILES['pkg_file']);
				
				$dest = $p_path.'/'.$_FILES['pkg_file']['name'];
				if (!move_uploaded_file($_FILES['pkg_file']['tmp_name'],$dest)) {
					throw new Exception(__('Unable to move uploaded file.'));
				}
			}
			else
			{
				$url = html::escapeHTML($_POST['pkg_url']);
				$dest = $p_path.'/'.basename($url);
				
				try
				{
					$client = netHttp::initClient($url,$path,10);
					$client->setUserAgent('Dotclear - http://www.dotclear.net/');
					$client->useGzip(false);
					$client->setPersistReferers(false);
					$client->setOutput($dest);
					$client->get($path);
				}
				catch( Exception $e)
				{
					throw new Exception(__('An error occured while downloading the file.'));
				}
				
				unset($client);
			}
			
			$ret_code = $core->plugins->installPackage($dest,$core->plugins);
			http::redirect('plugins.php?added='.$ret_code);
		}
		catch (Exception $e)
		{
			$core->error->add($e->getMessage());
			$default_tab = 'addplugin';
		}
	}
}

dcPage::open(__('Plugins management'),
	dcPage::jsLoad('js/_plugins.js').
	dcPage::jsPageTabs($default_tab)
);

echo
'<h2>'.__('Plugins management').'</h2>';

if (!empty($_GET['removed'])) {
	echo
	'<p class="message">'.__('Plugins have been successfully deleted.').'</p>';
}
if (!empty($_GET['added'])) {
	echo	'<p class="message">'.
	($_GET['added'] == 2 ? __('Plugin has been successfully upgraded') : __('Plugin has been successfully installed.')).
	'</p>';
}

# List all active plugins
echo
'<div class="multi-part" id="plugins" title="'.__('Plugins').'">';

$p_available = $core->plugins->getModules();
if (!empty($p_available)) 
{
	echo
	'<form action="plugins.php" method="post" id="form-plugins">'.
	'<table class="clear"><tr>'.
	'<th colspan="2">'.__('Plugin').'</th>'.
	'<th class="nowrap">'.__('Version').'</th>'.
	'<th class="nowrap">'.__('Description').'</th>'.
	'</tr>';

	foreach ($p_available as $k => $v)
	{
		$is_deletable = $is_writable && preg_match('!^'.$p_path_pat.'!',$v['root']);
		
		echo
		'<tr class="line">'.
		'<td>'.($is_deletable ? form::checkbox(array('plugin_del['.html::escapeHTML($k).']'),1) : '').'</td>'.
		'<td class="minimal nowrap">'.html::escapeHTML($v['name']).'</td>'.
		'<td class="minimal">'.html::escapeHTML($v['version']).'</td>'.
		'<td class="maximal">'.html::escapeHTML($v['desc']).'</td>'.
		'</tr>';
	}
	echo
	'</table>'.
	'<p><input type="submit" value="'.__('Remove selected plugins').'" />'.
	$core->formNonce().'</p>'.
	'</form>';
}

echo '</div>';

# Add a new plugin
echo
'<div class="multi-part" id="addplugin" title="'.__('Install or upgrade a plugin').'">';

if ($is_writable)
{
	echo '<p>'.__('You can install plugins by uploading or downloading zip files.').'</p>';
	
	# 'Upload plugin' form
	echo
	'<form method="post" action="plugins.php" id="uploadpkg" enctype="multipart/form-data">'.
	'<fieldset>'.
	'<legend>'.__('Upload a zip file').'</legend>'.
	'<p class="field"><label class="classic required" title="'.__('Required field').'">'.__('Plugin zip file:').' '.
	'<input type="file" name="pkg_file" /></label></p>'.
	'<p class="field"><label class="classic required" title="'.__('Required field').'">'.__('Your password:').' '.
	form::password(array('your_pwd'),20,255).'</label></p>'.
	'<input type="submit" name="upload_pkg" value="'.__('Upload plugin').'" />'.
	$core->formNonce().
	'</fieldset>'.
	'</form>';
	
	# 'Fetch plugin' form
	echo
	'<form method="post" action="plugins.php" id="fetchpkg">'.
	'<fieldset>'.
	'<legend>'.__('Download a zip file').'</legend>'.
	'<p class="field"><label class=" classic required" title="'.__('Required field').'">'.__('Plugin zip file URL:').' '.
	form::field(array('pkg_url'),40,255).'</label></p>'.
	'<p class="field"><label class="classic required" title="'.__('Required field').'">'.__('Your password:').' '.
	form::password(array('your_pwd'),20,255).'</label></p>'.
	'<input type="submit" name="fetch_pkg" value="'.__('Download plugin').'" />'.
	$core->formNonce().
	'</fieldset>'.
	'</form>';
}
else
{
	echo
	'<p class="static-msg">'.
	__('To enable this function, please give write access to your plugins directory.').
	'</p>';
}
echo '</div>';

# --BEHAVIOR-- pluginsToolsTabs
$core->callBehavior('pluginsToolsTabs',$core);

dcPage::close();
?>