public function index()
 {
     if (isset($_POST['editsubmit'])) {
         $group['name'] = h(t($_POST['name']));
         $group['intro'] = h(t($_POST['intro']));
         $group['cid0'] = intval($_POST['cid0']);
         // intval($_POST['cid1']) > 0	&& $group['cid1']  = intval($_POST['cid1']);
         $cid1 = D('Category')->_digCateNew($_POST);
         intval($cid1) > 0 && ($group['cid1'] = intval($cid1));
         if (!$group['name']) {
             $this->error('群组名称不能为空');
         } else {
             if (get_str_length($group['name']) > 30) {
                 $this->error('群组名称不能超过30个字');
             }
         }
         if (D('Category')->getField('id', 'name=' . $group['name'])) {
             $this->error('请选择群分类');
         }
         if (get_str_length($group['intro']) > 200) {
             $this->error('群组简介请不要超过200个字');
         }
         // 			if (!preg_replace("/[,\s]*/i", '', $_POST['tags']) || count(array_filter(explode(',', $_POST['tags']))) > 5) {
         // 				$this->error('标签不能为空或者不要超过5个');
         // 			}
         if ($_FILES['logo']['size'] > 0 && is_image_file($_FILES['logo']['name'])) {
             // 群组LOGO
             $options['allow_exts'] = 'jpg,gif,png,jpeg,bmp';
             $options['max_size'] = 2 * 1024 * 1024;
             $options['attach_type'] = 'group_logo';
             $data['upload_type'] = 'image';
             $info = model('Attach')->upload($data, $options);
             if ($info['status']) {
                 $group['logo'] = $info['info'][0]['save_path'] . $info['info'][0]['save_name'];
             }
         }
         $res = $this->group->where('id=' . $this->gid)->save($group);
         if ($res !== false) {
             D('Log')->writeLog($this->gid, $this->mid, '修改群组基本信息', 'setting');
             /* 	// 更新群组标签
             				D('GroupTag')->setGroupTag($_POST['tags'], $this->gid); */
             $this->assign('jumUrl', U('group/Manage/index', array('gid' => $this->gid)));
             $this->success('保存成功');
         }
         $this->error('保存失败');
     }
     //dump($this->groupinfo['tags']);exit;
     // 群组标签
     // 		foreach ($this->groupinfo['tags'] as $v) {
     // 			$_group_tags[] = $v['name'];
     // 		}
     // 		$this->assign('group_tags', implode(',', $_group_tags));
     // 		$this->assign('reTags', D('GroupTag')->getHotTags('recommend'));
     $this->assign('current', 'basic');
     $this->display();
 }
Exemple #2
0
function view_files($filename, $refname)
{
    global $viewer, $diff;
    if (is_image_file($filename)) {
        echo "View: {$refname} {$filename}\n";
        system("{$viewer} {$refname} {$filename}");
    } else {
        # Text file
        echo "===== Compare: {$refname} {$filename}\n";
        system("{$diff} {$refname} {$filename}");
        echo "=====\n";
    }
}
 function list_items($limit = null, $offset = 0, $col = 'name', $order = 'asc')
 {
     $CI =& get_instance();
     $CI->load->helper('array');
     $CI->load->helper('convert');
     if (!isset($this->filters['group_id'])) {
         return array();
     }
     $group_id = $this->filters['group_id'];
     if (strpos($group_id, '/') !== FALSE) {
         $this->filters['group_id'] = uri_safe_encode($group_id);
         // to pass the current folder
     } else {
         $group_id = uri_safe_decode($group_id);
     }
     $asset_dir = $this->get_dir($group_id);
     $assets_path = $CI->asset->assets_server_path . $asset_dir . DIRECTORY_SEPARATOR;
     $tmpfiles = directory_to_array($assets_path, TRUE, $CI->config->item('assets_excluded_dirs', 'fuel'), FALSE);
     $files = get_dir_file_info($assets_path, TRUE);
     $cnt = count($tmpfiles);
     $return = array();
     $asset_type_path = WEB_PATH . $CI->config->item('assets_path') . $asset_dir . '/';
     //for ($i = $offset; $i < $cnt - 1; $i++)
     for ($i = 0; $i < $cnt; $i++) {
         if (!empty($tmpfiles[$i]) && !empty($files[$tmpfiles[$i]])) {
             $key = $tmpfiles[$i];
             if (empty($this->filters['name']) || !empty($this->filters['name']) && (strpos($files[$key]['name'], $this->filters['name']) !== FALSE || strpos($key, $this->filters['name']) !== FALSE)) {
                 $file['id'] = uri_safe_encode(assets_server_to_web_path($files[$tmpfiles[$i]]['server_path'], TRUE));
                 //$file['filename'] = $files[$key]['name'];
                 $file['name'] = $key;
                 $file['last_updated'] = english_date($files[$key]['date'], true);
                 $file['preview/kb'] = $files[$key]['size'];
                 $file['link'] = NULL;
                 $return[] = $file;
             }
         }
     }
     $return = array_sorter($return, $col, $order, TRUE);
     $return = array_slice($return, $offset, $limit);
     // after sorting add the images
     foreach ($return as $key => $val) {
         if (is_image_file($return[$key]['name'])) {
             $return[$key]['preview/kb'] = $return[$key]['preview/kb'] . ' kb <div class="img_crop"><a href="' . $asset_type_path . $return[$key]['name'] . '" target="_blank"><img src="' . $asset_type_path . $return[$key]['name'] . '" border="0"></a></div>';
             $return[$key]['link'] = '<a href="' . $asset_type_path . $return[$key]['name'] . '" target="_blank">' . $asset_dir . '/' . $return[$key]['name'] . '</a>';
         } else {
             $return[$key]['preview/kb'] = $return[$key]['preview/kb'];
             $return[$key]['link'] = '<a href="' . $asset_type_path . $return[$key]['name'] . '" target="_blank">' . $asset_dir . '/' . $return[$key]['name'] . '</a>';
         }
     }
     return $return;
 }
