How to upload database using Dropbox? - database

I've just created a Barcode Scanner app and have a database of barcode. I want to upload/sync this database to the company's server then another programmer can get and build website UI. Unfortunately, our server is not public (but it can connect internet through proxy), so I want to use Dropbox to do that. Could you please give me a useful sample code or tell me the best way to upload/sync database in this case? I am extremely grateful for your help!

Alright, assuming your database is a MySQL DB with a host environment that lets you run cron jobs, access your FTP, etc... here's a possible code snippet for you, I just had to do this myself with the Dropbox API, you can actually read the full post here for a walk-thru (Dropbox API and MySQL DB Dump/Upload
<?php
# Include the Dropbox SDK libraries
require_once __DIR__."/dropbox-sdk/lib/Dropbox/autoload.php";
use \Dropbox as dbx;
//your access token from the Dropbox App Panel
$accessToken = 'NOT-A-REAL-TOKEN-REPLACE-THIS-QM8jS0z1w1t-REPLACE-THIS-TOKEN';
//run the MySQL dump and zip;
// location of your temp directory
$tmpDir = "your_temp_dir";
// username for MySQL
$user = "DB_user";
// password for MySQL
$password = "DB_password";
// database name to backup
$dbName = "DB_name";
// hostname or IP where database resides
$dbHost = "your_hostname";
// the zip file will have this prefix
$prefix = "sql_db_";
// Create the database backup file
$sqlFile = $tmpDir.$prefix.date('Y_m_d_h:i:s').".sql";
$backupFilename = $prefix.date('Y_m_d_h:i:s').".tgz";
$backupFile = $tmpDir.$backupFilename;
$createBackup = "mysqldump -h ".$dbHost." -u ".$user." --password='".$password."' ".$dbName." --> ".$sqlFile;
//echo $createBackup;
$createZip = "tar cvzf $backupFile $sqlFile";
//echo $createZip;
exec($createBackup);
exec($createZip);
//now run the DBox app info and set the client; we are naming the app folder SQL_Backup but CHANGE THAT TO YOUR ACTUAL APP FOLDER NAME;
$appInfo = dbx\AppInfo::loadFromJsonFile(__DIR__."/config.json");
$dbxClient = new dbx\Client($accessToken, "SQL_Backup");
//now the main handling of the zipped file upload;
//this message will send in a system e-mail from your cron job (assuming you set up cron to email you);
echo("Uploading $backupFilename to Dropbox\n");
//this is the actual Dropbox upload method;
$f = fopen($backupFile, "rb");
$result = $dbxClient->uploadFile('/SQL_Backup/'.$backupFilename, dbx\WriteMode::force(), $f);
fclose($f);
// Delete the temporary files
unlink($sqlFile);
unlink($backupFile);
?>
You also need to make a config.json file like so:
{
"key": "YOUR_KEY_FROM_DROPBOX_APP_PANEL",
"secret": "YOUR_SECRET_FROM_DROPBOX_APP_PANEL"
}
You will need to create a new Dropbox app under your Dropbox account to get your key and secret, and to generate the auth code for your username, do that here when logged in: https://www.dropbox.com/developers/apps
You also need to download the Dropbox PHP SDK library to put on your server in the same folder as this PHP code above, find that here: https://www.dropbox.com/developers/core/sdks/php
Hope this helps; if you need more step-by-step or your developer does, go that link at the top for a full walk through.

Related

wordpress function with custom database

I am writing a WordPress plugin.
In one program, I capture the WordPress user id and write it to a file in a custom database.
Another program connects to the custom database, retrieves multiple rows having the user id:
$connection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$sql = "SELECT ...";
$prep = $connection->prepare($sql);
and tries to access the wordpress function after retrieving each record:
$user_info = get_userdata($user_id);
As soon as the get_userdata function is executed, the programs dies.
Do I need to connect to the wordpress database?
If so, how?
First of all, Why you have made database connection manually this way as you can able to use global variable "global $wpdb;" and then able to write query based on "$wpdb".
Second thing, you might declare that $user_id variable as global, so can access it globally in file or you should define in functions.php file and check for their availability.
Please let me know if any of this solution does not work for you with details.

How to create database use servlet?

I want to create tables in jsp when user run the jsp file first time,like we install wordpress,it can create table by itself.Can it use the sql file?
PS:just because my friend ask me to make a jsp website,in his computer of course,,but he know nothing about mysql,so I think I should let the program create database,like we install wordpress,we just enter username and password ,it can create everything for us.
This class will execute a script from a file: http://pastebin.com/f10584951
Use something like this inside a JSP page.
ScriptRunner scriptRunner = new ScripRunner(connection);
Reader reader = new FileReader("path to file");
scriptRunner.runScript(reader);
connection.commit();

Yii Dynamic DB Connection according to user with master database

