function get_views()
 {
     global $wpdb, $post_mime_types, $avail_post_mime_types;
     $type_links = array();
     $_num_posts = (array) wp_count_attachments();
     $_total_posts = array_sum($_num_posts) - $_num_posts['trash'];
     if (!isset($total_orphans)) {
         $total_orphans = $wpdb->get_var("SELECT COUNT( * ) FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent < 1");
     }
     $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
     foreach ($matches as $type => $reals) {
         foreach ($reals as $real) {
             $num_posts[$type] = isset($num_posts[$type]) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
         }
     }
     $class = empty($_GET['post_mime_type']) && !isset($_GET['status']) ? ' class="current"' : '';
     $type_links['all'] = "<a href='upload.php'{$class}>" . sprintf(_nx('All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $_total_posts, 'uploaded files'), number_format_i18n($_total_posts)) . '</a>';
     foreach ($post_mime_types as $mime_type => $label) {
         $class = '';
         if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
             continue;
         }
         if (!empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type'])) {
             $class = ' class="current"';
         }
         if (!empty($num_posts[$mime_type])) {
             $type_links[$mime_type] = "<a href='upload.php?post_mime_type={$mime_type}'{$class}>" . sprintf(translate_nooped_plural($label[2], $num_posts[$mime_type]), number_format_i18n($num_posts[$mime_type])) . '</a>';
         }
     }
     if (!empty($_num_posts['trash'])) {
         $type_links['trash'] = '<a href="upload.php?status=trash"' . (isset($_GET['status']) && $_GET['status'] == 'trash' ? ' class="current"' : '') . '>' . sprintf(_nx('Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>', $_num_posts['trash'], 'uploaded files'), number_format_i18n($_num_posts['trash'])) . '</a>';
     }
     return array();
 }
 protected function get_views()
 {
     global $wpdb, $post_mime_types, $avail_post_mime_types;
     $type_links = array();
     $_num_posts = (array) wp_count_attachments();
     $_total_posts = array_sum($_num_posts) - $_num_posts['trash'];
     $total_orphans = $wpdb->get_var("SELECT COUNT( * ) FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent < 1");
     $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
     foreach ($matches as $type => $reals) {
         foreach ($reals as $real) {
             $num_posts[$type] = isset($num_posts[$type]) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
         }
     }
     $selected = empty($_GET['attachment-filter']) ? ' selected="selected"' : '';
     $type_links['all'] = "<option value=''{$selected}>" . sprintf(_nx('All (%s)', 'All (%s)', $_total_posts, 'uploaded files'), number_format_i18n($_total_posts)) . '</option>';
     foreach ($post_mime_types as $mime_type => $label) {
         if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
             continue;
         }
         $selected = '';
         if (!empty($_GET['attachment-filter']) && strpos($_GET['attachment-filter'], 'post_mime_type:') === 0 && wp_match_mime_types($mime_type, str_replace('post_mime_type:', '', $_GET['attachment-filter']))) {
             $selected = ' selected="selected"';
         }
         if (!empty($num_posts[$mime_type])) {
             $type_links[$mime_type] = '<option value="post_mime_type:' . esc_attr($mime_type) . '"' . $selected . '>' . sprintf(translate_nooped_plural($label[2], $num_posts[$mime_type]), number_format_i18n($num_posts[$mime_type])) . '</option>';
         }
     }
     $type_links['detached'] = '<option value="detached"' . ($this->detached ? ' selected="selected"' : '') . '>' . sprintf(_nx('Unattached (%s)', 'Unattached (%s)', $total_orphans, 'detached files'), number_format_i18n($total_orphans)) . '</option>';
     $type_links['uncategorized'] = '<option value="uncategorized"' . ($this->uncategorized ? ' selected="selected"' : '') . '>' . __('All Uncategorized', 'eml') . '</option>';
     if (!empty($_num_posts['trash'])) {
         $type_links['trash'] = '<option value="trash"' . (isset($_GET['attachment-filter']) && $_GET['attachment-filter'] == 'trash' ? ' selected="selected"' : '') . '>' . sprintf(_nx('Trash (%s)', 'Trash (%s)', $_num_posts['trash'], 'uploaded files'), number_format_i18n($_num_posts['trash'])) . '</option>';
     }
     return $type_links;
 }
예제 #3
0
 /**
  * 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 pronamic_framework_maybe_save_post()
{
    if (isset($_POST['pronamic_framework_edit_post_submit'])) {
        $post_ID = filter_input(INPUT_POST, 'post_ID', FILTER_SANITIZE_NUMBER_INT);
        // Post
        $post_title = filter_input(INPUT_POST, 'post_title', FILTER_SANITIZE_STRING);
        $post_content = filter_input(INPUT_POST, 'post_content', FILTER_UNSAFE_RAW);
        $post_content = wp_kses_post($post_content);
        $post = array('ID' => $post_ID, 'post_title' => $post_title, 'post_content' => $post_content);
        $result = wp_update_post($post);
        if (0 !== $result) {
        } else {
        }
        // Meta
        $meta = filter_input(INPUT_POST, 'post_meta', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY);
        foreach ($meta as $key => $value) {
            update_post_meta($post_ID, $key, $value);
        }
        // Attachments
        if (isset($_FILES['post_attachments'])) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            require_once ABSPATH . 'wp-admin/includes/media.php';
            require_once ABSPATH . 'wp-admin/includes/post.php';
            $post_mime_types = get_post_mime_types();
            foreach ($_FILES['post_attachments']['error'] as $key => $error) {
                if (UPLOAD_ERR_OK == $error) {
                    // no error
                    $tmp_name = $_FILES['post_attachments']['tmp_name'][$key];
                    $name = $_FILES['post_attachments']['name'][$key];
                    $bits = file_get_contents($tmp_name);
                    $result = wp_upload_bits($name, null, $bits);
                    if (false === $result['error']) {
                        // no error
                        $file_type = wp_check_filetype($result['file']);
                        $keys = array_keys(wp_match_mime_types(array_keys($post_mime_types), $file_type));
                        $type = array_shift($keys);
                        $attachment = array('post_title' => $name, 'post_mime_type' => $file_type['type'], 'guid' => $result['url'], 'post_parent' => $post_ID);
                        $attachment_id = wp_insert_attachment($attachment, $result['file'], $post_ID);
                        $meta_data = wp_generate_attachment_metadata($attachment_id, $result['file']);
                        $updated = wp_update_attachment_metadata($attachment_id, $meta_data);
                        if ('image' == $type) {
                            update_post_meta($post_ID, '_thumbnail_id', $attachment_id);
                        }
                    }
                }
            }
        }
    }
}
 /**
  * @global array $post_mime_types
  * @global array $avail_post_mime_types
  * @return array
  */
 protected function get_views()
 {
     global $post_mime_types, $avail_post_mime_types;
     $type_links = array();
     $filter = empty($_GET['attachment-filter']) ? '' : $_GET['attachment-filter'];
     $type_links['all'] = sprintf('<option value=""%s>%s</option>', selected($filter, true, false), __('All media items'));
     foreach ($post_mime_types as $mime_type => $label) {
         if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
             continue;
         }
         $selected = selected($filter && 0 === strpos($filter, 'post_mime_type:') && wp_match_mime_types($mime_type, str_replace('post_mime_type:', '', $filter)), true, false);
         $type_links[$mime_type] = sprintf('<option value="post_mime_type:%s"%s>%s</option>', esc_attr($mime_type), $selected, $label[0]);
     }
     $type_links['detached'] = '<option value="detached"' . ($this->detached ? ' selected="selected"' : '') . '>' . __('Unattached') . '</option>';
     if ($this->is_trash || defined('MEDIA_TRASH') && MEDIA_TRASH) {
         $type_links['trash'] = sprintf('<option value="trash"%s>%s</option>', selected('trash' === $filter, true, false), __('Trash'));
     }
     return $type_links;
 }
예제 #6
0
 public static function wp_custom_recount_attachments($views)
 {
     $_total_posts = array();
     $_num_posts = array();
     global $wpdb, $current_user, $post_mime_types, $avail_post_mime_types;
     $views = array();
     $count = $wpdb->get_results("\r\n\t\t\t\t\tSELECT post_mime_type, COUNT( * ) AS num_posts \r\n\t\t\t\t\tFROM {$wpdb->posts} \r\n\t\t\t\t\tWHERE post_type = 'attachment' \r\n\t\t\t\t\tAND post_author = {$current_user->ID} \r\n\t\t\t\t\tAND post_status != 'trash' \r\n\t\t\t\t\tGROUP BY post_mime_type\r\n\t\t\t\t", ARRAY_A);
     foreach ($count as $row) {
         $_num_posts[$row['post_mime_type']] = $row['num_posts'];
     }
     $_total_posts = array_sum($_num_posts);
     $detached = isset($_REQUEST['detached']) || isset($_REQUEST['find_detached']);
     if (!isset($total_orphans)) {
         $total_orphans = $wpdb->get_var("\r\n\t\t\t\t\t\tSELECT COUNT( * ) \r\n\t\t\t\t\t\tFROM {$wpdb->posts} \r\n\t\t\t\t\t\tWHERE post_type = 'attachment' \r\n\t\t\t\t\t\tAND post_author = {$current_user->ID} \r\n\t\t\t\t\t\tAND post_status != 'trash' \r\n\t\t\t\t\t\tAND post_parent < 1\r\n\t\t\t\t\t");
     }
     $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
     foreach ($matches as $type => $reals) {
         foreach ($reals as $real) {
             $num_posts[$type] = isset($num_posts[$type]) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
         }
     }
     $class = empty($_GET['post_mime_type']) && !$detached && !isset($_GET['status']) ? ' class="current"' : '';
     $views['all'] = "<a href='upload.php'{$class}>" . sprintf(__('All <span class="count">(%s)</span>', 'uploaded files'), number_format_i18n($_total_posts)) . '</a>';
     foreach ($post_mime_types as $mime_type => $label) {
         $class = '';
         if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
             continue;
         }
         if (!empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type'])) {
             $class = ' class="current"';
         }
         if (!empty($num_posts[$mime_type])) {
             $views[$mime_type] = "<a href='upload.php?post_mime_type={$mime_type}'{$class}>" . sprintf(translate_nooped_plural($label[2], $num_posts[$mime_type]), $num_posts[$mime_type]) . '</a>';
         }
     }
     $views['detached'] = '<a href="upload.php?detached=1"' . ($detached ? ' class="current"' : '') . '>' . sprintf(__('Unattached <span class="count">(%s)</span>', 'detached files'), $total_orphans) . '</a>';
     return $views;
 }
예제 #7
0
파일: import.php 프로젝트: dot2006/jobify
/**
 * Upload import file
 *
 * @since 0.3
 */
