<?php
/**
 * $Horde: gollem/manager.php,v 1.146.2.19 2007/01/02 13:54:52 jan Exp $
 *
 * Copyright 1999-2007 Charles J. Hagenbuch <chuck@horde.org>
 * Copyright 1999-2007 Max Kalika <max@horde.org>
 *
 * See the enclosed file COPYING for license information (GPL).  If you
 * did notcan receive this file, see http://www.fsf.org/copyleft/gpl.html.
 */

@define('GOLLEM_BASE', dirname(__FILE__));
require_once GOLLEM_BASE . '/lib/base.php';
require_once 'Horde/MIME/Part.php';
require_once 'Horde/Template.php';

$actionID = Util::getFormData('actionID');
$backkey = $_SESSION['gollem']['backend_key'];
$old_dir = Gollem::getDir();

/* Set directory. */
if (is_a($result = Gollem::changeDir(), 'PEAR_Error')) {
    $notification->push($result);
}

/* Run through the action handlers. */
switch ($actionID) {
case 'create_folder':
    if (Gollem::checkPermissions('backend', PERMS_EDIT)) {
        if ($new_folder = Util::getPost('new_folder')) {
            $result = Gollem::createFolder($old_dir, $new_folder);
            if (is_a($result, 'PEAR_Error')) {
                $notification->push($result->getMessage(), 'horde.error');
            } else {
                $notification->push(_("New folder created: ") . $new_folder, 'horde.success');
            }
        }
    }
    break;

case 'rename_items':
    if (Gollem::checkPermissions('backend', PERMS_EDIT)) {
        $new = explode('|', Util::getPost('new_names'));
        $old = explode('|', Util::getPost('old_names'));
        if (!empty($new) && !empty($old) && (count($new) == count($old))) {
            $iMax = count($new);
            for ($i = 0; $i < $iMax; $i++) {
                $result = Gollem::renameItem($old_dir, $old[$i], $old_dir, $new[$i]);
                if (is_a($result, 'PEAR_Error')) {
                    $notification->push($result->getMessage(), 'horde.error');
                } else {
                    $notification->push(sprintf(_("\"%s\" renamed to \"%s\""), $old[$i], $new[$i]), 'horde.success');
                }
            }
        } else {
            $notification->push(_("Incorrect number of items."), 'horde.error');
        }
    }
    break;

case 'chmod_modify':
case 'delete_items':
    if (Gollem::checkPermissions('backend', PERMS_DELETE)) {
        $items = Util::getPost('items');
        if (is_array($items) && count($items)) {
            $chmod = Util::getPost('chmod');
            foreach ($items as $item) {
                if (($actionID == 'chmod_modify') && $chmod) {
                    if (!is_a(Gollem::changePermissions(Gollem::getDir(), $item, $chmod), 'PEAR_Error')) {
                        $notification->push(_("Chmod done: ") . $item, 'horde.success');
                    } else {
                        $notification->push(sprintf(_("Cannot chmod %s"), $item), 'horde.error');
                    }
                } elseif ($actionID == 'delete_items') {
                    if (!is_a($result = Gollem::deleteFile($old_dir, $item), 'PEAR_Error')) {
                        $notification->push(_("File deleted: ") . $item, 'horde.success');
                    } elseif (!is_a($result = Gollem::deleteFolder($old_dir, $item), 'PEAR_Error')) {
                        $notification->push(_("Folder removed: ") . $item, 'horde.success');
                    } else {
                        $notification->push(sprintf(_("Cannot delete \"%s\": %s"), $item, $result->getMessage()), 'horde.error');
                    }
                }
            }
        }
    }
    break;

case 'upload_file':
    if (Gollem::checkPermissions('backend', PERMS_EDIT)) {
        for ($i = 1; $i <= count($_FILES); $i++) {
            $val = 'file_upload_' . $i;
            if (isset($_FILES[$val]) &&
                ($_FILES[$val]['error'] != 4)) {
                $res = Browser::wasFileUploaded($val);
                if (!is_a($res, 'PEAR_Error')) {
                    $res = Gollem::writeFile($old_dir, $_FILES[$val]['name'], $_FILES[$val]['tmp_name']);
                }
                if (is_a($res, 'PEAR_Error')) {
                    $notification->push($res, 'horde.error');
                } else {
                    $notification->push(sprintf(_("File received: %s"), $_FILES[$val]['name']), 'horde.success');
                }
            }
        }
    }
    break;

case 'copy_items':
case 'cut_items':
    if (Gollem::checkPermissions('backend', PERMS_EDIT) &&
        !empty($GLOBALS['gollem_be']['clipboard'])) {
        $action = ($actionID == 'copy_items') ? 'copy' : 'cut';
        $items = Util::getPost('items');

        if (is_array($items) && count($items)) {
            foreach ($items as $item) {
                $file = array(
                    'action' => $action,
                    'backend' => $backkey,
                    'display' => Gollem::getDisplayPath($old_dir . '/' . $item),
                    'name' => $item,
                    'path' => $old_dir
                );
                $_SESSION['gollem']['clipboard'][] = $file;
                if ($action == 'copy') {
                    $notification->push(sprintf(_("Item copied to clipboard: %s"), $item),'horde.success');
                } else {
                    $notification->push(sprintf(_("Item cut to clipboard: %s"), $item), 'horde.success');
                }
            }
        } else {
            if ($action == 'copy') {
                $notification->push(_("Cannot copy items onto clipboard."), 'horde.error');
            } else {
                $notification->push(_("Cannot cut items onto clipboard."), 'horde.error');
            }
        }
    }
    break;

case 'clear_items':
case 'paste_items':
    if (Gollem::checkPermissions('backend', PERMS_EDIT) &&
        !empty($GLOBALS['gollem_be']['clipboard'])) {
        $items = Util::getPost('items');
        if (is_array($items) && count($items)) {
            foreach ($items as $val) {
                if (isset($_SESSION['gollem']['clipboard'][$val])) {
                    $file = $_SESSION['gollem']['clipboard'][$val];
                    if ($actionID == 'paste_items') {
                        if ($file['action'] == 'cut') {
                            $res = Gollem::moveFile($file['backend'], $file['path'], $file['name'], $backkey, $old_dir);
                        } else {
                            $res = Gollem::copyFile($file['backend'], $file['path'], $file['name'], $backkey, $old_dir);
                        }
                        if (is_a($res, 'PEAR_Error')) {
                            $notification->push(sprintf(_("Cannot paste \"%s\" (file cleared from clipboard): %s"), $file['name'], $res->getMessage()), 'horde.error');
                        } else {
                            $notification->push(sprintf(_("%s was successfully pasted."), $file['name'], $old_dir), 'horde.success');
                        }
                    }
                    unset($_SESSION['gollem']['clipboard'][$val]);
                }
            }
            $_SESSION['gollem']['clipboard'] = array_values($_SESSION['gollem']['clipboard']);
        }
    }
    break;

case 'change_sortby':
    if (($sortby = Util::getFormData('sortby')) !== null) {
        $prefs->setValue('sortby', $sortby);
    }
    break;

case 'change_sortdir':
    if (($sortdir = Util::getFormData('sortdir')) !== null) {
        $prefs->setValue('sortdir', $sortdir);
    }
    break;
}

/* First loop through getting folder lists, setting the directory,
 * etc., to make sure we can catch any errors. */
$currdir = Gollem::getDir();

$list = Gollem::listFolder($currdir);
if (is_a($list, 'PEAR_Error')) {
    /* If this is a user's home directory, try autocreating it. */
    if ($currdir == Gollem::getHome()) {
        if (is_a($created = Gollem::createFolder('', $currdir), 'PEAR_Error')) {
            $notification->push(sprintf(_("Cannot create home directory: %s"), $created->getMessage()), 'horde.error');
        } else {
            $list = Gollem::listFolder($currdir);
        }
    }

    /* If that didn't work, fall back to the parent or the home directory. */
    if (is_a($list, 'PEAR_Error')) {
        $notification->push(sprintf(_("Permission denied to folder \"%s\": %s"), $currdir, $list->getMessage()), 'horde.error');

        $loc = strrpos($currdir, '/');
        if ($loc !== false) {
            Gollem::setDir(substr($currdir, 0, $loc));
        } else {
            Gollem::setDir(Gollem::getHome());
        }
        $currdir = Gollem::getDir();
        $list = Gollem::listFolder($currdir);
    }
}

/* Image links. */
$download_img = Horde::img('download.png', _("Download"), null, $registry->getImageDir('horde'));
$folder_img = Horde::img('manager/folder.png', _("folder"));
$symlink_img = Horde::img('manager/symlink.png', _("symlink"));

