Example #1
0
 /**
  * Save the submitted image as a temporary file.
  *
  * @todo Revisit file handling.
  *
  * @param string $img Base64 encoded image.
  * @return false|string File name on success, false on failure.
  */
 protected function save_temp_image($img)
 {
     // Strip the "data:image/png;base64," part and decode the image.
     $img = explode(',', $img);
     $img = isset($img[1]) ? base64_decode($img[1]) : base64_decode($img[0]);
     if (!$img) {
         return false;
     }
     // Upload to tmp folder.
     $filename = 'user-feedback-' . date('Y-m-d-H-i');
     $tempfile = wp_tempnam($filename);
     if (!$tempfile) {
         return false;
     }
     // WordPress adds a .tmp file extension, but we want .png.
     if (rename($tempfile, $filename . '.png')) {
         $tempfile = $filename . '.png';
     }
     if (!WP_Filesystem(request_filesystem_credentials(''))) {
         return false;
     }
     /**
      * WordPress Filesystem API.
      *
      * @var \WP_Filesystem_Base $wp_filesystem
      */
     global $wp_filesystem;
     $success = $wp_filesystem->put_contents($tempfile, $img);
     if (!$success) {
         return false;
     }
     return $tempfile;
 }
Example #2
0
 function download_url($url)
 {
     /*
     	http://core.trac.wordpress.org/browser/trunk/wp-admin/includes/file.php?rev=17928#L467
     	changes:  
     		- wanted a timeout < 5 min
     		- SSL fails when trying to access github
     */
     if (!$url) {
         return new WP_Error('http_no_url', __('Invalid URL Provided.'));
     }
     $tmpfname = wp_tempnam($url);
     if (!$tmpfname) {
         return new WP_Error('http_no_file', __('Could not create Temporary file.'));
     }
     $handle = @fopen($tmpfname, 'wb');
     if (!$handle) {
         return new WP_Error('http_no_file', __('Could not create Temporary file.'));
     }
     // This! is the one line I wanted to get at
     $response = wp_remote_get($url, array('sslverify' => false, 'timeout' => 30));
     if (is_wp_error($response)) {
         fclose($handle);
         unlink($tmpfname);
         return $response;
     }
     if ($response['response']['code'] != '200') {
         fclose($handle);
         unlink($tmpfname);
         return new WP_Error('http_404', trim($response['response']['message']));
     }
     fwrite($handle, $response['body']);
     fclose($handle);
     return $tmpfname;
 }
 public function is_win_paths_exception($repository_id)
 {
     if (!isset($this->is_win_paths_exception[$repository_id])) {
         $this->is_win_paths_exception[$repository_id] = false;
         if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
             $windows_max_path_length = 256;
             $longest_path['wpml'] = 109;
             $longest_path['toolset'] = 99;
             $margin = 15;
             $upgrade_path_length = strlen(WP_CONTENT_DIR . '/upgrade');
             $installer_settings = WP_Installer()->settings;
             if (is_array($installer_settings['repositories'][$repository_id]['data']['downloads']['plugins'])) {
                 $a_plugin = current($installer_settings['repositories'][$repository_id]['data']['downloads']['plugins']);
                 $url = WP_Installer()->append_site_key_to_download_url($a_plugin['url'], 'xxxxxx', $repository_id);
                 $tmpfname = wp_tempnam($url);
                 $tmpname_length = strlen(basename($tmpfname)) - 4;
                 // -.tmp
                 if ($upgrade_path_length + $tmpname_length + $longest_path[$repository_id] + $margin > $windows_max_path_length) {
                     $this->is_win_paths_exception[$repository_id] = true;
                 }
             }
         }
     }
     return $this->is_win_paths_exception[$repository_id];
 }