function wie_upload_import_file()
{
    // Check nonce for security since form was posted
    if (!empty($_POST) && !empty($_FILES['wie_import_file']) && check_admin_referer('wie_import', 'wie_import_nonce')) {
        // check_admin_referer prints fail page and dies
        // Uploaded file
        $uploaded_file = $_FILES['wie_import_file'];
        // Check file type
        // This will also fire if no file uploaded
        $wp_filetype = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name'], false);
        if ('wie' != $wp_filetype['ext'] && !wp_match_mime_types('wie', $wp_filetype['type'])) {
            wp_die(__('You must upload a <b>.wie</b> file generated by this plugin.', 'widget-importer-exporter'), '', array('back_link' => true));
        }
        // Check and move file to uploads dir, get file data
        // Will show die with WP errors if necessary (file too large, quota exceeded, etc.)
        $overrides = array('test_form' => false);
        $file_data = wp_handle_upload($uploaded_file, $overrides);
        if (isset($file_data['error'])) {
            wp_die($file_data['error'], '', array('back_link' => true));
        }
        // Process import file
        wie_process_import_file($file_data['file']);
    }
}
예제 #8
0
 /**
  * Upload the file to be cropped in the second step.
  *
  * @since 4.3.0
  */
 public function handle_upload()
 {
     $uploaded_file = $_FILES['site-icon'];
     $file_type = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name']);
     if (!wp_match_mime_types('image', $file_type['type'])) {
         wp_die(__('The uploaded file is not a valid image. Please try again.'));
     }
     $file = wp_handle_upload($uploaded_file, array('test_form' => false));
     if (isset($file['error'])) {
         wp_die($file['error'], __('Image Upload Error'));
     }
     $url = $file['url'];
     $type = $file['type'];
     $file = $file['file'];
     $filename = basename($file);
     // Construct the object array
     $object = array('post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'site-icon');
     // Save the data
     $attachment_id = wp_insert_attachment($object, $file);
     return compact('attachment_id', 'file', 'filename', 'url', 'type');
 }
/**
 * Get allowed attachment mime types.
 *
 * @since 2.4.0
 *
 * @param  string $type         The extension types to get (Optional).
 * @param  array $allowed_types List of allowed extensions
 * @return array                List of allowed mime types
 */
function bp_attachments_get_allowed_mimes($type = '', $allowed_types = array())
{
    if (empty($allowed_types)) {
        $allowed_types = bp_attachments_get_allowed_types($type);
    }
    $validate_mimes = wp_match_mime_types(join(',', $allowed_types), wp_get_mime_types());
    $allowed_mimes = array_map('implode', $validate_mimes);
    /**
     * Include jpg type if jpeg is set
     */
    if (isset($allowed_mimes['jpeg']) && !isset($allowed_mimes['jpg'])) {
        $allowed_mimes['jpg'] = $allowed_mimes['jpeg'];
    }
    return $allowed_mimes;
}
예제 #10
0
$_num_posts = (array) wp_count_attachments();
$_total_posts = array_sum($_num_posts);
$matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
foreach ($matches as $type => $reals) {
    foreach ($reals as $real) {
        $num_posts[$type] = isset($num_posts[$type]) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
    }
}
$class = empty($_GET['post_mime_type']) && !isset($_GET['detached']) ? ' class="current"' : '';
$type_links[] = "<li><a href='upload.php'{$class}>" . sprintf(_nx('All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $_total_posts, 'uploaded files'), number_format_i18n($_total_posts)) . '</a>';
foreach ($post_mime_types as $mime_type => $label) {
    $class = '';
    if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
        continue;
    }
    if (!empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type'])) {
        $class = ' class="current"';
    }
    $type_links[] = "<li><a href='upload.php?post_mime_type={$mime_type}'{$class}>" . sprintf(_n($label[2][0], $label[2][1], $num_posts[$mime_type]), number_format_i18n($num_posts[$mime_type])) . '</a>';
}
$class = isset($_GET['detached']) ? ' class="current"' : '';
$type_links[] = '<li><a href="upload.php?detached=1"' . $class . '>' . __('Unattached') . '</a>';
echo implode(" |</li>\n", $type_links) . '</li>';
unset($type_links);
?>
</ul>

<form class="search-form" action="" method="get">
<p class="search-box">
	<label class="screen-reader-text" for="media-search-input"><?php 
_e('Search Media');
예제 #11
0
파일: media.php 프로젝트: rkglug/WordPress
/**
 * Displays the image and editor in the post editor
 *
 * @since 3.5.0
 */
function edit_form_image_editor()
{
    $post = get_post();
    $thumb_url = false;
    if ($attachment_id = intval($post->ID)) {
        $thumb_url = wp_get_attachment_image_src($attachment_id, array(900, 600), true);
    }
    $filename = esc_html(basename($post->guid));
    $title = esc_attr($post->post_title);
    $post_mime_types = get_post_mime_types();
    $keys = array_keys(wp_match_mime_types(array_keys($post_mime_types), $post->post_mime_type));
    $type = array_shift($keys);
    $type_html = "<input type='hidden' id='type-of-{$attachment_id}' value='" . esc_attr($type) . "' />";
    $media_dims = '';
    $meta = wp_get_attachment_metadata($post->ID);
    if (is_array($meta) && array_key_exists('width', $meta) && array_key_exists('height', $meta)) {
        $media_dims .= "<span id='media-dims-{$post->ID}'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
    }
    $media_dims = apply_filters('media_meta', $media_dims, $post);
    $att_url = wp_get_attachment_url($post->ID);
    $image_edit_button = '';
    if (gd_edit_image_support($post->post_mime_type)) {
        $nonce = wp_create_nonce("image_editor-{$post->ID}");
        $image_edit_button = "<input type='button' id='imgedit-open-btn-{$post->ID}' onclick='imageEdit.open( {$post->ID}, \"{$nonce}\" )' class='button' value='" . esc_attr__('Edit Image') . "' /> <span class='spinner'></span>";
    }
    ?>
	<div class="wp_attachment_holder">
		<div class="imgedit-response" id="imgedit-response-<?php 
    echo $attachment_id;
    ?>
"></div>

		<div class="wp_attachment_image" id="media-head-<?php 
    echo $attachment_id;
    ?>
">
			<p><img class="thumbnail" src="<?php 
    echo set_url_scheme($thumb_url[0]);
    ?>
" style="max-width:100%" width="<?php 
    echo $thumb_url[1];
    ?>
" alt="" /></p>
			<p><?php 
    echo $image_edit_button;
    ?>
</p>
		</div>
		<div style="display:none" class="image-editor" id="image-editor-<?php 
    echo $attachment_id;
    ?>
"></div>

		<div class="wp_attachment_details">
			<p>
				<label for="attachment_url"><strong><?php 
    _e('File URL');
    ?>
</strong></label><br />
				<input type="text" class="widefat urlfield" readonly="readonly" name="attachment_url" value="<?php 
    echo esc_attr($att_url);
    ?>
" /><br />
			</p>
			<p><strong><?php 
    _e('File name:');
    ?>
</strong> <?php 
    echo $filename;
    ?>
<br />
			<strong><?php 
    _e('File type:');
    ?>
</strong> <?php 
    echo $post->post_mime_type;
    ?>
			<?php 
    if ($media_dims) {
        echo '<br /><strong>' . __('Dimensions:') . '</strong> ' . $media_dims;
    }
    ?>
			</p>
		</div>
	</div>
	<?php 
}
예제 #12
0
function yoimg_search_upload_images()
{
    $post_id = esc_html(isset($_POST['postId']) ? $_POST['postId'] : '');
    if (current_user_can('upload_files') && current_user_can('edit_post', $post_id)) {
        header('Content-type: application/json; charset=UTF-8');
        $images_urls = isset($_POST['imagesUrls']) ? $_POST['imagesUrls'] : array();
        if (count($images_urls) > 0) {
            status_header(200);
            $results = array();
            foreach ($images_urls as $image_url) {
                $result = array('origUrl' => $image_url);
                $downloaded_image = download_url($image_url);
                if (is_wp_error($downloaded_image)) {
                    $result['errorMessage'] = $downloaded_image->get_error_message();
                    status_header(503);
                } else {
                    $result['imageFilename'] = $downloaded_image;
                    $downloaded_image_info = pathinfo($downloaded_image);
                    $downloaded_image_basename = $downloaded_image_info['basename'];
                    $downloaded_image_basename .= '.gif';
                    $downloaded_image_filetype = wp_check_filetype_and_ext($downloaded_image, $downloaded_image_basename, false);
                    if (!wp_match_mime_types('image', $downloaded_image_filetype['type'])) {
                        $result['errorMessage'] = __('The uploaded file is not a valid image. Please try again.');
                        status_header(503);
                    } else {
                        $time = current_time('mysql');
                        if ($post = get_post($post_id)) {
                            if (substr($post->post_date, 0, 4) > 0) {
                                $time = $post->post_date;
                            }
                        }
                        $uploads = wp_upload_dir($time);
                        if (isset($uploads['error']) && $uploads['error'] === false) {
                            $filename = isset($downloaded_image_filetype['proper_filename']) ? $downloaded_image_filetype['proper_filename'] : $downloaded_image_basename;
                            $filename = wp_unique_filename($uploads['path'], $filename);
                            $new_file = $uploads['path'] . '/' . $filename;
                            $move_new_file = @rename($downloaded_image, $new_file);
                            if (false === $move_new_file) {
                                $result['errorMessage'] = sprintf(__('The uploaded file could not be moved to %s.'), $new_file);
                                status_header(503);
                            } else {
                                $stat = stat(dirname($new_file));
                                $perms = $stat['mode'] & 0666;
                                @chmod($new_file, $perms);
                                $url = $uploads['url'] . '/' . $filename;
                                $result['imageFilename'] = $new_file;
                                $result['imageUrl'] = $url;
                                $attachment = array('post_mime_type' => $downloaded_image_filetype['type'], 'guid' => $url, 'post_parent' => $post_id, 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit');
                                $image_id = wp_insert_attachment($attachment, $new_file, $post_id);
                                if (!is_wp_error($image_id)) {
                                    require_once ABSPATH . 'wp-admin/includes/image.php';
                                    wp_update_attachment_metadata($image_id, wp_generate_attachment_metadata($image_id, $new_file));
                                    $result['imageId'] = $image_id;
                                } else {
                                    $result['errorMessage'] = 'cannot insert attachment';
                                    status_header(503);
                                }
                            }
                        } else {
                            $result['errorMessage'] = __($uploads['error']);
                            status_header(503);
                        }
                    }
                }
                array_push($results, $result);
            }
            echo json_encode($results);
        } else {
            status_header(204);
        }
    } else {
        status_header(401);
    }
    die;
}
 /**
  * Returns HTML markup for one view that can be used with this table
  *
  * @since 1.40
  *
  * @param	string	View slug, key to MLA_POST_MIME_TYPES array 
  * @param	string	Slug for current view 
  * 
  * @return	string | false	HTML for link to display the view, false if count = zero
  */
 function _get_view($view_slug, $current_view)
 {
     global $wpdb;
     static $mla_types = NULL, $posts_per_type, $post_mime_types, $avail_post_mime_types, $matches, $num_posts;
     /*
      * Calculate the common values once per page load
      */
     if (is_null($mla_types)) {
         $query_types = MLAMime::mla_query_view_items(array('orderby' => 'menu_order'), 0, 0);
         if (!is_array($query_types)) {
             $query_types = array();
         }
         $mla_types = array();
         foreach ($query_types as $value) {
             $mla_types[$value->slug] = $value;
         }
         $posts_per_type = (array) wp_count_attachments();
         $post_mime_types = get_post_mime_types();
         $avail_post_mime_types = $this->_avail_mime_types($posts_per_type);
         $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($posts_per_type));
         foreach ($matches as $type => $reals) {
             foreach ($reals as $real) {
                 $num_posts[$type] = isset($num_posts[$type]) ? $num_posts[$type] + $posts_per_type[$real] : $posts_per_type[$real];
             }
         }
     }
     $class = $view_slug == $current_view ? ' class="current"' : '';
     $base_url = 'upload.php?page=' . MLA::ADMIN_PAGE_SLUG;
     /*
      * Handle the special cases: all, unattached and trash
      */
     switch ($view_slug) {
         case 'all':
             $total_items = array_sum($posts_per_type) - $posts_per_type['trash'];
             return "<a href='{$base_url}'{$class}>" . sprintf(_nx('All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_items, 'uploaded files'), number_format_i18n($total_items)) . '</a>';
         case 'unattached':
             $total_items = $wpdb->get_var("\r\n\t\t\t\t\t\tSELECT COUNT( * ) FROM {$wpdb->posts}\r\n\t\t\t\t\t\tWHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent < 1\r\n\t\t\t\t\t\t");
             if ($total_items) {
                 return '<a href="' . add_query_arg(array('detached' => '1'), $base_url) . '"' . $class . '>' . sprintf(_nx('Unattached <span class="count">(%s)</span>', 'Unattached <span class="count">(%s)</span>', $total_items, 'detached files'), number_format_i18n($total_items)) . '</a>';
             } else {
                 return false;
             }
         case 'trash':
             if ($posts_per_type['trash']) {
                 return '<a href="' . add_query_arg(array('status' => 'trash'), $base_url) . '"' . $class . '>' . sprintf(_nx('Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>', $posts_per_type['trash'], 'uploaded files'), number_format_i18n($posts_per_type['trash'])) . '</a>';
             } else {
                 return false;
             }
     }
     // switch special cases
     /*
      * Make sure the slug is in our list
      */
     if (array_key_exists($view_slug, $mla_types)) {
         $mla_type = $mla_types[$view_slug];
     } else {
         return false;
     }
     /*
      * Handle post_mime_types
      */
     if ($mla_type->post_mime_type) {
         if (!empty($num_posts[$view_slug])) {
             return "<a href='" . add_query_arg(array('post_mime_type' => $view_slug), $base_url) . "'{$class}>" . sprintf(translate_nooped_plural($post_mime_types[$view_slug][2], $num_posts[$view_slug]), number_format_i18n($num_posts[$view_slug])) . '</a>';
         } else {
             return false;
         }
     }
     /*
      * Handle extended specification types
      */
     if (empty($mla_type->specification)) {
         $query = array('post_mime_type' => $view_slug);
     } else {
         $query = MLAMime::mla_prepare_view_query($view_slug, $mla_type->specification);
     }
     $total_items = MLAData::mla_count_list_table_items($query);
     if ($total_items) {
         $singular = sprintf('%s <span class="count">(%%s)</span>', $mla_type->singular);
         $plural = sprintf('%s <span class="count">(%%s)</span>', $mla_type->plural);
         $nooped_plural = _n_noop($singular, $plural);
         if (isset($query['post_mime_type'])) {
             $query['post_mime_type'] = urlencode($query['post_mime_type']);
         } else {
             $query['meta_query'] = urlencode(serialize($query['meta_query']));
         }
         return "<a href='" . add_query_arg($query, $base_url) . "'{$class}>" . sprintf(translate_nooped_plural($nooped_plural, $total_items), number_format_i18n($total_items)) . '</a>';
     }
     return false;
 }
예제 #14
0
/**
 * {@internal Missing Short Description}}
 *
 * @since 2.5.0
 *
 * @param array $errors
 */
function media_upload_library_form($errors)
{
    global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types;
    media_upload_header();
    $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0;
    $form_action_url = admin_url("media-upload.php?type={$type}&tab=library&post_id={$post_id}");
    /** This filter is documented in wp-admin/includes/media.php */
    $form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type);
    $form_class = 'media-upload-form validate';
    if (get_user_setting('uploader')) {
        $form_class .= ' html-uploader';
    }
    $q = $_GET;
    $q['posts_per_page'] = 10;
    $q['paged'] = isset($q['paged']) ? intval($q['paged']) : 0;
    if ($q['paged'] < 1) {
        $q['paged'] = 1;
    }
    $q['offset'] = ($q['paged'] - 1) * 10;
    if ($q['offset'] < 1) {
        $q['offset'] = 0;
    }
    list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query($q);
    ?>

<form id="filter" action="" method="get">
<input type="hidden" name="type" value="<?php 
    echo esc_attr($type);
    ?>
" />
<input type="hidden" name="tab" value="<?php 
    echo esc_attr($tab);
    ?>
" />
<input type="hidden" name="post_id" value="<?php 
    echo (int) $post_id;
    ?>
" />
<input type="hidden" name="post_mime_type" value="<?php 
    echo isset($_GET['post_mime_type']) ? esc_attr($_GET['post_mime_type']) : '';
    ?>
" />
<input type="hidden" name="context" value="<?php 
    echo isset($_GET['context']) ? esc_attr($_GET['context']) : '';
    ?>
" />

<p id="media-search" class="search-box">
	<label class="screen-reader-text" for="media-search-input"><?php 
    _e('Search Media');
    ?>
:</label>
	<input type="search" id="media-search-input" name="s" value="<?php 
    the_search_query();
    ?>
" />
	<?php 
    submit_button(__('Search Media'), 'button', '', false);
    ?>
</p>

<ul class="subsubsub">
<?php 
    $type_links = array();
    $_num_posts = (array) wp_count_attachments();
    $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
    foreach ($matches as $_type => $reals) {
        foreach ($reals as $real) {
            if (isset($num_posts[$_type])) {
                $num_posts[$_type] += $_num_posts[$real];
            } else {
                $num_posts[$_type] = $_num_posts[$real];
            }
        }
    }
    // If available type specified by media button clicked, filter by that type
    if (empty($_GET['post_mime_type']) && !empty($num_posts[$type])) {
        $_GET['post_mime_type'] = $type;
        list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
    }
    if (empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all') {
        $class = ' class="current"';
    } else {
        $class = '';
    }
    $type_links[] = '<li><a href="' . esc_url(add_query_arg(array('post_mime_type' => 'all', 'paged' => false, 'm' => false))) . '"' . $class . '>' . __('All Types') . '</a>';
    foreach ($post_mime_types as $mime_type => $label) {
        $class = '';
        if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
            continue;
        }
        if (isset($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type'])) {
            $class = ' class="current"';
        }
        $type_links[] = '<li><a href="' . esc_url(add_query_arg(array('post_mime_type' => $mime_type, 'paged' => false))) . '"' . $class . '>' . sprintf(translate_nooped_plural($label[2], $num_posts[$mime_type]), '<span id="' . $mime_type . '-counter">' . number_format_i18n($num_posts[$mime_type]) . '</span>') . '</a>';
    }
    /**
     * Filter the media upload mime type list items.
     *
     * Returned values should begin with an <li> tag.
     *
     * @since 3.1.0
     *
     * @param array $type_links An array of list items containing mime type link HTML.
     */
    echo implode(' | </li>', apply_filters('media_upload_mime_type_links', $type_links)) . '</li>';
    unset($type_links);
    ?>
</ul>

<div class="tablenav">

<?php 
    $page_links = paginate_links(array('base' => add_query_arg('paged', '%#%'), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => ceil($wp_query->found_posts / 10), 'current' => $q['paged']));
    if ($page_links) {
        echo "<div class='tablenav-pages'>{$page_links}</div>";
    }
    ?>

<div class="alignleft actions">
<?php 
    $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM {$wpdb->posts} WHERE post_type = 'attachment' ORDER BY post_date DESC";
    $arc_result = $wpdb->get_results($arc_query);
    $month_count = count($arc_result);
    $selected_month = isset($_GET['m']) ? $_GET['m'] : 0;
    if ($month_count && !(1 == $month_count && 0 == $arc_result[0]->mmonth)) {
        ?>
<select name='m'>
<option<?php 
        selected($selected_month, 0);
        ?>
 value='0'><?php 
        _e('All dates');
        ?>
</option>
<?php 
        foreach ($arc_result as $arc_row) {
            if ($arc_row->yyear == 0) {
                continue;
            }
            $arc_row->mmonth = zeroise($arc_row->mmonth, 2);
            if ($arc_row->yyear . $arc_row->mmonth == $selected_month) {
                $default = ' selected="selected"';
            } else {
                $default = '';
            }
            echo "<option{$default} value='" . esc_attr($arc_row->yyear . $arc_row->mmonth) . "'>";
            echo esc_html($wp_locale->get_month($arc_row->mmonth) . " {$arc_row->yyear}");
            echo "</option>\n";
        }
        ?>
</select>
<?php 
    }
    ?>

<?php 
    submit_button(__('Filter &#187;'), 'button', 'post-query-submit', false);
    ?>

</div>

<br class="clear" />
</div>
</form>

<form enctype="multipart/form-data" method="post" action="<?php 
    echo esc_url($form_action_url);
    ?>
" class="<?php 
    echo $form_class;
    ?>
" id="library-form">

<?php 
    wp_nonce_field('media-form');
    //media_upload_form( $errors );
    ?>

<script type="text/javascript">
<!--
jQuery(function($){
	var preloaded = $(".media-item.preloaded");
	if ( preloaded.length > 0 ) {
		preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
		updateMediaForm();
	}
});
-->
</script>

<div id="media-items">
<?php 
    add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2);
    echo get_media_items(null, $errors);
    ?>
</div>
<p class="ml-submit">
<?php 
    submit_button(__('Save all changes'), 'button savebutton', 'save', false);
    ?>
<input type="hidden" name="post_id" id="post_id" value="<?php 
    echo (int) $post_id;
    ?>
" />
</p>
</form>
<?php 
}
예제 #15
0
 /**
  * Update user meta.
  *
  * @param int $user_id
  */
 public function update($user_id)
 {
     if (!empty($_FILES) && isset($_FILES[$this->name]) && !empty($_FILES[$this->name]['tmp_name'])) {
         $current_attachment_id = get_user_meta($user_id, $this->name, true);
         if ($current_attachment_id) {
             wp_delete_attachment($current_attachment_id);
         }
         $filetype = wp_check_filetype_and_ext($_FILES[$this->name]['tmp_name'], $_FILES[$this->name]['name']);
         if (!wp_match_mime_types('image', $filetype['type'])) {
             die;
         }
         $attachment_id = media_handle_upload($this->name, 0);
         if (!is_wp_error($attachment_id)) {
             update_user_meta($user_id, $this->name, $attachment_id);
         }
     }
 }
예제 #16
0
파일: form.php 프로젝트: Omuze/barakat
/**
 * Field: single file
 */
function _kc_field_file_single($args)
{
    extract($args, EXTR_OVERWRITE);
    $size = isset($field['size']) ? $field['size'] : 'thumbnail';
    #  Handle migration from multiple mode
    if (is_array($db_value)) {
        if (!empty($db_value['selected'])) {
            $db_value = $db_value['selected'][0];
        } elseif (!empty($db_value['files'])) {
            $db_value = $db_value['files'][0];
        } else {
            $db_value = '';
        }
    }
    if (get_post_type(absint($db_value)) === 'attachment' && ($attachment = get_post(absint($db_value)))) {
        $post_mime_types = get_post_mime_types();
        $keys = array_keys(wp_match_mime_types(array_keys($post_mime_types), $attachment->post_mime_type));
        $type = esc_attr(array_shift($keys));
        $valid = true;
        $title = $attachment->post_title;
    } else {
        $type = 'default';
        $valid = false;
        $title = '';
        $db_value = '';
    }
    $out = "<div id='{$id}' class='kcs-file-single' data-type='{$type}' data-size='{$size}' data-mime-type='{$field['mime_type']}'>\n";
    $out .= "\t<p class='current";
    if (!$valid) {
        $out .= ' hidden';
    }
    $out .= "'>\n";
    $out .= "<a href='" . esc_url($up_url) . "' title='" . __('Change file', 'kc-settings') . "' class='up'><img src='" . kc_get_attachment_icon_src($db_value, $size) . "' alt=''";
    if (!empty($field['size']) && is_numeric($field['size'])) {
        $out .= " style='width:{$field['size']}px'";
    }
    $out .= ' /></a>';
    $out .= "<span>{$title}</span>";
    $out .= '<br /><a href="#" class="rm">' . __('Remove', 'kc-settings') . '</a>';
    $out .= "\t</p>\n";
    $out .= "\t<a href='" . esc_url($up_url) . "' class='up";
    if ($valid) {
        $out .= ' hidden';
    }
    $out .= "'>" . __('Select file', 'kc-settings') . '</a>';
    $out .= "\t<input type='hidden' name='{$name}' value='{$db_value}' />\n";
    $out .= "</div>\n";
    return $out;
}
예제 #17
0
 public function _media_view_settings($settings = array(), $post = null)
 {
     $media_filter = clearbase_get_value('media_filter', '', clearbase_get_folder_settings($cb_post_id));
     if (!empty($media_filter)) {
         $post_mime_types = get_post_mime_types();
         $matches = wp_match_mime_types($media_filter, array_keys($post_mime_types));
         $settings['mimeTypes'] = wp_list_pluck(array_intersect_key($post_mime_types, $matches), 0);
         global $wpdb, $wp_locale;
         $post_parent = absint($post->ID);
         $and_where_mime = wp_post_mime_type_where($media_filter);
         $months = $wpdb->get_results("\n              SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month\n              FROM {$wpdb->posts}\n              WHERE post_parent = {$post_parent} AND post_type = 'attachment' {$and_where_mime}\n              ORDER BY post_date DESC");
         foreach ($months as $month_year) {
             $month_year->text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($month_year->month), $month_year->year);
         }
         $settings['months'] = $months;
     }
     return $settings;
 }
예제 #18
0
<?php
$type_links = array();
$_num_posts = (array) wp_count_attachments();
$matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
foreach ( $matches as $type => $reals )
	foreach ( $reals as $real )
		$num_posts[$type] += $_num_posts[$real];
$class = empty($_GET['post_mime_type']) ? ' class="current"' : '';
$type_links[] = "<li><a href=\"upload.php\"$class>".__('All Types')."</a>";
foreach ( $post_mime_types as $mime_type => $label ) {
	$class = '';

	if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
		continue;

	if ( wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
		$class = ' class="current"';

	$type_links[] = "<li><a href=\"upload.php?post_mime_type=$mime_type\"$class>" .
	sprintf(__ngettext($label[2][0], $label[2][1], $num_posts[$mime_type]), number_format_i18n( $num_posts[$mime_type] )) . '</a>';
}
echo implode(' | </li>', $type_links) . '</li>';
unset($type_links);
?>
</ul>

<?php
if ( isset($_GET['posted']) && $_GET['posted'] ) : $_GET['posted'] = (int) $_GET['posted']; ?>
<div id="message" class="updated fade"><p><strong><?php _e('Your media has been saved.'); ?></strong> <a href="<?php echo get_permalink( $_GET['posted'] ); ?>"><?php _e('View media'); ?></a> | <a href="media.php?action=edit&amp;attachment_id=<?php echo $_GET['posted']; ?>"><?php _e('Edit media'); ?></a></p></div>
<?php $_SERVER['REQUEST_URI'] = remove_query_arg(array('posted'), $_SERVER['REQUEST_URI']);
endif;
예제 #19
0
 function get_attachments_by_media_tags($args = '')
 {
     global $post;
     $defaults = array('call_source' => '', 'display_item_callback' => 'default_item_callback', 'media_tags' => '', 'media_types' => null, 'numberposts' => '-1', 'orderby' => 'menu_order', 'order' => 'ASC', 'offset' => '0', 'post_type' => '', 'return_type' => '', 'search_by' => 'slug', 'size' => 'medium', 'tags_compare' => 'OR', 'nopaging' => '');
     $r = wp_parse_args($args, $defaults);
     if (!$r['media_tags'] || strlen($r['media_tags']) == 0) {
         return;
     }
     //		if ((!$r['post_parent']) || (strlen($r['post_parent']) == 0))
     //		{
     //			if ($post)
     //				$r['post_parent'] = $post->ID;
     //			else
     //				return;
     //		}
     // Future support for multiple post_parents --- Coming Soon!
     //		if (strlen($r['post_parent']))
     //		{
     //			if (!is_array($r['post_parent']))
     //			{
     //				$r['post_parent'] = (array) $r['post_parent'];
     //			}
     //		}
     //		echo "post_parent<pre>"; print_r($r['post_parent']); echo "</pre>";
     // Force 'OR' on compare if searching by name (not slug). This is because the name search will return multiple
     // values per each 'media_tags' searched item.
     if ($r['search_by'] != 'slug') {
         $r['tags_compare'] = 'OR';
     }
     // First split the comma-seperated media-tags list into an array
     $r['media_tags_array'] = split(',', $r['media_tags']);
     if ($r['media_tags_array']) {
         foreach ($r['media_tags_array'] as $idx => $val) {
             //$r['media_tags_array'][$idx] = sanitize_title_with_dashes($val);
             $r['media_tags_array'][$idx] = sanitize_title($val);
         }
     }
     // Next split the comma-seperated media-types list into an array
     if ($r['media_types']) {
         $r['media_types_array'] = split(',', $r['media_types']);
         if ($r['media_types_array']) {
             foreach ($r['media_types_array'] as $idx => $val) {
                 //$r['media_types_array'][$idx] = sanitize_title_with_dashes($val);
                 $r['media_types_array'][$idx] = sanitize_title($val);
             }
         }
     }
     //echo "r<pre>"; print_r($r); echo "</pre>";
     // Next lookup each term in the terms table.
     $search_terms_array = array();
     if ($r['media_tags_array']) {
         foreach ($r['media_tags_array'] as $search_term) {
             $get_terms_args['hide_empty'] = 0;
             if ($r['search_by'] != "slug") {
                 $get_terms_args['search'] = $search_term;
             } else {
                 $get_terms_args['slug'] = $search_term;
             }
             $terms_item = get_terms(MEDIA_TAGS_TAXONOMY, $get_terms_args);
             if ($terms_item) {
                 $search_terms_array[$search_term] = $terms_item;
             }
         }
     }
     //echo "search_terms_array<pre>"; print_r($search_terms_array); echo "</pre>";
     $objects_ids_array = array();
     if (count($search_terms_array)) {
         foreach ($search_terms_array as $search_term_items) {
             if ($search_term_items) {
                 foreach ($search_term_items as $search_term_item) {
                     $objects_ids = get_objects_in_term($search_term_item->term_id, MEDIA_TAGS_TAXONOMY);
                     if ($objects_ids) {
                         $objects_ids_array[$search_term_item->slug] = $objects_ids;
                     } else {
                         $objects_ids_array[$search_term_item->slug] = array();
                     }
                 }
             }
         }
     }
     if (count($objects_ids_array) > 1) {
         foreach ($objects_ids_array as $idx_ids => $object_ids_item) {
             if (!isset($array_unique_ids) && $idx_ids == 0) {
                 $array_unique_ids = $object_ids_item;
             }
             if (strtoupper($r['tags_compare']) == strtoupper("AND")) {
                 $array_unique_ids = array_unique(array_intersect($array_unique_ids, $object_ids_item));
             } else {
                 $array_unique_ids = array_unique(array_merge($array_unique_ids, $object_ids_item));
             }
         }
         sort($array_unique_ids);
     } else {
         if (count($objects_ids_array) == 1) {
             foreach ($objects_ids_array as $idx_ids => $object_ids_item) {
                 $array_unique_ids = $object_ids_item;
                 break;
             }
         }
     }
     $object_ids_str = "";
     if ($array_unique_ids) {
         $object_ids_str = implode(',', $array_unique_ids);
     }
     if ($object_ids_str) {
         $query_array = array('post_type' => 'attachment', 'numberposts' => -1);
         if (isset($r['post_parent']) && intval($r['post_parent']) > 0) {
             $query_array['post_parent'] = $r['post_parent'];
         }
         if (isset($r['nopaging']) && strlen($r['nopaging'])) {
             $query_array['nopaging'] = $r['nopaging'];
         }
         if (isset($r['post_type']) && strlen($r['post_type'])) {
             $query_array['post_type'] = $r['post_type'];
         }
         //echo "query_array<pre>"; print_r($query_array); echo "</pre>";
         $attachment_posts = get_posts($query_array);
         $attachment_posts_ids = array();
         if ($attachment_posts) {
             foreach ($attachment_posts as $attachment_post) {
                 $attachment_posts_ids[] = $attachment_post->ID;
             }
         }
         $result = array_intersect($array_unique_ids, $attachment_posts_ids);
         if ($result) {
             $get_post_args['post_type'] = "attachment";
             $get_post_args['numberposts'] = $r['numberposts'];
             $get_post_args['offset'] = $r['offset'];
             $get_post_args['orderby'] = $r['orderby'];
             $get_post_args['order'] = $r['order'];
             $get_post_args['include'] = implode(',', $result);
             $attachment_posts = get_posts($get_post_args);
             // Now that we have the list of all matching posts we need to filter by the media type is provided
             if (isset($r['media_types_array']) && count($r['media_types_array'])) {
                 foreach ($attachment_posts as $attachment_idx => $attachment_post) {
                     $ret_mime_match = wp_match_mime_types($r['media_types_array'], $attachment_post->post_mime_type);
                     //echo "ret_mime_match<pre>"; print_r($ret_mime_match); echo "</pre>";
                     if (!$ret_mime_match) {
                         unset($attachment_posts[$attachment_idx]);
                     }
                 }
             }
             // If the calling system doesn't want the whole list.
             //if (($r['offset'] > 0) || ($r['numberposts'] > 0))
             //	$attachment_posts = array_slice($attachment_posts, $r['offset'], $r['numberposts']);
             //http://wordpress.org/support/topic/plugin-media-tags-get_attachments_by_media_tags-twice-offset-fix?replies=2
             if ($r['numberposts'] > 0) {
                 $attachment_posts = array_slice($attachment_posts, 0, $r['numberposts']);
             }
             if ($r['return_type'] === "li") {
                 $attachment_posts_list = "";
                 foreach ($attachment_posts as $attachment_idx => $attachment_post) {
                     if (strlen($r['display_item_callback']) && function_exists($r['display_item_callback'])) {
                         $attachment_posts_list .= call_user_func($r['display_item_callback'], $attachment_post, $r['size']);
                     }
                 }
                 return $attachment_posts_list;
             } else {
                 return $attachment_posts;
             }
         }
     }
 }
예제 #20
0
/**
 * Retrieves a sepecific playlist item.  In this case it is a media attachment.
 * @global string $redir_tab The tab to redirect to.
 * @param int $attachment_id The id of the attachment we are retrieving.
 * @param array $args Any additional arguments for query the database.
 * @param int $current_playlist The currently selected playlist.
 * @return string The HTML representing the playlist item.
 */
function get_jw_playlist_item($attachment_id, $args, $current_playlist, $prefix = "")
{
    global $redir_tab, $p_items;
    if (($attachment_id = intval($attachment_id)) && ($thumb_url = get_attachment_icon_src($attachment_id))) {
        $thumb_url = $thumb_url[0];
    } else {
        return false;
    }
    $default_args = array('errors' => null, 'send' => true, 'delete' => true, 'toggle' => true, 'show_title' => true);
    $args = wp_parse_args($args, $default_args);
    extract($args, EXTR_SKIP);
    $post = get_post($attachment_id);
    $filename = basename($post->guid);
    $title = esc_attr($post->post_title);
    if ($_tags = get_the_tags($attachment_id)) {
        foreach ($_tags as $tag) {
            $tags[] = $tag->name;
        }
        $tags = esc_attr(join(', ', $tags));
    }
    $post_mime_types = get_post_mime_types();
    $keys = array_keys(wp_match_mime_types(array_keys($post_mime_types), $post->post_mime_type));
    $type = array_shift($keys);
    $type_html = "<input type='hidden' id='type-of-{$attachment_id}' value='" . esc_attr($type) . "' />";
    $form_fields = get_attachment_fields_to_edit($post, $errors);
    $display_title = !empty($title) ? $title : $filename;
    // $title shouldn't ever be empty, but just in case
    $display_title = $show_title ? "<div class='filename new'><span class='title'>" . wp_html_excerpt($display_title, 60) . "</span></div>" : '';
    $gallery = isset($_REQUEST['tab']) && 'gallery' == $_REQUEST['tab'] || isset($redir_tab) && 'gallery' == $redir_tab ? true : false;
    $order = '';
    $checked = "";
    foreach ($p_items as $playlist_item) {
        if ($playlist_item == $attachment_id) {
            $checked = "checked='true'";
            break;
        }
    }
    foreach ($form_fields as $key => $val) {
        if ('menu_order' == $key) {
            if (true) {
                $order = '<div class="menu_order">';
                $order .= '<input class="menu_order_input" type="checkbox" id="' . $prefix . 'attachments[' . $attachment_id . '][enabled]" name="' . $prefix . 'attachments[' . $attachment_id . '][enabled]" value="' . $val['value'] . '"' . $checked . ' onclick="updatePlaylist(this);" /></div>';
            } else {
                $order = '<input type="hidden" name="' . $prefix . 'attachments[' . $attachment_id . '][menu_order]" value="' . $val['value'] . '" />';
            }
            unset($form_fields['menu_order']);
            break;
        }
    }
    $media_dims = '';
    $meta = wp_get_attachment_metadata($post->ID);
    if (is_array($meta) && array_key_exists('width', $meta) && array_key_exists('height', $meta)) {
        $media_dims .= "<span id='playlist-dims-{$post->ID}'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
    }
    $media_dims = apply_filters('media_meta', $media_dims, $post);
    $image_edit_button = '';
    if (gd_edit_image_support($post->post_mime_type)) {
        $nonce = wp_create_nonce("image_editor-{$post->ID}");
        $image_edit_button = "<input type='button' id='imgedit-open-btn-{$post->ID}' onclick='imageEdit.open({$post->ID}, \"{$nonce}\")' class='button' value='" . esc_attr__('Edit image') . "' /> <img src='images/wpspin_light.gif' class='imgedit-wait-spin' alt='' />";
    }
    $item = "\n\t{$type_html}\n\t{$toggle_links}\n\t{$order}\n\t{$display_title}\n  <table class='slidetoggle describe startclosed'>\n\t\t<thead class='media-item-info' id='media-head-{$post->ID}'>\n\t\t<tr>\n\t\t\t<td class='A1B1' id='thumbnail-head-{$post->ID}' rowspan='5'><img class='thumbnail' src='{$thumb_url}' alt='' /></td>\n\t\t\t<td><strong>" . __('File name:') . "</strong> {$filename}</td>\n\t\t</tr>\n\t\t<tr><td><strong>" . __('File type:') . "</strong> {$post->post_mime_type}</td></tr>\n\t\t<tr><td><strong>" . __('Upload date:') . "</strong> " . mysql2date(get_option('date_format'), $post->post_date) . "</td></tr>\n";
    if (!empty($media_dims)) {
        $item .= "<tr><td><strong>" . __('Dimensions:') . "</strong> {$media_dims}</td></tr>\n";
    }
    $item .= "\n\t\t<tr><td class='A1B1'>{$image_edit_button}</td></tr>\n\t\t</thead>\n\t\t<tbody>\n\t\t<tr><td colspan='2' class='imgedit-response' id='imgedit-response-{$post->ID}'></td></tr>\n\t\t<tr><td style='display:none' colspan='2' class='image-editor' id='image-editor-{$post->ID}'></td></tr>\n";
    $defaults = array('input' => 'text', 'required' => false, 'value' => '', 'extra_rows' => array());
    $thumbnail = '';
    $calling_post_id = 0;
    if (isset($_GET['post_id'])) {
        $calling_post_id = $_GET['post_id'];
    } elseif (isset($_POST) && count($_POST)) {
        // Like for async-upload where $_GET['post_id'] isn't set
        $calling_post_id = $post->post_parent;
    }
    if ('image' == $type && $calling_post_id && current_theme_supports('post-thumbnails', get_post_type($calling_post_id)) && get_post_thumbnail_id($calling_post_id) != $attachment_id) {
        $thumbnail = "<a class='wp-post-thumbnail' id='wp-post-thumbnail-" . $attachment_id . "' href='#' onclick='WPSetAsThumbnail(\"{$attachment_id}\");return false;'>" . esc_html__("Use as thumbnail") . "</a>";
    }
    if (($send || $thumbnail || $delete) && !isset($form_fields['buttons'])) {
        $form_fields['buttons'] = array('tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>{$send} {$thumbnail} {$delete}</td></tr>\n");
    }
    $hidden_fields = array();
    foreach ($form_fields as $id => $field) {
        if ($id[0] == '_') {
            continue;
        }
        if (!empty($field['tr'])) {
            $item .= $field['tr'];
            continue;
        }
        $field = array_merge($defaults, $field);
        $name = "attachments[{$attachment_id}][{$id}]";
        if ($field['input'] == 'hidden') {
            $hidden_fields[$name] = $field['value'];
            continue;
        }
        $required = $field['required'] ? '<abbr title="required" class="required">*</abbr>' : '';
        $aria_required = $field['required'] ? " aria-required='true' " : '';
        $class = $id;
        $class .= $field['required'] ? ' form-required' : '';
        $item .= "\t\t<tr class='{$class}'>\n\t\t\t<th valign='top' scope='row' class='label'><label for='{$name}'><span class='alignleft'>{$field['label']}</span><span class='alignright'>{$required}</span><br class='clear' /></label></th>\n\t\t\t<td class='field'>";
        if (!empty($field[$field['input']])) {
            $item .= $field[$field['input']];
        } elseif ($field['input'] == 'textarea') {
            $item .= "<textarea type='text' id='{$name}' name='{$name}'" . $aria_required . ">" . esc_html($field['value']) . "</textarea>";
        } else {
            $item .= "<input type='text' class='text' id='{$name}' name='{$name}' value='" . esc_attr($field['value']) . "'" . $aria_required . "/>";
        }
        if (!empty($field['helps'])) {
            $item .= "<p class='help'>" . join("</p>\n<p class='help'>", array_unique((array) $field['helps'])) . '</p>';
        }
        $item .= "</td>\n\t\t</tr>\n";
        $extra_rows = array();
        if (!empty($field['errors'])) {
            foreach (array_unique((array) $field['errors']) as $error) {
                $extra_rows['error'][] = $error;
            }
        }
        if (!empty($field['extra_rows'])) {
            foreach ($field['extra_rows'] as $class => $rows) {
                foreach ((array) $rows as $html) {
                    $extra_rows[$class][] = $html;
                }
            }
        }
        foreach ($extra_rows as $class => $rows) {
            foreach ($rows as $html) {
                $item .= "\t\t<tr><td></td><td class='{$class}'>{$html}</td></tr>\n";
            }
        }
    }
    if (!empty($form_fields['_final'])) {
        $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
    }
    $item .= "\t</tbody>\n";
    $item .= "\t</table>\n";
    //  $item .= "<img class='thumbnail hidden' src='$thumb_url' alt='' />";
    foreach ($hidden_fields as $name => $value) {
        $item .= "\t<input type='hidden' name='{$name}' id='{$name}' value='" . esc_attr($value) . "' />\n";
    }
    if ($post->post_parent < 1 && isset($_REQUEST['post_id'])) {
        $parent = (int) $_REQUEST['post_id'];
        $parent_name = $prefix . "attachments[{$attachment_id}][post_parent]";
        $item .= "\t<input type='hidden' name='{$parent_name}' id='{$parent_name}' value='" . $parent . "' />\n";
    }
    return $item;
}
예제 #21
0
function wp_ajax_upload_attachment()
{
    check_ajax_referer('media-form');
    if (!current_user_can('upload_files')) {
        wp_die();
    }
    if (isset($_REQUEST['post_id'])) {
        $post_id = $_REQUEST['post_id'];
        if (!current_user_can('edit_post', $post_id)) {
            wp_die();
        }
    } else {
        $post_id = null;
    }
    $post_data = isset($_REQUEST['post_data']) ? $_REQUEST['post_data'] : array();
    // If the context is custom header or background, make sure the uploaded file is an image.
    if (isset($post_data['context']) && in_array($post_data['context'], array('custom-header', 'custom-background'))) {
        $wp_filetype = wp_check_filetype_and_ext($_FILES['async-upload']['tmp_name'], $_FILES['async-upload']['name'], false);
        if (!wp_match_mime_types('image', $wp_filetype['type'])) {
            echo json_encode(array('success' => false, 'data' => array('message' => __('The uploaded file is not a valid image. Please try again.'), 'filename' => $_FILES['async-upload']['name'])));
            wp_die();
        }
    }
    $attachment_id = media_handle_upload('async-upload', $post_id, $post_data);
    if (is_wp_error($attachment_id)) {
        echo json_encode(array('success' => false, 'data' => array('message' => $attachment_id->get_error_message(), 'filename' => $_FILES['async-upload']['name'])));
        wp_die();
    }
    if (isset($post_data['context']) && isset($post_data['theme'])) {
        if ('custom-background' === $post_data['context']) {
            update_post_meta($attachment_id, '_wp_attachment_is_custom_background', $post_data['theme']);
        }
        if ('custom-header' === $post_data['context']) {
            update_post_meta($attachment_id, '_wp_attachment_is_custom_header', $post_data['theme']);
        }
    }
    if (!($attachment = wp_prepare_attachment_for_js($attachment_id))) {
        wp_die();
    }
    echo json_encode(array('success' => true, 'data' => $attachment));
    wp_die();
}
 /** WP_Media_List_Table does not provide a filter for managing get_views() so,
  *  so we have done the next best thing.  Override
  *
  * @global wpdb  $wpdb
  * @global array $post_mime_types
  * @global array $avail_post_mime_types
  * @return array
  */
 public function get_views()
 {
     global $wpdb, $cb_post_id, $post_mime_types, $avail_post_mime_types;
     $type_links = array();
     // $_num_posts = (array) wp_count_attachments();
     $_num_posts = (array) clearbase_count_attachments($cb_post_id);
     //$_total_posts = array_sum($_num_posts) - $_num_posts['trash'];
     $media_filter = clearbase_get_value('media_filter', '', clearbase_get_folder_settings($cb_post_id));
     if (empty($media_filter)) {
         $media_filter = array_keys($post_mime_types);
     }
     $matches = wp_match_mime_types($media_filter, array_keys($_num_posts));
     $num_posts = array();
     foreach ($matches as $type => $reals) {
         foreach ($reals as $real) {
             $num_posts[$type] = isset($num_posts[$type]) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
         }
     }
     $selected = empty($_GET['attachment-filter']) ? ' selected="selected"' : '';
     if (count($num_posts) > 1) {
         $_total_posts = array_sum($num_posts) - $_num_posts['trash'];
         $type_links['all'] = "<option value=''{$selected}>" . sprintf(_nx('All (%s)', 'All (%s)', $_total_posts, 'uploaded files'), number_format_i18n($_total_posts)) . '</option>';
     }
     foreach ($post_mime_types as $mime_type => $label) {
         if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
             continue;
         }
         $selected = '';
         if (!empty($_GET['attachment-filter']) && strpos($_GET['attachment-filter'], 'post_mime_type:') === 0 && wp_match_mime_types($mime_type, str_replace('post_mime_type:', '', $_GET['attachment-filter']))) {
             $selected = ' selected="selected"';
         }
         if (!empty($num_posts[$mime_type])) {
             $type_links[$mime_type] = '<option value="post_mime_type:' . esc_attr($mime_type) . '"' . $selected . '>' . sprintf(translate_nooped_plural($label[2], $num_posts[$mime_type]), number_format_i18n($num_posts[$mime_type])) . '</option>';
         }
     }
     // $type_links['detached'] = '<option value="detached"' . ( $this->detached ? ' selected="selected"' : '' ) . '>' . sprintf( _nx( 'Unattached (%s)', 'Unattached (%s)', $total_orphans, 'detached files' ), number_format_i18n( $total_orphans ) ) . '</option>';
     if (!empty($_num_posts['trash'])) {
         $type_links['trash'] = '<option value="trash"' . (isset($_GET['attachment-filter']) && $_GET['attachment-filter'] == 'trash' ? ' selected="selected"' : '') . '>' . sprintf(_nx('Trash (%s)', 'Trash (%s)', $_num_posts['trash'], 'uploaded files'), number_format_i18n($_num_posts['trash'])) . '</option>';
     }
     return $type_links;
 }
예제 #23
0
/**
 * {@internal Missing Short Description}}
 *
 * @since unknown
 *
 * @param unknown_type $errors
 */
function media_upload_library_form($errors)
{
    global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types;
    media_upload_header();
    $post_id = intval($_REQUEST['post_id']);
    $form_action_url = admin_url("media-upload.php?type={$GLOBALS['type']}&tab=library&post_id={$post_id}");
    $_GET['paged'] = isset($_GET['paged']) ? intval($_GET['paged']) : 0;
    if ($_GET['paged'] < 1) {
        $_GET['paged'] = 1;
    }
    $start = ($_GET['paged'] - 1) * 10;
    if ($start < 1) {
        $start = 0;
    }
    add_filter('post_limits', $limit_filter = create_function('$a', "return 'LIMIT {$start}, 10';"));
    list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
    ?>

<form id="filter" action="" method="get">
<input type="hidden" name="type" value="<?php 
    echo esc_attr($type);
    ?>
" />
<input type="hidden" name="tab" value="<?php 
    echo esc_attr($tab);
    ?>
" />
<input type="hidden" name="post_id" value="<?php 
    echo (int) $post_id;
    ?>
" />
<input type="hidden" name="post_mime_type" value="<?php 
    echo isset($_GET['post_mime_type']) ? esc_attr($_GET['post_mime_type']) : '';
    ?>
" />

<p id="media-search" class="search-box">
	<label class="screen-reader-text" for="media-search-input"><?php 
    _e('Search Media');
    ?>
:</label>
	<input type="text" id="media-search-input" name="s" value="<?php 
    the_search_query();
    ?>
" />
	<input type="submit" value="<?php 
    esc_attr_e('Search Media');
    ?>
" class="button" />
</p>

<ul class="subsubsub">
<?php 
    $type_links = array();
    $_num_posts = (array) wp_count_attachments();
    $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
    foreach ($matches as $_type => $reals) {
        foreach ($reals as $real) {
            if (isset($num_posts[$_type])) {
                $num_posts[$_type] += $_num_posts[$real];
            } else {
                $num_posts[$_type] = $_num_posts[$real];
            }
        }
    }
    // If available type specified by media button clicked, filter by that type
    if (empty($_GET['post_mime_type']) && !empty($num_posts[$type])) {
        $_GET['post_mime_type'] = $type;
        list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
    }
    if (empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all') {
        $class = ' class="current"';
    } else {
        $class = '';
    }
    $type_links[] = "<li><a href='" . esc_url(add_query_arg(array('post_mime_type' => 'all', 'paged' => false, 'm' => false))) . "'{$class}>" . __('All Types') . "</a>";
    foreach ($post_mime_types as $mime_type => $label) {
        $class = '';
        if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
            continue;
        }
        if (isset($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type'])) {
            $class = ' class="current"';
        }
        $type_links[] = "<li><a href='" . esc_url(add_query_arg(array('post_mime_type' => $mime_type, 'paged' => false))) . "'{$class}>" . sprintf(_n($label[2][0], $label[2][1], $num_posts[$mime_type]), "<span id='{$mime_type}-counter'>" . number_format_i18n($num_posts[$mime_type]) . '</span>') . '</a>';
    }
    echo implode(' | </li>', $type_links) . '</li>';
    unset($type_links);
    ?>
</ul>

<div class="tablenav">

<?php 
    $page_links = paginate_links(array('base' => add_query_arg('paged', '%#%'), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => ceil($wp_query->found_posts / 10), 'current' => $_GET['paged']));
    if ($page_links) {
        echo "<div class='tablenav-pages'>{$page_links}</div>";
    }
    ?>

<div class="alignleft actions">
<?php 
    $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM {$wpdb->posts} WHERE post_type = 'attachment' ORDER BY post_date DESC";
    $arc_result = $wpdb->get_results($arc_query);
    $month_count = count($arc_result);
    if ($month_count && !(1 == $month_count && 0 == $arc_result[0]->mmonth)) {
        ?>
<select name='m'>
<option<?php 
        selected(@$_GET['m'], 0);
        ?>
 value='0'><?php 
        _e('Show all dates');
        ?>
</option>
<?php 
        foreach ($arc_result as $arc_row) {
            if ($arc_row->yyear == 0) {
                continue;
            }
            $arc_row->mmonth = zeroise($arc_row->mmonth, 2);
            if ($arc_row->yyear . $arc_row->mmonth == $_GET['m']) {
                $default = ' selected="selected"';
            } else {
                $default = '';
            }
            echo "<option{$default} value='" . esc_attr($arc_row->yyear . $arc_row->mmonth) . "'>";
            echo esc_html($wp_locale->get_month($arc_row->mmonth) . " {$arc_row->yyear}");
            echo "</option>\n";
        }
        ?>
</select>
<?php 
    }
    ?>

<input type="submit" id="post-query-submit" value="<?php 
    echo esc_attr(__('Filter &#187;'));
    ?>
" class="button-secondary" />

</div>

<br class="clear" />
</div>
</form>

<form enctype="multipart/form-data" method="post" action="<?php 
    echo esc_attr($form_action_url);
    ?>
" class="media-upload-form validate" id="library-form">

<?php 
    wp_nonce_field('media-form');
    //media_upload_form( $errors );
    ?>

<script type="text/javascript">
<!--
jQuery(function($){
	var preloaded = $(".media-item.preloaded");
	if ( preloaded.length > 0 ) {
		preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
		updateMediaForm();
	}
});
-->
</script>

<div id="media-items">
<?php 
    add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2);
    echo get_media_items(null, $errors);
    ?>
</div>
<p class="ml-submit">
<input type="submit" class="button savebutton" name="save" value="<?php 
    esc_attr_e('Save all changes');
    ?>
" />
<input type="hidden" name="post_id" id="post_id" value="<?php 
    echo (int) $post_id;
    ?>
" />
</p>
</form>
<?php 
}
    /**
     * {@internal Missing Short Description}}
     *
     * @since 2.5.0
     *
     * @param unknown_type $errors
     */
    function media_upload_shared_media($errors)
    {
        global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types, $blog_id;
        media_upload_header();
        if (count($this->blogs) == 0) {
            echo '<form><h3 class="media-title">' . __("You don't have access to any other sites media...", 'networksharedmedia') . '</h3></form>';
            return;
        }
        // set the first part of the form action url now, to the current active site, to prevent X-Frame-Options problems
        $form_action_url = plugins_url('media-upload.php', __FILE__);
        $nsm_blog_id = null;
        if (!array_key_exists('blog_id', $_GET)) {
            $_GET['blog_id'] = null;
        }
        foreach ($this->blogs as $blog) {
            if ($_GET['blog_id'] == $blog['blog_id']) {
                $nsm_blog_id = $blog['blog_id'];
                break;
            }
        }
        if (null == $nsm_blog_id) {
            $nsm_blog_id = $this->blogs[0]['blog_id'];
        }
        switch_to_blog($nsm_blog_id);
        ?>

<?php 
        $post_id = intval($_REQUEST['post_id']);
        // fix to make get_media_item add "Insert" button
        unset($_GET['post_id']);
        $form_action_url .= "?type={$type}&tab=library&post_id={$post_id}&blog_id={$blog_id}";
        $form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type);
        $form_class = 'media-upload-form validate';
        $_GET['paged'] = isset($_GET['paged']) ? intval($_GET['paged']) : 0;
        if ($_GET['paged'] < 1) {
            $_GET['paged'] = 1;
        }
        $start = ($_GET['paged'] - 1) * 10;
        if ($start < 1) {
            $start = 0;
        }
        add_filter('post_limits', create_function('$a', "return 'LIMIT {$start}, 10';"));
        list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
        ?>
	
	<form id="filter" action="" method="get">
	<input type="hidden" name="type" value="<?php 
        echo esc_attr($type);
        ?>
" />
	<input type="hidden" name="tab" value="<?php 
        echo esc_attr($tab);
        ?>
" />
	<input type="hidden" name="post_id" value="<?php 
        echo (int) $post_id;
        ?>
" />
	<input type="hidden" name="blog_id" value="<?php 
        echo (int) $blog_id;
        ?>
" />
	<input type="hidden" name="post_mime_type" value="<?php 
        echo isset($_GET['post_mime_type']) ? esc_attr($_GET['post_mime_type']) : '';
        ?>
" />
	<?php 
        if (isset($_GET['chromeless'])) {
            ?>
	<input type="hidden" name="chromeless" value="<?php 
            echo (bool) $_GET['chromeless'];
            ?>
" />
	<?php 
        }
        ?>

	<style type="text/css">
		#media-upload #filter .nsm-site-select { float: none; width: 100%; margin: 0 1em 2em 1em; white-space: normal; }
	</style>

	<ul class="subsubsub nsm-site-select">
	<?php 
        if (count($this->blogs) == 1) {
            $blog = reset($this->blogs);
            echo "<li>" . __('Selected site:', 'networksharedmedia') . "</li>" . "<li><a href='" . esc_url(add_query_arg(array('blog_id' => $blog['blog_id'], 'paged' => false))) . "' class='current'>" . $blog['name'] . '</a>' . '</li>';
        } else {
            $all_blog_names = array();
            foreach ($this->blogs as $blog) {
                $all_blog_names[] = $blog['name'];
            }
            if (strlen(__('Select site:', 'networksharedmedia') . ' ' . implode(' | ', $all_blog_names)) < 71) {
                $blog_links = array();
                foreach ($this->blogs as $blog) {
                    $class = '';
                    if ($blog['blog_id'] == $blog_id) {
                        $class = ' class="current"';
                    }
                    $blog_links[] = "<li><a href='" . esc_url(add_query_arg(array('blog_id' => $blog['blog_id'], 'paged' => false))) . "'{$class}>" . $blog['name'] . '</a>';
                }
                echo "<li>" . __('Select site:', 'networksharedmedia') . " </li>" . implode(' | </li>', $blog_links) . '</li>';
                unset($blog_links);
            } else {
                $blog_options = array();
                foreach ($this->blogs as $blog) {
                    $selected = '';
                    if ($blog['blog_id'] == $blog_id) {
                        $selected = ' selected="selected"';
                    }
                    $blog_options[] = "<option value='{$blog['blog_id']}'{$selected}>" . $blog['name'] . '</option>';
                }
                echo "<li>" . __('Select site:', 'networksharedmedia') . "</li><li> <select name='blog_id'>" . implode('', $blog_options) . '</select></li><li> ' . get_submit_button(__('Select &#187;', 'networksharedmedia'), 'secondary', 'nsm-post-query-submit', false) . '</li>';
                unset($blog_options);
            }
            unset($all_blog_names);
        }
        ?>
	</ul>

	<p id="media-search" class="search-box">
		<label class="screen-reader-text" for="media-search-input"><?php 
        _e('Search Media');
        ?>
:</label>
		<input type="text" id="media-search-input" name="s" value="<?php 
        the_search_query();
        ?>
" />
		<?php 
        submit_button(__('Search Media'), 'button', '', false);
        ?>
	</p>
	
	<ul class="subsubsub">
	<?php 
        $type_links = array();
        $_num_posts = (array) wp_count_attachments();
        $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
        foreach ($matches as $_type => $reals) {
            foreach ($reals as $real) {
                if (isset($num_posts[$_type])) {
                    $num_posts[$_type] += $_num_posts[$real];
                } else {
                    $num_posts[$_type] = $_num_posts[$real];
                }
            }
        }
        // If available type specified by media button clicked, filter by that type
        if (empty($_GET['post_mime_type']) && !empty($num_posts[$type])) {
            $_GET['post_mime_type'] = $type;
            list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
        }
        if (empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all') {
            $class = ' class="current"';
        } else {
            $class = '';
        }
        $type_links[] = "<li><a href='" . esc_url(add_query_arg(array('post_mime_type' => 'all', 'paged' => false, 'm' => false))) . "'{$class}>" . __('All Types') . "</a>";
        foreach ($post_mime_types as $mime_type => $label) {
            $class = '';
            if (!wp_match_mime_types($mime_type, $avail_post_mime_types)) {
                continue;
            }
            if (isset($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type'])) {
                $class = ' class="current"';
            }
            $type_links[] = "<li><a href='" . esc_url(add_query_arg(array('post_mime_type' => $mime_type, 'paged' => false))) . "'{$class}>" . sprintf(translate_nooped_plural($label[2], $num_posts[$mime_type]), "<span id='{$mime_type}-counter'>" . number_format_i18n($num_posts[$mime_type]) . '</span>') . '</a>';
        }
        echo implode(' | </li>', apply_filters('media_upload_mime_type_links', $type_links)) . '</li>';
        unset($type_links);
        ?>
	</ul>
	
	<div class="tablenav">
	
	<?php 
        $page_links = paginate_links(array('base' => add_query_arg('paged', '%#%'), 'format' => '', 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'total' => ceil($wp_query->found_posts / 10), 'current' => $_GET['paged']));
        if ($page_links) {
            echo "<div class='tablenav-pages'>{$page_links}</div>";
        }
        ?>
	
	<div class="alignleft actions">
	<?php 
        $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM {$wpdb->posts} WHERE post_type = 'attachment' ORDER BY post_date DESC";
        $arc_result = $wpdb->get_results($arc_query);
        $month_count = count($arc_result);
        if ($month_count && !(1 == $month_count && 0 == $arc_result[0]->mmonth)) {
            ?>
	<select name='m'>
	<option<?php 
            selected(@$_GET['m'], 0);
            ?>
 value='0'><?php 
            _e('Show all dates');
            ?>
</option>
	<?php 
            foreach ($arc_result as $arc_row) {
                if ($arc_row->yyear == 0) {
                    continue;
                }
                $arc_row->mmonth = zeroise($arc_row->mmonth, 2);
                if (isset($_GET['m']) && $arc_row->yyear . $arc_row->mmonth == $_GET['m']) {
                    $default = ' selected="selected"';
                } else {
                    $default = '';
                }
                echo "<option{$default} value='" . esc_attr($arc_row->yyear . $arc_row->mmonth) . "'>";
                echo esc_html($wp_locale->get_month($arc_row->mmonth) . " {$arc_row->yyear}");
                echo "</option>\n";
            }
            ?>
	</select>
	<?php 
        }
        ?>
	
	<?php 
        submit_button(__('Filter &#187;'), 'secondary', 'post-query-submit', false);
        ?>
	
	</div>
	
	<br class="clear" />
	</div>
	</form>
	
	<form enctype="multipart/form-data" method="post" action="<?php 
        echo esc_attr($form_action_url);
        ?>
" class="<?php 
        echo $form_class;
        ?>
" id="library-form">
	
	<?php 
        wp_nonce_field('media-form');
        ?>
	<?php 
        //media_upload_form( $errors );
        ?>

	<?php 
        if (isset($_GET['chromeless']) && $_GET['chromeless']) {
            // WP3.5+ Media Browser calls iframe 'chromeless' and handles inserting differently
            ?>
	<script type="text/javascript">
	/* <![CDATA[ */
	function nsm_media_send_to_editor(htmlString) {
		<?php 
            /* copied from /wp-admin/includes/media.php media_send_to_editor() */
            ?>
		var win = window.dialogArguments || opener || parent || top;
		win.send_to_editor(htmlString);
	}

	jQuery(function($){
		$('input[id^=send].button').click(function(event) {
			event.preventDefault();
			var $this = $(event.target);
			var form = $('#library-form');
			var result = $.ajax({
				url: form.attr('action'),
				type: form.attr('method'),
				data: form.serialize() + '&' + encodeURIComponent($this.attr('id') ) + '=true&chromeless=1',
				success: nsm_media_send_to_editor
			});
		});
	});
	/* ]]> */
	</script>
	<?php 
        }
        /* chromeless */
        ?>

	<script type="text/javascript">
	<!--
	jQuery(function($){
		var preloaded = $(".media-item.preloaded");
		if ( preloaded.length > 0 ) {
			preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
			updateMediaForm();
		}
	});
	-->
	</script>
	
	<div id="media-items">
	<?php 
        add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2);
        ?>
	<?php 
        echo $this->get_media_items(null, $errors);
        ?>
	</div>
	<p class="ml-submit"></p>
	</form>
	<?php 
    }
