1<?php
2
3/**
4 * File upload field
5 */
6class helper_plugin_bureaucracy_fieldfile extends helper_plugin_bureaucracy_field {
7
8    /**
9     * Arguments:
10     *  - cmd
11     *  - label
12     *  - ^ (optional)
13     *
14     * @param array $args The tokenized definition, only split at spaces
15     */
16    function initialize($args) {
17        $this->init($args);
18
19        //default namespace for file upload (pagepath:file_name)
20        $this->opt['namespace'] = '.';
21
22        //check whenever the first argument is an upload namespace
23        if (isset($args[0]) && preg_match('/^[a-z.\-_:]+$/', $args[0])) {
24            $this->opt['namespace'] = array_shift($args);
25        }
26        $this->standardArgs($args);
27
28        $attr = array();
29        if(!isset($this->opt['optional'])) {
30            $attr['required'] = 'required';
31        }
32
33        $this->tpl = form_makeFileField('@@NAME@@', '@@DISPLAY@@', '@@ID@@', '@@CLASS@@', $attr);
34
35        if(!isset($this->opt['optional'])){
36            $this->tpl['class'] .= ' required';
37        }
38    }
39
40    /**
41     * Handle a post to the field
42     *
43     * Accepts and validates a posted value.
44     *
45     * @param array $value The passed value or array or null if none given
46     * @param helper_plugin_bureaucracy_field[] $fields (reference) form fields (POST handled upto $this field)
47     * @param int    $index  index number of field in form
48     * @param int    $formid unique identifier of the form which contains this field
49     * @return bool Whether the passed filename is valid
50     */
51    public function handle_post($value, &$fields, $index, $formid) {
52        $this->opt['file'] = $value;
53
54        return parent::handle_post($value['name'], $fields, $index, $formid);
55    }
56
57    /**
58     * @throws Exception max size, required or upload error
59     */
60    protected function _validate() {
61        global $lang;
62        parent::_validate();
63
64        $file = $this->getParam('file');
65        if($file['error'] == 1 || $file['error'] == 2) {
66            throw new Exception(sprintf($lang['uploadsize'],filesize_h(php_to_byte(ini_get('upload_max_filesize')))));
67        } else if($file['error'] == 4) {
68            if(!isset($this->opt['optional'])) {
69                throw new Exception(sprintf($this->getLang('e_required'),hsc($this->opt['label'])));
70            }
71        } else if( $file['error'] || !is_uploaded_file($file['tmp_name'])) {
72            throw new Exception(hsc($this->opt['label']) .' '. $lang['uploadfail'] . ' (' .$file['error'] . ')' );
73        }
74    }
75}
76