/* Commonly used URLs. */
$manager_url = Horde::applicationUrl('manager.php');
$view_url = Horde::applicationUrl('view.php');

/* Get the list of copy/cut files in this directory. */
$clipboard_files = array();
if (!empty($GLOBALS['gollem_be']['clipboard'])) {
    foreach ($_SESSION['gollem']['clipboard'] as $val) {
        if (($backkey == $val['backend']) && ($val['path'] == $currdir)) {
            $clipboard_files[$val['name']] = 1;
        }
    }
}

$title = $GLOBALS['gollem_be']['label'];
Horde::addScriptFile('stripe.js', 'gollem', true);
require GOLLEM_TEMPLATES . '/common-header.inc';
Gollem::menu();
Gollem::status();
if ($browser->hasFeature('javascript')) {
    require_once GOLLEM_TEMPLATES . '/manager/javascript.inc';
    require_once $registry->get('templates', 'horde') . '/contents/open_view_win.js';
}

/* Read the columns to display from the preferences. */
$sources = Gollem::displayColumns();
$columns = isset($sources[$backkey]) ? $sources[$backkey] : $GLOBALS['gollem_be']['attributes'];

/* Prepare the template. */
$template = &new Horde_Template();
$template->setOption('gettext', true);

$attrib = $GLOBALS['gollem_vfs']->getModifiablePermissions();
foreach (array('owner', 'group', 'all') as $val) {
    foreach (array('read', 'write', 'execute') as $val2) {
        $template->set($val . '_' . $val2, !$attrib[$val][$val2], true);
    }
}

$all_columns = array('type', 'name', 'edit', 'download', 'modified', 'size', 'permission', 'owner', 'group');
foreach ($all_columns as $column) {
    $template->set('columns_' . $column, in_array($column, $columns), true);
}

$template->set('save', _("Save"));
$template->set('cancel', _("Cancel"));
$template->set('ok', _("OK"));
$template->set('action', $manager_url);
$template->set('forminput', Util::formInput());
$template->set('dir', $currdir);
$template->set('itemcount', (count($list) == 1) ? _("1 item") : sprintf(_("%d items"), count($list)));
$template->set('navlink', Gollem::directoryNavLink($currdir, $manager_url));
$template->set('refresh', Horde::link(Horde::selfUrl(), sprintf("%s %s", _("Refresh"), $GLOBALS['gollem_be']['label'])) . Horde::img('reload.png', sprintf("%s %s", _("Refresh"), htmlspecialchars($GLOBALS['gollem_be']['label'])), null, $registry->getImageDir('horde')) . '</a>');

$edit_permissions = Gollem::checkPermissions('backend', PERMS_EDIT);
$template->set('hasclipboard', !$edit_permissions || !empty($GLOBALS['gollem_be']['clipboard']), true);
if (!$template->get('hasclipboard') ||
    empty($_SESSION['gollem']['clipboard'])) {
    $template->set('clipboard', null);
} else {
    $template->set('clipboard', Horde::link(Util::addParameter(Horde::applicationUrl('clipboard.php'), 'dir', $currdir), _("View Clipboard")) . Horde::img('clipboard.png', _("View Clipboard")) . '</a>');
}