Example #4
0
 function synved_option_item_addon_install($id, $name, $item)
 {
     $return = null;
     $type = synved_option_item_type($item);
     $target = synved_option_item_property($item, 'target');
     $folder = synved_option_item_property($item, 'folder');
     $field_name = synved_option_name_default($id);
     $path = null;
     if (file_exists($target)) {
         $path = $target;
     }
     if ($type != 'addon' || $path == null) {
         return false;
     }
     $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
     if (substr($path, -1) != DIRECTORY_SEPARATOR) {
         $path .= DIRECTORY_SEPARATOR;
     }
     if (isset($_FILES[$field_name])) {
         foreach ($_FILES[$field_name]["error"] as $key => $error) {
             if ($key == $name && $error == UPLOAD_ERR_OK) {
                 $tmp_name = $_FILES[$field_name]["tmp_name"][$key];
                 $name = $_FILES[$field_name]["name"][$key];
                 $tmpfname = wp_tempnam($name . '.zip');
                 if (move_uploaded_file($tmp_name, $tmpfname)) {
                     global $wp_filesystem;
                     $unzip_path = realpath($path);
                     $dirs = glob($path . '*', GLOB_ONLYDIR);
                     if ($wp_filesystem != null) {
                         $unzip_path = $wp_filesystem->find_folder($unzip_path);
                     }
                     wp_mkdir_p(realpath($path));
                     $return = unzip_file($tmpfname, $unzip_path);
                     if ($wp_filesystem != null) {
                         $wp_filesystem->delete($tmpfname);
                     }
                     $dirs_new = glob($path . '*', GLOB_ONLYDIR);
                     $dirs_diff = array_values(array_diff($dirs_new, $dirs));
                     $addon_path = $path;
                     if ($dirs_diff != null) {
                         $folder_path = null;
                         foreach ($dirs_diff as $dir) {
                             if (basename($dir) == $folder) {
                                 $folder_path = $dir;
                             }
                         }
                         // XXX no correct path, was unzip successful?
                         if ($folder_path == null) {
                             $folder_path = $dirs_diff[0];
                         }
                         $addon_path = $folder_path;
                     }
                     synved_option_set($id, $name, $addon_path);
                 }
             }
         }
     }
     return $return;
 }
 private function dumpTable($table)
 {
     global $wpdb;
     $fileName = wp_tempnam();
     $handle = fopen($fileName, 'w');
     $create = $wpdb->get_row("SHOW CREATE TABLE `{$table}`", ARRAY_N);
     @fwrite($handle, "{$create[1]};\n\n");
     $rowCount = $wpdb->get_var("SELECT Count(*) FROM `{$table}`");
     if ($rowCount > $this->qryLimit) {
         $batches = ceil($rowCount / $this->qryLimit);
     } else {
         if ($rowCount > 0) {
             $batches = 1;
         }
     }
     for ($i = 0; $i < $batches; $i++) {
         $sql = "";
         $limit = $i * $this->qryLimit;
         $query = "SELECT * FROM `{$table}` LIMIT {$limit}, {$this->qryLimit}";
         $rows = $wpdb->get_results($query, ARRAY_A);
         if (is_array($rows)) {
             foreach ($rows as $row) {
                 $sql .= "INSERT INTO `{$table}` VALUES(";
                 $values = array();
                 foreach ($row as $value) {
                     if (is_null($value) || !isset($value)) {
                         $values[] = 'NULL';
                     } else {
                         $values[] = '"' . @esc_sql($value) . '"';
                     }
                 }
                 $sql .= join(',', $values);
                 $sql .= ");\n";
             }
             fwrite($handle, $sql);
         }
     }
     $sql = "\nSET FOREIGN_KEY_CHECKS = 1; \n\n";
     fwrite($handle, $sql);
     fclose($handle);
     $zip = new \ZipArchive();
     $zipFile = wp_tempnam();
     $zip->open($zipFile, \ZipArchive::OVERWRITE);
     $zip->addFile($fileName, 'sql');
     $zip->close();
     unlink($fileName);
     return $zipFile;
 }
 protected static function download_wpcom_theme_to_file($theme)
 {
     $wpcom_theme_slug = preg_replace('/-wpcom$/', '', $theme);
     $file = wp_tempnam('theme');
     if (!$file) {
         return new WP_Error('problem_creating_theme_file', __('Problem creating file for theme download', 'jetpack'));
     }
     $url = "themes/download/{$theme}.zip";
     $args = array('stream' => true, 'filename' => $file);
     $result = Jetpack_Client::wpcom_json_api_request_as_blog($url, '1.1', $args);
     $response = $result['response'];
     if ($response['code'] !== 200) {
         unlink($file);
         return new WP_Error('problem_fetching_theme', __('Problem downloading theme', 'jetpack'));
     }
     return $file;
 }
 function download_url($url, $timeout = 300)
 {
     //WARNING: The file is not automatically deleted, The script must unlink() the file.
     if (!$url) {
         return new WP_Error('http_no_url', __('Invalid URL Provided.', 'themify-flow'));
     }
     $tmpfname = wp_tempnam($url);
     if (!$tmpfname) {
         return new WP_Error('http_no_file', __('Could not create Temporary file.', 'themify-flow'));
     }
     $response = wp_safe_remote_get($url, array('cookies' => $this->cookies, 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname));
     if (is_wp_error($response)) {
         unlink($tmpfname);
         return $response;
     }
     if (200 != wp_remote_retrieve_response_code($response)) {
         unlink($tmpfname);
         return new WP_Error('http_404', trim(wp_remote_retrieve_response_message($response)));
     }
     return $tmpfname;
 }
Example #8
0
File: file.php Project: rmccue/wpqi
/**
 * Downloads a url to a local file using the Snoopy HTTP Class.
 *
 * @since unknown
 * @todo Transition over to using the new HTTP Request API (jacob).
 *
 * @param string $url the URL of the file to download
 * @return mixed WP_Error on failure, string Filename on success.
 */