예제 #25
0
/**
 * Retrieve the icon for a MIME type.
 *
 * @since 2.1.0
 *
 * @param string|int $mime MIME type or attachment ID.
 * @return string|false Icon, false otherwise.
 */
function wp_mime_type_icon($mime = 0)
{
    if (!is_numeric($mime)) {
        $icon = wp_cache_get("mime_type_icon_{$mime}");
    }
    $post_id = 0;
    if (empty($icon)) {
        $post_mimes = array();
        if (is_numeric($mime)) {
            $mime = (int) $mime;
            if ($post = get_post($mime)) {
                $post_id = (int) $post->ID;
                $file = get_attached_file($post_id);
                $ext = preg_replace('/^.+?\\.([^.]+)$/', '$1', $file);
                if (!empty($ext)) {
                    $post_mimes[] = $ext;
                    if ($ext_type = wp_ext2type($ext)) {
                        $post_mimes[] = $ext_type;
                    }
                }
                $mime = $post->post_mime_type;
            } else {
                $mime = 0;
            }
        } else {
            $post_mimes[] = $mime;
        }
        $icon_files = wp_cache_get('icon_files');
        if (!is_array($icon_files)) {
            /**
             * Filter the icon directory path.
             *
             * @since 2.0.0
             *
             * @param string $path Icon directory absolute path.
             */
            $icon_dir = apply_filters('icon_dir', ABSPATH . WPINC . '/images/media');
            /**
             * Filter the icon directory URI.
             *
             * @since 2.0.0
             *
             * @param string $uri Icon directory URI.
             */
            $icon_dir_uri = apply_filters('icon_dir_uri', includes_url('images/media'));
            /**
             * Filter the list of icon directory URIs.
             *
             * @since 2.5.0
             *
             * @param array $uris List of icon directory URIs.
             */
            $dirs = apply_filters('icon_dirs', array($icon_dir => $icon_dir_uri));
            $icon_files = array();
            while ($dirs) {
                $keys = array_keys($dirs);
                $dir = array_shift($keys);
                $uri = array_shift($dirs);
                if ($dh = opendir($dir)) {
                    while (false !== ($file = readdir($dh))) {
                        $file = basename($file);
                        if (substr($file, 0, 1) == '.') {
                            continue;
                        }
                        if (!in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg'))) {
                            if (is_dir("{$dir}/{$file}")) {
                                $dirs["{$dir}/{$file}"] = "{$uri}/{$file}";
                            }
                            continue;
                        }
                        $icon_files["{$dir}/{$file}"] = "{$uri}/{$file}";
                    }
                    closedir($dh);
                }
            }
            wp_cache_add('icon_files', $icon_files, 'default', 600);
        }
        $types = array();
        // Icon basename - extension = MIME wildcard.
        foreach ($icon_files as $file => $uri) {
            $types[preg_replace('/^([^.]*).*$/', '$1', basename($file))] =& $icon_files[$file];
        }
        if (!empty($mime)) {
            $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
            $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
            $post_mimes[] = str_replace('/', '_', $mime);
        }
        $matches = wp_match_mime_types(array_keys($types), $post_mimes);
        $matches['default'] = array('default');
        foreach ($matches as $match => $wilds) {
            foreach ($wilds as $wild) {
                if (!isset($types[$wild])) {
                    continue;
                }
                $icon = $types[$wild];
                if (!is_numeric($mime)) {
                    wp_cache_add("mime_type_icon_{$mime}", $icon);
                }
                break 2;
            }
        }
    }
    /**
     * Filter the mime type icon.
     *
     * @since 2.1.0
     *
     * @param string $icon    Path to the mime type icon.
     * @param string $mime    Mime type.
     * @param int    $post_id Attachment ID. Will equal 0 if the function passed
     *                        the mime type.
     */
    return apply_filters('wp_mime_type_icon', $icon, $mime, $post_id);
}
예제 #26
0
/**
 * Get allowed avatar mime types
 *
 * @since  BuddyPress (2.3.0)
 */
