Skip to content
Snippets Groups Projects
class.forms.php 110 KiB
Newer Older
  • Learn to ignore specific revisions
  •                 Form::emitMedia($url, $type);
    
    
        function getAttachments($config=false) {
            if (!$config)
                $config = $this->field->getConfiguration();
    
    
            $field = new FileUploadField(array(
    
                'name'=>'attach:' . $this->field->get('id'),
    
            $field->setForm($this->field->getForm());
            return $field;
    
    class FileUploadWidget extends Widget {
        static $media = array(
            'css' => array(
                '/css/filedrop.css',
            ),
        );
    
    
        function render($options) {
    
            $config = $this->field->getConfiguration();
            $name = $this->field->getFormName();
    
            $id = substr(md5(spl_object_hash($this)), 10);
    
            $attachments = $this->field->getFiles();
    
            $mimetypes = array_filter($config['__mimetypes'],
                function($t) { return strpos($t, '/') !== false; }
            );
    
            $files = array();
    
            foreach ($this->value ?: array() as $fid) {
    
                $found = false;
                foreach ($attachments as $f) {
    
                    $file = $f->file;
    
                    $files[] = array(
                        'id' => $file->getId(),
                        'name' => $file->getName(),
                        'type' => $file->getType(),
                        'size' => $file->getSize(),
    
                        'download_url' => $file->getDownloadUrl(),
    
                ?>" class="filedrop"><div class="files"></div>
                <div class="dropzone"><i class="icon-upload"></i>
    
    Jared Hancock's avatar
    Jared Hancock committed
                <?php echo sprintf(
                    __('Drop files here or %s choose them %s'),
                    '<a href="#" class="manual">', '</a>'); ?>
    
            <input type="file" multiple="multiple"
                id="file-<?php echo $id; ?>" style="display:none;"
    
                accept="<?php echo implode(',', $config['__mimetypes']); ?>"/>
    
            <script type="text/javascript">
    
            $(function(){$('#<?php echo $id; ?> .dropzone').filedropbox({
    
              url: 'ajax.php/form/upload/<?php echo $this->field->get('id') ?>',
    
              link: $('#<?php echo $id; ?>').find('a.manual'),
    
              paramname: 'upload[]',
    
              fallback_id: 'file-<?php echo $id; ?>',
    
              allowedfileextensions: <?php echo JsonDataEncoder::encode(
    
                $config['__extensions'] ?: array()); ?>,
    
              allowedfiletypes: <?php echo JsonDataEncoder::encode(
    
              maxfiles: <?php echo $config['max'] ?: 20; ?>,
    
              maxfilesize: <?php echo ($config['size'] ?: 1048576) / 1048576; ?>,
    
              name: '<?php echo $name; ?>[]',
              files: <?php echo JsonDataEncoder::encode($files); ?>
            });});
            </script>
    <?php
        }
    
        function getValue() {
            $data = $this->field->getSource();
    
            $ids = array();
            // Handle manual uploads (IE<10)
            if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES[$this->name])) {
                foreach (AttachmentFile::format($_FILES[$this->name]) as $file) {
    
                        $F = $this->field->uploadFile($file);
                        $ids[] = $F->getId();
    
                    }
                    catch (FileUploadError $ex) {}
    
                }
                return array_merge($ids, parent::getValue() ?: array());
            }
    
            // If no value was sent, assume an empty list
    
            elseif ($data && is_array($data) && !isset($data[$this->name]))
    
                return array();
    
            return parent::getValue();
        }
    }
    
    
    class FileUploadError extends Exception {}
    
    
    class FreeTextField extends FormField {
        static $widget = 'FreeTextWidget';
    
        function getConfigurationOptions() {
            return array(
                'content' => new TextareaField(array(
    
                    'configuration' => array('html' => true, 'size'=>'large'),
    
                    'label'=>__('Content'), 'required'=>true, 'default'=>'',
                    'hint'=>__('Free text shown in the form, such as a disclaimer'),
                )),
            );
        }
    
        function hasData() {
            return false;
        }
    
        function isBlockLevel() {
            return true;
        }
    }
    
    class FreeTextWidget extends Widget {
    
        function render($options=array()) {
    
            $config = $this->field->getConfiguration();
    
            ?><div class=""><?php
            if ($label = $this->field->getLocal('label')) { ?>
                <h3><?php
                echo Format::htmlchars($label);
            ?></h3><?php
            }
            if ($hint = $this->field->getLocal('hint')) { ?>
            <em><?php
                echo Format::htmlchars($hint);
            ?></em><?php
            } ?>
            <div><?php
    
                echo Format::viewableImages($config['content']); ?></div>
            </div>
            <?php
        }
    }
    
    
    class VisibilityConstraint {
    
        const HIDDEN =      0x0001;
        const VISIBLE =     0x0002;
    
        var $initial;
        var $constraint;
    
        function __construct($constraint, $initial=self::VISIBLE) {
            $this->constraint = $constraint;
            $this->initial = $initial;
        }
    
        function emitJavascript($field) {
            $func = 'recheck';
            $form = $field->getForm();
    ?>
        <script type="text/javascript">
          !(function() {
            var <?php echo $func; ?> = function() {
    
              var target = $('#field<?php echo $field->getWidget()->id; ?>');
    
    
    <?php   $fields = $this->getAllFields($this->constraint);
            foreach ($fields as $f) {
                $field = $form->getField($f);
                echo sprintf('var %1$s = $("#%1$s");',
    
                    $field->getWidget()->id);
    
            }
            $expression = $this->compileQ($this->constraint, $form);
    ?>
    
              if (<?php echo $expression; ?>)
    
    Peter Rotich's avatar
    Peter Rotich committed
                target.slideDown('fast', function (){
    
                    $(this).trigger('show');
                    });
              else
                target.slideUp('fast', function (){
                    $(this).trigger('hide');
                    });
    
            };
    
    <?php   foreach ($fields as $f) {
                $w = $form->getField($f)->getWidget();
    ?>
    
            $('#<?php echo $w->id; ?>').on('change', <?php echo $func; ?>);
    
            $('#field<?php echo $w->id; ?>').on('show hide', <?php
                    echo $func; ?>);
    
    <?php   } ?>
          })();
        </script><?php
        }
    
        /**
         * Determines if the field was visible when the form was submitted
         */
        function isVisible($field) {
            return $this->compileQPhp($this->constraint, $field);
        }
    
        function compileQPhp(Q $Q, $field) {
    
            if (!($form = $field->getForm())) {
                return $this->initial == self::VISIBLE;
            }
    
            $expr = array();
            foreach ($Q->constraints as $c=>$value) {
                if ($value instanceof Q) {
                    $expr[] = $this->compileQPhp($value, $field);
                }
                else {
                    @list($f, $op) = explode('__', $c, 2);
                    $field = $form->getField($f);
                    $wval = $field->getClean();
                    switch ($op) {
                    case 'eq':
                    case null:
    
                        $expr[] = ($wval == $value && $field->isVisible());
    
                    }
                }
            }
            $glue = $Q->isOred()
                ? function($a, $b) { return $a || $b; }
                : function($a, $b) { return $a && $b; };
            $initial = !$Q->isOred();
            $expression = array_reduce($expr, $glue, $initial);
            if ($Q->isNegated)
                $expression = !$expression;
            return $expression;
        }
    
        function getAllFields(Q $Q, &$fields=array()) {
            foreach ($Q->constraints as $c=>$value) {
                if ($c instanceof Q) {
                    $this->getAllFields($c, $fields);
                }
                else {
                    list($f, $op) = explode('__', $c, 2);
                    $fields[$f] = true;
                }
            }
            return array_keys($fields);
        }
    
        function compileQ($Q, $form) {
            $expr = array();
            foreach ($Q->constraints as $c=>$value) {
                if ($value instanceof Q) {
                    $expr[] = $this->compileQ($value, $form);
                }
                else {
                    list($f, $op) = explode('__', $c, 2);
    
                    $widget = $form->getField($f)->getWidget();
                    $id = $widget->id;
    
                    switch ($op) {
                    case 'eq':
    
                        $expr[] = sprintf('(%s.is(":visible") && %s)',
                                $id,
                                sprintf('%s == %s',
                                    sprintf($widget->getJsValueGetter(), $id),
                                    JsonDataEncoder::encode($value))
                                );
    
                    }
                }
            }
            $glue = $Q->isOred() ? ' || ' : ' && ';
            $expression = implode($glue, $expr);
            if (count($expr) > 1)
                $expression = '('.$expression.')';
            if ($Q->isNegated)
                $expression = '!'.$expression;
            return $expression;
        }
    }
    
    
    Peter Rotich's avatar
    Peter Rotich committed
    class AssignmentForm extends Form {
    
        static $id = 'assign';
        var $_assignee = null;
    
    Peter Rotich's avatar
    Peter Rotich committed
        var $_dept = null;
    
    Peter Rotich's avatar
    Peter Rotich committed
    
        function __construct($source=null, $options=array()) {
            parent::__construct($source, $options);
    
    Peter Rotich's avatar
    Peter Rotich committed
            // Department of the object -- if necessary to limit assinees
            if (isset($options['dept']))
                $this->_dept = $options['dept'];
    
    Peter Rotich's avatar
    Peter Rotich committed
        }
    
        function getFields() {
    
            if ($this->fields)
                return $this->fields;
    
            $fields = array(
                'assignee' => new AssigneeField(array(
                        'id'=>1,
                        'label' => __('Assignee'),
                        'flags' => hexdec(0X450F3),
                        'required' => true,
                        'validator-error' => __('Assignee selection required'),
    
    Peter Rotich's avatar
    Peter Rotich committed
                        'configuration' => array(
                            'criteria' => array(
                                'available' => true,
                                ),
                            'dept' => $this->_dept ?: null,
                           ),
    
    Peter Rotich's avatar
    Peter Rotich committed
                        )
                    ),
                'comments' => new TextareaField(array(
                        'id' => 2,
                        'label'=> '',
                        'required'=>false,
                        'default'=>'',
                        'configuration' => array(
                            'html' => true,
    
                            'size' => 'small',
    
    Peter Rotich's avatar
    Peter Rotich committed
                            'placeholder' => __('Optional reason for the assignment'),
                            ),
                        )
                    ),
                );
    
            $this->setFields($fields);
    
            return $this->fields;
        }
    
        function isValid() {
    
            if (!parent::isValid())
                return false;
    
            // Do additional assignment validation
            if (!($assignee = $this->getAssignee())) {
                $this->getField('assignee')->addError(
                        __('Unknown assignee'));
            } elseif ($assignee instanceof Staff) {
                // Make sure the agent is available
                if (!$assignee->isAvailable())
                    $this->getField('assignee')->addError(
                            __('Agent is unavailable for assignment')
                            );
            }
    
            return !$this->errors();
        }
    
        function getClean() {
            return parent::getClean();
        }
    
        function render($options) {
    
            switch(strtolower($options['template'])) {
            case 'simple':
                $inc = STAFFINC_DIR . 'templates/dynamic-form-simple.tmpl.php';
                break;
            default:
                throw new Exception(sprintf(__('%s: Unknown template style %s'),
                            'FormUtils', $options['template']));
            }
    
            $form = $this;
            include $inc;
        }
    
        function getAssignee() {
    
            if (!isset($this->_assignee)) {
                $value = $this->getField('assignee')->getClean();
                if ($value[0] == 's')
                    $this->_assignee = Staff::lookup(substr($value, 1));
                elseif ($value[0] == 't')
                    $this->_assignee = Team::lookup(substr($value, 1));
            }
    
            return $this->_assignee;
        }
    
        function assigneeCriteria() {
            $dept = $this->id;
            return function () use($dept) {
                return array('dept_id' =>$dept);
            };
        }
    }
    
    class TransferForm extends Form {
    
        static $id = 'transfer';
        var $_dept = null;
    
        function __construct($source=null, $options=array()) {
            parent::__construct($source, $options);
        }
    
        function getFields() {
    
            if ($this->fields)
                return $this->fields;
    
            $fields = array(
                'dept' => new DepartmentField(array(
                        'id'=>1,
                        'label' => __('Department'),
                        'flags' => hexdec(0X450F3),
                        'required' => true,
                        'validator-error' => __('Department selection required'),
                        )
                    ),
                'comments' => new TextareaField(array(
                        'id' => 2,
                        'label'=> '',
                        'required'=>false,
                        'default'=>'',
                        'configuration' => array(
                            'html' => true,
    
    Peter Rotich's avatar
    Peter Rotich committed
                            'size' => 'small',
    
    Peter Rotich's avatar
    Peter Rotich committed
                            'placeholder' => __('Optional reason for the transfer'),
                            ),
                        )
                    ),
                );
    
            $this->setFields($fields);
    
            return $this->fields;
        }
    
        function isValid() {
    
            if (!parent::isValid())
                return false;
    
            // Do additional validations
            if (!($dept = $this->getDept()))
                $this->getField('dept')->addError(
                        __('Unknown department'));
    
            return !$this->errors();
        }
    
        function getClean() {
            return parent::getClean();
        }
    
        function render($options) {
    
            switch(strtolower($options['template'])) {
            case 'simple':
                $inc = STAFFINC_DIR . 'templates/dynamic-form-simple.tmpl.php';
                break;
            default:
                throw new Exception(sprintf(__('%s: Unknown template style %s'),
                            get_class(), $options['template']));
            }
    
            $form = $this;
            include $inc;
    
        }
    
        function getDept() {
    
            if (!isset($this->_dept)) {
                if (($id = $this->getField('dept')->getClean()))
                    $this->_dept = Dept::lookup($id);
            }
    
            return $this->_dept;
        }
    }
    
    
    /**
     * FieldUnchanged
     *
     * Thrown in the to_database() method to indicate the value should not be
     * saved in the database (it wasn't changed in the request)
     */
    class FieldUnchanged extends Exception {}