function wpqi_download_url($url)
{
    //WARNING: The file is not automatically deleted, The script must unlink() the file.
    if (!$url) {
        return new WP_Error('http_no_url', __('Invalid URL Provided'));
    }
    $tmpfname = wp_tempnam($url);
    if (!$tmpfname) {
        return new WP_Error('http_no_file', __('Could not create Temporary file'));
    }
    $response = wp_remote_get($url, array('timeout' => 60, 'stream' => true, 'filename' => $tmpfname));
    if (is_wp_error($response)) {
        unlink($tmpfname);
        return $response;
    }
    if ($response['response']['code'] != 200) {
        unlink($tmpfname);
        return new WP_Error('http_404', trim($response['response']['message']));
    }
    return array($tmpfname, $response);
}
Example #9
0
 protected static function download($url, $timeout = 300)
 {
     //WARNING: The file is not automatically deleted, The script must unlink() the file.
     if (!$url) {
         return new WP_Error('http_no_url', __('Invalid URL Provided.', 'wp-e-commerce'));
     }
     $tmpfname = wp_tempnam($url);
     if (!$tmpfname) {
         return new WP_Error('http_no_file', __('Could not create Temporary file.', 'wp-e-commerce'));
     }
     $args = array('timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname, 'headers' => array('X-WP-Domain' => Sputnik_API::domain()), 'user-agent' => 'WP eCommerce Marketplace: ' . WPSC_VERSION);
     Sputnik_API::sign_download($url, $args);
     $response = wp_safe_remote_get($url, $args);
     if (is_wp_error($response)) {
         unlink($tmpfname);
         return $response;
     }
     if (200 != wp_remote_retrieve_response_code($response)) {
         unlink($tmpfname);
         return new WP_Error('http_404', trim(wp_remote_retrieve_response_message($response)));
     }
     return $tmpfname;
 }
Example #10
0
/**
 * Downloads a url to a local temporary file using the WordPress HTTP Class.
 * Please note, That the calling function must unlink() the file.
 *
 * @since 2.5.0
 *
 * @param string $url the URL of the file to download
 * @param int $timeout The timeout for the request to download the file default 300 seconds
 * @return mixed WP_Error on failure, string Filename on success.
 */
function download_url( $url, $timeout = 300 ) {
	//WARNING: The file is not automatically deleted, The script must unlink() the file.
	if ( ! $url )
		return new WP_Error('http_no_url', __('Invalid URL Provided.'));

	$tmpfname = wp_tempnam($url);
	if ( ! $tmpfname )
		return new WP_Error('http_no_file', __('Could not create Temporary file.'));

	$response = wp_safe_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) );

	if ( is_wp_error( $response ) ) {
		unlink( $tmpfname );
		return $response;
	}

	if ( 200 != wp_remote_retrieve_response_code( $response ) ){
		unlink( $tmpfname );
		return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );
	}

	$content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
	if ( $content_md5 ) {
		$md5_check = verify_file_md5( $tmpfname, $content_md5 );
		if ( is_wp_error( $md5_check ) ) {
			unlink( $tmpfname );
			return $md5_check;
		}
	}

	return $tmpfname;
}
 /**
  * @param string $file
  * @param string $contents
  * @param bool|int $mode
  * @return bool
  */
 public function put_contents($file, $contents, $mode = false)
 {
     $tempfile = wp_tempnam($file);
     $temp = fopen($tempfile, 'wb+');
     if (!$temp) {
         return false;
     }
     mbstring_binary_safe_encoding();
     $data_length = strlen($contents);
     $bytes_written = fwrite($temp, $contents);
     reset_mbstring_encoding();
     if ($data_length !== $bytes_written) {
         fclose($temp);
         unlink($tempfile);
         return false;
     }
     fseek($temp, 0);
     // Skip back to the start of the file being written to
     $ret = @ftp_fput($this->link, $file, $temp, FTP_BINARY);
     fclose($temp);
     unlink($tempfile);
     $this->chmod($file, $mode);
     return $ret;
 }
 function put_contents($file, $contents, $type = '')
 {
     if (empty($type)) {
         $type = $this->is_binary($contents) ? FTP_BINARY : FTP_ASCII;
     }
     $this->ftp->SetType($type);
     $temp = wp_tempnam($file);
     if (!($temphandle = fopen($temp, 'w+'))) {
         unlink($temp);
         return false;
     }
     fwrite($temphandle, $contents);
     fseek($temphandle, 0);
     //Skip back to the start of the file being written to
     $ret = $this->ftp->fput($file, $temphandle);
     fclose($temphandle);
     unlink($temp);
     return $ret;
 }
 /**
  * Handles an upload via raw POST data.
  *
  * @since 4.7.0
  * @access protected
  *
  * @param array $data    Supplied file data.
  * @param array $headers HTTP headers from the request.
  * @return array|WP_Error Data from wp_handle_sideload().
  */
 protected function upload_from_data($data, $headers)
 {
     if (empty($data)) {
         return new WP_Error('rest_upload_no_data', __('No data supplied.'), array('status' => 400));
     }
     if (empty($headers['content_type'])) {
         return new WP_Error('rest_upload_no_content_type', __('No Content-Type supplied.'), array('status' => 400));
     }
     if (empty($headers['content_disposition'])) {
         return new WP_Error('rest_upload_no_content_disposition', __('No Content-Disposition supplied.'), array('status' => 400));
     }
     $filename = self::get_filename_from_disposition($headers['content_disposition']);
     if (empty($filename)) {
         return new WP_Error('rest_upload_invalid_disposition', __('Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.'), array('status' => 400));
     }
     if (!empty($headers['content_md5'])) {
         $content_md5 = array_shift($headers['content_md5']);
         $expected = trim($content_md5);
         $actual = md5($data);
         if ($expected !== $actual) {
             return new WP_Error('rest_upload_hash_mismatch', __('Content hash did not match expected.'), array('status' => 412));
         }
     }
     // Get the content-type.
     $type = array_shift($headers['content_type']);
     /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload() */
     require_once ABSPATH . 'wp-admin/includes/admin.php';
     // Save the file.
     $tmpfname = wp_tempnam($filename);
     $fp = fopen($tmpfname, 'w+');
     if (!$fp) {
         return new WP_Error('rest_upload_file_error', __('Could not open file handle.'), array('status' => 500));
     }
     fwrite($fp, $data);
     fclose($fp);
     // Now, sideload it in.
     $file_data = array('error' => null, 'tmp_name' => $tmpfname, 'name' => $filename, 'type' => $type);
     $overrides = array('test_form' => false);
     $sideloaded = wp_handle_sideload($file_data, $overrides);
     if (isset($sideloaded['error'])) {
         @unlink($tmpfname);
         return new WP_Error('rest_upload_sideload_error', $sideloaded['error'], array('status' => 500));
     }
     return $sideloaded;
 }
