Today we will write a plugin which allows your users to send their files to you, to your Dropbox account. It might be needed for several purposes; For example, if you provide a contest for your readers, they might need to send you some files that you want partitioned off on a unique folder location in Dropbox. In short, this plugin is for receiving files, which must not be made public yet, which must be reviewed by you.
Before We Start
You can download ready plugin via Download Source button. Now we are going to describe our plugin step by step. We will use Jaka Jancar's Dropbox Uploader class(under MIT license) for creating our plugin.
We will build this plugin using our own hypothetical situation from the intro paragraph: Assume that you are hosting a competition for the "Best Desktop Screenshot" around your users. Every registered site user may send his/her desktop screenshot to you. After a deadline, you will look all and then you will publish the winners. So let's begin to build our plugin!
Step 1 Creating First File
Create a folder called dbuploader in wp-content/plugins diretory. Create a new PHP file called DropboxUploader.php inside it; Open it in your text editor and paste&save this code:
<?php /** * Dropbox Uploader * * Copyright (c) 2009 Jaka Jancar * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author Jaka Jancar [[email protected]] [http://jaka.kubje.org/] * @version 1.1.5 */ class DropboxUploader { protected $email; protected $password; protected $caCertSourceType = self::CACERT_SOURCE_SYSTEM; const CACERT_SOURCE_SYSTEM = 0; const CACERT_SOURCE_FILE = 1; const CACERT_SOURCE_DIR = 2; protected $caCertSource; protected $loggedIn = false; protected $cookies = array(); /** * Constructor * * @param string $email * @param string|null $password */ public function __construct($email, $password) { // Check requirements if (!extension_loaded('curl')) throw new Exception('DropboxUploader requires the cURL extension.'); $this->email = $email; $this->password = $password; } public function setCaCertificateFile($file) { $this->caCertSourceType = self::CACERT_SOURCE_FILE; $this->caCertSource = $file; } public function setCaCertificateDir($dir) { $this->caCertSourceType = self::CACERT_SOURCE_DIR; $this->caCertSource = $dir; } public function upload($filename, $remoteDir='/') { if (!file_exists($filename) or !is_file($filename) or !is_readable($filename)) throw new Exception("File '$filename' does not exist or is not readable."); if (!is_string($remoteDir)) throw new Exception("Remote directory must be a string, is ".gettype($remoteDir)." instead."); if (!$this->loggedIn) $this->login(); $data = $this->request('https://www.dropbox.com/home'); $token = $this->extractToken($data, 'https://dl-web.dropbox.com/upload'); $data = $this->request('https://dl-web.dropbox.com/upload', true, array('plain'=>'yes', 'file'=>'@'.$filename, 'dest'=>$remoteDir, 't'=>$token)); if (strpos($data, 'HTTP/1.1 302 FOUND') === false) throw new Exception('Upload failed!'); } protected function login() { $data = $this->request('https://www.dropbox.com/login'); $token = $this->extractToken($data, '/login'); $data = $this->request('https://www.dropbox.com/login', true, array('login_email'=>$this->email, 'login_password'=>$this->password, 't'=>$token)); if (stripos($data, 'location: /home') === false) throw new Exception('Login unsuccessful.'); $this->loggedIn = true; } protected function request($url, $post=false, $postData=array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); switch ($this->caCertSourceType) { case self::CACERT_SOURCE_FILE: curl_setopt($ch, CURLOPT_CAINFO, $this->caCertSource); break; case self::CACERT_SOURCE_DIR: curl_setopt($ch, CURLOPT_CAPATH, $this->caCertSource); break; } curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($post) { curl_setopt($ch, CURLOPT_POST, $post); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); } // Send cookies $rawCookies = array(); foreach ($this->cookies as $k=>$v) $rawCookies[] = "$k=$v"; $rawCookies = implode(';', $rawCookies); curl_setopt($ch, CURLOPT_COOKIE, $rawCookies); $data = curl_exec($ch); if ($data === false) throw new Exception('Cannot execute request: '.curl_error($ch)); // Store received cookies preg_match_all('/Set-Cookie: ([^=]+)=(.*?);/i', $data, $matches, PREG_SET_ORDER); foreach ($matches as $match) $this->cookies[$match[1]] = $match[2]; curl_close($ch); return $data; } protected function extractToken($html, $formAction) { if (!preg_match('/<form [^>]*'.preg_quote($formAction, '/').'[^>]*>.*?(<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>).*?<\/form>/is', $html, $matches) || !isset($matches[2])) throw new Exception("Cannot extract token! (form action=$formAction)"); return $matches[2]; } }
Step 2 Building The Plugin File
Create main plugin file called dbuploader.php in the same directory; Open it inside your editor and paste&save this code there:
<?php /* Plugin Name: DboUploader - Dropbox upload Plugin URI: http://www.webania.net/dbouploader/ Description: Upload to Dropbox Version: 1.0 Author: Elvin Haci Author URI: http://www.webania.net License: GPL2 */ /* Copyright 2011, Elvin Haci (email : [email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ function dbouploader($content = '') { if (is_user_logged_in()) add_shortcode('dbouploader', 'shortcoder'); else add_shortcode('dbouploader', 'notloggedin'); return $content; } function notloggedin($atts,$content = '') { return 'You must be logged in!'; } function shortcoder($atts,$content = '') { ////////////////// define("dboconf","1"); include(WP_PLUGIN_DIR . "/" . plugin_basename(dirname(__FILE__))."/config.php"); if ($_POST) { include(WP_PLUGIN_DIR . "/" . plugin_basename(dirname(__FILE__))."/DropboxUploader.php"); try { // Rename uploaded file to reflect original name if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) throw new Exception('File was not successfully uploaded from your computer.'); if( !in_array($_FILES["file"]["type"],$supported_types) or $_FILES["file"]["size"] > $size_limit) throw new Exception('File size is too large or file type is not supported.'); $tmpDir = uniqid('/tmp/DropboxUploader-'); if (!mkdir($tmpDir)) throw new Exception('Cannot create temporary directory!'); if ($_FILES['file']['name'] === "") throw new Exception('File name not supplied by the browser.'); global $current_user; get_currentuserinfo(); $tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $current_user->user_email.'_'.$_FILES['file']['name']); if (!move_uploaded_file($_FILES['file']['tmp_name'], $tmpFile)) throw new Exception('Cannot rename uploaded file!'); // Enter your Dropbox account credentials here $uploader = new DropboxUploader($dropbox_email, $dropbox_password); $uploader->upload($tmpFile, $_POST['dest']); return '<span style="color: green;font-weight:bold;margin-left:0px;">File successfully uploaded. Thank you!</span>'; } catch(Exception $e) { return '<span style="color: red;font-weight:bold;margin-left:0px;">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'; } // Clean up if (isset($tmpFile) && file_exists($tmpFile)) unlink($tmpFile); if (isset($tmpDir) && file_exists($tmpDir)) rmdir($tmpDir); } else { return ' <div class="box" align="center"> <h1>Dropbox Uploader Demo<br> </h1> <form method="POST" enctype="multipart/form-data"> <input type="file" name="file" /><br><br> <input type="submit" value="Upload your file!" /> <input style="display:none" type="text" name="dest" value="'.$dropbox_folder.'" /> </div> '; } //////////////// } add_action('the_content', 'dbouploader'); ?>
Step 3 Finishing The Plugin:
Create config.php file in your plugin folder, then paste this code there:
<?php if(!defined('dboconf')){die();} $dropbox_email=''; // YOUR DROPBOX EMAIL $dropbox_password=''; // YOUR DROPBOX PASSWORD $dropbox_folder='shared'; $supported_types=array('image/png','image/jpeg'); $size_limit='512000'; ?>
Then edit this code: set your email, password, dropbox folder, file size limit, supported file types and then save it.
Some Suggestions:
Suggestion 1:
If you want to make it available for all users, not only for logged in users, then you can edit the code, remove this...
if (is_user_logged_in()) add_shortcode('dbouploader', 'shortcoder');
...condition from the plugin. Instead of it, you can integrate Recaptcha with your plugin.
Suggestion 2:
You can also format uploaded files' name. Just edit this line:
$tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $current_user->user_email.'_'.$_FILES['file']['name']);
That's all, good luck!
Comments