function bp_core_get_allowed_avatar_mimes()
{
    $allowed_types = bp_core_get_allowed_avatar_types();
    $validate_mimes = wp_match_mime_types(join(',', $allowed_types), wp_get_mime_types());
    $allowed_mimes = array_map('implode', $validate_mimes);
    /**
     * Include jpg type if needed so that bp_core_check_avatar_type()
     * will check for jpeg and jpg extensions.
     */
    if (isset($allowed_mimes['jpeg'])) {
        $allowed_mimes['jpg'] = $allowed_mimes['jpeg'];
    }
    return $allowed_mimes;
}
예제 #27
0
/**
 * Ajax handler for uploading attachments
 *
 * @since 3.3.0
 */
function wp_ajax_upload_attachment()
{
    check_ajax_referer('media-form');
    /*
     * This function does not use wp_send_json_success() / wp_send_json_error()
     * as the html4 Plupload handler requires a text/html content-type for older IE.
     * See https://core.trac.wordpress.org/ticket/31037
     */
    if (!current_user_can('upload_files')) {
        echo wp_json_encode(array('success' => false, 'data' => array('message' => __('You do not have permission to upload files.'), 'filename' => $_FILES['async-upload']['name'])));
        wp_die();
    }
    if (isset($_REQUEST['post_id'])) {
        $post_id = $_REQUEST['post_id'];
        if (!current_user_can('edit_post', $post_id)) {
            echo wp_json_encode(array('success' => false, 'data' => array('message' => __("You don't have permission to attach files to this post."), 'filename' => $_FILES['async-upload']['name'])));
            wp_die();
        }
    } else {
        $post_id = null;
    }
    $post_data = isset($_REQUEST['post_data']) ? $_REQUEST['post_data'] : array();
    // If the context is custom header or background, make sure the uploaded file is an image.
    if (isset($post_data['context']) && in_array($post_data['context'], array('custom-header', 'custom-background'))) {
        $wp_filetype = wp_check_filetype_and_ext($_FILES['async-upload']['tmp_name'], $_FILES['async-upload']['name']);
        if (!wp_match_mime_types('image', $wp_filetype['type'])) {
            echo wp_json_encode(array('success' => false, 'data' => array('message' => __('The uploaded file is not a valid image. Please try again.'), 'filename' => $_FILES['async-upload']['name'])));
            wp_die();
        }
    }
    $attachment_id = media_handle_upload('async-upload', $post_id, $post_data);
    if (is_wp_error($attachment_id)) {
        echo wp_json_encode(array('success' => false, 'data' => array('message' => $attachment_id->get_error_message(), 'filename' => $_FILES['async-upload']['name'])));
        wp_die();
    }
    if (isset($post_data['context']) && isset($post_data['theme'])) {
        if ('custom-background' === $post_data['context']) {
            update_post_meta($attachment_id, '_wp_attachment_is_custom_background', $post_data['theme']);
        }
        if ('custom-header' === $post_data['context']) {
            update_post_meta($attachment_id, '_wp_attachment_is_custom_header', $post_data['theme']);
        }
    }
    if (!($attachment = wp_prepare_attachment_for_js($attachment_id))) {
        wp_die();
    }
    echo wp_json_encode(array('success' => true, 'data' => $attachment));
    wp_die();
}
예제 #28
0
function ewf_import_uploadFile()
{
    // check_admin_referer prints fail page and dies
    if (!empty($_POST) && !empty($_FILES['ewf_import_file']) && check_admin_referer('ewf_import', 'ewf_import_nonce')) {
        $uploaded_file = $_FILES['ewf_import_file'];
        $uploaded_file_type = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name']);
        if ('txt' != $uploaded_file_type['ext'] && !wp_match_mime_types('txt', $uploaded_file_type['type'])) {
            echo '<div>' . '<strong>' . 'Error: ' . '</strong>' . 'You must upload a <b>.txt</b> file.' . '</div>';
            return false;
        }
        $uploaded_file_data = wp_handle_upload($uploaded_file, array('test_form' => false));
        if (isset($uploaded_file_data['error'])) {
            echo '<div>' . '<strong>' . 'Error: ' . '</strong>' . $uploaded_file_data['error'] . '</div>';
            return false;
        }
        // echo '<pre>';
        // print_r( $uploaded_file_data );
        // echo '</pre>';
        // }else{
        // echo '<div>'.'<strong>'.'Error: '.'</strong>'.'Something went wrong!'.'</div>';
    }
}
예제 #29
0
/**
 * Retrieve the icon for a MIME type.
 *
 * @since 2.1.0
 *
 * @param string $mime MIME type
 * @return string|bool
 */
