Created
January 12, 2012 17:25
-
-
Save mre/1601874 to your computer and use it in GitHub Desktop.
Monkeypatch to get PHP my Dropbox Gallery running with the new Dropbox Gallery.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
HACK: Replace the original dropbox-gallery.php with this file. | |
Script: | |
My PHP DropBox Gallery | |
Author: | |
Jonathan Ochej, <http://2boandco.com> | |
Copyright (C): | |
2009-2010 Jonathan Ochej, <http://2boandco.com>, MIT Style License. This file is part of My PHP DropBox Gallery. | |
*/ | |
// Assurons nous que le script n'est pas executé "directement" | |
if ( !defined('DB') ) | |
exit; | |
/** | |
* Charge toutes les informations concernant la galerie | |
* | |
* @since 1.0 | |
* | |
* @return array | |
*/ | |
function db_gallery() { | |
global $db_system; | |
/* | |
Tailles d'images disponible sur la DropBox : | |
o = Original size | |
xl = max 1024px × 768px | |
l = max 640px × 480px | |
w = max 480px × 270px | |
h = max 320px × 410px | |
m = max 128px × 128px | |
i = crop 72px × 72px (always cropped) | |
s = max 65px × 65px | |
*/ | |
// Configuration par défaut | |
$gallery_default = array( | |
'title' => 'My PHP DropBox Gallery', | |
'description' => '', // Description | |
'gallery_dir' => '', // Répertoire de la galerie sur la DropBox | |
//'photos_dir' => 'photos', // Répertoire des photos (https://www.dropbox.com/[photos/gallery_dir]) | |
//'gallery_hash' => db_hash(DB_EMAIL, DB_PASSWORD), // Hash unique de la galerie | |
//'admin_hash' => db_hash(DB_EMAIL.DB_PASSWORD, DB_PASSWORD_SALT), // Hash d'authentification à l'administration | |
//'password_hash' => db_hash('password', DB_PASSWORD_SALT), // Mot de passe pour accéder à la galerie | |
'image_size' => 's,i,h,m,w,l,xl,o', // Tailles des images disponibles | |
'cache_thumbs' => false, // Active la mise en cache des Thumbs | |
//'cache_thumbs_dir' => DB_CACHE_DIR.'thumbs/', | |
'cache_thumbs_size' => 's,i,h,m,w', // Tailles des images à mettre en cache | |
'theme' => DB_THEME_DEFAULT, | |
//'theme_dir' => DB_THEME_DEFAULT_DIR, | |
'num_photo_by_page' => 12, | |
'hide_photo_ext' => true, // Cacher les extentions dans le nom d'une photo | |
//'sort_albums' => 'ASC', | |
'sort_albums' => 'DESC', | |
//'sort_photos' => 'ASC', | |
'sort_photos' => 'DESC', | |
'download_photos' => true, | |
'refresh_cache' => 24*3600, // Raffraichissement du cache en secondes (24h par defaut) | |
); | |
// Configuration utilisateur de la galerie | |
if ( file_exists(DB_DATA_DIR.'gallery.php') ) { | |
include DB_DATA_DIR.'gallery.php'; | |
if ( isset($gallery) && is_array($gallery) ) | |
$gallery = array_merge($gallery_default, $gallery); | |
} | |
if ( !isset($gallery) ) | |
$gallery = $gallery_default; | |
// iPhone theme | |
if ( (stristr($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod')) && file_exists(DB_ROOT.'themes/iphone/') ) | |
$gallery['theme'] = 'iphone'; | |
// Clean certaines données | |
$gallery['gallery_dir'] = db_trim($gallery['gallery_dir'], '/'); | |
$gallery['theme'] = db_trim($gallery['theme'], '/'); | |
// Configuration du theme | |
$cur_theme = db_get_theme_info($gallery['theme']); | |
if ( is_array($cur_theme) && isset($cur_theme['num_photo_by_page']) && intval($cur_theme['num_photo_by_page']) > 0) | |
$gallery['num_photo_by_page'] = intval($cur_theme['num_photo_by_page']); | |
// Configurations automatiques pour simplifier l'usage | |
$gallery['photos_dir'] = !empty($gallery['gallery_dir']) ? 'photos/'.rawurlencode($gallery['gallery_dir']) : 'photos'; | |
$gallery['gallery_hash'] = db_hash(DB_EMAIL, DB_PASSWORD); | |
$gallery['admin_hash'] = db_hash(DB_EMAIL.DB_PASSWORD, DB_PASSWORD_SALT); | |
$gallery['cache_thumbs_dir'] = DB_CACHE_DIR.'thumbs/'; | |
$gallery['theme_dir'] = DB_ROOT.'themes/'.$gallery['theme'].'/'; | |
// Peut t'on écrire dans le répertoire de thumbs ? | |
if ( !@is_writable($gallery['cache_thumbs_dir']) ) | |
$db_system['alerts'][] = sprintf(__('Unable to write to the %1$s directory. Please make sure PHP has write access to the directory %1$s'), '<code>'.$gallery['cache_thumbs_dir'].'</code>'); | |
// Le répertoire du theme à utiliser n'héxiste pas | |
if ( !file_exists($gallery['theme_dir']) ) { | |
$db_system['alerts'][] = sprintf(__('The directory %s, as defined in the configuration file, is missing.'), '<code>'.db_htmlspecialchars($gallery['theme_dir']).'</code>'); | |
$gallery['theme'] = DB_THEME_DEFAULT; | |
$gallery['theme_dir'] = DB_THEME_DEFAULT_DIR; | |
} | |
return $gallery; | |
} | |
/** | |
* Communication avec la DropBox | |
* | |
* @since 1.0 | |
* | |
* @param string $url | |
* @param array $post | |
* | |
* @return $response | |
*/ | |
function db_request($url, $post = array()) { | |
global $db_gallery; | |
if ( !isset($_SESSION['DB_COOKIES_'.$db_gallery['gallery_hash']]) ) | |
$_SESSION['DB_COOKIES_'.$db_gallery['gallery_hash']] = array(); | |
// Connexion à la DropBox | |
$req = curl_init(); | |
curl_setopt($req, CURLOPT_HEADER, 1); // 1 pour inclure l'en-tête dans la valeur de retour. | |
curl_setopt($req, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setopt($req, CURLOPT_SSL_VERIFYHOST, false); | |
// curl_setopt($req, CURLOPT_SSL_VERIFYPEER, true); | |
// curl_setopt($req, CURLOPT_SSL_VERIFYHOST, 2); | |
curl_setopt($req, CURLOPT_RETURNTRANSFER, true); // true retourne directement le transfert sous forme de chaîne de la valeur retournée par curl_exec() au lieu de l'afficher directement. | |
curl_setopt($req, CURLOPT_REFERER, 'https://www.dropbox.com'); // DropBox referer | |
curl_setopt($req, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // User Agent | |
if ( is_array($post) && !empty($post) ) { | |
curl_setopt($req, CURLOPT_POST, true); | |
curl_setopt($req, CURLOPT_POSTFIELDS, $post); | |
} | |
curl_setopt($req, CURLOPT_URL, $url); | |
//curl_setopt($req, CURLOPT_VERBOSE, 0); | |
curl_setopt($req, CURLOPT_CONNECTTIMEOUT, 0); | |
curl_setopt($req, CURLOPT_TIMEOUT, 25); | |
// Envois les cookies. | |
$cur_cookies = array(); | |
foreach ( $_SESSION['DB_COOKIES_'.$db_gallery['gallery_hash']] as $k => $v ) | |
$cur_cookies[] = $k.'='.$v; | |
$cur_cookies = implode(';', $cur_cookies); | |
curl_setopt($req, CURLOPT_COOKIE, $cur_cookies); | |
$response = curl_exec($req); | |
if ( $response === false ) { | |
$cur_error = curl_error($req); | |
curl_close($req); // Ferme la connexion | |
if ( defined('DB_DEBUG') ) | |
db_error( sprintf(__('Unable to execute request: %s'), '<code>'.db_htmlspecialchars($cur_error).'</code>') ); | |
else | |
db_error(__('Unable to connect to DropBox.')); | |
} | |
// Stock les cookies reçu | |
preg_match_all('/Set-Cookie: ([^=]+)=(.*?);/i', $response, $matches, PREG_SET_ORDER); | |
foreach ( $matches as $match ) | |
$_SESSION['DB_COOKIES_'.$db_gallery['gallery_hash']][$match[1]] = $match[2]; | |
// Ferme la connexion. | |
curl_close($req); | |
return $response; | |
} | |
/** | |
* Connexion à la Dropbox | |
* | |
* @since 1.0 | |
* | |
* @return | |
*/ | |
function db_login() { | |
global $db_gallery; | |
// Si on est déjà connecté. | |
if ( isset($_SESSION['DB_LOGGED_'.$db_gallery['gallery_hash']]) && $_SESSION['DB_LOGGED_'.$db_gallery['gallery_hash']] == true ) | |
return; | |
$req = db_request('https://www.dropbox.com/login'); | |
$token = db_extract_token($req, '/login'); | |
$login = db_request('https://www.dropbox.com/login', array('login_email' => DB_EMAIL, 'login_password' => DB_PASSWORD, 't' => $token)); | |
if ( stripos($login, 'location: /home') === false ) { | |
// On tente une 2ème fois au cas ou la session à expirée. | |
unset($_SESSION['DB_LOGGED_'.$db_gallery['gallery_hash']]); | |
unset($_SESSION['DB_COOKIES_'.$db_gallery['gallery_hash']]); | |
$req = db_request('https://www.dropbox.com/login'); | |
$token = db_extract_token($req, '/login'); | |
$login = db_request('https://www.dropbox.com/login', array('login_email' => DB_EMAIL, 'login_password' => DB_PASSWORD, 't' => $token)); | |
if ( stripos($login, 'location: /home') === false ) { | |
if ( defined('DB_DEBUG') ) | |
db_error(__('Unable to connect to DropBox.').' '.__('Wrong email and/or password.')); | |
else | |
db_error(__('Unable to connect to DropBox.')); | |
} | |
} | |
$_SESSION['DB_LOGGED_'.$db_gallery['gallery_hash']] = true; | |
} | |
/** | |
* Extrait le token d'authentification | |
* | |
* @since 1.0 | |
* | |
* @return string $token | |
*/ | |
function db_extract_token($html, $form_action) { | |
if ( !preg_match('/<form [^>]*'.preg_quote($form_action, '/').'[^>]*>.*?(<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>).*?<\/form>/is', $html, $matches) || !isset($matches[2]) ) | |
db_error(sprintf(__('Cannot extract token: %s'), '<code>(form_action='.db_htmlspecialchars($form_action).')</code>')); | |
return $matches[2]; | |
} | |
/** | |
* Vérification et sécurisation d'un répertoire, pour ne pas remonter | |
* à la racine avec des ../../ | |
* | |
* @since 1.0 | |
* | |
* @return string $directory | |
*/ | |
function db_directory_escape($directory = '') { | |
$directory = db_trim($directory, '/'); | |
$directories = explode('/', $directory); | |
if ( is_array($directories) && !empty($directories) ) { | |
$new_directories = array(); | |
foreach ( $directories as $cur_directory ) { | |
if ( $cur_directory != '..' && $cur_directory != '.' ) | |
$new_directories[] = $cur_directory; | |
} | |
$directory = implode('/', $new_directories); | |
} | |
return $directory; | |
} | |
/** | |
* Info sur les albums | |
* | |
* @since 1.0 | |
* | |
* @param string $directory | |
* | |
* @return array | |
*/ | |
function db_get_albums($directory = '') { | |
global $db_gallery; | |
$directory = db_directory_escape($directory); | |
$directory = !empty($directory) ? $db_gallery['photos_dir'].'/'.rawurlencode($directory) : $db_gallery['photos_dir']; | |
$directory_hash = db_hash($directory, $db_gallery['gallery_hash']); | |
$directory_cache = DB_CACHE_DIR.'cache_album_'.$directory_hash.'_albums.php'; | |
// Un fichier de cache existe | |
if ( file_exists($directory_cache) ) { | |
$directory_refresh = filemtime($directory_cache); // Dernière date de modification | |
if ( (time() - $db_gallery['refresh_cache']) > $directory_refresh ) // Le cache est trop vieux, on le supprime | |
@unlink($directory_cache); | |
else | |
@include $directory_cache; // Charge le cache d'un album | |
} | |
// Pas de cache, on fait le chargement directement depuis la dropbox | |
if ( !isset($albums) || (isset($albums) && !is_array($albums)) ) { | |
$albums = array(); | |
db_login(); // Connexion obligatoire à la dropbox | |
$albums_html = db_request('https://www.dropbox.com/'.$directory); | |
$pattern = '{<div\s+class="albumblock"\s*>((?:(?:(?!<div[^>]*>|</div>).)++|<div[^>]*>(?1)</div>)*)</div>}si'; | |
$matchcount = preg_match_all($pattern, $albums_html, $matches); | |
if ( $matchcount > 0 ) { | |
for( $i = 0; $i < $matchcount; $i++ ) { // Album | |
// URL et key de l'album. | |
if ( preg_match('/(href=")(.*?)(")/i', $matches[1][$i], $url) ) { | |
$key = db_trim(substr(db_trim($url[2], '/'), utf8_strlen($db_gallery['photos_dir'])), '/'); | |
$albums[$key] = array( | |
'album_url' => $key, // URL de l'album | |
'album_name' => '', | |
'album_img' => '', | |
'album_num_albums' => 0, | |
'album_num_photos' => 0, | |
'album_modified_DB_date' => '', // DropBox Date Format | |
'album_modified_timestamp' => 0, | |
'album_modified_day' => '', | |
'album_modified_month' => '', | |
'album_modified_year' => '', | |
); | |
// Nom de l'album | |
if ( preg_match('/(<b>)(.*?)(<\/b>)/i', $matches[1][$i], $name) ) | |
$albums[$key]['album_name'] = $name[2]; | |
// Image de l'album | |
if ( preg_match('/(src=")(.*?)(")/i', $matches[1][$i], $img) ) { | |
if ( stripos($img[2], 'default') !== false ) | |
$albums[$key]['album_img'] = false; | |
else { | |
$albums[$key]['album_img'] = str_replace('/s/','/%image_size%/', $img[2]); | |
// Supprime les URL de la DropBox (ex. https://photos-1.dropbox.com/i/) | |
$albums[$key]['album_img'] = preg_replace('/https\:\/\/photos-([0-9]{1,2}).dropbox.com\/i\//', '', $albums[$key]['album_img']); | |
} | |
} | |
// Nb d'albums dans l'album | |
if ( preg_match('/([0-9]{1,})\s(album)/i', $matches[1][$i], $num_albums) ) | |
$albums[$key]['album_num_albums'] = intval($num_albums[1]); | |
// Nb de photos dans l'album | |
if ( preg_match('/([0-9]{1,})\s(photo)/i', $matches[1][$i], $num_photos) ) | |
$albums[$key]['album_num_photos'] = intval($num_photos[1]); | |
// Dernière modification | |
if ( preg_match('/(Last modified)\s([0-9\/-]{1,})\s/i', $matches[1][$i], $modified) ) { | |
$albums[$key]['album_modified_DB_date'] = $modified[2]; | |
list($albums[$key]['album_modified_month'], $albums[$key]['album_modified_day'], $albums[$key]['album_modified_year']) = explode('/', $albums[$key]['album_modified_DB_date']); | |
$albums[$key]['album_modified_timestamp'] = gmmktime(0, 0, 0, intval($albums[$key]['album_modified_month']), intval($albums[$key]['album_modified_day']), intval($albums[$key]['album_modified_year'])); | |
} | |
} | |
} | |
} | |
// Met en cache (même si c'est vide). | |
db_generate_array_file('albums', $albums, $directory_cache); | |
} | |
// Ordre d'affichage des albums | |
if ( $db_gallery['sort_albums'] == 'DESC' ) | |
$albums = krnatcasesort($albums); | |
else | |
$albums = knatcasesort($albums); | |
return $albums; | |
} | |
/* | |
* HACK for the new Dropbox Gallery layout | |
*/ | |
function html_decode($string) { | |
// Javascript entities | |
$string = str_replace("\\x3a", ":", $string); | |
$string = str_replace("\\x2f", "/", $string); | |
$string = str_replace("\\x2d", "-", $string); | |
$string = str_replace("\\x2e", ".", $string); | |
$string = str_replace("\\x5f", "_", $string); | |
$string = str_replace("\\x2c", ",", $string); | |
return $string; | |
} | |
/** | |
* Info sur les photos | |
* | |
* @since 1.0 | |
* | |
* @param string $directory | |
* | |
* @return | |
*/ | |
function db_get_photos($directory = '') { | |
global $db_gallery; | |
$directory = db_directory_escape($directory); | |
$directory = !empty($directory) ? $db_gallery['photos_dir'].'/'.rawurlencode($directory) : $db_gallery['photos_dir']; | |
$directory_hash = db_hash($directory, $db_gallery['gallery_hash']); | |
$directory_cache = DB_CACHE_DIR.'cache_album_'.$directory_hash.'_photos.php'; | |
// Un fichier de cache existe | |
/*if ( file_exists($directory_cache) ) { | |
$directory_refresh = filemtime($directory_cache); // Dernière date de modification | |
if ( (time() - $db_gallery['refresh_cache']) > $directory_refresh ) // Le cache est trop vieux, on le supprime | |
@unlink($directory_cache); | |
else | |
@include $directory_cache; // Charge le cache d'un album | |
} | |
*/ | |
// Pas de cache, on fait le chargement directement depuis la dropbox | |
if ( !isset($photos) || (isset($photos) && !is_array($photos)) ) { | |
$photos = array(); | |
db_login(); // Connexion obligatoire à la dropbox | |
$photos_html = db_request('https://www.dropbox.com/'.$directory); | |
$pattern = "#photos.push\({(.*?)}\);#is"; | |
$matchcount = preg_match_all($pattern, $photos_html, $matches); | |
if ( $matchcount > 0 ) { | |
for( $i = 0; $i < $matchcount; $i++ ) { // Photo | |
if ( preg_match('/(\'filename\': \')(.*?)(\')/i', $matches[0][$i], $filename) ) { | |
$key = $filename[2]; | |
$photos[$key] = array( | |
'photo_name' => $key, | |
'photo_img' => '', | |
'photo_img_db_dl' => '', // Url de download dropbox (différent des autres url) | |
); | |
if ( preg_match('/(\'large\': \')(.*?)(\')/i', $matches[0][$i], $large) ) { | |
$photos[$key]['photo_img'] = str_replace('/l/','/%image_size%/', $large[2]); | |
} else { | |
} | |
if ( preg_match('/(\'original\': \')(.*?)(\')/i', $matches[0][$i], $original) ) | |
$photos[$key]['photo_img_db_dl'] = $original[2]; | |
$photos[$key]['photo_img'] = html_decode($photos[$key]['photo_img']); | |
$photos[$key]['photo_img_db_dl'] = html_decode($photos[$key]['photo_img_db_dl']); | |
// Supprime les URL de la DropBox. (ex. https://photos-1.dropbox.com/i/) | |
$photos[$key]['photo_img'] = preg_replace('/https\:\/\/photos-([0-9]{1,2}).dropbox.com\/i\//', '', $photos[$key]['photo_img']); | |
$photos[$key]['photo_img_db_dl'] = preg_replace('/https\:\/\/photos-([0-9]{1,2}).dropbox.com\/i\//', '', $photos[$key]['photo_img_db_dl']); | |
} | |
} | |
} | |
// Met en cache (même si c'est vide) | |
db_generate_array_file('photos', $photos, $directory_cache); | |
} | |
// Ordre d'affichage des photos | |
if ( $db_gallery['sort_photos'] == 'DESC' ) | |
$photos = krnatcasesort($photos); | |
else | |
$photos = knatcasesort($photos); | |
return $photos; | |
} | |
/** | |
* Renvois l'url d'une image en fonction de ça taille | |
* | |
* @since 1.0 | |
* | |
* @param string $photo | |
* | |
* @return string $url | |
*/ | |
function db_imgurl($photo, $size = 's') { | |
global $db_gallery; | |
$url = null; | |
// Taille d'image valide | |
if ( in_array($size, explode(',', $db_gallery['image_size'])) ) { | |
// on a un array, donc ça provient d'une photo | |
if ( is_array($photo) ) { | |
if ( $size == 'o' && isset($photo['photo_img_db_dl']) ) | |
$url = $photo['photo_img_db_dl']; | |
else if ( $size != 'o' && isset($photo['photo_img']) ) | |
$url = str_replace('%image_size%', $size, $photo['photo_img']); | |
} | |
// string, donc surement une photo d'album | |
else { | |
if ( $size != 'o' ) | |
$url = str_replace('%image_size%', $size, $photo); | |
} | |
} | |
return $url; | |
} | |
/** | |
* Télécharge une photo depuis la dropbox | |
* | |
* @since 1.0 | |
* | |
* @param string $photo | |
* @param string $server Url du serveur de la DropBox | |
* | |
* @return array() | |
*/ | |
function get_db_photo($photo, $server = 'https://photos-%s.dropbox.com/i/') { | |
global $db_gallery; | |
$photo_size = current(explode('/', $photo)); | |
// C'est une taille valide | |
if ( in_array($photo_size, explode(',', $db_gallery['image_size'])) ) { | |
$server = db_trim(sprintf($server, rand(1,4)), '/'); // Serveur de 1 à 4, pour ne pas surcharger le server DropBox | |
$photo_data = db_request($server.'/'.$photo); | |
preg_match('/Content-Type: .+\/.+/', $photo_data, $content_type); | |
$photo_data = substr(stristr($photo_data, "\r\n\r\n"),4); | |
return array( | |
'db_size' => $photo_size, // Taille de la photo chez dropbox (h, s, etc...) | |
'path_to_cache' => $db_gallery['cache_thumbs_dir'].str_replace('/','_', $photo), | |
'data' => $photo_data, | |
'content_type' => db_trim(str_replace('Content-Type:', '', $content_type[0])), | |
'content_length' => strlen($photo_data), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment