function media_sideload_image_1($file, $post_id, $desc = null, $return = 'html')
{
    if (!empty($file)) {
        // Set variables for storage, fix file filename for query strings.
        preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches);
        $file_array = array();
        $file_array['name'] = basename($matches[0]);
        // Download file to temp location.
        $file_array['tmp_name'] = download_url($file);
        // If error storing temporarily, return the error.
        if (is_wp_error($file_array['tmp_name'])) {
            return $file_array['tmp_name'];
        }
        // Do the validation and storage stuff.
        $id = media_handle_sideload($file_array, $post_id, $desc);
        // If error storing permanently, unlink.
        if (is_wp_error($id)) {
            @unlink($file_array['tmp_name']);
            return $id;
        }
        /*$fullsize_path = get_attached_file( $id ); // Full path
          if (function_exists('ewww_image_optimizer')) {
            ewww_image_optimizer($fullsize_path, $gallery_type = 4, $converted = false, $new = true, $fullsize = true);
          }*/
        $src = wp_get_attachment_url($id);
    }
    if (!empty($src)) {
        //update_post_meta($post_id, 'image_value', $src);
        set_post_thumbnail($post_id, $id);
        //update_post_meta($post_id, 'Thumbnail', $src);
        return get_post_meta($post_id, 'image_value', true);
    } else {
        return new WP_Error('image_sideload_failed');
    }
}
 public static function image($post_id)
 {
     $images = array();
     $xml = simplexml_load_file('https://unsplash.com/rss');
     foreach ($xml->channel->item as $item) {
         foreach ($item->image->url as $url) {
             $images[] = (string) $url;
         }
     }
     shuffle($images);
     $url = $images[0];
     $tmp = download_url($url);
     $file_array = array('name' => 'new test image', 'tmp_name' => $tmp);
     // Check for download errors
     if (is_wp_error($tmp)) {
         @unlink($file_array['tmp_name']);
     }
     $image_id = media_handle_sideload($file_array, $post_id);
     // Check for handle sideload errors.
     if (is_wp_error($image_id)) {
         @unlink($file_array['tmp_name']);
     }
     if (is_wp_error($image_id)) {
         return $image_id;
     }
 }
Example #3
0
function geoip_detect_update()
{
    // TODO: Currently cron is scheduled but not executed. Remove scheduling.
    if (get_option('geoip-detect-source') != 'auto') {
        return;
    }
    $download_url = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz';
    $download_url = apply_filters('geoip_detect2_download_url', $download_url);
    $outFile = geoip_detect_get_database_upload_filename();
    // Download
    $tmpFile = download_url($download_url);
    if (is_wp_error($tmpFile)) {
        return $tmpFile->get_error_message();
    }
    // Ungzip File
    $zh = gzopen($tmpFile, 'r');
    $h = fopen($outFile, 'w');
    if (!$zh) {
        return __('Downloaded file could not be opened for reading.', 'geoip-detect');
    }
    if (!$h) {
        return sprintf(__('Database could not be written (%s).', 'geoip-detect'), $outFile);
    }
    while (($string = gzread($zh, 4096)) != false) {
        fwrite($h, $string, strlen($string));
    }
    gzclose($zh);
    fclose($h);
    unlink($tmpFile);
    return true;
}
Example #4
0
 public function maxmindUpdate()
 {
     require_once ABSPATH . '/wp-admin/includes/file.php';
     $download_url = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz';
     $download_url = apply_filters('geoip_detect2_download_url', $download_url);
     $outFile = $this->maxmindGetUploadFilename();
     // Download
     $tmpFile = download_url($download_url);
     if (is_wp_error($tmpFile)) {
         return $tmpFile->get_error_message();
     }
     // Ungzip File
     $zh = gzopen($tmpFile, 'r');
     $h = fopen($outFile, 'w');
     if (!$zh) {
         return __('Downloaded file could not be opened for reading.', 'geoip-detect');
     }
     if (!$h) {
         return sprintf(__('Database could not be written (%s).', 'geoip-detect'), $outFile);
     }
     while (($string = gzread($zh, 4096)) != false) {
         fwrite($h, $string, strlen($string));
     }
     gzclose($zh);
     fclose($h);
     unlink($tmpFile);
     return true;
 }
 protected function getDownloadUrl()
 {
     global $wp_filesystem;
     $this->skin->feedback('download_envato');
     $package_filename = 'js_composer.zip';
     $res = $this->fs_connect(array(WP_CONTENT_DIR));
     if (!$res) {
         return new WP_Error('no_credentials', __("Error! Can't connect to filesystem", 'js_composer'));
     }
     $username = WPBakeryVisualComposerSettings::get('envato_username');
     $api_key = WPBakeryVisualComposerSettings::get('envato_api_key');
     $purchase_code = WPBakeryVisualComposerSettings::get('js_composer_purchase_code');
     if (empty($username) || empty($api_key) || empty($purchase_code)) {
         return new WP_Error('no_credentials', __('Error! Envato username, api key and your purchase code are required for downloading updates from Envato marketplace for the Visual Composer. Visit <a href="' . admin_url('options-general.php?page=wpb_vc_settings&tab=updater') . '' . '">Settings</a> to fix.', 'js_composer'));
     }
     $json = wp_remote_get($this->envatoDownloadPurchaseUrl($username, $api_key, $purchase_code));
     $result = json_decode($json['body'], true);
     if (!isset($result['download-purchase']['download_url'])) {
         return new WP_Error('no_credentials', __('Error! Envato API error' . (isset($result['error']) ? ': ' . $result['error'] : '.'), 'js_composer'));
     }
     $result['download-purchase']['download_url'];
     $download_file = download_url($result['download-purchase']['download_url']);
     if (is_wp_error($download_file)) {
         return $download_file;
     }
     $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade_tmp/js_composer_envato_package';
     if (is_dir($upgrade_folder)) {
         $wp_filesystem->delete($upgrade_folder);
     }
     $result = unzip_file($download_file, $upgrade_folder);
     if ($result && is_file($upgrade_folder . '/' . $package_filename)) {
         return $upgrade_folder . '/' . $package_filename;
     }
     return new WP_Error('no_credentials', __('Error on unzipping package', 'js_composer'));
 }