function wp_mime_type_icon($mime = 0)
{
    if (!is_numeric($mime)) {
        $icon = wp_cache_get("mime_type_icon_{$mime}");
    }
    if (empty($icon)) {
        $post_id = 0;
        $post_mimes = array();
        if (is_numeric($mime)) {
            $mime = (int) $mime;
            if ($post =& get_post($mime)) {
                $post_id = (int) $post->ID;
                $ext = preg_replace('/^.+?\\.([^.]+)$/', '$1', $post->guid);
                if (!empty($ext)) {
                    $post_mimes[] = $ext;
                    if ($ext_type = wp_ext2type($ext)) {
                        $post_mimes[] = $ext_type;
                    }
                }
                $mime = $post->post_mime_type;
            } else {
                $mime = 0;
            }
        } else {
            $post_mimes[] = $mime;
        }
        $icon_files = wp_cache_get('icon_files');
        if (!is_array($icon_files)) {
            $icon_dir = apply_filters('icon_dir', ABSPATH . WPINC . '/images/crystal');
            $icon_dir_uri = apply_filters('icon_dir_uri', includes_url('images/crystal'));
            $dirs = apply_filters('icon_dirs', array($icon_dir => $icon_dir_uri));
            $icon_files = array();
            while ($dirs) {
                $dir = array_shift($keys = array_keys($dirs));
                $uri = array_shift($dirs);
                if ($dh = opendir($dir)) {
                    while (false !== ($file = readdir($dh))) {
                        $file = basename($file);
                        if (substr($file, 0, 1) == '.') {
                            continue;
                        }
                        if (!in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg'))) {
                            if (is_dir("{$dir}/{$file}")) {
                                $dirs["{$dir}/{$file}"] = "{$uri}/{$file}";
                            }
                            continue;
                        }
                        $icon_files["{$dir}/{$file}"] = "{$uri}/{$file}";
                    }
                    closedir($dh);
                }
            }
            wp_cache_set('icon_files', $icon_files, 600);
        }
        // Icon basename - extension = MIME wildcard
        foreach ($icon_files as $file => $uri) {
            $types[preg_replace('/^([^.]*).*$/', '$1', basename($file))] =& $icon_files[$file];
        }
        if (!empty($mime)) {
            $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
            $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
            $post_mimes[] = str_replace('/', '_', $mime);
        }
        $matches = wp_match_mime_types(array_keys($types), $post_mimes);
        $matches['default'] = array('default');
        foreach ($matches as $match => $wilds) {
            if (isset($types[$wilds[0]])) {
                $icon = $types[$wilds[0]];
                if (!is_numeric($mime)) {
                    wp_cache_set("mime_type_icon_{$mime}", $icon);
                }
                break;
            }
        }
    }
    return apply_filters('wp_mime_type_icon', $icon, $mime, $post_id);
    // Last arg is 0 if function pass mime type.
}
예제 #30
0
 /**
  * Handle an Image upload for the background image.
  *
  * @since 3.0.0
  */
 public function handle_upload()
 {
     if (empty($_FILES)) {
         return;
     }
     check_admin_referer('custom-background-upload', '_wpnonce-custom-background-upload');
     $overrides = array('test_form' => false);
     $uploaded_file = $_FILES['import'];
     $wp_filetype = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name']);
     if (!wp_match_mime_types('image', $wp_filetype['type'])) {
         wp_die(__('The uploaded file is not a valid image. Please try again.'));
     }
     $file = wp_handle_upload($uploaded_file, $overrides);
     if (isset($file['error'])) {
         wp_die($file['error']);
     }
     $url = $file['url'];
     $type = $file['type'];
     $file = $file['file'];
     $filename = basename($file);
     // Construct the object array
     $object = array('post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'custom-background');
     // Save the data
     $id = wp_insert_attachment($object, $file);
     // Add the meta-data
     wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file));
     update_post_meta($id, '_wp_attachment_is_custom_background', get_option('stylesheet'));
     set_theme_mod('background_image', esc_url_raw($url));
     $thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
     set_theme_mod('background_image_thumb', esc_url_raw($thumbnail[0]));
     /** This action is documented in wp-admin/custom-header.php */
     do_action('wp_create_file_in_uploads', $file, $id);
     // For replication
     $this->updated = true;
 }