Example #14
0
/**
 * Launch system's $EDITOR to edit text
 *
 * @param [string] $input Text to be put into the temp file for changing
 * @param [string] $title Name for the temporary file
 * @return [string] $output Output string if input has changed, false otherwise
 */
function launch_editor_for_input($input, $title = 'Terminus')
{
    $tmpfile = wp_tempnam($title);
    if (!$tmpfile) {
        \Terminus::error('Error creating temporary file.');
    }
    $output = '';
    file_put_contents($tmpfile, $input);
    $editor = getenv('EDITOR');
    if (!$editor) {
        if (isset($_SERVER['OS']) && strpos($_SERVER['OS'], 'indows') !== false) {
            $editor = 'notepad';
        } else {
            $editor = 'vi';
        }
    }
    \Terminus::launch("{$editor} " . escapeshellarg($tmpfile));
    $output = file_get_contents($tmpfile);
    unlink($tmpfile);
    if ($output == $input) {
        return false;
    }
    return $output;
}
Example #15
0
 function get_google_drive_backup($args)
 {
     require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Google/Client.php';
     require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/Google/Service/Drive.php';
     //refresh token
     $client = new IWP_google_Client();
     $client->setClientId($args['clientID']);
     $client->setClientSecret($args['clientSecretKey']);
     $client->setRedirectUri($args['redirectURL']);
     $client->setScopes(array('https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));
     //$client->setUseObjects(true);
     $accessToken = $args['token'];
     $refreshToken = $accessToken['refresh_token'];
     try {
         $client->refreshToken($refreshToken);
     } catch (Exception $e) {
         echo 'google Error ', $e->getMessage(), "\n";
         return array("error" => $e->getMessage(), "error_code" => "google_error_refresh_token");
     }
     //downloading the file
     $service = new IWP_google_Service_Drive($client);
     $file = $service->files->get($args['backup_file']);
     $downloadUrl = $file->getDownloadUrl();
     $temp = wp_tempnam('iwp_temp_backup.zip');
     try {
         if ($downloadUrl) {
             $request = new IWP_google_Http_Request($downloadUrl, 'GET', null, null);
             $signHttpRequest = $client->getAuth()->sign($request);
             $httpRequest = $client->getIo()->makeRequest($signHttpRequest);
             if ($httpRequest->getResponseHttpCode() == 200) {
                 file_put_contents($temp, $httpRequest->getResponseBody());
                 return $temp;
             } else {
                 // An error occurred.
                 return array("error" => "There is some error.", "error_code" => "google_error_bad_response_code");
             }
         } else {
             // The file doesn't have any content stored on Drive.
             return array("error" => "Google Drive file doesnt have nay content.", "error_code" => "google_error_download_url");
         }
     } catch (Exception $e) {
         echo 'google Error ', $e->getMessage(), "\n";
         return array("error" => $e->getMessage(), "error_code" => "google_error_download_url_catch_excep");
     }
 }
 /**
  * Test that a passed mime type overrides the extension in the filename
  * @ticket 6821
  */
 public function test_mime_overrides_filename()
 {
     if (!extension_loaded('fileinfo')) {
         $this->markTestSkipped('The fileinfo PHP extension is not loaded.');
     }
     // Test each image editor engine
     $classes = array('WP_Image_Editor_GD', 'WP_Image_Editor_Imagick');
     foreach ($classes as $class) {
         // If the image editor isn't available, skip it
         if (!call_user_func(array($class, 'test'))) {
             continue;
         }
         $img = new $class(DIR_TESTDATA . '/images/canola.jpg');
         $loaded = $img->load();
         // Save the file
         $mime_type = 'image/gif';
         $file = wp_tempnam('tmp.jpg');
         $ret = $img->save($file, $mime_type);
         // Make assertions
         $this->assertNotEmpty($ret);
         $this->assertNotInstanceOf('WP_Error', $ret);
         $this->assertEquals($mime_type, $this->get_mime_type($ret['path']));
         // Clean up
         unlink($file);
         unlink($ret['path']);
         unset($img);
     }
 }
Example #17
0
File: media.php Project: nkeat12/dv
 /**
  * @ticket 22768
  */
 public function test_media_handle_upload_sets_post_excerpt()
 {
     $iptc_file = DIR_TESTDATA . '/images/test-image-iptc.jpg';
     // Make a copy of this file as it gets moved during the file upload
     $tmp_name = wp_tempnam($iptc_file);
     copy($iptc_file, $tmp_name);
     $_FILES['upload'] = array('tmp_name' => $tmp_name, 'name' => 'test-image-iptc.jpg', 'type' => 'image/jpeg', 'error' => 0, 'size' => filesize($iptc_file));
     $post_id = media_handle_upload('upload', 0, array(), array('action' => 'test_iptc_upload', 'test_form' => false));
     unset($_FILES['upload']);
     $post = get_post($post_id);
     // Clean up.
     wp_delete_attachment($post_id);
     $this->assertEquals('This is a comment. / Это комментарий. / Βλέπετε ένα σχόλιο.', $post->post_excerpt);
 }
Example #18
0
 /**
  * Generate starter code for a theme.
  *
  * ## OPTIONS
  *
  * <slug>
  * : The slug for the new theme, used for prefixing functions.
  *
  * [--activate]
  * : Activate the newly downloaded theme.
  *
  * [--enable-network]
  * : Enable the newly downloaded theme for the entire network.
  *
  * [--theme_name=<title>]
  * : What to put in the 'Theme Name:' header in style.css
  *
  * [--author=<full-name>]
  * : What to put in the 'Author:' header in style.css
  *
  * [--author_uri=<uri>]
  * : What to put in the 'Author URI:' header in style.css
  *
  * [--sassify]
  * : Include stylesheets as SASS
  */
 function _s($args, $assoc_args)
 {
     $theme_slug = $args[0];
     $theme_path = WP_CONTENT_DIR . "/themes";
     $url = "http://underscores.me";
     $timeout = 30;
     $data = wp_parse_args($assoc_args, array('theme_name' => ucfirst($theme_slug), 'author' => "Me", 'author_uri' => ""));
     $theme_description = "Custom theme: " . $data['theme_name'] . " developed by, " . $data['author'];
     $body = array();
     $body['underscoresme_name'] = $data['theme_name'];
     $body['underscoresme_slug'] = $theme_slug;
     $body['underscoresme_author'] = $data['author'];
     $body['underscoresme_author_uri'] = $data['author_uri'];
     $body['underscoresme_description'] = $theme_description;
     $body['underscoresme_generate_submit'] = "Generate";
     $body['underscoresme_generate'] = "1";
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'sassify')) {
         $body['underscoresme_sass'] = 1;
     }
     $tmpfname = wp_tempnam($url);
     $response = wp_remote_post($url, array('timeout' => $timeout, 'body' => $body, 'stream' => true, 'filename' => $tmpfname));
     if (is_wp_error($response)) {
         WP_CLI::error($response);
     }
     $response_code = wp_remote_retrieve_response_code($response);
     if (200 != $response_code) {
         WP_CLI::error("Couldn't create theme (received {$response_code} response).");
     }
     $this->maybe_create_themes_dir();
     $this->init_wp_filesystem();
     $unzip_result = unzip_file($tmpfname, $theme_path);
     unlink($tmpfname);
     if (true === $unzip_result) {
         WP_CLI::success("Created theme '{$data['theme_name']}'.");
     } else {
         WP_CLI::error("Could not decompress your theme files ('{$tmpfname}') at '{$theme_path}': {$unzip_result->get_error_message()}");
     }
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'activate')) {
         WP_CLI::run_command(array('theme', 'activate', $theme_slug));
     } else {
         if (\WP_CLI\Utils\get_flag_value($assoc_args, 'enable-network')) {
             WP_CLI::run_command(array('theme', 'enable', $theme_slug), array('network' => true));
         }
     }
 }
 /**
  * Handler for the ajax request to process a chunk of data (e.g. SQL inserts).
  *
  * @return bool|null
  */
 function respond_to_process_chunk()
 {
     add_filter('wpmdb_before_response', array($this, 'scramble'));
     $key_rules = array('action' => 'key', 'remote_state_id' => 'key', 'table' => 'string', 'chunk_gzipped' => 'positive_int', 'sig' => 'string');
     $this->set_post_data($key_rules, 'remote_state_id');
     $filtered_post = $this->filter_post_elements($this->state_data, array('action', 'remote_state_id', 'table', 'chunk_gzipped'));
     $gzip = isset($this->state_data['chunk_gzipped']) && $this->state_data['chunk_gzipped'];
     $tmp_file_name = 'chunk.txt';
     if ($gzip) {
         $tmp_file_name .= '.gz';
     }
     $tmp_file_path = wp_tempnam($tmp_file_name);
     if (!isset($_FILES['chunk']['tmp_name']) || !move_uploaded_file($_FILES['chunk']['tmp_name'], $tmp_file_path)) {
         $result = $this->end_ajax(__('Could not upload the SQL to the server. (#135)', 'wp-migrate-db'));
         return $result;
     }
     if (false === ($chunk = file_get_contents($tmp_file_path))) {
         $result = $this->end_ajax(__('Could not read the SQL file we uploaded to the server. (#136)', 'wp-migrate-db'));
         return $result;
     }
     // TODO: Use WP_Filesystem API.
     @unlink($tmp_file_path);
     $filtered_post['chunk'] = $chunk;
     if (!$this->verify_signature($filtered_post, $this->settings['key'])) {
         $error_msg = $this->invalid_content_verification_error . ' (#130)';
         $this->log_error($error_msg, $filtered_post);
         $result = $this->end_ajax($error_msg);
         return $result;
     }
     if ($this->settings['allow_push'] != true) {
         $result = $this->end_ajax(__('The connection succeeded but the remote site is configured to reject push connections. You can change this in the "settings" tab on the remote site. (#139)', 'wp-migrate-db'));
         return $result;
     }
     if ($gzip) {
         $filtered_post['chunk'] = gzuncompress($filtered_post['chunk']);
     }
     $process_chunk_result = $this->process_chunk($filtered_post['chunk']);
     $result = $this->end_ajax($process_chunk_result);
     return $result;
 }
 function put_contents($file, $contents, $type = '')
 {
     if (empty($type)) {
         $extension = substr(strrchr($file, '.'), 1);
         $type = isset($this->filetypes[$extension]) ? $this->filetypes[$extension] : FTP_AUTOASCII;
     }
     $this->ftp->SetType($type);
     $temp = wp_tempnam($file);
     if (!($temphandle = fopen($temp, 'w+'))) {
         unlink($temp);
         return false;
     }
     fwrite($temphandle, $contents);
     fseek($temphandle, 0);
     //Skip back to the start of the file being written to
     $ret = $this->ftp->fput($file, $temphandle);
     fclose($temphandle);
     unlink($temp);
     return $ret;
 }
 /**
  * @param string $file
  * @param string $contents
  * @param int|bool $mode
  * @return bool
  */
 public function put_contents($file, $contents, $mode = false)
 {
     $temp = wp_tempnam($file);
     if (!($temphandle = @fopen($temp, 'w+'))) {
         unlink($temp);
         return false;
     }
     // The FTP class uses string functions internally during file download/upload
     mbstring_binary_safe_encoding();
     $bytes_written = fwrite($temphandle, $contents);
     if (false === $bytes_written || $bytes_written != strlen($contents)) {
         fclose($temphandle);
         unlink($temp);
         reset_mbstring_encoding();
         return false;
     }
     fseek($temphandle, 0);
     // Skip back to the start of the file being written to
     $ret = $this->ftp->fput($file, $temphandle);
     reset_mbstring_encoding();
     fclose($temphandle);
     unlink($temp);
     $this->chmod($file, $mode);
     return $ret;
 }
 function put_contents($file, $contents, $mode = false)
 {
     $tempfile = wp_tempnam($file);
     $temp = fopen($tempfile, 'w+');
     if (!$temp) {
         return false;
     }
     fwrite($temp, $contents);
     fseek($temp, 0);
     //Skip back to the start of the file being written to
     $type = $this->is_binary($contents) ? FTP_BINARY : FTP_ASCII;
     $ret = @ftp_fput($this->link, $file, $temp, $type);
     fclose($temp);
     unlink($tempfile);
     $this->chmod($file, $mode);
     return $ret;
 }