My project is on the basis of multi-tenent SaaS.
I have multiple clients (companies) and each client has multiple users - they all will use the same database layout.
Each client has their own database, so during user authentication, I want to Build a master database that associates the user with a company database for that user.
The structure of each database is identical... only the data is different.
So that we can keep the different database for the different company, that will not going to mix in data in database.
The number of clients (and therefor the number of databases) is unknown when the application is written, so it is not possible to include all the connections in the bootstrap script.
Now, what I want to do is, dynamically alter the DB connection that is in the bootstrap or have the ability to dynamically create a new connection for the user signing in. Is there a simple solution for this in Yii and still use AR , query builder ?
I saw this solution but not working for me http://www.yiiframework.com/forum/index.php?/topic/5385-dynamic-db-connection/
This is how my config file looks today for the script running one database, i want to call a master database that controls which database the user belongs to and the app uses in Yii, any idea?
<? php
$language = 'en';
$currencyBaseCode = 'USD';
$theme = 'default';
$connectionString = 'mysql:host=localhost;port=3306;dbname=master';
$username = 'root';
$password = 'YOUR PASS';
$memcacheServers = array( // An empty array means memcache is not used.
array(
'host' => '127.0.0.1',
'port' => 11211, // This is the default memcached port.
'weight' => 100,
),
);
$adminEmail = 'EMAIL ADDRESS';
$installed = true; // Set to true by the installation process.
$maintenanceMode = false; // Set to true during upgrade process or other maintenance tasks.
$instanceConfig = array(); //Set any parameters you want to have merged into configuration array.
//#see CustomManagement
$instanceConfig['components']['request']['hostInfo'] = 'website url';
$instanceConfig['components']['request']['scriptUrl'] = '/app/index.php';
$urlManager = array (); // Set any parameters you want to customize url manager.
? >
Define the master database in the config file, and use the normal AR class to connect to it to retrieve the credentials. Then, close the connection.
Then extend the AR class, specifically the getDbConnection() method. Get the relevant credentials, and pass them as a parameters to a new CDbConnection object.
The initial DB request to get the credentials is going to be a huge performance drag, so you should really store them in-memory with Redis or Memcached. Yii doesn't do that natively.
There are a few different ways around this:
Different front controllers loading different config files, each of which is dynamically generated or destroyed by a separate app.
One big database. Each record has a key to define which client it belongs to.
One big database. Tables can be duplicated by using a client name as part of the table name.
None of these will be easy with Yii, as this is not really something Yii was designed to do.

Drupal Password set

I have to reset my password direct through database for that I used query
UPDATE users SET pass = md5('NEWPASSWORD') WHERE name = 'admin'
but still I am not able to login.
Can you please tell me where I am going wrong?
With drupal 7, password are no more encrypted through md5.
There are several way to reset a password in drupal7.
Using drush :
drush upwd admin --password="newpassword"
Without drush, if you have a cli access to the server :
cd <drupal root directory>
php scripts/password-hash.sh 'myPassword'
Now copy the resultant hash and paste it into the query:
update users set name='admin', pass='pasted_big_hash_from_above' where uid=1;
If you are working on a remote environment on which you cannot connect, you can put this specified code in a file such as password.php such as this one:
<?php
if (isset($_GET['p'])) {
require_once dirname(__FILE__) . '/includes/bootstrap.inc';
require_once dirname(__FILE__) . '/includes/password.inc';
print _password_crypt('sha512', $_GET['p'], _password_generate_salt(DRUPAL_HASH_COUNT));
exit();
}
print "No password to hash.";
And then hit your site using: http://domain.tld/password.php?p=MyPassword. The hash will appear on your browser's tab.
Don't forget to remove it once you done it.
Are you locked out of your account? If you've got DB access then try clearing out the "flood" table.

Exporting files from Basecamp

