<?php
/**
 * Populate form element's values from any table
 *
 * $Id$
 *
 * @author gERD Schaufelberger <gerd@php-tools.net>
 * @license PHP License
 * @package WB
 * @subpackage db
 */

WBClass::load('WBDatasource_FormAttribute');

/**
 * Populate form element's values from file lists
 *
 * Use files in directory to populate values
 *
 * @version 1.1.1
 * @package WB
 * @subpackage db
 */
class WBDatasource_FormAttribute_File extends WBDatasource_FormAttribute
{
    const TYPE_FILE =   'file';
    const TYPE_DIR  =   'dir';

    /**
     * configuration parameter
     * @var array
     */
    protected $config   =   array(
                                'folder'        =>  'template/Static',
                                'recursive'     =>  1,
                                'suffix'        =>  '.tmpl',
                                'type'          =>  'file',
                                'withresource'  =>  0
                            );

    /**
     * List of found files to avoid duplicates
     * @var array
     */
    protected $file =   array();

    /**
     * get attribute's value
     *
     * Use dicktionary to fetch list of values
     *
     * @param mixed $current actual attribute value
     * @return array
     */
    protected function getAttributeValue($current)
    {
        if (!is_array($current)) {
            $current =   array();
        }

        $dir    =   array();

        // just one folder
        if (1 > $this->config['withresource']) {
            if ('/' == $this->config['folder'][0]) {
                $dir[]  =   $this->config['folder'];
            }
            else {
                $dir[]  =   WBParam::get('wb/dir/base') . '/' . $this->config['folder'];
            }
        }

        // many folders
        else {
            if ('/' == $this->config['folder'][0]) {
                $dir[]  =   $this->config['folder'];
            }
            else {
                $dir[]  =   WBParam::get('wb/dir/base') . '/' . $this->config['folder'];
                $res    =   WBParam::get('wb/dir/resource', array());
                foreach ($res as $r) {
                    $dir[]  =   $r . '/' . $this->config['folder'];
                }
            }
        }

        foreach ($dir as $d) {
            $this->addFolder($current, $d);
        }

        usort($current, array($this, 'compareValuesByLabel'));
        return $current;
    }

    /**
     * add files of folder
     *
     * recursively scan folder for matching files
     *
     * @param array $current
     * @param string $dir
     * @param string $prefix
     */
    private function addFolder(&$current, $dir, $prefix = '')
    {
        // don't add
        if (!is_dir($dir)) {
            return;
        }

        if (!empty($prefix)) {
            $prefix .=  '/';
        }
        $dh =   new DirectoryIterator($dir);
        foreach ($dh as $i) {
            $name   =   $i->getFilename();
            if (in_array($name, $this->file)) {
                continue;
            }
            $this->file[]   =   $name;

            // hidden files / folders
            if ($i->isDot() || '.' == $name[0]) {
                continue;
            }

            // sub folder
            if ($i->isDir()) {
                if (self::TYPE_DIR == $this->config['type']) {
                    $name       =   $prefix . $name;
                    $current[]  =   array(
                                    'label' =>  str_replace('_', ' ', $name),
                                    'value' =>  $name
                                    );
                }
                if ($this->config['recursive']) {
                    $this->addFolder($current, $i->getRealPath(), $prefix . $i->getFilename());
                }
                continue;
            }


            // see whether suffix matches
            if (strlen($this->config['suffix'])) {
                if (substr($name, -strlen($this->config['suffix'])) != $this->config['suffix']) {
                    continue;
                }
                $name   =   substr($name, 0, -strlen($this->config['suffix']));
            }

            if (self::TYPE_FILE == $this->config['type']) {
                $name       =   $prefix . $name;
                $current[]  =   array(
                                'label' =>  str_replace('_', ' ', $name),
                                'value' =>  $name
                                );
            }
        }
    }
}