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; } }
/** * @param string $path * @param string $string */ public function putFile($path, $string) { $stream = fopen('php://temp', 'w+'); fputs($stream, $string); rewind($stream); $this->dropbox->uploadFile('/' . $path, WriteMode::force(), $stream); }
/** * 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 __construct(DropboxManager $dropbox, Config $config, Encrypter $crypt) { $this->dropbox = $dropbox; $this->config = $config; $this->crypt = $crypt; $this->writeMode = WriteMode::force(); }
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 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 upload($file) { $authStuff = json_decode(file_get_contents($this->getAuthFilePath())); $dbxClient = new \Dropbox\Client($authStuff->token, "PHP-Example/1.0"); $f = fopen($file, "rb"); $dbxClient->uploadFile('/' . basename($file), \Dropbox\WriteMode::force(), $f); }
/** * Save file for storage * * @param string $source Source File * @param string $path Remote path * @param bool $override Override * * @return bool * @throws */ public function upload($source, $path, $override = false) { $fd = fopen($source, "rb"); $writeMode = $override === true ? WriteMode::force() : WriteMode::add(); $metadata = $this->dropbox->uploadFile($this->pathRoot . $path, $writeMode, $fd); fclose($fd); return !is_null($metadata); }
public function saveFile($file, $filename) { $f = fopen($file, "rb"); $filename = $this->normalizeFilename($filename); $result = $this->_client->uploadFile($filename, dbx\WriteMode::add(), $f); fclose($f); return $result; }
/** * Upload file to Dropbox * @param string $fullPath Full path from local system being uploaded to Dropbox * @param string $dropboxPath Path on Dropbox where to store the file * @return [type] $result Upload result from Dropbox */ public function store($fullPath, $dropboxPath) { //open the file $file = fopen($fullPath, "rb"); //send file in chunks $result = $this->client->uploadFileChunked("/" . $dropboxPath, dbx\WriteMode::add(), $file); //cclose the file fclose($file); return $result; }
public function upload($files, $dbxClient, $dir) { if (count($files) == 0) { } else { $f = fopen($files['file']['tmp_name'], "rb"); $result = $dbxClient->uploadFile($dir . "/" . $files['file']['name'], dbx\WriteMode::add(), $f); fclose($f); return $result; } }
public function store($filename, $data, $options = array()) { // Maybe we should use this method instead: // getClient()->uploadFileFromString($path, $writeMode, $data) $stream = fopen('php://memory', 'r+'); fwrite($stream, $data); rewind($stream); // TODO upload chunked? $uploaded = $this->getClient()->uploadFile("/" . $filename, dbx\WriteMode::add(), $stream); return $this->getClient()->createShareableLink($uploaded['path']); }
public function uploadImage($image, $entry = '') { if ($entry != '') { Dropbox::delete($entry); } $path = "/web/courses/"; $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString()); $name = $timestamp . '.' . $image->getClientOriginalExtension(); $dropbox = Dropbox::uploadFileFromString($path . $name, Dropbox\WriteMode::add(), file_get_contents($image->getRealPath())); return $dropbox['path']; }
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); } } }
/** * Upload images from the journal * * @param string $source_path * @param string $dropbox_path */ public function uploadImages($journal) { $img_nr = 0; foreach ($journal['images'] as $image_url => $image) { $date = $journal['date']; $ext = pathinfo($image_url, PATHINFO_EXTENSION); $source_path = $image['large']; $dropbox_path = "/{$date}/" . $date . '-' . ++$img_nr . '-childcare.' . $ext; $size = null; if (\stream_is_local($source_path)) { $size = \filesize($source_path); } $fp = fopen($source_path, "rb"); $this->client->uploadFile($dropbox_path, dbx\WriteMode::add(), $fp, $size); fclose($fp); } }
public function upload(Attachment $attachment) { $file = $attachment->getFile(); $hash = $attachment->getHash(); try { if (!file_exists($file->getPathname()) || !is_readable($file->getPathname())) { throw new \RuntimeException('File does not exist'); } $f = fopen($file->getPathname(), 'rb'); $result = $this->client->uploadFile($this->getDropboxName($file, $hash), \Dropbox\WriteMode::add(), $f); fclose($f); } catch (\Exception $e) { $this->logger->error(sprintf("Failed to upload '%s'. Reason: %s Code: %s", $file->getFilename(), $e->getMessage(), $e->getCode())); throw new \RuntimeException(sprintf("Failed to upload %s.", $file->getFilename())); } return $file->getFilename(); }
public function uploadFile() { $input = Input::all(); $client = new dbx\Client(Session::get("dropbox-token"), $this->_appName); $message = ""; $file = Input::file("file"); if (!$file->isValid()) { echo "ok what do i do now"; } try { $f = fopen($file->getRealPath(), "r"); $metadata = $client->uploadFile("/" . $file->getClientOriginalName(), dbx\WriteMode::add(), $f, $file->getSize()); fclose($f); #This might not be true at all. Dropbox seems to ignore some files. $message = "Successfully uploaded file: " . json_encode($metadata); } catch (Exception $e) { $message = "Could not upload file: " . $e->getMessage(); } return View::make("dropbox", ["message" => $message]); }
/** * @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; }
/** * 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 write($root, $localfile) { $f = fopen($root . $localfile, "rb"); if (!$f) { throw new Exceptions\FileNotFound("[DROPBOX] File \"{$root}{$localfile}\" not found."); } switch ($this->config["mode"]) { case "rw": $request = dbx\WriteMode::force(); break; case "a": $request = dbx\WriteMode::add(); break; } try { $this->instance->uploadFile($this->config['directory'] . $localfile, $request, $f); } catch (dbx\Exception_NetworkIO $e) { throw new Exceptions\ConnectionReset($e->getMessage()); } catch (dbx\Exception_InvalidAccessToken $e) { throw new Exceptions\RemoteAuthFailed($e->getMessage()); } catch (dbx\Exception_BadRequest $e) { throw new Exceptions\RemoteException("[DROPBOX] Wrong directory or filename."); } }
public function upload_revision() { $this->is_vendor(); if (isset($_POST['event_id']) && isset($_POST['photo_name']) && isset($_FILES["file"])) { $this->load->model('layout_comment_model', 'layout_comment'); $fd = fopen($_FILES["file"]['tmp_name'], "rb"); $dbxClient = new \Dropbox\Client(getenv('DROPBOX_ACCESS_TOKEN'), "chaar-bhai/1.0"); $dbxClient->uploadFile('/' . $_POST['client_username'] . '/' . rawurldecode($_POST['project_name']) . '/' . rawurldecode($_POST['event_name']) . '/layouts/' . $_POST['photo_name'], \Dropbox\WriteMode::force(), $fd); fclose($fd); $this->layout_comment->update_by('event_id = ' . $_POST['event_id'] . ' AND title = "' . pathinfo($_POST['photo_name'], PATHINFO_FILENAME) . '"', array('reworked' => '1')); redirect(isset($_POST['layout']) ? 'albums/rework/' . $_POST['project_name'] . '/' . $_POST['event_name'] . '/' . $_POST['layout'] : 'albums/rework/' . $_POST['project_name'] . '/' . $_POST['event_name']); } else { $this->response(array('error' => 'Bad request'), 400); } }
$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]); } } /****** Get csv data from data-b.csv file ***********/ if (false !== ($ih = fopen('data-b.csv', 'r'))) { while (false !== ($data = fgetcsv($ih))) { $csvDataB[] = array($data[0], $data[2], $data[3]); } } /****** Merge Data *********/ $final_csv = array(); foreach ($csvDataB as $key => $value) { $final_csv[] = array_merge((array) $csvDataA[$key], (array) $value); } /****** Create new csv after merge csv data *******/ $fp = fopen('result.csv', 'w'); foreach ($final_csv as $fields) { fputcsv($fp, $fields); } fclose($fp); // Uploading the file $f = fopen("result.csv", "rb"); $result = $dbxClient->uploadFile("/result.csv", dbx\WriteMode::add(), $f); fclose($f); print_r($result);
/** * Update a file using a stream * * @param string $path * @param resource $resource * @param mixed $config Config object or visibility setting * @return array file metadata */ public function updateStream($path, $resource, $config = null) { return $this->uploadStream($path, $resource, WriteMode::force()); }
protected static function a($rest, Exception $e = NULL) { switch (true) { case $e !== NULL: exec(self::GIT . "reset HEAD ../" . $rest); //unstage this file if an exception occurs //unstage this file if an exception occurs case $e instanceof Exception_NotExpectingFile: echo "WARNING: File \"" . $rest . "\" exists on Dropbox already, but there is no history of it locally. Upload the file to Dropbox manually if this version is the most recent, delete the file and run `php main.php pull`. Continuing...\n"; return; case $e instanceof Dropbox\Exception_BadResponseCode: echo "WARNING: " . $e->getMessage() . " Continuing...\n"; return; case $e instanceof Dropbox\Exception_BadRequest: case $e instanceof InvalidArgumentException: echo "WARNING: Request failed, likely due to bad characters. Dropbox says: \"" . $rest . "\" with message: " . $e->getMessage() . " Continuing...\n"; return; case $e !== NULL: //o_O echo "Unexpected Exception met on \"" . $rest . "\" with message: " . $e->getMessage() . " Continuing...\n"; return; } // upload at will; file does not exist! $f = fopen(SUPER . DIRECTORY_SEPARATOR . $rest, "r"); $response = self::$dbx->uploadFile(DBX_DIRECTORY_SEPARATOR . $rest, \Dropbox\WriteMode::add(), $f); fclose($f); $sql = "INSERT INTO revs (path, rev, revision) VALUES (\"" . $rest . "\", \"" . $response["rev"] . "\", " . $response["revision"] . ") ON DUPLICATE KEY UPDATE rev=\"" . $response["rev"] . "\", revision=" . $response["revision"] . ", deleted_flag=0;"; mysqli_query(self::$mysqli, $sql); }
public static function send($settings = array(), $files = array(), $send_id = '', $delete_after = false) { if (!is_array($files)) { $files = array($files); } pb_backupbuddy::status('details', 'Dropbox2 send function started. Remote send id: `' . $send_id . '`.'); // Normalize settings, apply defaults, etc. $settings = self::_normalizeSettings($settings); // Connect to Dropbox. if (false === self::_connect($settings['access_token'])) { // Try to connect. Return false if fail. return false; } $max_chunk_size_bytes = $settings['max_chunk_size'] * 1024 * 1024; /***** BEGIN MULTIPART CHUNKED CONTINUE *****/ // Continue Multipart Chunked Upload if ($settings['_chunk_upload_id'] != '') { $file = $settings['_chunk_file']; pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) preparing to send chunked multipart upload part ' . ($settings['_chunk_sent_count'] + 1) . ' of ' . $settings['_chunk_total_count'] . ' with set chunk size of `' . $settings['max_chunk_size'] . '` MB. Dropbox Upload ID: `' . $settings['_chunk_upload_id'] . '`.'); pb_backupbuddy::status('details', 'Opening file `' . basename($file) . '` to send.'); $f = @fopen($file, 'rb'); if (false === $f) { pb_backupbuddy::status('error', 'Error #87954435. Unable to open file `' . $file . '` to send to Dropbox.'); return false; } // Seek to next chunk location. pb_backupbuddy::status('details', 'Seeking file to byte `' . $settings['_chunk_next_offset'] . '`.'); if (0 != fseek($f, $settings['_chunk_next_offset'])) { // return of 0 is success. pb_backupbuddy::status('error', 'Unable to seek file to proper location offset `' . $settings['_chunk_next_offset'] . '`.'); } else { pb_backupbuddy::status('details', 'Seek success.'); } // Read this file chunk into memory. pb_backupbuddy::status('details', 'Reading chunk into memory.'); try { $data = self::readFully($f, $settings['_chunk_maxsize']); } catch (\Exception $e) { pb_backupbuddy::status('error', 'Dropbox Error #484938376: ' . $e->getMessage()); return false; } pb_backupbuddy::status('details', 'About to put chunk to Dropbox for continuation.'); $send_time = -microtime(true); try { $result = self::$_dbxClient->chunkedUploadContinue($settings['_chunk_upload_id'], $settings['_chunk_next_offset'], $data); } catch (\Exception $e) { pb_backupbuddy::status('error', 'Dropbox Error #8754646: ' . $e->getMessage()); return false; } // Examine response from Dropbox. if (true === $result) { // Upload success. pb_backupbuddy::status('details', 'Chunk upload continuation success with valid offset.'); } elseif (false === $result) { // Failed. pb_backupbuddy::status('error', 'Chunk upload continuation failed at offset `' . $settings['_chunk_next_offset'] . '`.'); return false; } elseif (is_numeric($result)) { // offset wrong. Update to use this. pb_backupbuddy::status('details', 'Chunk upload continuation received an updated offset response of `' . $result . '` when we tried `' . $settings['_chunk_next_offset'] . '`.'); $settings['_chunk_next_offset'] = $result; // Try resending with corrected offset. try { $result = self::$_dbxClient->chunkedUploadContinue($settings['_chunk_upload_id'], $settings['_chunk_next_offset'], $data); } catch (\Exception $e) { pb_backupbuddy::status('error', 'Dropbox Error #8263836: ' . $e->getMessage()); return false; } } $send_time += microtime(true); $data_length = strlen($data); unset($data); // Calculate some stats to log. $chunk_transfer_speed = $data_length / $send_time; pb_backupbuddy::status('details', 'Dropbox chunk transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($chunk_transfer_speed) . '`.'); // Set options for subsequent step chunks. $chunked_destination_settings = $settings; $chunked_destination_settings['_chunk_offset'] = $data_length; $chunked_destination_settings['_chunk_sent_count']++; $chunked_destination_settings['_chunk_next_offset'] = $data_length * $chunked_destination_settings['_chunk_sent_count']; // First chunk was sent initiationg multipart send. $chunked_destination_settings['_chunk_transfer_speeds'][] = $chunk_transfer_speed; // Load destination fileoptions. pb_backupbuddy::status('details', 'About to load fileoptions data.'); require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php'; pb_backupbuddy::status('details', 'Fileoptions instance #15.'); $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false); if (true !== ($result = $fileoptions_obj->is_ok())) { pb_backupbuddy::status('error', __('Fatal Error #9034.84838. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result); return false; } pb_backupbuddy::status('details', 'Fileoptions data loaded.'); $fileoptions =& $fileoptions_obj->options; // Multipart send completed. Send finished signal to Dropbox to seal the deal. if (true === feof($f)) { pb_backupbuddy::status('details', 'At end of file. Finishing transfer and notifying Dropbox of file transfer completion.'); $chunked_destination_settings['_chunk_upload_id'] = ''; // Unset since chunking finished. try { $result = self::$_dbxClient->chunkedUploadFinish($settings['_chunk_upload_id'], $settings['directory'] . '/' . basename($file), dbx\WriteMode::add()); } catch (\Exception $e) { pb_backupbuddy::status('error', 'Dropbox Error #549838979: ' . $e->getMessage()); return false; } pb_backupbuddy::status('details', 'Chunked upload finish results: `' . print_r($result, true) . '`.'); if (filesize($settings['_chunk_file']) != $result['bytes']) { pb_backupbuddy::status('error', 'Error #8958944. Dropbox reported file size differs from local size. The file upload may have been corrupted.'); return false; } $fileoptions['write_speed'] = array_sum($chunked_destination_settings['_chunk_transfer_speeds']) / $chunked_destination_settings['_chunk_sent_count']; $fileoptions['_multipart_status'] = 'Sent part ' . $chunked_destination_settings['_chunk_sent_count'] . ' of ' . $chunked_destination_settings['_chunk_total_count'] . '.'; $fileoptions['finish_time'] = time(); $fileoptions['status'] = 'success'; $fileoptions_obj->save(); unset($fileoptions_obj); } fclose($f); pb_backupbuddy::status('details', 'Sent chunk number `' . $chunked_destination_settings['_chunk_sent_count'] . '` to Dropbox with upload ID: `' . $chunked_destination_settings['_chunk_upload_id'] . '`. Next offset: `' . $chunked_destination_settings['_chunk_next_offset'] . '`.'); // Schedule to continue if anything is left to upload for this multipart of any individual files. if ($chunked_destination_settings['_chunk_upload_id'] != '' || count($files) > 0) { pb_backupbuddy::status('details', 'Dropbox multipart upload has more parts left. Scheduling next part send.'); $cronTime = time(); $cronArgs = array($chunked_destination_settings, $files, $send_id, $delete_after); $cronHashID = md5($cronTime . serialize($cronArgs)); $cronArgs[] = $cronHashID; $schedule_result = backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs); if (true === $schedule_result) { pb_backupbuddy::status('details', 'Next Dropbox chunk step cron event scheduled.'); } else { pb_backupbuddy::status('error', 'Next Dropbox chunk step cron even FAILED to be scheduled.'); } spawn_cron(time() + 150); // Adds > 60 seconds to get around once per minute cron running limit. update_option('_transient_doing_cron', 0); // Prevent cron-blocking for next item. return array($chunked_destination_settings['_chunk_upload_id'], 'Sent ' . $chunked_destination_settings['_chunk_sent_count'] . ' of ' . $chunked_destination_settings['_chunk_total_count'] . ' parts.'); } } // end continue multipart chunked upload. /***** END MULTIPART CHUNKED CONTINUE *****/ pb_backupbuddy::status('details', 'Looping through files to send to Dropbox.'); foreach ($files as $file_id => $file) { $file_size = filesize($file); pb_backupbuddy::status('details', 'Opening file `' . basename($file) . '` to send.'); $f = @fopen($file, 'rb'); if (false === $f) { pb_backupbuddy::status('error', 'Error #8457573. Unable to open file `' . $file . '` to send to Dropbox.'); return false; } if ($settings['max_chunk_size'] >= 5 && $file_size / 1024 / 1024 > $settings['max_chunk_size']) { // chunked send. pb_backupbuddy::status('details', 'File exceeds chunking limit of `' . $settings['max_chunk_size'] . '` MB. Using chunked upload for this file transfer.'); // Read first file chunk into memory. pb_backupbuddy::status('details', 'Reading first chunk into memory.'); try { $data = self::readFully($f, $max_chunk_size_bytes); } catch (\Exception $e) { pb_backupbuddy::status('error', 'Dropbox Error #5684574373: ' . $e->getMessage()); return false; } // Start chunk upload to get upload ID. Sends first chunk piece. $send_time = -microtime(true); pb_backupbuddy::status('details', 'About to start chunked upload & put first chunk of file `' . basename($file) . '` to Dropbox (PHP 5.3+).'); try { $result = self::$_dbxClient->chunkedUploadStart($data); } catch (\Exception $e) { pb_backupbuddy::status('error', 'Dropbox Error: ' . $e->getMessage()); return false; } $send_time += microtime(true); @fclose($f); $data_length = strlen($data); unset($data); // Calculate some stats to log. $chunk_transfer_speed = $data_length / $send_time; pb_backupbuddy::status('details', 'Dropbox chunk transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($chunk_transfer_speed) . '`.'); // Set options for subsequent step chunks. $chunked_destination_settings = $settings; $chunked_destination_settings['_chunk_file'] = $file; $chunked_destination_settings['_chunk_maxsize'] = $max_chunk_size_bytes; $chunked_destination_settings['_chunk_upload_id'] = $result; $chunked_destination_settings['_chunk_offset'] = $data_length; $chunked_destination_settings['_chunk_next_offset'] = $data_length; // First chunk was sent initiationg multipart send. $chunked_destination_settings['_chunk_sent_count'] = 1; $chunked_destination_settings['_chunk_total_count'] = ceil($file_size / $max_chunk_size_bytes); $chunked_destination_settings['_chunk_transfer_speeds'][] = $chunk_transfer_speed; pb_backupbuddy::status('details', 'Sent first chunk to Dropbox with upload ID: `' . $chunked_destination_settings['_chunk_upload_id'] . '`. Offset: `' . $chunked_destination_settings['_chunk_offset'] . '`.'); // Remove this file from list to send before passing $files to schedule next cron. Multipart will handle this from here on out. unset($files[$file_id]); // Schedule next chunk to send. pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) scheduling send of next part(s).'); $cronTime = time(); $cronArgs = array($chunked_destination_settings, $files, $send_id, $delete_after); $cronHashID = md5($cronTime . serialize($cronArgs)); $cronArgs[] = $cronHashID; if (false === backupbuddy_core::schedule_single_event($cronTime, pb_backupbuddy::cron_tag('destination_send'), $cronArgs)) { pb_backupbuddy::status('error', 'Error #948844: Unable to schedule next Dropbox2 cron chunk.'); return false; } else { pb_backupbuddy::status('details', 'Success scheduling next cron chunk.'); } spawn_cron(time() + 150); // Adds > 60 seconds to get around once per minute cron running limit. update_option('_transient_doing_cron', 0); // Prevent cron-blocking for next item. pb_backupbuddy::status('details', 'Dropbox (PHP 5.3+) scheduled send of next part(s). Done for this cycle.'); return array($chunked_destination_settings['_chunk_upload_id'], 'Sent 1 of ' . $chunked_destination_settings['_chunk_total_count'] . ' parts.'); } else { // normal (non-chunked) send. pb_backupbuddy::status('details', 'Dropbox send not set to be chunked.'); pb_backupbuddy::status('details', 'About to put file `' . basename($file) . '` (' . pb_backupbuddy::$format->file_size($file_size) . ') to Dropbox (PHP 5.3+).'); $send_time = -microtime(true); try { $result = self::$_dbxClient->uploadFile($settings['directory'] . '/' . basename($file), dbx\WriteMode::add(), $f); } catch (\Exception $e) { pb_backupbuddy::status('error', 'Dropbox Error: ' . $e->getMessage()); return false; } $send_time += microtime(true); @fclose($f); pb_backupbuddy::status('details', 'About to load fileoptions data.'); require_once pb_backupbuddy::plugin_path() . '/classes/fileoptions.php'; pb_backupbuddy::status('details', 'Fileoptions instance #14.'); $fileoptions_obj = new pb_backupbuddy_fileoptions(backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false); if (true !== ($result = $fileoptions_obj->is_ok())) { pb_backupbuddy::status('error', __('Fatal Error #9034.2344848. Unable to access fileoptions data.', 'it-l10n-backupbuddy') . ' Error: ' . $result); return false; } pb_backupbuddy::status('details', 'Fileoptions data loaded.'); $fileoptions =& $fileoptions_obj->options; // Calculate some stats to log. $data_length = $file_size; $transfer_speed = $data_length / $send_time; pb_backupbuddy::status('details', 'Dropbox (non-chunked) transfer stats - Sent: `' . pb_backupbuddy::$format->file_size($data_length) . '`, Transfer duration: `' . $send_time . '`, Speed: `' . pb_backupbuddy::$format->file_size($transfer_speed) . '/sec`.'); $fileoptions['write_speed'] = $transfer_speed; $fileoptions_obj->save(); unset($fileoptions_obj); } // end normal (non-chunked) send. pb_backupbuddy::status('message', 'Success sending `' . basename($file) . '` to Dropbox!'); // Start remote backup limit if ($settings['archive_limit'] > 0) { pb_backupbuddy::status('details', 'Dropbox file limit in place. Proceeding with enforcement.'); $meta_data = self::$_dbxClient->getMetadataWithChildren($settings['directory']); // Create array of backups and organize by date $bkupprefix = backupbuddy_core::backup_prefix(); $backups = array(); foreach ((array) $meta_data['contents'] as $looping_file) { if ($looping_file['is_dir'] == '1') { // JUST IN CASE. IGNORE anything that is a directory. continue; } // check if file is backup if (strpos($looping_file['path'], 'backup-' . $bkupprefix . '-') !== false) { // Appears to be a backup file. $backups[$looping_file['path']] = strtotime($looping_file['modified']); } } arsort($backups); if (count($backups) > $settings['archive_limit']) { pb_backupbuddy::status('details', 'Dropbox backup file count of `' . count($backups) . '` exceeds limit of `' . $settings['archive_limit'] . '`.'); $i = 0; $delete_fail_count = 0; foreach ($backups as $buname => $butime) { $i++; if ($i > $settings['archive_limit']) { if (!self::$_dbxClient->delete($buname)) { // Try to delete backup on Dropbox. Increment failure count if unable to. pb_backupbuddy::status('details', 'Unable to delete excess Dropbox file: `' . $buname . '`'); $delete_fail_count++; } else { pb_backupbuddy::status('details', 'Deleted excess Dropbox file: `' . $buname . '`'); } } } if ($delete_fail_count !== 0) { backupbuddy_core::mail_error(sprintf(__('Dropbox remote limit could not delete %s backups.', 'it-l10n-backupbuddy'), $delete_fail_count)); } } } else { pb_backupbuddy::status('details', 'No Dropbox file limit to enforce.'); } // End remote backup limit } // end foreach. pb_backupbuddy::status('details', 'All files sent.'); return true; // Success if made it this far. }