Example #6
0
 public function load_thumbnail($post_id, $url, $desc = null)
 {
     if (!empty($url)) {
         // Download file to temp location
         $tmp = download_url($url);
         // Set variables for storage
         // fix file filename for query strings
         preg_match('/[^\\?]+\\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $url, $matches);
         if (isset($matches[0])) {
             $file_array['name'] = basename($matches[0]);
         }
         $file_array['tmp_name'] = $tmp;
         // If error storing temporarily, unlink
         if (is_wp_error($tmp)) {
             @unlink($file_array['tmp_name']);
             $file_array['tmp_name'] = '';
         }
         // do the validation and storage stuff
         $id = media_handle_sideload($file_array, $post_id, $desc);
         if (!is_wp_error($id)) {
             return $id;
         }
         // If error storing permanently, unlink
         @unlink($file_array['tmp_name']);
     }
     return false;
 }
Example #7
0
/**
 * Similar to `media_sideload_image` except that it simply returns the attachment's ID on success
 *
 * @param (string) $file the url of the image to download and attach to the post
 * @param (integer) $post_id the post ID to attach the image to
 * @param (string) $desc an optional description for the image
 *
 * @since 0.5.2
 */
function largo_media_sideload_image($file, $post_id, $desc = null)
{
    if (!empty($file)) {
        include_once ABSPATH . 'wp-admin/includes/image.php';
        include_once ABSPATH . 'wp-admin/includes/file.php';
        include_once ABSPATH . 'wp-admin/includes/media.php';
        // Set variables for storage, fix file filename for query strings.
        preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches);
        $file_array = array();
        $file_array['name'] = basename($matches[0]);
        // Download file to temp location.
        $file_array['tmp_name'] = download_url($file);
        // If error storing temporarily, return the error.
        if (is_wp_error($file_array['tmp_name'])) {
            return $file_array['tmp_name'];
        }
        // Do the validation and storage stuff.
        $id = media_handle_sideload($file_array, $post_id, $desc);
        // If error storing permanently, unlink.
        if (is_wp_error($id)) {
            @unlink($file_array['tmp_name']);
        }
        return $id;
    }
}
 public function import_settings()
 {
     $file_url = base64_decode($_POST['file_url']);
     $temporary_file = "";
     try {
         include_once ABSPATH . 'wp-admin/includes/file.php';
         //Contains download_url
         $temporary_file = download_url($file_url);
         if (is_wp_error($temporary_file)) {
             throw new Exception('Error: ' . $temporary_file->get_error_message());
         } else {
             if ($this->import_seo_settings($temporary_file)) {
                 $information['success'] = true;
             } else {
                 throw new Exception(__('Settings could not be imported:', 'wordpress-seo'));
             }
         }
     } catch (Exception $e) {
         $information['error'] = $e->getMessage();
     }
     if (file_exists($temporary_file)) {
         unlink($temporary_file);
     }
     MainWPHelper::write($information);
 }
 public static function update_database()
 {
     set_time_limit(0);
     $outFile = self::get_upload_file_path();
     // for download_url()
     require_once ABSPATH . 'wp-admin/includes/file.php';
     $tmpFile = \download_url(self::SOURCE_URL);
     if (is_wp_error($tmpFile)) {
         die($tmpFile->get_error_message());
     }
     $zh = gzopen($tmpFile, 'rb');
     $h = fopen($outFile, 'wb');
     if (!$zh) {
         die('Downloaded file could not be opened for reading.');
     }
     if (!$h) {
         die(sprintf('Database could not be written (%s).', $outFile));
     }
     while (!gzeof($zh)) {
         fwrite($h, gzread($zh, 4096));
     }
     gzclose($zh);
     fclose($h);
     unlink($tmpFile);
     if (!self::is_db_valid()) {
         die(sprintf('Checksum does not match (%s).', $outFile));
     }
 }
