Beispiel #1
0
 function ajax($action)
 {
     define('DOING_AJAX', true);
     if (empty($action)) {
         return;
     }
     ini_set('html_errors', 0);
     if (AJAXFLOW_NONCE) {
         if (!wp_verify_nonce($action, $_REQUEST['_wpnonce'])) {
             wp_die('Security check didn´t pass, please check _wpnonce!', AJAXFLOW_TAG);
         }
     }
     $shortinit = apply_filters(AJAXFLOW_TAG . '_shortinit', false, $action);
     if ($shortinit || isset($_REQUEST['shortinit']) && $_REQUEST['shortinit']) {
         define('SHORTINIT', true);
     }
     require_once ABSPATH . '/wp-load.php';
     header('Content-Type: text/html');
     send_nosniff_header();
     header('Cache-Control: no-cache');
     header('Pragma: no-cache');
     do_action(AJAXFLOW_TAG . '_shortinit_load');
     if (is_user_logged_in()) {
         do_action(AJAXFLOW_TAG . '_' . $action);
     } else {
         do_action(AJAXFLOW_TAG . '_nopriv_' . $action);
     }
     wp_die('Your ' . AJAXFLOW_TAG . ' call does not exists or exit is missing in action!', AJAXFLOW_TAG);
     exit;
 }
 /**
  * Update Headers for better security
  */
 public static function send_headers($headers)
 {
     send_nosniff_header();
     $headers['X-Frame-Options'] = 'SAMEORIGIN';
     // http://engineeredweb.com/blog/2013/secure-site-clickjacking-x-frame-options/
     $headers['X-XSS-Protection'] = '1; mode=block';
     // https://kb.sucuri.net/warnings/hardening/headers-x-xss-protection
     return $headers;
 }
Beispiel #3
0
 /**
  * Send headers for WC Ajax Requests
  * @since 2.5.0
  */
 private static function wc_ajax_headers()
 {
     send_origin_headers();
     @header('Content-Type: text/html; charset=' . get_option('blog_charset'));
     @header('X-Robots-Tag: noindex');
     send_nosniff_header();
     nocache_headers();
     status_header(200);
 }
function json_template_redirect()
{
    // If this is not a request for json then bail
    if (is_json_request()) {
        // Set the appropriate header
        header('Content-Type: application/json; charset=utf-8');
        // Help prevent MIME-type confusion attacks in IE8+
        send_nosniff_header();
    }
    return;
}
 function essb_proccess_share_this_image()
 {
     $current_action = isset($_REQUEST['essb-image-share']) ? $_REQUEST['essb-image-share'] : '';
     if ($current_action == "yes") {
         define('DOING_AJAX', true);
         send_nosniff_header();
         header('Pragma: no-cache');
         include_once ESSB3_PLUGIN_ROOT . 'lib/modules/social-image-share/essb-social-image-share-selected.php';
         exit;
     }
 }
 /**
  * Redirect to a JSON representation of a post if the JSON query var is set.
  *
  * In order to power the SPA, a JSON representation of a post is needed. This function hooks into "template_redirect"
  * and will use a JSON template to render a post when needed. Appending "?cspa-json=1" to a post or a post format
  * archive will render the JSON template.
  *
  * @since  1.0.
  *
  * @return void
  */
 function zt_json_template_redirect()
 {
     global $wp_query;
     // If this is not a request for json then bail
     if (!isset($wp_query->query_vars['zt-json']) || '1' !== $wp_query->query_vars['zt-json']) {
         return;
     }
     // Set the appropriate header
     header('Content-Type: application/json; charset=utf-8');
     // Help prevent MIME-type confusion attacks in IE8+
     send_nosniff_header();
     // Render the template and stop execution
     get_template_part('json', 'posts');
     exit;
 }
Beispiel #7
0
/**
 * Hooked to the 'bbp_template_redirect' action, this is bbPress's custom
 * theme-side ajax handler.
 *
 * @since 2.3.0 bbPress (r4543)
 *
 * @return If not a bbPress ajax request
 */
function bbp_do_ajax()
{
    // Bail if not an ajax request
    if (!bbp_is_ajax()) {
        return;
    }
    // Set WordPress core ajax constant
    define('DOING_AJAX', true);
    // Set the header content type
    @header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
    // Disable content sniffing in browsers that support it
    send_nosniff_header();
    // Perform custom bbPress ajax
    do_action('bbp_ajax_' . $_REQUEST['action']);
    // All done
    die('0');
}
 /**
  * Set BSR AJAX constant and headers.
  * @access public
  */
 public function define_ajax()
 {
     if (isset($_GET['bsr-ajax']) && !empty($_GET['bsr-ajax'])) {
         // Define the WordPress "DOING_AJAX" constant.
         if (!defined('DOING_AJAX')) {
             define('DOING_AJAX', true);
         }
         // Prevent notices from breaking AJAX functionality.
         if (!WP_DEBUG || WP_DEBUG && !WP_DEBUG_DISPLAY) {
             @ini_set('display_errors', 0);
         }
         // Send the headers.
         send_origin_headers();
         @header('Content-Type: text/html; charset=' . get_option('blog_charset'));
         @header('X-Robots-Tag: noindex');
         send_nosniff_header();
         nocache_headers();
     }
 }
Beispiel #9
0
 public function endpoint()
 {
     global $wp_query;
     if (!isset($wp_query->query_vars[$this->endpoint])) {
         return;
     }
     do_action('cornerstone_before_endpoint');
     send_origin_headers();
     if (empty($_REQUEST['action'])) {
         die('0');
     }
     @header('X-Robots-Tag: noindex');
     @header('Cornerstone: true');
     send_nosniff_header();
     nocache_headers();
     $action = is_user_logged_in() ? 'cornerstone_endpoint_' : 'cornerstone_endpoint_nopriv_';
     do_action($action . $_REQUEST['action']);
     die('0');
 }
Beispiel #10
0
 /**
  * Handles AJAX response
  *
  * @since 6.3
  * @access public
  */
 public function template_redirect()
 {
     $theme_my_login = Theme_My_Login::get_object();
     if (Theme_My_Login::is_tml_page() && isset($_GET['ajax'])) {
         define('DOING_AJAX', true);
         $instance =& $theme_my_login->get_instance();
         $instance->set_option('default_action', !empty($theme_my_login->request_action) ? $theme_my_login->request_action : 'login');
         $instance->set_option('gravatar_size', 75);
         $instance->set_option('before_title', '<h2>');
         $instance->set_option('after_title', '</h2>');
         $data = $instance->display();
         send_origin_headers();
         @header('Content-Type: text/html; charset=' . get_option('blog_charset'));
         @header('X-Robots-Tag: noindex');
         send_nosniff_header();
         nocache_headers();
         $x = new WP_Ajax_Response(array('what' => 'login', 'action' => $theme_my_login->request_action, 'data' => $theme_my_login->errors->get_error_code() ? $theme_my_login->errors : $data, 'supplemental' => array('html' => $data, 'success' => is_user_logged_in())));
         $x->send();
         exit;
     }
 }
Beispiel #11
0
 /**
  * Set WC AJAX constant and headers.
  */
 public static function define_ajax()
 {
     if (!empty($_GET['wc-ajax'])) {
         if (!defined('DOING_AJAX')) {
             define('DOING_AJAX', true);
         }
         if (!defined('WC_DOING_AJAX')) {
             define('WC_DOING_AJAX', true);
         }
         // Turn off display_errors during AJAX events to prevent malformed JSON
         if (!WP_DEBUG || WP_DEBUG && !WP_DEBUG_DISPLAY) {
             @ini_set('display_errors', 0);
         }
         // Send headers like admin-ajax.php
         send_origin_headers();
         @header('Content-Type: text/html; charset=' . get_option('blog_charset'));
         @header('X-Robots-Tag: noindex');
         send_nosniff_header();
         nocache_headers();
     }
 }
Beispiel #12
0
 public static function upload()
 {
     GFCommon::log_debug('GFAsyncUpload::upload(): Starting.');
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         status_header(404);
         die;
     }
     header('Content-Type: text/html; charset=' . get_option('blog_charset'));
     send_nosniff_header();
     nocache_headers();
     status_header(200);
     // If the file is bigger than the server can accept then the form_id might not arrive.
     // This might happen if the file is bigger than the max post size ini setting.
     // Validation in the browser reduces the risk of this happening.
     if (!isset($_REQUEST['form_id'])) {
         GFCommon::log_debug('GFAsyncUpload::upload(): File upload aborted because the form_id was not found. The file may have been bigger than the max post size ini setting.');
         self::die_error(500, __('Failed to upload file.', 'gravityforms'));
     }
     $form_id = absint($_REQUEST['form_id']);
     $form_unique_id = rgpost('gform_unique_id');
     $form = GFAPI::get_form($form_id);
     if (empty($form) || !$form['is_active']) {
         die;
     }
     if (rgar($form, 'requireLogin')) {
         if (!is_user_logged_in()) {
             die;
         }
         check_admin_referer('gform_file_upload_' . $form_id, '_gform_file_upload_nonce_' . $form_id);
     }
     if (!ctype_alnum($form_unique_id)) {
         die;
     }
     $target_dir = GFFormsModel::get_upload_path($form_id) . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
     if (!is_dir($target_dir)) {
         if (!wp_mkdir_p($target_dir)) {
             GFCommon::log_debug("GFAsyncUpload::upload(): Couldn't create the tmp folder: " . $target_dir);
             self::die_error(500, __('Failed to upload file.', 'gravityforms'));
         }
     }
     $time = current_time('mysql');
     $y = substr($time, 0, 4);
     $m = substr($time, 5, 2);
     //adding index.html files to all subfolders
     if (!file_exists(GFFormsModel::get_upload_root() . '/index.html')) {
         GFForms::add_security_files();
     } else {
         if (!file_exists(GFFormsModel::get_upload_path($form_id) . '/index.html')) {
             GFCommon::recursive_add_index_file(GFFormsModel::get_upload_path($form_id));
         } else {
             if (!file_exists(GFFormsModel::get_upload_path($form_id) . "/{$y}/index.html")) {
                 GFCommon::recursive_add_index_file(GFFormsModel::get_upload_path($form_id) . "/{$y}");
             } else {
                 GFCommon::recursive_add_index_file(GFFormsModel::get_upload_path($form_id) . "/{$y}/{$m}");
             }
         }
     }
     if (!file_exists($target_dir . '/index.html')) {
         GFCommon::recursive_add_index_file($target_dir);
     }
     $uploaded_filename = $_FILES['file']['name'];
     $file_name = isset($_REQUEST['name']) ? $_REQUEST['name'] : '';
     $field_id = rgpost('field_id');
     $field_id = absint($field_id);
     $field = GFFormsModel::get_field($form, $field_id);
     if (empty($field) || GFFormsModel::get_input_type($field) != 'fileupload') {
         die;
     }
     $file_name = sanitize_file_name($file_name);
     $uploaded_filename = sanitize_file_name($uploaded_filename);
     $allowed_extensions = !empty($field->allowedExtensions) ? GFCommon::clean_extensions(explode(',', strtolower($field->allowedExtensions))) : array();
     $max_upload_size_in_bytes = $field->maxFileSize > 0 ? $field->maxFileSize * 1048576 : wp_max_upload_size();
     $max_upload_size_in_mb = $max_upload_size_in_bytes / 1048576;
     if ($_FILES['file']['size'] > 0 && $_FILES['file']['size'] > $max_upload_size_in_bytes) {
         self::die_error(104, sprintf(__('File exceeds size limit. Maximum file size: %dMB', 'gravityforms'), $max_upload_size_in_mb));
     }
     if (GFCommon::file_name_has_disallowed_extension($file_name) || GFCommon::file_name_has_disallowed_extension($uploaded_filename)) {
         GFCommon::log_debug("GFAsyncUpload::upload(): Illegal file extension: {$file_name}");
         self::die_error(104, __('The uploaded file type is not allowed.', 'gravityforms'));
     }
     if (!empty($allowed_extensions)) {
         if (!GFCommon::match_file_extension($file_name, $allowed_extensions) || !GFCommon::match_file_extension($uploaded_filename, $allowed_extensions)) {
             GFCommon::log_debug("GFAsyncUpload::upload(): The uploaded file type is not allowed: {$file_name}");
             self::die_error(104, sprintf(__('The uploaded file type is not allowed. Must be one of the following: %s', 'gravityforms'), strtolower($field['allowedExtensions'])));
         }
     }
     $whitelisting_disabled = apply_filters('gform_file_upload_whitelisting_disabled', false);
     if (empty($allowed_extensions) && !$whitelisting_disabled) {
         // Whitelist the file type
         $valid_uploaded_filename = GFCommon::check_type_and_ext($_FILES['file'], $uploaded_filename);
         if (is_wp_error($valid_uploaded_filename)) {
             self::die_error($valid_uploaded_filename->get_error_code(), $valid_uploaded_filename->get_error_message());
         }
         $valid_file_name = GFCommon::check_type_and_ext($_FILES['file'], $file_name);
         if (is_wp_error($valid_uploaded_filename)) {
             self::die_error($valid_file_name->get_error_code(), $valid_file_name->get_error_message());
         }
     }
     $tmp_file_name = $form_unique_id . '_input_' . $field_id . '_' . $file_name;
     $tmp_file_name = sanitize_file_name($tmp_file_name);
     $file_path = $target_dir . $tmp_file_name;
     $cleanup_target_dir = true;
     // Remove old files
     $max_file_age = 5 * 3600;
     // Temp file age in seconds
     // Remove old temp files
     if ($cleanup_target_dir) {
         if (is_dir($target_dir) && ($dir = opendir($target_dir))) {
             while (($file = readdir($dir)) !== false) {
                 $tmp_file_path = $target_dir . $file;
                 // Remove temp file if it is older than the max age and is not the current file
                 if (preg_match('/\\.part$/', $file) && filemtime($tmp_file_path) < time() - $max_file_age && $tmp_file_path != "{$file_path}.part") {
                     GFCommon::log_debug('GFAsyncUpload::upload(): Deleting file: ' . $tmp_file_path);
                     @unlink($tmp_file_path);
                 }
             }
             closedir($dir);
         } else {
             GFCommon::log_debug('GFAsyncUpload::upload(): Failed to open temp directory: ' . $target_dir);
             self::die_error(100, __('Failed to open temp directory.', 'gravityforms'));
         }
     }
     if (isset($_SERVER['HTTP_CONTENT_TYPE'])) {
         $contentType = $_SERVER['HTTP_CONTENT_TYPE'];
     }
     if (isset($_SERVER['CONTENT_TYPE'])) {
         $contentType = $_SERVER['CONTENT_TYPE'];
     }
     $chunk = isset($_REQUEST['chunk']) ? intval($_REQUEST['chunk']) : 0;
     $chunks = isset($_REQUEST['chunks']) ? intval($_REQUEST['chunks']) : 0;
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, 'multipart') !== false) {
         if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
             // Open temp file
             $out = @fopen("{$file_path}.part", $chunk == 0 ? 'wb' : 'ab');
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = @fopen($_FILES['file']['tmp_name'], 'rb');
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     self::die_error(101, __('Failed to open input stream.', 'gravityforms'));
                 }
                 @fclose($in);
                 @fclose($out);
                 @unlink($_FILES['file']['tmp_name']);
             } else {
                 self::die_error(102, __('Failed to open output stream.', 'gravityforms'));
             }
         } else {
             self::die_error(103, __('Failed to move uploaded file.', 'gravityforms'));
         }
     } else {
         // Open temp file
         $out = @fopen("{$file_path}.part", $chunk == 0 ? 'wb' : 'ab');
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = @fopen('php://input', 'rb');
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 self::die_error(101, __('Failed to open input stream.', 'gravityforms'));
             }
             @fclose($in);
             @fclose($out);
         } else {
             self::die_error(102, __('Failed to open output stream.', 'gravityforms'));
         }
     }
     // Check if file has been uploaded
     if (!$chunks || $chunk == $chunks - 1) {
         // Strip the temp .part suffix off
         rename("{$file_path}.part", $file_path);
     }
     if (file_exists($file_path)) {
         GFFormsModel::set_permissions($file_path);
     } else {
         self::die_error(105, __('Upload unsuccessful', 'gravityforms') . ' ' . $uploaded_filename);
     }
     $output = array('status' => 'ok', 'data' => array('temp_filename' => $tmp_file_name, 'uploaded_filename' => str_replace("\\'", "'", urldecode($uploaded_filename))));
     $output = json_encode($output);
     GFCommon::log_debug(sprintf('GFAsyncUpload::upload(): File upload complete. temp_filename: %s  uploaded_filename: %s ', $tmp_file_name, $uploaded_filename));
     gf_do_action('gform_post_multifile_upload', $form['id'], $form, $field, $uploaded_filename, $tmp_file_name, $file_path);
     die($output);
 }
 /**
  * Sets various HTTP headers related to Content-Type and browser caching.
  *
  * Most of this class method is derived from {@link WP::send_headers()}.
  *
  * @since 1.9.0
  */
 protected function http_headers()
 {
     // Set up some additional headers if not on a directory page
     // this is done b/c BP uses pseudo-pages.
     if (!bp_is_directory()) {
         global $wp_query;
         $wp_query->is_404 = false;
         status_header(200);
     }
     // Set content-type.
     @header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true);
     send_nosniff_header();
     // Cache-related variables.
     $last_modified = mysql2date('D, d M Y H:i:s O', bp_activity_get_last_updated(), false);
     $modified_timestamp = strtotime($last_modified);
     $etag = md5($last_modified);
     // Set cache-related headers.
     @header('Last-Modified: ' . $last_modified);
     @header('Pragma: no-cache');
     @header('ETag: ' . '"' . $etag . '"');
     // First commit of BuddyPress! (Easter egg).
     @header('Expires: Tue, 25 Mar 2008 17:13:55 GMT');
     // Get ETag from supported user agents.
     if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
         $client_etag = wp_unslash($_SERVER['HTTP_IF_NONE_MATCH']);
         // Remove quotes from ETag.
         $client_etag = trim($client_etag, '"');
         // Strip suffixes from ETag if they exist (eg. "-gzip").
         $etag_suffix_pos = strpos($client_etag, '-');
         if (!empty($etag_suffix_pos)) {
             $client_etag = substr($client_etag, 0, $etag_suffix_pos);
         }
         // No ETag found.
     } else {
         $client_etag = false;
     }
     // Get client last modified timestamp from supported user agents.
     $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
     $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
     // Set 304 status if feed hasn't been updated since last fetch.
     if ($client_last_modified && $client_etag ? $client_modified_timestamp >= $modified_timestamp && $client_etag == $etag : $client_modified_timestamp >= $modified_timestamp || $client_etag == $etag) {
         $status = 304;
     } else {
         $status = false;
     }
     // If feed hasn't changed as reported by the user agent, set 304 status header.
     if (!empty($status)) {
         status_header($status);
         // Cached response, so stop now!
         if ($status == 304) {
             exit;
         }
     }
 }
 /**
  * Generate and output ajax response for related posts API call.
  * NOTE: Calls exit() to end all further processing after payload has been outputed.
  *
  * @param array $excludes array of post_ids to exclude
  * @uses send_nosniff_header, self::get_for_post_id, get_the_ID
  * @return null
  */
 protected function _action_frontend_init_ajax(array $excludes)
 {
     define('DOING_AJAX', true);
     header('Content-type: application/json; charset=utf-8');
     // JSON can only be UTF-8
     send_nosniff_header();
     $related_posts = $this->get_for_post_id(get_the_ID(), array('exclude_post_ids' => $excludes));
     $options = $this->get_options();
     $response = array('version' => self::VERSION, 'show_thumbnails' => (bool) $options['show_thumbnails'], 'items' => array());
     if (count($related_posts) == $options['size']) {
         $response['items'] = $related_posts;
     }
     echo json_encode($response);
     exit;
 }
