<?php
App::uses('AppModel', 'Model');
class File extends AppModel 
{
    public $name = 'File';
    public $useTable = 'files';
    
    public $belongsTo = array('User');
    public $hasMany = array(
        'FileComment' => array(
            'className' => 'FileComment',
            'conditions' => array('FileComment.deleted' => '0'),
            'order' => 'FileComment.created DESC'
        ),
        'FileAttachment' => array(
            'className' => 'FileAttachment',
            'conditions' => array('FileAttachment.deleted' => '0'),
            'order' => 'FileAttachment.file ASC'
        )
    );
    
    public $actsAs = array(
        'Upload.Upload' => array(
            'file' => array(
                'path' => '{ROOT}webroot{DS}data{DS}files{DS}{field}{DS}',
                'fields' => array(
                    'dir' => 'file_dir'
                )
            )
        ),
        'HtmlPurifier.HtmlPurifier' => array(
            'config' => 'basic',
            'fields' => array(
                'title', 'content'
            )
        )
    );
    
    
    public function afterFind($results, $primary = false) 
    {
        if (count($results) > 1) {
            foreach ($results as $key => $result) {
                if ((!empty($result['File']['file'])) && (!empty($result['File']['file_dir']))) {
                    $file = 'data/files/file/' . $result['File']['file_dir'] . '/' . $result['File']['file'];
                    if (file_exists(WWW_ROOT.$file)) {
                        $results[$key]['File']['file'] = '/' . $file;
                    } else {
                        $results[$key]['File']['file'] = '';
                    }
                }
            }
        } elseif (array_key_exists(0, $results)) {
            if ((!empty($results[0]['File']['file'])) && (!empty($results[0]['File']['file_dir']))) {
                $file = 'data/files/file/' . $results[0]['File']['file_dir'] . '/' . $results[0]['File']['file'];
                if (file_exists(WWW_ROOT.$file)) {
                    $results[0]['File']['file'] = '/' . $file;
                } else {
                    $results[0]['File']['file'] = '';
                }
            }
        } else {
            if ((!empty($results['file'])) && (!empty($results['file_dir']))) {
                $file = 'data/files/file/' . $results['file_dir'] . '/' . $results['file'];
                if (file_exists(WWW_ROOT.$file)) {
                    $results['file'] = '/' . $file;
                } else {
                    $results['file'] = '';
                }
            }
        }

        return $results;
    }
    
    public function isOwnedBy($item, $user) 
    {
        return $this->field('id', array('id' => $item, 'user_id' => $user)) !== false;
    }    
}