Example #10
0
 private function create_file($name, $vararray)
 {
     $string = $this->generate_csv_string($vararray);
     $upload_dir = wp_upload_dir();
     $file = $upload_dir['path'] . "/" . $name . ".csv";
     file_put_contents($file, $string);
     $url = $upload_dir['url'] . "/" . $name . ".csv";
     $tmp = download_url($url);
     $post_id = $this->options[$this->page_id_field];
     $file_array = array();
     // Set variables for storage
     // fix file filename for query strings
     preg_match('/[^\\?]+\\.(jpg|jpe|jpeg|gif|png|csv)/i', $url, $matches);
     $file_array['name'] = basename($matches[0]);
     $file_array['tmp_name'] = $tmp;
     // If error storing temporarily, unlink
     if (is_wp_error($tmp)) {
         print_r($tmp);
         @unlink($file_array['tmp_name']);
         $file_array['tmp_name'] = '';
     }
     // do the validation and storage stuff
     $id = media_handle_sideload($file_array, $post_id, $desc);
     // If error storing permanently, unlink
     if (is_wp_error($id)) {
         print_r($id);
         @unlink($file_array['tmp_name']);
         return $id;
     }
     $src = wp_get_attachment_url($id);
     echo $src;
 }
 /**
  * Import images from Unsplash into your Media Library.
  *
  * ## OPTIONS
  *
  * [--count=<number>]
  * : How many media items to generate. Default: 10
  *
  * [--media_author=<login>]
  * : The author of the generated media. Default: none
  *
  * [--media_date=<yyyy-mm-dd|random>]
  * : The date of the generated media. Default: current date
  *
  * [--media_dimensions=<dimensions>]
  * : The dimensions of the generated media. Default: none
  *
  * ## EXAMPLES
  *
  *     wp unsplash --count=10
  *     wp unsplash --media_date=random
  *     wp unsplash --media_dimensions=1080x720
  */
 public function __invoke($args, $assoc_args = array())
 {
     $defaults = array('count' => 10, 'media_author' => false, 'media_date' => current_time('mysql'), 'media_dimensions' => false);
     extract(array_merge($defaults, $assoc_args), EXTR_SKIP);
     if ($media_author) {
         $user_fetcher = new \WP_CLI\Fetchers\User();
         $media_author = $user_fetcher->get_check($media_author)->ID;
     }
     $url = 'https://source.unsplash.com/random/';
     if ($media_dimensions) {
         $url .= $media_dimensions;
     }
     $notify = \WP_CLI\Utils\make_progress_bar('Generating media', $count);
     for ($i = 0; $i < $count; $i++) {
         $tmp_file = download_url($url);
         if (!is_wp_error($tmp_file)) {
             $this->_process_downloaded_image($tmp_file, $media_author, $media_date);
         } else {
             WP_CLI::warning('Could not download image from Unsplash API.');
         }
         if (file_exists($tmp_file)) {
             unlink($tmp_file);
         }
         $notify->tick();
     }
     $notify->finish();
 }
 static function uploadImage($img_url)
 {
     include_once ABSPATH . 'wp-admin/includes/file.php';
     //Contains download_url
     //Download $img_url
     $temporary_file = download_url($img_url);
     if (is_wp_error($temporary_file)) {
         throw new Exception('Error: ' . $temporary_file->get_error_message());
     } else {
         $upload_dir = wp_upload_dir();
         $local_img_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . basename($img_url);
         //Local name
         $local_img_url = $upload_dir['url'] . '/' . basename($img_url);
         $moved = @rename($temporary_file, $local_img_path);
         if ($moved) {
             $wp_filetype = wp_check_filetype(basename($img_url), null);
             //Get the filetype to set the mimetype
             $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($img_url)), 'post_content' => '', 'post_status' => 'inherit');
             $attach_id = wp_insert_attachment($attachment, $local_img_path);
             //Insert the image in the database
             require_once ABSPATH . 'wp-admin/includes/image.php';
             $attach_data = wp_generate_attachment_metadata($attach_id, $local_img_path);
             wp_update_attachment_metadata($attach_id, $attach_data);
             //Update generated metadata
             return array('id' => $attach_id, 'url' => $local_img_url);
         }
     }
     if (file_exists($temporary_file)) {
         unlink($temporary_file);
     }
     return null;
 }
Example #13
0
/**
 * Cron - Thumbnail extraction
 */
