From e89203bcb1ae1f35fa364f995d42a26372ffda9a Mon Sep 17 00:00:00 2001 From: Tobias Reich Date: Sat, 30 Jan 2016 21:43:57 +0100 Subject: [PATCH] // for comments and spaces for alignment --- php/Access/Admin.php | 94 +-- php/Access/Guest.php | 74 +-- php/Access/Installation.php | 6 +- php/Modules/Album.php | 491 +++++++-------- php/Modules/Config.php | 50 +- php/Modules/Database.php | 162 ++--- php/Modules/Import.php | 94 +-- php/Modules/Log.php | 10 +- php/Modules/Photo.php | 806 ++++++++++++------------- php/Modules/Plugins.php | 22 +- php/Modules/Session.php | 46 +- php/Modules/Settings.php | 126 ++-- php/database/update_020700.php | 32 +- php/database/update_030000.php | 29 +- php/database/update_030001.php | 49 +- php/database/update_030003.php | 19 +- php/define.php | 22 +- php/helpers/fastImageCopyResampled.php | 28 +- php/helpers/getGraphHeader.php | 24 +- php/helpers/getHashedString.php | 21 +- php/helpers/hasPermissions.php | 3 +- php/helpers/search.php | 42 +- php/index.php | 59 +- 23 files changed, 1139 insertions(+), 1170 deletions(-) diff --git a/php/Access/Admin.php b/php/Access/Admin.php index c4576d2..84175d8 100644 --- a/php/Access/Admin.php +++ b/php/Access/Admin.php @@ -15,51 +15,51 @@ final class Admin extends Access { switch ($fn) { - # Album functions - case 'Album::getAll': self::getAlbumsAction(); break; - case 'Album::get': self::getAlbumAction(); break; - case 'Album::add': self::addAlbumAction(); break; - case 'Album::setTitle': self::setAlbumTitleAction(); break; - case 'Album::setDescription': self::setAlbumDescriptionAction(); break; - case 'Album::setPublic': self::setAlbumPublicAction(); break; - case 'Album::delete': self::deleteAlbumAction(); break; - case 'Album::merge': self::mergeAlbumsAction(); break; + // Album functions + case 'Album::getAll': self::getAlbumsAction(); break; + case 'Album::get': self::getAlbumAction(); break; + case 'Album::add': self::addAlbumAction(); break; + case 'Album::setTitle': self::setAlbumTitleAction(); break; + case 'Album::setDescription': self::setAlbumDescriptionAction(); break; + case 'Album::setPublic': self::setAlbumPublicAction(); break; + case 'Album::delete': self::deleteAlbumAction(); break; + case 'Album::merge': self::mergeAlbumsAction(); break; - # Photo functions - case 'Photo::get': self::getPhotoAction(); break; - case 'Photo::setTitle': self::setPhotoTitleAction(); break; - case 'Photo::setDescription': self::setPhotoDescriptionAction(); break; - case 'Photo::setStar': self::setPhotoStarAction(); break; - case 'Photo::setPublic': self::setPhotoPublicAction(); break; - case 'Photo::setAlbum': self::setPhotoAlbumAction(); break; - case 'Photo::setTags': self::setPhotoTagsAction(); break; - case 'Photo::duplicate': self::duplicatePhotoAction(); break; - case 'Photo::delete': self::deletePhotoAction(); break; + // Photo functions + case 'Photo::get': self::getPhotoAction(); break; + case 'Photo::setTitle': self::setPhotoTitleAction(); break; + case 'Photo::setDescription': self::setPhotoDescriptionAction(); break; + case 'Photo::setStar': self::setPhotoStarAction(); break; + case 'Photo::setPublic': self::setPhotoPublicAction(); break; + case 'Photo::setAlbum': self::setPhotoAlbumAction(); break; + case 'Photo::setTags': self::setPhotoTagsAction(); break; + case 'Photo::duplicate': self::duplicatePhotoAction(); break; + case 'Photo::delete': self::deletePhotoAction(); break; - # Add functions - case 'Photo::add': self::uploadAction(); break; - case 'Import::url': self::importUrlAction(); break; - case 'Import::server': self::importServerAction(); break; + // Add functions + case 'Photo::add': self::uploadAction(); break; + case 'Import::url': self::importUrlAction(); break; + case 'Import::server': self::importServerAction(); break; - # Search functions - case 'search': self::searchAction(); break; + // Search functions + case 'search': self::searchAction(); break; - # Session functions - case 'Session::init': self::initAction(); break; - case 'Session::login': self::loginAction(); break; - case 'Session::logout': self::logoutAction(); break; + // Session functions + case 'Session::init': self::initAction(); break; + case 'Session::login': self::loginAction(); break; + case 'Session::logout': self::logoutAction(); break; - # Settings functions - case 'Settings::setLogin': self::setLoginAction(); break; - case 'Settings::setSorting': self::setSortingAction(); break; - case 'Settings::setDropboxKey': self::setDropboxKeyAction(); break; + // Settings functions + case 'Settings::setLogin': self::setLoginAction(); break; + case 'Settings::setSorting': self::setSortingAction(); break; + case 'Settings::setDropboxKey': self::setDropboxKeyAction(); break; - # $_GET functions - case 'Album::getArchive': self::getAlbumArchiveAction(); break; - case 'Photo::getArchive': self::getPhotoArchiveAction(); break; + // $_GET functions + case 'Album::getArchive': self::getAlbumArchiveAction(); break; + case 'Photo::getArchive': self::getPhotoArchiveAction(); break; - # Error - default: self::fnNotFound(); break; + // Error + default: self::fnNotFound(); break; } @@ -67,7 +67,7 @@ final class Admin extends Access { } - # Album functions + // Album functions private static function getAlbumsAction() { @@ -138,7 +138,7 @@ final class Admin extends Access { } - # Photo functions + // Photo functions private static function getPhotoAction() { @@ -221,7 +221,7 @@ final class Admin extends Access { } - # Add functions + // Add functions private static function uploadAction() { @@ -250,7 +250,7 @@ final class Admin extends Access { } - # Search functions + // Search functions private static function searchAction() { @@ -260,7 +260,7 @@ final class Admin extends Access { } - # Session functions + // Session functions private static function initAction() { @@ -285,7 +285,7 @@ final class Admin extends Access { } - # Settings functions + // Settings functions private static function setLoginAction() { @@ -302,8 +302,8 @@ final class Admin extends Access { $sA = Settings::setSortingAlbums($_POST['typeAlbums'], $_POST['orderAlbums']); $sP = Settings::setSortingPhotos($_POST['typePhotos'], $_POST['orderPhotos']); - if ($sA===true&&$sP===true) echo true; - else echo false; + if ($sA===true&&$sP===true) echo true; + else echo false; } @@ -315,7 +315,7 @@ final class Admin extends Access { } - # Get functions + // Get functions private static function getAlbumArchiveAction() { diff --git a/php/Access/Guest.php b/php/Access/Guest.php index 73fca67..e8e2c9c 100644 --- a/php/Access/Guest.php +++ b/php/Access/Guest.php @@ -13,25 +13,25 @@ final class Guest extends Access { switch ($fn) { - # Album functions - case 'Album::getAll': self::getAlbumsAction(); break; - case 'Album::get': self::getAlbumAction(); break; - case 'Album::getPublic': self::checkAlbumAccessAction(); break; + // Album functions + case 'Album::getAll': self::getAlbumsAction(); break; + case 'Album::get': self::getAlbumAction(); break; + case 'Album::getPublic': self::checkAlbumAccessAction(); break; - # Photo functions - case 'Photo::get': self::getPhotoAction(); break; + // Photo functions + case 'Photo::get': self::getPhotoAction(); break; - # Session functions - case 'Session::init': self::initAction(); break; - case 'Session::login': self::loginAction(); break; - case 'Session::logout': self::logoutAction(); break; + // Session functions + case 'Session::init': self::initAction(); break; + case 'Session::login': self::loginAction(); break; + case 'Session::logout': self::logoutAction(); break; - # $_GET functions - case 'Album::getArchive': self::getAlbumArchiveAction(); break; - case 'Photo::getArchive': self::getPhotoArchiveAction(); break; + // $_GET functions + case 'Album::getArchive': self::getAlbumArchiveAction(); break; + case 'Photo::getArchive': self::getPhotoArchiveAction(); break; - # Error - default: self::fnNotFound(); break; + // Error + default: self::fnNotFound(); break; } @@ -39,7 +39,7 @@ final class Guest extends Access { } - # Album functions + // Album functions private static function getAlbumsAction() { @@ -56,13 +56,13 @@ final class Guest extends Access { if ($album->getPublic()) { - # Album public - if ($album->checkPassword($_POST['password'])) echo json_encode($album->get()); - else echo 'Warning: Wrong password!'; + // Album public + if ($album->checkPassword($_POST['password'])) echo json_encode($album->get()); + else echo 'Warning: Wrong password!'; } else { - # Album private + // Album private echo 'Warning: Album private!'; } @@ -77,20 +77,20 @@ final class Guest extends Access { if ($album->getPublic()) { - # Album public - if ($album->checkPassword($_POST['password'])) echo true; - else echo false; + // Album public + if ($album->checkPassword($_POST['password'])) echo true; + else echo false; } else { - # Album private + // Album private echo false; } } - # Photo functions + // Photo functions private static function getPhotoAction() { @@ -100,13 +100,13 @@ final class Guest extends Access { $pgP = $photo->getPublic($_POST['password']); - if ($pgP===2) echo json_encode($photo->get($_POST['albumID'])); - else if ($pgP===1) echo 'Warning: Wrong password!'; - else if ($pgP===0) echo 'Warning: Photo private!'; + if ($pgP===2) echo json_encode($photo->get($_POST['albumID'])); + else if ($pgP===1) echo 'Warning: Wrong password!'; + else if ($pgP===0) echo 'Warning: Photo private!'; } - # Session functions + // Session functions private static function initAction() { @@ -131,7 +131,7 @@ final class Guest extends Access { } - # $_GET functions + // $_GET functions private static function getAlbumArchiveAction() { @@ -141,13 +141,13 @@ final class Guest extends Access { if ($album->getPublic()&&$album->getDownloadable()) { - # Album Public - if ($album->checkPassword($_GET['password'])) $album->getArchive(); - else exit('Warning: Wrong password!'); + // Album Public + if ($album->checkPassword($_GET['password'])) $album->getArchive(); + else exit('Warning: Wrong password!'); } else { - # Album Private + // Album Private exit('Warning: Album private or not downloadable!'); } @@ -162,15 +162,15 @@ final class Guest extends Access { $pgP = $photo->getPublic($_GET['password']); - # Photo Download + // Photo Download if ($pgP===2) { - # Photo Public + // Photo Public $photo->getArchive(); } else { - # Photo Private + // Photo Private exit('Warning: Photo private or password incorrect!'); } diff --git a/php/Access/Installation.php b/php/Access/Installation.php index 982642f..946f6bc 100644 --- a/php/Access/Installation.php +++ b/php/Access/Installation.php @@ -11,10 +11,10 @@ final class Installation extends Access { switch ($fn) { - case 'Config::create': self::configCreateAction(); break; + case 'Config::create': self::configCreateAction(); break; - # Error - default: self::initAction(); break; + // Error + default: self::initAction(); break; } diff --git a/php/Modules/Album.php b/php/Modules/Album.php index b5b051a..ebfe111 100644 --- a/php/Modules/Album.php +++ b/php/Modules/Album.php @@ -8,8 +8,8 @@ final class Album { public function __construct($albumIDs) { - # Init vars - $this->albumIDs = $albumIDs; + // Init vars + $this->albumIDs = $albumIDs; return true; @@ -17,22 +17,22 @@ final class Album { public function add($title = 'Untitled') { - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Parse + // Parse if (strlen($title)>50) $title = substr($title, 0, 50); - # Properties - $public = 0; - $visible = 1; + // Properties + $public = 0; + $visible = 1; - # Database - $sysstamp = time(); - $query = Database::prepare(Database::get(), "INSERT INTO ? (title, sysstamp, public, visible) VALUES ('?', '?', '?', '?')", array(LYCHEE_TABLE_ALBUMS, $title, $sysstamp, $public, $visible)); - $result = Database::get()->query($query); + // Database + $sysstamp = time(); + $query = Database::prepare(Database::get(), "INSERT INTO ? (title, sysstamp, public, visible) VALUES ('?', '?', '?', '?')", array(LYCHEE_TABLE_ALBUMS, $title, $sysstamp, $public, $visible)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -45,31 +45,31 @@ final class Album { public static function prepareData(array $data) { - # This function requires the following album-attributes and turns them - # into a front-end friendly format: id, title, public, sysstamp, password - # Note that some attributes remain unchanged + // This function requires the following album-attributes and turns them + // into a front-end friendly format: id, title, public, sysstamp, password + // Note that some attributes remain unchanged - # Init + // Init $album = null; - # Set unchanged attributes - $album['id'] = $data['id']; - $album['title'] = $data['title']; - $album['public'] = $data['public']; + // Set unchanged attributes + $album['id'] = $data['id']; + $album['title'] = $data['title']; + $album['public'] = $data['public']; - # Additional attributes - # Only part of $album when available - if (isset($data['description'])) $album['description'] = $data['description']; - if (isset($data['visible'])) $album['visible'] = $data['visible']; - if (isset($data['downloadable'])) $album['downloadable'] = $data['downloadable']; + // Additional attributes + // Only part of $album when available + if (isset($data['description'])) $album['description'] = $data['description']; + if (isset($data['visible'])) $album['visible'] = $data['visible']; + if (isset($data['downloadable'])) $album['downloadable'] = $data['downloadable']; - # Parse date + // Parse date $album['sysdate'] = date('F Y', $data['sysstamp']); - # Parse password + // Parse password $album['password'] = ($data['password']=='' ? '0' : '1'); - # Parse thumbs or set default value + // Parse thumbs or set default value $album['thumbs'] = (isset($data['thumbs']) ? explode(',', $data['thumbs']) : array()); return $album; @@ -78,85 +78,90 @@ final class Album { public function get() { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Get album information + // Get album information switch ($this->albumIDs) { - case 'f': $return['public'] = '0'; - $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE star = 1 " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - break; + case 'f': + $return['public'] = '0'; + $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE star = 1 " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + break; - case 's': $return['public'] = '0'; - $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE public = 1 " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - break; + case 's': + $return['public'] = '0'; + $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE public = 1 " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + break; - case 'r': $return['public'] = '0'; - $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE LEFT(id, 10) >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 1 DAY)) " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - break; + case 'r': + $return['public'] = '0'; + $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE LEFT(id, 10) >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 1 DAY)) " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + break; - case '0': $return['public'] = '0'; - $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE album = 0 " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - break; + case '0': + $return['public'] = '0'; + $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE album = 0 " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + break; - default: $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); - $albums = Database::get()->query($query); - $return = $albums->fetch_assoc(); - $return = Album::prepareData($return); - $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE album = '?' " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); - break; + default: + $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); + $albums = Database::get()->query($query); + $return = $albums->fetch_assoc(); + $return = Album::prepareData($return); + $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE album = '?' " . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); + break; } - # Get photos - $photos = Database::get()->query($query); - $previousPhotoID = ''; + // Get photos + $photos = Database::get()->query($query); + $previousPhotoID = ''; while ($photo = $photos->fetch_assoc()) { - # Turn data from the database into a front-end friendly format + // Turn data from the database into a front-end friendly format $photo = Photo::prepareData($photo); - # Set previous and next photoID for navigation purposes + // Set previous and next photoID for navigation purposes $photo['previousPhoto'] = $previousPhotoID; - $photo['nextPhoto'] = ''; + $photo['nextPhoto'] = ''; - # Set current photoID as nextPhoto of previous photo + // Set current photoID as nextPhoto of previous photo if ($previousPhotoID!=='') $return['content'][$previousPhotoID]['nextPhoto'] = $photo['id']; $previousPhotoID = $photo['id']; - # Add to return + // Add to return $return['content'][$photo['id']] = $photo; } if ($photos->num_rows===0) { - # Album empty + // Album empty $return['content'] = false; } else { - # Enable next and previous for the first and last photo - $lastElement = end($return['content']); - $lastElementId = $lastElement['id']; - $firstElement = reset($return['content']); - $firstElementId = $firstElement['id']; + // Enable next and previous for the first and last photo + $lastElement = end($return['content']); + $lastElementId = $lastElement['id']; + $firstElement = reset($return['content']); + $firstElementId = $firstElement['id']; if ($lastElementId!==$firstElementId) { - $return['content'][$lastElementId]['nextPhoto'] = $firstElementId; - $return['content'][$firstElementId]['previousPhoto'] = $lastElementId; + $return['content'][$lastElementId]['nextPhoto'] = $firstElementId; + $return['content'][$firstElementId]['previousPhoto'] = $lastElementId; } } - $return['id'] = $this->albumIDs; - $return['num'] = $photos->num_rows; + $return['id'] = $this->albumIDs; + $return['num'] = $photos->num_rows; - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return $return; @@ -165,45 +170,45 @@ final class Album { public function getAll($public = true) { - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Initialize return var + // Initialize return var $return = array( - 'smartalbums' => null, - 'albums' => null, - 'num' => 0 + 'smartalbums' => null, + 'albums' => null, + 'num' => 0 ); - # Get SmartAlbums + // Get SmartAlbums if ($public===false) $return['smartalbums'] = $this->getSmartInfo(); - # Albums query - if ($public===false) $query = Database::prepare(Database::get(), 'SELECT id, title, public, sysstamp, password FROM ? ' . Settings::get()['sortingAlbums'], array(LYCHEE_TABLE_ALBUMS)); - else $query = Database::prepare(Database::get(), 'SELECT id, title, public, sysstamp, password FROM ? WHERE public = 1 AND visible <> 0 ' . Settings::get()['sortingAlbums'], array(LYCHEE_TABLE_ALBUMS)); + // Albums query + if ($public===false) $query = Database::prepare(Database::get(), 'SELECT id, title, public, sysstamp, password FROM ? ' . Settings::get()['sortingAlbums'], array(LYCHEE_TABLE_ALBUMS)); + else $query = Database::prepare(Database::get(), 'SELECT id, title, public, sysstamp, password FROM ? WHERE public = 1 AND visible <> 0 ' . Settings::get()['sortingAlbums'], array(LYCHEE_TABLE_ALBUMS)); - # Execute query + // Execute query $albums = Database::get()->query($query); if (!$albums) { Log::error(__METHOD__, __LINE__, 'Could not get all albums (' . Database::get()->error . ')'); exit('Error: ' . Database::get()->error); } - # For each album + // For each album while ($album = $albums->fetch_assoc()) { - # Turn data from the database into a front-end friendly format + // Turn data from the database into a front-end friendly format $album = Album::prepareData($album); - # Thumbs + // Thumbs if (($public===true&&$album['password']==='0')|| ($public===false)) { - # Execute query - $query = Database::prepare(Database::get(), "SELECT thumbUrl FROM ? WHERE album = '?' ORDER BY star DESC, " . substr(Settings::get()['sortingPhotos'], 9) . " LIMIT 3", array(LYCHEE_TABLE_PHOTOS, $album['id'])); - $thumbs = Database::get()->query($query); + // Execute query + $query = Database::prepare(Database::get(), "SELECT thumbUrl FROM ? WHERE album = '?' ORDER BY star DESC, " . substr(Settings::get()['sortingPhotos'], 9) . " LIMIT 3", array(LYCHEE_TABLE_PHOTOS, $album['id'])); + $thumbs = Database::get()->query($query); - # For each thumb + // For each thumb $k = 0; while ($thumb = $thumbs->fetch_object()) { $album['thumbs'][$k] = LYCHEE_URL_UPLOADS_THUMB . $thumb->thumbUrl; @@ -212,15 +217,15 @@ final class Album { } - # Add to return + // Add to return $return['albums'][] = $album; } - # Num of albums + // Num of albums $return['num'] = $albums->num_rows; - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return $return; @@ -229,25 +234,25 @@ final class Album { private function getSmartInfo() { - # Initialize return var + // Initialize return var $return = array( - 'unsorted' => null, - 'public' => null, - 'starred' => null, - 'recent' => null + 'unsorted' => null, + 'public' => null, + 'starred' => null, + 'recent' => null ); - ### - # Unsorted - ### + /** + * Unsorted + */ - $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE album = 0 ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - $unsorted = Database::get()->query($query); - $i = 0; + $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE album = 0 ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + $unsorted = Database::get()->query($query); + $i = 0; $return['unsorted'] = array( - 'thumbs' => array(), - 'num' => $unsorted->num_rows + 'thumbs' => array(), + 'num' => $unsorted->num_rows ); while($row = $unsorted->fetch_object()) { @@ -257,17 +262,17 @@ final class Album { } else break; } - ### - # Starred - ### + /** + * Starred + */ - $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE star = 1 ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - $starred = Database::get()->query($query); - $i = 0; + $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE star = 1 ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + $starred = Database::get()->query($query); + $i = 0; $return['starred'] = array( - 'thumbs' => array(), - 'num' => $starred->num_rows + 'thumbs' => array(), + 'num' => $starred->num_rows ); while($row3 = $starred->fetch_object()) { @@ -277,17 +282,17 @@ final class Album { } else break; } - ### - # Public - ### + /** + * Public + */ - $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE public = 1 ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - $public = Database::get()->query($query); - $i = 0; + $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE public = 1 ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + $public = Database::get()->query($query); + $i = 0; $return['public'] = array( - 'thumbs' => array(), - 'num' => $public->num_rows + 'thumbs' => array(), + 'num' => $public->num_rows ); while($row2 = $public->fetch_object()) { @@ -297,17 +302,17 @@ final class Album { } else break; } - ### - # Recent - ### + /** + * Recent + */ - $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE LEFT(id, 10) >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 1 DAY)) ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); - $recent = Database::get()->query($query); - $i = 0; + $query = Database::prepare(Database::get(), 'SELECT thumbUrl FROM ? WHERE LEFT(id, 10) >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 1 DAY)) ' . Settings::get()['sortingPhotos'], array(LYCHEE_TABLE_PHOTOS)); + $recent = Database::get()->query($query); + $i = 0; $return['recent'] = array( - 'thumbs' => array(), - 'num' => $recent->num_rows + 'thumbs' => array(), + 'num' => $recent->num_rows ); while($row3 = $recent->fetch_object()) { @@ -317,117 +322,117 @@ final class Album { } else break; } - # Return SmartAlbums + // Return SmartAlbums return $return; } public function getArchive() { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Illicit chars + // Illicit chars $badChars = array_merge( - array_map('chr', range(0,31)), - array("<", ">", ":", '"', "/", "\\", "|", "?", "*") - ); + array_map('chr', range(0,31)), + array("<", ">", ":", '"', "/", "\\", "|", "?", "*") + ); - # Photos query + // Photos query switch($this->albumIDs) { case 's': - $photos = Database::prepare(Database::get(), 'SELECT title, url FROM ? WHERE public = 1', array(LYCHEE_TABLE_PHOTOS)); - $zipTitle = 'Public'; + $photos = Database::prepare(Database::get(), 'SELECT title, url FROM ? WHERE public = 1', array(LYCHEE_TABLE_PHOTOS)); + $zipTitle = 'Public'; break; case 'f': - $photos = Database::prepare(Database::get(), 'SELECT title, url FROM ? WHERE star = 1', array(LYCHEE_TABLE_PHOTOS)); - $zipTitle = 'Starred'; + $photos = Database::prepare(Database::get(), 'SELECT title, url FROM ? WHERE star = 1', array(LYCHEE_TABLE_PHOTOS)); + $zipTitle = 'Starred'; break; case 'r': - $photos = Database::prepare(Database::get(), 'SELECT title, url FROM ? WHERE LEFT(id, 10) >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 1 DAY)) GROUP BY checksum', array(LYCHEE_TABLE_PHOTOS)); - $zipTitle = 'Recent'; + $photos = Database::prepare(Database::get(), 'SELECT title, url FROM ? WHERE LEFT(id, 10) >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 1 DAY)) GROUP BY checksum', array(LYCHEE_TABLE_PHOTOS)); + $zipTitle = 'Recent'; break; default: - $photos = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE album = '?'", array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); - $zipTitle = 'Unsorted'; + $photos = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE album = '?'", array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); + $zipTitle = 'Unsorted'; } - # Get title from database when album is not a SmartAlbum + // Get title from database when album is not a SmartAlbum if ($this->albumIDs!=0&&is_numeric($this->albumIDs)) { $query = Database::prepare(Database::get(), "SELECT title FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); $album = Database::get()->query($query); - # Error in database query + // Error in database query if (!$album) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; } - # Fetch object + // Fetch object $album = $album->fetch_object(); - # Photo not found + // Photo not found if ($album===null) { Log::error(__METHOD__, __LINE__, 'Album not found. Cannot start download.'); return false; } - # Set title + // Set title $zipTitle = $album->title; } - # Escape title + // Escape title $zipTitle = str_replace($badChars, '', $zipTitle); $filename = LYCHEE_DATA . $zipTitle . '.zip'; - # Create zip + // Create zip $zip = new ZipArchive(); if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { Log::error(__METHOD__, __LINE__, 'Could not create ZipArchive'); return false; } - # Execute query + // Execute query $photos = Database::get()->query($photos); - # Check if album empty + // Check if album empty if ($photos->num_rows==0) { Log::error(__METHOD__, __LINE__, 'Could not create ZipArchive without images'); return false; } - # Parse each path + // Parse each path $files = array(); while ($photo = $photos->fetch_object()) { - # Parse url + // Parse url $photo->url = LYCHEE_UPLOADS_BIG . $photo->url; - # Parse title + // Parse title $photo->title = str_replace($badChars, '', $photo->title); if (!isset($photo->title)||$photo->title==='') $photo->title = 'Untitled'; - # Check if readable + // Check if readable if (!@is_readable($photo->url)) continue; - # Get extension of image + // Get extension of image $extension = getExtension($photo->url); - # Set title for photo + // Set title for photo $zipFileName = $zipTitle . '/' . $photo->title . $extension; - # Check for duplicates + // Check for duplicates if (!empty($files)) { $i = 1; while (in_array($zipFileName, $files)) { - # Set new title for photo + // Set new title for photo $zipFileName = $zipTitle . '/' . $photo->title . '-' . $i . $extension; $i++; @@ -435,27 +440,27 @@ final class Album { } } - # Add to array + // Add to array $files[] = $zipFileName; - # Add photo to zip + // Add photo to zip $zip->addFile($photo->url, $zipFileName); } - # Finish zip + // Finish zip $zip->close(); - # Send zip + // Send zip header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=\"$zipTitle.zip\""); header("Content-Length: " . filesize($filename)); readfile($filename); - # Delete zip + // Delete zip unlink($filename); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return true; @@ -464,17 +469,17 @@ final class Album { public function setTitle($title = 'Untitled') { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Execute query - $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $title, $this->albumIDs)); + // Execute query + $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $title, $this->albumIDs)); $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -487,17 +492,17 @@ final class Album { public function setDescription($description = '') { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Execute query - $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $description, $this->albumIDs)); - $result = Database::get()->query($query); + // Execute query + $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $description, $this->albumIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -510,20 +515,20 @@ final class Album { public function getPublic() { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); if ($this->albumIDs==='0'||$this->albumIDs==='s'||$this->albumIDs==='f') return false; - # Execute query - $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); - $albums = Database::get()->query($query); - $album = $albums->fetch_object(); + // Execute query + $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); + $albums = Database::get()->query($query); + $album = $albums->fetch_object(); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if ($album->public==1) return true; @@ -533,20 +538,20 @@ final class Album { public function getDownloadable() { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); if ($this->albumIDs==='0'||$this->albumIDs==='s'||$this->albumIDs==='f'||$this->albumIDs==='r') return false; - # Execute query - $query = Database::prepare(Database::get(), "SELECT downloadable FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); - $albums = Database::get()->query($query); - $album = $albums->fetch_object(); + // Execute query + $query = Database::prepare(Database::get(), "SELECT downloadable FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); + $albums = Database::get()->query($query); + $album = $albums->fetch_object(); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if ($album->downloadable==1) return true; @@ -556,39 +561,39 @@ final class Album { public function setPublic($public, $password, $visible, $downloadable) { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Convert values - $public = ($public==='1' ? 1 : 0); - $visible = ($visible==='1' ? 1 : 0); - $downloadable = ($downloadable==='1' ? 1 : 0); + // Convert values + $public = ($public==='1' ? 1 : 0); + $visible = ($visible==='1' ? 1 : 0); + $downloadable = ($downloadable==='1' ? 1 : 0); - # Set public - $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?', visible = '?', downloadable = '?', password = NULL WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $public, $visible, $downloadable, $this->albumIDs)); - $result = Database::get()->query($query); + // Set public + $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?', visible = '?', downloadable = '?', password = NULL WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $public, $visible, $downloadable, $this->albumIDs)); + $result = Database::get()->query($query); if (!$result) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; } - # Reset permissions for photos + // Reset permissions for photos if ($public===1) { - $query = Database::prepare(Database::get(), "UPDATE ? SET public = 0 WHERE album IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); - $result = Database::get()->query($query); + $query = Database::prepare(Database::get(), "UPDATE ? SET public = 0 WHERE album IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); + $result = Database::get()->query($query); if (!$result) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; } } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); - # Set password + // Set password if (isset($password)&&strlen($password)>0) return $this->setPassword($password); return true; @@ -597,33 +602,33 @@ final class Album { private function setPassword($password) { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); if (strlen($password)>0) { - # Get hashed password + // Get hashed password $password = getHashedString($password); - # Set hashed password - # Do not prepare $password because it is hashed and save - # Preparing (escaping) the password would destroy the hash - $query = Database::prepare(Database::get(), "UPDATE ? SET password = '$password' WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); + // Set hashed password + // Do not prepare $password because it is hashed and save + // Preparing (escaping) the password would destroy the hash + $query = Database::prepare(Database::get(), "UPDATE ? SET password = '$password' WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); } else { - # Unset password - $query = Database::prepare(Database::get(), "UPDATE ? SET password = NULL WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); + // Unset password + $query = Database::prepare(Database::get(), "UPDATE ? SET password = NULL WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); } - # Execute query - $result = Database::get()->query($query); + // Execute query + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -636,18 +641,18 @@ final class Album { public function checkPassword($password) { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Execute query - $query = Database::prepare(Database::get(), "SELECT password FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); - $albums = Database::get()->query($query); - $album = $albums->fetch_object(); + // Execute query + $query = Database::prepare(Database::get(), "SELECT password FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); + $albums = Database::get()->query($query); + $album = $albums->fetch_object(); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if ($album->password=='') return true; @@ -658,35 +663,35 @@ final class Album { public function merge() { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Convert to array + // Convert to array $albumIDs = explode(',', $this->albumIDs); - # Get first albumID + // Get first albumID $albumID = array_splice($albumIDs, 0, 1); $albumID = $albumID[0]; - $query = Database::prepare(Database::get(), "UPDATE ? SET album = ? WHERE album IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->albumIDs)); - $result = Database::get()->query($query); + $query = Database::prepare(Database::get(), "UPDATE ? SET album = ? WHERE album IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->albumIDs)); + $result = Database::get()->query($query); if (!$result) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; } - # $albumIDs contains all IDs without the first albumID - # Convert to string + // $albumIDs contains all IDs without the first albumID + // Convert to string $filteredIDs = implode(',', $albumIDs); - $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $filteredIDs)); - $result = Database::get()->query($query); + $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $filteredIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -699,20 +704,20 @@ final class Album { public function delete() { - # Check dependencies + // Check dependencies Validator::required(isset($this->albumIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Init vars + // Init vars $error = false; - # Execute query - $query = Database::prepare(Database::get(), "SELECT id FROM ? WHERE album IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); + // Execute query + $query = Database::prepare(Database::get(), "SELECT id FROM ? WHERE album IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->albumIDs)); $photos = Database::get()->query($query); - # For each album delete photo + // For each album delete photo while ($row = $photos->fetch_object()) { $photo = new Photo($row->id); @@ -720,11 +725,11 @@ final class Album { } - # Delete albums - $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); - $result = Database::get()->query($query); + // Delete albums + $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_ALBUMS, $this->albumIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if ($error) return false; diff --git a/php/Modules/Config.php b/php/Modules/Config.php index 0c03786..060b1df 100644 --- a/php/Modules/Config.php +++ b/php/Modules/Config.php @@ -6,43 +6,37 @@ final class Config { public static function create($host, $user, $password, $name = 'lychee', $prefix = '') { - # Open a new connection to the MySQL server + // Open a new connection to the MySQL server $connection = Database::connect($host, $user, $password); - # Check if the connection was successful + // Check if the connection was successful if ($connection===false) return 'Warning: Connection failed!'; - # Check if user can create the database before saving the configuration + // Check if user can create the database before saving the configuration if (!Database::createDatabase($connection, $name)) return 'Warning: Creation failed!'; - # Escape data - $host = mysqli_real_escape_string($connection, $host); - $user = mysqli_real_escape_string($connection, $user); - $password = mysqli_real_escape_string($connection, $password); - $name = mysqli_real_escape_string($connection, $name); - $prefix = mysqli_real_escape_string($connection, $prefix); + // Escape data + $host = mysqli_real_escape_string($connection, $host); + $user = mysqli_real_escape_string($connection, $user); + $password = mysqli_real_escape_string($connection, $password); + $name = mysqli_real_escape_string($connection, $name); + $prefix = mysqli_real_escape_string($connection, $prefix); - # Save config.php + // Save config.php $config = ""; - # Save file + // Save file if (file_put_contents(LYCHEE_CONFIG_FILE, $config)===false) return 'Warning: Could not create file!'; return true; @@ -60,11 +54,11 @@ if(!defined('LYCHEE')) exit('Error: Direct access is not allowed!'); require(LYCHEE_CONFIG_FILE); return(array( - 'host' => $dbHost, - 'user' => $dbUser, - 'password' => $dbPassword, - 'name' => $dbName, - 'prefix' => $dbTablePrefix + 'host' => $dbHost, + 'user' => $dbUser, + 'password' => $dbPassword, + 'name' => $dbName, + 'prefix' => $dbTablePrefix )); } diff --git a/php/Modules/Database.php b/php/Modules/Database.php index 770d62b..bac8126 100755 --- a/php/Modules/Database.php +++ b/php/Modules/Database.php @@ -10,10 +10,10 @@ final class Database { private static $instance = null; private static $versions = array( - '020700', #2.7.0 - '030000', #3.0.0 - '030001', #3.0.1 - '030003' #3.0.3 + '020700', // 2.7.0 + '030000', // 3.0.0 + '030001', // 3.0.1 + '030003' // 3.0.3 ); public static function get() { @@ -38,27 +38,27 @@ final class Database { private function __construct($host, $user, $password, $name = 'lychee', $dbTablePrefix) { - # Check dependencies + // Check dependencies Validator::required(isset($host, $user, $password, $name), __METHOD__); - # Define the table prefix + // Define the table prefix defineTablePrefix($dbTablePrefix); - # Open a new connection to the MySQL server + // Open a new connection to the MySQL server $connection = self::connect($host, $user, $password); - # Check if the connection was successful + // Check if the connection was successful if ($connection===false) exit('Error: ' . $connection->connect_error); if (!self::setCharset($connection)) exit('Error: Could not set database charset!'); - # Create database + // Create database if (!self::createDatabase($connection, $name)) exit('Error: Could not create database!'); - # Create tables + // Create tables if (!self::createTables($connection)) exit('Error: Could not create tables!'); - # Update database + // Update database if (!self::update($connection, $name)) exit('Error: Could not update database and tables!'); $this->connection = $connection; @@ -67,10 +67,10 @@ final class Database { public static function connect($host = 'localhost', $user, $password) { - # Open a new connection to the MySQL server + // Open a new connection to the MySQL server $connection = new Mysqli($host, $user, $password); - # Check if the connection was successful + // Check if the connection was successful if ($connection->connect_errno) return false; return $connection; @@ -79,14 +79,14 @@ final class Database { private static function setCharset($connection) { - # Check dependencies + // Check dependencies Validator::required(isset($connection), __METHOD__); - # Avoid sql injection on older MySQL versions by using GBK + // Avoid sql injection on older MySQL versions by using GBK if ($connection->server_version<50500) @$connection->set_charset('GBK'); else @$connection->set_charset('utf8'); - # Set unicode + // Set unicode $connection->query('SET NAMES utf8;'); return true; @@ -95,14 +95,14 @@ final class Database { public static function createDatabase($connection, $name = 'lychee') { - # Check dependencies + // Check dependencies Validator::required(isset($connection), __METHOD__); - # Check if database exists + // Check if database exists if ($connection->select_db($name)) return true; - # Create database - $query = self::prepare($connection, 'CREATE DATABASE IF NOT EXISTS ?', array($name)); + // Create database + $query = self::prepare($connection, 'CREATE DATABASE IF NOT EXISTS ?', array($name)); $result = $connection->query($query); if (!$connection->select_db($name)) return false; @@ -112,68 +112,68 @@ final class Database { private static function createTables($connection) { - # Check dependencies + // Check dependencies Validator::required(isset($connection), __METHOD__); - # Check if tables exist + // Check if tables exist $query = self::prepare($connection, 'SELECT * FROM ?, ?, ?, ? LIMIT 0', array(LYCHEE_TABLE_PHOTOS, LYCHEE_TABLE_ALBUMS, LYCHEE_TABLE_SETTINGS, LYCHEE_TABLE_LOG)); if ($connection->query($query)) return true; - # Create log + // Create log $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_LOG)); if (!$connection->query($exist)) { - # Read file - $file = __DIR__ . '/../database/log_table.sql'; - $query = @file_get_contents($file); + // Read file + $file = __DIR__ . '/../database/log_table.sql'; + $query = @file_get_contents($file); if (!isset($query)||$query===false) return false; - # Create table + // Create table $query = self::prepare($connection, $query, array(LYCHEE_TABLE_LOG)); if (!$connection->query($query)) return false; } - # Create settings + // Create settings $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_SETTINGS)); if (!$connection->query($exist)) { - # Read file - $file = __DIR__ . '/../database/settings_table.sql'; - $query = @file_get_contents($file); + // Read file + $file = __DIR__ . '/../database/settings_table.sql'; + $query = @file_get_contents($file); if (!isset($query)||$query===false) { Log::error(__METHOD__, __LINE__, 'Could not load query for lychee_settings'); return false; } - # Create table + // Create table $query = self::prepare($connection, $query, array(LYCHEE_TABLE_SETTINGS)); if (!$connection->query($query)) { Log::error(__METHOD__, __LINE__, $connection->error); return false; } - # Read file - $file = __DIR__ . '/../database/settings_content.sql'; - $query = @file_get_contents($file); + // Read file + $file = __DIR__ . '/../database/settings_content.sql'; + $query = @file_get_contents($file); if (!isset($query)||$query===false) { Log::error(__METHOD__, __LINE__, 'Could not load content-query for lychee_settings'); return false; } - # Add content + // Add content $query = self::prepare($connection, $query, array(LYCHEE_TABLE_SETTINGS)); if (!$connection->query($query)) { Log::error(__METHOD__, __LINE__, $connection->error); return false; } - # Generate identifier - $identifier = md5(microtime(true)); - $query = self::prepare($connection, "UPDATE `?` SET `value` = '?' WHERE `key` = 'identifier' LIMIT 1", array(LYCHEE_TABLE_SETTINGS, $identifier)); + // Generate identifier + $identifier = md5(microtime(true)); + $query = self::prepare($connection, "UPDATE `?` SET `value` = '?' WHERE `key` = 'identifier' LIMIT 1", array(LYCHEE_TABLE_SETTINGS, $identifier)); if (!$connection->query($query)) { Log::error(__METHOD__, __LINE__, $connection->error); return false; @@ -181,20 +181,20 @@ final class Database { } - # Create albums + // Create albums $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_ALBUMS)); if (!$connection->query($exist)) { - # Read file - $file = __DIR__ . '/../database/albums_table.sql'; - $query = @file_get_contents($file); + // Read file + $file = __DIR__ . '/../database/albums_table.sql'; + $query = @file_get_contents($file); if (!isset($query)||$query===false) { Log::error(__METHOD__, __LINE__, 'Could not load query for lychee_albums'); return false; } - # Create table + // Create table $query = self::prepare($connection, $query, array(LYCHEE_TABLE_ALBUMS)); if (!$connection->query($query)) { Log::error(__METHOD__, __LINE__, $connection->error); @@ -203,20 +203,20 @@ final class Database { } - # Create photos + // Create photos $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_PHOTOS)); if (!$connection->query($exist)) { - # Read file - $file = __DIR__ . '/../database/photos_table.sql'; - $query = @file_get_contents($file); + // Read file + $file = __DIR__ . '/../database/photos_table.sql'; + $query = @file_get_contents($file); if (!isset($query)||$query===false) { Log::error(__METHOD__, __LINE__, 'Could not load query for lychee_photos'); return false; } - # Create table + // Create table $query = self::prepare($connection, $query, array(LYCHEE_TABLE_PHOTOS)); if (!$connection->query($query)) { Log::error(__METHOD__, __LINE__, $connection->error); @@ -231,21 +231,21 @@ final class Database { private static function update($connection, $dbName) { - # Check dependencies + // Check dependencies Validator::required(isset($connection, $dbName), __METHOD__); - # Get current version - $query = self::prepare($connection, "SELECT * FROM ? WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS)); - $results = $connection->query($query); - $current = $results->fetch_object()->value; + // Get current version + $query = self::prepare($connection, "SELECT * FROM ? WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS)); + $results = $connection->query($query); + $current = $results->fetch_object()->value; - # For each update + // For each update foreach (self::$versions as $version) { - # Only update when newer version available + // Only update when newer version available if ($version<=$current) continue; - # Load update + // Load update include(__DIR__ . '/../database/update_' . $version . '.php'); } @@ -256,10 +256,10 @@ final class Database { public static function setVersion($connection, $version) { - # Check dependencies + // Check dependencies Validator::required(isset($connection), __METHOD__); - $query = self::prepare($connection, "UPDATE ? SET value = '?' WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS, $version)); + $query = self::prepare($connection, "UPDATE ? SET value = '?' WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS, $version)); $result = $connection->query($query); if (!$result) { Log::error(__METHOD__, __LINE__, 'Could not update database (' . $connection->error . ')'); @@ -270,62 +270,62 @@ final class Database { public static function prepare($connection, $query, array $data) { - # Check dependencies + // Check dependencies Validator::required(isset($connection, $query), __METHOD__); - # Count the number of placeholders and compare it with the number of arguments - # If it doesn't match, calculate the difference and skip this number of placeholders before starting the replacement - # This avoids problems with placeholders in user-input - # $skip = Number of placeholders which need to be skipped - $skip = 0; - $temp = ''; - $num = array( - 'placeholder' => substr_count($query, '?'), - 'data' => count($data) + // Count the number of placeholders and compare it with the number of arguments + // If it doesn't match, calculate the difference and skip this number of placeholders before starting the replacement + // This avoids problems with placeholders in user-input + // $skip = Number of placeholders which need to be skipped + $skip = 0; + $temp = ''; + $num = array( + 'placeholder' => substr_count($query, '?'), + 'data' => count($data) ); if (($num['data']-$num['placeholder'])<0) Log::notice(__METHOD__, __LINE__, 'Could not completely prepare query. Query has more placeholders than values.'); foreach ($data as $value) { - # Escape + // Escape $value = mysqli_real_escape_string($connection, $value); - # Recalculate number of placeholders + // Recalculate number of placeholders $num['placeholder'] = substr_count($query, '?'); - # Calculate number of skips + // Calculate number of skips if ($num['placeholder']>$num['data']) $skip = $num['placeholder'] - $num['data']; if ($skip>0) { - # Need to skip $skip placeholders, because the user input contained placeholders - # Calculate a substring which does not contain the user placeholders - # 1 or -1 is the length of the placeholder (placeholder = ?) + // Need to skip $skip placeholders, because the user input contained placeholders + // Calculate a substring which does not contain the user placeholders + // 1 or -1 is the length of the placeholder (placeholder = ?) $pos = -1; for ($i=$skip; $i>0; $i--) $pos = strpos($query, '?', $pos + 1); $pos++; - $temp = substr($query, 0, $pos); # First part of $query - $query = substr($query, $pos); # Last part of $query + $temp = substr($query, 0, $pos); // First part of $query + $query = substr($query, $pos); // Last part of $query } - # Replace + // Replace $query = preg_replace('/\?/', $value, $query, 1); if ($skip>0) { - # Reassemble the parts of $query + // Reassemble the parts of $query $query = $temp . $query; } - # Reset skip + // Reset skip $skip = 0; - # Decrease number of data elements + // Decrease number of data elements $num['data']--; } diff --git a/php/Modules/Import.php b/php/Modules/Import.php index dcc3041..886e83b 100644 --- a/php/Modules/Import.php +++ b/php/Modules/Import.php @@ -6,20 +6,20 @@ final class Import { private function photo($path, $albumID = 0, $description = '', $tags = '') { - # No need to validate photo type and extension in this function. - # $photo->add will take care of it. + // No need to validate photo type and extension in this function. + // $photo->add will take care of it. - $info = getimagesize($path); - $size = filesize($path); - $photo = new Photo(null); + $info = getimagesize($path); + $size = filesize($path); + $photo = new Photo(null); - $nameFile = array(array()); - $nameFile[0]['name'] = $path; - $nameFile[0]['type'] = $info['mime']; - $nameFile[0]['tmp_name'] = $path; - $nameFile[0]['error'] = 0; - $nameFile[0]['size'] = $size; - $nameFile[0]['error'] = UPLOAD_ERR_OK; + $nameFile = array(array()); + $nameFile[0]['name'] = $path; + $nameFile[0]['type'] = $info['mime']; + $nameFile[0]['tmp_name'] = $path; + $nameFile[0]['error'] = 0; + $nameFile[0]['size'] = $size; + $nameFile[0]['error'] = UPLOAD_ERR_OK; if (!$photo->add($nameFile, $albumID, $description, $tags, true)) return false; return true; @@ -28,21 +28,21 @@ final class Import { public function url($urls, $albumID = 0) { - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); $error = false; - # Parse URLs + // Parse URLs $urls = str_replace(' ', '%20', $urls); $urls = explode(',', $urls); foreach ($urls as &$url) { - # Validate photo type and extension even when $this->photo (=> $photo->add) will do the same. - # This prevents us from downloading invalid photos. + // Validate photo type and extension even when $this->photo (=> $photo->add) will do the same. + // This prevents us from downloading invalid photos. - # Verify extension + // Verify extension $extension = getExtension($url); if (!in_array(strtolower($extension), Photo::$validExtensions, true)) { $error = true; @@ -50,7 +50,7 @@ final class Import { continue; } - # Verify image + // Verify image $type = @exif_imagetype($url); if (!in_array($type, Photo::$validTypes, true)) { $error = true; @@ -58,9 +58,9 @@ final class Import { continue; } - $pathinfo = pathinfo($url); - $filename = $pathinfo['filename'] . '.' . $pathinfo['extension']; - $tmp_name = LYCHEE_DATA . $filename; + $pathinfo = pathinfo($url); + $filename = $pathinfo['filename'] . '.' . $pathinfo['extension']; + $tmp_name = LYCHEE_DATA . $filename; if (@copy($url, $tmp_name)===false) { $error = true; @@ -68,7 +68,7 @@ final class Import { continue; } - # Import photo + // Import photo if (!$this->photo($tmp_name, $albumID)) { $error = true; Log::error(__METHOD__, __LINE__, 'Could not import file: ' . $tmp_name); @@ -77,7 +77,7 @@ final class Import { } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if ($error===false) return true; @@ -87,16 +87,16 @@ final class Import { public function server($path, $albumID = 0) { - # Parse path - if (!isset($path)) $path = LYCHEE_UPLOADS_IMPORT; - if (substr($path, -1)==='/') $path = substr($path, 0, -1); + // Parse path + if (!isset($path)) $path = LYCHEE_UPLOADS_IMPORT; + if (substr($path, -1)==='/') $path = substr($path, 0, -1); if (is_dir($path)===false) { Log::error(__METHOD__, __LINE__, 'Given path is not a directory (' . $path . ')'); return 'Error: Given path is not a directory!'; } - # Skip folders of Lychee + // Skip folders of Lychee if ($path===LYCHEE_UPLOADS_BIG||($path . '/')===LYCHEE_UPLOADS_BIG|| $path===LYCHEE_UPLOADS_MEDIUM||($path . '/')===LYCHEE_UPLOADS_MEDIUM|| $path===LYCHEE_UPLOADS_THUMB||($path . '/')===LYCHEE_UPLOADS_THUMB) { @@ -104,22 +104,22 @@ final class Import { return 'Error: Given path is a reserved path of Lychee!'; } - $error = false; - $contains['photos'] = false; - $contains['albums'] = false; + $error = false; + $contains['photos'] = false; + $contains['albums'] = false; - # Call plugins - # Note that updated albumId and path explicitly passed, rather - # than using func_get_args() which will only return original ones + // Call plugins + // Note that updated albumId and path explicitly passed, rather + // than using func_get_args() which will only return original ones Plugins::get()->activate(__METHOD__, 0, array($albumID, $path)); - # Get all files + // Get all files $files = glob($path . '/*'); foreach ($files as $file) { - # It is possible to move a file because of directory permissions but - # the file may still be unreadable by the user + // It is possible to move a file because of directory permissions but + // the file may still be unreadable by the user if (!is_readable($file)) { $error = true; Log::error(__METHOD__, __LINE__, 'Could not read file or directory: ' . $file); @@ -128,7 +128,7 @@ final class Import { if (@exif_imagetype($file)!==false) { - # Photo + // Photo $contains['photos'] = true; @@ -140,11 +140,11 @@ final class Import { } else if (is_dir($file)) { - # Folder + // Folder - $album = new Album(null); - $newAlbumID = $album->add('[Import] ' . basename($file)); - $contains['albums'] = true; + $album = new Album(null); + $newAlbumID = $album->add('[Import] ' . basename($file)); + $contains['albums'] = true; if ($newAlbumID===false) { $error = true; @@ -164,14 +164,14 @@ final class Import { } - # Call plugins - # Note that updated albumId and path explicitly passed, rather - # than using func_get_args() which will only return original ones + // Call plugins + // Note that updated albumId and path explicitly passed, rather + // than using func_get_args() which will only return original ones Plugins::get()->activate(__METHOD__, 1, array($albumID, $path)); - # The following returns will be caught in the front-end - if ($contains['photos']===false&&$contains['albums']===false) return 'Warning: Folder empty or no readable files to process!'; - if ($contains['photos']===false&&$contains['albums']===true) return 'Notice: Import only contained albums!'; + // The following returns will be caught in the front-end + if ($contains['photos']===false&&$contains['albums']===false) return 'Warning: Folder empty or no readable files to process!'; + if ($contains['photos']===false&&$contains['albums']===true) return 'Notice: Import only contained albums!'; if ($error===true) return false; return true; diff --git a/php/Modules/Log.php b/php/Modules/Log.php index 44e9696..de49453 100644 --- a/php/Modules/Log.php +++ b/php/Modules/Log.php @@ -24,15 +24,15 @@ final class Log { private static function text($type, $function, $line, $text = '') { - # Check dependencies + // Check dependencies Validator::required(isset($type, $function, $line, $text), __METHOD__); - # Get time + // Get time $sysstamp = time(); - # Save in database - $query = Database::prepare(Database::get(), "INSERT INTO ? (time, type, function, line, text) VALUES ('?', '?', '?', '?', '?')", array(LYCHEE_TABLE_LOG, $sysstamp, $type, $function, $line, $text)); - $result = Database::get()->query($query); + // Save in database + $query = Database::prepare(Database::get(), "INSERT INTO ? (time, type, function, line, text) VALUES ('?', '?', '?', '?', '?')", array(LYCHEE_TABLE_LOG, $sysstamp, $type, $function, $line, $text)); + $result = Database::get()->query($query); if (!$result) return false; return true; diff --git a/php/Modules/Photo.php b/php/Modules/Photo.php index 4a069a9..039fe79 100755 --- a/php/Modules/Photo.php +++ b/php/Modules/Photo.php @@ -21,8 +21,8 @@ final class Photo { public function __construct($photoIDs) { - # Init vars - $this->photoIDs = $photoIDs; + // Init vars + $this->photoIDs = $photoIDs; return true; @@ -30,10 +30,10 @@ final class Photo { public function add(array $files, $albumID = 0, $description = '', $tags = '', $returnOnError = false) { - # Use $returnOnError if you want to handle errors by your own - # e.g. when calling this functions inside an if-condition + // Use $returnOnError if you want to handle errors by your own + // e.g. when calling this functions inside an if-condition - # Check permissions + // Check permissions if (hasPermissions(LYCHEE_UPLOADS)===false|| hasPermissions(LYCHEE_UPLOADS_BIG)===false|| hasPermissions(LYCHEE_UPLOADS_THUMB)===false) { @@ -41,77 +41,77 @@ final class Photo { exit('Error: An upload-folder is missing or not readable and writable!'); } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); switch($albumID) { case 's': - # s for public (share) - $public = 1; - $star = 0; - $albumID = 0; + // s for public (share) + $public = 1; + $star = 0; + $albumID = 0; break; case 'f': - # f for starred (fav) - $star = 1; - $public = 0; - $albumID = 0; + // f for starred (fav) + $star = 1; + $public = 0; + $albumID = 0; break; case 'r': - # r for recent - $public = 0; - $star = 0; - $albumID = 0; + // r for recent + $public = 0; + $star = 0; + $albumID = 0; break; default: - $star = 0; - $public = 0; + $star = 0; + $public = 0; break; } foreach ($files as $file) { - # Check if file exceeds the upload_max_filesize directive + // Check if file exceeds the upload_max_filesize directive if ($file['error']===UPLOAD_ERR_INI_SIZE) { Log::error(__METHOD__, __LINE__, 'The uploaded file exceeds the upload_max_filesize directive in php.ini'); if ($returnOnError===true) return false; exit('Error: The uploaded file exceeds the upload_max_filesize directive in php.ini!'); } - # Check if file was only partially uploaded + // Check if file was only partially uploaded if ($file['error']===UPLOAD_ERR_PARTIAL) { Log::error(__METHOD__, __LINE__, 'The uploaded file was only partially uploaded'); if ($returnOnError===true) return false; exit('Error: The uploaded file was only partially uploaded!'); } - # Check if writing file to disk failed + // Check if writing file to disk failed if ($file['error']===UPLOAD_ERR_CANT_WRITE) { Log::error(__METHOD__, __LINE__, 'Failed to write photo to disk'); if ($returnOnError===true) return false; exit('Error: Failed to write photo to disk!'); } - # Check if a extension stopped the file upload + // Check if a extension stopped the file upload if ($file['error']===UPLOAD_ERR_EXTENSION) { Log::error(__METHOD__, __LINE__, 'A PHP extension stopped the file upload'); if ($returnOnError===true) return false; exit('Error: A PHP extension stopped the file upload!'); } - # Check if the upload was successful + // Check if the upload was successful if ($file['error']!==UPLOAD_ERR_OK) { Log::error(__METHOD__, __LINE__, 'Upload contains an error (' . $file['error'] . ')'); if ($returnOnError===true) return false; exit('Error: Upload failed!'); } - # Verify extension + // Verify extension $extension = getExtension($file['name']); if (!in_array(strtolower($extension), self::$validExtensions, true)) { Log::error(__METHOD__, __LINE__, 'Photo format not supported'); @@ -119,7 +119,7 @@ final class Photo { exit('Error: Photo format not supported!'); } - # Verify image + // Verify image $type = @exif_imagetype($file['tmp_name']); if (!in_array($type, self::$validTypes, true)) { Log::error(__METHOD__, __LINE__, 'Photo type not supported'); @@ -127,16 +127,16 @@ final class Photo { exit('Error: Photo type not supported!'); } - # Generate id + // Generate id $id = str_replace('.', '', microtime(true)); while(strlen($id)<14) $id .= 0; - # Set paths - $tmp_name = $file['tmp_name']; - $photo_name = md5($id) . $extension; - $path = LYCHEE_UPLOADS_BIG . $photo_name; + // Set paths + $tmp_name = $file['tmp_name']; + $photo_name = md5($id) . $extension; + $path = LYCHEE_UPLOADS_BIG . $photo_name; - # Calculate checksum + // Calculate checksum $checksum = sha1_file($tmp_name); if ($checksum===false) { Log::error(__METHOD__, __LINE__, 'Could not calculate checksum for photo'); @@ -144,29 +144,29 @@ final class Photo { exit('Error: Could not calculate checksum for photo!'); } - # Check if image exists based on checksum + // Check if image exists based on checksum if ($checksum===false) { - $checksum = ''; - $exists = false; + $checksum = ''; + $exists = false; } else { $exists = $this->exists($checksum); if ($exists!==false) { - $photo_name = $exists['photo_name']; - $path = $exists['path']; - $path_thumb = $exists['path_thumb']; - $medium = ($exists['medium']==='1' ? 1 : 0); - $exists = true; + $photo_name = $exists['photo_name']; + $path = $exists['path']; + $path_thumb = $exists['path_thumb']; + $medium = ($exists['medium']==='1' ? 1 : 0); + $exists = true; } } if ($exists===false) { - # Import if not uploaded via web + // Import if not uploaded via web if (!is_uploaded_file($tmp_name)) { if (!@copy($tmp_name, $path)) { Log::error(__METHOD__, __LINE__, 'Could not copy photo to uploads'); @@ -183,8 +183,8 @@ final class Photo { } else { - # Photo already exists - # Check if the user wants to skip duplicates + // Photo already exists + // Check if the user wants to skip duplicates if (Settings::get()['skipDuplicates']==='1') { Log::notice(__METHOD__, __LINE__, 'Skipped upload of existing photo because skipDuplicates is activated'); if ($returnOnError===true) return false; @@ -193,46 +193,46 @@ final class Photo { } - # Read infos + // Read infos $info = $this->getInfo($path); - # Use title of file if IPTC title missing + // Use title of file if IPTC title missing if ($info['title']==='') $info['title'] = substr(basename($file['name'], $extension), 0, 30); - # Use description parameter if set + // Use description parameter if set if ($description==='') $description = $info['description']; if ($exists===false) { - # Set orientation based on EXIF data + // Set orientation based on EXIF data if ($file['type']==='image/jpeg'&&isset($info['orientation'])&&$info['orientation']!=='') { $adjustFile = $this->adjustFile($path, $info); if ($adjustFile!==false) $info = $adjustFile; else Log::notice(__METHOD__, __LINE__, 'Skipped adjustment of photo (' . $info['title'] . ')'); } - # Set original date + // Set original date if ($info['takestamp']!==''&&$info['takestamp']!==0) @touch($path, $info['takestamp']); - # Create Thumb + // Create Thumb if (!$this->createThumb($path, $photo_name, $info['type'], $info['width'], $info['height'])) { Log::error(__METHOD__, __LINE__, 'Could not create thumbnail for photo'); if ($returnOnError===true) return false; exit('Error: Could not create thumbnail for photo!'); } - # Create Medium + // Create Medium if ($this->createMedium($path, $photo_name, $info['width'], $info['height'])) $medium = 1; else $medium = 0; - # Set thumb url + // Set thumb url $path_thumb = md5($id) . '.jpeg'; } - # Save to DB - $values = array(LYCHEE_TABLE_PHOTOS, $id, $info['title'], $photo_name, $description, $tags, $info['type'], $info['width'], $info['height'], $info['size'], $info['iso'], $info['aperture'], $info['make'], $info['model'], $info['shutter'], $info['focal'], $info['takestamp'], $path_thumb, $albumID, $public, $star, $checksum, $medium); - $query = Database::prepare(Database::get(), "INSERT INTO ? (id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum, medium) VALUES ('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')", $values); + // Save to DB + $values = array(LYCHEE_TABLE_PHOTOS, $id, $info['title'], $photo_name, $description, $tags, $info['type'], $info['width'], $info['height'], $info['size'], $info['iso'], $info['aperture'], $info['make'], $info['model'], $info['shutter'], $info['focal'], $info['takestamp'], $path_thumb, $albumID, $public, $star, $checksum, $medium); + $query = Database::prepare(Database::get(), "INSERT INTO ? (id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum, medium) VALUES ('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')", $values); $result = Database::get()->query($query); if (!$result) { @@ -243,7 +243,7 @@ final class Photo { } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return true; @@ -252,11 +252,11 @@ final class Photo { private function exists($checksum, $photoID = null) { - # Exclude $photoID from select when $photoID is set + // Exclude $photoID from select when $photoID is set if (isset($photoID)) $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, medium FROM ? WHERE checksum = '?' AND id <> '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $checksum, $photoID)); else $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, medium FROM ? WHERE checksum = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $checksum)); - $result = Database::get()->query($query); + $result = Database::get()->query($query); if (!$result) { Log::error(__METHOD__, __LINE__, 'Could not check for existing photos with the same checksum'); @@ -268,10 +268,10 @@ final class Photo { $result = $result->fetch_object(); $return = array( - 'photo_name' => $result->url, - 'path' => LYCHEE_UPLOADS_BIG . $result->url, - 'path_thumb' => $result->thumbUrl, - 'medium' => $result->medium + 'photo_name' => $result->url, + 'path' => LYCHEE_UPLOADS_BIG . $result->url, + 'path_thumb' => $result->thumbUrl, + 'medium' => $result->medium ); return $return; @@ -284,36 +284,36 @@ final class Photo { private function createThumb($url, $filename, $type, $width, $height) { - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Size of the thumbnail - $newWidth = 200; - $newHeight = 200; + // Size of the thumbnail + $newWidth = 200; + $newHeight = 200; - $photoName = explode('.', $filename); - $newUrl = LYCHEE_UPLOADS_THUMB . $photoName[0] . '.jpeg'; - $newUrl2x = LYCHEE_UPLOADS_THUMB . $photoName[0] . '@2x.jpeg'; + $photoName = explode('.', $filename); + $newUrl = LYCHEE_UPLOADS_THUMB . $photoName[0] . '.jpeg'; + $newUrl2x = LYCHEE_UPLOADS_THUMB . $photoName[0] . '@2x.jpeg'; - # Create thumbnails with Imagick + // Create thumbnails with Imagick if(extension_loaded('imagick')&&Settings::get()['imagick']==='1') { - # Read image + // Read image $thumb = new Imagick(); $thumb->readImage($url); $thumb->setImageCompressionQuality(Settings::get()['thumbQuality']); $thumb->setImageFormat('jpeg'); - # Copy image for 2nd thumb version + // Copy image for 2nd thumb version $thumb2x = clone $thumb; - # Create 1st version + // Create 1st version $thumb->cropThumbnailImage($newWidth, $newHeight); $thumb->writeImage($newUrl); $thumb->clear(); $thumb->destroy(); - # Create 2nd version + // Create 2nd version $thumb2x->cropThumbnailImage($newWidth*2, $newHeight*2); $thumb2x->writeImage($newUrl2x); $thumb2x->clear(); @@ -321,47 +321,47 @@ final class Photo { } else { - # Create image - $thumb = imagecreatetruecolor($newWidth, $newHeight); - $thumb2x = imagecreatetruecolor($newWidth*2, $newHeight*2); + // Create image + $thumb = imagecreatetruecolor($newWidth, $newHeight); + $thumb2x = imagecreatetruecolor($newWidth*2, $newHeight*2); - # Set position + // Set position if ($width<$height) { - $newSize = $width; - $startWidth = 0; - $startHeight = $height/2 - $width/2; + $newSize = $width; + $startWidth = 0; + $startHeight = $height/2 - $width/2; } else { - $newSize = $height; - $startWidth = $width/2 - $height/2; - $startHeight = 0; + $newSize = $height; + $startWidth = $width/2 - $height/2; + $startHeight = 0; } - # Create new image + // Create new image switch($type) { - case 'image/jpeg': $sourceImg = imagecreatefromjpeg($url); break; - case 'image/png': $sourceImg = imagecreatefrompng($url); break; - case 'image/gif': $sourceImg = imagecreatefromgif($url); break; - default: Log::error(__METHOD__, __LINE__, 'Type of photo is not supported'); - return false; - break; + case 'image/jpeg': $sourceImg = imagecreatefromjpeg($url); break; + case 'image/png': $sourceImg = imagecreatefrompng($url); break; + case 'image/gif': $sourceImg = imagecreatefromgif($url); break; + default: Log::error(__METHOD__, __LINE__, 'Type of photo is not supported'); + return false; + break; } - # Create thumb + // Create thumb fastImageCopyResampled($thumb, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth, $newHeight, $newSize, $newSize); imagejpeg($thumb, $newUrl, Settings::get()['thumbQuality']); imagedestroy($thumb); - # Create retina thumb + // Create retina thumb fastImageCopyResampled($thumb2x, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth*2, $newHeight*2, $newSize, $newSize); imagejpeg($thumb2x, $newUrl2x, Settings::get()['thumbQuality']); imagedestroy($thumb2x); - # Free memory + // Free memory imagedestroy($sourceImg); } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return true; @@ -370,40 +370,40 @@ final class Photo { private function createMedium($url, $filename, $width, $height) { - # Function creates a smaller version of a photo when its size is bigger than a preset size - # Excepts the following: - # (string) $url = Path to the photo-file - # (string) $filename = Name of the photo-file - # (int) $width = Width of the photo - # (int) $height = Height of the photo - # Returns the following - # (boolean) true = Success - # (boolean) false = Failure + // Function creates a smaller version of a photo when its size is bigger than a preset size + // Excepts the following: + // (string) $url = Path to the photo-file + // (string) $filename = Name of the photo-file + // (int) $width = Width of the photo + // (int) $height = Height of the photo + // Returns the following + // (boolean) true = Success + // (boolean) false = Failure - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Set to true when creation of medium-photo failed + // Set to true when creation of medium-photo failed $error = false; - # Size of the medium-photo - # When changing these values, - # also change the size detection in the front-end - $newWidth = 1920; - $newHeight = 1080; + // Size of the medium-photo + // When changing these values, + // also change the size detection in the front-end + $newWidth = 1920; + $newHeight = 1080; - # Check permissions + // Check permissions if (hasPermissions(LYCHEE_UPLOADS_MEDIUM)===false) { - # Permissions are missing + // Permissions are missing Log::notice(__METHOD__, __LINE__, 'Skipped creation of medium-photo, because uploads/medium/ is missing or not readable and writable.'); $error = true; } - # Is photo big enough? - # Is medium activated? - # Is Imagick installed and activated? + // Is photo big enough? + // Is medium activated? + // Is Imagick installed and activated? if (($error===false)&& ($width>$newWidth||$height>$newHeight)&& (Settings::get()['medium']==='1')&& @@ -411,14 +411,14 @@ final class Photo { $newUrl = LYCHEE_UPLOADS_MEDIUM . $filename; - # Read image + // Read image $medium = new Imagick(); $medium->readImage($url); - # Adjust image + // Adjust image $medium->scaleImage($newWidth, $newHeight, true); - # Save image + // Save image try { $medium->writeImage($newUrl); } catch (ImagickException $err) { Log::notice(__METHOD__, __LINE__, 'Could not save medium-photo: ' . $err->getMessage()); @@ -430,14 +430,14 @@ final class Photo { } else { - # Photo too small or - # Medium is deactivated or - # Imagick not installed + // Photo too small or + // Medium is deactivated or + // Imagick not installed $error = true; } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if ($error===true) return false; @@ -447,15 +447,15 @@ final class Photo { public function adjustFile($path, array $info) { - # Function rotates and flips a photo based on its EXIF orientation - # Excepts the following: - # (string) $path = Path to the photo-file - # (array) $info = ['orientation', 'width', 'height'] - # Returns the following - # (array) $info = ['orientation', 'width', 'height'] = Success - # (boolean) false = Failure + // Function rotates and flips a photo based on its EXIF orientation + // Excepts the following: + // (string) $path = Path to the photo-file + // (array) $info = ['orientation', 'width', 'height'] + // Returns the following + // (array) $info = ['orientation', 'width', 'height'] = Success + // (boolean) false = Failure - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); $swapSize = false; @@ -469,13 +469,13 @@ final class Photo { break; case 6: - $rotateImage = 90; - $swapSize = true; + $rotateImage = 90; + $swapSize = true; break; case 8: - $rotateImage = 270; - $swapSize = true; + $rotateImage = 270; + $swapSize = true; break; default: @@ -496,52 +496,52 @@ final class Photo { } else { - $newWidth = $info['width']; - $newHeight = $info['height']; - $sourceImg = imagecreatefromjpeg($path); + $newWidth = $info['width']; + $newHeight = $info['height']; + $sourceImg = imagecreatefromjpeg($path); switch ($info['orientation']) { case 2: - # mirror - # not yet implemented + // mirror + // not yet implemented return false; break; case 3: - $sourceImg = imagerotate($sourceImg, -180, 0); + $sourceImg = imagerotate($sourceImg, -180, 0); break; case 4: - # rotate 180 and mirror - # not yet implemented + // rotate 180 and mirror + // not yet implemented return false; break; case 5: - # rotate 90 and mirror - # not yet implemented + // rotate 90 and mirror + // not yet implemented return false; break; case 6: - $sourceImg = imagerotate($sourceImg, -90, 0); - $newWidth = $info['height']; - $newHeight = $info['width']; - $swapSize = true; + $sourceImg = imagerotate($sourceImg, -90, 0); + $newWidth = $info['height']; + $newHeight = $info['width']; + $swapSize = true; break; case 7: - # rotate -90 and mirror - # not yet implemented + // rotate -90 and mirror + // not yet implemented return false; break; case 8: - $sourceImg = imagerotate($sourceImg, 90, 0); - $newWidth = $info['height']; - $newHeight = $info['width']; - $swapSize = true; + $sourceImg = imagerotate($sourceImg, 90, 0); + $newWidth = $info['height']; + $newHeight = $info['width']; + $swapSize = true; break; default: @@ -550,26 +550,26 @@ final class Photo { } - # Recreate photo + // Recreate photo $newSourceImg = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newSourceImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight); imagejpeg($newSourceImg, $path, 100); - # Free memory + // Free memory imagedestroy($sourceImg); imagedestroy($newSourceImg); } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); - # SwapSize should be true when the image has been rotated - # Return new dimensions in this case + // SwapSize should be true when the image has been rotated + // Return new dimensions in this case if ($swapSize===true) { - $swapSize = $info['width']; - $info['width'] = $info['height']; - $info['height'] = $swapSize; + $swapSize = $info['width']; + $info['width'] = $info['height']; + $info['height'] = $swapSize; } return $info; @@ -578,39 +578,39 @@ final class Photo { public static function prepareData(array $data) { - # Function turns photo-attributes into a front-end friendly format. Note that some attributes remain unchanged. - # Excepts the following: - # (array) $data = ['id', 'title', 'tags', 'public', 'star', 'album', 'thumbUrl', 'takestamp', 'url'] - # Returns the following: - # (array) $photo + // Function turns photo-attributes into a front-end friendly format. Note that some attributes remain unchanged. + // Excepts the following: + // (array) $data = ['id', 'title', 'tags', 'public', 'star', 'album', 'thumbUrl', 'takestamp', 'url'] + // Returns the following: + // (array) $photo - # Init + // Init $photo = null; - # Set unchanged attributes - $photo['id'] = $data['id']; - $photo['title'] = $data['title']; - $photo['tags'] = $data['tags']; - $photo['public'] = $data['public']; - $photo['star'] = $data['star']; - $photo['album'] = $data['album']; + // Set unchanged attributes + $photo['id'] = $data['id']; + $photo['title'] = $data['title']; + $photo['tags'] = $data['tags']; + $photo['public'] = $data['public']; + $photo['star'] = $data['star']; + $photo['album'] = $data['album']; - # Parse urls - $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $data['thumbUrl']; - $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $data['url']; + // Parse urls + $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $data['thumbUrl']; + $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $data['url']; - # Use takestamp as sysdate when possible + // Use takestamp as sysdate when possible if (isset($data['takestamp'])&&$data['takestamp']!=='0') { - # Use takestamp - $photo['cameraDate'] = '1'; - $photo['sysdate'] = date('d F Y', $data['takestamp']); + // Use takestamp + $photo['cameraDate'] = '1'; + $photo['sysdate'] = date('d F Y', $data['takestamp']); } else { - # Use sysstamp from the id - $photo['cameraDate'] = '0'; - $photo['sysdate'] = date('d F Y', substr($data['id'], 0, -4)); + // Use sysstamp from the id + $photo['cameraDate'] = '0'; + $photo['sysdate'] = date('d F Y', substr($data['id'], 0, -4)); } @@ -620,57 +620,57 @@ final class Photo { public function get($albumID) { - # Functions returns data of a photo - # Excepts the following: - # (string) $albumID = Album which is currently visible to the user - # Returns the following: - # (array) $photo + // Functions returns data of a photo + // Excepts the following: + // (string) $albumID = Album which is currently visible to the user + // Returns the following: + // (array) $photo - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Get photo - $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); - $photos = Database::get()->query($query); - $photo = $photos->fetch_assoc(); + // Get photo + $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); + $photos = Database::get()->query($query); + $photo = $photos->fetch_assoc(); - # Parse photo + // Parse photo $photo['sysdate'] = date('d M. Y', substr($photo['id'], 0, -4)); if (strlen($photo['takestamp'])>1) $photo['takedate'] = date('d M. Y', $photo['takestamp']); - # Parse medium - if ($photo['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $photo['url']; - else $photo['medium'] = ''; + // Parse medium + if ($photo['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $photo['url']; + else $photo['medium'] = ''; - # Parse paths - $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $photo['url']; - $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $photo['thumbUrl']; + // Parse paths + $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $photo['url']; + $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $photo['thumbUrl']; if ($albumID!='false') { - # Only show photo as public when parent album is public - # Check if parent album is not 'Unsorted' + // Only show photo as public when parent album is public + // Check if parent album is not 'Unsorted' if ($photo['album']!=='0') { - # Get album - $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $photo['album'])); - $albums = Database::get()->query($query); - $album = $albums->fetch_assoc(); + // Get album + $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $photo['album'])); + $albums = Database::get()->query($query); + $album = $albums->fetch_assoc(); - # Parse album + // Parse album $photo['public'] = ($album['public']==='1' ? '2' : $photo['public']); } - $photo['original_album'] = $photo['album']; - $photo['album'] = $albumID; + $photo['original_album'] = $photo['album']; + $photo['album'] = $albumID; } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return $photo; @@ -679,33 +679,33 @@ final class Photo { public function getInfo($url) { - # Functions returns information and metadata of a photo - # Excepts the following: - # (string) $url = Path to photo-file - # Returns the following: - # (array) $return + // Functions returns information and metadata of a photo + // Excepts the following: + // (string) $url = Path to photo-file + // Returns the following: + // (array) $return - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - $iptcArray = array(); - $info = getimagesize($url, $iptcArray); + $iptcArray = array(); + $info = getimagesize($url, $iptcArray); - # General information - $return['type'] = $info['mime']; - $return['width'] = $info[0]; - $return['height'] = $info[1]; + // General information + $return['type'] = $info['mime']; + $return['width'] = $info[0]; + $return['height'] = $info[1]; - # Size + // Size $size = filesize($url)/1024; if ($size>=1024) $return['size'] = round($size/1024, 1) . ' MB'; else $return['size'] = round($size, 1) . ' KB'; - # IPTC Metadata Fallback - $return['title'] = ''; - $return['description'] = ''; + // IPTC Metadata Fallback + $return['title'] = ''; + $return['description'] = ''; - # IPTC Metadata + // IPTC Metadata if(isset($iptcArray['APP13'])) { $iptcInfo = iptcparse($iptcArray['APP13']); @@ -724,21 +724,21 @@ final class Photo { } - # EXIF Metadata Fallback - $return['orientation'] = ''; - $return['iso'] = ''; - $return['aperture'] = ''; - $return['make'] = ''; - $return['model'] = ''; - $return['shutter'] = ''; - $return['focal'] = ''; - $return['takestamp'] = 0; + // EXIF Metadata Fallback + $return['orientation'] = ''; + $return['iso'] = ''; + $return['aperture'] = ''; + $return['make'] = ''; + $return['model'] = ''; + $return['shutter'] = ''; + $return['focal'] = ''; + $return['takestamp'] = 0; - # Read EXIF + // Read EXIF if ($info['mime']=='image/jpeg') $exif = @exif_read_data($url, 'EXIF', 0); else $exif = false; - # EXIF Metadata + // EXIF Metadata if ($exif!==false) { if (isset($exif['Orientation'])) $return['orientation'] = $exif['Orientation']; @@ -775,7 +775,7 @@ final class Photo { } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return $return; @@ -784,62 +784,62 @@ final class Photo { public function getArchive() { - # Functions starts a download of a photo - # Returns the following: - # (boolean + output) true = Success - # (boolean) false = Failure + // Functions starts a download of a photo + // Returns the following: + // (boolean + output) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Get photo - $query = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); - $photos = Database::get()->query($query); - $photo = $photos->fetch_object(); + // Get photo + $query = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); + $photos = Database::get()->query($query); + $photo = $photos->fetch_object(); - # Error in database query + // Error in database query if (!$photos) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; } - # Photo not found + // Photo not found if ($photo===null) { Log::error(__METHOD__, __LINE__, 'Album not found. Cannot start download.'); return false; } - # Get extension + // Get extension $extension = getExtension($photo->url); if ($extension===false) { Log::error(__METHOD__, __LINE__, 'Invalid photo extension'); return false; } - # Illicit chars - $badChars = array_merge( - array_map('chr', range(0,31)), - array("<", ">", ":", '"', "/", "\\", "|", "?", "*") - ); + // Illicit chars + $badChars = array_merge( + array_map('chr', range(0,31)), + array("<", ">", ":", '"', "/", "\\", "|", "?", "*") + ); - # Parse title + // Parse title if ($photo->title=='') $photo->title = 'Untitled'; - # Escape title + // Escape title $photo->title = str_replace($badChars, '', $photo->title); - # Set headers + // Set headers header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"" . $photo->title . $extension . "\""); header("Content-Length: " . filesize(LYCHEE_UPLOADS_BIG . $photo->url)); - # Send file + // Send file readfile(LYCHEE_UPLOADS_BIG . $photo->url); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return true; @@ -848,24 +848,24 @@ final class Photo { public function setTitle($title) { - # Functions sets the title of a photo - # Excepts the following: - # (string) $title = Title with a maximum length of 50 chars - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions sets the title of a photo + // Excepts the following: + // (string) $title = Title with a maximum length of 50 chars + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Set title - $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $title, $this->photoIDs)); - $result = Database::get()->query($query); + // Set title + $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $title, $this->photoIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -878,24 +878,24 @@ final class Photo { public function setDescription($description) { - # Functions sets the description of a photo - # Excepts the following: - # (string) $description = Description with a maximum length of 1000 chars - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions sets the description of a photo + // Excepts the following: + // (string) $description = Description with a maximum length of 1000 chars + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Set description - $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN ('?')", array(LYCHEE_TABLE_PHOTOS, $description, $this->photoIDs)); - $result = Database::get()->query($query); + // Set description + $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN ('?')", array(LYCHEE_TABLE_PHOTOS, $description, $this->photoIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -908,38 +908,38 @@ final class Photo { public function setStar() { - # Functions stars a photo - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions stars a photo + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Init vars - $error = false; + // Init vars + $error = false; - # Get photos - $query = Database::prepare(Database::get(), "SELECT id, star FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); - $photos = Database::get()->query($query); + // Get photos + $query = Database::prepare(Database::get(), "SELECT id, star FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); + $photos = Database::get()->query($query); - # For each photo + // For each photo while ($photo = $photos->fetch_object()) { - # Invert star + // Invert star $star = ($photo->star==0 ? 1 : 0); - # Set star - $query = Database::prepare(Database::get(), "UPDATE ? SET star = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $star, $photo->id)); - $star = Database::get()->query($query); + // Set star + $query = Database::prepare(Database::get(), "UPDATE ? SET star = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $star, $photo->id)); + $star = Database::get()->query($query); if (!$star) $error = true; } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if ($error===true) { @@ -952,78 +952,78 @@ final class Photo { public function getPublic($password) { - # Functions checks if photo or parent album is public - # Returns the following: - # (int) 0 = Photo private and parent album private - # (int) 1 = Album public, but password incorrect - # (int) 2 = Photo public or album public and password correct + // Functions checks if photo or parent album is public + // Returns the following: + // (int) 0 = Photo private and parent album private + // (int) 1 = Album public, but password incorrect + // (int) 2 = Photo public or album public and password correct - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Get photo - $query = Database::prepare(Database::get(), "SELECT public, album FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); - $photos = Database::get()->query($query); - $photo = $photos->fetch_object(); + // Get photo + $query = Database::prepare(Database::get(), "SELECT public, album FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); + $photos = Database::get()->query($query); + $photo = $photos->fetch_object(); - # Check if public + // Check if public if ($photo->public==='1') { - # Photo public + // Photo public return 2; } else { - # Check if album public - $album = new Album($photo->album); - $agP = $album->getPublic(); - $acP = $album->checkPassword($password); + // Check if album public + $album = new Album($photo->album); + $agP = $album->getPublic(); + $acP = $album->checkPassword($password); - # Album public and password correct + // Album public and password correct if ($agP===true&&$acP===true) return 2; - # Album public, but password incorrect + // Album public, but password incorrect if ($agP===true&&$acP===false) return 1; } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); - # Photo private + // Photo private return 0; } public function setPublic() { - # Functions toggles the public property of a photo - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions toggles the public property of a photo + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Get public - $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); - $photos = Database::get()->query($query); - $photo = $photos->fetch_object(); + // Get public + $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); + $photos = Database::get()->query($query); + $photo = $photos->fetch_object(); - # Invert public + // Invert public $public = ($photo->public==0 ? 1 : 0); - # Set public - $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $public, $this->photoIDs)); - $result = Database::get()->query($query); + // Set public + $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $public, $this->photoIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -1036,22 +1036,22 @@ final class Photo { function setAlbum($albumID) { - # Functions sets the parent album of a photo - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions sets the parent album of a photo + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Set album - $query = Database::prepare(Database::get(), "UPDATE ? SET album = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->photoIDs)); - $result = Database::get()->query($query); + // Set album + $query = Database::prepare(Database::get(), "UPDATE ? SET album = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->photoIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -1064,28 +1064,28 @@ final class Photo { public function setTags($tags) { - # Functions sets the tags of a photo - # Excepts the following: - # (string) $tags = Comma separated list of tags with a maximum length of 1000 chars - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions sets the tags of a photo + // Excepts the following: + // (string) $tags = Comma separated list of tags with a maximum length of 1000 chars + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Parse tags + // Parse tags $tags = preg_replace('/(\ ,\ )|(\ ,)|(,\ )|(,{1,}\ {0,})|(,$|^,)/', ',', $tags); $tags = preg_replace('/,$|^,|(\ ){0,}$/', '', $tags); - # Set tags - $query = Database::prepare(Database::get(), "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs)); - $result = Database::get()->query($query); + // Set tags + $query = Database::prepare(Database::get(), "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs)); + $result = Database::get()->query($query); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); if (!$result) { @@ -1098,36 +1098,36 @@ final class Photo { public function duplicate() { - # Functions duplicates a photo - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions duplicates a photo + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Get photos - $query = Database::prepare(Database::get(), "SELECT id, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); - $photos = Database::get()->query($query); + // Get photos + $query = Database::prepare(Database::get(), "SELECT id, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); + $photos = Database::get()->query($query); if (!$photos) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; } - # For each photo + // For each photo while ($photo = $photos->fetch_object()) { - # Generate id + // Generate id $id = str_replace('.', '', microtime(true)); while(strlen($id)<14) $id .= 0; - # Duplicate entry - $values = array(LYCHEE_TABLE_PHOTOS, $id, LYCHEE_TABLE_PHOTOS, $photo->id); - $query = Database::prepare(Database::get(), "INSERT INTO ? (id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum) SELECT '?' AS id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum FROM ? WHERE id = '?'", $values); - $duplicate = Database::get()->query($query); + // Duplicate entry + $values = array(LYCHEE_TABLE_PHOTOS, $id, LYCHEE_TABLE_PHOTOS, $photo->id); + $query = Database::prepare(Database::get(), "INSERT INTO ? (id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum) SELECT '?' AS id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum FROM ? WHERE id = '?'", $values); + $duplicate = Database::get()->query($query); if (!$duplicate) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; @@ -1141,65 +1141,65 @@ final class Photo { public function delete() { - # Functions deletes a photo with all its data and files - # Returns the following: - # (boolean) true = Success - # (boolean) false = Failure + // Functions deletes a photo with all its data and files + // Returns the following: + // (boolean) true = Success + // (boolean) false = Failure - # Check dependencies + // Check dependencies Validator::required(isset($this->photoIDs), __METHOD__); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Get photos - $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); - $photos = Database::get()->query($query); + // Get photos + $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs)); + $photos = Database::get()->query($query); if (!$photos) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; } - # For each photo + // For each photo while ($photo = $photos->fetch_object()) { - # Check if other photos are referring to this images - # If so, only delete the db entry + // Check if other photos are referring to this images + // If so, only delete the db entry if ($this->exists($photo->checksum, $photo->id)===false) { - # Get retina thumb url + // Get retina thumb url $thumbUrl2x = explode(".", $photo->thumbUrl); $thumbUrl2x = $thumbUrl2x[0] . '@2x.' . $thumbUrl2x[1]; - # Delete big + // Delete big if (file_exists(LYCHEE_UPLOADS_BIG . $photo->url)&&!unlink(LYCHEE_UPLOADS_BIG . $photo->url)) { Log::error(__METHOD__, __LINE__, 'Could not delete photo in uploads/big/'); return false; } - # Delete medium + // Delete medium if (file_exists(LYCHEE_UPLOADS_MEDIUM . $photo->url)&&!unlink(LYCHEE_UPLOADS_MEDIUM . $photo->url)) { Log::error(__METHOD__, __LINE__, 'Could not delete photo in uploads/medium/'); return false; } - # Delete thumb + // Delete thumb if (file_exists(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)&&!unlink(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)) { Log::error(__METHOD__, __LINE__, 'Could not delete photo in uploads/thumb/'); return false; } - # Delete thumb@2x - if (file_exists(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)&&!unlink(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)) { + // Delete thumb@2x + if (file_exists(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)&&!unlink(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)) { Log::error(__METHOD__, __LINE__, 'Could not delete high-res photo in uploads/thumb/'); return false; } } - # Delete db entry - $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photo->id)); - $delete = Database::get()->query($query); + // Delete db entry + $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photo->id)); + $delete = Database::get()->query($query); if (!$delete) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; @@ -1207,7 +1207,7 @@ final class Photo { } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return true; diff --git a/php/Modules/Plugins.php b/php/Modules/Plugins.php index 13bb55c..ed17f02 100644 --- a/php/Modules/Plugins.php +++ b/php/Modules/Plugins.php @@ -30,7 +30,7 @@ final class Plugins implements SplSubject { private function __construct(array $plugins) { - # Load plugins + // Load plugins foreach ($plugins as $plugin) { if ($plugin==='') continue; @@ -47,7 +47,7 @@ final class Plugins implements SplSubject { if (!isset($observer)) return false; - # Add observer + // Add observer $this->observers[] = $observer; return true; @@ -58,7 +58,7 @@ final class Plugins implements SplSubject { if (!isset($observer)) return false; - # Remove observer + // Remove observer $key = array_search($observer, $this->observers, true); if ($key) unset($this->observers[$key]); @@ -68,7 +68,7 @@ final class Plugins implements SplSubject { public function notify() { - # Notify each observer + // Notify each observer foreach ($this->observers as $value) $value->update($this); return true; @@ -79,15 +79,15 @@ final class Plugins implements SplSubject { if (!isset($name, $location, $args)) return false; - # Parse - $location = ($location===0 ? 'before' : 'after'); - $action = $name . ":" . $location; + // Parse + $location = ($location===0 ? 'before' : 'after'); + $action = $name . ":" . $location; - # Save vars - $this->action = $action; - $this->args = $args; + // Save vars + $this->action = $action; + $this->args = $args; - # Notify observers + // Notify observers $this->notify(); return true; diff --git a/php/Modules/Session.php b/php/Modules/Session.php index 580274e..94c4278 100755 --- a/php/Modules/Session.php +++ b/php/Modules/Session.php @@ -6,23 +6,23 @@ final class Session { public function init($public = true) { - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - # Return settings + // Return settings $return['config'] = Settings::get(); - # Path to Lychee for the server-import dialog + // Path to Lychee for the server-import dialog $return['config']['location'] = LYCHEE; - # Remove username and password from response + // Remove username and password from response unset($return['config']['username']); unset($return['config']['password']); - # Remove identifier from response + // Remove identifier from response unset($return['config']['identifier']); - # Check if login credentials exist and login if they don't + // Check if login credentials exist and login if they don't if ($this->noLogin()===true) { $public = false; $return['config']['login'] = false; @@ -32,15 +32,15 @@ final class Session { if ($public===false) { - # Logged in + // Logged in $return['status'] = LYCHEE_STATUS_LOGGEDIN; } else { - # Logged out + // Logged out $return['status'] = LYCHEE_STATUS_LOGGEDOUT; - # Unset unused vars + // Unset unused vars unset($return['config']['skipDuplicates']); unset($return['config']['thumbQuality']); unset($return['config']['sortingAlbums']); @@ -54,7 +54,7 @@ final class Session { } - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return $return; @@ -63,24 +63,24 @@ final class Session { public function login($username, $password) { - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); $username = crypt($username, Settings::get()['username']); $password = crypt($password, Settings::get()['password']); - # Check login with crypted hash + // Check login with crypted hash if (Settings::get()['username']===$username&& Settings::get()['password']===$password) { - $_SESSION['login'] = true; - $_SESSION['identifier'] = Settings::get()['identifier']; + $_SESSION['login'] = true; + $_SESSION['identifier'] = Settings::get()['identifier']; return true; } - # No login + // No login if ($this->noLogin()===true) return true; - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return false; @@ -89,11 +89,11 @@ final class Session { private function noLogin() { - # Check if login credentials exist and login if they don't + // Check if login credentials exist and login if they don't if (Settings::get()['username']===''&& Settings::get()['password']==='') { - $_SESSION['login'] = true; - $_SESSION['identifier'] = Settings::get()['identifier']; + $_SESSION['login'] = true; + $_SESSION['identifier'] = Settings::get()['identifier']; return true; } @@ -103,15 +103,15 @@ final class Session { public function logout() { - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 0, func_get_args()); - $_SESSION['login'] = null; - $_SESSION['identifier'] = null; + $_SESSION['login'] = null; + $_SESSION['identifier'] = null; session_destroy(); - # Call plugins + // Call plugins Plugins::get()->activate(__METHOD__, 1, func_get_args()); return true; diff --git a/php/Modules/Settings.php b/php/Modules/Settings.php index d916cce..9d22d99 100755 --- a/php/Modules/Settings.php +++ b/php/Modules/Settings.php @@ -10,14 +10,14 @@ final class Settings { if (self::$cache) return self::$cache; - # Execute query - $query = Database::prepare(Database::get(), "SELECT * FROM ?", array(LYCHEE_TABLE_SETTINGS)); - $settings = Database::get()->query($query); + // Execute query + $query = Database::prepare(Database::get(), "SELECT * FROM ?", array(LYCHEE_TABLE_SETTINGS)); + $settings = Database::get()->query($query); - # Add each to return + // Add each to return while ($setting = $settings->fetch_object()) $return[$setting->key] = $setting->value; - # Convert plugins to array + // Convert plugins to array $return['plugins'] = explode(';', $return['plugins']); self::$cache = $return; @@ -30,12 +30,12 @@ final class Settings { if ($row===false) { - $query = Database::prepare(Database::get(), "UPDATE ? SET value = '?' WHERE `key` = '?'", array(LYCHEE_TABLE_SETTINGS, $value, $key)); + $query = Database::prepare(Database::get(), "UPDATE ? SET value = '?' WHERE `key` = '?'", array(LYCHEE_TABLE_SETTINGS, $value, $key)); } elseif ($row===true) { - # Do not prepare $value because it has already been escaped or is a true statement - $query = Database::prepare(Database::get(), "UPDATE ? SET value = '$value' WHERE `key` = '?'", array(LYCHEE_TABLE_SETTINGS, $key)); + // Do not prepare $value because it has already been escaped or is a true statement + $query = Database::prepare(Database::get(), "UPDATE ? SET value = '$value' WHERE `key` = '?'", array(LYCHEE_TABLE_SETTINGS, $key)); } else { @@ -54,10 +54,10 @@ final class Settings { if ($oldPassword===self::get()['password']||self::get()['password']===crypt($oldPassword, self::get()['password'])) { - # Save username + // Save username if (self::setUsername($username)!==true) exit('Error: Updating username failed!'); - # Save password + // Save password if (self::setPassword($password)!==true) exit('Error: Updating password failed!'); return true; @@ -70,15 +70,15 @@ final class Settings { private static function setUsername($username) { - # Check dependencies + // Check dependencies Validator::required(isset($username), __METHOD__); - # Hash username + // Hash username $username = getHashedString($username); - # Execute query - # Do not prepare $username because it is hashed and save - # Preparing (escaping) the username would destroy the hash + // Execute query + // Do not prepare $username because it is hashed and save + // Preparing (escaping) the username would destroy the hash if (self::set('username', $username, true)===false) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; @@ -89,14 +89,14 @@ final class Settings { private static function setPassword($password) { - # Check dependencies + // Check dependencies Validator::required(isset($password), __METHOD__); - # Hash password + // Hash password $password = getHashedString($password); - # Do not prepare $password because it is hashed and save - # Preparing (escaping) the password would destroy the hash + // Do not prepare $password because it is hashed and save + // Preparing (escaping) the password would destroy the hash if (self::set('password', $password, true)===false) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; @@ -124,52 +124,34 @@ final class Settings { $sorting = 'ORDER BY '; - # Set row + // Set row switch ($type) { - case 'id': $sorting .= 'id'; - break; - - case 'title': $sorting .= 'title'; - break; - - case 'description': $sorting .= 'description'; - break; - - case 'public': $sorting .= 'public'; - break; - - case 'type': $sorting .= 'type'; - break; - - case 'star': $sorting .= 'star'; - break; - - case 'takestamp': $sorting .= 'takestamp'; - break; - - default: exit('Error: Unknown type for sorting!'); + case 'id': $sorting .= 'id'; break; + case 'title': $sorting .= 'title'; break; + case 'description': $sorting .= 'description'; break; + case 'public': $sorting .= 'public'; break; + case 'type': $sorting .= 'type'; break; + case 'star': $sorting .= 'star'; break; + case 'takestamp': $sorting .= 'takestamp'; break; + default: exit('Error: Unknown type for sorting!'); } $sorting .= ' '; - # Set order + // Set order switch ($order) { - case 'ASC': $sorting .= 'ASC'; - break; - - case 'DESC': $sorting .= 'DESC'; - break; - - default: exit('Error: Unknown order for sorting!'); + case 'ASC': $sorting .= 'ASC'; break; + case 'DESC': $sorting .= 'DESC'; break; + default: exit('Error: Unknown order for sorting!'); } - # Do not prepare $sorting because it is a true statement - # Preparing (escaping) the sorting would destroy it - # $sorting is save and can't contain user-input + // Do not prepare $sorting because it is a true statement + // Preparing (escaping) the sorting would destroy it + // $sorting is save and can't contain user-input if (self::set('sortingPhotos', $sorting, true)===false) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; @@ -182,43 +164,31 @@ final class Settings { $sorting = 'ORDER BY '; - # Set row + // Set row switch ($type) { - case 'id': $sorting .= 'id'; - break; - - case 'title': $sorting .= 'title'; - break; - - case 'description': $sorting .= 'description'; - break; - - case 'public': $sorting .= 'public'; - break; - - default: exit('Error: Unknown type for sorting!'); + case 'id': $sorting .= 'id'; break; + case 'title': $sorting .= 'title'; break; + case 'description': $sorting .= 'description'; break; + case 'public': $sorting .= 'public'; break; + default: exit('Error: Unknown type for sorting!'); } $sorting .= ' '; - # Set order + // Set order switch ($order) { - case 'ASC': $sorting .= 'ASC'; - break; - - case 'DESC': $sorting .= 'DESC'; - break; - - default: exit('Error: Unknown order for sorting!'); + case 'ASC': $sorting .= 'ASC'; break; + case 'DESC': $sorting .= 'DESC'; break; + default: exit('Error: Unknown order for sorting!'); } - # Do not prepare $sorting because it is a true statement - # Preparing (escaping) the sorting would destroy it - # $sorting is save and can't contain user-input + // Do not prepare $sorting because it is a true statement + // Preparing (escaping) the sorting would destroy it + // $sorting is save and can't contain user-input if (self::set('sortingAlbums', $sorting, true)===false) { Log::error(__METHOD__, __LINE__, Database::get()->error); return false; diff --git a/php/database/update_020700.php b/php/database/update_020700.php index c610054..292d9e6 100644 --- a/php/database/update_020700.php +++ b/php/database/update_020700.php @@ -1,43 +1,43 @@ query($query)) { - $query = Database::prepare($connection, "ALTER TABLE `?` ADD `medium` TINYINT(1) NOT NULL DEFAULT 0", array(LYCHEE_TABLE_PHOTOS)); - $result = $connection->query($query); + $query = Database::prepare($connection, "ALTER TABLE `?` ADD `medium` TINYINT(1) NOT NULL DEFAULT 0", array(LYCHEE_TABLE_PHOTOS)); + $result = $connection->query($query); if (!$result) { Log::error('update_020700', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } } -# Create medium folder +// Create medium folder if (is_dir(LYCHEE_UPLOADS_MEDIUM)===false) { - # Only create the folder when it is missing - if (@mkdir(LYCHEE_UPLOADS_MEDIUM)===false) + // Only create the folder when it is missing + if (@mkdir(LYCHEE_UPLOADS_MEDIUM)===false) { Log::error('update_020700', __LINE__, 'Could not create medium-folder'); + } } -# Add medium to settings -$query = Database::prepare($connection, "SELECT `key` FROM `?` WHERE `key` = 'medium' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); -$result = $connection->query($query); +// Add medium to settings +$query = Database::prepare($connection, "SELECT `key` FROM `?` WHERE `key` = 'medium' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); +$result = $connection->query($query); if ($result->num_rows===0) { - $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('medium', '1')", array(LYCHEE_TABLE_SETTINGS)); - $result = $connection->query($query); + $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('medium', '1')", array(LYCHEE_TABLE_SETTINGS)); + $result = $connection->query($query); if (!$result) { Log::error('update_020700', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } } -# Set version +// Set version if (Database::setVersion($connection, '020700')===false) return false; ?> \ No newline at end of file diff --git a/php/database/update_030000.php b/php/database/update_030000.php index 937f1d4..c5a5f2a 100644 --- a/php/database/update_030000.php +++ b/php/database/update_030000.php @@ -1,37 +1,36 @@ query($query); +// Remove login +// Login now saved as crypt without md5. Legacy code has been removed. +$query = Database::prepare($connection, "UPDATE `?` SET `value` = '' WHERE `key` = 'username' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); +$resetUsername = $connection->query($query); if (!$resetUsername) { Log::error('update_030000', __LINE__, 'Could not reset username (' . $connection->error . ')'); return false; } -$query = Database::prepare($connection, "UPDATE `?` SET `value` = '' WHERE `key` = 'password' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); -$resetPassword = $connection->query($query); +$query = Database::prepare($connection, "UPDATE `?` SET `value` = '' WHERE `key` = 'password' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); +$resetPassword = $connection->query($query); if (!$resetPassword) { Log::error('update_030000', __LINE__, 'Could not reset password (' . $connection->error . ')'); return false; } -# Make public albums private and reset password -# Password now saved as crypt without md5. Legacy code has been removed. -$query = Database::prepare($connection, "UPDATE `?` SET `public` = 0, `password` = NULL", array(LYCHEE_TABLE_ALBUMS)); -$resetPublic = $connection->query($query); +// Make public albums private and reset password +// Password now saved as crypt without md5. Legacy code has been removed. +$query = Database::prepare($connection, "UPDATE `?` SET `public` = 0, `password` = NULL", array(LYCHEE_TABLE_ALBUMS)); +$resetPublic = $connection->query($query); if (!$resetPublic) { Log::error('update_030000', __LINE__, 'Could not reset public albums (' . $connection->error . ')'); return false; } -# Set version +// Set version if (Database::setVersion($connection, '030000')===false) return false; ?> \ No newline at end of file diff --git a/php/database/update_030001.php b/php/database/update_030001.php index c13505c..2e3309c 100644 --- a/php/database/update_030001.php +++ b/php/database/update_030001.php @@ -1,62 +1,61 @@ query($query); +// Change length of photo title +$query = Database::prepare($connection, "ALTER TABLE `?` CHANGE `title` `title` VARCHAR( 100 ) NOT NULL DEFAULT ''", array(LYCHEE_TABLE_PHOTOS)); +$result = $connection->query($query); if (!$result) { Log::error('update_030001', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } -# Change length of album title -$query = Database::prepare($connection, "ALTER TABLE `?` CHANGE `title` `title` VARCHAR( 100 ) NOT NULL DEFAULT ''", array(LYCHEE_TABLE_ALBUMS)); -$result = $connection->query($query); +// Change length of album title +$query = Database::prepare($connection, "ALTER TABLE `?` CHANGE `title` `title` VARCHAR( 100 ) NOT NULL DEFAULT ''", array(LYCHEE_TABLE_ALBUMS)); +$result = $connection->query($query); if (!$result) { Log::error('update_030001', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } -# Add album sorting to settings -$query = Database::prepare($connection, "SELECT `key` FROM `?` WHERE `key` = 'sortingAlbums' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); -$result = $connection->query($query); +// Add album sorting to settings +$query = Database::prepare($connection, "SELECT `key` FROM `?` WHERE `key` = 'sortingAlbums' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); +$result = $connection->query($query); if ($result->num_rows===0) { - $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('sortingAlbums', 'ORDER BY id DESC')", array(LYCHEE_TABLE_SETTINGS)); - $result = $connection->query($query); + $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('sortingAlbums', 'ORDER BY id DESC')", array(LYCHEE_TABLE_SETTINGS)); + $result = $connection->query($query); if (!$result) { Log::error('update_030001', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } } -# Rename sorting to sortingPhotos -$query = Database::prepare($connection, "UPDATE ? SET `key` = 'sortingPhotos' WHERE `key` = 'sorting' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); -$result = $connection->query($query); +// Rename sorting to sortingPhotos +$query = Database::prepare($connection, "UPDATE ? SET `key` = 'sortingPhotos' WHERE `key` = 'sorting' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); +$result = $connection->query($query); if (!$result) { Log::error('update_030001', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } -# Add identifier to settings -$query = Database::prepare($connection, "SELECT `key` FROM `?` WHERE `key` = 'identifier' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); -$result = $connection->query($query); +// Add identifier to settings +$query = Database::prepare($connection, "SELECT `key` FROM `?` WHERE `key` = 'identifier' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); +$result = $connection->query($query); if ($result->num_rows===0) { - $identifier = md5(microtime(true)); - $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('identifier', '?')", array(LYCHEE_TABLE_SETTINGS, $identifier)); - $result = $connection->query($query); + $identifier = md5(microtime(true)); + $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('identifier', '?')", array(LYCHEE_TABLE_SETTINGS, $identifier)); + $result = $connection->query($query); if (!$result) { Log::error('update_030001', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } } -# Set version +// Set version if (Database::setVersion($connection, '030001')===false) return false; ?> \ No newline at end of file diff --git a/php/database/update_030003.php b/php/database/update_030003.php index dd09fe7..16b22b1 100644 --- a/php/database/update_030003.php +++ b/php/database/update_030003.php @@ -1,25 +1,24 @@ query($query); +// Add skipDuplicates to settings +$query = Database::prepare($connection, "SELECT `key` FROM `?` WHERE `key` = 'skipDuplicates' LIMIT 1", array(LYCHEE_TABLE_SETTINGS)); +$result = $connection->query($query); if ($result->num_rows===0) { - $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('skipDuplicates', '0')", array(LYCHEE_TABLE_SETTINGS)); - $result = $connection->query($query); + $query = Database::prepare($connection, "INSERT INTO `?` (`key`, `value`) VALUES ('skipDuplicates', '0')", array(LYCHEE_TABLE_SETTINGS)); + $result = $connection->query($query); if (!$result) { Log::error('update_030003', __LINE__, 'Could not update database (' . $connection->error . ')'); return false; } } -# Set version +// Set version if (Database::setVersion($connection, '030003')===false) return false; ?> \ No newline at end of file diff --git a/php/define.php b/php/define.php index cf35353..a215adc 100644 --- a/php/define.php +++ b/php/define.php @@ -1,14 +1,14 @@ getPublic('')===false) return false; - $query = Database::prepare(Database::get(), "SELECT title, description, url, medium FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photoID)); - $result = Database::get()->query($query); - $row = $result->fetch_object(); + $query = Database::prepare(Database::get(), "SELECT title, description, url, medium FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photoID)); + $result = Database::get()->query($query); + $row = $result->fetch_object(); if (!$result||!$row) return false; - if ($row->medium==='1') $dir = 'medium'; - else $dir = 'big'; + if ($row->medium==='1') $dir = 'medium'; + else $dir = 'big'; - $parseUrl = parse_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); - $url = $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['path'] . '?' . $parseUrl['query']; - $picture = $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['path'] . '/../uploads/' . $dir . '/' . $row->url; + $parseUrl = parse_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); + $url = $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['path'] . '?' . $parseUrl['query']; + $picture = $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['path'] . '/../uploads/' . $dir . '/' . $row->url; - $url = htmlentities($url); - $picture = htmlentities($picture); + $url = htmlentities($url); + $picture = htmlentities($picture); - $row->title = htmlentities($row->title); - $row->description = htmlentities($row->description); + $row->title = htmlentities($row->title); + $row->description = htmlentities($row->description); $return = ''; $return .= ''; diff --git a/php/helpers/getHashedString.php b/php/helpers/getHashedString.php index 1205586..3c5f890 100644 --- a/php/helpers/getHashedString.php +++ b/php/helpers/getHashedString.php @@ -2,28 +2,35 @@ function getHashedString($password) { - # Inspired by http://alias.io/2010/01/store-passwords-safely-with-php-and-mysql/ + // Inspired by http://alias.io/2010/01/store-passwords-safely-with-php-and-mysql/ - # A higher $cost is more secure but consumes more processing power + // A higher $cost is more secure but consumes more processing power $cost = 10; - # Create a random salt + // Create a random salt if (extension_loaded('openssl')) { + $salt = strtr(substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22), '+', '.'); + } elseif (extension_loaded('mcrypt')) { + $salt = strtr(substr(base64_encode(mcrypt_create_iv(17, MCRYPT_DEV_URANDOM)),0,22), '+', '.'); + } else { - $salt = ""; + + $salt = ''; + for ($i = 0; $i < 22; $i++) { $salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1); } + } - # Prefix information about the hash so PHP knows how to verify it later. - # "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter. + // Prefix information about the hash so PHP knows how to verify it later. + // "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter. $salt = sprintf("$2a$%02d$", $cost) . $salt; - # Hash the password with the salt + // Hash the password with the salt return crypt($password, $salt); } diff --git a/php/helpers/hasPermissions.php b/php/helpers/hasPermissions.php index f5f8bbd..c862436 100644 --- a/php/helpers/hasPermissions.php +++ b/php/helpers/hasPermissions.php @@ -4,8 +4,7 @@ function hasPermissions($path) { // Check if the given path is readable and writable // Both functions are also verifying that the path exists - if (is_readable($path)===true&& - is_writeable($path)===true) return true; + if (is_readable($path)===true&&is_writeable($path)===true) return true; return false; diff --git a/php/helpers/search.php b/php/helpers/search.php index 5786b83..f975577 100755 --- a/php/helpers/search.php +++ b/php/helpers/search.php @@ -2,21 +2,19 @@ function search($term) { - $return['albums'] = ''; - - # Initialize return var + // Initialize return var $return = array( - 'photos' => null, - 'albums' => null, - 'hash' => '' + 'photos' => null, + 'albums' => null, + 'hash' => '' ); - ### - # Photos - ### + /** + * Photos + */ - $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE title LIKE '%?%' OR description LIKE '%?%' OR tags LIKE '%?%'", array(LYCHEE_TABLE_PHOTOS, $term, $term, $term)); - $result = Database::get()->query($query); + $query = Database::prepare(Database::get(), "SELECT id, title, tags, public, star, album, thumbUrl, takestamp, url FROM ? WHERE title LIKE '%?%' OR description LIKE '%?%' OR tags LIKE '%?%'", array(LYCHEE_TABLE_PHOTOS, $term, $term, $term)); + $result = Database::get()->query($query); while($photo = $result->fetch_assoc()) { @@ -25,35 +23,35 @@ function search($term) { } - ### - # Albums - ### + /** + * Albums + */ - $query = Database::prepare(Database::get(), "SELECT id, title, public, sysstamp, password FROM ? WHERE title LIKE '%?%' OR description LIKE '%?%'", array(LYCHEE_TABLE_ALBUMS, $term, $term)); + $query = Database::prepare(Database::get(), "SELECT id, title, public, sysstamp, password FROM ? WHERE title LIKE '%?%' OR description LIKE '%?%'", array(LYCHEE_TABLE_ALBUMS, $term, $term)); $result = Database::get()->query($query); while($album = $result->fetch_assoc()) { - # Turn data from the database into a front-end friendly format + // Turn data from the database into a front-end friendly format $album = Album::prepareData($album); - # Thumbs - $query = Database::prepare(Database::get(), "SELECT thumbUrl FROM ? WHERE album = '?' " . Settings::get()['sortingPhotos'] . " LIMIT 0, 3", array(LYCHEE_TABLE_PHOTOS, $album['id'])); - $thumbs = Database::get()->query($query); + // Thumbs + $query = Database::prepare(Database::get(), "SELECT thumbUrl FROM ? WHERE album = '?' " . Settings::get()['sortingPhotos'] . " LIMIT 0, 3", array(LYCHEE_TABLE_PHOTOS, $album['id'])); + $thumbs = Database::get()->query($query); - # For each thumb + // For each thumb $k = 0; while ($thumb = $thumbs->fetch_object()) { $album['thumbs'][$k] = LYCHEE_URL_UPLOADS_THUMB . $thumb->thumbUrl; $k++; } - # Add to return + // Add to return $return['albums'][$album['id']] = $album; } - # Hash + // Hash $return['hash'] = md5(json_encode($return)); return $return; diff --git a/php/index.php b/php/index.php index 2e72991..04b9858 100755 --- a/php/index.php +++ b/php/index.php @@ -1,10 +1,9 @@