Example #23
0
/**
 * Launch system's $EDITOR to edit text
 *
 * @param  str  $content  Text to edit (eg post content)
 * @return str|bool       Edited text, if file is saved from editor
 *                        False, if no change to file
 */
function launch_editor_for_input($input, $title = 'WP-CLI')
{
    $tmpfile = wp_tempnam($title);
    if (!$tmpfile) {
        \WP_CLI::error('Error creating temporary file.');
    }
    $output = '';
    file_put_contents($tmpfile, $input);
    $editor = getenv('EDITOR');
    if (!$editor) {
        if (isset($_SERVER['OS']) && false !== strpos($_SERVER['OS'], 'indows')) {
            $editor = 'notepad';
        } else {
            $editor = 'vi';
        }
    }
    $descriptorspec = array(STDIN, STDOUT, STDERR);
    $process = proc_open("{$editor} " . escapeshellarg($tmpfile), $descriptorspec, $pipes);
    $r = proc_close($process);
    if ($r) {
        exit($r);
    }
    $output = file_get_contents($tmpfile);
    unlink($tmpfile);
    if ($output === $input) {
        return false;
    }
    return $output;
}
Example #24
0
 /**
  * Get a local copy of the file.
  *
  * @param  string $file
  * @return string
  */
 public function copy_image_from_s3($file)
 {
     $temp_filename = wp_tempnam($file, 's3-uploads');
     copy($file, $temp_filename);
     return $temp_filename;
 }
 function import_resources($data)
 {
     if (!property_exists($data, 'resources')) {
         return $data;
     }
     if (is_array($data->resources) && count($data->resources) > 0) {
         $upload_dir = $this->wp_upload_dir();
         $path = $upload_dir['basedir'] . '/' . $this->resources_path;
         //$upload_dir['basedir']
         foreach ($data->resources as $content) {
             if ($this->alt_temp) {
                 //usually uploads is writable, so in the case the systems tmp is giving issues, use uploads. (iis bug).
                 $filename = wp_tempnam('addon', trailingslashit($upload_dir['basedir']));
             } else {
                 $filename = wp_tempnam();
             }
             if (file_exists($filename)) {
                 file_put_contents($filename, $content);
                 //---
                 if (class_exists('ZipArchive')) {
                     $zip = new ZipArchive();
                     $res = $zip->open($filename);
                     if ($res === TRUE) {
                         $zip->extractTo($path);
                         $zip->close();
                         @unlink($filename);
                         return true;
                     }
                 } else {
                     $to = $path . '/';
                     if (!is_dir($path)) {
                         mkdir($path);
                     }
                     require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
                     $archive = new PclZip($filename);
                     $files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
                     foreach ($files as $file) {
                         if ('__MACOSX/' === substr($file['filename'], 0, 9)) {
                             continue;
                         }
                         $needed_dirs[] = $to . untrailingslashit($file['folder'] ? $file['filename'] : dirname($file['filename']));
                     }
                     $needed_dirs = array_unique($needed_dirs);
                     foreach ($needed_dirs as $dir) {
                         // Check the parent folders of the folders all exist within the creation array.
                         if (untrailingslashit($to) == $dir) {
                             // Skip over the working directory, We know this exists (or will exist)
                             continue;
                         }
                         if (strpos($dir, $to) === false) {
                             // If the directory is not within the working directory, Skip it
                             continue;
                         }
                         $parent_folder = dirname($dir);
                         while (!empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs)) {
                             $needed_dirs[] = $parent_folder;
                             $parent_folder = dirname($parent_folder);
                         }
                     }
                     asort($needed_dirs);
                     foreach ($needed_dirs as $_dir) {
                         if (is_dir($_dir)) {
                             continue;
                         }
                         if (!mkdir($_dir)) {
                             $this->last_error .= sprintf(__('Unable to create directory %s', 'pop'), $_dir);
                             @unlink($filename);
                             return false;
                         }
                     }
                     $last_file = false;
                     foreach ($files as $file) {
                         if ($file['folder']) {
                             continue;
                         }
                         if ('__MACOSX/' === substr($file['filename'], 0, 9)) {
                             // Don't extract the OS X-created __MACOSX directory files
                             continue;
                         }
                         $this->last_error .= $path . '/' . $file['filename'] . "<BR />";
                         $last_file = $path . '/' . $file['filename'];
                         file_put_contents($path . '/' . $file['filename'], $file['content']);
                     }
                     @unlink($filename);
                     return file_exists($last_file) ? true : false;
                 }
             } else {
                 $this->last_error = __("Could not create temporary file", 'pop');
             }
         }
     }
     return false;
 }
