Error http uploading images on Wordpress - php

I'm working with Imagick and I don't know what happens because when I upload an file "png" or "jpg" It returns:
Error HTTP
but when I upload an file "jpge" it works perfectly.
This is the code on functions.php:
add_filter( 'wp_generate_attachment_metadata', 'generate_watermarked_image' );
function watermark_image( $filename, $upload_dir ) {
$original_image_path = trailingslashit( $upload_dir['path'] ) . $filename;
$image_resource = new Imagick( $original_image_path );
$watermark_resource = new Imagick( get_stylesheet_directory() . '/images/logo.png' );
$image_resource->compositeImage( $watermark_resource, Imagick::COMPOSITE_DEFAULT, 0, 0 );
return save_watermarked_image( $image_resource, $original_image_path );
}
function save_watermarked_image( $image_resource, $original_image_path ) {
$image_data = pathinfo( $original_image_path );
$new_filename = $image_data['filename'] . '-watermarked.' . $image_data['extension'];
$watermarked_image_path = str_replace($image_data['basename'], $new_filename, $original_image_path);
if ( ! $image_resource->writeImage( $watermarked_image_path ) )
return $image_data['basename'];
unlink( $original_image_path ); // Because that file isn't referred to anymore
return $new_filename;
}
I'm sorry for my english.

Related

Problems with Imagick and PHP in Wordpress