I've been looking around for a long time how to get files from Basecamp and so far it seems like a 'mission impossible', but I wanted to ask here as well:
Is there any way to get files from Basecamp projects and, if there is one, how?
Thanks in advance.
Edited: I mean how to get the uploaded files. You can export all project data except the files you have uploaded there.
You can export everything from Basecamp using the following steps.
Log in using Chrome.
Copy Cookie header from a page document
request in Chrome Developer tools.
wget --mirror -e robots=no
--reject logout --no-cookies 'http://your-subdomain.basecamphq.com' --header <pasted-cookie-header>
Matt McClure's answer was spot on but a couple of things held me up;
To find the required cookie in Chrome Developer tools, click on Network icon on top and then Headers tab.
Copy the entire cookie section from the 'request headers' section, including the 'Cookie:' label
Paste the entire string with quotes where matt indicated <pasted-cookie-header> as follows;
wget --mirror -e robots=no --reject logout --no-cookies 'http://your-subdomain.basecamphq.com' --header 'Cookie: session_token=c6a1ea88a0187b88025e; transition_token=BAhbB2kDA0VjSXU6CVRpbWUNqB...'
(I've shortened the cookie string for clarity)
The BaseCamp API purports to offer FULL access including files.
Basecamp API documentation http://developer.37signals.com/basecamp/
List of wrappers/libraries http://developer.37signals.com/
If you have any knowledge of REST you will be able to pull any/all data out (modulo rate limiting) manually and then do whatever you like with it.
Incidentally, if you write a tool that lets me move a project from one account to another, I'll pay good money for that!
Both Matt and Peter already proposed using wget --mirror which I think it is the easiest solution out there. However, I was unable to properly copy the cookies from Google Chrome.
Instead I went on a slightly different direction and used the Chrome cookie.txt export extension to copy all cookies as plain text to a cookies.txt file.
My wget command then looked like this:
wget --mirror -e robots=no --reject logout 'http://yourdomain.basecamphq.com' --load-cookies cookies.txt
Additional note for Mac users: wget can be easily installed with homebrew:
brew install wget
basecamp offers you to export your projects in XML, HTML - and there is also a way to get it in PDF. this information could be found in the help/faq section of basecamp: http://basecamphq.com/help/general#exporting_data
more about the PDF export: http://37signals.blogs.com/products/2008/02/export-a-baseca.html
Use this tool for Windows.
In trial mode, this tool will allow three projects to be downloaded from base, will list all the projects on your base account after you login using your basecamp credentials.
Import you Basecamp Classic project to the new Basecamp
Export Data from new Basecamp
Wait
Get email that it's done and download the zip file
You can set up an integration between Basecamp and Dropbox to automatically transfer all your Basecamp attachments into a dedicated Dropbox folder:
http://blog.cloudwork.com/your-automatic-basecamp-dropbox-backup-step-by-step/
The integration is done by CloudWork, which has a free plan so if you don't think you'll be backing up more than 100 attachments a month, it can do it for free. Above that, there is a pricing plan.
If you have php installed on your machine, save this code to basecampfilevac.php:
<?
// make sure the folder of the script is writeable (0777)
ini_set('memory_limit', '-1');//keeps the script from timing out
function BasecampCall($endPoint, $usePrefix = true) {
// From: http://prattski.com/2008/10/22/basecamp-api-examples-using-php-and-curl-get/
$session = curl_init();
$basecampId = '[Your Basecamp Account Id Here]'; //this should be a number like 9999999, You can find it in the URL when you log into Basecamp.
$username = '[Your Basecamp Username Here]';
$password = '[Your Basecamp Password Here]';
$emailaddress = '[Your Basecamp Email Address Here]';
$basecampUrl = 'https://basecamp.com/' . $basecampId . '/api/v1/';
curl_setopt($session, CURLOPT_URL, ($usePrefix == true ? $basecampUrl : "") . $endPoint);
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($session, CURLOPT_HTTPGET, 1);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_USERAGENT, "MyApp (".$emailaddress.")");
curl_setopt($session,CURLOPT_USERPWD, $username . ":" . $password);
if(ereg("^(https)",$request)) curl_setopt($session,CURLOPT_SSL_VERIFYPEER,false);
$response = curl_exec($session);
curl_close($session);
if($usePrefix){
$r = json_decode($response);
} else {
$r = $response;
}
return $r;
}
$projects = BasecampCall('projects.json');
// For each project take name and id
foreach($projects as $proj) {
$pr = array(
"id" => (string)$proj->id,
"name" => (string)$proj->name
);
// Retrieve the attachments
echo "\nSaving attachments for project: " . $pr['name'] . "...\n";
#mkdir($pr['name']);
$filesArray = array();
$n = 1;
do {
$attachments = BasecampCall("projects/" . $proj->id . "/attachments.json?page=" . $n);
if(count($attachments) > 0) {
foreach($attachments as $attachment) {
$file = pathinfo($attachment->name);
#file_put_contents($pr['name'] . "/" . $file['filename'] . (in_array($file['filename'], $filesArray) ? "-" . rand() : "") . "." . $file['extension'], BasecampCall($attachment->{'url'}, false));
$filesArray[] = $file['filename'];
echo "Saving file " . $attachment->name . "...\n";
}
}
$n++;
} while(count($attachments) == 50);
}
?>
then update the following lines with the correct information:
$basecampId = '[Your Basecamp Account Id Here]'; //this should be a number like 9999999, You can find it in the URL when you log into Basecamp.
$username = '[Your Basecamp Username Here]';
$password = '[Your Basecamp Password Here]';
$emailaddress = '[Your Basecamp Email Address Here]';
then save and execute this command: php basecampfilevac.php
This is a modified script originally from Rettger Galactic
My solution to download the Basecamp export zip-file in bash on the server was quit easy:
Follow the instructions at https://3.basecamp-help.com/article/150-export-your-basecamp-data to start the export.
Wait for Basecamp email with link to the export page.
Open the link to the export download page while having your Browser dev tools open (I'm using Firefox).
Check any GET request in the dev tools and copy that request as cURL command
Paste the cURL command in the shell and change the URL to the download link from the 'Download my export' button
Add -L flag (follow redirects) as well as --output <your_file.zip> to the cURL command.
Execute cURL command and downlad the file ;)

Resources