wordpress media upload to rename files appropriately if file exists - wordpress

I'm creating a plugin in wordpress that uses the wp media uploader to upload files to the site. Problem is that if a file exists with the same name, the name of the file being currently uploaded is appended with a number at the end.
This is a problem if I upload file001.pdf and then the next file is renamed to file0012.pdf instead of file001-2.pdf
It's a problem because then the user may think that is file 12 and not version 2 of file 1.
How can i change that so if there's already a file in the system with the same name, the file being uploaded gets the right rename?
EDIT
So I found out there's a function in wp-includes/functions.php called wp_unique_filename which will check for unique file names and increment until the name is unique. I just need to find a way now to customize that function on the plugin directory.

WordPress provides one hook wp_handle_upload_prefilter as below
function handle_uploadedimage($arr) {
$random_number = md5(rand(10000,99999));
$ext = pathinfo($arr['name'], PATHINFO_EXTENSION);
$arr['name'] = $random_number .'.'.$ext;
return $arr;
}
add_filter('wp_handle_upload_prefilter', 'handle_uploadedimage', 1, 1);

Related

Script to cause duplicate active script with name change and importrange function + new folder

I am new to stackoverflow and i am not a programmer but i am developing my skills in google sheets and scripts ( but still a newbie).
Right now i am trying to do this:
Duplicating active spreadsheet to totally new file but with use of importrange function so the new file can be automaticly updated when i change data in original file.
rename the new file using particular cell in original file.
Create new folder in particular master folder where this new file will be placed and rename this folder using the same particular cell as above.
i am able to rename or duplicate the file but i don't know how to implicate the importrange function and totally dumb with folder creation in master folder. Any hints will be gold for me ;)
I have tried renaming and duplicating the file, i honestly don't know how to implement importrange ( the function have to take file ID automaticly as i will be copying the template of Master file for every event i make.
For now i have managed to copy the file and rename it with particular cell with this function:
function createCopy() {
var myValue = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("H1").getValue();
var destinationFolder = DriveApp.getFolderById("MASTER FOLDER");
DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).makeCopy(myValue,destinationFolder);
}

How To Display Uploaded Image Correctly?

I have Wordpress Plugin in which I try To display an uploaded image, but I get url like this:
http://localhost/opt/lampp/htdocs/wordpress2/wp-content/plugins/fileuploadplugin/uploads/website-development-banner.jpg
instead of this:
http://localhost/wordpress2/wp-content/plugins/fileuploadplugin/uploads/website-development-banner.jpg
My code is:
<?php
// Configuration - Your Options
$allowed_filetypes = array('.csv','.jpg','.gif','.png','.jpeg'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/wordpress2/wp-content/plugins' );
//$targetpath=WP_PLUGIN_DIR.'/testplugin/documents/'.basename($_FILES["photo"]["name"]);
$upload_path = WP_PLUGIN_DIR.'/fileuploadplugin/uploads/'; // The place the files will be uploaded to (currently a 'files' directory).
//echo $upload_path;exit;
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
//$targetpath='/uploads'.basename($filename);
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
My Problem is how to remove /opt/lampp/htdocs from $uploadpath to get uploaded image to display correctly?
The problem is that you are using the same path for both uploading and displaying the image.
Path to Upload the image
In your upload code above, you need to use the file system path, as you are doing. The path in your code is:
$upload_path = WP_PLUGIN_DIR.'/fileuploadplugin/uploads/'; // The place the files will be uploaded to (currently a 'files' directory).
This will have a value something like
/home/user/var/www/wp-content/plugins/fileuploadplugin/uploads/
URL to Display the image
The file system path obviously won't work to display the image, so you need to use a URL or a path relative to your website, e.g.
http://www.example.com/wp-content/plugins/fileuploadplugin/uploads/uploadedimage.jpg
To get the URL for your plugins folder, you need to use:
$upload_url = WP_PLUGIN_URL.'/fileuploadplugin/uploads/';
And then you can display the image using that path, e.g.
<img src="/<?php echo $upload_url.$filename; ?>" />
Note:
I have kept WP_PLUGIN_DIR and used WP_PLUGIN_URL in the code above to make it easier for you to see the changes required. However these should not be used directly. Instead you should use the functions provided by WP to get these values: ref Wordpress Codex: Determining Plugin and Content Directories.

Dynamically Update Manifest file based on image uploads in SilverStripe admin

I'm new to HTML5's application cache, but am familiar with the basics of it. I'm working on a cache manifest file for a SilverStripe site that needs to be dynamically updated whenever the content manager uploads a new image. I understand that the images will be appended to the Manifest function below using a loop, but the part that I find to be a challenge is updating the date and version number every time. Would I need to have the date and version listed as variables? Or is that not possible considering the setup of the Manifest function?
public function Manifest() {
$static = <<<EOT
CACHE MANIFEST
# 2016-03-17 v6.0.0
[manifest content]
EOT;
//Append any new image file that gets uploaded
$static = $static . "\n" . "/test.html";
$this->response->addHeader("Content-type", "text/cache-manifest");
return $static;
}
When you change cached by manifest file, the manifest content does not change. However you must change the content to trigger update in a browser. In this case you update a comment. This comment can contain anything. The date and version is common practice, because they reflect the change. So all you need it to get most recent change date from File.LastEdited field.

Wordpress I18n generator: Missing Keys

I downloaded the I18n generator package from: http://codex.wordpress.org/I18n_for_WordPress_Developers#Generating_a_POT_file. I want to generate a pot file for my created template now:
php makepot.php /home/mr/workspace/blog/wp-content/themes/myTheme/ de_DE.pot
After executing this command, I get a de_DE.pot with some the WP standard keys in. But my new keys will not be found. But if I add them to the file manually and upload it, they will be translated.
Why doesn't WordPress pick up all my keys?
I have used the poEdit in the following way.
File Menu > New Catalog
Set the language as per your need. Set utf8
Set the paths as . and ..(if you want to place your .mo file at languages folder).
Define the functions from which the strings to take( ie , _, _e, _n, _x, _ex etc).
Now save the file to your template's folder as templateName.po
Now update catalog.
Upon saving the .mo file will be generated in the same folder.
Now rename the .mo file to the specific Locale (for mine bn_BD.mo, for your case de_DE.mo)
I would suggest a few tips from here

File renaming functions in wordpress upload process

I have a script that loads posts automatically from a predefined array and uploads images as featured images from a physical path on a local machine.
When I copy the file into upload directory I use path and filename like so:
$upload_dir['path'].'/'.$new_post_id.$filename
This way if I upload apple.jpg several times, the file will be named 1apple.jpg, 2apple.jpg and so on and it will not be overwritten.
I would however like to use Wordpress native functions that check and rename files. In wordpress uploads if you upload apple.jpg several times it will add a new number before the extension like so: apple1.jpg, apple2.jpg and so on, and the number portion is not based on a post.
I was wondering if you could point me to the function in wordpress that does this check and creates new filename so I can use the wordpress native functions for naming my uploaded files.
You need to filter the function wp_unique_post_slug().
As discussed in WPSE.
I found the answer: wp_unique_filename()

Resources