function wp_rp_upload_attachment($url, $post_id)
{
    /* Parts copied from wp-admin/includes/media.php:media_sideload_image */
    include_once ABSPATH . 'wp-admin/includes/file.php';
    include_once ABSPATH . 'wp-admin/includes/media.php';
    include_once ABSPATH . 'wp-admin/includes/image.php';
    $tmp = download_url($url);
    preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $url, $matches);
    $file_array['name'] = sanitize_file_name(urldecode(basename($matches[0])));
    $file_array['tmp_name'] = $tmp;
    if (is_wp_error($tmp)) {
        @unlink($file_array['tmp_name']);
        return false;
    }
    $post_data = array('guid' => $url, 'post_title' => 'rp_' . $file_array['name']);
    $attachment_id = media_handle_sideload($file_array, $post_id, null, $post_data);
    if (is_wp_error($attachment_id)) {
        @unlink($file_array['tmp_name']);
        return false;
    }
    $attach_data = wp_get_attachment_metadata($attachment_id);
    $platform_options = wp_rp_get_platform_options();
    $min_width = $platform_options['custom_size_thumbnail_enabled'] ? WP_RP_CUSTOM_THUMBNAILS_WIDTH : WP_RP_THUMBNAILS_WIDTH;
    $min_height = $platform_options['custom_size_thumbnail_enabled'] ? WP_RP_CUSTOM_THUMBNAILS_HEIGHT : WP_RP_THUMBNAILS_HEIGHT;
    if (!$attach_data || $attach_data['width'] < $min_width || $attach_data['height'] < $min_height) {
        wp_delete_attachment($attachment_id);
        return false;
    }
    return $attachment_id;
}
 public function install($name)
 {
     if (!defined('FS_METHOD')) {
         define('FS_METHOD', 'direct');
     }
     WP_Filesystem();
     $params = array('apikey' => self::API_KEY, 'name' => $name, 'site' => get_site_url(), 'version' => BACKUP_TO_DROPBOX_VERSION);
     $download_file = download_url("{$this->get_url(true)}/download?" . http_build_query($params));
     if (is_wp_error($download_file)) {
         $errorMsg = $download_file->get_error_message();
         if ($errorMsg == 'Forbidden') {
             $errorMsg = __('access is deined, this could be because your payment has expired.', 'wpbtd');
         } else {
             $errorMsg = __('you have exceeded your download limit for this extension on this site.', 'wpbtd');
         }
         throw new Exception(__('There was an error downloading your premium extension because', 'wpbtd') . " {$errorMsg}");
     }
     $result = unzip_file($download_file, EXTENSIONS_DIR);
     if (is_wp_error($result)) {
         $errorCode = $result->get_error_code();
         $errorMsg = strtolower($result->get_error_message());
         if (in_array($errorCode, array('copy_failed', 'incompatible_archive'))) {
             $errorMsg = sprintf(__("'%s' is not writeable.", 'wpbtd'), EXTENSIONS_DIR);
         }
         throw new Exception(__('There was an error installing your premium extension because', 'wpbtd') . " {$errorMsg}");
     }
     unlink($download_file);
     $extensions = get_option('wpb2d-premium-extensions');
     $extensions[$name] = EXTENSIONS_DIR . 'class-' . str_replace(' ', '-', strtolower($name)) . '.php';
     update_option('wpb2d-premium-extensions', $extensions);
     include_once $extensions[$name];
     return $this->get_instance($name);
 }
function setFeaturedImage($post_id, $url, $featuredImageTitle)
{
    // Download file to temp location and setup a fake $_FILE handler
    // with a new name based on the post_id
    $tmp_name = download_url($url);
    //								echo $tmp_name;
    $file_array['name'] = $post_id . '-thumb.jpg';
    // new filename based on slug
    $file_array['tmp_name'] = $tmp_name;
    // If error storing temporarily, unlink
    if (is_wp_error($tmp_name)) {
        @unlink($file_array['tmp_name']);
        $file_array['tmp_name'] = '';
    }
    // do validation and storage .  Make a description based on the Post_ID
    $attachment_id = media_handle_sideload($file_array, $post_id, 'Thumbnail for ' . $post_id);
    // If error storing permanently, unlink
    if (is_wp_error($attachment_id)) {
        $error_string = $attachment_id->get_error_message();
        @unlink($file_array['tmp_name']);
        return;
    }
    // Set as the post attachment
    $post_result = add_post_meta($post_id, '_thumbnail_id', $attachment_id, true);
    //					echo $post_result);
}
Example #16
0
    /**
     * Render the page.
     *
     * @return void
     * @author Kavin Gray
     **/
    function wpui_update_page_callback()
    {
        global $wpui_fs;
        // $wpui_fs = new WP_Filesystem();
        // $filename = '';
        // $resp = wp_remote_get( "https://github.com/kavingray/wp-ui/zipball/master" );
        $resp = download_url("https://github.com/kavingray/wp-ui/zipball/master");
        // $resp = wp_remote_get( "http://kav.in/favicon.ico" );
        // if ( ! is_wp_error( $resp ) && $resp[ 'response' ][ 'code' ] == 200 ) {
        //
        // 	if ( ! empty( $resp[ 'filename' ] ) ) {
        // 		$filename = $resp[ 'filename' ];
        // 	} elseif ( isset( $resp[ 'headers' ][ 'content-disposition' ] ) ) {
        // 		$contdisp = $resp[ 'headers' ][ 'content-disposition' ];
        // 		preg_match( '/filename=(.*)$/im', $contdisp, $matches );
        // 		echo '<pre>';
        // 		echo '$matches';
        // 		echo "\n=========================================\n";
        // 		var_export($matches);
        // 		echo '</pre>';
        // 	}
        //
        // }
        die;
        ?>
		<!-- .wrap -->
		<div class="wrap">
			<div class="icon32" id="icon-plugins"></div>
			<h2>WP UI Custom Update</h2>
			<p>This page toggles between WordPress and GitHub distributed WP UI versions. GitHub version is usually the most recent.</p>
			<form method="post">

				<label for="github"><input type="radio" id="github" value="github" value="github"/> <span>GitHub Version</span></label> <br />
				<label for="wp"><input type="radio" id="wp" value="wp" value="wp"/><span>Roll back to WordPress distributed Version</span></label> <br />

				<!-- .submit-action -->
				<div class="submit-action">
					<input type="submit" id="perform" name="perform" class="button-primary" />
				</div>
				<!-- /.submit-action -->

			</form>


			<hr />
			<p>Return to <a href="<?php 
        echo admin_url("options-general.php?page=wpUI-options");
        ?>
" title="Return to WP UI Options">WP UI Options page</a> | Visit <a href="<?php 
        echo site_url();
        ?>
"><?php 
        bloginfo('name');
        ?>
</a></p>
		</div>
		<!-- /.wrap -->

		<?php 
    }