Hy, i have this function:
function process_pdf( $file ) {
if( $file['type'] === 'application/pdf' ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
$filename = $file[ 'name' ];
$filename_wo_extension = basename( $filename, ".pdf" );
$im = new Imagick();
$im->setResolution(300, 300);
$im->setBackgroundColor('white');
$im->readimage( $file[ 'tmp_name' ] );
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$pages = $im->getNumberImages();
$attachments_array = array();
// iterate over pages of the pdf file
for($p = 1; $p <= $pages; $p++){
$im->setIteratorIndex( $p - 1 );
$im->setImageFormat('jpeg');
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$page_title = get_the_title($post_id);
$filename_neu = $page_title .'_pagina_'. $p .'.jpg';
// upload new image to wordpress
// https://codex.wordpress.org/Function_Reference/wp_insert_attachment
$upload_file = wp_upload_bits($filename_neu, null, $im);
if (!$upload_file['error']) {
$attachment = array(
'post_mime_type' => 'image/jpeg',
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename_neu),
'post_content' => '',
'post_parent' => $post_id,
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );
if (!is_wp_error( $attachment_id )) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
$attachments_array[] = $attachment_id;
}
}
}
// add new images to a gallery (advanced custom fields plugin)
// http://www.advancedcustomfields.com/resources/update_field/
//update_field( 'field_62a736b215b2f', $attachments_array, $post_id );
$im->destroy();
}
}
return $file;
}
add_filter('wp_handle_upload_prefilter', 'process_pdf' );
when i upload PDF file on wordpress all page is converted to JPG and upload in site.
Function work and do what i need, but problem appear when i upload THIS File:
https://easyupload.io/o6hsk3
for understand where is the problem:
i try to compare this file with another;
i upload a big pdf file with more resolution, page.
All work good, but this pdf file not work:(
have any ideea why?

WordPress plugin development : How to upload a file to the default "uploads" directory?

I'm trying to upload files to the default "wp-content/uploads" directory. Have tried almost all the available tags, still not working.
Few of the codes I tried:
$filename = $_FILES["uploadfile"]["name"];
$tempname = $_FILES["uploadfile"]["tmp_name"];
$folder= 'wp_upload_dir()'. $filename; //This code is uploading the file to the "wp-admin" directory
if(move_uploaded_file($tempname, $folder)){$response}
$uploaddir = 'uploads/'; $uploadfile = $uploaddir . $filename;`
if(move_uploaded_file($tempname, $uploadfile))
`
I've coded to save the image in uploads folder for one of my website. please check if this code helps
//taking image in $name_icon
$name_icon = $_POST['myfile'];
// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );
$wordpress_upload_dir = wp_upload_dir();
$i = 1; // number of tries when the file with the same name is already exists
$profilepicture = $_FILES['myfile'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
if( empty( $profilepicture ) )
die();
if( $profilepicture['error'] )
die( $profilepicture['error'] );
if( $profilepicture['size'] > wp_max_upload_size() )
die( 'It is too large than expected.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
$upload_id = wp_insert_attachment( array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
'post_content' => '',
'post_status' => 'inherit'
), $new_file_path );
// wp_generate_attachment_metadata() won't work if you do not include this file
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate and save the attachment metas into the database
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
Tested & works

pdf extension not allowed when adding an attachment to xero with API

Wonder if anyone can explain what rstrictions Xero has for adding a pdf file I creted using mPDF. I have managed to use a png file and uploaded it to an invoice but cannot get past this block.
public function attachPDF( $invoice ) {
try {
$company = Company::find( $invoice->company_id );
list( $xeroTenantId, $accountingApi, $identityApi ) = VivattiXero::getApiConnection( $company, false );
$filename = 'AUTH#' . sprintf( '%08d', $invoice->id ) . '.pdf';
//$filename = 'favicon.png';
$guid = $invoice->invoice_id;
$contents = $invoice->getPDF( \Mpdf\Output\Destination::FILE, true, $filename );
$handle = fopen( $filename, "r" );
$contents = fread( $handle, filesize( $filename ) );
fclose( $handle );
//unlink( $filename );
$result['apiResponse'] = $accountingApi->createInvoiceAttachmentByFileName( $xeroTenantId, $guid, $filename, $contents, true );
$result['message'] = 'PDF was attached to invoice #' . sprintf( '%08d', $invoice->id );
$result['success'] = true;
}catch (\XeroAPI\XeroPHP\ApiException $e) {
$error = AccountingObjectSerializer::deserialize(
$e->getResponseBody(),
'\XeroAPI\XeroPHP\Models\Accounting\Error',
[]
);
$result['message'] = "ApiException - " . $error->getElements()[0]["validation_errors"][0]["message"];
$result['success'] = false;
}
return $result;
}
}
Has anyone successfully uploaded a pdf to xero? anyone with a mpdf pdf?
thanks

Wordpress and crontab

I have built a Wordpress plugin that polls an api, this api along with other data, returns URLs to images (the user polling the api owns these images). Moving the images from the api server to my server is time consuming but needs to be done as we want Wordpress to create multiple sizes of the images - thus we need to utilise it's upload functionality. Sometimes the data may return 500+ results each result could multiple images.
I am wanting to offset the image retrieval into a daily CRON job, however I cannot seem to get the cron to run, I have done the following in my code,
wp-config.php
define('DISABLE_WP_CRON', true);
I register a scheduled event in my plugin code like this,
wp_schedule_event( time(), 'daily', 'process_images_hourly' );
This theoretically should put this function (below) into a job list.
function process_images_hourly()
{
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM wp_autotrader_image_process WHERE process_status = 'Unprocessed';");
$processed_id = [];
foreach($results as $result) {
if(isset($result->image_url)) {
$upload_dir = wp_upload_dir();
$attachment_array = [];
if( !class_exists( 'WP_Http' ) ) {
include_once( ABSPATH . WPINC . '/class-http.php' );
}
$http = new WP_Http();
$file = file_get_contents($result->image_url);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$ext = $finfo->buffer($file);
if(strpos($ext, 'jpeg') || strpos($ext, 'jpg')) {
$type = '.jpg';
} elseif(strpos($ext, 'png')) {
$type = '.png';
} elseif(strpos($ext, 'gif')) {
$type = '.gif';
}
$response = $http->request( $result->image_url );
//die(print_r($image['secure']['href']));
if( $response['response']['code'] != 200 ) {
die(print_r($response['response']));
return false;
}
$upload = wp_upload_bits( basename($result->image_url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
die(print_r($upload));
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name . $type,
'post_mime_type' => $finfo->buffer($file),
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $post_info, $file_path );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
$attachment_array[] = $attach_id;
update_field( 'gallery', $attachment_array , $result->post_id );
$wpdb->delete( 'wp_autotrader_image_process', array( 'id' => $result->id ));
}
}
}
I then have cronjob on my server that does this,
*/15 * * * * curl https://Xxxxxx.xxxxxxxxx.com/wp-cron.php > /dev/null 2>&1 >/dev/null 2>&1
This runs the wp-cron file every fifteen minutes.
However I don't think my function is running, can anyone explain to why, or how set this up properly?
Thanks
add this code:
add_action( 'call_process_images_hourly', 'process_images_hourly' );
and update:
wp_schedule_event( time(), 'daily', 'call_process_images_hourly' );

How to differ two uploads in one form with same upload handling?

I have already created a form for my plugin, and it has two upload fields; one for an image and one for a zip-file. They are both using the same upload handler, and I want to save the attachment ID's to the database. The problem is that they use the same upload handler, so the value of the variable with the attachment ID will always be the last upload field. How is the best way to do this? Save in array (first index is first field, second index is second field)? Two upload handler is probably a bit overkill. Any ideas how to solve this in a good way?
This is the function that handles the upload:
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
}
As I said, as both upload fields uses the same function, the $attach_ID variable will be the value of the latest upload.
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
// $ids[]= $attach_id;
// save $attach id here, its correct for this loop, on the next loop it will be different and so on..
}
}
return $ids; // or save here serialize() maybe needed depending on how you are saving.
}

Categories