Example #26
0
 function get_amazons3_backup($args)
 {
     if (!$this->iwp_mmb_function_exists('curl_init')) {
         return array('error' => 'You cannot use Amazon S3 on your server. Please enable curl first.', 'partial' => 1, 'error_code' => 'cannot_use_s3_enable_curl_first');
     }
     if (!class_exists('S3Client')) {
         require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/amazon/autoload.php';
     }
     extract($args);
     $temp = '';
     try {
         $s3 = S3Client::factory(array('key' => trim($as3_access_key), 'secret' => trim(str_replace(' ', '+', $as3_secure_key)), 'region' => $as3_bucket_region, 'signature' => 'v4', 'ssl.certificate_authority' => false));
         if ($as3_site_folder == true) {
             if (!empty($as3_directory)) {
                 $as3_directory .= '/' . $this->site_name;
             } else {
                 $as3_directory = $this->site_name;
             }
         }
         if (empty($as3_directory)) {
             $single_as3_file = $backup_file;
         } else {
             $single_as3_file = $as3_directory . '/' . $backup_file;
         }
         //$temp = ABSPATH . 'iwp_temp_backup.zip';
         $temp = wp_tempnam('iwp_temp_backup.zip');
         $getResult = $s3->getObject(array('Bucket' => $as3_bucket, 'Key' => $single_as3_file, 'SaveAs' => $temp));
     } catch (Exception $e) {
         return false;
     }
     return $temp;
 }
