public function add_content_from_file($filepath, $name = null) { // Get the contents of the file. $contents = ''; // Try wp_remote_get first. if (defined('WPCOM_IS_VIP_ENV') && WPCOM_IS_VIP_ENV) { $request = vip_safe_wp_remote_get($filepath); } else { $request = wp_remote_get($filepath); } if (is_wp_error($request)) { // Try file_get_contents instead. This could be a local path. $contents = file_get_contents($filepath); } else { $contents = wp_remote_retrieve_body($request); } // Attempt to get the size $size = strlen($contents); // If this fails for some reason, try alternate methods if (empty($size)) { if (filter_var($filepath, FILTER_VALIDATE_URL)) { $headers = get_headers($filepath); foreach ($headers as $header) { if (preg_match('/Content-Length: ([0-9]+)/i', $header, $matches)) { $size = intval($matches[1]); } } } else { // This will be the final catch for local files $size = filesize($filepath); } } // If the name wasn't specified, build it from the filename $filename = \Apple_News::get_filename($filepath); if (empty($name)) { $name = sanitize_key($filename); } return $this->build_attachment($name, $filename, $contents, $this->get_mime_type_for($filepath), $size); }
/** * Parses the API response and checks for errors. * TODO The exporter has an abstracted article class. Should we have * something similar here? That way this method could live there. * * @param string $article * @param array $bundles * @param array $meta * @return string * @since 0.2.0 */ private function build_content($article, $bundles = array(), $meta = null) { $bundles = array_unique($bundles); $content = ''; if ($meta) { $content .= $this->mime_builder->add_metadata($meta); } $content .= $this->mime_builder->add_json_string('my_article', 'article.json', $article); foreach ($bundles as $bundle) { $content .= $this->mime_builder->add_content_from_file($bundle); } $content .= $this->mime_builder->close(); return $content; }