Exemple #4
0
function pieform_element_filebrowser_upload(Pieform $form, $element, $data)
{
    global $USER;
    $parentfolder = $data['uploadfolder'] ? (int) $data['uploadfolder'] : null;
    $institution = !empty($element['institution']) ? $element['institution'] : $form->get_property('institution');
    $group = !empty($element['group']) ? $element['group'] : $form->get_property('group');
    if (get_config('licensemetadata')) {
        $license = $data['license'];
        $licensor = $data['licensor'];
        $licensorurl = $data['licensorurl'];
    }
    $uploadnumber = (int) $data['uploadnumber'];
    $editable = (int) $element['config']['edit'];
    $selectable = (int) $element['config']['select'];
    $querybase = $element['page'] . (strpos($element['page'], '?') === false ? '?' : '&');
    $prefix = $form->get_name() . '_' . $element['name'];
    $userfileindex = isset($data['userfileindex']) ? $data['userfileindex'] : null;
    $resizeonuploadenable = get_config_plugin('artefact', 'file', 'resizeonuploadenable');
    $resizeonuploaduseroption = get_config_plugin('artefact', 'file', 'resizeonuploaduseroption');
    $resizeonuploaduserenable = (int) $data['resizeonuploaduserenable'];
    $result = array('error' => false, 'uploadnumber' => $uploadnumber);
    if ($parentfolder == 0) {
        $parentfolder = null;
    }
    $data = new StdClass();
    $data->parent = $parentfolder;
    $data->owner = $data->group = $data->institution = null;
    if (get_config('licensemetadata')) {
        $data->license = $license;
        $data->licensor = $licensor;
        $data->licensorurl = $licensorurl;
    }
    if ($parentfolder) {
        $parentartefact = artefact_instance_from_id($parentfolder);
        if (!$USER->can_edit_artefact($parentartefact)) {
            $result['error'] = true;
            $result['message'] = get_string('cannoteditfolder', 'artefact.file');
            return $result;
        } else {
            if ($parentartefact->get('locked')) {
                $result['error'] = true;
                $result['message'] = get_string('cannoteditfoldersubmitted', 'artefact.file');
                return $result;
            }
        }
        $parentfoldername = $parentartefact->get('title');
    } else {
        $parentfoldername = null;
    }
    if ($institution) {
        if (!$USER->can_edit_institution($institution)) {
            $result['error'] = true;
            $result['message'] = get_string('notadminforinstitution', 'admin');
            return $result;
        }
        $data->institution = $institution;
    } else {
        if ($group) {
            if (!group_within_edit_window($group)) {
                return array('error' => true, 'message' => get_string('cannoteditfolder', 'artefact.file'));
            }
            if (!$parentfolder) {
                if (!pieform_element_filebrowser_edit_group_folder($group, 0)) {
                    return array('error' => true, 'message' => get_string('cannoteditfolder', 'artefact.file'));
                }
            }
            $data->group = $group;
        } else {
            $data->owner = $USER->get('id');
        }
    }
    $data->container = 0;
    if (isset($userfileindex)) {
        $originalname = $_FILES['userfile']['name'][$userfileindex];
    } else {
        $originalname = $_FILES['userfile']['name'];
    }
    $originalname = $originalname ? basename($originalname) : get_string('file', 'artefact.file');
    $data->title = ArtefactTypeFileBase::get_new_file_title($originalname, $parentfolder, $data->owner, $group, $institution);
    // Overwrite image file with resized version if required
    $resized = false;
    $resizeattempted = false;
    // resize specified if (resizing is enabled AND user has enabled resizing) OR (resizing is enabled AND user is not given an option to enable/disable)
    if ($resizeonuploadenable && $resizeonuploaduserenable || $resizeonuploadenable && !$resizeonuploaduseroption) {
        require_once 'file.php';
        require_once 'imageresizer.php';
        $file = $_FILES['userfile'];
        if (isset($userfileindex)) {
            $tmpname = $file['tmp_name'][$userfileindex];
        } else {
            $tmpname = $file['tmp_name'];
        }
        if (is_image_file($tmpname)) {
            $imageinfo = getimagesize($tmpname);
            $mimetype = $imageinfo['mime'];
            $width = $imageinfo[0];
            $height = $imageinfo[1];
            $bmptypes = array('image/bmp', 'image/x-bmp', 'image/ms-bmp', 'image/x-ms-bmp');
            // resize image if necessary
            $resizeonuploadmaxwidth = get_config_plugin('artefact', 'file', 'resizeonuploadmaxwidth');
            $resizeonuploadmaxheight = get_config_plugin('artefact', 'file', 'resizeonuploadmaxheight');
            // Don't support bmps for now
            if (($width > $resizeonuploadmaxwidth || $height > $resizeonuploadmaxheight) && !in_array($mimetype, $bmptypes)) {
                $resizeattempted = true;
                $imgrs = new ImageResizer($tmpname, $mimetype);
                $img = $imgrs->get_image();
                if (!empty($img)) {
                    $imgrs->resize_image(array('w' => $resizeonuploadmaxwidth, 'h' => $resizeonuploadmaxheight), $mimetype);
                    //auto
                    $saveresize = $imgrs->save_image($tmpname, $mimetype, 85);
                    if (!$saveresize) {
                        return array('error' => true, 'message' => get_string('problemresizing', 'artefact.file'));
                    }
                    $resized = true;
                }
            }
        }
    }
    try {
        $newid = ArtefactTypeFile::save_uploaded_file('userfile', $data, $userfileindex, $resized);
    } catch (QuotaExceededException $e) {
        prepare_upload_failed_message($result, $e, $parentfoldername, $originalname);
        // update the file listing
        if (defined('GROUP')) {
            $group = group_current_group();
            $result['quota'] = $group->quota;
            $result['quotaused'] = $group->quotaused;
        } else {
            $result['quota'] = $USER->get('quota');
            $result['quotaused'] = $USER->get('quotaused');
        }
        $result['newlist'] = pieform_element_filebrowser_build_filelist($form, $element, $parentfolder, null, $data->owner, $data->group, $data->institution);
        return $result;
    } catch (UploadException $e) {
        prepare_upload_failed_message($result, $e, $parentfoldername, $originalname);
        if (defined('GROUP')) {
            $group = group_current_group();
            $result['quota'] = $group->quota;
            $result['quotaused'] = $group->quotaused;
        }
        return $result;
    }
    // Upload succeeded
    if (isset($element['filters'])) {
        $artefacttypes = isset($element['filters']['artefacttype']) ? $element['filters']['artefacttype'] : null;
        $filetypes = isset($element['filters']['filetype']) ? $element['filters']['filetype'] : null;
        if (!empty($artefacttypes) || !empty($filetypes)) {
            // Need to check the artefacttype or filetype (mimetype) of the uploaded file.
            $file = artefact_instance_from_id($newid);
            if (is_array($artefacttypes) && !in_array($file->get('artefacttype'), $artefacttypes) || is_array($filetypes) && !in_array($file->get('filetype'), $filetypes)) {
                $result['error'] = true;
                $result['uploaded'] = true;
                $result['message'] = get_string('wrongfiletypeforblock', 'artefact.file');
                return $result;
            }
        }
    }
    if ($parentfoldername) {
        if ($data->title == $originalname) {
            $result['message'] = get_string('uploadoffiletofoldercomplete', 'artefact.file', $originalname, $parentfoldername);
        } else {
            $result['message'] = get_string('fileuploadedtofolderas', 'artefact.file', $originalname, $parentfoldername, $data->title);
        }
    } else {
        if ($data->title == $originalname) {
            $result['message'] = get_string('uploadoffilecomplete', 'artefact.file', $originalname);
        } else {
            $result['message'] = get_string('fileuploadedas', 'artefact.file', $originalname, $data->title);
        }
    }
    if ($resizeattempted && !$resized) {
        $result['message'] .= get_string('insufficientmemoryforresize', 'artefact.file');
    }
    $result['highlight'] = $newid;
    $artefact = artefact_instance_from_id($newid);
    $result['artefacttype'] = $artefact->get('artefacttype');
    $result['uploaded'] = true;
    $result['newlist'] = pieform_element_filebrowser_build_filelist($form, $element, $parentfolder, $newid, $data->owner, $data->group, $data->institution);
    if (defined('GROUP')) {
        $group = group_current_group(false);
        $result['quota'] = $group->quota;
        $result['quotaused'] = $group->quotaused;
    } else {
        $result['quota'] = $USER->get('quota');
        $result['quotaused'] = $USER->get('quotaused');
    }
    $result['maxuploadsize'] = display_size(get_max_upload_size(!$institution && !$group));
    return $result;
}
 /**
  * Displays the most recently uplloaded 
  *
  * @access	public
  * @param	array View variable data (optional)
  * @return	mixed Can be an array of items or a string value
  */
 public function related_items($params)
 {
     $CI =& get_instance();
     $uploaded_post = $CI->session->flashdata('uploaded_post');
     if (!empty($uploaded_post['uploaded_file_webpath'])) {
         $img = '';
         foreach ($uploaded_post['uploaded_file_webpath'] as $uploaded_image) {
             if (is_image_file($uploaded_image)) {
                 $img .= '<a href="' . $uploaded_image . '" target="_blank"><img src="' . $uploaded_image . '?c=' . time() . '" alt="" style="max-width: 100%;" /></a>';
             }
         }
         return $img;
     }
     return '';
 }
 /**
 * Uploads the files in the $_FILES array
 *
 * Accepts an associative array as which can have the following parameters:
 *
 		<ul>
 		 	<li><strong>upload_path</strong>: the server path to upload the file</li>
 		 	<li><strong>override_post_params</strong>: determines whether post parameters (e.g. {$_FILES_key}_{param}) take precedence over parameters passed to the method</li>
 		 	<li><strong>file_name</strong>: the name of the file to change to</li>
 		 	<li><strong>overwrite</strong>: boolean value that determines whether to overwrite the file or create a new file which will append a number at the end</li>
 		 	<li><strong>xss_clean</strong>: boolean value that determines whether to try and run the xss_clean function on any images that are uploaded</li>
 		 	<li><strong>encrypt_name</strong>: boolean value that determines whether to encrypt the file name and make it unique</li>
 		 	<li><strong>create_thumb</strong>: image specific boolean value that determines whether to create a thumbnail image based on the original uploaded image</li>
 		 	<li><strong>thumb_marker</strong>: the default suffix to use on a generated thumbnail. The default is "_thumb"</li>
 		 	<li><strong>maintain_ratio</strong>:image specific boolean value that determines whether to maintain the aspect ratio of the image upon resize</li>
 		 	<li><strong>master_dim</strong>: image specific boolean value that determines which dimension should be used when resizing and maintaining the aspect ratio. Options are height, width, auto</li>
 		 	<li><strong>width</strong>: sets the width of the uploaded image</li>
 		 	<li><strong>height</strong>: sets the height of the uploaded image</li>
 		 	<li><strong>resize_and_crop</strong>: image specific boolean value that determines whether to both resize and crop the image to the specified height and width</li>
 		 </ul>
 *
 * @access	public
 * @param	array	upload parameters (optional)
 * @return	boolean
 */
 public function upload($params = array())
 {
     $this->CI->load->library('upload');
     $this->CI->load->library('image_lib');
     $this->CI->load->library('encrypt');
     $valid = array('upload_path' => '', 'file_name' => '', 'overwrite' => FALSE, 'xss_clean' => FALSE, 'encrypt_name' => FALSE, 'unzip' => FALSE, 'override_post_params' => FALSE, 'posted' => $_POST, 'create_thumb' => NULL, 'thumb_marker' => '_thumb', 'maintain_ratio' => NULL, 'master_dim' => NULL, 'width' => NULL, 'height' => NULL, 'resize_and_crop' => FALSE);
     // used later
     $has_empty_filename = empty($params['file_name']) ? TRUE : FALSE;
     // set defaults
     foreach ($valid as $param => $default) {
         $params[$param] = isset($params[$param]) ? $params[$param] : $default;
     }
     // upload the file
     foreach ($_FILES as $key => $file) {
         if ($file['error'] == 0) {
             $ext = end(explode('.', $file['name']));
             $field_name = current(explode('___', $key));
             // extract out multi file upload infor
             // loop through all the allowed file types that are accepted for the asset directory
             foreach ($this->dir_filetypes() as $dir => $types) {
                 $file_types = explode('|', strtolower($types));
                 if (in_array(strtolower($ext), $file_types)) {
                     $default_asset_dir = $dir;
                     break;
                 }
             }
             if (empty($default_asset_dir)) {
                 $this->_add_error(lang('upload_invalid_filetype'));
                 return FALSE;
             }
             $non_multi_key = current(explode('___', $key));
             $posted_filename = FALSE;
             // get params based on the posted variables
             if (empty($params['override_post_params'])) {
                 $posted = array();
                 foreach ($valid as $param => $default) {
                     if ($param != 'posted') {
                         $input_key = $non_multi_key . '_' . $param;
                         $input_key_arr = explode('--', $input_key);
                         $input_key = end($input_key_arr);
                         $field_name_arr = explode('--', $field_name);
                         $field_name = end($field_name_arr);
                         // decode encrypted file path values
                         if (isset($params['posted'][$input_key])) {
                             if ($input_key == $field_name . '_upload_path') {
                                 $posted['upload_path'] = $this->CI->encrypt->decode($params['posted'][$input_key]);
                                 foreach ($params['posted'] as $k => $p) {
                                     if (!is_array($p)) {
                                         $posted['upload_path'] = str_replace('{' . $k . '}', $p, $posted['upload_path']);
                                     }
                                 }
                                 // security check to make sure that no crazy paths are being generated
                                 $posted['upload_path'] = str_replace('..' . DIRECTORY_SEPARATOR, '', $posted['upload_path']);
                             } else {
                                 $posted[$param] = $params['posted'][$input_key];
                             }
                             if ($param == 'file_name') {
                                 $posted_filename = TRUE;
                             }
                         }
                     }
                 }
                 $params = array_merge($params, $posted);
                 unset($params['override_post_params'], $params['posted']);
             }
             $asset_dir = trim(str_replace(assets_server_path(), '', $params['upload_path']), '/');
             // set restrictions
             $params['max_size'] = $this->fuel->config('assets_upload_max_size');
             $params['max_width'] = $this->fuel->config('assets_upload_max_width');
             $params['max_height'] = $this->fuel->config('assets_upload_max_height');
             if ($this->dir_filetype($asset_dir)) {
                 $params['allowed_types'] = $this->dir_filetype($asset_dir);
             } else {
                 if ($this->dir_filetype($default_asset_dir)) {
                     $params['allowed_types'] = $this->dir_filetype($default_asset_dir);
                     $asset_dir = $default_asset_dir;
                 } else {
                     $params['allowed_types'] = 'jpg|jpeg|png|gif';
                     $asset_dir = $default_asset_dir;
                 }
             }
             // set the upload path
             if (empty($params['upload_path'])) {
                 $params['upload_path'] = !empty($params[$field_name . '_path']) ? $params[$field_name . '_path'] : assets_server_path() . $asset_dir . '/';
             }
             $params['remove_spaces'] = TRUE;
             // make directory if it doesn't exist and subfolder creation is allowed'
             if (!is_dir($params['upload_path']) and $this->fuel->config('assets_allow_subfolder_creation')) {
                 // will recursively create folder
                 @mkdir($params['upload_path'], 0777, TRUE);
                 if (!file_exists($params['upload_path'])) {
                     $this->_add_error(lang('upload_not_writable'));
                 } else {
                     chmodr($params['upload_path'], 0777);
                 }
             }
             // set file name
             if (!$posted_filename) {
                 if ($has_empty_filename and !empty($params[$field_name . '_file_name'])) {
                     $params['file_name'] = $params[$field_name . '_file_name'];
                 } else {
                     if ($has_empty_filename) {
                         $file_name = pathinfo($file['name'], PATHINFO_FILENAME);
                         $params['file_name'] = url_title($file_name, 'underscore', FALSE);
                     }
                 }
             }
             // set overwrite
             $params['overwrite'] = is_true_val($params['overwrite']);
             if (is_image_file($params['file_name']) and !empty($params['xss_clean'])) {
                 $tmp_file = file_get_contents($file['tmp_name']);
                 if (xss_clean($tmp_file, TRUE) === FALSE) {
                     $this->_add_error(lang('upload_invalid_filetype'));
                 }
             }
             // if errors, then we simply return FALSE at this point and don't continue any further processing'
             if ($this->has_errors()) {
                 return FALSE;
             }
             // UPLOAD!!!
             $this->CI->upload->initialize($params);
             if (!$this->CI->upload->do_upload($key)) {
                 $this->_add_error($this->CI->upload->display_errors('', ''));
             } else {
                 $this->_data[$key] = $this->CI->upload->data();
                 // set the file perm if necessary
                 if ($this->fuel->config('set_upload_file_perms') !== FALSE and function_exists('chmod') and is_integer($this->fuel->config('set_upload_file_perms'))) {
                     chmod($this->_data[$key]['full_path'], $this->fuel->config('set_upload_file_perms'));
                 }
             }
         }
     }
     // set maintain ration if it is set to maintain_ratio
     if (!empty($params['resize_method']) and $params['resize_method'] == 'maintain_ratio') {
         $params['maintain_ratio'] = TRUE;
     }
     // now loop through the uploaded files to do any further image processing
     foreach ($this->_data as $file) {
         if (is_image_file($file['file_name']) and (isset($params['create_thumb']) or isset($params['maintain_ratio']) or !empty($params['width']) or !empty($params['height']) or !empty($params['master_dim']) or !empty($params['resize_and_crop']) or !empty($params['resize_method']))) {
             $params['source_image'] = $file['full_path'];
             // cast
             $params['maintain_ratio'] = (bool) $params['maintain_ratio'];
             // to fix issues with resize and crop
             if (empty($params['create_thumb'])) {
                 $params['thumb_marker'] = '';
             }
             $this->CI->image_lib->initialize($params);
             // check for if they want just a resize or a resize AND crop
             if (!empty($params['resize_and_crop']) or !empty($params['resize_method']) and $params['resize_method'] == 'resize_and_crop') {
                 $resize = $this->CI->image_lib->resize_and_crop();
             } else {
                 $resize = $this->CI->image_lib->resize();
             }
             if (!$resize) {
                 $this->_add_error($this->CI->image_lib->display_errors());
             }
         } else {
             if (is_true_val($params['unzip']) and $file['file_ext'] == '.zip') {
                 // unzip the contents
                 $this->unzip($file['full_path']);
                 // then delete the zip file
                 $this->delete($file['full_path']);
             }
         }
     }
     if ($this->has_errors()) {
         return FALSE;
     }
     return TRUE;
 }
Exemple #7
0
 /**
  * Test file type and return a new Image or File.
  */
 public static function new_file($path, $data)
 {
     require_once 'file.php';
     if (is_image_file($path)) {
         // If it's detected as an image, overwrite the browser mime type
         $imageinfo = getimagesize($path);
         $data->filetype = $imageinfo['mime'];
         $data->width = $imageinfo[0];
         $data->height = $imageinfo[1];
         return new ArtefactTypeImage(0, $data);
     }
     return new ArtefactTypeFile(0, $data);
 }
Exemple #8
0
 /**
  * Test file type and return a new Image or File.
  */
 public static function new_file($path, $data)
 {
     require_once 'file.php';
     if (is_image_file($path)) {
         // If it's detected as an image, overwrite the browser mime type
         $imageinfo = getimagesize($path);
         $data->filetype = $imageinfo['mime'];
         $data->width = $imageinfo[0];
         $data->height = $imageinfo[1];
         return new ArtefactTypeImage(0, $data);
     }
     $data->guess = file_mime_type($path, "foo.{$data->oldextension}");
     // The guessed mimetype tends to be more accurate than what the browser tells us.
     // Use the guess, unless it failed to find a match.
     // But if it failed to find a match *and* there is no browser-supplied mimetype,
     // then just use the guess.
     if ($data->guess != 'application/octet-stream' || empty($data->filetype)) {
         $data->filetype = $data->guess;
     }
     foreach (array('video', 'audio', 'archive') as $artefacttype) {
         $classname = 'ArtefactType' . ucfirst($artefacttype);
         if (call_user_func_array(array($classname, 'is_valid_file'), array($path, &$data))) {
             return new $classname(0, $data);
         }
     }
     return new ArtefactTypeFile(0, $data);
 }
	function on_after_post($values)
	{
		if (empty($values['userfile_path'])) return;

		// process any uploaded images files that have been specified
		foreach($_FILES as $file)
		{
			if (is_image_file($file['name']) AND 
					(!empty($values['userfile_create_thumb']) OR 
					!empty($values['userfile_maintain_ratio']) OR 
					!empty($values['userfile_width']) OR 
					!empty($values['userfile_height'])))
			{
	
				$CI =& get_instance();
				$CI->load->library('image_lib');

				$config['source_image']	= $values['userfile_path'].$file['name'];
				$config['create_thumb'] = $values['userfile_create_thumb'];
				$config['maintain_ratio'] = $values['userfile_maintain_ratio'];
				if (!empty($values['userfile_width'])) $config['width'] = $values['userfile_width'];
				if (!empty($values['userfile_height'])) $config['height'] = $values['userfile_height'];
				if (!empty($values['userfile_master_dim'])) $config['master_dim'] = $values['userfile_master_dim'];
				
				$this->image_lib->initialize($config); 

				if ( ! $CI->image_lib->resize())
				{
					$error = $CI->image_lib->display_errors();
					$CI->validator->catch_error($error);
				}
			}
		}
	}
 /**
  * doEditEvent
  * 修改活动
  * @access public
  * @return void
  */
 public function doEditEvent()
 {
     $id['id'] = intval($_POST['id']);
     //判断作者
     if (!CheckAuthorPermission(D('Event'), $id['id'])) {
         $this->error('对不起,您没有权限进行该操作');
     }
     $id['optsId'] = intval($_POST['optsId']);
     $map['title'] = t($_POST['title']);
     $map['address'] = t($_POST['address']);
     $map['limitCount'] = intval(t($_POST['limitCount']));
     $map['type'] = ',' . trim($_POST['type'], ',') . ',';
     $map['explain'] = preg_replace('/class="[0-9a-zA-Z_\\-]+"/', '', h($_POST['content']));
     $map['contact'] = t($_POST['contact']);
     $map['deadline'] = $deadline = $this->_paramDate($_POST['deadline']);
     $map['sTime'] = $stime = $this->_paramDate($_POST['sTime']);
     $map['eTime'] = $etime = $this->_paramDate($_POST['eTime']);
     $map['evob'] = intval(t($_POST['evob']));
     $map['implement_type'] = intval(t($_POST['implement_type'])) ? intval(t($_POST['implement_type'])) : 1;
     if (!t($_POST['title'])) {
         $this->error("活动标题不能为空");
     }
     if ($map['implement_type'] == 2 && !t($_POST['address'])) {
         $this->error("活动地址不能为空");
     }
     /*
     if(intval($_POST['type']) == 0){
         $this->error("请选择活动分类");
     }
     */
     if ($stime > $etime) {
         $this->error("结束时间不得早于开始时间");
     }
     if ($deadline > $etime) {
         $this->error("报名截止时间不能晚于结束时间");
     }
     //$string=iconv("UTF-8","GBK", t($map['explain']));
     $length = strlen($map['explain']);
     if ($length < 20) {
         $this->error('活动介绍不得小于20个字符');
     }
     //处理省份,市,区
     //list( $opts['province'],$opts['city'],$opts['area'] ) = explode( " ",safe($_POST['city']));
     //得到上传的图片
     $config = event_getConfig();
     $options['userId'] = $this->mid;
     $options['max_size'] = $config['photo_max_size'];
     $options['allow_exts'] = $config['photo_file_ext'];
     if (!empty($_FILES['cover']['tmp_name'])) {
         if (!is_image_file($_FILES['cover']['name'])) {
             $this->error("封面不是图片文件");
             exit;
         }
         $data['attach_type'] = 'event';
         $data['upload_type'] = 'image';
         $cover = model('attach')->upload($data);
     }
     //处理选项
     $opts['cost'] = intval($_POST['cost']);
     $opts['costExplain'] = t($_POST['costExplain']);
     $friend = isset($_POST['friend']) ? 1 : 0;
     $allow = isset($_POST['allow']) ? 1 : 0;
     $opts['opts'] = array('friend' => $friend, 'allow' => $allow);
     if ($this->event->doEditEvent($map, $opts, $cover, $id)) {
         // $this->assign('jumpUrl',U('//eventDetail',array('id'=>$id['id'],'uid'=>$this->mid)));
         //    $this->success($this->appName.'修改成功!');
         $res['id'] = intval($_POST['id']);
         $res['uid'] = $this->mid;
         return $this->ajaxReturn($res, $this->appName . '保存成功', 1);
     } else {
         $this->error($this->appName . '修改失败');
     }
 }
    /**
     * Creates an asset select/upload field
     *
     * @access	public
     * @param	array Fields parameters
     * @return	string
     */
    public function asset($params)
    {
        $this->CI->load->helper('file');
        $this->CI->load->helper('html');
        $form_builder =& $params['instance'];
        if (empty($params['folder'])) {
            $params['folder'] = 'images';
        }
        $asset_class = '';
        if (!isset($params['select']) or isset($params['select']) and $params['select'] !== FALSE) {
            $asset_class .= ' asset_select';
        }
        if (!isset($params['upload']) or isset($params['upload']) and $params['upload'] !== FALSE) {
            $asset_class .= ' asset_upload';
        }
        $asset_class .= ' ' . $params['folder'];
        $params['class'] = !empty($params['class']) ? $params['class'] . ' ' . $asset_class : $asset_class;
        // set the image preview containing class
        if (empty($params['img_container_styles'])) {
            $params['img_container_styles'] = 'overflow: auto; height: 200px; width: 400px; margin-top: 5px;';
        }
        // set the styles specific to the image
        if (!isset($params['img_styles'])) {
            $params['img_styles'] = 'float: left; width: 100px;';
        }
        // folders and intended contents
        $editable_filetypes = $this->fuel->config('editable_asset_filetypes');
        // set data parameters so that we can use them with the JS
        // set multiple and separator data attributes so can be used by javascript
        if (!isset($params['multiple'])) {
            $multiple = !empty($params['multiple']) or strpos($params['value'], ',') !== FALSE;
        } else {
            $multiple = $params['multiple'];
        }
        // set the separator based on if it is multiple lines or just a single line
        $separator = (isset($params['multiline']) and $params['multiline'] === TRUE) ? "\n" : ', ';
        $params['data'] = array('multiple' => $multiple, 'separator' => $separator, 'folder' => $params['folder']);
        if (!empty($params['value'])) {
            if (is_string($params['value'])) {
                // unserialize if it is a serialized string
                if (is_json_str($params['value'])) {
                    $assets = json_decode($params['value'], TRUE);
                    //$assets = unserialize($params['value']);
                } else {
                    if ($multiple) {
                        // create assoc array with key being the image and the value being either the image name again or the caption
                        $assets = preg_split('#\\s*,\\s*|\\n#', $params['value']);
                    } else {
                        $assets = array($params['value']);
                    }
                }
                $preview_str = '';
                // loop through all the assets and concatenate them
                foreach ($assets as $asset) {
                    if (!empty($asset)) {
                        $asset_path = '';
                        foreach ($editable_filetypes as $folder => $regex) {
                            if (!is_http_path($asset)) {
                                if (preg_match('#' . $regex . '#i', $asset)) {
                                    $path = trim($params['folder'], '/') . '/' . $asset;
                                    $asset_path = assets_path($path);
                                    break;
                                }
                            } else {
                                $asset_path = $asset;
                            }
                        }
                        if (!empty($asset_path)) {
                            $preview_str .= '<a href="' . $asset_path . '" target="_blank">';
                            if (isset($params['is_image']) or !isset($params['is_image']) and is_image_file($asset)) {
                                $preview_str .= '<img src="' . $asset_path . '" style="' . $params['img_styles'] . '"/>';
                            } else {
                                $preview_str .= $asset;
                            }
                            $preview_str .= '</a>';
                        }
                    }
                }
            }
            $preview = '';
            if (!empty($preview_str)) {
                $img_container_styles = $params['img_container_styles'];
                if ($multiple == FALSE and !empty($params['img_styles'])) {
                    $img_container_styles = $params['img_styles'];
                }
                $preview = '<br /><div class="noclone" style="' . $img_container_styles . '">';
                $preview .= $preview_str;
                $preview .= '</div><div class="clear"></div>';
            }
            $params['after_html'] = $preview;
        }
        $params['type'] = '';
        if ($multiple) {
            $process_key = isset($params['subkey']) ? $params['subkey'] : $params['key'];
            // create an array with the key being the image name and the value being the caption (if it exists... otherwise the image name is used again)
            $func_str = '
				if (is_array($value))
				{
					foreach($value as $key => $val)
					{
						if (isset($val["' . $process_key . '"]))
						{
							if (is_string($val["' . $process_key . '"]))
							{
								$z = $val["' . $process_key . '"];
							}
							else if (is_array($val["' . $process_key . '"]) AND isset($val["' . $process_key . '"]["' . $params['name'] . '"]))
							{
								$z = $val["' . $process_key . '"]["' . $params['name'] . '"];
							}
							$z = trim($z);
							$assets = array();
							$assets_arr = preg_split("#\\s*,\\s*|\\n#", $z);

							if (is_string($val["' . $process_key . '"]))
							{
								if (count($assets_arr) > 1)
								{
									$value[$key]["' . $process_key . '"] = json_encode($assets_arr);
								}
								else
								{
									$value[$key]["' . $process_key . '"] = $z;
								}
							}
							else if (is_array($val["' . $process_key . '"]) AND isset($val["' . $process_key . '"]["' . $params['name'] . '"]))
							{
								if (count($assets_arr) > 1)
								{
									$value[$key]["' . $process_key . '"]["' . $params['name'] . '"] = json_encode($assets_arr);
								}
								else
								{
									$value[$key]["' . $process_key . '"]["' . $params['name'] . '"] = $z;
								}
							}
							
						}
					}
					return $value;
				}
				else
				{
					$value = trim($value);
					$assets_arr = preg_split("#\\s*,\\s*|\\n#", $value);
					if (count($assets_arr) > 1)
					{
						return json_encode($assets_arr);
					}
					else
					{
						return $value;
					}
				}
				';
            $func = create_function('$value', $func_str);
            $form_builder->set_post_process($params['key'], $func);
        }
        // unserialize value if it's serialized
        //$value = (is_serialized_str($params['value'])) ? unserialize($params['value']) : $params['value'];
        $value = (is_string($params['value']) and is_json_str($params['value'])) ? json_decode($params['value'], TRUE) : $params['value'];
        if (is_array($value)) {
            $params['value'] = '';
            foreach ($value as $key => $val) {
                if (!empty($val)) {
                    $params['value'] .= $val . $separator;
                }
            }
        }
        $params['value'] = trim($params['value'], ",\n ");
        //$params['comment'] = 'Add a caption value to your image by inserting a colon after the image name and then enter your caption like so: my_img.jpg:My caption goes here.';
        // data params
        $data_params['asset_folder'] = $params['folder'];
        $data_params['subfolder'] = isset($params['subfolder']) ? $params['subfolder'] : '';
        $data_params['userfile_file_name'] = isset($params['file_name']) ? $params['file_name'] : '';
        $data_params['overwrite'] = isset($params['overwrite']) ? (bool) $params['overwrite'] : TRUE;
        $data_params['unzip'] = isset($params['unzip']) ? (bool) $params['unzip'] : TRUE;
        $data_params['create_thumb'] = isset($params['create_thumb']) ? (bool) $params['create_thumb'] : FALSE;
        $data_params['maintain_ratio'] = isset($params['maintain_ratio']) ? (bool) $params['maintain_ratio'] : FALSE;
        $data_params['width'] = isset($params['width']) ? (int) $params['width'] : '';
        $data_params['height'] = isset($params['height']) ? (int) $params['height'] : '';
        $data_params['master_dim'] = isset($params['master_dim']) ? $params['master_dim'] : '';
        $data_params['resize_and_crop'] = isset($params['resize_and_crop']) ? $params['resize_and_crop'] : '';
        $data_params['resize_method'] = isset($params['resize_method']) ? $params['resize_method'] : 'maintain_ratio';
        $data_params['hide_options'] = isset($params['hide_options']) ? (bool) $params['hide_options'] : FALSE;
        $data_params['accept'] = isset($params['accept']) ? $params['accept'] : '';
        if (isset($params['hide_image_options'])) {
            $data_params['hide_image_options'] = isset($params['hide_image_options']) ? (bool) $params['hide_image_options'] : FALSE;
        } else {
            if (!isset($params['hide_image_options']) and !preg_match('#^images#', $params['folder'])) {
                $data_params['hide_image_options'] = TRUE;
            }
        }
        $params['data']['params'] = http_build_query($data_params);
        if (!empty($params['multiline'])) {
            $params['class'] = 'no_editor ' . $params['class'];
            if (empty($params['style'])) {
                $params['style'] = 'float: left; width: 400px; height: 60px';
            }
            $str = $form_builder->create_textarea($params);
        } else {
            $str = $form_builder->create_text($params);
        }
        $str .= $params['after_html'];
        return $str;
    }
 /**
  * Creates a file upload field but has the option to allow multiple fields
  *
  * @access	public
  * @param	array Fields parameters
  * @return	string
  */
 public function file($params)
 {
     $this->CI->load->helper('file');
     $form_builder =& $params['instance'];
     $file_params = $params;
     if (!empty($params['multiple'])) {
         $file_params['class'] = 'multifile ' . $params['class'];
     }
     $file_params['name'] = str_replace(array('[', ']', '__'), array('_', '', '_'), $params['name']);
     $file_params['id'] = $file_params['name'] . '_upload';
     $str = '';
     $preview = '';
     $asset_folder = '';
     if (!isset($params['display_preview']) or $params['display_preview'] === TRUE) {
         // set the image preview containing class
         if (empty($params['img_container_styles'])) {
             $params['img_container_styles'] = 'overflow: auto; height: 200px; width: 400px; margin-top: 5px;';
         }
         // set the styles specific to the image
         if (!isset($params['img_styles'])) {
             $params['img_styles'] = 'float: left; width: 100px;';
         }
         if (empty($params['value'])) {
             $params['value'] = '';
         }
         if (isset($params['folder']) or isset($params['upload_path'])) {
             if (isset($params['folder'])) {
                 $asset_folder = trim($params['folder'], '/') . '/';
                 $asset_path = $asset_folder . $params['value'];
                 $asset_path = assets_path($asset_path);
             } else {
                 $asset_folder = assets_server_to_web_path($params['upload_path']) . '/';
                 $asset_path = $asset_folder . $params['value'];
             }
             if (!empty($params['replace_values'])) {
                 foreach ($params['replace_values'] as $key => $val) {
                     if (is_string($val)) {
                         $asset_path = str_replace('{' . $key . '}', $val, $asset_path);
                         $asset_folder = str_replace('{' . $key . '}', $val, $asset_folder);
                     }
                 }
             }
         }
         $preview = '';
         if (!empty($asset_path) and !empty($params['value'])) {
             $preview .= ' ';
             $preview .= '<div class="asset_upload_preview deletable noclone"><a href="#' . $params['key'] . '" class="asset_delete"></a><a href="' . $asset_path . '" target="_blank">';
             if (isset($params['is_image']) or !isset($params['is_image']) and is_image_file($asset_path)) {
                 $preview .= '<br><img src="' . $asset_path . '" style="' . $params['img_styles'] . '" class="img_bg">';
             } else {
                 $preview .= $asset_path;
             }
             $preview .= '</a>';
         }
     }
     $params['after_html'] = $preview;
     $str .= $form_builder->create_file($file_params);
     if (!empty($params['display_input'])) {
         $params['data'] = array('folder' => $asset_folder);
         $asset_class = '';
         if (!isset($params['select']) or isset($params['select']) and $params['select'] !== FALSE) {
             $asset_class = 'asset_select';
         }
         $params['class'] = !empty($params['class']) ? $params['class'] . ' ' . $asset_class : $asset_class;
         $params['type'] = '';
         $str .= '<br><br>' . $form_builder->create_field($params);
     } else {
         $params['type'] = 'hidden';
         $str .= $form_builder->create_field($params);
     }
     // add image altering hidden field values
     $additional_params = array('create_thumb', 'thumb_marker', 'maintain_ratio', 'master_dim', 'width', 'height', 'resize_and_crop', 'remove_spaces', 'resize_method');
     foreach ($additional_params as $p) {
         if (isset($params[$p])) {
             $str .= $this->CI->form->hidden($file_params['name'] . '_' . $p, $params[$p], 'class="noclear"');
         }
     }
     return $str;
 }
function is_image($string)
{
    return file_exists("{$string}") && is_image_file($string) ? true : false;
}