public function get_authorize_url()
 {
     $oauth = new Dropbox_OAuth_PEAR(self::CONSUMER_KEY, self::CONSUMER_SECRET);
     $this->tokens['request'] = $oauth->getRequestToken();
     $this->save_tokens();
     return $oauth->getAuthorizeUrl();
 }
Example #2
0
 function get_authorize_url()
 {
     $oauth = new Dropbox_OAuth_PEAR($this->_key, $this->_secret);
     $this->_token['request'] = $oauth->getRequestToken();
     pb_backupbuddy::save();
     //echo 'authorizeurltoken:<pre>';
     //print_r( $this->_token );
     //echo '</pre>';
     return str_replace('api.', 'www.', $oauth->getAuthorizeUrl());
 }
 public function initRepository()
 {
     if (is_array($this->pluginConf)) {
         $this->driverConf = $this->pluginConf;
     } else {
         $this->driverConf = array();
     }
     $this->detectStreamWrapper(true);
     $this->urlBase = "pydio://" . $this->repository->getId();
     if (!AJXP_Utils::searchIncludePath('HTTP/OAuth/Consumer.php')) {
         $this->logError("Dropbox", "The PEAR HTTP_OAuth package must be installed!");
         return;
     }
     $consumerKey = $this->repository->getOption("CONSUMER_KEY");
     $consumerSecret = $this->repository->getOption("CONSUMER_SECRET");
     $oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);
     // TOKENS IN SESSION?
     if (!empty($_SESSION["OAUTH_DROPBOX_TOKENS"])) {
         return;
     }
     // TOKENS IN FILE ?
     $tokens = $this->getTokens();
     if (!empty($tokens)) {
         $_SESSION["OAUTH_DROPBOX_TOKENS"] = $tokens;
         return;
     }
     // OAUTH NEGOCIATION
     if (isset($_SESSION['DROPBOX_NEGOCIATION_STATE'])) {
         $state = $_SESSION['DROPBOX_NEGOCIATION_STATE'];
     } else {
         $state = 1;
     }
     switch ($state) {
         case 1:
             $tokens = $oauth->getRequestToken();
             //print_r($tokens);
             // Note that if you want the user to automatically redirect back, you can
             // add the 'callback' argument to getAuthorizeUrl.
             //echo "Step 2: You must now redirect the user to:\n";
             $_SESSION['DROPBOX_NEGOCIATION_STATE'] = 2;
             $_SESSION['oauth_tokens'] = $tokens;
             throw new Exception("Please go to <a style=\"text-decoration:underline;\" target=\"_blank\" href=\"" . $oauth->getAuthorizeUrl() . "\">" . $oauth->getAuthorizeUrl() . "</a> to authorize the access to your dropbox. Then try again to switch to this workspace.");
         case 2:
             $oauth->setToken($_SESSION['oauth_tokens']);
             try {
                 $tokens = $oauth->getAccessToken();
             } catch (Exception $oauthEx) {
                 throw new Exception($oauthEx->getMessage() . ". Please go to <a style=\"text-decoration:underline;\" target=\"_blank\" href=\"" . $oauth->getAuthorizeUrl() . "\">" . $oauth->getAuthorizeUrl() . "</a> to authorize the access to your dropbox. Then try again to switch to this workspace.");
             }
             $_SESSION['DROPBOX_NEGOCIATION_STATE'] = 3;
             $_SESSION['OAUTH_DROPBOX_TOKENS'] = $tokens;
             $this->setTokens($tokens);
             return;
     }
     throw new Exception("Impossible to find the dropbox tokens for accessing this workspace");
 }
 function initRepository()
 {
     if (is_array($this->pluginConf)) {
         $this->driverConf = $this->pluginConf;
     } else {
         $this->driverConf = array();
     }
     $wrapperData = $this->detectStreamWrapper(true);
     AJXP_Logger::debug("Detected wrapper data", $wrapperData);
     $this->wrapperClassName = $wrapperData["classname"];
     $this->urlBase = $wrapperData["protocol"] . "://" . $this->repository->getId();
     $consumerKey = $this->repository->getOption("CONSUMER_KEY");
     $consumerSecret = $this->repository->getOption("CONSUMER_SECRET");
     $oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);
     // TOKENS IN SESSION?
     if (!empty($_SESSION["OAUTH_DROPBOX_TOKENS"])) {
         return;
     }
     // TOKENS IN FILE ?
     $tokens = $this->getTokens($this->repository->getId());
     if (!empty($tokens)) {
         $_SESSION["OAUTH_DROPBOX_TOKENS"] = $tokens;
         return;
     }
     // OAUTH NEGOCIATION
     if (isset($_SESSION['DROPBOX_NEGOCIATION_STATE'])) {
         $state = $_SESSION['DROPBOX_NEGOCIATION_STATE'];
     } else {
         $state = 1;
     }
     switch ($state) {
         case 1:
             $tokens = $oauth->getRequestToken();
             //print_r($tokens);
             // Note that if you want the user to automatically redirect back, you can
             // add the 'callback' argument to getAuthorizeUrl.
             //echo "Step 2: You must now redirect the user to:\n";
             $_SESSION['DROPBOX_NEGOCIATION_STATE'] = 2;
             $_SESSION['oauth_tokens'] = $tokens;
             throw new Exception("Please go to <a style=\"text-decoration:underline;\" target=\"_blank\" href=\"" . $oauth->getAuthorizeUrl() . "\">" . $oauth->getAuthorizeUrl() . "</a> to authorize the access to your dropbox. Then try again to switch to this repository.");
         case 2:
             $oauth->setToken($_SESSION['oauth_tokens']);
             $tokens = $oauth->getAccessToken();
             $_SESSION['DROPBOX_NEGOCIATION_STATE'] = 3;
             $_SESSION['OAUTH_DROPBOX_TOKENS'] = $tokens;
             $this->setTokens($this->repository->getId(), $tokens);
             return;
     }
     throw new Exception("Impossible to find the tokens for accessing the dropbox repository");
 }
