Skip to content

Instantly share code, notes, and snippets.

@tuanphpvn
Last active August 4, 2016 01:38
Show Gist options
  • Save tuanphpvn/3d2bd83f54eac16402ee to your computer and use it in GitHub Desktop.
Save tuanphpvn/3d2bd83f54eac16402ee to your computer and use it in GitHub Desktop.
Pl Upload multiple #Wordpress #PlUpload
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
if(!$_FILES) {
wp_die(''); // Do nothing
}
// check max allowed
$max_upload_gal_img = of_get_option(Apollo_DB_Schema::_MAX_UPLOAD_GALLERY_IMG, Apollo_Display_Config::MAX_UPLOAD_GALLERY_IMG);
if(isset($_SESSION['apollo'][Apollo_SESSION::EVENT_ADD_GALLERY]) && count($_SESSION['apollo'][Apollo_SESSION::EVENT_ADD_GALLERY]) > $max_upload_gal_img) {
wp_die(1); // do nothing
}
// Just process one image currently
$i =0;
$arrGallery = array();
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
$arrGallery = array_merge($arrGallery, array(
'error' => 'true',
'key' => $_POST['id'],
'msg' => 'Error upload file. Please try again'
));
$i++;
continue;
}
$wp_filetype = wp_check_filetype_and_ext($_FILES[$file]['tmp_name'], $_FILES[$file]['name'] );
$ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
$type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
if ( ( ! $type || !$ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
$arrGallery = array_merge($arrGallery, array(
'error' => 'true',
'key' => $_POST['id'],
'msg' => 'Unsupport that file'
));
$i++;
continue;
}
$meta = getimagesize($_FILES[$file]['tmp_name']);
$min_w = 2*get_option('medium_size_w');
$min_h = 2*get_option('medium_size_h');
if($meta[0] < $min_w || $meta[1] < $min_h) {
$arrGallery = array_merge($arrGallery, array(
'error' => 'true',
'key' => $_POST['id'],
'msg' => sprintf(__("Image must have width > %s px and height > %s px", 'apollo'), $min_w, $min_h)
));
$i++;
continue;
}
// copy to upload directory
if ( ! ( ( $uploads = wp_upload_dir( ) ) && false === $uploads['error'] ) ) {
wp_send_json(array(
'error'=> true,
'data' => array(
'msg' => 'Error upload file: '.$_FILES[$file]['name']
),
));
}
$oname = $_FILES[$file]['name'];
$tmpname = $oname;
$fname = wp_unique_filename( $uploads['path'], $tmpname );
// Move the file to the uploads dir.
$new_file = $uploads['path'] .'/'. $fname;
$url = $uploads['url'] .'/'. $fname;
$move_new_file = @ move_uploaded_file( $_FILES[$file]['tmp_name'], $new_file );
if ( false === $move_new_file ) {
$arrGallery = array_merge($arrGallery, array(
'error' => 'true',
'key' => $_POST['id'],
'msg' => __('Upload error', 'apollo')
));
$i++;
continue;
}
$_SESSION['apollo'][Apollo_SESSION::EVENT_ADD_GALLERY][$_POST['id']] = array(
'file' => $new_file,
'oname' => $oname,
'type' => $type,
'url' => $url,
);
$arrGallery[] = array(
'error' => false,
'url' => $url,
'id' => $_POST['id'],
);
$i++;
}
wp_send_json(array(
'error'=> false,
'data' => array(
'msg' => 'Upload successfully',
'gallerys' => $arrGallery,
)
));
var _template_box = $("#_box_template").html()
, _list_template = $("#_list_template").html()
, $gallery_console = $("#_gallery_console")
, $galler_list = $("#_galler_list")
, $cancel_gallery_btn = $("#_cancel_gallery_btn")
, $save_gallery_btn = $("#_upload_gallery_btn")
, $gallery_box = $("#_gallery_box")
;
/* Custome add filter */
plupload.addFileFilter('min_img_size', function(min_img_size, file, cb) {
var self = this, img = new o.Image();
function finalize(result) {
// cleanup
img.destroy();
img = null;
// if rule has been violated in one way or another, trigger an error
if (!result) {
self.trigger('Error', {
message : "Upload file " + file.name + "fail! Because min resolution allowed is " + min_img_size.w + " x " + min_img_size.h + " pixels.",
file : file
});
}
cb(result);
}
img.onload = function() {
// check if resolution cap is not exceeded
finalize(img.width > min_img_size.w && img.height > min_img_size.h);
};
img.onerror = function() {
finalize(false);
};
img.load(file.getSource());
});
/* clear timeout array */
$.fn.pluploader = {
'gallery.hasshowerror': false,
'gallery.timers': []
};
/* Using plupload to upload */
var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button : '_upload_gallery_btn', // you can pass in id...
container: document.getElementById('_upload_gallery'), // ... or DOM Element itself
url : APL.ajax_url + '?action=apollo_upload_multi_gallery',
filters : {
max_file_size : APL.upload_image.filters.max_file_size,
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
],
min_img_size: {'w': min_size_w, 'h': min_size_h} // 1MP = 1 million pixels
},
// Flash settings
flah_swf_url : APL.flah_swf_url,
// Silverlight settings
silverlight_xap_url : APL.silverlight_xap_url,
init: {
BeforeUpload: function(up, file) {
uploader.settings.multipart_params = {'id': file.id};
},
FilesAdded: function(up, files) {
var maxfiles = parseInt(APL.upload_image.filters.max_upload_gal_img, 10);
if(up.files.length > maxfiles )
{
up.files.splice(maxfiles);
alert('No more than '+maxfiles + ' file(s)');
}
plupload.each(up.files, function(file) {
//document.getElementById('_gallery_box').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
document.getElementById('_gallery_box').innerHTML += _template_box.replace('{i}', file.id).replace('{filename}', file.name).replace('{filesize}', plupload.formatSize(file.size));
});
uploader.start();
},
UploadProgress: function(up, file) {
$('#_gallery_box_'+file.id+' .status span').css('width', file.percent + '%');
},
FileUploaded: function(up, file, info) {
var res = JSON.parse(info['response']);
var href = 'javascript:void(0);';
console.log('debug');
if(res.error === true) {
uploader.trigger('Error', {
code : plupload.GENERIC_ERROR,
message : res.data.gallerys.msg + "."
});
return false;
}
$(res.data.gallerys).each(function(_, data) {
var $_gallery_box_id = $('#_gallery_box_'+data.id);
if(data.error === true) {
$_gallery_box_id.remove();
return true; /* continue */
}
$galler_list.append(_list_template.replace('{i}', data.id).replace('{href}', href).replace('{src}', data.url));
var _overview = $_gallery_box_id.find('.overview');
_overview.attr('src', data.url);
_overview.removeClass('hidden');
});
$save_gallery_btn.addClass('hidden');
$cancel_gallery_btn.removeClass('hidden');
},
Error: function(up, err) {
$gallery_console.append("<div>" + err.message + "</div>");
var idtimer = setTimeout(function () {
$gallery_console.fadeOut('slow');
}, 8000);
$.fn.pluploader["gallery.timers"].push(idtimer);
}
}
});
/* init upload */
uploader.init();
/* When click this button will remove all timer and empty console error */
$save_gallery_btn.on('click', function(e) {
$($.fn.pluploader["gallery.timers"]).each(function(_, v) {
clearTimeout(v);
});
$.fn.pluploader["gallery.timers"] = [];
$gallery_console.empty();
});
/* cancel upload */
$cancel_gallery_btn.on('click', function(e) {
$.ajax({
url: APL.ajax_url,
beforeSend: function() {
$block_container.block(_blockUI);
},
data: {
action: 'apollo_remove_multi_gallery'
},
success: function (res) {
console.log(res);
},
complete: function() {
$galler_list.empty();
$gallery_box.empty();
/* Perfect reset uploader */
uploader.splice();
uploader.refresh();
$gallery_console.empty();
$save_gallery_btn.removeClass('hidden');
$cancel_gallery_btn.addClass('hidden');
$block_container.unblock();
}
});
});
/* There are a small close button on each images. Put class for it to easy remove it */
$block_container.on('click', '.gallery-list .rm_img', function(e) {
var $this = $(this);
var id = $this.data('id');
$.ajax({
url: APL.ajax_url,
beforeSend: function() {
$block_container.block(_blockUI);
},
data: {
action: 'apollo_remove_multi_gallery',
id: id
},
success: function (res) {
console.log(res);
},
complete: function() {
$this.parents('li._list_').remove();
$('#_gallery_box_'+id).remove();
$block_container.unblock();
/* check if don't have any image left remove cancel upload */
if($galler_list.find('li').length === 0 ) {
uploader.splice();
uploader.refresh();
$gallery_console.empty();
$save_gallery_btn.removeClass('hidden');
$cancel_gallery_btn.addClass('hidden');
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment