public function stream_close() { $res = fclose(self::$crtHandle); if (self::$crtWritePath != null) { $path = $this->initPath(self::$crtWritePath); try { $postRes = self::$dropbox->putFile($path, self::$crtTmpFile); AJXP_Logger::debug(__CLASS__, __FUNCTION__, "Post to {$path} succeeded:"); } catch (Dropbox_Exception $dE) { AJXP_Logger::debug(__CLASS__, __FUNCTION__, "Post to {$path} failed :" . $dE->getMessage()); } } unlink(self::$crtTmpFile); return $res; }
/** * @param \Dropbox_API $dropbox */ function it_does_not_mask_exception_from_client_during_write($dropbox) { $dropbox->putFile('filename', Argument::any())->willThrow(new \RuntimeException('write')); $this->shouldThrow(new \RuntimeException('write'))->duringWrite('filename', 'some content'); }
function show_dropbox($atts, $content = NULL) { add_thickbox(); $wpsdb_short_attr = shortcode_atts(array('notification' => get_bloginfo('admin_email'), 'fields' => 'none'), $atts); //print_r($wpsdb_short_attr); $wpsdb_up_method = get_option('wpsdb_php_pear'); $wpsdb_path = get_option('wpsdb_path'); $wpsdb_tmp_path = get_option('wpsdb_temp_path'); $wpsdb_allow_ext = trim(get_option('wpsdb_allow_ext')); $wpsdb_thank_message = stripslashes(get_option('wpsdb_thank_message')); $wpsdb_show_progress = get_option('wpsdb_show_progress'); $wpsdb_show_multi = get_option('wpsdb_show_multi'); $wpsdb_show_form = get_option('wpsdb_show_form'); $wpsdb_delete_file = get_option('wpsdb_delete_file'); $wpsdb_key = get_option('wpsdb_key'); $wpsdb_secret = get_option('wpsdb_secret'); $wpsdb_token = get_option('wpsdb_auth_token'); $wpsdb_token_secret = get_option('wpsdb_auth_token_secret'); echo '<div class="wp-dropbox">'; $wpsshowform = "showit"; try { if ($wpsdb_allow_ext == '') { throw new Exception(__('Need to configure allowed file extensions!', 'simpleDbUpload')); } if (get_option('wpsdb_auth_step') < 3 or $wpsdb_key == '' or $wpsdb_secret == '' or $wpsdb_token == '' or $wpsdb_token_secret == '') { throw new Exception(__('Need to authorize plugin!', 'simpleDbUpload')); } } catch (Exception $e) { echo '<span id="wpsdb-error">' . __('Error:', 'simpleDbUpload') . ' ' . htmlspecialchars($e->getMessage()) . '</span>'; $wpsshowform = "hideit"; } /*if (isset($_POST['upupnaway']) and $_POST['upupnaway']) { try{ $wpsdbMultiFiles = $_POST['multimages']; $wpsdbMultiFiles = split(",",$wpsdbMultiFiles); $wpsdbMultiFiles = array_filter($wpsdbMultiFiles); //echo count($wpsdbMultiFiles); if (!file_exists($wpsdb_tmp_path.'/')){ if (!mkdir($wpsdb_tmp_path.'/')) throw new Exception(__('Internal Server Error!','simpleDbUpload')); } try { require_once (dirname( __FILE__ ) . '/inc/Dropbox/autoload.php'); if($wpsdb_up_method == 'curl'){ $oauth = new Dropbox_OAuth_Curl($wpsdb_key, $wpsdb_secret); } if (class_exists('HTTP_OAuth_Consumer') && $wpsdb_up_method == 'php'){ $oauth = new Dropbox_OAuth_PHP($wpsdb_key, $wpsdb_secret); }elseif(class_exists('OAuth') && $wpsdb_up_method == 'pear'){ $oauth = new Dropbox_OAuth_PEAR($wpsdb_key, $wpsdb_secret); } $oauth->setToken($wpsdb_token,$wpsdb_token_secret); $dropbox = new Dropbox_API($oauth); } catch(Exception $e) { echo '<span id="wpsdb-error">'.__('Error:','simpleDbUpload'). ' ' . htmlspecialchars($e->getMessage()) . '</span>'; $wpsshowform = "hideit"; } foreach ($wpsdbMultiFiles as $wpsdbMF){ //echo $wpsdbMF.'<br />'; $wpsdbNewFileName = explode(".",$wpsdbMF); $wpsdbTmpFile = $wpsdb_tmp_path.'/'.preg_replace('/\s+/', '_', $wpsdbNewFileName[0]) . "_" . rand(1000,9999) . "_" . date("Y-m-d").".".preg_replace("/\s+/", '_', end($wpsdbNewFileName));//$wpsdbNewFileName[1]); //echo $wpsdbTmpFile.'<br />'; //echo $wpsdb_tmp_path.'/tmp/'.$wpsdbMF.'<br/>'; if (!rename($wpsdb_tmp_path.'/'.$wpsdbMF, $wpsdbTmpFile)){ throw new Exception(__('Problem with uploaded file!','simpleDbUpload')); exit(); } // Upload $wpschunks = explode("/",$wpsdbTmpFile); for($i = 0; $i < count($wpschunks); $i++){ $c = $i; } if ( !$dropbox->putFile(trim($wpsdb_path,'/').'/'.$wpschunks[$c], $wpsdbTmpFile,"dropbox") ) { throw new Exception(__('ERROR! Upload Failed.','simpleDbUpload')); } if($wpsdb_delete_file == "True"){ if (isset($wpsdbTmpFile) && file_exists($wpsdbTmpFile)){ unlink($wpsdbTmpFile); } } } //$adminEmail = get_bloginfo('admin_email'); $adminEmail = $wpsdb_short_attr['notification']; $headers = 'From: Simple Dropbox <simpledropbox@'.$_SERVER['HTTP_HOST'].'>' . "\r\n"; wp_mail($adminEmail, 'New File Received', 'You have received a new file from the dropbox form on your website.', $headers);//, $attachments); echo (get_option('wpsdb_redirect_page')!='')?'<script>window.location = "'.get_page_link(get_option('wpsdb_redirect_page')).'"</script>':'<span id="wpsdb-success">'.$wpsdb_thank_message.'</span>'; //echo '<span id="wpsdb-success">'.$wpsdb_thank_message.'</span>'; if($wpsdb_show_form == "True"){ $wpsshowform = "showit"; }else{ $wpsshowform = "hideit"; } }catch(Exception $e) { echo '<span id="wpsdb-error">'.__('Error: ','simpleDbUpload') . ' ' . html_entity_decode($e->getMessage()) . '</span>'; $wpsshowform = "showit"; } }*/ if (isset($_POST['gogogadget']) and $_POST['gogogadget']) { try { $wpsallowedExtensions = split("[ ]+", $wpsdb_allow_ext); foreach ($_FILES as $file) { if ($file['tmp_name'] > '') { //if($wpsdb_up_method == 'curl'){ $file['name'] = str_replace(' ', '_', $file['name']); /*}else{ $file['name'] = str_replace(' ', '%20', $file['name']); }*/ if (!in_array(end(explode(".", strtolower($file['name']))), $wpsallowedExtensions)) { $wpsext = implode(", ", $wpsallowedExtensions); throw new Exception(__('Allowed file extensions: ', 'simpleDbUpload') . '' . $wpsext); } } } // Rename uploaded file to reflect original name if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) { throw new Exception(__('File was not uploaded from your computer.', 'simpleDbUpload')); } if (!file_exists($wpsdb_tmp_path)) { if (!mkdir($wpsdb_tmp_path)) { throw new Exception(__('Internal Server Error!', 'simpleDbUpload')); } } if ($_FILES['file']['name'] === "") { throw new Exception(__('File name not supplied by the browser.', 'simpleDbUpload')); } $wpsnew_file_name = explode(".", $file['name']); $wpstmpFile = $wpsdb_tmp_path . '/' . str_replace("/", '_', $wpsnew_file_name[0]) . "_" . rand(1000, 9999) . "_" . date("Y-m-d") . "." . str_replace("/", '_', end($wpsnew_file_name)); //$wpsnew_file_name[1]); if (!move_uploaded_file($_FILES['file']['tmp_name'], $wpstmpFile)) { throw new Exception(__('Problem with uploaded file!', 'simpleDbUpload')); } // Upload $wpschunks = explode("/", $wpstmpFile); for ($i = 0; $i < count($wpschunks); $i++) { $c = $i; } try { require_once dirname(__FILE__) . '/inc/Dropbox/autoload.php'; //include 'inc/Dropbox/autoload.php'; if ($wpsdb_up_method == 'curl') { $oauth = new Dropbox_OAuth_Curl($wpsdb_key, $wpsdb_secret); } if (class_exists('HTTP_OAuth_Consumer') && $wpsdb_up_method == 'php') { $oauth = new Dropbox_OAuth_PHP($wpsdb_key, $wpsdb_secret); } elseif (class_exists('OAuth') && $wpsdb_up_method == 'pear') { $oauth = new Dropbox_OAuth_PEAR($wpsdb_key, $wpsdb_secret); } $oauth->setToken($wpsdb_token, $wpsdb_token_secret); $dropbox = new Dropbox_API($oauth); } catch (Exception $e) { echo '<span id="wpsdb-error">' . __('Error:', 'simpleDbUpload') . ' ' . htmlspecialchars($e->getMessage()) . '</span>'; $wpsshowform = "hideit"; } if (!$dropbox->putFile(trim($wpsdb_path, '/') . '/' . $wpschunks[$c], $wpstmpFile, "dropbox")) { throw new Exception(__('ERROR! Upload Failed.', 'simpleDbUpload')); } echo '<span id="wpsdb-success">' . $wpsdb_thank_message . '</span>'; if ($wpsdb_show_form == "True") { $wpsshowform = "showit"; } else { $wpsshowform = "hideit"; } if ($wpsdb_delete_file == "True") { $wpsdelete_file = "deleteit"; } else { $wpsdelete_file = "keepit"; } //$adminEmail = get_bloginfo('admin_email'); $adminEmail = $wpsdb_short_attr['notification']; //$adminEmail = "*****@*****.**"; $headers = 'From: Simple Dropbox <simpledropbox@' . $_SERVER['HTTP_HOST'] . '>' . "\r\n"; wp_mail($adminEmail, 'New File Received', 'You have received a new file from the dropbox form on your website.', $headers); //, $attachments); } catch (Exception $e) { echo '<span id="wpsdb-error">' . __('Error: ', 'simpleDbUpload') . ' ' . html_entity_decode($e->getMessage()) . '</span>'; $wpsshowform = "showit"; $wpsdelete_file = "deleteit"; } // Clean up if ($wpsdelete_file == "deleteit") { if (isset($wpstmpFile) && file_exists($wpstmpFile)) { unlink($wpstmpFile); } } } if ($wpsshowform == "showit") { if (false) { //$wpsdb_show_multi=="True"){ ?> <p><a class="thickbox" href="<?php echo plugins_url('', __FILE__) . '/multi.php?'; ?> &height=500&width=1000&TB_iframe=true"><?php echo get_option('wpsdb_multi_link_text'); ?> </a></p> <form name="multi_image" method="POST" enctype="multipart/form-data"> <input type="hidden" name="upupnaway" value="1"/> <input type="hidden" name="multimages" id="multimages" value=""/> </form> <?php } if ($wpsdb_show_progress == "True") { ?> <style> .progress{ position:relative; width:200px; border:1px solid #ddd; padding:1px;border-radius:3px; margin-top:10px; } .bar{ background-color:#b4f5b4; width:0%; height:20px; border-radius:3px; } .percent{ position:absolute; display:inline-block; top:3px; left:48%; } #cover { background: url("<?php echo plugins_url('/images/gears_animated.gif', __FILE__); ?> ") no-repeat scroll center center; position: fixed; height: 100%; width: 100%; overflow:hidden; z-index:999999999; } </style> <?php } ?> <form name="single_image" method="POST" enctype="multipart/form-data"> <input type="hidden" name="gogogadget" value="1"/> <?php $wpsdb_fields_exploded = explode(",", $wpsdb_short_attr['fields']); if ($wpsdb_fields_exploded[0] != 'none') { foreach ($wpsdb_fields_exploded as $wpsdb_field) { $wpsdb_field = trim($wpsdb_field); echo '<p><span id="wpsdb_' . $wpsdb_field . '" style="margin-right:3px;">' . $wpsdb_field . ':</span>'; echo '<input name="wpsdb_' . $wpsdb_field . '" id="wpsdb_' . $wpsdb_field . '" type="text" size="34"/>'; echo '</p>'; } } ?> <input class="input_form" size="34" type="file" name="file" /> <input id="submit_button" type="submit" value="<?php _e('Submit', 'simpleDbUpload'); ?> " /> </form> <?php if ($wpsdb_show_progress == "True") { ?> <div class="progress"> <div class="bar"></div> <div class="percent">0%</div> </div> <?php /*<div id="status"></div>*/ ?> <script src="<?php echo plugins_url('/js/jquery.js', __FILE__); ?> "></script> <script src="<?php echo plugins_url('/js/jquery.form.js', __FILE__); ?> "></script> <script src="<?php echo plugins_url('/js/overlay.js', __FILE__); ?> "></script> <script> jQuery(document).ready(function(){ var h = jQuery.noConflict(),bar=h('.bar'),percent=h('.percent'); var cover = h('<div />').prependTo('body'); cover.attr({'id':'cover','style':'display:none'}); h('form').ajaxForm({ beforeSend:function(){ <?php /*status.empty();*/ ?> var percentVal='0%'; bar.width(percentVal) percent.html(percentVal); }, uploadProgress:function(event,position,total,percentComplete){ h(this).openOverlay({sColor:'#ffffff',iOpacity:60}); h('#cover').fadeIn(500); var percentVal=percentComplete+'%'; bar.width(percentVal) percent.html(percentVal); }, success:function(){ var percentVal='100%'; bar.width(percentVal) percent.html(percentVal); }, complete:function(xhr){ <?php /*status.html(xhr.responseText);*/ ?> h('#cover').fadeOut(500); h(this).openOverlay.closeOverlay(); setTimeout(function(){ window.location = <?php echo get_option('wpsdb_redirect_page') ? '"' . get_page_link(get_option('wpsdb_redirect_page')) . '"' : 'window.location.href.toString()'; ?> ; },1000); } }); }) </script> <?php } } echo "</div>"; }
<?php $consumerKey = 'key'; // key $consumerSecret = 'sercret'; // sercret include 'vendor/dropbox-php/dropbox-php/src/Dropbox/autoload.php'; $oauth = new Dropbox_OAuth_PHP($consumerKey, $consumerSecret); $dropbox = new Dropbox_API($oauth); // auth $tokens = $dropbox->getToken('email', 'pass'); $oauth->setToken($tokens); $h = fopen('/PATH/browserling.jpg', 'r'); // upload file $dropbox->putFile('browserling.jpg', $h); // put file
protected function doProcess($arguments = array(), $options = array()) { # DISABLED //$this->logBlock('DISABLED.', 'ERROR'); // exit; if (!$options['go']) $this->logBlock('Running in dry mode, no files will be uploaded.', 'ERROR'); $consumerKey = sfConfig::get("app_dropbox_consumer_key"); $consumerSecret = sfConfig::get("app_dropbox_consumer_secret"); $token = sfConfig::get("app_dropbox_token"); $token_secret = sfConfig::get("app_dropbox_token_secret"); $dropboxRoot = sfConfig::get("app_dropbox_root"); ProjectConfiguration::registerDropboxAPI(); // If the PHP OAuth extension is not available, you can try // PEAR's HTTP_OAUTH instead. $oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret); $dropbox = new Dropbox_API( $oauth ); $tokens = array( "token" => $token, "token_secret" => $token_secret ); $oauth->setToken($tokens); // get DROPBOX directory listing $metadata = $dropbox->getMetaData($dropboxRoot, $list = true, $hash = null, $fileLimit = null, $root = null); $dropbox_list = array(); $this->logBlock(sprintf("Connected dropbox in %s", $dropboxRoot), 'COMMENT'); if (is_array( $metadata['contents'] )) { foreach( $metadata['contents'] as $info) { /* if ($info["mime_type"] == "application/pdf") { $filename = strtolower( basename( $info["path"] ) ); */ $filename = strtolower( basename( $info["path"] ) ); // https://www.dropbox.com/developers/docs $timestamp = strtotime($info["modified"]); /* $ftime = strptime($info["modified"], "%a, %d %b %Y %H:%M:%S %z"); $timestamp = mktime( $ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1 , $ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900 ); */ // time zone problem ?!? //$timestamp = strtotime("+2 hours", $timestamp); $dropbox_list["$filename"] = $timestamp; // } } } // compare DROPBOX contents to "live" files $push_files = array(); $dir = sfConfig::get('sf_data_dir').sfConfig::get('app_rockstep_pdf_dir'); $weeds = array('.', '..','.DS_Store'); $directory = array_diff(scandir($dir), $weeds); if (!$options['force']) { $this->logBlock(sprintf("Checking %d files in %s", count($directory), $dir), 'COMMENT'); } else { $this->logBlock(sprintf("Pushing %d files from %s", count($directory), $dir), 'COMMENT'); } foreach( $directory as $id => $filename ) { if (is_file($dir.$filename)) { if (!$options['force']) { if (array_key_exists(strtolower($filename), $dropbox_list)) { $this->logSection('file', sprintf("%s %s %s", $filename, filemtime($dir.$filename), $dropbox_list[strtolower($filename)] )); //echo date('Y-m-d H:m:s u', strtotime( $dropbox_list[strtolower($filename)] ))."--".date('Y-m-d H:m:s u', filemtime($dir.$filename)); if ( filemtime($dir.$filename) > $dropbox_list[strtolower($filename)] ) { //echo date('Y-m-d H:m:s', $dropbox_list[strtolower($filename)] )."--".date('Y-m-d H:m:s', filemtime($dir.$filename)); $push_files[] = $filename; } } else { $push_files[] = $filename; } } else { $push_files[] = $filename; } } } // PUSH to dropbox $error = 0; $success = 0; if (count($push_files) == 0) { $this->logBlock("Everything is up to date.", 'INFO'); $this->task->setErrorCode(304); $this->setOk(); } else { if (!$options['force']) $this->logBlock(sprintf("%d files have been modified", count($push_files)), 'INFO'); foreach ($push_files as $filename) { if ($options['go']) { // sync $this->logBlock(sprintf("try: %s => %s", $dir.$filename, $dropboxRoot.$filename), 'INFO'); $result = $dropbox->putFile($dropboxRoot.$filename, $dir.$filename); if($result['httpStatus'] == 200 ) { // set datemodified to the dropbox-date $metadata = $dropbox->getMetaData($dropboxRoot.$filename, $list = true, $hash = null, $fileLimit = null, $root = null); touch($dir.$filename, strtotime($metadata['modified']) ); //echo date('Y-m-d H:m:s u', strtotime($metadata['modified']))."--".date('Y-m-d H:m:s u', filemtime($dir.$filename)); //echo strtotime($metadata['modified']); $this->logSection('file+', sprintf("%s", $filename)); $success += 1; } else { $this->logSection('error', sprintf("%s", $filename)); $error += 1; } } else { // dry run $this->logSection('file+', sprintf("%s", $filename)); $success += 1; } } if ($options['go']) { if ($error > 0) { $this->logBlock(sprintf('Error Uploading on %d out of %d Files', $error, $success, $dropboxRoot), 'ERROR'); $this->task->setErrorCode(500); $this->setNOk($error); } else { $this->logBlock(sprintf('Uploaded %d Files to %s', $success, $dropboxRoot), 'INFO'); $this->task->setErrorCode(200); $this->setOk(); } } else { // dry run } } }
static function DropboxUpload($fileid) { /* * This script shoud upload a file to a * special folder in the users dropbox. * The session should bestarted and the * user should be logged in already. * * @author Nils Bussmann <*****@*****.**> * @date 05.02.2011 * @param filename should be the path to the local file * @param folder the folder in the dropbox * * @return fail: filename if something went wrong * success:filename if everything went right * exists: filename if the file already exists */ if (isset($fileid)) { session_start(); //generate filename, filepath, intended_path //get filename from database $db = \DBManager::get(); $query = " SELECT dokument_id, range_id, filename, seminar_id\n\t\t\t\t\t\tFROM dokumente\n\t\t\t\t\t\tWHERE dokumente.dokument_id = '{$fileid}' "; $file_result = $db->query($query)->fetchAll(); //get folder from database $seminar_id = $file_result[0]["seminar_id"]; $range_id = $file_result[0]["range_id"]; $query = " SELECT folder.folder_id, folder.name as folder_name, seminare.Seminar_id, seminare.name as seminar_name\n\t\t\t\t\t\tFROM folder\n\t\t\t\t\t\tJOIN seminare ON seminare.Seminar_id = '{$seminar_id}' \n\t\t\t\t\t\tWHERE folder.folder_id = '{$range_id}' "; $folder_result = $db->query($query)->fetchAll(); // repart the important strings $filename = \Helper::cleanFilename($file_result[0]["filename"]); $file = $GLOBALS['UPLOAD_PATH'] . "/" . substr($fileid, 0, 2) . "/" . $fileid; $folder = \Helper::cleanFilename($folder_result[0]["seminar_name"] . "/" . $folder_result[0]["folder_name"]); //check if everthing is allright if (!isset($filename) || !isset($file) || !isset($folder)) { if (!isset($filename)) { $filename = fileid; } return "fail:" . $filename; } /* start interaction width dropbox session shoud be started, user should logged in Please supply your own consumer key and consumer secret */ $consumerKey = '5wty9mf06gcuco0'; $consumerSecret = 'hveok3hllw48hji'; try { $oauth = new \Dropbox_OAuth_PEAR($consumerKey, $consumerSecret); $dropbox = new \Dropbox_API($oauth, \Dropbox_API::ROOT_SANDBOX); $oauth->setToken($_SESSION['oauth_tokens']); //Check if the directories are created and //single subfolders in $folders $folders = explode("/", $folder); $checked_path = "/"; foreach ($folders as $subfolder) { $found_folder = false; $info = $dropbox->getMetaData($checked_path); foreach ($info["contents"] as $meta_info) { if ($meta_info["is_dir"] == 1 && \Helper::endsWith($meta_info["path"], $subfolder)) { $found_folder = true; break; } } if (!$found_folder) { $dropbox->createFolder($checked_path . "/" . $subfolder); } if ($checked_path == "/") { $checked_path .= $subfolder; } else { $checked_path .= "/" . $subfolder; } } //depending folder exists //check if file already exisits $found = false; // $found shows if file already exisits $info = $dropbox->getMetaData($folder); foreach ($info["contents"] as $array_files) { if (strpos($array_files["path"], $filename) != false) { $ausgabe = "exists:" . $filename; $found = true; } } //Upload the file if nessasery if ($found == false) { if ($dropbox->putFile($folder . "/" . $filename, $file)) { $ausgabe = "success:" . $filename; } else { $ausgabe = "fail:" . $filename; } } } catch (Exception $e) { // something went wrong, not specified // to specify the error there are other exeptions to catch $ausgabe = "fail:" . $filename; } catch (HTTP_OAuth_Exception $e) { $ausgabe = "fail:" . $filename; } } else { $ausgabe = "fail:" . $filename; } return $ausgabe; }