'name',
'hide_empty' => false,
'parent' => $parnet
);
$categories = get_categories($args);
foreach ($categories as $category) {
if( !in_array( $category->name, $excludes ) ) {
$cats[] = array( 'id' => $category->term_id, 'name' => $category->name, 'parent' => $category->parent);
$cats = adv_cat_list( $category->term_id, $cats, $excludes );
}
}
return $cats;
}
function adv_admin_inline_js($hook) {
global $adv_file_upload_admin_page, $wpdb;
//get plugin's options
$destinations = get_option('adv_file_upload_destination');
$gallery = get_option('adv_file_upload_gallery');
$bws = get_option('adv_file_upload_bws');
$cat = get_option('adv_file_upload_cat');
$progress = get_option('adv_file_upload_progress');
$maxFileSize = '1073741824';
//set the default location
$upload_dir = wp_upload_dir();
$default_dir = str_replace ( ABSPATH, '', $upload_dir['path'] );
// get list wordpress galleries
if ($gallery) {
$query = "
SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->posts.post_name
FROM $wpdb->posts
WHERE $wpdb->posts.post_type IN ('post','page')
AND $wpdb->posts.post_status IN ('publish','private','protected')
AND $wpdb->posts.post_content LIKE '%[gallery%ids=%'
";
$galleries = $wpdb->get_results($query);
//option to create new gallery
$destinations[] = Array ('label' => 'Create New Gallery',
'dest' => $default_dir,
'library' => true,
'type' => "Wordpress Gallery",
'id' => 'new');
//show existing Galleries
foreach( $galleries as $gallery ) {
$destinations[] = Array ('label' => $gallery->post_title,
'dest' => $default_dir,
'library' => true,
'type' => "Wordpress Gallery",
'id' => $gallery->ID);
}
}
// get list BWS galleries
if ($bws) {
//get BWS galleries
$args = array(
'post_type' => 'gallery',
'post_status' => array('publish','private','protected'),
);
$query = new WP_Query( $args );
$gllr_options = get_option( 'gllr_options' );
if ( $query->have_posts() ) {
foreach ($query->posts as $post) {
$destinations[] = Array ('label' => $post->post_title,
'dest' => $default_dir,
'library' => true,
'type' => "BWS Gallery",
'id' => $post->ID);
}
}
/* Restore original Post Data */
wp_reset_postdata();
}
// get list of Categories
if ($cat) {
$excludes = explode (',', get_option( 'adv_file_upload_exc_cat', 'Uncategorized' ));
$cats = adv_cat_list( 0, array(), $excludes );
}
if ($progress) {
//added Style sheet based on settings
echo "\n";
}
if ( $adv_file_upload_admin_page == $hook ) {
echo "\n";
}
//added javascript vairables
echo "";
}
function adv_file_upload_admin_menu() {
global $adv_file_upload_admin_page;
/* Register our plugin page */
if (!get_option('adv_file_upload_replace_default')) {
$adv_file_upload_admin_page = add_media_page(
__('Advanced uploader','adv-file-upload'), // The Page title
__('Advanced uploader','adv-file-upload'), // The Menu title
'upload_files', // The capability required for access to this item
'adv-file-upload', // the slug to use for the page in the URL
'adv_file_upload_manage_menu' // The function to call to render the page
);
}
add_action('admin_enqueue_scripts', 'adv_file_upload_admin_scripts');
}
function adv_file_upload_admin_scripts($hook) {
global $adv_file_upload_admin_page, $post;
if( !($adv_file_upload_admin_page == $hook ||
(($hook == 'media-new.php' || $hook == 'post-new.php' || $hook == 'post.php') &&
get_option('adv_file_upload_replace_default')))
|| (is_object($post) && $post->post_type == "attachment" ))
return;
wp_enqueue_script( 'adv-file-upload' );
if (get_option('adv_file_upload_replace_default') || $adv_file_upload_admin_page == $hook) {
//check version number and include newer version plupload if wordpress version is older then 3.9
global $wp_version;
if( version_compare( $wp_version, 3.9 ) < 0 ) {
wp_deregister_script('plupload');
wp_deregister_script('plupload-html5');
wp_deregister_script('plupload-flash');
wp_deregister_script('plupload-silverlight');
wp_deregister_script('plupload-html4');
wp_register_script( 'plupload', null, array( 'plupload2' ), '1.0');
wp_register_script( 'plupload-html5', null, array( 'plupload2' ), '1.0');
wp_register_script( 'plupload-flash', null, array( 'plupload2' ), '1.0');
wp_register_script( 'plupload-silverlight', null, array( 'plupload2' ), '1.0');
wp_register_script( 'plupload-html4', null, array( 'plupload2' ), '1.0');
}
}
wp_enqueue_style( 'adv-file-upload-css' );
wp_enqueue_style( 'wp-jquery-ui-dialog' );
// js varaibles to page
adv_admin_inline_js($hook);
}
function adv_file_upload_set_loader() {
set_user_setting('adv_uploader', $_REQUEST['loader']);
exit();
}
function adv_file_upload_manage_menu() {
if ( !current_user_can( 'upload_files' ) ) {
wp_die( __( 'You do not have permission to upload files.' ) );
}
wp_enqueue_script('plupload-handlers');
echo "
";
screen_icon('upload');
echo "
Advanced uploader
";
echo "";
echo "\n";
}
function adv_upload_add_file ($name, $target_path, $parent_id, $sizes, $dest, $galleryType, $galleryID) {
$upload_dir = wp_upload_dir();
$wp_filetype = wp_check_filetype($name);
//set parent ID to add picture to BWS gallery
if ($galleryType == 'BWS Gallery')
$parent_id = $galleryID;
$attachment = array(
'guid' => $upload_dir ['url'] . '/' . $name,
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $name),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $target_path . $name, $parent_id);
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
//get reduced size images imformation from file
if($sizes != null && count($sizes) > 0) {
if (pathinfo($name, PATHINFO_EXTENSION) != 'pdf') {
//get image dimentions
$size = getimagesize ($target_path . $name);
//Horizontal size of image attachment, in pixels.
$attach_data["width"] = $size[0];
//Vertical size of image attachment, in pixels.
$attach_data["height"] = $size[1];
//get additional picture meta data
$attach_data["image_meta"] = wp_read_image_metadata($target_path . $name);
}
//Path to image attachment, relative to the currently configured uploads directory.
//need to add logic to check if the upload dir is organised into year/month.
$rel_path = str_replace ( $upload_dir['basedir'] . DIRECTORY_SEPARATOR, '', $target_path );
$rel_path = untrailingslashit( $rel_path ) . DIRECTORY_SEPARATOR;
$attach_data["file"] = $rel_path . urlencode($name);
$attach_data["sizes"] = $sizes;
} else {
$attach_data = wp_generate_attachment_metadata( $attach_id, $target_path . $name );
}
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id;
}
// ------------------------------------------------------------------
// fields and settings during admin_init
// ------------------------------------------------------------------
//
function adv_file_upload_settings_api_init() {
// Add the section to reading settings so we can add our
// fields to it
add_settings_section('adv_file_upload',
'Advanced uploader',
'adv_file_upload_setting_section',
'media');
// Add the field with the names and function to use for our new
// settings, put it in our new section
add_settings_field('adv_file_upload_destination',
'Destinations',
'adv_file_upload_setting_dest',
'media',
'adv_file_upload');
add_settings_field('adv_file_upload_progress',
'Colour of progress bar',
'adv_file_upload_setting_prog',
'media',
'adv_file_upload');
add_settings_field('adv_file_upload_gallery',
'Include Wordpress Galleries',
'adv_file_upload_setting_gallery',
'media',
'adv_file_upload');
add_settings_field('adv_file_upload_bws',
'Include BWS Galleries',
'adv_file_upload_setting_bws',
'media',
'adv_file_upload');
add_settings_field('adv_file_upload_cat',
'Include Categories',
'adv_file_upload_setting_cat',
'media',
'adv_file_upload');
add_settings_field('adv_file_upload_exc_cat',
'Categories to exclude',
'adv_file_upload_setting_exc_cat',
'media',
'adv_file_upload');
add_settings_field('adv_file_upload_replace_default',
'Replace Default Uploader',
'adv_file_upload_setting_replace_default',
'media',
'adv_file_upload');
// Register our setting so that $_POST handling is done for us and
// our callback function just has to echo the
register_setting('media','adv_file_upload_destination','adv_file_upload_validate_destination');
register_setting('media','adv_file_upload_progress','adv_file_upload_validate_progress');
register_setting('media','adv_file_upload_gallery');
register_setting('media','adv_file_upload_bws');
register_setting('media','adv_file_upload_cat');
register_setting('media','adv_file_upload_exc_cat');
register_setting('media','adv_file_upload_replace_default');
}
add_action('admin_init', 'adv_file_upload_settings_api_init');
// ------------------------------------------------------------------
// Settings link
// ------------------------------------------------------------------
//
// This function adds settings link to plugin page.
//
//Add the filter with your plugin information
add_filter( 'plugin_action_links_' . 'advanced-uploader/upload.php', 'adv_file_upload_setting_action_links' );
//The callback function to add the settings link
function adv_file_upload_setting_action_links( $links ) {
array_unshift( $links, 'Settings' );
return $links;
}
// ------------------------------------------------------------------
// Settings section callback function
// ------------------------------------------------------------------
//
// This function is needed for the new section.
//
function adv_file_upload_setting_section () {
wp_enqueue_script( 'adv-file-upload-settings' );
echo '
Settings for the Advanced uploader plugin
';
}
// ------------------------------------------------------------------
// Default Override Callback function
// ------------------------------------------------------------------
//
// creates a checkbox for overiding default
//
function adv_file_upload_setting_replace_default () {
$default = get_option('adv_file_upload_replace_default');
echo "";
}
// ------------------------------------------------------------------
// Wordpress Galleries Callback function
// ------------------------------------------------------------------
//
// creates a checkbox for Wordpress Galleries settings
//
function adv_file_upload_setting_gallery () {
$gallery = get_option('adv_file_upload_gallery');
echo "";
echo " Selecting this will include Wordpress Galleries as destinations ";
}
// ------------------------------------------------------------------
// BWS Galleries Callback function
// ------------------------------------------------------------------
//
// creates a checkbox for BWS Galleries settings
//
function adv_file_upload_setting_bws () {
$bws = get_option('adv_file_upload_bws');
echo "";
echo " Selecting this will include BWS Galleries as destinations ";
echo "Note: BWS Gallery needs to be active to use this feature";
}
// ------------------------------------------------------------------
// Category Callback functions
// ------------------------------------------------------------------
//
// creates a checkbox for Category settings
//
function adv_file_upload_setting_cat () {
$cat = get_option('adv_file_upload_cat');
echo "";
echo " Selecting this will include Categories as destinations ";
echo "Note: It is recommend to have Media Categories By Eddie Moya to be active to use this feature";
}
//
// creates a text box for Category exclusion settings
//
function adv_file_upload_setting_exc_cat () {
$cat = get_option('adv_file_upload_exc_cat','Uncategorized');
echo "";
echo "Note: Enter category names separated with a comma, parent categories will exclude child categories";
}
// ------------------------------------------------------------------
// Destinations Callback function
// ------------------------------------------------------------------
//
// creates a boxes for destination settings
//
function adv_file_upload_setting_dest() {
$destinations = get_option('adv_file_upload_destination');
echo "
Note: Thumbnail images are only created when adding to Wordpress Library";
echo "Note: When adding to Wordpress Library your directory needs to be within the default upload directory
";
}
// ------------------------------------------------------------------
// Validate destination field
// ------------------------------------------------------------------
//
// This function is needed to check that the destiantion exist
//
function adv_file_upload_validate_destination ($input) {
if (!isset($input))
return $input;
$valid_input = array();
foreach ($input as $id => $dest) {
// register destination does not exist error
if( is_dir( ABSPATH . $dest['dest'] ) == FALSE ) {
add_settings_error(
'Destination', // setting title
0, // error ID
__('Expecting a valid directory! Please fix.','wptuts_textdomain'), // error message
'error' // type of message
);
$valid_input[$id]['error']['dest'] = true;
}
// register destination does is not in uploads directory error
$upload_dir = wp_upload_dir(); //get upload base dir
$default_dir = str_replace ( ABSPATH, '', $upload_dir['basedir'] ); //remove site root
if( $dest['library'] && !preg_match( '#^' . $default_dir . '/#', $dest['dest'] )
&& !preg_match( '#^' . $default_dir . '$#', $dest['dest'] ) ) {
add_settings_error(
'Destination', // setting title
0, // error ID
__('To add to Wordpress Library Destination must be in within uploads directory! Please fix.','wptuts_textdomain'), // error message
'error' // type of message
);
$valid_input[$id]['error']['library'] = true;
}
$valid_input[$id]['label'] = $dest['label'];
$valid_input[$id]['dest'] = rtrim($dest['dest'], "/");
$valid_input[$id]['library'] = $dest['library'];
}
return $valid_input;
}
// ------------------------------------------------------------------
// Progress Bar Colour Callback function
// ------------------------------------------------------------------
//
// creates a boxes for destination settings
//
function adv_file_upload_setting_prog() {
$progress = get_option('adv_file_upload_progress');
$errors = get_settings_errors( 'adv_file_upload_progress');
foreach ($errors as $error) {
if ($error['code']) {
$destStyle = "background-color: #ffebe8;";
$progress = $error['code'];
}
}
// show Progress colour
echo "";
echo "This should be an HTML colour code. e.g. #0063a6 ";
echo "Note: Leave blank for browser default";
}
// ------------------------------------------------------------------
// Validate Progress Bar Colour field
// ------------------------------------------------------------------
//
// This function is needed to check that the Progress Bar Colour is a valid colour
//
function adv_file_upload_validate_progress ($input) {
//add hash to front of colour code if missing
if(preg_match('/^[a-f0-9]{6}$/i', $input))
$input = '#' . $input;
//validate valid input (empty for browser default)
if(preg_match('/^#[a-f0-9]{6}$/i', $input) || $input == '')
return $input;
add_settings_error( 'adv_file_upload_progress', // setting title
$input, // error ID
__('Expecting a valid HTML Colour Code! Please fix.','wptuts_textdomain'), // error message
'error' // type of message
);
return get_option('adv_file_upload_progress');
}
function show_attachment_thumb( $link, $id, $size, $permalink, $icon, $text) {
$id = intval( $id );
$_post = & get_post( $id );
//get meta data
$meta = wp_get_attachment_metadata($id);
if ($meta == false) return $link;
$upload_dir = wp_upload_dir();
$rel_path = pathinfo ($meta['file'] , PATHINFO_DIRNAME);
$thumb_path = $upload_dir['basedir'] . '/' . $rel_path . '/' . $meta['sizes']['thumbnail']['file'];
$thumb_url = $upload_dir['baseurl'] . '/' . $rel_path . '/' . $meta['sizes']['thumbnail']['file'];
//if file exists use thumbnail else use icon
if (file_exists( $thumb_path ))
return preg_replace( "/(<.*?>)$_post->post_title/", "$1", $link );
else
return $link;
}
add_filter( 'wp_get_attachment_link', 'show_attachment_thumb', 100, 6 );
//if thumbnail exist replace default icon
function change_mime_icon($icon, $mime = null, $post_id = null){
//get the path and URL to thumbnail and store globally
global $thumb_path;
$thumb_path = "";
//get meta data
$meta = wp_get_attachment_metadata($post_id);
if ($meta == false || !isset($meta['sizes'])) return $icon;
$upload_dir = wp_upload_dir();
$rel_path = pathinfo ($meta['file'] , PATHINFO_DIRNAME);
$thumb_path = $upload_dir['basedir'] . '/' . $rel_path . '/' . $meta['sizes']['thumbnail']['file'];
$thumb_url = $upload_dir['baseurl'] . '/' . $rel_path . '/' . $meta['sizes']['thumbnail']['file'];
//if file exists use thumbnail else use icon
if (file_exists( $thumb_path ))
return $thumb_url;
else
return $icon;
}
add_filter('wp_mime_type_icon', 'change_mime_icon', 100, 3); //if thumbnail exist replace default icon
function change_icon_dir($icon_dir) {
//retrive globally stored thumb path
global $thumb_path;
//if thumbnail exists use instead icon
if (file_exists( $thumb_path ))
return dirname ($thumb_path);
else
return $icon_dir;
}
add_filter('icon_dir', 'change_icon_dir', 100, 1);
// Hide image overflow for icons replace with thumbnails in the ADMIN AREA
function hideoverflow() {
echo '';
}
add_action('admin_head', 'hideoverflow');
function change_media_send_to_editor($html, $post_id, $attachment) {
//get display_attachment_image post data
$size = "";
$att_img = get_post_meta($post_id,'display_attachment_image');
if( is_array($att_img) )
$size = $att_img[0];
//get meta data
$meta = wp_get_attachment_metadata($post_id);
if ($size == '' || $meta == false) return $html;
//remove display_attachment_image from post meta so isn't used incorrectly
delete_post_meta($post_id, 'display_attachment_image');
$upload_dir = wp_upload_dir();
$rel_path = pathinfo ($meta['file'] , PATHINFO_DIRNAME);
$thumb_path = $upload_dir['basedir'] . '/' . $rel_path . '/' . $meta['sizes'][$size]['file'];
$thumb_url = $upload_dir['baseurl'] . '/' . $rel_path . '/' . $meta['sizes'][$size]['file'];
//if file exists use thumbnail else use icon
if (file_exists( $thumb_path )) {
$html = preg_replace('/(.*href=.*>)(.*)(<.*)/', '\1\3', $html);
}
return $html;
}
add_filter('media_send_to_editor', 'change_media_send_to_editor', 20, 3);
//add images sizes to pdf attachemnts (if stored in meta) for selection in media library
function advupl_attachment_fields_to_edit($form_fields, $post) {
if ( !preg_match("/^image/", $post->post_mime_type) ) {
$attachment_url = wp_get_attachment_url( $post->ID );
$meta = wp_get_attachment_metadata( $post->ID );
$sizes = array();
$possible_sizes = apply_filters( 'image_size_names_choose', array(
'thumbnail' => __('Thumbnail'),
'medium' => __('Medium'),
'large' => __('Large'),
'full' => __('Full Size'),
) );
unset( $possible_sizes['full'] );
if( isset( $meta['sizes'] ) ) {
// Loop through all potential sizes that may be chosen.
foreach ( $possible_sizes as $size => $label ) {
if ( isset( $meta['sizes'][ $size ] ) ) {
if ( ! isset( $base_url ) )
$base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
// Nothing from the filter, so consult image metadata if we have it.
$size_meta = $meta['sizes'][ $size ];
// We have the actual image size, but might need to further constrain it if content_width is narrower.
// Thumbnail, medium, and full sizes are also checked against the site's height/width options.
list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
$sizes[ $size ] = "";
}
}
//add image size select if attachment has other images associated
if (count ($sizes) > 0) {
$sizes['link'] = "";
$sizes_array = array(
'display_attachment_image_heading' => array(
'label' => __('
Attachment Image
', 'display_attachment_image'),
'input' => 'html',
'html' => ' '
),
'display_attachment_image' => array(
'label' => __('Sizes', 'display_attachment_image'),
'input' => 'html',
'html' => "\n"
));
$form_fields = array_merge( $form_fields, $sizes_array );
}
}
}
return $form_fields;
}
add_filter('attachment_fields_to_edit', 'advupl_attachment_fields_to_edit', 20, 2);
function save_display_attachment_image($post, $attachment_data) {
// use this filter to add post meta if key exists or delete it if not
if ( !empty($attachment_data['display_attachment_image']) && $attachment_data['display_attachment_image'] != 'link' )
update_post_meta($post['ID'], 'display_attachment_image', $attachment_data['display_attachment_image']);
else
delete_post_meta($post['ID'], 'display_attachment_image');
// return $post in any case, things will break otherwise
return $post;
}
add_filter('attachment_fields_to_save', 'save_display_attachment_image', 20, 2);
function adv_plupload_default_settings($defaults) {
if ( get_option('adv_file_upload_replace_default') ) {
$defaults['flash_swf_url'] = plugins_url('/js/Moxie.swf', __FILE__);
$defaults['silverlight_xap_url'] = plugins_url('/js/Moxie.xap', __FILE__);
$defaults['max_retries'] = 3;
}
return $defaults;
}
add_filter('plupload_default_settings', 'adv_plupload_default_settings');
add_filter('plupload_init', 'adv_plupload_default_settings');
//create new post
function adv_upload_new_post () {
check_ajax_referer('alt_upl_nonce' . get_current_user_id(),'security');
$titles = json_decode(stripcslashes($_REQUEST["title"]));
$results = array();
foreach( $titles as $title ) {
// Create post object
$new_post = array(
'post_title' => $title,
);
// Insert the post into the database
$results[] = array( 'id' => wp_insert_post( $new_post ), 'title' => $title);
}
echo json_encode( $results );
wp_die();
}
function adv_upload_thumbs () {
//check nounce is correct
check_ajax_referer('alt_upl_nonce' . get_current_user_id(),'security');
// 5 minutes execution time
@set_time_limit(5 * 60);
// Get parameters
$post_id = isset($_REQUEST["post_id"]) ? intval($_REQUEST["post_id"]) : 0;
$name = isset($_REQUEST["filename"]) ? $_REQUEST["filename"] : '';
$sizesObj = json_decode(stripcslashes($_REQUEST['meta']));
//get destinations from JSON object
$destinations = json_decode(stripcslashes($_REQUEST['destinations']));
$dest = isset($_REQUEST["fileDest"]) ? intval($_REQUEST["fileDest"]) : 0;
$album = isset($_REQUEST["album"]) ? stripcslashes($_REQUEST["album"]) : '';
$targetDir = ABSPATH . $destinations [$dest][1];
$targetUrl = site_url() . DIRECTORY_SEPARATOR . $destinations [$dest][1];
if( $destinations[$dest][2] == 'Wordpress Gallery' ) {
if( $destinations[$dest][3] == 'new' ) {
$post_id = intval( $album );
} else {
$post_id = $destinations[$dest][3];
}
}
// Look for the content type header
if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
if (isset($_SERVER["CONTENT_TYPE"]))
$contentType = $_SERVER["CONTENT_TYPE"];
if (strpos($contentType, "multipart") !== false) {
for ($i = 0; $i < count($_FILES['thumbs']['name']); $i++) {
$file = array();
$file['name'] = $_FILES['thumbs']['name'][$i];
$file['tmp_name'] = $_FILES['thumbs']['tmp_name'][$i];
if (isset($file['tmp_name']) && is_uploaded_file($file['tmp_name'])) {
// write to desired location
$out = @fopen($targetDir . DIRECTORY_SEPARATOR . $file['name'], "wb");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen($file['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open input stream.',
'code' => 101,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
@fclose($in);
@fclose($out);
@unlink($file['tmp_name']);
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open output stream.',
'code' => 102,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to move uploaded file.',
'code' => 103,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
}
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open input stream.',
'code' => 104,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
if(file_exists($targetDir . DIRECTORY_SEPARATOR . $name)) {
if($sizesObj != null)
foreach ($sizesObj as $sizeDesc => $array)
foreach ($array as $element => $content)
$sizes[$sizeDesc][$element] = $content;
else
$sizes = null;
//add to wordpress library if relevant
if( $destinations[$dest][4] ) {
$attachment_id = adv_upload_add_file ($name,
$targetDir . DIRECTORY_SEPARATOR,
$post_id,
$sizes,
$destinations [$dest][0],
$destinations [$dest][2],
$destinations [$dest][3]);
} else {
//set url to mime type icon or file dependant on Mime type
$fileInfo = wp_check_filetype( $name );
$type = wp_ext2type( $fileInfo['ext'] );
if( preg_match( '/^image/', $fileInfo['type'] ) )
$url = $targetUrl . DIRECTORY_SEPARATOR . $name;
else
$url = wp_mime_type_icon( $type );
echo json_encode( array(
'success' => true,
'data' => array( 'id' => false,
'url' => $url,
'name' => $name)
) );
wp_die();
}
if( $destinations[$dest][2] == 'Category' ) {
$category = get_term_by( 'name', $album, 'category' );
if( $category != false )
wp_set_object_terms( $attachment_id, intval($category->term_id), 'category' );
}
if( $destinations[$dest][2] == 'Wordpress Gallery' ) {
$gallery = get_post( $post_id );
if( $gallery->post_content == "" ) {
$gal_upd = array(
'ID' => $post_id,
'post_content' => '[gallery link="file" ids="' . $attachment_id . '"]'
);
// Update the post into the database
wp_update_post( $gal_upd );
} elseif( preg_match( '/^(.*\[gallery.+ids=".+)(".*)$/', $gallery->post_content, $matches) ) {
$gal_upd = array(
'ID' => $post_id,
'post_content' => $matches[1] . ',' . $attachment_id . $matches[2]
);
// Update the post into the database
wp_update_post( $gal_upd );
}
}
if ( ! $attachment = wp_prepare_attachment_for_js( $attachment_id ) )
wp_die();
echo json_encode( array(
'success' => true,
'data' => $attachment,
) );
wp_die();
}
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to find uploaded file.',
'code' => 104,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
function adv_upload_plupload() {
//check nounce is correct
check_ajax_referer('alt_upl_nonce' . get_current_user_id(),'security');
// Settings
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
// 5 minutes execution time
@set_time_limit(5 * 60);
// Get parameters
$post_id = isset($_REQUEST["post_id"]) ? intval($_REQUEST["post_id"]) : 0;
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
//get destinations from JSON object
$destinations = json_decode(stripcslashes($_REQUEST['destinations']));
$dest = isset($_REQUEST["fileDest"]) ? intval($_REQUEST["fileDest"]) : 0;
$targetDir = ABSPATH . $destinations [$dest][1];
$targetUrl = site_url() . DIRECTORY_SEPARATOR . $destinations [$dest][1];
// get a valid wordpress filesname
$fileName = wp_unique_filename($targetDir, $fileName);
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
$fileurl = $targetUrl . DIRECTORY_SEPARATOR . $fileName;
// Create target dir
if (!file_exists($targetDir))
@mkdir($targetDir);
// Remove old temp files
if ($cleanupTargetDir) {
if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
@unlink($tmpfilePath);
}
}
closedir($dir);
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open temp directory.',
'code' => 100,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
}
// Look for the content type header
if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
if (isset($_SERVER["CONTENT_TYPE"]))
$contentType = $_SERVER["CONTENT_TYPE"];
// Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
if (strpos($contentType, "multipart") !== false) {
if (isset($_FILES['async-upload']['tmp_name']) && is_uploaded_file($_FILES['async-upload']['tmp_name'])) {
// Open temp file
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen($_FILES['async-upload']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open input stream.',
'code' => 101,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
@fclose($in);
@fclose($out);
@unlink($_FILES['async-upload']['tmp_name']);
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open input stream.',
'code' => 102,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to move uploaded file.',
'code' => 103,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
} else {
// Open temp file
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen("php://input", "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open input stream.',
'code' => 101,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
@fclose($in);
@fclose($out);
} else {
echo json_encode( array(
'success' => false,
'data' => array(
'message' => 'Failed to open output stream.',
'code' => 102,
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
}
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// rename from temp filename
rename("{$filePath}.part", $filePath);
echo json_encode( array(
'success' => 'file_complete',
'data' => array(
'filename' => $_FILES['async-upload']['name'],
'name' => $fileName,
'file' => $fileurl,
)
) );
wp_die();
}
echo json_encode( array(
'success' => null,
'data' => array(
'filename' => $_FILES['async-upload']['name'],
)
) );
wp_die();
}
?>