public static function uploadFile($access_token, $uploadFile, $fileName, $config) { if (!isset($access_token)) { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth(\HttpReceiver\HttpReceiver::get('userId', 'int'), $config)); } if (!file_exists($uploadFile)) { return array('status' => 'error', 'fileNotExist'); } $dbxClient = new dbx\Client($access_token, "PHP-Example/1.0"); $f = fopen($uploadFile, "rb"); try { if (!isset($fileName) || strlen($fileName) == 0 || $fileName == '0') { $tmp = explode('/', $uploadFile); $fileName = $tmp[sizeof($tmp) - 1]; } else { $fileName .= '.pdf'; } $result = $dbxClient->uploadFile("/" . $config['SAVE_FOLDER'] . "/" . $fileName, dbx\WriteMode::add(), $f); } catch (Exception $e) { return array('status' => 'error', 'msg' => 'refreshToken', 'url' => self::auth(\HttpReceiver\HttpReceiver::get('userId', 'int'), $config)); } fclose($f); if (!isset($result) || !isset($result['size'])) { return array('status' => 'error', 'msg' => 'refreshToken'); } else { return array('status' => 'ok'); } }
public function upload($article_id) { $accessToken = Yii::$app->params['accessToken']; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); if ($this->validate()) { $image_name = Yii::$app->security->generateRandomString(); $this->file->saveAs('uploads/' . $image_name . '.' . $this->file->extension); $file_name = 'uploads/' . $image_name . '.' . $this->file->extension; $f = fopen("{$file_name}", "rb"); $result = $dbxClient->uploadFile("/{$image_name}" . '.' . $this->file->extension, dbx\WriteMode::add(), $f); fclose($f); $src = $dbxClient->createShareableLink($result['path']); $src[strlen($src) - 1] = '1'; $image = new Image(); $image->image_name = $image_name . '.' . $this->file->extension; $image->image_article = $article_id; $image->image_src_big = $src; //small $file_name = 'uploads/' . $image_name . '.' . $this->file->extension; $resizedFile = 'uploads/small_' . $image_name . '.' . $this->file->extension; smart_resize_image($file_name, null, 0, 100, true, $resizedFile, false, false, 100); $f = fopen("{$resizedFile}", "rb"); $result = $dbxClient->uploadFile("/small_" . "{$image_name}" . '.' . $this->file->extension, dbx\WriteMode::add(), $f); fclose($f); $src = $dbxClient->createShareableLink($result['path']); $src[strlen($src) - 1] = '1'; $image->image_src_small = $src; $image->save(); unlink($file_name); unlink($resizedFile); return true; } else { return false; } }
/** * this will transfer the dbBackup zip to dropbox(LEAD-140) */ public function transferZip() { $root_dir = dirname(__DIR__); $backUpFolderPath = $root_dir . '/api/dbBackUp'; $host = gethostname(); $db_name = 'mydb'; /*dropbox settings starts here*/ $dropbox_config = array('key' => 'xxxxxxxx', 'secret' => 'xxxxxxxxx'); $appInfo = dbx\AppInfo::loadFromJson($dropbox_config); $webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0"); $accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); /*dropbox settings ends here*/ $current_date = date('Y-m-d'); $backUpFileName = $current_date . '_' . $db_name . '.sql.zip'; $fullBackUpPath = $backUpFolderPath . '/' . $backUpFileName; if (file_exists($backUpFolderPath)) { $files = scandir($backUpFolderPath); //retrieve all the files foreach ($files as $file) { if ($file == $backUpFileName) { // file matches with the db back up file created today /* transfer the file to dropbox*/ $f = fopen($fullBackUpPath, "rb"); $dbxClient->uploadFileChunked("/{$backUpFileName}", dbx\WriteMode::add(), $f); fclose($f); echo 'Upload Completed'; } } } }
public function getFilesFromPath($index, $path, $access_token) { $client = new dbx\Client($access_token, "PHP"); #get file information from current path; $data = $client->getMetadataWithChildren("{$path}"); #if the file has 'content' (directory) print out the information like normal if (array_key_exists('contents', $data) && $data['is_dir'] == 1) { $return_dropfiles = array('type' => 'folder'); $return_dropfiles['content'] = []; $return_dropfiles['service'] = 1; $return_dropfiles['index'] = $index; foreach ($data['contents'] as $file) { $temp = []; $path = $file['path']; //parsing out the filename from the path $namefile = explode('/', $path); $num = count($namefile) - 1; $temp['name'] = $namefile[$num]; $temp['size'] = $file['size']; $temp['kind'] = $file['icon']; $temp['path'] = $path; array_push($return_dropfiles['content'], $temp); } return $return_dropfiles; } else { $link = array('type' => 'file'); $link['service'] = '1'; $link['link'] = $client->createTemporaryDirectLink($data['path']); return $link; } }
function upload_file_to_dropbox($params = array()) { if (!$params) { return; } if (!($filename = pathinfo($params['source'], PATHINFO_BASENAME))) { return; } /* copy file to Dropbox */ echo "\naccessing Dropbox...\n"; if (!($dbxClient = new dbx\Client(@$params['dropbox_access_token'], "PHP-Example/1.0"))) { return; } /* $accountInfo = $dbxClient->getAccountInfo(); print_r($accountInfo); */ if ($f = Functions::file_open(CONTENT_RESOURCE_LOCAL_PATH . $filename, "rb")) { if ($info = $dbxClient->getMetadata($params['dropbox_path'] . $filename)) { $dbxClient->delete($params['dropbox_path'] . $filename); echo "\nexisting file deleted\n"; } else { echo "\nfile does not exist yet\n"; } if ($info = $dbxClient->uploadFile($params['dropbox_path'] . $filename, dbx\WriteMode::add(), $f)) { echo "\nfile uploaded OK\n"; return true; } else { echo "\nfile not uploaded!\n"; } fclose($f); } return false; }
public function closeEditor(Request $request) { $dbxClient = $this->getDropboxClient(); $LocalAddress = $request->input('LocalAddress'); $LocalName = $request->input('LocalName'); $DropBoxFile = $request->input('DropBoxFile'); // $dropboxFileName = $request->input('fileName'); file_put_contents($LocalAddress, $_POST['text']); $editContent = array(); $editContent[0] = htmlspecialchars($_POST['text']); //updated text $editContent[1] = $LocalAddress; // full local folder name with location $editContent[2] = $LocalName; //full local file name $editContent[3] = $DropBoxFile; //full dropbox path with name $LocalName = str_replace(' ', '', $LocalName); $f = fopen($editContent[1], "rb"); $result = $dbxClient->uploadFile($editContent[3], dbx\WriteMode::force(), $f); fclose($f); $dropboxObject = Dropbox::where('userId', Auth::id())->firstOrFail(); $access_token = $dropboxObject->accessToken; $dropboxClient = new dbx\Client($access_token, "PHP-Example/1.0"); $folderMetadata = $dropboxClient->getMetadataWithChildren("/"); $this->deleteFile($LocalAddress); return view('pages.dropbox')->with('dropboxData', $folderMetadata); }
public function uploadFile(\Dropbox\Client $dropboxClient) { $remotePath = rtrim($this->folder, "/") . "/" . $this->file['name']; $fileHandle = fopen($this->file['tmp_name'], "rb"); $this->result = $dropboxClient->uploadFile($remotePath, \Dropbox\WriteMode::add(), $fileHandle); fclose($fileHandle); }
public function generate() { if (PHP_SAPI != 'cli') { throw new \Exception("This script only can be used in CLI"); } $config = $this->config->database; system('/usr/bin/mysqldump -u ' . $config->username . ' -p' . $config->password . ' -r /tmp/phosphorum.sql ' . $config->dbname); system('bzip2 /tmp/phosphorum.sql'); $sourcePath = '/tmp/phosphorum.sql.bz2'; if (!file_exists($sourcePath)) { throw new \Exception("Backup could not be created"); } list($accessToken, $host) = AuthInfo::loadFromJsonFile(APP_PATH . '/app/config/backup.auth'); $client = new Client($accessToken, "phosphorum", null, $host); $dropboxPath = '/phosphorum.sql.bz2'; $pathError = Path::findErrorNonRoot($dropboxPath); if ($pathError !== null) { throw new \Exception("Invalid <dropbox-path>: {$pathError}"); } try { $client->delete($dropboxPath); } catch (\Exception $e) { // ... } $size = null; if (\stream_is_local($sourcePath)) { $size = \filesize($sourcePath); } $fp = fopen($sourcePath, "rb"); $client->uploadFile($dropboxPath, WriteMode::add(), $fp, $size); fclose($fp); @unlink($sourcePath); }
function crearCarpeta($folio, $tipo = "PREVIO") { $empresaSes = str_replace(" ", "_", $_SESSION["empresa"]); global $cliente_id; //cliente de dropbox try { $appInfo = dbx\AppInfo::loadFromJsonFile("../includes/Dropbox/config.json"); $accessToken = "jxxJCQnl2ykAAAAAAAAAGRmgdiFo8REFSCcJ-sb19QyT2lPiEEV8g7GiyB2booGP"; // desde la pagina de app console $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); $root = "/examenes"; $empresa = "/" . $empresaSes; $folder = "/" . $folio; //este va a ser el folio del paciente $path = $root . $empresa . $folder; //creamos el folder $createFolder = $dbxClient->createFolder($path); //subimos los archivos si se creó el folder if ($createFolder) { if ($cliente_id == 479) { $files_root = "../archivos"; $files_emp = "/{$empresaSes}"; $files_type = "/{$tipo}"; $files_path = $files_root . $files_emp . $files_type; foreach (scandir($files_path) as $d) { if ($d == "." || $d == "..") { continue; } $archivos[] = array("filename" => $path . "/" . $d, "file" => file_get_contents("{$files_path}/{$d}")); } } else { switch ($tipo) { case 'PREVIO': $archivos = array(array("filename" => $path . "/Audiometria.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/PREVIO/Audiometria.xlsx")), array("filename" => $path . "/Electrocardiograma.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/PREVIO/Electrocardiograma.xlsx")), array("filename" => $path . "/Historia_Clinica.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/PREVIO/Historia_Clinica.xlsx")), array("filename" => $path . "/Radiografias.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/PREVIO/Radiografias.xlsx"))); break; case 'STAFF': $archivos = array(array("filename" => $path . "/Audiometria.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/STAFF/Audiometria.xlsx")), array("filename" => $path . "/Electrocardiograma.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/STAFF/Electrocardiograma.xlsx")), array("filename" => $path . "/Historia_Clinica.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/STAFF/Historia_Clinica.xlsx")), array("filename" => $path . "/Radiografias.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/STAFF/Radiografias.xlsx"))); break; case 'OPERARIO': $archivos = array(array("filename" => $path . "/Audiometria.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/OPERARIO/Audiometria.xlsx")), array("filename" => $path . "/Fuerza_Equilibrio.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/OPERARIO/Fuerza_Equilibrio.xlsx")), array("filename" => $path . "/Historia_Clinica.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/OPERARIO/Historia_Clinica.xlsx")), array("filename" => $path . "/Radiografias.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/OPERARIO/Radiografias.xlsx"))); break; default: $archivos = array(array("filename" => $path . "/Audiometria.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/Audiometria.xlsx")), array("filename" => $path . "/Electrocardiograma.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/Electrocardiograma.xlsx")), array("filename" => $path . "/Historia_Clinica.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/Historia_Clinica.xlsx")), array("filename" => $path . "/Radiografias.xlsx", "file" => file_get_contents("../archivos/{$empresaSes}/Radiografias.xlsx"))); break; } } foreach ($archivos as $d) { $dbxClient->uploadFileFromString($d["filename"], dbx\WriteMode::add(), $d["file"]); } } } catch (Exception $e) { } }
/** * {@inheritdoc} */ public function upload($archive) { $fileName = explode('/', $archive); $pathError = Dropbox\Path::findErrorNonRoot($this->remotePath); if ($pathError !== null) { throw new UploadException(sprintf('Invalid path "%s".', $archive)); } $client = new Dropbox\Client($this->access_token, 'CloudBackupBundle'); $size = filesize($archive); $fp = fopen($archive, 'rb'); $client->uploadFile($this->remotePath . '/' . end($fileName), Dropbox\WriteMode::add(), $fp, $size); fclose($fp); }
/** * [save_to_dbx description] * @param [type] $from [description] * @param [type] $to [description] * @return [type] [description] */ public static function save_to_dbx($from, $to) { if ($from && $to && \File::exists($from)) { try { $dbx_client = new Dbx\Client(\Config::get('my.dropbox.token'), "PHP-Example/1.0"); $f = fopen($from, "rb"); $result = $dbx_client->uploadFile($to, Dbx\WriteMode::add(), $f); fclose($f); } catch (\Exception $e) { print $e . "\n"; \Log::error($e); } } }
/** * @param string $path * @param array|null $extensionFilter * @param bool $includeExtension * @return array Array of filenames * @todo Directories */ public function getFilesList($path, array $extensionFilter = null, $includeExtension = true) { $metadata = $this->dropbox->getMetadataWithChildren('/' . $path); $list = []; foreach ($metadata['contents'] as $file) { $pathParts = pathinfo($file['path']); if (!$extensionFilter or in_array($pathParts['extension'], $extensionFilter)) { if ($includeExtension) { $list[] = trim($file['path'], '/'); } else { $list[] = trim($pathParts['dirname'] . '/' . $pathParts['filename'], '/\\'); } } } return $list; }
/** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $sourcePath = $target->getPathname(); $dropboxPath = $this->path . $target->getFilename(); $client = new DropboxApi\Client($this->token, "phpbu/1.1.0"); $pathError = DropboxApi\Path::findErrorNonRoot($dropboxPath); if (substr(__FILE__, 0, 7) == 'phar://') { DropboxApi\RootCertificates::useExternalPaths(); } if ($pathError !== null) { throw new Exception(sprintf('Invalid \'dropbox-path\': %s', $pathError)); } $size = null; if (stream_is_local($sourcePath)) { $size = filesize($sourcePath); } try { $fp = fopen($sourcePath, 'rb'); $res = $client->uploadFile($dropboxPath, DropboxApi\WriteMode::add(), $fp, $size); fclose($fp); } catch (\Exception $e) { throw new Exception($e->getMessage(), null, $e); } $result->debug('upload: done (' . $res['size'] . ')'); }
/** * Do the actual upload of a file resource. * * @param string $path * @param resource $resource * @param WriteMode $mode * * @return array|false file metadata */ protected function uploadStream($path, $resource, WriteMode $mode) { $location = $this->applyPathPrefix($path); if (!($result = $this->client->uploadFile($location, $mode, $resource))) { return false; } return $this->normalizeResponse($result, $path); }
public function getFileUrl($hash) { if (!($remoteFile = $this->fileExists($hash))) { throw new \RuntimeException('File not found'); } list($url, $expiration) = $this->client->createTemporaryDirectLink($remoteFile); return $url; }
/** * Do the actual upload of a file resource. * * @param string $path * @param resource $resource * @param WriteMode $mode * * @return array|false file metadata */ protected function uploadStream($path, $resource, WriteMode $mode) { $location = $this->applyPathPrefix($path); // If size is zero, consider it unknown. $size = Util::getStreamSize($resource) ?: null; if (!($result = $this->client->uploadFile($location, $mode, $resource, $size))) { return false; } return $this->normalizeResponse($result, $path); }
/** * @return bool */ public function send() { $sent = true; $files = $this->backup->getFilesTobackup(); foreach ($files as $file => $name) { $file = fopen($file, 'r'); $upload = $this->dropbox->uploadFile($this->folder . '/' . $name, \Dropbox\WriteMode::force(), $file); if (!$upload) { $sent = false; echo 'DROPBOX upload manqu�e de ' . $file . ' vers ' . $this->folder . $name; } } $streams = $this->backup->getStreamsTobackup(); foreach ($streams as $stream => $name) { $upload = $this->dropbox->uploadFileFromString($this->folder . '/' . $name, \Dropbox\WriteMode::force(), $stream); if (!$upload) { $sent = false; echo 'DROPBOX upload manqu�e de ' . $file . ' vers ' . $this->folder . $name; } } return $sent; }
/** * Get an array of all files in a directory. * * @param string $directory * @return array */ public function files($directory) { $files = array(); $metadata = $this->dropbox->getMetadataWithChildren($this->pathRoot . $directory); if (isset($metadata['contents']) && is_array($metadata['contents'])) { foreach ($metadata['contents'] as $file) { if ($file['is_dir'] == false) { $files[] = $file['path']; } } } return $files; }
/** * Upload file to dropbox * @param init $comment_id * @param init $project_id * @param array $commentdata * @return void */ function upload_file_dropbox($post_id = 0, $attachment_id) { require_once MDROP_PATH . '/lib/dropbox/autoload.php'; $accesstoken = mdrop_get_token(get_current_user_id()); //'v1FIiYf35K4AAAAAAAADPLhrp-T8miNShTgeuJ5zrDmyb39gf411tgDJx22_ILSK'; //$this->dropbox_accesstoken; $dbxClient = new dbx\Client($accesstoken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); $post = get_post($post_id); $files = get_attached_file($attachment_id); $file_name = basename(get_attached_file($attachment_id)); $drop_path = '/EmailAttachment/' . $post->post_title . '/' . $file_name; $shareableLink = $dbxClient->createShareableLink($drop_path); if (!empty($shareableLink)) { return; } $f = fopen($files, "rb"); $uploaded_file = $dbxClient->uploadFile($drop_path, dbx\WriteMode::add(), $f); fclose($f); $dropbox_file_path = $uploaded_file['path']; $shareableLink = $dbxClient->createShareableLink($drop_path); $this->update_dropbox_shareablelink($attachment_id, $shareableLink); $this->update_dropbox_filepath($attachment_id, $dropbox_file_path); }
public function retrieveListing($dir, $recursive = true) { $listing = array(); $directory = rtrim($dir, '/.'); $length = strlen($directory) + 1; $location = $this->prefix($directory); if (!($result = $this->client->getMetadataWithChildren($location))) { return array(); } foreach ($result['contents'] as $object) { $listing[] = $this->normalizeObject($object, substr($object['path'], $length)); if ($recursive && $object['is_dir']) { $listing = array_merge($listing, $this->retrieveListing($object['path'])); } } return $listing; }
public function listContents($directory = '', $recursive = false) { $listing = array(); $directory = trim($directory, '/.'); $location = $this->applyPathPrefix($directory); if (!($result = $this->client->getMetadataWithChildren($location))) { return array(); } foreach ($result['contents'] as $object) { $path = $this->removePathPrefix($object['path']); $listing[] = $this->normalizeObject($object, $path); if ($recursive && $object['is_dir']) { $listing = array_merge($listing, $this->listContents($path, true)); } } return $listing; }
public function listContents($directory = '', $recursive = false) { $listing = array(); $directory = trim($directory, '/.'); $prefixLength = strlen($this->prefix); $location = '/' . trim($this->prefix($directory), '/'); if (!($result = $this->client->getMetadataWithChildren($location))) { return array(); } foreach ($result['contents'] as $object) { $path = substr($object['path'], $prefixLength); $listing[] = $this->normalizeObject($object, trim($path, '/')); if ($recursive && $object['is_dir']) { $listing = array_merge($listing, $this->listContents($path)); } } return $listing; }
function __construct($accessToken, $clientIdentifier, $userLocale = null) { parent::__construct($accessToken, $clientIdentifier, $userLocale); // The $host parameter is sort of internal. We don't include it in the param list because // we don't want it to be included in the documentation. Use PHP arg list hacks to get at // it. $host = null; if (\func_num_args() == 4) { $host = \func_get_arg(3); dbx\Host::checkArgOrNull("host", $host); } if ($host === null) { $host = dbx\Host::getDefault(); } //$this->host = $host; // These fields are redundant, but it makes these values a little more convenient // to access. $this->myApiHost = $host->getApi(); //$this->contentHost = $host->getContent(); }
?> </tbody> </table> <body> <!--side bar navigation--> <div id="page-sidebar"> <div> <a id="linkaccount" href = "linkaccount.php">Link Account</a> <a id="logout" href = "logout.php">Log Out</a> </div> <div id="accountInfo"> <?php #grabs quota from each account and shows you how much space you have used so far $accounts = query("SELECT * FROM dropbox_accounts WHERE id = ?", $_SESSION["id"]); foreach ($accounts as $account) { $client = new dbx\Client($account["dropbox_accessToken"], "PHP"); $userData = $client->getAccountInfo(); $email = $account["dropbox_email"]; $normalbytes = $userData['quota_info']['normal']; $quotabytes = $userData['quota_info']['quota']; #format_bytes is in config.php converts bytes to more readable format. print "<br><a class=\"emaillink\" href=\"index.php?{$email}&/\">" . $email . '</a>:' . '</br>' . format_bytes($normalbytes) . ' out of ' . format_bytes($quotabytes) . '</br>'; } ?> </div> <!--example from plupload, filelist will show if you dont have flash, or HTML5--> <div id="filelist">Your browser doesn't have Flash, Silverlight or HTML5 support.</div> <br /> <!--clicking on of these will trigger actions in the script below--> <div id="container"> <a id="pickfiles" href="javascript:;">[Select files]</a>
use Dropbox as dbx; $dropbox_config = array('key' => 'c8jlvwm238snfvt', 'secret' => 'ij8qwmb3schujpr'); /*$appInfo = dbx\AppInfo::loadFromJson($dropbox_config); $webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0"); $authCode = trim('4DK3_Q9x-YAAAAAAAAAANH7Nbq9GAa42leQ3914ju_8'); $authorizeUrl = $webAuth->start(); echo "1. Go to: " . $authorizeUrl . "<br>"; echo "2. Click \"Allow\" (you might have to log in first).<br>"; echo "3. Copy the authorization code and insert it into $authCode.<br>"; list($accessToken, $dropboxUserId) = $webAuth->finish($authCode); echo "Access Token: " . $accessToken . "<br>";*/ $accessToken = '4DK3_Q9x-YAAAAAAAAAANZ5B_dVR1tKG78PDXJR4WTWXdCmo0vTSi_enWGrupgSW'; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); /****** Download csv file from dropbox account ***********/ $fa = fopen("data-a.csv", "w+b"); $fileMetadata_a = $dbxClient->getFile("/data-a.csv", $fa); fclose($fa); print_r($fileMetadata_a); $fb = fopen("data-b.csv", "w+b"); $fileMetadata_b = $dbxClient->getFile("/data-b.csv", $fb); fclose($fb); print_r($fileMetadata_b); /****** Get csv data from data-a.csv file ***********/ if (false !== ($ih = fopen('data-a.csv', 'r'))) { while (false !== ($data = fgetcsv($ih))) { $csvDataA[] = array($data[0], $data[2], $data[4], $data[5]); } }
// Respond with an HTTP 400 and display error page... } catch (dbx\WebAuthException_BadState $ex) { // Auth session expired. Restart the auth process. header('Location: /dropbox-auth-start'); } catch (dbx\WebAuthException_Csrf $ex) { error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage()); // Respond with HTTP 403 and display error page... } catch (dbx\WebAuthException_NotApproved $ex) { error_log("/dropbox-auth-finish: not approved: " . $ex->getMessage()); } catch (dbx\WebAuthException_Provider $ex) { error_log("/dropbox-auth-finish: error redirect from Dropbox: " . $ex->getMessage()); } catch (dbx\Exception $ex) { error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage()); } print "Access Token: " . $accessToken . "\n"; $dbxClient = new dbx\Client(trim($accessToken), "my-app/1.0"); $f = fopen("./data-b.csv", "a+"); $fileMetadata = $dbxClient->getFile("/data-b.csv", $f); fclose($f); $fa = fopen("./data-a.csv", "a+"); $fileMetadata = $dbxClient->getFile("/data-a.csv", $fa); fclose($fa); echo '<pre>'; $data_csv = array(); $file = fopen("data-a.csv", "r"); while (!feof($file)) { $temp = fgetcsv($file); if (!empty($temp)) { $key = $temp[1]; unset($temp[1]); unset($temp[3]);
protected function legacy() { echo "dropbox test"; /** @var \Shockwavedesign\Mail\Dropbox\Model\Dropbox\User $dropboxUser */ $dropboxUser = $this->scopeConfig->getDropboxUser(); $key = $this->config->getValue('system/smtp/dropbox_key', ScopeInterface::SCOPE_STORE); $secret = $this->config->getValue('system/smtp/dropbox_secret', ScopeInterface::SCOPE_STORE); $accessToken = $dropboxUser->getAccessToken(); $path = $this->config->getValue('system/smtp/dropbox_host_temp_folder_path', ScopeInterface::SCOPE_STORE); $appInfo = dbx\AppInfo::loadFromJson(array('key' => $key, 'secret' => $secret)); //$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0"); //$authorizeUrl = $webAuth->start(); //echo "1. Go to: " . $authorizeUrl . "\n"; //echo "2. Click \"Allow\" (you might have to log in first).\n"; //echo "3. Copy the authorization code.\n"; //$authCode = "WDUOKE3OsNIAAAAAAAATNEuROlA8b_uXFy0zJ6Rb_XM"; //list($accessToken, $dropboxUserId) = $webAuth->finish($authCode); //print "DropboxUserId: " . $dropboxUserId . "Access Token: " . $accessToken . "\n"; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); print_r($accountInfo); /* $f = fopen($path . "test.txt", "rb"); $result = $dbxClient->uploadFile("/test.txt", dbx\WriteMode::add(), $f); fclose($f); print_r($result); */ $folderMetadata = $dbxClient->getMetadataWithChildren("/"); print_r($folderMetadata); $f = fopen($path . "test.txt", "w+b"); $fileMetadata = $dbxClient->getFile("/test.txt", $f); fclose($f); print_r($fileMetadata); }
public function createShareLink(Request $request) { $filePath = $request->input('hidden-file-path'); $dropboxObject = Dropbox::where('userId', Auth::id())->firstOrFail(); $access_token = $dropboxObject->accessToken; $dropboxClient = new dbx\Client($access_token, "PHP-Example/1.0"); $url = $dropboxClient->createShareableLink($filePath); $data = array('public_url' => $url, 'userName' => $dropboxObject->username); return View("pages.shareLink")->with('publicLink', $data); //die(); }
<?php # Include the Dropbox SDK libraries require_once "../components/lib/Dropbox/autoload.php"; use Dropbox as dbx; $accessToken = "lDdQ_znbyQAAAAAAAAAADJ22hHnEgTDhHf6KtzH359oJUEQQ2qTc_TtEF8_ILBry"; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); $accountInfo = $dbxClient->getAccountInfo(); echo "<pre>"; print_r($accountInfo); /*$file_name = "Marian3.png"; $f = fopen("$file_name", "rb"); $result = $dbxClient->uploadFile("/$file_name", dbx\WriteMode::add(), $f); fclose($f); print_r($result); $src = $dbxClient->createShareableLink($result['path']); $src[strlen($src) - 1] = '1'; echo $src; echo '<img src='."$src".' height="300px">'.'<br>';*/ /*$files = $dbxClient->getMetadataWithChildren("/")['contents']; //print_r($files); for($i = 0; $i < count($files); $i++) if (strpos($files[$i]['mime_type'], "image") !== false){ $src = $dbxClient->createShareableLink($files[$i]['path']); $src[strlen($src) - 1] = '1'; echo '<img src='."$src".' height="300px">'.'<br>'; }*/ /*$f = fopen("$file_name", "w+b");
// ---------------------- Send SMS -------------------- echo "\n"; echo "------------Download Call Recordings to dropbox ----------------"; echo "\n"; try { // Dropbox Authentication $appInfo = dbx\AppInfo::loadFromJsonFile("app/config.json"); $webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0"); $authorizeUrl = $webAuth->start(); echo "1. Go to: " . $authorizeUrl . "\n"; echo "2. Click \"Allow\" (you might have to log in first).\n"; echo "3. Copy the authorization code.\n"; $authCode = \trim(\readline("Enter the authorization code here: ")); list($accessToken, $dropboxUserId) = $webAuth->finish($authCode); print "Access Token: " . $accessToken . "\n"; $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0"); // RC call logs $callRecordings = $platform->get('/account/~/extension/~/call-log', array('type' => 'Voice', 'withRecording' => 'True'))->json()->records; $timePerRecording = 6; foreach ($callRecordings as $i => $callRecording) { if (property_exists($callRecording, 'recording')) { $id = $callRecording->recording->id; print "Downloading Call Log Record {$id}" . PHP_EOL; $uri = $callRecording->recording->contentUri; print "Retrieving {$uri}" . PHP_EOL; $apiResponse = $platform->get($callRecording->recording->contentUri); $ext = $apiResponse->response()->getHeader('Content-Type')[0] == 'audio/mpeg' ? 'mp3' : 'wav'; $start = microtime(true); // Store the file locally file_put_contents("/Recordings/sample_{$id}.{$ext}", $apiResponse->raw()); // Push the file to DropBox