function __construct() { add_action('init', array($this, 'action_init')); $this->allowed_mime_types = function_exists('wp_get_mime_types') ? wp_get_mime_types() : get_allowed_mime_types(); $this->has_correct_role = BYT_Theme_Utils::check_user_role(BOOKYOURTRAVEL_FRONTEND_SUBMIT_ROLE, $this->get_current_user_id()); $this->_html_helper = new Html_Helper(); }
function check_upload($errors) { $mime = get_allowed_mime_types(); $size_limit = (int) wp_convert_hr_to_bytes(fep_get_option('attachment_size', '4MB')); $fields = (int) fep_get_option('attachment_no', 4); for ($i = 0; $i < $fields; $i++) { $tmp_name = isset($_FILES['fep_upload']['tmp_name'][$i]) ? basename($_FILES['fep_upload']['tmp_name'][$i]) : ''; $file_name = isset($_FILES['fep_upload']['name'][$i]) ? basename($_FILES['fep_upload']['name'][$i]) : ''; //if file is uploaded if ($tmp_name) { $attach_type = wp_check_filetype($file_name); $attach_size = $_FILES['fep_upload']['size'][$i]; //check file size if ($attach_size > $size_limit) { $errors->add('AttachmentSize', sprintf(__("Attachment (%s) file is too big", 'fep'), $file_name)); } //check file type if (!in_array($attach_type['type'], $mime)) { $errors->add('AttachmentType', sprintf(__("Invalid attachment file type.Allowed Types are (%s)", 'fep'), implode(',', $mime))); } } // if $filename } // endfor //return $errors; }
function __construct() { global $sc_theme_globals; $this->sc_theme_globals = $sc_theme_globals; add_action('init', array($this, 'action_init')); $this->allowed_mime_types = function_exists('wp_get_mime_types') ? wp_get_mime_types() : get_allowed_mime_types(); $this->_html_helper = new Html_Helper(); }
function pugpig_adbundles_admin_notice() { $allowed_types = get_site_option('upload_filetypes'); if (!array_key_exists('zip', get_allowed_mime_types())) { ?> <div class="update-nag"><p><?php _e('Pugpig - Ad Bundles require zips to be in the allowed upload types.'); ?> </p></div> <?php } }
function allowed_file_types() { $allowed_file_types = array(); // http://codex.wordpress.org/Uploading_Files $mime_types = get_allowed_mime_types(); foreach ($mime_types as $type => $mime_type) { $extras = explode('|', $type); foreach ($extras as $extra) { $allowed_file_types[] = $extra; } } return $allowed_file_types; }
/** * Lista os formatos permitidos dentro do custom uploader * * @return array $allowed_mime_types Os tipos permitidos */ function get_custom_uploader_allowed_types($mime_types = array()) { if (empty($mime_types)) { $mime_types = get_allowed_mime_types(); } $allowed_mime_types = $mime_types; foreach ($mime_types as $key => $value) { if (wp_match_mime_types('image, audio, video', $value)) { unset($allowed_mime_types[$key]); } } return $allowed_mime_types; }
function display_ext() { echo '<input type="text" name="ext" id="ext" value="' . get_option('ext') . '" size="30" style="width:85%" />'; echo '<p><small>' . __('Entrez les extensions de fichier que vous souhaitez ajouter sans le point (séparé par un espace, ex: "mp3 doc gif")') . '</small></p>'; echo '<p><strong>' . __('Liste des extensions déjà disponibles : '); echo '</strong>'; $mimes = get_allowed_mime_types(); $type_aff = array(); foreach ($mimes as $ext => $mime) { $type_aff[] = str_replace('|', ', ', $ext); } echo implode(', ', $type_aff) . '</p>'; }
function wppb_upload_file_type($file) { if (isset($_POST['wppb_upload']) && $_POST['wppb_upload'] == 'true') { if (isset($_POST['meta_name']) && !empty($_POST['meta_name'])) { $meta_name = $_POST['meta_name']; /*let's get the field details so we can see if we have any file restrictions */ $all_fields = get_option('wppb_manage_fields'); if (!empty($all_fields)) { foreach ($all_fields as $field) { if ($field['meta-name'] == $meta_name) { $allowed_upload_extensions = ''; if ($field['field'] == 'Upload' && !empty($field['allowed-upload-extensions'])) { $allowed_upload_extensions = $field['allowed-upload-extensions']; } if ($field['field'] == 'Avatar' && !empty($field['allowed-image-extensions'])) { if (trim($field['allowed-image-extensions']) == '.*') { $allowed_upload_extensions = '.jpg,.jpeg,.gif,.png'; } else { $allowed_upload_extensions = $field['allowed-image-extensions']; } } $ext = strtolower(substr(strrchr($file['name'], '.'), 1)); if (!empty($allowed_upload_extensions) && $allowed_upload_extensions != '.*') { $allowed = str_replace('.', '', array_map('trim', explode(",", strtolower($allowed_upload_extensions)))); //first check if the user uploaded the right type if (!in_array($ext, (array) $allowed)) { $file['error'] = __("Sorry, you cannot upload this file type for this field.", 'profile-builder'); return $file; } } //check if the type is allowed at all by WordPress foreach (get_allowed_mime_types() as $key => $value) { if (strpos($key, $ext) !== false || $key == $ext) { return $file; } } $file['error'] = __("Sorry, you cannot upload this file type for this field.", 'profile-builder'); } } } } if (empty($_POST['meta_name'])) { $file['error'] = __("An error occurred, please try again later.", 'profile-builder'); } } return $file; }
function wp_check_filetype($filename, $mimes = null) { if (empty($mimes)) { $mimes = get_allowed_mime_types(); } $type = false; $ext = false; foreach ($mimes as $ext_preg => $mime_match) { $ext_preg = '!\\.(' . $ext_preg . ')(\\?.*)?$!i'; if (preg_match($ext_preg, $filename, $ext_matches)) { $type = $mime_match; $ext = $ext_matches[1]; break; } } return compact('ext', 'type'); }
/** * Get image mime types * * @since 0.1.0 * @return array */ protected function get_image_mime_types() { $mime_types = get_allowed_mime_types(); foreach ($mime_types as $id => $type) { if (false === strpos($type, 'image/')) { unset($mime_types[$id]); } } /** * Filter image mime types * * @since 0.1.0 * @param array $mime_types Image mime types. */ $mime_types = apply_filters('icon_picker_image_mime_types', $mime_types); // We need to exclude image/svg*. unset($mime_types['svg']); return $mime_types; }
function sanitize_file_name($filename) { $filename_raw = $filename; $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "\$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0)); // $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw); $filename = str_replace($special_chars, '', $filename); $filename = preg_replace('/[\\s-]+/', '-', $filename); $filename = trim($filename, '.-_'); // Split the filename into a base and extension[s] $parts = explode('.', $filename); // Return if only one extension if (count($parts) <= 2) { return $filename; } // Process multiple extensions $filename = array_shift($parts); $extension = array_pop($parts); $mimes = get_allowed_mime_types(); // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character // long alpha string not in the extension whitelist. foreach ((array) $parts as $part) { $filename .= '.' . $part; if (preg_match("/^[a-zA-Z]{2,5}\\d?\$/", $part)) { $allowed = false; foreach ($mimes as $ext_preg => $mime_match) { $ext_preg = '!^(' . $ext_preg . ')$!i'; if (preg_match($ext_preg, $part)) { $allowed = true; break; } } if (!$allowed) { $filename .= '_'; } } } $filename .= '.' . $extension; return $filename; }
function dynimg_404_handler() { if (!is_404()) { return; } if (preg_match('/(.*)-([0-9]+)x([0-9]+)(c)?\\.(jpg|png|gif)/i', $_SERVER['REQUEST_URI'], $matches)) { $filename = $matches[1] . '.' . $matches[5]; $width = $matches[2]; $height = $matches[3]; $crop = !empty($matches[4]); $uploads_dir = wp_upload_dir(); $temp = parse_url($uploads_dir['baseurl']); $upload_path = $temp['path']; $findfile = str_replace($upload_path, '', $filename); $basefile = $uploads_dir['basedir'] . $findfile; $suffix = $width . 'x' . $height; if ($crop) { $suffix .= 'c'; } if (file_exists($basefile)) { // we have the file, so call the wp function to actually resize the image // $resized = image_resize($basefile, $width, $height, $crop, $suffix); $resized = image_resize($basefile, $width, $height, true, $suffix); // find the mime type foreach (get_allowed_mime_types() as $exts => $mime) { if (preg_match('!^(' . $exts . ')$!i', $matches[5])) { $type = $mime; break; } } // serve the image this one time (next time the webserver will do it for us) header('Content-Type: ' . $type); header('Content-Length: ' . filesize($resized)); readfile($resized); exit; } } }
public function enqueue_scripts($override = false) { if (is_admin()) { return; } global $post; if (is_page(EDD_FES()->helper->get_option('fes-vendor-dashboard-page', false)) || $override) { wp_enqueue_script('jquery'); wp_enqueue_script('underscore'); // FES outputs minified scripts by default on the frontend. To load full versions, hook into this and return empty string. $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; $minify = apply_filters('fes_output_minified_versions', $suffix); wp_enqueue_script('fes_form', fes_plugin_url . 'assets/js/frontend-form' . $minify . '.js', array('jquery'), fes_plugin_version); wp_localize_script('fes_form', 'fes_form', array('ajaxurl' => admin_url('admin-ajax.php'), 'error_message' => __('Please fix the errors to proceed', 'edd_fes'), 'nonce' => wp_create_nonce('fes_nonce'), 'avatar_title' => __('Choose an avatar', 'edd_fes'), 'avatar_button' => __('Select as avatar', 'edd_fes'), 'file_title' => __('Choose a file', 'edd_fes'), 'file_button' => __('Insert file URL', 'edd_fes'), 'feat_title' => __('Choose a featured image', 'edd_fes'), 'feat_button' => __('Select as featured image', 'edd_fes'), 'one_option' => __('You must have at least one option', 'edd_fes'), 'too_many_files_pt_1' => __('You may not add more than ', 'edd_fes'), 'too_many_files_pt_2' => __(' files!', 'edd_fes'), 'file_types' => implode('|', array_keys(get_allowed_mime_types())))); wp_enqueue_media(); wp_enqueue_script('comment-reply'); wp_enqueue_script('jquery-ui-datepicker'); wp_enqueue_script('jquery-ui-autocomplete'); wp_enqueue_script('suggest'); wp_enqueue_script('jquery-ui-slider'); wp_enqueue_script('jquery-ui-timepicker', fes_plugin_url . 'assets/js/jquery-ui-timepicker-addon.js', array('jquery-ui-datepicker')); } }
/** * Download a file - hook into init function. * * @access public * @return void */ function woocommerce_download_product() { if (isset($_GET['download_file']) && isset($_GET['order']) && isset($_GET['email'])) { global $wpdb, $is_IE; $product_id = (int) urldecode($_GET['download_file']); $order_key = urldecode($_GET['order']); $email = sanitize_email(str_replace(' ', '+', urldecode($_GET['email']))); $download_id = isset($_GET['key']) ? urldecode($_GET['key']) : ''; // backwards compatibility for existing download URLs $_product = get_product($product_id); $file_download_method = apply_filters('woocommerce_file_download_method', get_option('woocommerce_file_download_method'), $product_id); if (!is_email($email)) { wp_die(__('Invalid email address.', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } $query = "\n\t\t\tSELECT order_id,downloads_remaining,user_id,download_count,access_expires,download_id\n\t\t\tFROM " . $wpdb->prefix . "woocommerce_downloadable_product_permissions\n\t\t\tWHERE user_email = %s\n\t\t\tAND order_key = %s\n\t\t\tAND product_id = %s"; $args = array($email, $order_key, $product_id); if ($download_id) { // backwards compatibility for existing download URLs $query .= " AND download_id = %s"; $args[] = $download_id; } $download_result = $wpdb->get_row($wpdb->prepare($query, $args)); if (!$download_result) { wp_die(__('Invalid download.', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } $download_id = $download_result->download_id; $order_id = $download_result->order_id; $downloads_remaining = $download_result->downloads_remaining; $download_count = $download_result->download_count; $user_id = $download_result->user_id; $access_expires = $download_result->access_expires; if ($user_id && get_option('woocommerce_downloads_require_login') == 'yes') { if (!is_user_logged_in()) { wp_die(__('You must be logged in to download files.', 'woocommerce') . ' <a href="' . wp_login_url(get_permalink(woocommerce_get_page_id('myaccount'))) . '">' . __('Login →', 'woocommerce') . '</a>'); } elseif ($user_id != get_current_user_id()) { wp_die(__('This is not your download link.', 'woocommerce')); } } if (!get_post($product_id)) { wp_die(__('Product no longer exists.', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } if ($order_id) { $order = new WC_Order($order_id); if (!$order->is_download_permitted() || $order->post_status != 'publish') { wp_die(__('Invalid order.', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } } if ($downloads_remaining == '0') { wp_die(__('Sorry, you have reached your download limit for this file', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } if ($access_expires > 0 && strtotime($access_expires) < current_time('timestamp')) { wp_die(__('Sorry, this download has expired', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } if ($downloads_remaining > 0) { $wpdb->update($wpdb->prefix . "woocommerce_downloadable_product_permissions", array('downloads_remaining' => $downloads_remaining - 1), array('user_email' => $email, 'order_key' => $order_key, 'product_id' => $product_id, 'download_id' => $download_id), array('%d'), array('%s', '%s', '%d', '%s')); } // Count the download $wpdb->update($wpdb->prefix . "woocommerce_downloadable_product_permissions", array('download_count' => $download_count + 1), array('user_email' => $email, 'order_key' => $order_key, 'product_id' => $product_id, 'download_id' => $download_id), array('%d'), array('%s', '%s', '%d', '%s')); // Trigger action do_action('woocommerce_download_product', $email, $order_key, $product_id, $user_id, $download_id, $order_id); // Get the download URL and try to replace the url with a path $file_path = $_product->get_file_download_path($download_id); if (!$file_path) { wp_die(__('No file defined', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } // Redirect to the file... if ($file_download_method == "redirect") { header('Location: ' . $file_path); exit; } // ...or serve it if (!is_multisite()) { /* * Download file may be either http or https. * site_url() depends on whether the page containing the download (ie; My Account) is served via SSL because WC * modifies site_url() via a filter to force_ssl. * So blindly doing a str_replace is incorrect because it will fail when schemes are mismatched. This code * handles the various permutations. */ $scheme = parse_url($file_path, PHP_URL_SCHEME); if ($scheme) { $site_url = set_url_scheme(site_url(''), $scheme); } else { $site_url = is_ssl() ? str_replace('https:', 'http:', site_url()) : site_url(); } $file_path = str_replace(trailingslashit($site_url), ABSPATH, $file_path); } else { $network_url = is_ssl() ? str_replace('https:', 'http:', network_admin_url()) : network_admin_url(); $upload_dir = wp_upload_dir(); // Try to replace network url $file_path = str_replace(trailingslashit($network_url), ABSPATH, $file_path); // Now try to replace upload URL $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $file_path); } // See if its local or remote if (strstr($file_path, 'http:') || strstr($file_path, 'https:') || strstr($file_path, 'ftp:')) { $remote_file = true; } else { $remote_file = false; // Remove Query String if (strstr($file_path, '?')) { $file_path = current(explode('?', $file_path)); } $file_path = realpath($file_path); } $file_extension = strtolower(substr(strrchr($file_path, "."), 1)); $ctype = "application/force-download"; foreach (get_allowed_mime_types() as $mime => $type) { $mimes = explode('|', $mime); if (in_array($file_extension, $mimes)) { $ctype = $type; break; } } // Start setting headers if (!ini_get('safe_mode')) { @set_time_limit(0); } if (function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime()) { @set_magic_quotes_runtime(0); } if (function_exists('apache_setenv')) { @apache_setenv('no-gzip', 1); } @session_write_close(); @ini_set('zlib.output_compression', 'Off'); @ob_end_clean(); if (ob_get_level()) { @ob_end_clean(); } // Zip corruption fix if ($is_IE && is_ssl()) { // IE bug prevents download via SSL when Cache Control and Pragma no-cache headers set. header('Expires: Wed, 11 Jan 1984 05:00:00 GMT'); header('Cache-Control: private'); } else { nocache_headers(); } $file_name = basename($file_path); if (strstr($file_name, '?')) { $file_name = current(explode('?', $file_name)); } header("Robots: none"); header("Content-Type: " . $ctype); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=\"" . $file_name . "\";"); header("Content-Transfer-Encoding: binary"); if ($size = @filesize($file_path)) { header("Content-Length: " . $size); } if ($file_download_method == 'xsendfile') { // Path fix - kudos to Jason Judge if (getcwd()) { $file_path = trim(preg_replace('`^' . getcwd() . '`', '', $file_path), '/'); } header("Content-Disposition: attachment; filename=\"" . $file_name . "\";"); if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) { header("X-Sendfile: {$file_path}"); exit; } elseif (stristr(getenv('SERVER_SOFTWARE'), 'lighttpd')) { header("X-Lighttpd-Sendfile: {$file_path}"); exit; } elseif (stristr(getenv('SERVER_SOFTWARE'), 'nginx') || stristr(getenv('SERVER_SOFTWARE'), 'cherokee')) { header("X-Accel-Redirect: /{$file_path}"); exit; } } if ($remote_file) { @woocommerce_readfile_chunked($file_path) or header('Location: ' . $file_path); } else { @woocommerce_readfile_chunked($file_path) or wp_die(__('File not found', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } exit; } }
/** * Recursively go through uploads directories and get a batch of media files. * Stops when it has scanned all files/directories or after it has run for * $this->media_files_batch_time_limit seconds, whichever comes first. * * @param string $dir The directory to start in * @param string $start_filename The file or directory to start at within $dir * @param array $local_media_files Array to populate with media files found */ function get_local_media_files_batch_recursive($dir, $start_filename, &$local_media_files) { $upload_dir = $this->uploads_dir(); static $allowed_mime_types; if (is_null($allowed_mime_types)) { $allowed_mime_types = array_flip(get_allowed_mime_types()); } static $finish_time; if (is_null($finish_time)) { $finish_time = microtime(true) + $this->media_files_batch_time_limit; } $dir = '/' == $dir ? '' : $dir; $dir_path = $upload_dir . $dir; $sub_paths = glob($dir_path . '*', GLOB_MARK); // Get all the files except the one we use to store backups. $wpmdb_upload_folder = $this->get_upload_info(); $pattern = '/' . preg_quote($wpmdb_upload_folder, '/') . '/'; $files = preg_grep($pattern, $sub_paths ? $sub_paths : array(), PREG_GREP_INVERT); $reached_start_file = false; foreach ($files as $file_path) { if (microtime(true) >= $finish_time) { break; } // Are we starting from a certain file within the directory? // If so, we skip all the files that come before it. if ($start_filename) { if (basename($file_path) == $start_filename) { $reached_start_file = true; continue; } elseif (!$reached_start_file) { continue; } } $short_file_path = str_replace(array($upload_dir, '\\'), array('', '/'), $file_path); // Is directory? We use this instead of is_dir() to save us an I/O call if (substr($file_path, -1) == DIRECTORY_SEPARATOR) { $this->get_local_media_files_batch_recursive($short_file_path, '', $local_media_files); continue; } // ignore files that we shouldn't touch, e.g. .php, .sql, etc $filetype = wp_check_filetype($short_file_path); if (!isset($allowed_mime_types[$filetype['type']])) { continue; } if (apply_filters('wpmdbmf_exclude_local_media_file_from_removal', false, $upload_dir, $short_file_path, $this)) { continue; } $local_media_files[] = $short_file_path; } }
/** * Enqueues all scripts, styles, settings, and templates necessary to use * all media JS APIs. * * @since 3.5.0 * * @global int $content_width * @global wpdb $wpdb * @global WP_Locale $wp_locale * * @param array $args { * Arguments for enqueuing media scripts. * * @type int|WP_Post A post object or ID. * } */ function wp_enqueue_media($args = array()) { // Enqueue me just once per page, please. if (did_action('wp_enqueue_media')) { return; } global $content_width, $wpdb, $wp_locale; $defaults = array('post' => null); $args = wp_parse_args($args, $defaults); // We're going to pass the old thickbox media tabs to `media_upload_tabs` // to ensure plugins will work. We will then unset those tabs. $tabs = array('type' => '', 'type_url' => '', 'gallery' => '', 'library' => ''); /** This filter is documented in wp-admin/includes/media.php */ $tabs = apply_filters('media_upload_tabs', $tabs); unset($tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library']); $props = array('link' => get_option('image_default_link_type'), 'align' => get_option('image_default_align'), 'size' => get_option('image_default_size')); $exts = array_merge(wp_get_audio_extensions(), wp_get_video_extensions()); $mimes = get_allowed_mime_types(); $ext_mimes = array(); foreach ($exts as $ext) { foreach ($mimes as $ext_preg => $mime_match) { if (preg_match('#' . $ext . '#i', $ext_preg)) { $ext_mimes[$ext] = $mime_match; break; } } } $has_audio = $wpdb->get_var("\n\t\tSELECT ID\n\t\tFROM {$wpdb->posts}\n\t\tWHERE post_type = 'attachment'\n\t\tAND post_mime_type LIKE 'audio%'\n\t\tLIMIT 1\n\t"); $has_video = $wpdb->get_var("\n\t\tSELECT ID\n\t\tFROM {$wpdb->posts}\n\t\tWHERE post_type = 'attachment'\n\t\tAND post_mime_type LIKE 'video%'\n\t\tLIMIT 1\n\t"); $months = $wpdb->get_results($wpdb->prepare("\n\t\tSELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month\n\t\tFROM {$wpdb->posts}\n\t\tWHERE post_type = %s\n\t\tORDER BY post_date DESC\n\t", 'attachment')); foreach ($months as $month_year) { $month_year->text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($month_year->month), $month_year->year); } $settings = array('tabs' => $tabs, 'tabUrl' => add_query_arg(array('chromeless' => true), admin_url('media-upload.php')), 'mimeTypes' => wp_list_pluck(get_post_mime_types(), 0), 'captions' => !apply_filters('disable_captions', ''), 'nonce' => array('sendToEditor' => wp_create_nonce('media-send-to-editor')), 'post' => array('id' => 0), 'defaultProps' => $props, 'attachmentCounts' => array('audio' => $has_audio ? 1 : 0, 'video' => $has_video ? 1 : 0), 'embedExts' => $exts, 'embedMimes' => $ext_mimes, 'contentWidth' => $content_width, 'months' => $months, 'mediaTrash' => MEDIA_TRASH ? 1 : 0); $post = null; if (isset($args['post'])) { $post = get_post($args['post']); $settings['post'] = array('id' => $post->ID, 'nonce' => wp_create_nonce('update-post_' . $post->ID)); $thumbnail_support = current_theme_supports('post-thumbnails', $post->post_type) && post_type_supports($post->post_type, 'thumbnail'); if (!$thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type) { if (wp_attachment_is('audio', $post)) { $thumbnail_support = post_type_supports('attachment:audio', 'thumbnail') || current_theme_supports('post-thumbnails', 'attachment:audio'); } elseif (wp_attachment_is('video', $post)) { $thumbnail_support = post_type_supports('attachment:video', 'thumbnail') || current_theme_supports('post-thumbnails', 'attachment:video'); } } if ($thumbnail_support) { $featured_image_id = get_post_meta($post->ID, '_thumbnail_id', true); $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1; } } if ($post) { $post_type_object = get_post_type_object($post->post_type); } else { $post_type_object = get_post_type_object('post'); } $strings = array('url' => __('URL'), 'addMedia' => __('Add Media'), 'search' => __('Search'), 'select' => __('Select'), 'cancel' => __('Cancel'), 'update' => __('Update'), 'replace' => __('Replace'), 'remove' => __('Remove'), 'back' => __('Back'), 'selected' => __('%d selected'), 'dragInfo' => __('Drag and drop to reorder media files.'), 'uploadFilesTitle' => __('Upload Files'), 'uploadImagesTitle' => __('Upload Images'), 'mediaLibraryTitle' => __('Media Library'), 'insertMediaTitle' => __('Insert Media'), 'createNewGallery' => __('Create a new gallery'), 'createNewPlaylist' => __('Create a new playlist'), 'createNewVideoPlaylist' => __('Create a new video playlist'), 'returnToLibrary' => __('← Return to library'), 'allMediaItems' => __('All media items'), 'allDates' => __('All dates'), 'noItemsFound' => __('No items found.'), 'insertIntoPost' => $post_type_object->labels->insert_into_item, 'unattached' => __('Unattached'), 'trash' => _x('Trash', 'noun'), 'uploadedToThisPost' => $post_type_object->labels->uploaded_to_this_item, 'warnDelete' => __("You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete."), 'warnBulkDelete' => __("You are about to permanently delete these items.\n 'Cancel' to stop, 'OK' to delete."), 'warnBulkTrash' => __("You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete."), 'bulkSelect' => __('Bulk Select'), 'cancelSelection' => __('Cancel Selection'), 'trashSelected' => __('Trash Selected'), 'untrashSelected' => __('Untrash Selected'), 'deleteSelected' => __('Delete Selected'), 'deletePermanently' => __('Delete Permanently'), 'apply' => __('Apply'), 'filterByDate' => __('Filter by date'), 'filterByType' => __('Filter by type'), 'searchMediaLabel' => __('Search Media'), 'noMedia' => __('No media attachments found.'), 'attachmentDetails' => __('Attachment Details'), 'insertFromUrlTitle' => __('Insert from URL'), 'setFeaturedImageTitle' => $post_type_object->labels->featured_image, 'setFeaturedImage' => $post_type_object->labels->set_featured_image, 'createGalleryTitle' => __('Create Gallery'), 'editGalleryTitle' => __('Edit Gallery'), 'cancelGalleryTitle' => __('← Cancel Gallery'), 'insertGallery' => __('Insert gallery'), 'updateGallery' => __('Update gallery'), 'addToGallery' => __('Add to gallery'), 'addToGalleryTitle' => __('Add to Gallery'), 'reverseOrder' => __('Reverse order'), 'imageDetailsTitle' => __('Image Details'), 'imageReplaceTitle' => __('Replace Image'), 'imageDetailsCancel' => __('Cancel Edit'), 'editImage' => __('Edit Image'), 'chooseImage' => __('Choose Image'), 'selectAndCrop' => __('Select and Crop'), 'skipCropping' => __('Skip Cropping'), 'cropImage' => __('Crop Image'), 'cropYourImage' => __('Crop your image'), 'cropping' => __('Cropping…'), 'suggestedDimensions' => __('Suggested image dimensions:'), 'cropError' => __('There has been an error cropping your image.'), 'audioDetailsTitle' => __('Audio Details'), 'audioReplaceTitle' => __('Replace Audio'), 'audioAddSourceTitle' => __('Add Audio Source'), 'audioDetailsCancel' => __('Cancel Edit'), 'videoDetailsTitle' => __('Video Details'), 'videoReplaceTitle' => __('Replace Video'), 'videoAddSourceTitle' => __('Add Video Source'), 'videoDetailsCancel' => __('Cancel Edit'), 'videoSelectPosterImageTitle' => __('Select Poster Image'), 'videoAddTrackTitle' => __('Add Subtitles'), 'playlistDragInfo' => __('Drag and drop to reorder tracks.'), 'createPlaylistTitle' => __('Create Audio Playlist'), 'editPlaylistTitle' => __('Edit Audio Playlist'), 'cancelPlaylistTitle' => __('← Cancel Audio Playlist'), 'insertPlaylist' => __('Insert audio playlist'), 'updatePlaylist' => __('Update audio playlist'), 'addToPlaylist' => __('Add to audio playlist'), 'addToPlaylistTitle' => __('Add to Audio Playlist'), 'videoPlaylistDragInfo' => __('Drag and drop to reorder videos.'), 'createVideoPlaylistTitle' => __('Create Video Playlist'), 'editVideoPlaylistTitle' => __('Edit Video Playlist'), 'cancelVideoPlaylistTitle' => __('← Cancel Video Playlist'), 'insertVideoPlaylist' => __('Insert video playlist'), 'updateVideoPlaylist' => __('Update video playlist'), 'addToVideoPlaylist' => __('Add to video playlist'), 'addToVideoPlaylistTitle' => __('Add to Video Playlist')); /** * Filter the media view settings. * * @since 3.5.0 * * @param array $settings List of media view settings. * @param WP_Post $post Post object. */ $settings = apply_filters('media_view_settings', $settings, $post); /** * Filter the media view strings. * * @since 3.5.0 * * @param array $strings List of media view strings. * @param WP_Post $post Post object. */ $strings = apply_filters('media_view_strings', $strings, $post); $strings['settings'] = $settings; // Ensure we enqueue media-editor first, that way media-views is // registered internally before we try to localize it. see #24724. wp_enqueue_script('media-editor'); wp_localize_script('media-views', '_wpMediaViewsL10n', $strings); wp_enqueue_script('media-audiovideo'); wp_enqueue_style('media-views'); if (is_admin()) { wp_enqueue_script('mce-view'); wp_enqueue_script('image-edit'); } wp_enqueue_style('imgareaselect'); wp_plupload_default_settings(); require_once ABSPATH . WPINC . '/media-template.php'; add_action('admin_footer', 'wp_print_media_templates'); add_action('wp_footer', 'wp_print_media_templates'); add_action('customize_controls_print_footer_scripts', 'wp_print_media_templates'); /** * Fires at the conclusion of wp_enqueue_media(). * * @since 3.5.0 */ do_action('wp_enqueue_media'); }
/** * Allowed mime types array that can be edited for specific S3 uploading * * @return array */ function get_allowed_mime_types() { return apply_filters('as3cf_allowed_mime_types', get_allowed_mime_types()); }
/** * Returns array of detected URLs for theme templates * * @param string $theme_name * @return array */ function get_theme_urls($theme_name) { $urls = array(); $theme = w3tc_get_theme($theme_name); if ($theme && isset($theme['Template Files'])) { $front_page_template = false; if (get_option('show_on_front') == 'page') { $front_page_id = get_option('page_on_front'); if ($front_page_id) { $front_page_template_file = get_post_meta($front_page_id, '_wp_page_template', true); if ($front_page_template_file) { $front_page_template = basename($front_page_template_file, '.php'); } } } $home_url = w3_get_home_url(); $template_files = (array) $theme['Template Files']; $mime_types = get_allowed_mime_types(); $custom_mime_types = array(); foreach ($mime_types as $mime_type) { list($type1, $type2) = explode('/', $mime_type); $custom_mime_types = array_merge($custom_mime_types, array($type1, $type2, $type1 . '_' . $type2)); } foreach ($template_files as $template_file) { $link = false; $template = basename($template_file, '.php'); /** * Check common templates */ switch (true) { /** * Handle home.php or index.php or front-page.php */ case !$front_page_template && $template == 'home': case !$front_page_template && $template == 'index': case !$front_page_template && $template == 'front-page': /** * Handle custom home page */ /** * Handle custom home page */ case $template == $front_page_template: $link = $home_url . '/'; break; /** * Handle 404.php */ /** * Handle 404.php */ case $template == '404': $permalink = get_option('permalink_structure'); if ($permalink) { $link = sprintf('%s/%s/', $home_url, '404_test'); } else { $link = sprintf('%s/?p=%d', $home_url, 999999999); } break; /** * Handle search.php */ /** * Handle search.php */ case $template == 'search': $link = sprintf('%s/?s=%s', $home_url, 'search_test'); break; /** * Handle date.php or archive.php */ /** * Handle date.php or archive.php */ case $template == 'date': case $template == 'archive': $posts = get_posts(array('numberposts' => 1, 'orderby' => 'rand')); if (is_array($posts) && count($posts)) { $time = strtotime($posts[0]->post_date); $link = get_day_link(date('Y', $time), date('m', $time), date('d', $time)); } break; /** * Handle author.php */ /** * Handle author.php */ case $template == 'author': $author_id = false; if (function_exists('get_users')) { $users = get_users(); if (is_array($users) && count($users)) { $user = current($users); $author_id = $user->ID; } } else { $author_ids = get_author_user_ids(); if (is_array($author_ids) && count($author_ids)) { $author_id = $author_ids[0]; } } if ($author_id) { $link = get_author_posts_url($author_id); } break; /** * Handle category.php */ /** * Handle category.php */ case $template == 'category': $category_ids = get_all_category_ids(); if (is_array($category_ids) && count($category_ids)) { $link = get_category_link($category_ids[0]); } break; /** * Handle tag.php */ /** * Handle tag.php */ case $template == 'tag': $term_ids = get_terms('post_tag', 'fields=ids'); if (is_array($term_ids) && count($term_ids)) { $link = get_term_link($term_ids[0], 'post_tag'); } break; /** * Handle taxonomy.php */ /** * Handle taxonomy.php */ case $template == 'taxonomy': $taxonomy = ''; if (isset($GLOBALS['wp_taxonomies']) && is_array($GLOBALS['wp_taxonomies'])) { foreach ($GLOBALS['wp_taxonomies'] as $wp_taxonomy) { if (!in_array($wp_taxonomy->name, array('category', 'post_tag', 'link_category'))) { $taxonomy = $wp_taxonomy->name; break; } } } if ($taxonomy) { $terms = get_terms($taxonomy, array('number' => 1)); if (is_array($terms) && count($terms)) { $link = get_term_link($terms[0], $taxonomy); } } break; /** * Handle attachment.php */ /** * Handle attachment.php */ case $template == 'attachment': $attachments = get_posts(array('post_type' => 'attachment', 'numberposts' => 1, 'orderby' => 'rand')); if (is_array($attachments) && count($attachments)) { $link = get_attachment_link($attachments[0]->ID); } break; /** * Handle single.php */ /** * Handle single.php */ case $template == 'single': $posts = get_posts(array('numberposts' => 1, 'orderby' => 'rand')); if (is_array($posts) && count($posts)) { $link = get_permalink($posts[0]->ID); } break; /** * Handle page.php */ /** * Handle page.php */ case $template == 'page': $pages_ids = get_all_page_ids(); if (is_array($pages_ids) && count($pages_ids)) { $link = get_page_link($pages_ids[0]); } break; /** * Handle comments-popup.php */ /** * Handle comments-popup.php */ case $template == 'comments-popup': $posts = get_posts(array('numberposts' => 1, 'orderby' => 'rand')); if (is_array($posts) && count($posts)) { $link = sprintf('%s/?comments_popup=%d', $home_url, $posts[0]->ID); } break; /** * Handle paged.php */ /** * Handle paged.php */ case $template == 'paged': global $wp_rewrite; if ($wp_rewrite->using_permalinks()) { $link = sprintf('%s/page/%d/', $home_url, 1); } else { $link = sprintf('%s/?paged=%d', 1); } break; /** * Handle author-id.php or author-nicename.php */ /** * Handle author-id.php or author-nicename.php */ case preg_match('~^author-(.+)$~', $template, $matches): if (is_numeric($matches[1])) { $link = get_author_posts_url($matches[1]); } else { $link = get_author_posts_url(null, $matches[1]); } break; /** * Handle category-id.php or category-slug.php */ /** * Handle category-id.php or category-slug.php */ case preg_match('~^category-(.+)$~', $template, $matches): if (is_numeric($matches[1])) { $link = get_category_link($matches[1]); } else { $term = get_term_by('slug', $matches[1], 'category'); if (is_object($term)) { $link = get_category_link($term->term_id); } } break; /** * Handle tag-id.php or tag-slug.php */ /** * Handle tag-id.php or tag-slug.php */ case preg_match('~^tag-(.+)$~', $template, $matches): if (is_numeric($matches[1])) { $link = get_tag_link($matches[1]); } else { $term = get_term_by('slug', $matches[1], 'post_tag'); if (is_object($term)) { $link = get_tag_link($term->term_id); } } break; /** * Handle taxonomy-taxonomy-term.php */ /** * Handle taxonomy-taxonomy-term.php */ case preg_match('~^taxonomy-(.+)-(.+)$~', $template, $matches): $link = get_term_link($matches[2], $matches[1]); break; /** * Handle taxonomy-taxonomy.php */ /** * Handle taxonomy-taxonomy.php */ case preg_match('~^taxonomy-(.+)$~', $template, $matches): $terms = get_terms($matches[1], array('number' => 1)); if (is_array($terms) && count($terms)) { $link = get_term_link($terms[0], $matches[1]); } break; /** * Handle MIME_type.php */ /** * Handle MIME_type.php */ case in_array($template, $custom_mime_types): $posts = get_posts(array('post_mime_type' => '%' . $template . '%', 'post_type' => 'attachment', 'numberposts' => 1, 'orderby' => 'rand')); if (is_array($posts) && count($posts)) { $link = get_permalink($posts[0]->ID); } break; /** * Handle single-posttype.php */ /** * Handle single-posttype.php */ case preg_match('~^single-(.+)$~', $template, $matches): $posts = get_posts(array('post_type' => $matches[1], 'numberposts' => 1, 'orderby' => 'rand')); if (is_array($posts) && count($posts)) { $link = get_permalink($posts[0]->ID); } break; /** * Handle page-id.php or page-slug.php */ /** * Handle page-id.php or page-slug.php */ case preg_match('~^page-(.+)$~', $template, $matches): if (is_numeric($matches[1])) { $link = get_permalink($matches[1]); } else { $posts = get_posts(array('pagename' => $matches[1], 'post_type' => 'page', 'numberposts' => 1)); if (is_array($posts) && count($posts)) { $link = get_permalink($posts[0]->ID); } } break; /** * Try to handle custom template */ /** * Try to handle custom template */ default: $posts = get_posts(array('pagename' => $template, 'post_type' => 'page', 'numberposts' => 1)); if (is_array($posts) && count($posts)) { $link = get_permalink($posts[0]->ID); } break; } if ($link && !is_wp_error($link)) { $urls[$template] = $link; } } } return $urls; }
/** * @ticket 21594 */ function test_get_allowed_mime_types() { $mimes = get_allowed_mime_types(); $this->assertInternalType('array', $mimes); $this->assertNotEmpty($mimes); add_filter('upload_mimes', '__return_empty_array'); $mimes = get_allowed_mime_types(); $this->assertInternalType('array', $mimes); $this->assertEmpty($mimes); remove_filter('upload_mimes', '__return_empty_array'); $mimes = get_allowed_mime_types(); $this->assertInternalType('array', $mimes); $this->assertNotEmpty($mimes); }
/** * Validate the allowed mime types using WordPress allowed mime types. * * In case of a multisite, the mime types are already restricted by * the 'upload_filetypes' setting. BuddyPress will respect this setting. * * @see check_upload_mimes() * * @since 2.3.0 * */ protected function validate_mime_types() { $wp_mimes = get_allowed_mime_types(); $valid_mimes = array(); // Set the allowed mimes for the upload. foreach ((array) $this->allowed_mime_types as $ext) { foreach ($wp_mimes as $ext_pattern => $mime) { if ($ext !== '' && strpos($ext_pattern, $ext) !== false) { $valid_mimes[$ext_pattern] = $mime; } } } return $valid_mimes; }
/** * Retrieves the supported media types. * * Media types are considered the MIME type category. * * @since 4.7.0 * @access protected * * @return array Array of supported media types. */ protected function get_media_types() { $media_types = array(); foreach (get_allowed_mime_types() as $mime_type) { $parts = explode('/', $mime_type); if (!isset($media_types[$parts[0]])) { $media_types[$parts[0]] = array(); } $media_types[$parts[0]][] = $mime_type; } return $media_types; }
/** * Upload a file using WordPress file API. * @param array $file_data Array of $_FILE data to upload. * @param array $args Optional arguments * @return array|WP_Error Array of objects containing either file information or an error */ function job_manager_upload_file($file, $args = array()) { global $job_manager_upload, $job_manager_uploading_file; include_once ABSPATH . 'wp-admin/includes/file.php'; include_once ABSPATH . 'wp-admin/includes/media.php'; $args = wp_parse_args($args, array('file_key' => '', 'file_label' => '', 'allowed_mime_types' => get_allowed_mime_types())); $job_manager_upload = true; $job_manager_uploading_file = $args['file_key']; $uploaded_file = new stdClass(); if (!in_array($file['type'], $args['allowed_mime_types'])) { if ($args['file_label']) { return new WP_Error('upload', sprintf(__('"%s" (filetype %s) needs to be one of the following file types: %s', 'wp-job-manager'), $args['file_label'], $file['type'], implode(', ', array_keys($args['allowed_mime_types'])))); } else { return new WP_Error('upload', sprintf(__('Uploaded files need to be one of the following file types: %s', 'wp-job-manager'), implode(', ', array_keys($args['allowed_mime_types'])))); } } else { $upload = wp_handle_upload($file, apply_filters('submit_job_wp_handle_upload_overrides', array('test_form' => false))); if (!empty($upload['error'])) { return new WP_Error('upload', $upload['error']); } else { $uploaded_file->url = $upload['url']; $uploaded_file->file = $upload['file']; $uploaded_file->name = basename($upload['file']); $uploaded_file->type = $upload['type']; $uploaded_file->size = $file['size']; $uploaded_file->extension = substr(strrchr($uploaded_file->name, '.'), 1); } } $job_manager_upload = false; $job_manager_uploading_file = ''; return $uploaded_file; }
/** * Save meta box data * * @deprecated 2.4.0 Deprecated in favor to WC_AJAX::save_variations() */ public static function save_variations($post_id, $post) { global $wpdb; $attributes = (array) maybe_unserialize(get_post_meta($post_id, '_product_attributes', true)); if (isset($_POST['variable_sku'])) { $variable_post_id = $_POST['variable_post_id']; $variable_sku = $_POST['variable_sku']; $variable_regular_price = $_POST['variable_regular_price']; $variable_sale_price = $_POST['variable_sale_price']; $upload_image_id = $_POST['upload_image_id']; $variable_download_limit = $_POST['variable_download_limit']; $variable_download_expiry = $_POST['variable_download_expiry']; $variable_shipping_class = $_POST['variable_shipping_class']; $variable_tax_class = isset($_POST['variable_tax_class']) ? $_POST['variable_tax_class'] : array(); $variable_menu_order = $_POST['variation_menu_order']; $variable_sale_price_dates_from = $_POST['variable_sale_price_dates_from']; $variable_sale_price_dates_to = $_POST['variable_sale_price_dates_to']; $variable_weight = isset($_POST['variable_weight']) ? $_POST['variable_weight'] : array(); $variable_length = isset($_POST['variable_length']) ? $_POST['variable_length'] : array(); $variable_width = isset($_POST['variable_width']) ? $_POST['variable_width'] : array(); $variable_height = isset($_POST['variable_height']) ? $_POST['variable_height'] : array(); $variable_enabled = isset($_POST['variable_enabled']) ? $_POST['variable_enabled'] : array(); $variable_is_virtual = isset($_POST['variable_is_virtual']) ? $_POST['variable_is_virtual'] : array(); $variable_is_downloadable = isset($_POST['variable_is_downloadable']) ? $_POST['variable_is_downloadable'] : array(); $variable_manage_stock = isset($_POST['variable_manage_stock']) ? $_POST['variable_manage_stock'] : array(); $variable_stock = isset($_POST['variable_stock']) ? $_POST['variable_stock'] : array(); $variable_backorders = isset($_POST['variable_backorders']) ? $_POST['variable_backorders'] : array(); $variable_stock_status = isset($_POST['variable_stock_status']) ? $_POST['variable_stock_status'] : array(); $variable_description = isset($_POST['variable_description']) ? $_POST['variable_description'] : array(); $max_loop = max(array_keys($_POST['variable_post_id'])); for ($i = 0; $i <= $max_loop; $i++) { if (!isset($variable_post_id[$i])) { continue; } $variation_id = absint($variable_post_id[$i]); // Checkboxes $is_virtual = isset($variable_is_virtual[$i]) ? 'yes' : 'no'; $is_downloadable = isset($variable_is_downloadable[$i]) ? 'yes' : 'no'; $post_status = isset($variable_enabled[$i]) ? 'publish' : 'private'; $manage_stock = isset($variable_manage_stock[$i]) ? 'yes' : 'no'; // Generate a useful post title $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), absint($variation_id), esc_html(get_the_title($post_id))); // Update or Add post if (!$variation_id) { $variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $post_id, 'post_type' => 'product_variation', 'menu_order' => $variable_menu_order[$i]); $variation_id = wp_insert_post($variation); do_action('woocommerce_create_product_variation', $variation_id); } else { $wpdb->update($wpdb->posts, array('post_status' => $post_status, 'post_title' => $variation_post_title, 'menu_order' => $variable_menu_order[$i]), array('ID' => $variation_id)); do_action('woocommerce_update_product_variation', $variation_id); } // Only continue if we have a variation ID if (!$variation_id) { continue; } // Unique SKU $sku = get_post_meta($variation_id, '_sku', true); $new_sku = wc_clean(stripslashes($variable_sku[$i])); if ('' == $new_sku) { update_post_meta($variation_id, '_sku', ''); } elseif ($new_sku !== $sku) { if (!empty($new_sku)) { $unique_sku = wc_product_has_unique_sku($variation_id, $new_sku); if (!$unique_sku) { WC_Admin_Meta_Boxes::add_error(__('Variation SKU must be unique.', 'woocommerce')); } else { update_post_meta($variation_id, '_sku', $new_sku); } } else { update_post_meta($variation_id, '_sku', ''); } } // Update post meta update_post_meta($variation_id, '_thumbnail_id', absint($upload_image_id[$i])); update_post_meta($variation_id, '_virtual', wc_clean($is_virtual)); update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable)); if (isset($variable_weight[$i])) { update_post_meta($variation_id, '_weight', '' === $variable_weight[$i] ? '' : wc_format_decimal($variable_weight[$i])); } if (isset($variable_length[$i])) { update_post_meta($variation_id, '_length', '' === $variable_length[$i] ? '' : wc_format_decimal($variable_length[$i])); } if (isset($variable_width[$i])) { update_post_meta($variation_id, '_width', '' === $variable_width[$i] ? '' : wc_format_decimal($variable_width[$i])); } if (isset($variable_height[$i])) { update_post_meta($variation_id, '_height', '' === $variable_height[$i] ? '' : wc_format_decimal($variable_height[$i])); } // Stock handling update_post_meta($variation_id, '_manage_stock', $manage_stock); // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level if (!empty($variable_stock_status[$i])) { wc_update_product_stock_status($variation_id, $variable_stock_status[$i]); } if ('yes' === $manage_stock) { update_post_meta($variation_id, '_backorders', wc_clean($variable_backorders[$i])); wc_update_product_stock($variation_id, wc_stock_amount($variable_stock[$i])); } else { delete_post_meta($variation_id, '_backorders'); delete_post_meta($variation_id, '_stock'); } // Price handling $regular_price = wc_format_decimal($variable_regular_price[$i]); $sale_price = $variable_sale_price[$i] === '' ? '' : wc_format_decimal($variable_sale_price[$i]); $date_from = wc_clean($variable_sale_price_dates_from[$i]); $date_to = wc_clean($variable_sale_price_dates_to[$i]); update_post_meta($variation_id, '_regular_price', $regular_price); update_post_meta($variation_id, '_sale_price', $sale_price); // Save Dates update_post_meta($variation_id, '_sale_price_dates_from', $date_from ? strtotime($date_from) : ''); update_post_meta($variation_id, '_sale_price_dates_to', $date_to ? strtotime($date_to) : ''); if ($date_to && !$date_from) { update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp'))); } // Update price if on sale if ('' !== $sale_price && '' === $date_to && '' === $date_from) { update_post_meta($variation_id, '_price', $sale_price); } else { update_post_meta($variation_id, '_price', $regular_price); } if ('' !== $sale_price && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) { update_post_meta($variation_id, '_price', $sale_price); } if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) { update_post_meta($variation_id, '_price', $regular_price); update_post_meta($variation_id, '_sale_price_dates_from', ''); update_post_meta($variation_id, '_sale_price_dates_to', ''); } if (isset($variable_tax_class[$i]) && $variable_tax_class[$i] !== 'parent') { update_post_meta($variation_id, '_tax_class', wc_clean($variable_tax_class[$i])); } else { delete_post_meta($variation_id, '_tax_class'); } if ('yes' == $is_downloadable) { update_post_meta($variation_id, '_download_limit', wc_clean($variable_download_limit[$i])); update_post_meta($variation_id, '_download_expiry', wc_clean($variable_download_expiry[$i])); $files = array(); $file_names = isset($_POST['_wc_variation_file_names'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_names'][$variation_id]) : array(); $file_urls = isset($_POST['_wc_variation_file_urls'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_urls'][$variation_id]) : array(); $file_url_size = sizeof($file_urls); $allowed_file_types = get_allowed_mime_types(); for ($ii = 0; $ii < $file_url_size; $ii++) { if (!empty($file_urls[$ii])) { // Find type and file URL if (0 === strpos($file_urls[$ii], 'http')) { $file_is = 'absolute'; $file_url = esc_url_raw($file_urls[$ii]); } elseif ('[' === substr($file_urls[$ii], 0, 1) && ']' === substr($file_urls[$ii], -1)) { $file_is = 'shortcode'; $file_url = wc_clean($file_urls[$ii]); } else { $file_is = 'relative'; $file_url = wc_clean($file_urls[$ii]); } $file_name = wc_clean($file_names[$ii]); $file_hash = md5($file_url); // Validate the file extension if (in_array($file_is, array('absolute', 'relative'))) { $file_type = wp_check_filetype(strtok($file_url, '?')); $parsed_url = parse_url($file_url, PHP_URL_PATH); $extension = pathinfo($parsed_url, PATHINFO_EXTENSION); if (!empty($extension) && !in_array($file_type['type'], $allowed_file_types)) { WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not have an allowed file type. Allowed types include: %s', 'woocommerce'), '<code>' . basename($file_url) . '</code>', '<code>' . implode(', ', array_keys($allowed_file_types)) . '</code>')); continue; } } // Validate the file exists if ('relative' === $file_is && !apply_filters('woocommerce_downloadable_file_exists', file_exists($file_url), $file_url)) { WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not exist on the server.', 'woocommerce'), '<code>' . $file_url . '</code>')); continue; } $files[$file_hash] = array('name' => $file_name, 'file' => $file_url); } } // grant permission to any newly added files on any existing orders for this product prior to saving do_action('woocommerce_process_product_file_download_paths', $post_id, $variation_id, $files); update_post_meta($variation_id, '_downloadable_files', $files); } else { update_post_meta($variation_id, '_download_limit', ''); update_post_meta($variation_id, '_download_expiry', ''); update_post_meta($variation_id, '_downloadable_files', ''); } update_post_meta($variation_id, '_variation_description', wp_kses_post($variable_description[$i])); // Save shipping class $variable_shipping_class[$i] = !empty($variable_shipping_class[$i]) ? (int) $variable_shipping_class[$i] : ''; wp_set_object_terms($variation_id, $variable_shipping_class[$i], 'product_shipping_class'); // Update Attributes $updated_attribute_keys = array(); foreach ($attributes as $attribute) { if ($attribute['is_variation']) { $attribute_key = 'attribute_' . sanitize_title($attribute['name']); $updated_attribute_keys[] = $attribute_key; if ($attribute['is_taxonomy']) { // Don't use wc_clean as it destroys sanitized characters $value = isset($_POST[$attribute_key][$i]) ? sanitize_title(stripslashes($_POST[$attribute_key][$i])) : ''; } else { $value = isset($_POST[$attribute_key][$i]) ? wc_clean(stripslashes($_POST[$attribute_key][$i])) : ''; } update_post_meta($variation_id, $attribute_key, $value); } } // Remove old taxonomies attributes so data is kept up to date - first get attribute key names $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id)); foreach ($delete_attribute_keys as $key) { delete_post_meta($variation_id, $key); } do_action('woocommerce_save_product_variation', $variation_id, $i); } } // Update parent if variable so price sorting works and stays in sync with the cheapest child WC_Product_Variable::sync($post_id); // Update default attribute options setting $default_attributes = array(); foreach ($attributes as $attribute) { if ($attribute['is_variation']) { // Don't use wc_clean as it destroys sanitized characters if (isset($_POST['default_attribute_' . sanitize_title($attribute['name'])])) { $value = sanitize_title(trim(stripslashes($_POST['default_attribute_' . sanitize_title($attribute['name'])]))); } else { $value = ''; } if ($value) { $default_attributes[sanitize_title($attribute['name'])] = $value; } } } update_post_meta($post_id, '_default_attributes', $default_attributes); }
/** * Checks the submitted files if has any errors * * @return array error list */ function wpuf_check_upload() { $errors = array(); $mime = get_allowed_mime_types(); $size_limit = (int) (wpuf_get_option('attachment_max_size') * 1024); $fields = (int) wpuf_get_option('attachment_num'); for ($i = 0; $i < $fields; $i++) { $tmp_name = basename($_FILES['wpuf_post_attachments']['tmp_name'][$i]); $file_name = basename($_FILES['wpuf_post_attachments']['name'][$i]); //if file is uploaded if ($file_name) { $attach_type = wp_check_filetype($file_name); $attach_size = $_FILES['wpuf_post_attachments']['size'][$i]; //check file size if ($attach_size > $size_limit) { $errors[] = __("Attachment file is too big"); } //check file type if (!in_array($attach_type['type'], $mime)) { $errors[] = __("Invalid attachment file type"); } } // if $filename } // endfor return $errors; }
/** * Sanitizes a filename, replacing whitespace with dashes. * * Removes special characters that are illegal in filenames on certain * operating systems and special characters requiring special escaping * to manipulate at the command line. Replaces spaces and consecutive * dashes with a single dash. Trims period, dash and underscore from beginning * and end of filename. * * @since 2.1.0 * * @param string $filename The filename to be sanitized * @return string The sanitized filename */ function sanitize_file_name($filename) { $filename_raw = $filename; $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "\$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0)); /** * Filter the list of characters to remove from a filename. * * @since 2.8.0 * * @param array $special_chars Characters to remove. * @param string $filename_raw Filename as it was passed into sanitize_file_name(). */ $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw); $filename = preg_replace("#\\x{00a0}#siu", ' ', $filename); $filename = str_replace($special_chars, '', $filename); $filename = str_replace(array('%20', '+'), '-', $filename); $filename = preg_replace('/[\\r\\n\\t -]+/', '-', $filename); $filename = trim($filename, '.-_'); // Split the filename into a base and extension[s] $parts = explode('.', $filename); // Return if only one extension if (count($parts) <= 2) { /** * Filter a sanitized filename string. * * @since 2.8.0 * * @param string $filename Sanitized filename. * @param string $filename_raw The filename prior to sanitization. */ return apply_filters('sanitize_file_name', $filename, $filename_raw); } // Process multiple extensions $filename = array_shift($parts); $extension = array_pop($parts); $mimes = get_allowed_mime_types(); /* * Loop over any intermediate extensions. Postfix them with a trailing underscore * if they are a 2 - 5 character long alpha string not in the extension whitelist. */ foreach ((array) $parts as $part) { $filename .= '.' . $part; if (preg_match("/^[a-zA-Z]{2,5}\\d?\$/", $part)) { $allowed = false; foreach ($mimes as $ext_preg => $mime_match) { $ext_preg = '!^(' . $ext_preg . ')$!i'; if (preg_match($ext_preg, $part)) { $allowed = true; break; } } if (!$allowed) { $filename .= '_'; } } } $filename .= '.' . $extension; /** This filter is documented in wp-includes/formatting.php */ return apply_filters('sanitize_file_name', $filename, $filename_raw); }
/** * Upload a file * @return string or array */ public function upload_file($field_key, $field) { if (isset($_FILES[$field_key]) && !empty($_FILES[$field_key]) && !empty($_FILES[$field_key]['name'])) { if (!empty($field['allowed_mime_types'])) { $allowed_mime_types = $field['allowed_mime_types']; } else { $allowed_mime_types = get_allowed_mime_types(); } $files = array(); $files_to_upload = job_manager_prepare_uploaded_files($_FILES[$field_key]); add_filter('job_manager_upload_dir', array($this, 'upload_dir'), 10, 2); foreach ($files_to_upload as $file_to_upload) { $uploaded_file = job_manager_upload_file($file_to_upload, array('file_key' => $field_key)); if (is_wp_error($uploaded_file)) { throw new Exception($uploaded_file->get_error_message()); } else { if (!isset($uploaded_file->file)) { $uploaded_file->file = str_replace(site_url(), ABSPATH, $uploaded_file->url); } $files[] = $uploaded_file; } } remove_filter('job_manager_upload_dir', array($this, 'upload_dir'), 10, 2); return $files; } }
/** * Returns the full supported mine types. * * @return array */ protected function _getMimeTypes() { if ($this->_aMimeTypes === null) { $aMimeTypes = get_allowed_mime_types(); $aFullMimeTypes = array(); foreach ($aMimeTypes as $sExtensions => $sMineType) { $aExtension = explode('|', $sExtensions); foreach ($aExtension as $sExtension) { $aFullMimeTypes[$sExtension] = $sMineType; } } $this->_aMimeTypes = $aFullMimeTypes; } return $this->_aMimeTypes; }
function hocwp_get_allowed_image_mime_types() { $types = get_allowed_mime_types(); $result = array(); foreach ($types as $key => $text) { if (false !== strpos($text, 'image')) { $result[$key] = $text; } } return $result; }
/** * Slightly convoluted workaround to allow modifying of allowed MIME types for WP < 3.5, * Workaround for IE sometimes setting image/pjepg and image/x-png for JPEGs and PNGs respectively */ function _get_mime_types() { // Use wp_get_mime_types if available, fallback to get_allowed_mime_types() $mime_types = function_exists('wp_get_mime_types') ? wp_get_mime_types() : get_allowed_mime_types(); $fu_mime_types = fu_get_mime_types(); // Workaround for IE $mime_types['jpg|jpe|jpeg|pjpg'] = 'image/pjpeg'; $mime_types['png|xpng'] = 'image/x-png'; // Iterate through default extensions foreach ($fu_mime_types as $extension => $details) { // Skip if it's not in the settings if (!in_array($extension, $this->settings['enabled_files'])) { continue; } // Iterate through mime-types for this extension foreach ($details['mimes'] as $ext_mime) { $mime_types[$extension . '|' . $extension . sanitize_title_with_dashes($ext_mime)] = $ext_mime; } } // Configuration filter: fu_allowed_mime_types should return array of allowed mime types (see readme) $mime_types = apply_filters('fu_allowed_mime_types', $mime_types); foreach ($mime_types as $ext_key => $mime) { // Check for php just in case if (false !== strpos($mime, 'php')) { unset($mime_types[$ext_key]); } } return $mime_types; }
function gmedia_add_media_upload() { global $gmCore, $gmDB, $gmProcessor, $user_ID; if (!current_user_can('gmedia_upload')) { _e('You do not have permissions to upload media', 'grand-media'); return; } $maxupsize = wp_max_upload_size(); $maxupsize_mb = floor($maxupsize / 1024 / 1024); $maxchunksize = floor($maxupsize * 0.9); $maxchunksize_mb = floor($maxupsize_mb * 0.9); $gm_screen_options = $gmProcessor->user_options; ?> <div class="panel panel-default"> <div class="panel-body" style="top:0"> <form class="row" id="gmUpload" name="upload_form" method="POST" accept-charset="utf-8" onsubmit="return false;"> <div class="col-md-8 col-md-push-4" id="pluploadUploader" style="padding: 0;"> <p><?php _e("You browser doesn't have Flash or HTML5 support. Check also if page have no JavaScript errors.", 'grand-media'); ?> </p> <?php $mime_types = get_allowed_mime_types($user_ID); $type_ext = array(); $filters = array(); foreach ($mime_types as $ext => $mime) { $type = strtok($mime, '/'); $type_ext[$type][] = $ext; } foreach ($type_ext as $filter => $ext) { $filters[] = array('title' => $filter, 'extensions' => str_replace('|', ',', implode(',', $ext))); } ?> <script type="text/javascript"> // Convert divs to queue widgets when the DOM is ready jQuery(function($) { //noinspection JSDuplicatedDeclaration $("#pluploadUploader").plupload({ <?php if ('auto' != $gm_screen_options['uploader_runtime']) { ?> runtimes: '<?php echo $gm_screen_options['uploader_runtime']; ?> ', <?php } ?> url: '<?php echo admin_url('admin-ajax.php'); ?> ', <?php if ('true' == $gm_screen_options['uploader_urlstream_upload'] && 'html4' != $gm_screen_options['uploader_runtime']) { ?> urlstream_upload: true, multipart: false, <?php } else { ?> multipart: true, <?php } ?> multipart_params: {action: 'gmedia_upload_handler', _ajax_nonce: '<?php echo wp_create_nonce('GmediaUpload'); ?> ', params: ''}, <?php if ('true' == $gm_screen_options['uploader_chunking'] && 'html4' != $gm_screen_options['uploader_runtime']) { ?> max_file_size: '2000Mb', chunk_size: <?php echo min($maxchunksize, $gm_screen_options['uploader_chunk_size'] * 1024 * 1024); ?> , <?php } else { ?> max_file_size: <?php echo $maxupsize; ?> , <?php } ?> max_retries: 2, unique_names: false, rename: true, sortable: true, dragdrop: true, views: { list: true, thumbs: true, active: 'thumbs' }, filters: <?php echo json_encode($filters); ?> , flash_swf_url: '<?php echo $gmCore->gmedia_url; ?> /assets/plupload/Moxie.swf', silverlight_xap_url: '<?php echo $gmCore->gmedia_url; ?> /assets/plupload/Moxie.xap' }); var closebtn = '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'; var uploader = $("#pluploadUploader").plupload('getUploader'); uploader.bind('StateChanged', function(up) { if(up.state == plupload.STARTED) { up.settings.multipart_params.params = jQuery('#uploader_multipart_params :input').serialize(); } console.log('[StateChanged]', up.state, up.settings.multipart_params); }); uploader.bind('ChunkUploaded', function(up, file, info) { console.log('[ChunkUploaded] File:', file, "Info:", info); var response = $.parseJSON(info.response); if(response && response.error) { up.stop(); file.status = plupload.FAILED; $('<div></div>').addClass('alert alert-danger alert-dismissable').html(closebtn + '<strong>' + response.id + ':</strong> ' + response.error.message).appendTo('#gmedia-msg-panel'); console.log(response.error); up.trigger('QueueChanged StateChanged'); up.trigger('UploadProgress', file); up.start(); } }); uploader.bind('FileUploaded', function(up, file, info) { console.log('[FileUploaded] File:', file, "Info:", info); var response = jQuery.parseJSON(info.response); if(response && response.error) { file.status = plupload.FAILED; $('<div></div>').addClass('alert alert-danger alert-dismissable').html(closebtn + '<strong>' + response.id + ':</strong> ' + response.error.message).appendTo('#gmedia-msg-panel'); console.log(response.error); } }); uploader.bind('UploadProgress', function(up, file) { var percent = uploader.total.percent; $('#total-progress-info .progress-bar').css('width', percent + "%").attr('aria-valuenow', percent); }); uploader.bind('Error', function(up, args) { console.log('[Error] ', args); $('<div></div>').addClass('alert alert-danger alert-dismissable').html(closebtn + '<strong>' + args.file.name + ':</strong> ' + args.message + ' ' + args.status).appendTo('#gmedia-msg-panel'); }); uploader.bind('UploadComplete', function(up, files) { console.log('[UploadComplete]', files); $('<div></div>').addClass('alert alert-success alert-dismissable').html(closebtn + "<?php esc_attr_e(__('Upload finished', 'grand-media')); ?> ").appendTo('#gmedia-msg-panel'); $('#total-progress-info .progress-bar').css('width', '0').attr('aria-valuenow', '0'); }); }); </script> </div> <div class="col-md-4 col-md-pull-8" id="uploader_multipart_params"> <div id="gmedia-msg-panel"></div> <br/> <?php if ('false' == $gm_screen_options['uploader_chunking'] || 'html4' == $gm_screen_options['uploader_runtime']) { ?> <p class="clearfix text-right"><span class="label label-default"><?php echo __('Maximum file size', 'grand-media') . ": {$maxupsize_mb}Mb"; ?> </span></p> <?php } else { ?> <p class="clearfix text-right hidden"> <span class="label label-default"><?php echo __('Maximum $_POST size', 'grand-media') . ": {$maxupsize_mb}Mb"; ?> </span> <span class="label label-default"><?php echo __('Chunk size', 'grand-media') . ': ' . min($maxchunksize_mb, $gm_screen_options['uploader_chunk_size']) . 'Mb'; ?> </span> </p> <?php } ?> <div class="form-group"> <label><?php _e('Title', 'grand-media'); ?> </label> <select name="set_title" class="form-control input-sm"> <option value="exif"><?php _e('EXIF or File Name', 'grand-media'); ?> </option> <option value="filename"><?php _e('File Name', 'grand-media'); ?> </option> <option value="empty"><?php _e('Empty', 'grand-media'); ?> </option> </select> </div> <div class="form-group"> <label><?php _e('Status', 'grand-media'); ?> </label> <select name="set_status" class="form-control input-sm"> <option value="inherit"><?php _e('Same as Album or Public', 'grand-media'); ?> </option> <option value="publish"><?php _e('Public', 'grand-media'); ?> </option> <option value="private"><?php _e('Private', 'grand-media'); ?> </option> <option value="draft"><?php _e('Draft', 'grand-media'); ?> </option> </select> </div> <hr/> <?php if ($gmCore->caps['gmedia_terms']) { ?> <div class="form-group"> <?php $term_type = 'gmedia_album'; $gm_terms = $gmDB->get_terms($term_type, array('global' => array(0, $user_ID), 'orderby' => 'global_desc_name')); $terms_album = ''; if (count($gm_terms)) { foreach ($gm_terms as $term) { $terms_album .= '<option value="' . esc_attr($term->term_id) . '">' . esc_html($term->name) . ($term->global ? '' : __(' (shared)', 'grand-media')) . ('publish' == $term->status ? '' : " [{$term->status}]") . '</option>' . "\n"; } } ?> <label><?php _e('Add to Album', 'grand-media'); ?> </label> <select id="combobox_gmedia_album" name="terms[gmedia_album]" class="form-control input-sm" placeholder="<?php _e('Album Name...', 'grand-media'); ?> "> <option value=""></option> <?php echo $terms_album; ?> </select> </div> <div class="form-group"> <?php $term_type = 'gmedia_category'; $gm_cat_terms = $gmDB->get_terms($term_type, array('fields' => 'names')); ?> <label><?php _e('Assign Categories', 'grand-media'); ?> </label> <input id="combobox_gmedia_category" name="terms[gmedia_category]" class="form-control input-sm" value="" placeholder="<?php _e('Uncategorized', 'grand-media'); ?> "/> </div> <div class="form-group"> <?php $term_type = 'gmedia_tag'; $gm_tag_terms = $gmDB->get_terms($term_type, array('fields' => 'names')); ?> <label><?php _e('Add Tags', 'grand-media'); ?> </label> <input id="combobox_gmedia_tag" name="terms[gmedia_tag]" class="form-control input-sm" value="" placeholder="<?php _e('Add Tags...', 'grand-media'); ?> "/> </div> <div class="addtags-gap"> </div> <script type="text/javascript"> jQuery(function($) { $('#combobox_gmedia_album').selectize({ <?php if ($gmCore->caps['gmedia_album_manage']) { ?> create: true, createOnBlur: true, <?php } else { ?> create: false, <?php } ?> persist: false }); var gm_cat_terms = <?php echo json_encode($gm_cat_terms); ?> ; //noinspection JSUnusedAssignment var cat_items = gm_cat_terms.map(function(x) { return {item: x}; }); //noinspection JSDuplicatedDeclaration $('#combobox_gmedia_category').selectize({ <?php if ($gmCore->caps['gmedia_category_manage']) { ?> create: function(input) { return { item: input } }, createOnBlur: true, <?php } else { ?> create: false, <?php } ?> delimiter: ',', maxItems: null, openOnFocus: true, persist: false, options: cat_items, labelField: 'item', valueField: 'item', searchField: ['item'], hideSelected: true }); var gm_tag_terms = <?php echo json_encode($gm_tag_terms); ?> ; //noinspection JSUnusedAssignment var tag_items = gm_tag_terms.map(function(x) { return {item: x}; }); $('#combobox_gmedia_tag').selectize({ <?php if ($gmCore->caps['gmedia_tag_manage']) { ?> create: function(input) { return { item: input } }, createOnBlur: true, <?php } else { ?> create: false, <?php } ?> delimiter: ',', maxItems: null, openOnFocus: true, persist: false, options: tag_items, labelField: 'item', valueField: 'item', searchField: ['item'], hideSelected: true }); }); </script> <?php } else { ?> <p><?php _e('You are not allowed to assign terms', 'grand-media'); ?> </p> <?php } ?> <script type="text/javascript"> jQuery(function($) { $('#uploader_runtime select').change(function() { if('html4' == $(this).val()) { $('#uploader_chunking').addClass('hide'); $('#uploader_urlstream_upload').addClass('hide'); } else { $('#uploader_chunking').removeClass('hide'); $('#uploader_urlstream_upload').removeClass('hide'); } }); }); </script> </div> </form> </div> </div> <?php }