function fetch_remote_file($url, $post) { global $url_remap; // extract the file name and extension from the url $file_name = basename($url); // get placeholder file in the upload dir with a unique, sanitized filename $upload = wp_upload_bits($file_name, 0, '', $post['upload_date']); if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); // request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'wordpress-importer')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'wordpress-importer'), esc_html($headers['response']), get_status_header_desc($headers['response']))); } $filesize = filesize($upload['file']); if (isset($headers['content-length']) && $filesize != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'wordpress-importer')); } if (0 == $filesize) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Zero size file downloaded', 'wordpress-importer')); } // keep track of the old and new urls so we can substitute them later $url_remap[$url] = $upload['url']; return $upload; }
function get_contents($url) { if (substr($url, 0, 5) == 'http:') { return wp_get_http($url); } return file_get_contents($url); }
function test_get_redirect_limit_exceeded() { // this will redirect to asdftestblog1.files.wordpress.com $url = 'http://asdftestblog1.wordpress.com/files/2007/09/2007-06-30-dsc_4700-1.jpg'; $file = tempnam('/tmp', 'testfile'); // pretend we've already redirected 5 times $headers = wp_get_http($url, $file, 6); $this->assertFalse($headers); }
/** * * @param unknown_type $url */ private function getImageFromRemote($url) { // check for http in url if (substr_count($url, 'http') == 0) { $url = $this->host_name . $url; } // extract the file name and extension from the url $file_name = basename($url); // get placeholder file in the upload dir with a unique, sanitized filename // $upload = wp_upload_bits( $file_name, 0, '', $post['upload_date'] ); $upload = wp_upload_bits($file_name, 0, ''); if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); // request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'wordpress-importer')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'wordpress-importer'), esc_html($headers['response']), get_status_header_desc($headers['response']))); } $filesize = filesize($upload['file']); if (isset($headers['content-length']) && $filesize != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'wordpress-importer')); } if (0 == $filesize) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Zero size file downloaded', 'wordpress-importer')); } return $upload; }
/** * Move Images from a remote url to upload directory. * * @since 1.0.0 * @package GeoDirectory * @param string $url The remote image url. * @return array|WP_Error The uploaded data as array. When failure returns error. */ function fetch_remote_file($url) { // extract the file name and extension from the url require_once ABSPATH . 'wp-includes/pluggable.php'; $file_name = basename($url); if (strpos($file_name, '?') !== false) { list($file_name) = explode('?', $file_name); } // get placeholder file in the upload dir with a unique, sanitized filename $post_upload_date = isset($post['upload_date']) ? $post['upload_date'] : ''; $upload = wp_upload_bits($file_name, 0, '', $post_upload_date); if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); // request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'geodirectory')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'geodirectory'), esc_html($headers['response']), get_status_header_desc($headers['response']))); } $filesize = filesize($upload['file']); if (isset($headers['content-length']) && $filesize != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'geodirectory')); } if (0 == $filesize) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Zero size file downloaded', 'geodirectory')); } return $upload; }
/** * Validate widget input * * @access public * @return Mixed */ function validate($args, $options, $preview) { extract($args); $output = ""; $permalink = trim($permalink); if ($options['required']) { if (empty($permalink) || $permalink == $options['default']) { $output .= __('You must specify the permalink.', 'tdomf'); } } if (!empty($permalink) && $permalink != $options['default'] && !tdomf_check_url($permalink)) { $output .= __('The permalink you specified seems incorrect', 'tdomf'); } else { if (!$preview && $options['test'] && function_exists('wp_get_http')) { $headers = wp_get_http($permalink, false, 1); if ($headers == false) { $output .= sprintf(__('The permalink doesn\'t doesnt seem to exist.', 'tdomf'), $headers["response"]); } else { if ($headers["response"] != '200') { $output .= sprintf(__('The permalink doesn\'t doesnt seem to exist. Returned %d error code.', 'tdomf'), $headers["response"]); } } } } return $output; }
function tdomf_get_error_messages($show_links = true, $form_id = 0) { global $wpdb, $wp_roles; if (!isset($wp_roles)) { $wp_roles = new WP_Roles(); } $roles = $wp_roles->role_objects; $message = ""; #if(ini_get('register_globals') && !TDOMF_HIDE_REGISTER_GLOBAL_ERROR){ # $message .= "<font color=\"red\"><strong>".__("ERROR: <em>register_globals</em> is enabled. This is a security risk and also prevents TDO Mini Forms from working.")."</strong></font>"; #} if (version_compare("5.0.0", phpversion(), ">")) { $message .= sprintf(__("Warning: You are currently using PHP version %s. It is strongly recommended to use PHP5 with TDO Mini Forms.", "tdomf"), phpversion()); $message .= "<br/>"; } if (get_option(TDOMF_OPTION_VERIFICATION_METHOD) == 'none') { $message .= __("Warning: Form input verification is disabled. This is a potential security risk.", "tdomf"); $message .= "<br/>"; } # Revisions disabled => editing won't work well if (!constant('WP_POST_REVISIONS')) { $form_ids = tdomf_get_form_ids(); foreach ($form_ids as $a_form_id) { if (tdomf_get_option_form(TDOMF_OPTION_FORM_EDIT, $a_form_id->form_id)) { $message .= __("Error: Post Revisioning is disabled, post editing will not work correctly!", "tdomf"); $message .= "<br/>"; break; } } } if (isset($_REQUEST['form']) || $form_id != 0) { if ($form_id == 0) { $form_id = intval($_REQUEST['form']); } // permissions error if (tdomf_get_option_form(TDOMF_OPTION_ALLOW_EVERYONE, $form_id) == false) { $caps = tdomf_get_option_form(TDOMF_OPTION_ALLOW_CAPS, $form_id); if (is_array($caps) && empty($caps)) { $caps = false; } $users = tdomf_get_option_form(TDOMF_OPTION_ALLOW_USERS, $form_id); if (is_array($users) && empty($users)) { $users = false; } $publish = tdomf_get_option_form(TDOMF_OPTION_ALLOW_PUBLISH, $form_id); $role_count = 0; $role_publish_count = 0; foreach ($roles as $role) { if (isset($role->capabilities[TDOMF_CAPABILITY_CAN_SEE_FORM . '_' . $form_id])) { $role_count++; if (isset($role->capabilities['publish_posts'])) { $role_publish_count++; } } } // if nothing set if ($role_count == 0 && $caps == false && $users == false && $publish == false) { if ($show_links) { $message .= "<font color=\"red\">" . sprintf(__("<b>Warning</b>: No-one has been configured to be able to access the form! <a href=\"%s\">Configure on Options Page »</a>", "tdomf"), get_bloginfo('wpurl') . "/wp-admin/admin.php?page=tdomf_show_form_options_menu&form={$form_id}") . "</font><br/>"; } else { $message .= "<font color=\"red\">" . __("<b>Warning</b>: No-one has been configured to be able to access the form!", "tdomf") . "</font><br/>"; } tdomf_log_message("No-one has been configured to access this form ({$form_id})", TDOMF_LOG_BAD); } else { if ($caps == false && $users == false && $role_count == $role_publish_count && $publish == false) { if ($show_links) { $message .= "<font color=\"red\">" . sprintf(__("<b>Warning</b>: Only users who can <i>already publish posts</i>, can see the form! <a href=\"%s\">Configure on Options Page »</a>", "tdomf"), get_bloginfo('wpurl') . "/wp-admin/admin.php?page=tdomf_show_form_options_menu&form={$form_id}") . "</font><br/>"; } else { $message .= "<font color=\"red\">" . __("<b>Warning</b>: Only users who can <i>already publish posts</i>, can see this form!", "tdomf") . "</font><br/>"; } tdomf_log_message("Only users who can already publish can access the form ({$form_id})", TDOMF_LOG_BAD); } } } // form hacker modified $mode = tdomf_generate_default_form_mode($form_id) . '-hack'; $curr_unmod_prev = trim(tdomf_preview_form(array('tdomf_form_id' => $form_id), $mode)); $org_unmod_prev = trim(tdomf_get_option_form(TDOMF_OPTION_FORM_PREVIEW_HACK_ORIGINAL, $form_id)); $hacked_prev = trim(tdomf_get_option_form(TDOMF_OPTION_FORM_PREVIEW_HACK, $form_id)); if ($hacked_prev != false && $curr_unmod_prev != $org_unmod_prev) { $message .= "<font color=\"red\">"; $diffs = "admin.php?page=tdomf_show_form_hacker&form={$form_id}&mode={$mode}&diff&form2=cur&form1=org&type=preview"; $form_hacker = "admin.php?page=tdomf_show_form_hacker&form={$form_id}"; $dismiss = wp_nonce_url("admin.php?page=tdomf_show_form_hacker&form={$form_id}&dismiss&type=preview", 'tdomf-form-hacker'); $message .= sprintf(__("<b>Warning</b>: Form configuration has been changed that affect the preview output but Form Hacker has not been updated! <a href='%s'>Diff »</a> | <a href='%s'>Hack Form »</a> | <a href='%s'>Dismiss</a>", "tdomf"), $diffs, $form_hacker, $dismiss); $message .= "</font><br/>"; } $curr_unmod_form = trim(tdomf_generate_form($form_id, $mode)); $org_unmod_form = trim(tdomf_get_option_form(TDOMF_OPTION_FORM_HACK_ORIGINAL, $form_id)); $hacked_form = trim(tdomf_get_option_form(TDOMF_OPTION_FORM_HACK, $form_id)); if ($hacked_form != false && $curr_unmod_form != $org_unmod_form) { $message .= "<font color=\"red\">"; $diffs = "admin.php?page=tdomf_show_form_hacker&form={$form_id}&mode={$mode}&diff&form2=cur&form1=org"; $form_hacker = "admin.php?page=tdomf_show_form_hacker&form={$form_id}"; $dismiss = wp_nonce_url("admin.php?page=tdomf_show_form_hacker&form={$form_id}&dismiss", 'tdomf-form-hacker'); $message .= sprintf(__("<b>Warning</b>: Form configuration has been changed that affect the generated form but Form Hacker has not been updated! <a href='%s'>Diff »</a> | <a href='%s'>Hack Form »</a> | <a href='%s'>Dismiss</a>", "tdomf"), $diffs, $form_hacker, $dismiss); $message .= "</font><br/>"; } // widget errors global $tdomf_form_widgets_admin_errors; $mode = "new-post"; if (tdomf_get_option_form(TDOMF_OPTION_SUBMIT_PAGE, $form_id)) { $mode = "new-page"; } $uri = "admin.php?page=tdomf_show_form_menu&form=" . $form_id; do_action('tdomf_control_form_start', $form_id, $mode); $widget_order = tdomf_get_widget_order($form_id); $widgets = tdomf_filter_widgets($mode, $tdomf_form_widgets_admin_errors); foreach ($widget_order as $w) { if (isset($widgets[$w])) { $widget_message = call_user_func($widgets[$w]['cb'], $form_id, $widgets[$w]['params']); if (!empty($widget_message)) { $message .= "<font color=\"red\">" . $widget_message . sprintf(__(" <a href='%s'>Fix »</a>", "tdomf"), $uri) . "</font><br/>"; } } } // @todo check that key is unique in custom fields } if (get_option(TDOMF_OPTION_EXTRA_LOG_MESSAGES) && !get_option(TDOMF_OPTION_DISABLE_ERROR_MESSAGES)) { $message .= "<font color=\"red\">"; if ($show_links) { $message .= sprintf(__("<b>Warning:</b> You have enabled 'Extra Debug Messages' and disabled 'Disable Error Messages'. This invokes a special mode where all PHP errors are turned on. This can lead to unexpected problems and could be considered a security leak! <a href=\"%s\">Change on the Options Page »</a>", "tdomf"), get_bloginfo('wpurl') . "/wp-admin/admin.php?page=tdomf_show_options_menu"); } else { $message .= __("<b>Warning:</b> You have enabled 'Extra Debug Messages' and disabled 'Disable Error Messages'. This invokes a special mode where all PHP errors are turned on. This can lead to unexpected problems and could be considered a security leak! This should only be used for debugging purposes.", "tdomf"); } $message .= "</font><br/>"; } $create_user_link = get_bloginfo('wpurl') . "/wp-admin/admin.php?page=tdomf_show_options_menu&action=create_dummy_user"; if (function_exists('wp_nonce_url')) { $create_user_link = wp_nonce_url($create_user_link, 'tdomf-create-dummy-user'); } if (get_option(TDOMF_DEFAULT_AUTHOR) == false) { $message .= "<font color=\"red\">" . sprintf(__("<b>Error</b>: No default author set! <a href=\"%s\">Create dummy user for default author automatically »</a>", "tdomf"), $create_user_link) . "</font><br/>"; tdomf_log_message("Option Default Author not set!", TDOMF_LOG_BAD); } else { $def_aut = new WP_User(get_option(TDOMF_DEFAULT_AUTHOR)); if (empty($def_aut->data->ID)) { // User does not exist! Deleting option delete_option(TDOMF_DEFAULT_AUTHOR); $message .= "<font color=\"red\">" . sprintf(__("<b>Error</b>: Current Default Author does not exist! <a href=\"%s\">Create dummy user for default author automatically »</a>", "tdomf"), $create_user_link) . "</font><br/>"; tdomf_log_message("Current Default Author does not exist! Deleting option.", TDOMF_LOG_BAD); } if ($def_aut->has_cap("publish_posts")) { $message .= "<font color=\"red\">" . sprintf(__("<b>Error</b>: Default author can publish posts. Default author should not be able to publish posts! <a href=\"%s\">Create a dummy user for default author automatically »</a>", "tdomf"), $create_user_link) . "</font><br/>"; tdomf_log_message("Option Default Author is set to an author who can publish posts.", TDOMF_LOG_BAD); } } if (function_exists('wp_get_http')) { $post_uri = TDOMF_URLPATH . 'tdomf-form-post.php'; $headers = wp_get_http($post_uri, false, 1); if ($headers != false && $headers["response"] != '200') { $message .= "<font color=\"red\">"; $message .= sprintf(__("<b>Error</b>: Got a %d error when checking <a href=\"%s\">%s</a>! This will prevent posts from being submitted. The permissions may be wrong on the tdo-mini-forms folder.", "tdomf"), $headers["response"], $post_uri, $post_uri); $message .= "</font><br/>"; tdomf_log_message("Did not receive a 200 response when checking {$post_uri}:<pre>" . var_export($headers, true) . "</pre>", TDOMF_LOG_ERROR); } $ajax_uri = TDOMF_URLPATH . 'tdomf-form-ajax.php'; $headers = wp_get_http($ajax_uri, false, 1); if ($headers != false && $headers["response"] != '200') { $message .= "<font color=\"red\">"; $message .= sprintf(__("<b>Error</b>: Got a %d error when checking <a href=\"%s\">%s</a>! This will prevent forms that use AJAX from submitting posts. The permissions may be wrong on the tdo-mini-forms folder.", "tdomf"), $headers["response"], $ajax_uri, $ajax_uri); $message .= "</font><br/>"; tdomf_log_message("Did not receive a 200 response when checking {$ajax_uri}:<pre>" . var_export($headers, true) . "</pre>", TDOMF_LOG_ERROR); } $css_uri = TDOMF_URLPATH . 'tdomf-style-form.css'; $headers = wp_get_http($css_uri, false, 1); if ($headers != false && $headers["response"] != '200') { $message .= "<font color=\"red\">"; $message .= sprintf(__("<b>Error</b>: Got a %d error when checking <a href=\"%s\">%s</a>! This will make your forms, by default, look very ugly. The permissions may be wrong on the tdo-mini-forms folder.", "tdomf"), $headers["response"], $css_uri, $css_uri); $message .= "</font><br/>"; tdomf_log_message("Did not receive a 200 response when checking {$css_uri}:<pre>" . var_export($headers, true) . "</pre>", TDOMF_LOG_ERROR); } } return $message; }
/** * Perform a HTTP HEAD or GET request. * * If $file_path is a writable filename, this will do a GET request and write * the file to that path. * * @since 2.5.0 * * @param string $url URL to fetch. * @param string|bool $file_path Optional. File path to write request to. Default false. * @param int $red Optional. The number of Redirects followed, Upon 5 being hit, * returns false. Default 1. * @return bool|string False on failure and string of headers if HEAD request. */ function wp_get_http($url, $file_path = false, $red = 1) { @set_time_limit(60); if ($red > 5) { return false; } $options = array(); $options['redirection'] = 5; if (false == $file_path) { $options['method'] = 'HEAD'; } else { $options['method'] = 'GET'; } $response = wp_safe_remote_request($url, $options); if (is_wp_error($response)) { return false; } $headers = wp_remote_retrieve_headers($response); $headers['response'] = wp_remote_retrieve_response_code($response); // WP_HTTP no longer follows redirects for HEAD requests. if ('HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset($headers['location'])) { return wp_get_http($headers['location'], $file_path, ++$red); } if (false == $file_path) { return $headers; } // GET request - write it to the supplied filename $out_fp = fopen($file_path, 'w'); if (!$out_fp) { return $headers; } fwrite($out_fp, wp_remote_retrieve_body($response)); fclose($out_fp); clearstatcache(); return $headers; }
/** * Cache AddToAny */ function A2A_SHARE_SAVE_refresh_cache() { $contents = wp_remote_fopen('http://www.addtoany.com/ext/updater/files_list/'); $file_urls = explode("\n", $contents, 20); $upload_dir = wp_upload_dir(); // Make directory if needed if (!wp_mkdir_p(dirname($upload_dir['basedir'] . '/addtoany/foo'))) { $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), dirname($new_file)); return array('error' => $message); } if (count($file_urls) > 0) { for ($i = 0; $i < count($file_urls); $i++) { // Download files $file_url = trim($file_urls[$i]); $file_name = substr(strrchr($file_url, '/'), 1, 99); // Place files in uploads/addtoany directory wp_get_http($file_url, $upload_dir['basedir'] . '/addtoany/' . $file_name); } } }
function validate($args, $opts, $preview = false, $original_field_name = false) { $output = ""; $text = false; // grab the input because we're going to test it $text = false; if (empty($output)) { if (isset($args[$this->prefix . 'tf'])) { $text = $args[$this->prefix . 'tf']; } else { if ($original_field_name != false && isset($args[$original_field_name])) { $text = $args[$original_field_name]; } else { $output .= __("ERROR: Form is invalid. Please check TDO Mini Forms admin.", "tdomf"); } } } // is it empty? if (empty($output) && $opts[$this->prefix . 'required']) { if (empty($text) || trim($text) == "" || $text == $opts[$this->prefix . 'default-text']) { if ($opts[$this->prefix . 'restrict-type'] == 'url') { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("You must specify a vaild URL for %s.", "tdomf"), $opts[$this->prefix . 'title']); } else { $output .= __("You must specify a valid URL.", "tdomf"); } } else { if ($opts[$this->prefix . 'restrict-type'] == 'email') { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("You must specify a vaild email address for %s.", "tdomf"), $opts[$this->prefix . 'title']); } else { $output .= __("You must specify a valid email.", "tdomf"); } } else { if ($opts[$this->prefix . 'restrict-type'] == 'number') { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("You must specify a number for %s.", "tdomf"), $opts[$this->prefix . 'title']); } else { $output .= __("You must specify a number.", "tdomf"); } } else { #$opts[$this->prefix.'restrict-type'] == 'text' if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("You must specify some %s.", "tdomf"), $opts[$this->prefix . 'title']); } else { $output .= __("You must specify some text.", "tdomf"); } } } } } } // is it a real email, url or number if (empty($output) && $opts[$this->prefix . 'restrict-type'] != 'text') { if ($opts[$this->prefix . 'restrict-type'] == 'url') { if (!tdomf_check_url($text)) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("The URL \"%s\" for %s does not look correct.", "tdomf"), $text, $opts[$this->prefix . 'title']); } else { $output .= sprintf(__("The URL \"%s\" does not look correct.", "tdomf"), $text); } } else { if ($opts[$this->prefix . 'validate-url']) { if (function_exists('wp_get_http')) { $headers = wp_get_http($text, false, 1); if ($headers == false) { $output .= sprintf(__('The URL doesn\'t doesnt seem to exist.', 'tdomf'), $headers["response"]); } else { if ($headers["response"] != '200') { $output .= sprintf(__('The link doesn\'t doesnt seem to exist. Returned %d error code.', 'tdomf'), $headers["response"]); } } } } } } else { if ($opts[$this->prefix . 'restrict-type'] == 'email') { if (!tdomf_check_email_address($text, $opts[$this->prefix . 'validate-email'])) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("The email address \"%s\" for %s does not seem to be correct.", "tdomf"), $text, $opts[$this->prefix . 'title']); } else { $output .= sprintf(__("The email address \"%s\" does not seem to be correct.", "tdomf"), $text); } } } else { if ($opts[$this->prefix . 'restrict-type'] == 'number') { if (is_numeric($text)) { if ($opts[$this->prefix . 'number-decimal']) { $number = floatval($text); if ($opts[$this->prefix . 'number-start'] !== false && $number < $opts[$this->prefix . 'number-start']) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("%f for %s is too low. It must be equal to or greater than %f.", "tdomf"), $number, $opts[$this->prefix . 'title'], $opts[$this->prefix . 'number-start']); } else { $output .= sprintf(__("%f is too low. It must be equal to or greater than %f.", "tdomf"), $text, $opts[$this->prefix . 'number-start']); } } else { if ($opts[$this->prefix . 'number-end'] !== false && $number > $opts[$this->prefix . 'number-end']) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("%f for %s is too high. It must be equal to or less than %f.", "tdomf"), $text, $opts[$this->prefix . 'title'], $opts[$this->prefix . 'number-start']); } else { $output .= sprintf(__("%f is too high. It must be equal to or less than %f.", "tdomf"), $text, $opts[$this->prefix . 'number-start']); } } } } else { $number = intval($text); if ($opts[$this->prefix . 'number-start'] !== false && $number < $opts[$this->prefix . 'number-start']) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("%d for %s is too low. It must be equal to or greater than %d.", "tdomf"), $number, $opts[$this->prefix . 'title'], $opts[$this->prefix . 'number-start']); } else { $output .= sprintf(__("%d is too low. It must be equal to or greater than %d.", "tdomf"), $text, $opts[$this->prefix . 'number-start']); } } else { if ($opts[$this->prefix . 'number-end'] !== false && $number > $opts[$this->prefix . 'number-end']) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("%d for %s is too high. It must be equal to or less than %d.", "tdomf"), $text, $opts[$this->prefix . 'title'], $opts[$this->prefix . 'number-start']); } else { $output .= sprintf(__("%d is too high. It must be equal to or less than %d.", "tdomf"), $text, $opts[$this->prefix . 'number-start']); } } } } } else { if (trim($text) != "") { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("\"%s\" for %s is not a valid number.", "tdomf"), $text, $opts[$this->prefix . 'title']); } else { $output .= sprintf(__("\"%s\" is not a valid number.", "tdomf"), $text); } } } } } } } // does it fit the counts? if (empty($output) && $opts[$this->prefix . 'restrict-type'] == 'text' && ($opts[$this->prefix . 'word-limit'] > 0 || $opts[$this->prefix . 'char-limit']) > 0) { if ($opts[$this->prefix . 'allowable-tags'] != "" && $opts[$this->prefix . 'restrict-tags']) { $text = strip_tags($text, $opts[$this->prefix . 'allowable-tags']); } $len = strlen($text); if ($opts[$this->prefix . 'char-limit'] > 0 && $len > $opts[$this->prefix . 'char-limit']) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("You have exceeded the max character length by %d characters for %s.", "tdomf"), $len - $opts[$this->prefix . 'char-limit'], $opts[$this->prefix . 'title']); } else { $output .= sprintf(__("You have exceeded the max character length by %d characters.", "tdomf"), $len - $opts[$this->prefix . 'char-limit']); } } else { if ($opts[$this->prefix . 'word-limit'] > 0) { // Remove all HTML tags as they do not count as "words"! $text = trim(strip_tags($text)); // Replace newlines with spaces $text = preg_replace("/\r?\n/", " ", $text); // Remove excess whitespace $text = preg_replace('/\\s\\s+/', ' ', $text); // count the words! $word_count = count(explode(" ", $text)); if ($word_count > $opts[$this->prefix . 'word-limit']) { if (!empty($opts[$this->prefix . 'title'])) { $output .= sprintf(__("You have exceeded the max word count by %d words for %s.", "tdomf"), $word_count - $opts[$this->prefix . 'word-limit'], $opts[$this->prefix . 'title']); } else { $output .= sprintf(__("You have exceeded the max word count by %d words.", "tdomf"), $word_count - $opts[$this->prefix . 'word-limit']); } } } } } return $output; }
protected function import_file($post, $insert_post_id, $date) { $upload = wp_upload_dir($date); // nuke the old file so the new one can claim its name $existing_file_check = trailingslashit($upload['basedir']) . $post['meta']['_wp_attached_file']; if (is_file($existing_file_check)) { @unlink($existing_file_check); } $url = $post['file']['url']; $file_name = basename($post['meta']['_wp_attached_file']); $upload = wp_upload_bits($file_name, 0, '', $date); /* -- taken from wp-importer --*/ if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); //Request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'wordpress-importer')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file returned error response %1$d %2$s', 'wordpress-importer'), $headers['response'], get_status_header_desc($headers['response']))); } elseif (isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'wordpress-importer')); } $max_size = $this->max_attachment_size(); if (!empty($max_size) and filesize($upload['file']) > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is too large, limit is %s', size_format($max_size), 'wordpress-importer'))); } /*-- end taken from wp-importer --*/ wp_update_attachment_metadata($insert_post_id, wp_generate_attachment_metadata($insert_post_id, $upload['file'])); return true; }
/** * Used to download and create image from 'src' and attach to media library * * @param array $match Array in which [0]->whole img tag and [1]->the img src * @param object|array $post The global post variable or object from get_posts() * @param string $size The image size required * @param array $double_check_tag Used to take care of the misleading wp-image class * @return string * * @since rtPanel 2.0 */ function rtp_create_external_thumb($match, $post, $size, $double_check_tag = '') { require_once ABSPATH . '/wp-admin/includes/class-wp-filesystem-base.php'; require_once ABSPATH . '/wp-admin/includes/class-wp-filesystem-direct.php'; @($file_object = new WP_Filesystem_Direct()); $img_path = urldecode($match[1]); // Need to do this else image fetching will fail $remote_get_path = str_replace(' ', '%20', $img_path); // Get the img name from url $img_name = basename($img_path); /* Set permissions if directory is not writable */ $upload_path = wp_upload_dir(); if (!is_writable($upload_path['basedir']) || !is_executable($upload_path['basedir'])) { $stat = @stat(dirname($upload_path['basedir'])); // Get the permission bits $dir_perms = $stat['mode'] & 07777; @chmod($upload_path['basedir'], $dir_perms); } /* For sanitization of name (just a precaution, although wp_upload_bits will try to take care of this) */ $img_name = str_replace('&', '-', $img_name); $img_name = str_replace('?', '-', $img_name); $allowed_image_types = array('jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'ico', 'tif', 'tiff'); $check_extension = pathinfo($img_name); // if not in the array assign a particular name if (!in_array($check_extension['extension'], $allowed_image_types)) { $img_name = 'query-image.jpg'; } // get placeholder file in the upload dir with a unique, sanitized filename $file = wp_upload_bits($img_name, 0, ''); // fetch the remote url and write it to the placeholder file $wp_remote_get = wp_get_http($remote_get_path, $file['file'], 5); if ($wp_remote_get == '' || $wp_remote_get == false) { $file_object->delete($file['file']); return 0; } /* if response id is 200 and it's type is image */ if ($wp_remote_get['response'] == 200 && substr($wp_remote_get['content-type'], 0, 5) == 'image') { //created img path $img_path = $file['file']; //created img url $img_url = $file['url']; // Get the image type. Must to use it as a post thumbnail. $img_type = wp_check_filetype($img_path); extract($img_type); $img_info = apply_filters('wp_handle_upload', array('file' => $img_path, 'url' => $img_url, 'type' => $type), 'sideload'); require_once ABSPATH . '/wp-admin/includes/image.php'; /* use image exif/iptc data for title and caption defaults if possible */ if ($img_meta = @wp_read_image_metadata($img_info['file'])) { if (trim($img_meta['title']) && !is_numeric(sanitize_title($img_meta['title']))) { $img_title = $img_meta['title']; } if (trim($img_meta['caption'])) { $img_content = $img_meta['caption']; } } $img_title = isset($img_title) ? $img_title : str_replace('.' . $ext, '', basename($img_url)); $img_content = isset($img_content) ? $img_content : str_replace('.' . $ext, '', basename($img_url)); // Construct the attachment array $attachment = array('post_mime_type' => $img_info['type'], 'guid' => $img_url, 'post_parent' => $post->ID, 'post_title' => $img_title, 'post_content' => $img_content); // Save the attachment metadata $new_image_id = wp_insert_attachment($attachment, $img_info['file'], $post->ID); if (!is_wp_error($new_image_id) && $new_image_id != 0 && $new_image_id != '') { wp_update_attachment_metadata($new_image_id, wp_generate_attachment_metadata($new_image_id, $img_info['file'])); $updated_post = array(); $updated_post['ID'] = $post->ID; if (is_int($new_image_id)) { $image_src = wp_get_attachment_image_src($new_image_id, $size); // get the img tag classes preg_match('/<img.*class\\s*=\\s*"([^"]*)[^>]+>/i', $match[0], $class); /* if the image tag has class attribute and it does not have wp-image in class */ if (isset($class[1])) { $updated_class = $class[1] . ' wp-image-' . $new_image_id; $updated_image_tag = str_replace('class="' . $class[1] . '"', 'class="' . $updated_class . '"', $match[0]); $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content); if ($double_check_tag != '') { $updated_post['post_content'] = str_replace($double_check_tag, $updated_image_tag, $post->post_content); } // Update the post wp_update_post($updated_post); } else { $updated_image_tag = str_replace('<img', '<img role="img" class="wp-image-' . $new_image_id . '"', $match[0]); $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content); // Update the post wp_update_post($updated_post); } return $image_src[0]; } else { $updated_post = array(); $updated_post['ID'] = $post->ID; $new_image_id = rtp_get_attachment_id_from_src($new_image_id); $image_src = wp_get_attachment_image_src($new_image_id, $size); preg_match('/<img.*class\\s*=\\s*"([^"]*)[^>]+>/i', $match[0], $class); if (isset($class[1])) { $updated_class = $class[1] . ' wp-image-' . $new_image_id; $updated_image_tag = str_replace('class="' . $class[1] . '"', 'class="' . $updated_class . '"', $match[0]); $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content); if ($double_check_tag != '') { $updated_post['post_content'] = str_replace($double_check_tag, $updated_image_tag, $post->post_content); } // Update the post wp_update_post($updated_post); } else { $updated_image_tag = str_replace('<img', '<img role="img" class="wp-image-' . $new_image_id . '"', $match[0]); $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content); // Update the post wp_update_post($updated_post); } return $image_src[0]; } } } else { $file_object->delete($file['file']); return 0; } }
function downloadImage($image, $moblog, $id) { $upload = wp_upload_dir(); $base_dir = $upload['basedir'] . '/moblog-' . $moblog . '/'; $newimage = $base_dir . $id . '.jpg'; $newimageurl = $upload['baseurl'] . '/moblog-' . $moblog . '/' . $id . '.jpg'; if (!is_dir($base_dir)) { mkdir($base_dir); } $get = wp_get_http($image, $newimage); if ($get['response'] == 200 && file_exists($newimage)) { return $newimageurl; } else { return $image; } }
/** * Attempt to download a remote file attachment * * @param string $url URL of item to fetch * @param array $post Attachment details * @return array|WP_Error Local file location details on success, WP_Error otherwise */ function fetch_remote_file($url, $subdir = null) { add_filter('http_request_timeout', array($this, 'bump_request_timeout')); // extract the file name and extension from the url $file_name = basename($url); // get placeholder file in the upload dir with a unique, sanitized filename $upload = $this->wp_upload_bits($file_name, '', $subdir); // var_dump( $upload ); //echo "<br />" . $url . "<br />"; return new WP_Error( 'import_file_error', '' ); if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); // request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'wordpress-importer')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'wordpress-importer'), esc_html($headers['response']), get_status_header_desc($headers['response']))); } $filesize = filesize($upload['file']); if (isset($headers['content-length']) && $filesize != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'wordpress-importer')); } if (0 == $filesize) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Zero size file downloaded', 'wordpress-importer')); } $max_size = (int) $this->max_attachment_size(); if (!empty($max_size) && $filesize > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is too large, limit is %s', 'wordpress-importer'), size_format($max_size))); } return $upload; }
function rigr_fetch_remote_file($post, $url) { $url2 = str_replace('&', '&', str_replace('https://', 'http://', $url)); preg_match('/[a-z0-9;=_%\\Q?&.-+[]\\E]+\\.(jpg|jpeg|gif|png|rar|zip|mp3|mp4|flv|pdf|swf)/i', $url2, $pu); $file_name = str_replace('%25', '-', $pu[0]); $file_name = preg_replace('/[;=%\\Q?&-+\\E]+/i', '-', $file_name); $file_name = strlen($file_name) > 255 ? substr($file_name, 180) : $file_name; $upload = wp_upload_bits($file_name, 0, '', $post['post_date']); if ($upload['error']) { echo $upload['error']; return new WP_Error('upload_dir_error', $upload['error']); } $headers = wp_get_http($url2, $upload['file']); if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('<p class="help"><img src="images/no.png"> <span style="color: #ff0000;">Remote server did not respond</span></p>', 'rigr')); } if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server says: %1$d %2$s', 'rigr'), $headers['response'], get_status_header_desc($headers['response']))); } elseif (isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('<p class="help"><img src="images/no.png"> <span style="color: #ff0000;">Remote file can not be downloaded</span></p>', 'rigr')); } $min_size = max((double) $_POST['rigr_min_size'], 0) * 1024; $max_size = max((int) $_POST['rigr_max_size'], (int) get_site_option('fileupload_maxk')) * 1024; /* -- fileupload_maxk for wpmu compatibility -- */ $file_size = filesize($upload['file']); if (!empty($max_size) && $file_size > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is %1$d KB but limit is %2$d', 'rigr'), $file_size / 1024, $max_size / 1024)); } elseif (!empty($min_size) && $file_size < $min_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file size is less then %1$d KB', 'rigr'), $min_size / 1024)); } /* -- This check is for wpmu compatibility -- */ if (function_exists('get_space_allowed')) { $space_allowed = 1048576 * get_space_allowed(); $space_used = get_dirsize(BLOGUPLOADDIR); $space_left = $space_allowed - $space_used; if ($space_left < 0) { @unlink($upload['file']); return new WP_Error('not_enough_diskspace', sprintf(__('You have %1$d KB diskspace used but %2$d allowed.', 'rigr'), $space_used / 1024, $space_allowed / 1024)); } } $upload['content-type'] = $headers['content-type']; return $upload; }
function evc_fetch_remote_file($args) { if (!empty($args)) { extract($args); } //$post_date = date('Y-m-d H:i:s'); $upload = wp_upload_dir(); $upload = wp_upload_bits($file_name, 0, ''); if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } $headers = wp_get_http($url, $upload['file']); if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'evc')); } if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server says: %1$d %2$s', 'evc'), $headers['response'], get_status_header_desc($headers['response']))); } elseif (isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'evc')); } $max_size = (int) get_site_option('fileupload_maxk') * 1024; // fileupload_maxk for wpmu compatibility $file_size = filesize($upload['file']); if (!empty($max_size) && $file_size > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is %1$d KB but limit is %2$d', 'evc'), $file_size / 1024, $max_size / 1024)); } // This check is for wpmu compatibility if (function_exists('get_space_allowed')) { $space_allowed = 1048576 * get_space_allowed(); $space_used = get_dirsize(BLOGUPLOADDIR); $space_left = $space_allowed - $space_used; if ($space_left < 0) { @unlink($upload['file']); return new WP_Error('not_enough_diskspace', sprintf(__('You have %1$d KB diskspace used but %2$d allowed.', 'evc'), $space_used / 1024, $space_allowed / 1024)); } } $upload['content-type'] = $headers['content-type']; return $upload; }
function wp_get_http_headers($url, $red = 1) { return wp_get_http($url, false, $red); }
function fetch_attachment($url, $file_path) { // If the file already exists locally, we don't need to re-download // it. We can instead just read the relevant info off the disk // and save some network time if (file_exists($file_path) && filesize($file_path) > 100) { return array('response' => '200', 'content-length' => filesize($file_path)); } $url_parts = parse_url($url); $world_ip = $this->global_ip_for_host($url_parts['host']); // If we can't find a world routable IP, fall back on local routing if (empty($world_ip)) { return wp_get_http($url, $file_path); } else { if (!empty($url_parts['query'])) { $url_parts['path'] .= '?' . $url_parts['query']; } $headers = array('Host: ' . $url_parts['host']); $url = $url_parts['scheme'] . "://" . $world_ip . str_replace(' ', '%20', $url_parts['path']); $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_MAXREDIRS, 10); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); $response_headers = curl_getinfo($curl); // Now, map the CURL provided headers into the format that // WP functions expect. $wp_headers = array('response' => $response_headers['http_code'], 'content-length' => $response_headers['download_content_length']); curl_close($curl); if (false == $file_path) { return $wp_headers; } $out_fp = fopen($file_path, 'w'); if (!$out_fp) { return $wp_headers; } fwrite($out_fp, $result); fclose($out_fp); clearstatcache(); return $wp_headers; } }
function fetch_remote_file($post, $url) { add_filter('http_request_timeout', array(&$this, 'bump_request_timeout')); $upload = wp_upload_dir($post['post_date']); // extract the file name and extension from the url $file_name = basename($url); // get placeholder file in the upload dir with a unique sanitized filename $upload = wp_upload_bits($file_name, 0, '', $post['post_date']); if ($upload['error']) { echo $upload['error']; return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); //Request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'wordpress-importer')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file returned error response %1$d %2$s', 'wordpress-importer'), $headers['response'], get_status_header_desc($headers['response']))); } elseif (isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'wordpress-importer')); } $max_size = $this->max_attachment_size(); if (!empty($max_size) and filesize($upload['file']) > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is too large, limit is %s', size_format($max_size), 'wordpress-importer'))); } // keep track of the old and new urls so we can substitute them later $this->url_remap[$url] = $upload['url']; $this->url_remap[$post['guid']] = $upload['url']; // if the remote url is redirected somewhere else, keep track of the destination too if ($headers['x-final-location'] != $url) { $this->url_remap[$headers['x-final-location']] = $upload['url']; } return $upload; }
function dwtp_attach_images($post_array) { global $image_settings; $post_id = $post_array['ID']; $post_content = $post_array['post_content']; if (empty($post_id)) { gdocs_log("Post ID was null when trying to insert images", "error"); return false; } $attached_guids = array(); if (!empty($post_id) && ($images = get_posts(array('post_parent' => $post_id, 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC')))) { foreach ($images as $image) { $attached_images[] = get_image_send_to_editor($image->ID, '', $image->post_title, $image_settings['image_alignment'], wp_get_attachment_url($image->ID), FALSE, $image_settings['image_size'], $image->post_content); if (preg_match('/gdocs.{10}_/', $image->guid, $guid_match) > 0) { //match guids with the gdocs id inserted $attached_guids[] = $guid_match[0]; //for identifying gdocs images added since before } else { $attached_guids[] = $image->guid; } } } //MF preg_match_all('/<img(.*?)>/', $post_content, $doc_imgs, PREG_OFFSET_CAPTURE); gdocs_log("Image GUIDs: " . implode($attached_guids), "debug"); $upload_dir = wp_upload_dir(); $path = $upload_dir['path'] . '/' . $image_settings['gdocs_image_folder']; //assumed subdir of upload if (!file_exists($path)) { mkdir($path); } $replace_offset = 0; foreach ($doc_imgs[0] as $doc_img) { //$doc_imgs[0] because we only need first pattern, not the subpattern preg_match('/src="https(.*?)"/', $doc_img[0], $src_match); //Use doc_img[0] as we also match position in index [1] $img_hash = 'gdocs' . substr($src_match[1], -10) . '_'; // Pick file name hash from last 10 of gdocs user content hash (hope it's static!) $new_img_tag = ''; $existing_img = array_search($img_hash, $attached_guids); // see if we already have this img as attachment if ($existing_img === FALSE) { // Gdocs defaults to HTTPSing their images, but we can go with normal http for simplicity $headers = wp_get_http('http' . $src_match[1], $path . $img_hash); $contentdisposition = explode('"', $headers["content-disposition"]); //pattern is: inline;filename="xxx.jpg" if (count($contentdisposition) > 1) { $filename = urldecode($contentdisposition[1]); // filename may include URL characters that mess up later $file_ext = strripos($filename, '.'); // look for extension from end of string $name = $file_ext > 0 ? substr($filename, 0, $file_ext) : $filename; //strip out file type from name } else { $filename = 'unknown.jpg'; $name = "unknown"; } $filename = $img_hash . $filename; // for uniqueness combine with hash $newpath = $path . $filename; rename($path . $img_hash, $newpath); $wp_filetype = wp_check_filetype(basename($newpath), null); $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => $name, 'post_name' => $name, 'guid' => $upload_dir['baseurl'] . '/gdocs/' . $filename, 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $newpath, $post_id); $attach_data = wp_generate_attachment_metadata($attach_id, $newpath); wp_update_attachment_metadata($attach_id, $attach_data); gdocs_log("Inserted attachment " . implode($attachment) . " to post {$post_id} and generated metadata:", "debug"); $new_img_tag = get_image_send_to_editor($attach_id, '', $name, $image_settings['image_alignment'], wp_get_attachment_url($image->ID), FALSE, $image_settings['image_size'], ''); gdocs_log("Downloaded https" . $src_match[1] . " as {$filename} (content-disp: " . $headers["content-disposition"] . ", hash {$img_hash} not found, index {$existing_img})\n", "debug"); } else { $new_img_tag = $attached_images[$existing_img]; gdocs_log("{$img_hash} already downloaded (index in guid: {$existing_img})\n", "debug"); } // as we replace in post_content the originally matched positions will be offsetted, so we compensate $post_content = substr_replace($post_content, $new_img_tag, $doc_img[1] + $replace_offset, strlen($doc_img[0])); $replace_offset = $replace_offset + (strlen($new_img_tag) - strlen($doc_img[0])); } $post_array['post_content'] = $post_content; return $post_array; }
/** * Attempt to download a remote file attachment * * @param string $url URL of item to fetch * @param array $post Attachment details * @return array|WP_Error Local file location details on success, WP_Error otherwise */ function fetch_remote_file($url, $post) { // extract the file name and extension from the url $file_name = basename($url); // get placeholder file in the upload dir with a unique, sanitized filename $upload = wp_upload_bits($file_name, 0, '', $post['upload_date']); if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); // request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'radium')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'radium'), esc_html($headers['response']), get_status_header_desc($headers['response']))); } $filesize = filesize($upload['file']); if (isset($headers['content-length']) && $filesize != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'radium')); } if (0 == $filesize) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Zero size file downloaded', 'radium')); } $max_size = (int) $this->max_attachment_size(); if (!empty($max_size) && $filesize > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is too large, limit is %s', 'radium'), size_format($max_size))); } // keep track of the old and new urls so we can substitute them later $this->url_remap[$url] = $upload['url']; $this->url_remap[$post['guid']] = $upload['url']; // r13735, really needed? // keep track of the destination if the remote url is redirected somewhere else if (isset($headers['x-final-location']) && $headers['x-final-location'] != $url) { $this->url_remap[$headers['x-final-location']] = $upload['url']; } return $upload; }
function skyrock_downloadImage($image, $blog) { $upload_dir = wp_upload_dir(); $upload_basedir = $upload_dir['basedir'] . '/skyrock-' . $blog . '/'; if (!is_dir($upload_basedir)) { mkdir($upload_basedir); } $filepath = $upload_basedir . basename($image); if (file_exists($filepath)) { return $upload_dir['baseurl'] . '/skyrock-' . $blog . '/' . basename($image); } $get = wp_get_http($image, $filepath); if ($get['response'] == 200) { $image_orig = str_replace('_small', '', $image, $count); if ($count == 1) { skyrock_downloadImage($image_orig, $blog); } return $upload_dir['baseurl'] . '/skyrock-' . $blog . '/' . basename($image); } else { return false; } }