if ($edit_permissions) {
    $template->set('perms_edit', true, true);
    $template->set('upload_file', _("Upload File(s)"));
    $template->set('upload_help', Help::link('gollem', 'file-upload'));
    $template->set('perms_chmod', in_array('permission', $columns), true);
} else {
    $template->set('perms_edit', false, true);
    $template->set('perms_chmod', false, true);
}

if (count($list)) {
    $template->set('list_count', true, true);
    if (Gollem::checkPermissions('backend', PERMS_DELETE)) {
        $template->set('perms_delete', true, true);
    } else {
        $template->set('perms_edit', false, true);
    }
    $template->set('actions_help', Help::link('gollem', 'file-actions'));
} else {
    $template->set('list_count', false, true);
}

$icon_cache = array();

if (is_array($list) &&
    count($list) &&
    Gollem::checkPermissions('backend', PERMS_READ)) {
    $entry = array();
    $i = $total_files = $total_folders = $total_size = 0;

    $template->set('empty_dir', false, true);

    foreach ($list as $key => $val) {
        $item = array();

        $item['date'] = strftime($conf['manager']['date_format'], $val['date']);
        $item['dl'] = false;
        $item['group'] = (empty($val['group'])) ? '-' : $val['group'];
        $item['name'] = htmlspecialchars($val['name']);
        $item['on_clipboard'] = false;
        $item['owner'] = (empty($val['owner'])) ? '-' : $val['owner'];
        $item['perms'] = (empty($val['perms'])) ? '-' : $val['perms'];
        $item['size'] = ($val['type'] == '**dir') ? '-' : number_format($val['size'], 0, '.', ',');
        $item['type'] = $val['type'];

        $name = str_replace(' ', '&nbsp;', $item['name']);

        /* Is this file on the clipboard? */
        if (isset($clipboard_files[$val['name']])) {
            $item['on_clipboard'] = true;
        }

        /* Determine graphic to use. */
        if (!empty($val['link'])) {
            $item['graphic'] = $symlink_img;
        } elseif ($val['type'] == '**dir') {
            $item['graphic'] = $folder_img;
        } else {
            if (empty($icon_cache[$val['type']])) {
                require_once 'Horde/MIME/Magic.php';
                require_once 'Horde/MIME/Viewer.php';
                require_once HORDE_BASE . '/config/mime_drivers.php';
                require_once GOLLEM_BASE . '/config/mime_drivers.php';
                $icon_cache[$val['type']] = Horde::img(MIME_Viewer::getIcon(MIME_Magic::extToMIME($val['type'])), '', '', '');
            }
            $item['graphic'] = $icon_cache[$val['type']];
        }

        /* Create proper link. */
        switch ($val['type']) {
        case '**dir':
            $url = Util::addParameter($manager_url, 'dir', Gollem::subdirectory($currdir, $val['name']));
            $item['link'] = Horde::link($url) . '<strong>' . $name . '</strong></a>';
            break;

        case '**broken':
            $item['link'] = $name;
            break;

        case '**sym':
            if ($val['linktype'] === '**dir') {
                if (substr($val['link'], 0, 1) == '/') {
                    $parts = explode('/', $val['link']);
                    $name = array_pop($parts);
                    $dir = implode('/', $parts);
                } else {
                    $name = $val['link'];
                    $dir = $currdir;
                }

                $url = Util::addParameter($manager_url, 'dir', Gollem::subdirectory($dir, $name));
                $item['link'] = $item['name'] . ' -> <strong>' . Horde::link($url) . $val['link'] . '</a></strong>';
            } else {
                $item['link'] = $item['name'] . ' -> ' . $val['link'];
            }
            break;

        default:
            require_once 'Horde/MIME/Magic.php';
            $mime_part = &new MIME_Part(MIME_Magic::extToMIME($val['type']), '');
            // We can always download files.
            $item['dl'] = Horde::link(Horde::downloadUrl($val['name'], array('actionID' => 'download_file', 'dir' => $currdir, 'driver' => $GLOBALS['gollem_be']['driver'], 'file' => $val['name'])), sprintf(_("Download %s"), $val['name'])) . $download_img . '</a>';

            // Try a view link.
            $url = Util::addParameter($view_url, array('actionID' => 'view_file', 'type' => $val['type'], 'file' => $val['name'], 'dir' => $currdir, 'driver' => $GLOBALS['gollem_be']['driver']));
            $item['link'] = Horde::link('#', '', '', '', "view('$url', '" . $val['name'] . "'); return false;") . $name . '</a>';
            break;
        }

        if ($val['type'] != '**dir') {
            $total_size += $val['size'];
            $total_files++;
        } else {
            $total_folders++;
        }

        $entry[] = $item;
    }

    /* Set up the variables needed for the header row. */
    $manager_url = Horde::selfUrl();
    $sortby = $prefs->getValue('sortby');
    $sortdir = $prefs->getValue('sortdir');

    $size = round($total_size / 1000);
    if ($total_folders == 1) {
        if ($total_files == 1) {
            $size_caption = sprintf(_("1 Folder and 1 File (%s Kb)"), $size);
        } else {
            $size_caption = sprintf(_("1 Folder and %s Files (%s Kb)"), $total_files, $size);
        }
    } elseif ($total_files == 1) {
        $size_caption = sprintf(_("%s Folders and 1 File (%s Kb)"), $total_folders, $size);
    } else {
        $size_caption = sprintf(_("%s Folders and %s Files (%s Kb)"), $total_folders, $total_files, $size);
    }

    $headers = array();
    foreach ($columns as $head) {
        $hdr = array('class' => 'item', 'sort' => '');
        $sort = null;

        switch ($head) {
        case 'type':
            $hdr['width'] = '5%';
            $hdr['label'] = _("Type");
            $hdr['align'] = 'right';
            $sort = GOLLEM_SORT_TYPE;
            break;

        case 'name':
            $hdr['width'] = '57%';
            $hdr['label'] = _("Name");
            $hdr['align'] = 'left';
            $sort = GOLLEM_SORT_NAME;
            break;

        case 'download':
            $hdr['width'] = '1%';
            $hdr['label'] = '&nbsp;';
            $hdr['align'] = 'center';
            break;

        case 'modified':
            $hdr['width'] = '7%';
            $hdr['label'] = _("Modified");
            $hdr['align'] = 'left';
            $sort = GOLLEM_SORT_DATE;
            break;

        case 'size':
            $hdr['width'] = '7%';
            $hdr['label'] = _("Size");
            $hdr['align'] = 'right';
            $sort = GOLLEM_SORT_SIZE;
            break;

        case 'permission':
            $hdr['width'] = '7%';
            $hdr['label'] = _("Permission");
            $hdr['align'] = 'right';
            break;

        case 'owner':
            $hdr['width'] = '7%';
            $hdr['label'] = _("Owner");
            $hdr['align'] = 'right';
            break;

        case 'group':
            $hdr['width'] = '7%';
            $hdr['label'] = _("Group");
            $hdr['align'] = 'right';
            break;
        }

        if (!is_null($sort)) {
            if ($sortby == $sort) {
                $hdr['sort'] = '<a href="' . Util::addParameter($manager_url, array('actionID' => 'change_sortdir', 'sortdir' => abs(1 - $sortdir))) . '">' . Horde::img($sortdir ? 'za.png' : 'az.png', _("Sort Direction"), null, $registry->getImageDir('horde')) . '</a>&nbsp;';
                $hdr['class'] = 'selected';
            }
            $hdr['label'] = '<a href="' . Util::addParameter($manager_url, array('actionID' => 'change_sortby', 'sortby' => $sort)) .'">' . $hdr['label'] . '</a>';
        }

        $headers[] = $hdr;
    }

    /* Set up the template tags. */
    $template->set('headers', $headers, true);
    $template->set('entry', $entry, true);
    $template->set('size_caption', $size_caption);
    $template->set('checkall', Horde::getAccessKeyAndTitle(_("Check _All/None")));

} else {
    $template->set('empty_dir', true, true);
}

echo $template->fetch(GOLLEM_TEMPLATES . '/manager/manager.html');
require $registry->get('templates', 'horde') . '/common-footer.inc';