Example #5
0
	            finden.<br /><small>StudIp erhält nicht auf Ihre gesamte Dropbox Zugriff.</small>
	    </li>
    </ul>
    <a href="<?=$dropCom ?>" data-role="button" data-theme="b">StudIp verbinden</a>
	<?
}
elseif($dropCom == "connected")
{
	// der nutzer ist eingelogged 
	//nun können dateien hochgeladen werden
	
	try
	{
		$consumerKey 	= '5wty9mf06gcuco0';
        $consumerSecret = 'hveok3hllw48hji';
        $oauth   = new \Dropbox_OAuth_PEAR( $consumerKey, $consumerSecret );
        $dropbox = new \Dropbox_API( $oauth,\Dropbox_API::ROOT_SANDBOX );

        $oauth->setToken( $_SESSION['oauth_tokens'] );
		$accInfo= $dropbox->getAccountInfo();
	}
	catch (\DropboxException $e)
	{
		echo "Es ist ein Fehler aufgetreten, bitte laden Sie die Seite neu.";
		die();
	}
    ?>
    <ul data-role="listview" data-inset="true" data-theme="e">
        <li>
            <h1>Verbundener Dropbox Account</h1>
            <fieldset class="ui-grid-a">
Example #6
0
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?';
            ?>
&amp;height=500&amp;width=1000&amp;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>";
}
Example #7
0
 static function tryToConnect($call_back_link, $user_id, $token = null)
 {
     if (isset($token)) {
         //token übergeben
         $_SESSION['oauth_tokens'] = array("token" => $token['token'], "token_secret" => $token['token_secret']);
         $_SESSION['state'] = 3;
         $state = 3;
     }
     if (!isset($_SESSION['state'])) {
         //ganz neu
         $_SESSION['state'] = 1;
     }
     $state = $_SESSION['state'];
     //try to login
     $consumerKey = '5wty9mf06gcuco0';
     $consumerSecret = 'hveok3hllw48hji';
     $oauth = new \Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);
     $dropbox = new \Dropbox_API($oauth, \Dropbox_API::ROOT_SANDBOX);
     try {
         switch ($state) {
             /* In this phase we grab the initial request tokens
                and redirect the user to the 'authorize' page hosted
                on dropbox */
             case 1:
                 $tokens = $oauth->getRequestToken();
                 $link = $oauth->getAuthorizeUrl($call_back_link) . "\n";
                 // Note that if you want the user to automatically redirect back, you can
                 // add the 'callback' argument to getAuthorizeUrl.
                 $link = $oauth->getAuthorizeUrl($call_back_link) . "\n";
                 $_SESSION['state'] = 2;
                 $_SESSION['oauth_tokens'] = $tokens;
                 return $link;
                 break;
                 /* In this phase, the user just came back from authorizing
                    and we're going to fetch the real access tokens */
             /* In this phase, the user just came back from authorizing
                and we're going to fetch the real access tokens */
             case 2:
                 $oauth->setToken($_SESSION['oauth_tokens']);
                 try {
                     $tokens = $oauth->getAccessToken();
                     $_SESSION['state'] = 3;
                     $state = 3;
                     $_SESSION['oauth_tokens'] = $tokens;
                 } catch (\PEAR_Exception $e) {
                     $_SESSION['state'] = 1;
                     $state = 1;
                     $_SESSION['oauth_tokens'] = NULL;
                     $tokens = NULL;
                     $link = $oauth->getAuthorizeUrl($call_back_link) . "\n";
                     return self::tryToConnect($call_back_link, $user_id);
                     break;
                 }
                 // There is no break here, intentional
                 /* This part gets called if the authentication process
                    already succeeded. We can use our stored tokens and the api 
                    should work. Store these tokens somewhere, like a database */
             // There is no break here, intentional
             /* This part gets called if the authentication process
                already succeeded. We can use our stored tokens and the api 
                should work. Store these tokens somewhere, like a database */
             case 3:
                 try {
                     $oauth->setToken($_SESSION['oauth_tokens']);
                     //checks if Connection is Good
                     $dropbox->getAccountInfo();
                 } catch (\Dropbox_Exception $e) {
                     $_SESSION['state'] = 1;
                     $state = 1;
                     $link = $oauth->getAuthorizeUrl($call_back_link) . "\n";
                     unset($_SESSION['oauth_tokens']);
                     // delete the stored token
                     self::deleteToken($user_id);
                     return self::tryToConnect($call_back_link, $user_id);
                 } catch (\HTTP_OAuth_Exception $e) {
                     $_SESSION['state'] = 1;
                     $state = 1;
                     $link = $oauth->getAuthorizeUrl($call_back_link) . "\n";
                     unset($_SESSION['oauth_tokens']);
                     // delete the stored token
                     self::deleteToken($user_id);
                     return self::tryToConnect($call_back_link, $user_id);
                 }
                 break;
         }
         //connection should be good
         self::storeToken($user_id);
         return "connected";
     } catch (Exception $e) {
         return false;
     } catch (\HTTP_OAuth_Exception $e) {
         return false;
     } catch (\Dropbox_Exception $e) {
         return false;
     }
 }
  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
      } 
    }
    
  }