Example #27
0
 /**
  * Download an external file via a URL
  *
  * @param string  $url
  * @param int     $timeout
  * @return string|WP_Error the location of the temporay file name or an error
  * @deprecated since 0.20.0
  */
 static function download_url($url, $timeout = 300)
 {
     if (!$url) {
         return new WP_Error('http_no_url', __('Invalid URL Provided.'));
     }
     $tmpfname = wp_tempnam($url);
     if (!$tmpfname) {
         return new WP_Error('http_no_file', __('Could not create Temporary file.'));
     }
     $response = wp_remote_get($url, array('timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname));
     if (is_wp_error($response)) {
         unlink($tmpfname);
         return $response;
     }
     if (200 != wp_remote_retrieve_response_code($response)) {
         unlink($tmpfname);
         return new WP_Error('http_404', trim(wp_remote_retrieve_response_message($response)));
     }
     return $tmpfname;
 }
Example #28
0
 function ajax_process_chunk()
 {
     $filtered_post = $this->filter_post_elements($_POST, array('action', 'table', 'chunk_gzipped'));
     $gzip = isset($_POST['chunk_gzipped']) && $_POST['chunk_gzipped'];
     $tmp_file_name = 'chunk.txt';
     if ($gzip) {
         $tmp_file_name .= '.gz';
     }
     $tmp_file_path = wp_tempnam($tmp_file_name);
     if (!isset($_FILES['chunk']['tmp_name']) || !move_uploaded_file($_FILES['chunk']['tmp_name'], $tmp_file_path)) {
         $result = $this->end_ajax(__('Could not upload the SQL to the server. (#135)', 'wp-migrate-db'));
         return $result;
     }
     if (false === ($chunk = file_get_contents($tmp_file_path))) {
         $result = $this->end_ajax(__('Could not read the SQL file we uploaded to the server. (#136)', 'wp-migrate-db'));
         return $result;
     }
     @unlink($tmp_file_path);
     $filtered_post['chunk'] = $chunk;
     if (!$this->verify_signature($filtered_post, $this->settings['key'])) {
         $error_msg = $this->invalid_content_verification_error . ' (#130)';
         $this->log_error($error_msg, $filtered_post);
         $result = $this->end_ajax($error_msg);
         return $result;
     }
     if ($this->settings['allow_push'] != true) {
         $result = $this->end_ajax(__('The connection succeeded but the remote site is configured to reject push connections. You can change this in the "settings" tab on the remote site. (#133)', 'wp-migrate-db'));
         return $result;
     }
     if ($gzip) {
         $filtered_post['chunk'] = gzuncompress($filtered_post['chunk']);
     }
     $process_chunk_result = $this->process_chunk($filtered_post['chunk']);
     $result = $this->end_ajax($process_chunk_result);
     return $result;
 }
/**
 * Downloads a url to a local temporary file using the WordPress HTTP Class.
 * Please note, That the calling function must unlink() the  file.
 *
 * @since 2.5.0
 *
 * @param string $url the URL of the file to download
 * @return mixed WP_Error on failure, string Filename on success.
 */
function download_url($url)
{
    //WARNING: The file is not automatically deleted, The script must unlink() the file.
    if (!$url) {
        return new WP_Error('http_no_url', __('Invalid URL Provided'));
    }
    $tmpfname = wp_tempnam($url);
    if (!$tmpfname) {
        return new WP_Error('http_no_file', __('Could not create Temporary file'));
    }
    $handle = @fopen($tmpfname, 'wb');
    if (!$handle) {
        return new WP_Error('http_no_file', __('Could not create Temporary file'));
    }
    $response = wp_remote_get($url, array('timeout' => 300));
    if (is_wp_error($response)) {
        fclose($handle);
        unlink($tmpfname);
        return $response;
    }
    if ($response['response']['code'] != '200') {
        fclose($handle);
        unlink($tmpfname);
        return new WP_Error('http_404', trim($response['response']['message']));
    }
    fwrite($handle, $response['body']);
    fclose($handle);
    return $tmpfname;
}
Example #30
0
/**
 * {@internal Missing Short Description}}
 *
 * @since unknown
 *
 * @param unknown_type $args
 * @return unknown
 */
function get_filesystem_method($args = array())
{
    $method = false;
    if (function_exists('getmyuid') && function_exists('fileowner')) {
        $temp_file = wp_tempnam();
        if (getmyuid() == fileowner($temp_file)) {
            $method = 'direct';
        }
        unlink($temp_file);
    }
    if (!$method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2')) {
        $method = 'ssh2';
    }
    if (!$method && extension_loaded('ftp')) {
        $method = 'ftpext';
    }
    if (!$method && (extension_loaded('sockets') || function_exists('fsockopen'))) {
        $method = 'ftpsockets';
    }
    //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
    return apply_filters('filesystem_method', $method);
}