Example #17
0
function geoip_detect_update()
{
    $download_url = 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz';
    $outFile = geoip_detect_get_database_upload_filename();
    // Download
    $tmpFile = download_url($download_url);
    if (is_wp_error($tmpFile)) {
        return $tmpFile->get_error_message();
    }
    // Ungzip File
    $zh = gzopen($tmpFile, 'r');
    $h = fopen($outFile, 'w');
    if (!$zh) {
        return __('Downloaded file could not be opened for reading.', 'geoip-detect');
    }
    if (!$h) {
        return sprintf(__('Database could not be written (%s).', 'geoip-detect'), $outFile);
    }
    while (($string = gzread($zh, 4096)) != false) {
        fwrite($h, $string, strlen($string));
    }
    gzclose($zh);
    fclose($h);
    //unlink($tmpFile);
    return true;
}
Example #18
0
/**
 * media_sideload_image, but returns ID
 * @param  string  $image_url [description]
 * @param  boolean $post_id   [description]
 * @return [type]             [description]
 */
function custom_media_sideload_image($image_url = '', $post_id = false)
{
    require_once ABSPATH . 'wp-admin/includes/file.php';
    $tmp = download_url($image_url);
    // Set variables for storage
    // fix file filename for query strings
    preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $image_url, $matches);
    $file_array['name'] = basename($matches[0]);
    $file_array['tmp_name'] = $tmp;
    // If error storing temporarily, unlink
    if (is_wp_error($tmp)) {
        @unlink($file_array['tmp_name']);
        $file_array['tmp_name'] = '';
    }
    $time = current_time('mysql');
    $file = wp_handle_sideload($file_array, array('test_form' => false), $time);
    if (isset($file['error'])) {
        return new WP_Error('upload_error', $file['error']);
    }
    $url = $file['url'];
    $type = $file['type'];
    $file = $file['file'];
    $title = preg_replace('/\\.[^.]+$/', '', basename($file));
    $parent = (int) absint($post_id) > 0 ? absint($post_id) : 0;
    $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => $parent, 'post_title' => $title, 'post_content' => '');
    $id = wp_insert_attachment($attachment, $file, $parent);
    if (!is_wp_error($id)) {
        require_once ABSPATH . 'wp-admin/includes/image.php';
        $data = wp_generate_attachment_metadata($id, $file);
        wp_update_attachment_metadata($id, $data);
    }
    return $id;
}
 /**
  * 패키지 파일의 압축을 풀고 설치한다.
  * @param string $package
  * @param string $version
  * @param string $plugins_dir
  * @return boolean
  */
 public function install($package, $version, $plugins_dir)
 {
     $download_file = download_url("{$this->server}/download-{$package}?version={$version}");
     if (is_wp_error($download_file)) {
         unlink($download_file);
         echo '<script>alert("다운로드에 실패 했습니다. 다시 시도해 주세요.");</script>';
         return false;
     }
     // See #15789 - PclZip uses string functions on binary data, If it's overloaded with Multibyte safe functions the results are incorrect.
     if (ini_get('mbstring.func_overload') && function_exists('mb_internal_encoding')) {
         $previous_encoding = mb_internal_encoding();
         mb_internal_encoding('ISO-8859-1');
     }
     require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
     $archive = new PclZip($download_file);
     $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
     unlink($download_file);
     if ($archive_files) {
         if (is_writable($plugins_dir)) {
             foreach ($archive_files as $file) {
                 if ($file['folder']) {
                     $extract_result = wp_mkdir_p($plugins_dir . '/' . $file['filename']);
                 } else {
                     $extract_result = file_put_contents($plugins_dir . '/' . $file['filename'], $file['content']);
                 }
                 if (!$extract_result) {
                     break;
                 }
             }
             if (!$extract_result) {
                 echo '<script>alert("FTP로 파일 쓰기에 실패했습니다. 서버 관리자에게 문의하시기 바랍니다.");</script>';
                 return false;
             }
         } else {
             global $wp_filesystem;
             $target_dir = trailingslashit($wp_filesystem->find_folder($plugins_dir));
             foreach ($archive_files as $file) {
                 if ($file['folder']) {
                     if ($wp_filesystem->is_dir($target_dir . $file['filename'])) {
                         continue;
                     } else {
                         $extract_result = $wp_filesystem->mkdir($target_dir . $file['filename'], FS_CHMOD_DIR);
                     }
                 } else {
                     $extract_result = $wp_filesystem->put_contents($target_dir . $file['filename'], $file['content'], FS_CHMOD_FILE);
                 }
                 if (!$extract_result) {
                     break;
                 }
             }
             if (!$extract_result) {
                 echo '<script>alert("FTP로 파일 쓰기에 실패했습니다. 서버 관리자에게 문의하시기 바랍니다.");</script>';
                 return false;
             }
         }
     }
     return true;
 }
