<?php
/**
 * Browse through the object tree.
 *
 * @param string $path       The level of the tree to browse.
 * @param array $properties  The item properties to return. Defaults to 'name',
 *                           'icon', and 'browseable'.
 *
 * @return array  The contents of $path
 */
function _sfcoop_browse($path = '', $properties = array())
{
    require_once dirname(__FILE__) . '/Bootstrap.php';
    global $registry;

    // Default properties.
    if (!$properties) {
        $properties = array('name', 'icon', 'browseable');
    }

    if (substr($path, 0, 6) == 'sfcoop') {
        $path = substr($path, 6);
    }
    $path = trim($path, '/');

    $manufacturers = _sfcoop_listManufacturers();

    if (empty($path)) {
        $results = array();
        foreach ($manufacturers as $id => $name) {
            $results['sfcoop/' . rawurlencode($name)] =
                array('name' => $name,
                      'icon' => $registry->getImageDir('horde') . '/about.png',
                      'browseable' => true);
        }
        return $results;
    } elseif (strpos($path, '/') === false) {
        $brand = $GLOBALS['b']->find(Horde_RDO::FIND_FIRST, array('name' => $path));
        if (!$brand) {
            $brand = $GLOBALS['b']->find(Horde_RDO::FIND_FIRST, array('name' => urldecode($path)));
        }
        $items = _sfcoop_listItems($brand->id);

        $results = array();
        foreach ($items as $id => $name) {
            $key = 'sfcoop/' . $brand->id . '/' . rawurlencode($name) . '.txt';
            if (in_array('name', $properties)) {
                $results[$key]['name'] = $name;
            }
            if (in_array('displayname', $properties)) {
                $results[$key]['displayname'] = rawurlencode($name);
            }
            if (in_array('icon', $properties)) {
                $results[$key]['icon'] = $registry->getImageDir('horde') . '/about.png';
            }
            if (in_array('browseable', $properties)) {
                $results[$key]['browseable'] = false;
            }
            if (in_array('contenttype', $properties)) {
                $results[$key]['contenttype'] = 'text/plain';
            }
            if (in_array('contentlength', $properties)) {
                $results[$key]['contentlength'] = strlen($GLOBALS['p']->find($id)->toString());
            }
        }
        return $results;
    } else {
        $path = explode('/', $path, 2);
        $name = str_replace('.txt', '', $path[1]);
        $product = $GLOBALS['p']->find(Horde_RDO::FIND_FIRST, array('description' => $name));
        if ($product instanceof Product) {
            return array('data' => $product->toString(),
                         'mimetype' => 'text/plain');
        }
    }

    return PEAR::raiseError($path . ' does not exist or permission denied');
}