Beispiel #15
0
 /**
  * Our own Ajax response, avoiding calling admin-ajax
  */
 function ajax_response()
 {
     // Only proceed if the url query has a key of "Infinity"
     if (!self::got_infinity()) {
         return false;
     }
     // This should already be defined below, but make sure.
     if (!defined('DOING_AJAX')) {
         define('DOING_AJAX', true);
     }
     @header('Content-Type: text/html; charset=' . get_option('blog_charset'));
     send_nosniff_header();
     /**
      * Fires at the end of the Infinite Scroll Ajax response.
      *
      * @module infinite-scroll
      *
      * @since 2.0.0
      */
     do_action('custom_ajax_infinite_scroll');
     die('0');
 }
Beispiel #16
0
function gmedia_import_handler()
{
    global $wpdb, $gmCore, $gmDB;
    ini_set('max_execution_time', 600);
    // HTTP headers for no cache etc
    send_nosniff_header();
    //send_origin_headers();
    nocache_headers();
    check_admin_referer('GmediaImport');
    if (!current_user_can('gmedia_import')) {
        wp_die(__('You do not have permission to upload files.'));
    }
    // 10 minutes execution time
    @set_time_limit(10 * 60);
    // fake upload time
    usleep(10);
    $import = $gmCore->_post('import');
    $terms = $gmCore->_post('terms', array());
    if (ob_get_level() == 0) {
        ob_start();
    }
    echo str_pad(' ', 4096) . PHP_EOL;
    wp_ob_end_flush_all();
    flush();
    ?>
    <html>
    <style type="text/css">
        * { margin:0; padding:0; }
        pre { display:block; }
        p { padding:10px 0; font-size:14px; }
        .ok { color:darkgreen; }
        .ko { color:darkred; }
    </style>
    <body>
    <?php 
    if ('import-folder' == $import || isset($_POST['import-folder'])) {
        $path = $gmCore->_post('path');
        echo '<h4 style="margin: 0 0 10px">' . __('Import Server Folder') . " `{$path}`:</h4>" . PHP_EOL;
        if ($path) {
            $path = trim(urldecode($path), '/');
            if (!empty($path)) {
                $fullpath = ABSPATH . trailingslashit($path);
                $files = glob($fullpath . '?*.?*', GLOB_NOSORT);
                if (!empty($files)) {
                    $allowed_ext = get_allowed_mime_types();
                    $allowed_ext = array_keys($allowed_ext);
                    $allowed_ext = implode('|', $allowed_ext);
                    $allowed_ext = explode('|', $allowed_ext);
                    if (GMEDIA_UPLOAD_FOLDER == basename(dirname(dirname($path))) || GMEDIA_UPLOAD_FOLDER == basename(dirname($path))) {
                        global $wpdb;
                        $gmedias = $wpdb->get_col("SELECT gmuid FROM {$wpdb->prefix}gmedia");
                        foreach ($files as $i => $filepath) {
                            $gmuid = basename($filepath);
                            if (in_array($gmuid, $gmedias)) {
                                $fileinfo = $gmCore->fileinfo($gmuid, false);
                                if (!('image' == $fileinfo['dirname'] && !is_file($fileinfo['filepath']))) {
                                    unset($files[$i]);
                                }
                            }
                        }
                        $move = false;
                        $exists = false;
                    } else {
                        $move = $gmCore->_post('delete_source');
                        $exists = $gmCore->_post('skip_exists', 0);
                    }
                    foreach ($files as $i => $filepath) {
                        $ext = pathinfo($filepath, PATHINFO_EXTENSION);
                        if (!in_array(strtolower($ext), $allowed_ext)) {
                            unset($files[$i]);
                        }
                    }
                    $gmCore->gmedia_import_files($files, $terms, $move, $exists);
                } else {
                    echo sprintf(__('Folder `%s` is empty', 'grand-media'), $path) . PHP_EOL;
                }
            } else {
                echo __('No folder chosen', 'grand-media') . PHP_EOL;
            }
        }
    } elseif ('import-flagallery' == $import || isset($_POST['import-flagallery'])) {
        echo '<h4 style="margin: 0 0 10px">' . __('Import from Flagallery plugin') . ":</h4>" . PHP_EOL;
        $gallery = $gmCore->_post('gallery');
        if (!empty($gallery)) {
            $album = !isset($terms['gmedia_album']) || empty($terms['gmedia_album']) ? false : true;
            foreach ($gallery as $gid) {
                $flag_gallery = $wpdb->get_row($wpdb->prepare("SELECT gid, path, title, galdesc FROM {$wpdb->prefix}flag_gallery WHERE gid = %d", $gid), ARRAY_A);
                if (empty($flag_gallery)) {
                    continue;
                }
                if (!$album) {
                    $terms['gmedia_album'] = $flag_gallery['title'];
                    if ($gmCore->is_digit($terms['gmedia_album'])) {
                        $terms['gmedia_album'] = 'a' . $terms['gmedia_album'];
                    }
                    if (!$gmDB->term_exists($terms['gmedia_album'], 'gmedia_album')) {
                        $term_id = $gmDB->insert_term($terms['gmedia_album'], 'gmedia_album', array('description' => htmlspecialchars_decode(stripslashes($flag_gallery['galdesc']))));
                    }
                }
                $path = ABSPATH . trailingslashit($flag_gallery['path']);
                echo '<h5 style="margin: 10px 0 5px">' . sprintf(__('Import `%s` gallery', 'grand-media'), $flag_gallery['title']) . ":</h5>" . PHP_EOL;
                $flag_pictures = $wpdb->get_results($wpdb->prepare("SELECT CONCAT('%s', filename) AS file, description, alttext AS title, link FROM {$wpdb->prefix}flag_pictures WHERE galleryid = %d", $path, $flag_gallery['gid']), ARRAY_A);
                if (empty($flag_pictures)) {
                    echo '<pre>' . __('gallery contains 0 images', 'grand-media') . '</pre>';
                    continue;
                }
                $exists = $gmCore->_post('skip_exists', 0);
                //echo '<pre>'.print_r($flag_pictures, true).'</pre>';
                $gmCore->gmedia_import_files($flag_pictures, $terms, false, $exists);
            }
        } else {
            echo __('No gallery chosen', 'grand-media') . PHP_EOL;
        }
    } elseif ('import-nextgen' == $import || isset($_POST['import-nextgen'])) {
        echo '<h4 style="margin: 0 0 10px">' . __('Import from NextGen plugin') . ":</h4>" . PHP_EOL;
        $gallery = $gmCore->_post('gallery');
        if (!empty($gallery)) {
            $album = !isset($terms['gmedia_album']) || empty($terms['gmedia_album']) ? false : true;
            foreach ($gallery as $gid) {
                $ngg_gallery = $wpdb->get_row($wpdb->prepare("SELECT gid, path, title, galdesc FROM {$wpdb->prefix}ngg_gallery WHERE gid = %d", $gid), ARRAY_A);
                if (empty($ngg_gallery)) {
                    continue;
                }
                if (!$album) {
                    $terms['gmedia_album'] = $ngg_gallery['title'];
                    if ($gmCore->is_digit($terms['gmedia_album'])) {
                        $terms['gmedia_album'] = 'a' . $ngg_gallery['title'];
                    }
                    if (!$gmDB->term_exists($terms['gmedia_album'], 'gmedia_album')) {
                        $term_id = $gmDB->insert_term($terms['gmedia_album'], 'gmedia_album', array('description' => htmlspecialchars_decode(stripslashes($ngg_gallery['galdesc']))));
                    }
                }
                $path = ABSPATH . trailingslashit($ngg_gallery['path']);
                echo '<h5 style="margin: 10px 0 5px">' . sprintf(__('Import `%s` gallery', 'grand-media'), $ngg_gallery['title']) . ":</h5>" . PHP_EOL;
                $ngg_pictures = $wpdb->get_results($wpdb->prepare("SELECT CONCAT('%s', filename) AS file, description, alttext AS title FROM {$wpdb->prefix}ngg_pictures WHERE galleryid = %d", $path, $ngg_gallery['gid']), ARRAY_A);
                if (empty($ngg_pictures)) {
                    echo '<pre>' . __('gallery contains 0 images', 'grand-media') . '</pre>';
                    continue;
                }
                $exists = $gmCore->_post('skip_exists', 0);
                $gmCore->gmedia_import_files($ngg_pictures, $terms, false, $exists);
            }
        } else {
            echo __('No gallery chosen', 'grand-media') . PHP_EOL;
        }
    } elseif ('import-wpmedia' == $import || isset($_POST['import-wpmedia'])) {
        echo '<h4 style="margin: 0 0 10px">' . __('Import from WP Media Library') . ":</h4>" . PHP_EOL;
        $wpMediaLib = $gmDB->get_wp_media_lib(array('filter' => 'selected', 'selected' => $gmCore->_post('selected')));
        if (!empty($wpMediaLib)) {
            $wp_media = array();
            foreach ($wpMediaLib as $item) {
                $wp_media[] = array('file' => get_attached_file($item->ID), 'title' => $item->post_title, 'description' => $item->post_content);
            }
            $exists = $gmCore->_post('skip_exists', 0);
            //echo '<pre>' . print_r($wp_media, true) . '</pre>';
            $gmCore->gmedia_import_files($wp_media, $terms, false, $exists);
        } else {
            echo __('No items chosen', 'grand-media') . PHP_EOL;
        }
    }
    ?>
    </body>
    </html>
    <?php 
    wp_ob_end_flush_all();
    die;
}
 /**
  * Send a HTTP header to disable content type sniffing in browsers which
  * support it. This prevents browsers from attempting to determine a mime
  * type automatically, and forces rendering in the mime type provided by
  * the server.
  *
  * @return void
  */
 public function enableNoSniff()
 {
     if (!headers_sent()) {
         send_nosniff_header();
     }
 }
Beispiel #18
0
/**
 * Tap into the filter to use data from a readme.txt file
 *
 * @since  2.4
 * @see  EDD_Software_Licensing::get_latest_version_remote()
 * @param  array  $original_response License response array
 * @param  WP_Post $download          Post object of the Download item
 * @return array                    Modified array, if readme exists. Otherwise, original array is returned.
 */
function edd_sl_readme_modify_license_response($response = array(), $download = NULL)
{
    if (is_admin() || defined('DOING_AJAX')) {
        // Prevent errors and send headers
        ini_set('display_errors', 0);
        ini_set('log_errors', 1);
        error_reporting(0);
        define('DOING_AJAX', true);
        @header('Content-type: text/plain');
        @send_nosniff_header();
    }
    // Get the URL to use in the WP.org validator
    $readme_url = get_post_meta($download->ID, '_edd_readme_location', true);
    // If the URL doesn't exist, get outta here.
    if (empty($readme_url)) {
        return $response;
    }
    // Fetch the cached/fresh readme data
    $readme = _edd_sl_get_readme_data($readme_url, $download->ID);
    // The readme didn't exist or process. Return existing response.
    if (empty($readme)) {
        return $response;
    }
    // Modify the homepage linked to in the Update Notice
    $response['homepage'] = edd_sl_readme_get_download_homepage($download->ID);
    // Set the slug
    $response['new_version'] = edd_software_licensing()->get_latest_version($download->ID);
    // The original response sections
    $response['sections'] = maybe_unserialize(@$response['sections']);
    // Get the override readme sections settings
    if ($readme_sections = get_post_meta($download->ID, '_edd_readme_sections', true)) {
        // We loop through the settings sections and make overwrite the
        // existing sections with the custom readme.txt sections.
        foreach ((array) $readme_sections as $section) {
            $response['sections'][$section] = $readme['sections']["{$section}"];
        }
    }
    if (!empty($readme['tested_up_to'])) {
        $response['tested'] = $readme['tested_up_to'];
    }
    // Reserialize it
    $response['sections'] = serialize($response['sections']);
    // Get the override readme meta settings
    if ($readme_meta = get_post_meta($download->ID, '_edd_readme_meta', true)) {
        // We loop through the settings sections and make overwrite the
        // existing sections with the custom readme.txt sections.
        foreach ((array) $readme_meta as $meta) {
            $response[$meta] = $readme["{$meta}"];
        }
    }
    if (get_post_meta($download->ID, '_edd_readme_plugin_added', true)) {
        $response['added'] = date('Y-m-d', strtotime($download->post_date_gmt));
    }
    if (get_post_meta($download->ID, '_edd_readme_plugin_last_updated', true)) {
        $response['last_updated'] = apply_filters('edd_sl_readme_last_updated', human_time_diff(strtotime($download->post_modified_gmt), current_time('timestamp', 1)) . ' ago', $download);
    }
    // Remove empty items
    $response = array_filter($response);
    // Filter this if you want to.
    return apply_filters('edd_sl_license_readme_response', $response, $download, $readme);
}
 /**
  * File headers
  *
  * @access private
  * @param  string $filename
  * @return void
  */
 private function csv_header($filename)
 {
     send_nosniff_header();
     nocache_headers();
     @header('Content-Type: application/csv; charset=' . get_option('blog_charset'), true);
     @header('Content-Type: application/force-download');
     @header('Content-Description: File Transfer');
     @header('Content-Disposition: attachment; filename=' . $filename);
 }
 public function ajax_download_export_file()
 {
     $this->ajax_nonce('not allowed');
     $folder = MYMAIL_UPLOAD_DIR;
     $file = $folder . '/' . $_REQUEST['file'];
     if (!file_exists($file)) {
         die('not found');
     }
     $format = $_REQUEST['format'];
     $filename = basename($file);
     send_nosniff_header();
     nocache_headers();
     switch ($format) {
         case 'html':
             header('Content-Type: text/html; name="' . $filename . '.html"');
             break;
         case 'csv':
             header('Content-Type: text/csv; name="' . $filename . '.csv"');
             header('Content-Transfer-Encoding: binary');
             break;
         default:
             die('format not allowed');
     }
     header('Content-Disposition: attachment; filename="' . basename($file) . '"');
     header('Content-Length: ' . filesize($file));
     header('Connection: close');
     if ($format == 'html') {
         echo '<table>';
     }
     readfile($file);
     if ($format == 'html') {
         echo '</table>';
     }
     mymail_require_filesystem();
     global $wp_filesystem;
     $wp_filesystem->delete($file);
     exit;
 }
Beispiel #21
0
 /**
  * Get AJAX ready by defining AJAX constants and sending proper headers.
  * @param string $content_type Type of content to be set in header.
  * @param boolean $cache Do you want to cache the results?
  */
 function do_ajax($content_type = 'text/plain', $cache = false)
 {
     // If it's already been defined, that means we don't need to do it again.
     if (defined('IDX_AJAX_IS_SETUP')) {
         return;
     } else {
         define('IDX_AJAX_IS_SETUP', true);
     }
     if (!defined('ZP_NO_REDIRECT')) {
         define('ZP_NO_REDIRECT', true);
     }
     if (!defined('ZP_NO_REDIRECT')) {
         define('DOING_AJAX', true);
     }
     send_nosniff_header();
     @header('Content-Type: ' . $content_type . ';');
     @header('Accept-Encoding: gzip, deflate');
     if ($cache) {
         header('Cache-Control: public, store, post-check=10000000, pre-check=100000;');
         header('Expires: Thu, 15 Apr 2030 20:00:00 GMT;');
         header('Vary: Accept-Encoding');
         header("Last-Modified: " . gmdate("D, d M Y H:i:s", strtotime('-2 months')) . " GMT");
     }
     @header('Status Code: 200 OK;');
     @header('X-Robots-Tag:noindex;');
 }
Beispiel #22
0
<?php

/**
 * Handle default dashboard widgets options AJAX.
 *
 * @package WordPress
 * @subpackage Administration
 */
define('DOING_AJAX', true);
/** Load WordPress Bootstrap */
require_once './admin.php';
/** Load WordPress Administration Dashboard API */
require ABSPATH . 'wp-admin/includes/dashboard.php';
@header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
send_nosniff_header();
switch ($_GET['jax']) {
    case 'dashboard_incoming_links':
        wp_dashboard_incoming_links();
        break;
    case 'dashboard_primary':
        wp_dashboard_primary();
        break;
    case 'dashboard_secondary':
        wp_dashboard_secondary();
        break;
    case 'dashboard_plugins':
        wp_dashboard_plugins();
        break;
}
 function essb_proccess_light_ajax()
 {
     $current_action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
     if ($current_action == "essb_counts") {
         define('DOING_AJAX', true);
         send_nosniff_header();
         header('content-type: application/json');
         header('Cache-Control: no-cache');
         header('Pragma: no-cache');
         if (is_user_logged_in()) {
             do_action('wp_ajax_essb_counts');
         } else {
             do_action('wp_ajax_nopriv_essb_counts');
         }
         exit;
     }
 }
Beispiel #24
0
 function ajax_request()
 {
     // exit if robot
     $bot = 'bot';
     $bot2 = 'Yandex|Googlebot|slurp|yahoo|Teoma|Scooter|ia_archiver|Lycos|Rambler|Mail.Ru|Aport|WebAlta|ezooms|nigma|bingbot|Twitterbot';
     $bot3 = 'Gigabot|trendictionbot|msnbot|jeeves|webcrawler|turnitinbot|technorati|findexa|findlinks|gaisbo|zyborg|surveybot|bloglines|blogsearch|pubsub|syndic8|userland|become.com';
     if (preg_match("~{$bot}|{$bot2}~i", $_SERVER['HTTP_USER_AGENT'])) {
         exit('bot');
     }
     // path to wp-load.php
     $wp_load_file = $_SERVER['DOCUMENT_ROOT'] . '/core/wp-load.php';
     // подраздел куда установлен WP
     if (!file_exists($wp_load_file)) {
         $wp_load_file = $_SERVER['DOCUMENT_ROOT'] . '/wordpress/wp-load.php';
     }
     if (!file_exists($wp_load_file)) {
         $wp_load_file = $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';
     }
     global $wpdb;
     // WP load
     define('SHORTINIT', true);
     include_once $wp_load_file;
     send_nosniff_header();
     nocache_headers();
     @header('Content-Type: text/html; charset=UTF-8');
     @header('X-Robots-Tag: noindex');
     $meta_id = intval($_POST['id']);
     if (empty($meta_id)) {
         exit('no meta_id');
     }
     // поле должно уже существовать
     if ($wpdb->query("UPDATE {$wpdb->postmeta} SET meta_value = meta_value+1 WHERE meta_id={$meta_id}")) {
         exit((string) $wpdb->get_var("SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_id={$meta_id}"));
     }
     exit('0');
 }
 /**
  * Handle an async upload.
  *
  * Triggers on `async-upload.php?action=wxr-import-upload` to handle
  * Plupload requests from the importer.
  */
 public function handle_async_upload()
 {
     header('Content-Type: text/html; charset=' . get_option('blog_charset'));
     send_nosniff_header();
     nocache_headers();
     check_ajax_referer('wxr-import-upload');
     /*
      * 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['import']['name'])));
         exit;
     }
     $file = wp_import_handle_upload();
     if (is_wp_error($file)) {
         echo wp_json_encode(array('success' => false, 'data' => array('message' => $file->get_error_message(), 'filename' => $_FILES['import']['name'])));
         wp_die();
     }
     $attachment = wp_prepare_attachment_for_js($file['id']);
     if (!$attachment) {
         exit;
     }
     echo wp_json_encode(array('success' => true, 'data' => $attachment));
     exit;
 }
Beispiel #26
0
 public static function upload()
 {
     GFCommon::log_debug("GFAsyncUpload::upload() - Starting");
     header('Content-Type: text/html; charset=' . get_option('blog_charset'));
     send_nosniff_header();
     nocache_headers();
     status_header(200);
     // If the file is bigger than the server can accept then the form_id might not arrive.
     // This might happen if the file is bigger than the max post size ini setting.
     // Validation in the browser reduces the risk of this happening.
     if (!isset($_REQUEST["form_id"])) {
         GFCommon::log_debug("GFAsyncUpload::upload() - File upload aborted because the form_id was not found. The file may have been bigger than the max post size ini setting.");
         die('{"status" : "error", "error" : {"code": 500, "message": "' . __("Failed to upload file.", "gravityforms") . '"}}');
     }
     $form_id = $_REQUEST["form_id"];
     $form_unique_id = rgpost("gform_unique_id");
     $form = GFFormsModel::get_form_meta($form_id);
     $target_dir = GFFormsModel::get_upload_path($form_id) . DIRECTORY_SEPARATOR . "tmp" . DIRECTORY_SEPARATOR;
     wp_mkdir_p($target_dir);
     $cleanup_target_dir = true;
     // Remove old files
     $maxFileAge = 5 * 3600;
     // Temp file age in seconds
     // Chunking is not currently implemented in the front-end because it's not widely supported. The code is left here for when browsers catch up.
     $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
     $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
     $file_name = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
     $field_id = rgpost("field_id");
     $field = GFFormsModel::get_field($form, $field_id);
     // Clean the fileName for security reasons
     $file_name = preg_replace('/[^\\w\\._]+/', '_', $file_name);
     $ext_pos = strrpos($file_name, '.');
     $extension = strtolower(substr($file_name, $ext_pos + 1));
     $allowed_extensions = isset($field["allowedExtensions"]) && !empty($field["allowedExtensions"]) ? GFCommon::clean_extensions(explode(",", strtolower($field["allowedExtensions"]))) : array();
     $disallowed_extensions = GFCommon::get_disallowed_file_extensions();
     if (empty($field["allowedExtensions"]) && in_array($extension, $disallowed_extensions)) {
         GFCommon::log_debug("GFAsyncUpload::upload() - illegal file extension: {$file_name})");
         die('{"status" : "error", "error" : {"code": 104, "message": "' . __("The uploaded file type is not allowed.", "gravityforms") . '"}}');
     } elseif (!empty($allowed_extensions) && !in_array($extension, $allowed_extensions)) {
         GFCommon::log_debug("GFAsyncUpload::upload() - The uploaded file type is not allowed: {$file_name})");
         die('{"status" : "error", "error" : {"code": 104, "message": "' . sprintf(__("The uploaded file type is not allowed. Must be one of the following: %s", "gravityforms"), strtolower($field["allowedExtensions"])) . '"}}');
     }
     $tmp_file_name = $form_unique_id . "_input_" . $field_id . "_" . $file_name;
     $file_path = $target_dir . $tmp_file_name;
     // Remove old temp files
     if ($cleanup_target_dir) {
         if (is_dir($target_dir) && ($dir = opendir($target_dir))) {
             while (($file = readdir($dir)) !== false) {
                 $tmp_file_path = $target_dir . $file;
                 // Remove temp file if it is older than the max age and is not the current file
                 if (preg_match('/\\.part$/', $file) && filemtime($tmp_file_path) < time() - $maxFileAge && $tmp_file_path != "{$file_path}.part") {
                     GFCommon::log_debug("GFAsyncUpload::upload() - Deleting file: " . $tmp_file_path);
                     @unlink($tmp_file_path);
                 }
             }
             closedir($dir);
         } else {
             GFCommon::log_debug("GFAsyncUpload::upload() - Failed to open temp directory: " . $target_dir);
             die('{"status" : "error", "error" : {"code": 100, "message": "' . __("Failed to open temp directory.", "gravityforms") . '"}}');
         }
     }
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($_FILES["file"]['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
             // Open temp file
             $out = @fopen("{$file_path}.part", $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = @fopen($_FILES["file"]['tmp_name'], "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"status" : "error", "error" : {"code": 101, "message": "' . __("Failed to open input stream.", "gravityforms") . '"}}');
                 }
                 @fclose($in);
                 @fclose($out);
                 @unlink($_FILES["file"]['tmp_name']);
             } else {
                 die('{"status" : "error", "error" : {"code": 102, "message": "' . __("Failed to open output stream.", "gravityforms") . '"}}');
             }
         } else {
             die('{"status" : "error", "error" : {"code": 103, "message": "' . __("Failed to move uploaded file.", "gravityforms") . '"}}');
         }
     } else {
         // Open temp file
         $out = @fopen("{$file_path}.part", $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = @fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"status" : "error", "error" : {"code": 101, "message": "' . __("Failed to open input stream.", "gravityforms") . '"}}');
             }
             @fclose($in);
             @fclose($out);
         } else {
             die('{"status" : "error", "error" : {"code": 102, "message": "' . __("Failed to open output stream.", "gravityforms") . '"}}');
         }
     }
     // Check if file has been uploaded
     if (!$chunks || $chunk == $chunks - 1) {
         // Strip the temp .part suffix off
         rename("{$file_path}.part", $file_path);
     }
     $uploaded_filename = $_FILES["file"]["name"];
     $output = '{"status" : "ok", "data" : {"temp_filename" : "' . $tmp_file_name . '", "uploaded_filename" : "' . $uploaded_filename . '"}}';
     GFCommon::log_debug(sprintf("GFAsyncUpload::upload() - File upload complete. temp_filename: %s  uploaded_filename: %s ", $tmp_file_name, $uploaded_filename));
     die($output);
 }
    /**
     * AJAX chunk receiver.
     * Ajax callback for plupload to handle chunked uploads.
     * Based on code by Davit Barbakadze
     * https://gist.github.com/jayarjo/5846636
     * 
     * @since 1.2.0
     */
    public function ajax_chunk_receiver()
    {
        /** Check that we have an upload and there are no errors. */
        if (empty($_FILES) || $_FILES['async-upload']['error']) {
            /** Failed to move uploaded file. */
            die;
        }
        /** Authenticate user. */
        if (!is_user_logged_in() || !current_user_can('upload_files')) {
            die;
        }
        check_admin_referer('media-form');
        /** Check and get file chunks. */
        $chunk = isset($_REQUEST['chunk']) ? intval($_REQUEST['chunk']) : 0;
        $chunks = isset($_REQUEST['chunks']) ? intval($_REQUEST['chunks']) : 0;
        /** Get file name and path + name. */
        $fileName = isset($_REQUEST['name']) ? $_REQUEST['name'] : $_FILES['async-upload']['name'];
        $filePath = dirname($_FILES['async-upload']['tmp_name']) . '/' . md5($fileName);
        $tuxbfu_max_upload_size = intval(get_option('tuxbfu_max_upload_size', 0) * 1048576);
        if ($tuxbfu_max_upload_size < 0) {
            $tuxbfu_max_upload_size = 0;
        }
        if ($tuxbfu_max_upload_size > 0 && file_exists("{$filePath}.part") && filesize("{$filePath}.part") + filesize($_FILES['async-upload']['tmp_name']) > $tuxbfu_max_upload_size) {
            if (!$chunks || $chunk == $chunks - 1) {
                @unlink("{$filePath}.part");
                if (!isset($_REQUEST['short']) || !isset($_REQUEST['type'])) {
                    echo wp_json_encode(array('success' => false, 'data' => array('message' => __('The file size has exceeded the maximum file size setting.', 'tuxed-big-file-uploads'), 'filename' => $_FILES['async-upload']['name'])));
                    wp_die();
                } else {
                    echo '<div class="error-div error">
					<a class="dismiss" href="#" onclick="jQuery(this).parents(\'div.media-item\').slideUp(200, function(){jQuery(this).remove();});">' . __('Dismiss') . '</a>
					<strong>' . sprintf(__('&#8220;%s&#8221; has failed to upload.'), esc_html($_FILES['async-upload']['name'])) . '<br />' . __('The file size has exceeded the maximum file size setting.', 'tuxed-big-file-uploads') . '</strong><br />' . esc_html($id->get_error_message()) . '</div>';
                }
            }
            die;
        }
        /** Open temp file. */
        $out = @fopen("{$filePath}.part", $chunk == 0 ? 'wb' : 'ab');
        if ($out) {
            /** Read binary input stream and append it to temp file. */
            $in = @fopen($_FILES['async-upload']['tmp_name'], 'rb');
            if ($in) {
                while ($buff = fread($in, 4096)) {
                    fwrite($out, $buff);
                }
            } else {
                /** Failed to open input stream. */
                /** Attempt to clean up unfinished output. */
                @fclose($out);
                @unlink("{$filePath}.part");
                die;
            }
            @fclose($in);
            @fclose($out);
            @unlink($_FILES['async-upload']['tmp_name']);
        } else {
            /** Failed to open output stream. */
            die;
        }
        /** Check if file has finished uploading all parts. */
        if (!$chunks || $chunk == $chunks - 1) {
            /** Recreate upload in $_FILES global and pass off to WordPress. */
            rename("{$filePath}.part", $_FILES['async-upload']['tmp_name']);
            $_FILES['async-upload']['name'] = $fileName;
            $_FILES['async-upload']['size'] = filesize($_FILES['async-upload']['tmp_name']);
            $_FILES['async-upload']['type'] = $this->get_mime_content_type($_FILES['async-upload']['tmp_name']);
            header('Content-Type: text/html; charset=' . get_option('blog_charset'));
            if (!isset($_REQUEST['short']) || !isset($_REQUEST['type'])) {
                send_nosniff_header();
                nocache_headers();
                wp_ajax_upload_attachment();
                die('0');
            } else {
                $post_id = 0;
                if (isset($_REQUEST['post_id'])) {
                    $post_id = absint($_REQUEST['post_id']);
                    if (!get_post($post_id) || !current_user_can('edit_post', $post_id)) {
                        $post_id = 0;
                    }
                }
                $id = media_handle_upload('async-upload', $post_id);
                if (is_wp_error($id)) {
                    echo '<div class="error-div error">
					<a class="dismiss" href="#" onclick="jQuery(this).parents(\'div.media-item\').slideUp(200, function(){jQuery(this).remove();});">' . __('Dismiss') . '</a>
					<strong>' . sprintf(__('&#8220;%s&#8221; has failed to upload.'), esc_html($_FILES['async-upload']['name'])) . '</strong><br />' . esc_html($id->get_error_message()) . '</div>';
                    exit;
                }
                if (isset($_REQUEST['short']) && $_REQUEST['short']) {
                    // Short form response - attachment ID only.
                    echo $id;
                } elseif (isset($_REQUEST['type'])) {
                    // Long form response - big chunk o html.
                    $type = $_REQUEST['type'];
                    /**
                     * Filter the returned ID of an uploaded attachment.
                     *
                     * The dynamic portion of the hook name, `$type`, refers to the attachment type,
                     * such as 'image', 'audio', 'video', 'file', etc.
                     *
                     * @since 1.2.0
                     *
                     * @param int $id Uploaded attachment ID.
                     */
                    echo apply_filters("async_upload_{$type}", $id);
                }
            }
        }
        die;
    }
Beispiel #28
0
 /**
  * Our own Ajax response, avoiding calling admin-ajax
  */
 function ajax_response()
 {
     // Only proceed if the url query has a key of "Infinity"
     if (!self::got_infinity()) {
         return false;
     }
     define('DOING_AJAX', true);
     @header('Content-Type: text/html; charset=' . get_option('blog_charset'));
     send_nosniff_header();
     do_action('custom_ajax_infinite_scroll');
     die('0');
 }
Beispiel #29
0
 public function run_ajax()
 {
     global $wp_query;
     if ($wp_query->get("no-admin-ajax")) {
         // Constant for plugins to know that we are on an AJAX request
         define("DOING_AJAX", true);
         // If we don't have an action, do nothing
         if (!isset($_REQUEST["action"])) {
             die(0);
         }
         // Escape the parameter to prevent disastrous things
         $action = esc_attr($_REQUEST["action"]);
         // Run customized no-admin-ajax methods with action "no-admin-ajax/before"
         do_action("no-admin-ajax/before");
         // Run customized no-admin-ajax methods for specific ajax actions with "no-admin-ajax/before/{action}"
         do_action("no-admin-ajax/before/" . $action);
         // Same headers as WordPress normal AJAX routine sends
         $default_headers = array("Content-Type: text/html; charset=" . get_option("blog_charset"), "X-Robots-Tag: noindex");
         // Filter to customize the headers sent by ajax calls
         $headers = apply_filters("no-admin-ajax/headers", $default_headers);
         // Send the headers to the user
         if (is_array($headers) && count($headers) > 0) {
             foreach ($headers as $header) {
                 @header($header);
             }
         }
         send_nosniff_header();
         nocache_headers();
         // Run the actions
         if (is_user_logged_in()) {
             do_action("wp_ajax_" . $action);
         } else {
             do_action("wp_ajax_nopriv_" . $action);
         }
         die(0);
     }
 }