function wp_behance_project_display_do_daily()
{
    //sync projects from behance
    $behance_username = get_option('behance_username');
    $behance_api = get_option('behance_api');
    $behance_url = "http://www.behance.net/v2/users/" . $behance_username . "/projects?api_key=" . $behance_api;
    $temp_file_location = download_url($behance_url);
    $file_content = file_get_contents($temp_file_location);
    update_option('wp_behance_projects', $file_content);
}
/**
 * Add track details when a post is saved.
 *
 * @param int 	$post_id 		The post ID.
 * @param post 	$post 			The post object.
 * @param bool 	$update 		Whether this is an existing post being updated or not.
 */
function soundpress_add_track_details_to_post($post_id, $post, $update)
{
    $trackurl = get_post_meta($post_id, 'soundpress_soundcloud_url', true);
    if (wp_is_post_revision($post_id)) {
        return;
    }
    if ($trackurl) {
        $track_details = soundcloud_remote_get($trackurl);
        if (is_object($track_details)) {
            // Check for thumbnail. If not present, get the board Image
            if (!has_post_thumbnail($post_id)) {
                $thumbnailurl = $track_details->artwork_url;
                if (empty($thumbnailurl)) {
                    $thumbnailurl = $track_details->user->avatar_url;
                }
                $tmp = download_url($thumbnailurl);
                if (is_wp_error($tmp)) {
                }
                $desc = get_the_title($post_id);
                $file_array = array();
                // Set variables for storage
                // fix file filename for query strings
                preg_match('/[^\\?]+\\.(jpg|jpe|jpeg|gif|png)/i', $thumbnailurl, $matches);
                $file_array['name'] = basename($matches[0]);
                $file_array['tmp_name'] = $tmp;
                // If error storing temporarily, unlink
                if (is_wp_error($tmp)) {
                    @unlink($file_array['tmp_name']);
                    $file_array['tmp_name'] = '';
                }
                // do the validation and storage stuff
                $id = media_handle_sideload($file_array, $post_id, $desc);
                // If error storing permanently, unlink
                if (is_wp_error($id)) {
                    @unlink($file_array['tmp_name']);
                    return $id;
                }
                set_post_thumbnail($post_id, $id);
            }
            // Check for Description
            if ("" == get_the_content()) {
                $postcontentarray = array('ID' => $post_id, 'post_content' => $track_details->description);
                // Update the post into the database
                wp_update_post($postcontentarray);
            }
            // Get The Duration
            $durationseconds = $track_details->duration / 1000;
            update_post_meta($post_id, 'podcast_duration', esc_attr($durationseconds));
            if (TRUE == $track_details->downloadable) {
                $download_url = esc_attr($track_details->download_url);
                update_post_meta($post_id, 'podcast_download_url', $download_url);
            }
        }
    }
}
Example #22
0
function FetchRemoteListFile($url, $destination)
{
    // fetch remote list file from $url and put it as $destination locally
    require_once ABSPATH . 'wp-admin/includes/file.php';
    $temp_file = download_url($url, LISTFILETIMEOUT);
    if (!is_wp_error($temp_file)) {
        rename($temp_file, $destination);
        return $destination;
    }
    return false;
}
Example #23
0
 protected function getDownloadUrl()
 {
     require_once ABSPATH . '/wp-admin/includes/file.php';
     WP_Filesystem();
     global $wp_filesystem;
     $this->skin->feedback('download_envato');
     $package_filename = 'Ultimate_VC_Addons.zip';
     $res = $this->fs_connect(array(WP_CONTENT_DIR));
     if (!$res) {
         return new WP_Error('no_credentials', __("Error! Can't connect to filesystem", 'ultimate_vc'));
     }
     $ultimate_keys = get_option('ultimate_keys');
     $username = trim($ultimate_keys['envato_username']);
     $api_key = trim($ultimate_keys['envato_api_key']);
     $purchase_code = trim($ultimate_keys['ultimate_purchase_code']);
     if (empty($username) || empty($api_key) || empty($purchase_code)) {
         return new WP_Error('no_credentials', __('Error! Envato username, api key and your purchase code are required for downloading updates from Envato marketplace for the Visual Composer.', 'ultimate_vc') . ' ' . __('Visit', 'ultimate_vc') . ' <a href="' . admin_url('options-general.php?page=wpb_vc_settings&tab=updater') . '' . '">' . __('Settings', 'ultimate_vc') . '</a> ' . _('to fix.', 'ultimate_vc'));
     }
     $json = wp_remote_get($this->envatoDownloadPurchaseUrl($username, $api_key, $purchase_code));
     $result = json_decode($json['body'], true);
     if (!isset($result['wp-download']['url'])) {
         return new WP_Error('no_credentials', __('Error! Envato API error' . (isset($result['error']) ? ': ' . $result['error'] : '.'), 'ultimate_vc'));
     }
     $download_file = download_url($result['wp-download']['url']);
     if (is_wp_error($download_file)) {
         $download_file = file_get_contents($result['wp-download']['url']);
         if (is_wp_error($download_file)) {
             return $download_file;
         }
     }
     $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade_tmp/ultimate_envato_package';
     if (is_dir($upgrade_folder)) {
         $wp_filesystem->delete($upgrade_folder);
     } else {
         mkdir($upgrade_folder, 0755);
     }
     $is_unzip = unzip_file($download_file, $upgrade_folder);
     if ($is_unzip) {
         $result = copy($result['wp-download']['url'], $upgrade_folder . '/' . $package_filename);
         if ($result) {
             return $upgrade_folder . '/' . $package_filename;
         } else {
             if (file_exists($upgrade_folder . '/Ultimate_VC_Addons') && is_dir($upgrade_folder . '/Ultimate_VC_Addons')) {
                 $this->Ultimate_Zip($upgrade_folder . '/Ultimate_VC_Addons', $upgrade_folder . '/' . $package_filename);
                 if (is_file($upgrade_folder . '/' . $package_filename)) {
                     return $upgrade_folder . '/' . $package_filename;
                 }
                 return new WP_Error('no_credentials', __('Error while zipping plugin', 'ultimate_vc'));
             }
             return new WP_Error('no_credentials', __('Error while coping zip from Remote server, allow_url_fopen is disabled on your server.', 'ultimate_vc'));
         }
     }
     return new WP_Error('no_credentials', __('Error on unzipping package', 'ultimate_vc'));
 }