Example #9
0
<?php

if (isset($_POST['allow_access'])) {
    //modify include path to work w/ PEAR on Dreamhost
    ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . "/home/kshrine/.pear/home/kshrine/pear/php");
    $consumerKey = '';
    $consumerSecret = '';
    include 'Dropbox/autoload.php';
    $oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);
    $dropbox = new Dropbox_API($oauth);
    $tokens = $dropbox->getToken($_POST['email_address'], $_POST['password']);
    update_option('wpdp_token', $tokens);
    $stored_tokens = get_option('wpdp_token');
    $oauth->setToken($stored_tokens);
    $acct_info = $dropbox->getAccountInfo();
    update_option('wpdp_acct_name', $acct_info['display_name']);
}
?>
<div class="wrap">
  <h2>WP-Dropbox</h2>
  <?php 
$name_on_authorized_acct = get_option('wpdp_acct_name');
if (empty($name_on_authorized_acct)) {
    echo "<h3>No Dropbox in use.</h3>";
} else {
    echo "<h3>Using {$name_on_authorized_acct}'s Dropbox.</h3>";
}
?>


Example #10
0
     $state = (int) $_SESSION[$state_key];
 }
 @(include_once 'Dropbox/autoload.php');
 if (class_exists('OAuth')) {
     try {
         $oauth = new Dropbox_OAuth_PHP($config['dropbox_token'], $config['dropbox_seckey']);
     } catch (Exception $e) {
         $state = 0;
     }
 } else {
     if (!class_exists('HTTP_OAuth_Consumer')) {
         @(include 'HTTP/OAuth/Consumer.php');
     }
     if (class_exists('HTTP_OAuth_Consumer')) {
         try {
             $oauth = new Dropbox_OAuth_PEAR($config['dropbox_token'], $config['dropbox_seckey']);
         } catch (Exception $e) {
             $state = 0;
         }
     }
 }
 if (!empty($config['dropbox_acc_token']) && !empty($config['dropbox_acc_seckey'])) {
     $_SESSION[$state_key . '_tokens'] = array('token' => $config['dropbox_acc_token'], 'token_secret' => $config['dropbox_acc_seckey']);
     $state = 3;
 }
 if ($state > 2 && isset($_SESSION[$state_key . '_tokens'])) {
     // acc token check
     try {
         $oauth->setToken($_SESSION[$state_key . '_tokens']);
         $dropbox = new Dropbox_API($oauth);
         $dropbox->getAccountInfo();
Example #11
0
 function createDropboxFolders($semId)
 {
     session_start();
     $consumerKey = '5wty9mf06gcuco0';
     $consumerSecret = 'hveok3hllw48hji';
     $folder_paths = self::get_folder_pathes($semId);
     $ausgabe = "Success";
     try {
         $oauth = new \Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);
         $dropbox = new \Dropbox_API($oauth, \Dropbox_API::ROOT_SANDBOX);
         $oauth->setToken($_SESSION['oauth_tokens']);
     } catch (Exception $e) {
         return "Error";
     }
     foreach ($folder_paths as $folder_path) {
         try {
             if (!self::create_dropbox_folder($folder_path, $dropbox)) {
                 $ausgabe = "Error";
             }
         } catch (Exception $e) {
             /*              echo $e; */
         }
     }
     return $ausgabe;
 }