Example #24
0
function get_php_net()
{
    $st = @stat(CACHEFILE);
    if ($st === false) {
        // fallthrough and download it
        return download_url();
    }
    if (CACHETIME < time() - $st['mtime']) {
        return get_cached_data();
    }
    return download_url();
}
function connotea_get_tags_for_user($username)
{
    global $config;
    $url = "http://www.connotea.org/data/tags/user/{$username}";
    $results = download_url($url, $config['connotea_username'], $config['connotea_password']);
    $matches = array();
    preg_match_all("/<rdf:value>(.*?)<\\/rdf\\:value>(?:.*?)<postCount>(\\d+)<\\/postCount>/si", $results, $matches);
    $tags = $matches[1];
    $counts = $matches[2];
    $return = array();
    for ($i = 0; $i < sizeof($tags); $i++) {
        $return[mysql_escape_string($tags[$i])] = mysql_escape_string($counts[$i]);
    }
    return $return;
}
Example #26
0
 function install($url, $args)
 {
     global $wpdb, $wp_filesystem;
     /*
      * Use WordPress WP_Filesystem methods to install DB
      */
     // Check Credentials
     if (false === ($creds = request_filesystem_credentials($url, NULL, false, false, $args))) {
         // Not yet valid, a form will have been presented - drop out.
         return array('HideForm' => true);
     }
     if (!WP_Filesystem($creds)) {
         // our credentials were no good, ask the user for them again
         request_filesystem_credentials($url, NULL, true, false, $args);
         return array('HideForm' => true);
     }
     /* Skip the download if it has already been done */
     if (!is_readable($this->temp_file)) {
         $temp_file = download_url($this->remote_file);
         if (is_wp_error($temp_file)) {
             return array('Success' => False, 'Message' => __('ip2nation install: Failed to download file: ', 'amazon-link') . $temp_file->get_error_message());
         }
         $result = unzip_file($temp_file, $this->temp_dir);
         if (is_wp_error($result)) {
             unlink($temp_file);
             return array('Success' => False, 'Message' => __('ip2nation install: Failed to unzip file: ', 'amazon-link') . $result->get_error_message());
         }
     }
     // Install the database
     // This can take a while on slow servers, disable aborts until
     // I do a proper jquery progress version.
     set_time_limit(0);
     ignore_user_abort(true);
     // Process database file
     $sql = $wp_filesystem->get_contents($this->temp_file);
     $lines = explode(';', $sql);
     unset($sql);
     $queries = 0;
     foreach ($lines as $line) {
         $line = trim($line);
         if (!empty($line) && $wpdb->query($line . ';') === FALSE) {
             return array('Success' => False, 'Message' => '=' . $line . '=' . sprintf(__('ip2nation install: Database downloaded and unzipped but failed to install [%s]', 'amazon-link'), $wpdb->last_error));
         }
         $queries++;
     }
     $wp_filesystem->delete($this->temp_dir, true);
     return array('Success' => True, 'Message' => sprintf(__('ip2nation install: Database downloaded and installed successfully. %s queries executed.', 'amazon-link'), $queries));
 }
Example #27
0
 /**
  * Get a fresh icon image from grabicon.com and cache it.
  */
 public function sideload_icon()
 {
     require_once ABSPATH . 'wp-admin/includes/file.php';
     require_once ABSPATH . 'wp-admin/includes/media.php';
     require_once ABSPATH . 'wp-admin/includes/image.php';
     $grab_base_url = 'http://grabicon.com/icon';
     $home_url_parts = parse_url(home_url());
     $grab_url = add_query_arg(array('size' => $this->size, 'domain' => $home_url_parts['host'], 'origin' => $home_url_parts['host'], 'reset' => 'true', 'key' => self::$api_key), $grab_base_url);
     $file_info = array('name' => 'prompt-site-icon-' . $this->size . '.png', 'tmp_name' => download_url($grab_url, 5));
     if (is_wp_error($file_info['tmp_name'])) {
         return;
     }
     $id = media_handle_sideload($file_info, 0);
     if (!is_wp_error($id)) {
         $this->attachment_id = $id;
     }
 }
Example #28
0
function loadImg($url)
{
    // во фронтэнде нужны эти файлы
    require_once ABSPATH . "wp-admin" . '/includes/image.php';
    require_once ABSPATH . "wp-admin" . '/includes/file.php';
    require_once ABSPATH . "wp-admin" . '/includes/media.php';
    $file_array = array();
    $tmp = download_url($url);
    // корректируем умя файла в строках запроса.
    $nameR = end(explode('.', end(explode('/', $url))));
    $file_array['name'] = rand(100000, 999999) . '.' . $nameR;
    $file_array['tmp_name'] = $tmp;
    $id = media_handle_sideload($file_array, 0);
    // удалим временный файл
    @unlink($file_array['tmp_name']);
    return $id;
}
/**
 * An enhanced version of WP's media_sideload_image function.
 *
 * If media_sideload_image fails, the file is downloaded manually
 * as an image, inserted as an attachment, and attached to the post.
 * 
 * @since 3.5.1
 */
function wprss_media_sideload_image($file, $post_id, $desc = null)
{
    try {
        if (!empty($file)) {
            // Download file to temp location
            $tmp = download_url($file);
            // Set variables for storage
            // fix file filename for query strings
            preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches);
            if (count($matches) > 0) {
                $file_array['name'] = basename($matches[0]);
            } else {
                preg_match('/[\\/\\?\\=\\&]([^\\/\\?\\=\\&]*)[\\?]*$/i', $file, $matches2);
                if (count($matches2) > 1) {
                    $file_array['name'] = $matches2[1] . '.png';
                } else {
                    @unlink($tmp);
                    return "<img src='{$file}' alt='' />";
                }
            }
            $file_array['tmp_name'] = $tmp;
            // If error storing temporarily, unlink
            if (is_wp_error($tmp)) {
                @unlink($file_array['tmp_name']);
                $file_array['tmp_name'] = '';
            }
            // do the validation and storage stuff
            $id = media_handle_sideload($file_array, $post_id, $desc);
            // If error storing permanently, unlink
            if (is_wp_error($id)) {
                @unlink($file_array['tmp_name']);
                return "<img src='{$file}' alt='' />";
            }
            $src = wp_get_attachment_url($id);
        }
        // Finally check to make sure the file has been saved, then return the html
        if (!empty($src)) {
            $alt = isset($desc) ? esc_attr($desc) : '';
            $html = "<img src='{$src}' alt='{$alt}' />";
            return $html;
        }
    } catch (Exception $e) {
        return "<img src='{$file}' alt='' />";
    }
}
 public function install($name, $file)
 {
     if (!defined('FS_METHOD')) {
         define('FS_METHOD', 'direct');
     }
     WP_Filesystem();
     $params = array('key' => $this->key, 'name' => $name, 'site' => get_site_url());
     $download_file = download_url("{$this->get_url()}/download?" . http_build_query($params));
     if (is_wp_error($download_file)) {
         $errorMsg = $download_file->get_error_messages();
         throw new Exception(__('There was an error downloading your premium extension') . ' - ' . $errorMsg[0]);
     }
     $result = unzip_file($download_file, EXTENSIONS_DIR);
     if (is_wp_error($result)) {
         $errorMsg = $result->get_error_messages();
         if ($errorMsg[0] == "Incompatible Archive.") {
             $errorMsg[0] = file_get_contents($download_file);
         }
         unlink($download_file);
         throw new Exception(__('There was an error installing your premium extension') . ' - ' . $errorMsg[0]);
     }
     unlink($download_file);
     $extensions = get_option('backup-to-dropbox-premium-extensions');
     $extensions[$name] = $file;
     update_option('backup-to-dropbox-premium-extensions', $extensions);
 }