diff --git a/.gitignore b/.gitignore index deb80874..b5882790 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ /public/build /logs Homestead.yaml +/public/storage .env .vagrant _ide_helper.php diff --git a/app/AlbumDownloader.php b/app/AlbumDownloader.php index 7ade8e0a..c1829712 100644 --- a/app/AlbumDownloader.php +++ b/app/AlbumDownloader.php @@ -45,7 +45,7 @@ class AlbumDownloader public function download() { // Check whether the format is lossless yet not all master files are lossless - $isLosslessFormatWithLossyTracks = in_array($this->_format, Track::$LosslessFormats) + $isLosslessFormatWithLossyTracks = in_array($this->_format, Track::$LosslessFormats) && !$this->_album->hasLosslessTracksOnly() && $this->_album->hasLosslessTracks(); @@ -77,11 +77,15 @@ class AlbumDownloader if ($isLosslessFormatWithLossyTracks && $track->isMasterLossy()) { $masterFormatName = $track->getMasterFormatName(); - $zip->addLargeFile($track->getFileFor($masterFormatName), - $directory . $track->getDownloadFilenameFor($masterFormatName)); + $zip->addLargeFile( + $track->getFileFor($masterFormatName), + $directory . $track->getDownloadFilenameFor($masterFormatName) + ); } else { - $zip->addLargeFile($track->getFileFor($this->_format), - $directory . $track->getDownloadFilenameFor($this->_format)); + $zip->addLargeFile( + $track->getFileFor($this->_format), + $directory . $track->getDownloadFilenameFor($this->_format) + ); } $notes .= diff --git a/app/Commands/CommandBase.php b/app/Commands/CommandBase.php index 3cb09b4c..f3d67d35 100644 --- a/app/Commands/CommandBase.php +++ b/app/Commands/CommandBase.php @@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Commands; abstract class CommandBase { - private $_listeners = array(); + private $_listeners = []; public function listen($listener) { @@ -47,5 +47,5 @@ abstract class CommandBase /** * @return CommandResponse */ - public abstract function execute(); + abstract public function execute(); } diff --git a/app/Commands/CommandResponse.php b/app/Commands/CommandResponse.php index 7af02cd0..72e25ae5 100644 --- a/app/Commands/CommandResponse.php +++ b/app/Commands/CommandResponse.php @@ -44,7 +44,6 @@ class CommandResponse if (is_array($validatorOrMessages)) { $response->_messages = $validatorOrMessages; $response->_validator = null; - } else { $response->_validator = $validatorOrMessages; } @@ -102,7 +101,6 @@ class CommandResponse { if ($this->_validator !== null) { return $this->_validator->messages()->getMessages(); - } else { return $this->_messages; } diff --git a/app/Commands/CreateCommentCommand.php b/app/Commands/CreateCommentCommand.php index 70696d9f..d5892007 100644 --- a/app/Commands/CreateCommentCommand.php +++ b/app/Commands/CreateCommentCommand.php @@ -100,16 +100,12 @@ class CreateCommentCommand extends CommandBase // Recount the track's comments, if this is a track comment if ($this->_type === 'track') { $entity = Track::find($this->_id); - } elseif ($this->_type === 'album') { $entity = Album::find($this->_id); - } elseif ($this->_type === 'playlist') { $entity = Playlist::find($this->_id); - } elseif ($this->_type === 'user') { $entity = User::find($this->_id); - } else { App::abort(400, 'This comment is being added to an invalid entity!'); } diff --git a/app/Commands/DeleteGenreCommand.php b/app/Commands/DeleteGenreCommand.php index 0ce27885..22023993 100644 --- a/app/Commands/DeleteGenreCommand.php +++ b/app/Commands/DeleteGenreCommand.php @@ -35,7 +35,8 @@ class DeleteGenreCommand extends CommandBase private $_genreToDelete; private $_destinationGenre; - public function __construct($genreId, $destinationGenreId) { + public function __construct($genreId, $destinationGenreId) + { $this->_genreToDelete = Genre::find($genreId); $this->_destinationGenre = Genre::find($destinationGenreId); } @@ -43,7 +44,8 @@ class DeleteGenreCommand extends CommandBase /** * @return bool */ - public function authorize() { + public function authorize() + { return Gate::allows('delete', $this->_genreToDelete); } @@ -51,7 +53,8 @@ class DeleteGenreCommand extends CommandBase * @throws \Exception * @return CommandResponse */ - public function execute() { + public function execute() + { $rules = [ 'genre_to_delete' => 'required', 'destination_genre' => 'required', diff --git a/app/Commands/DeleteShowSongCommand.php b/app/Commands/DeleteShowSongCommand.php index 7cab2ef5..36ef06c6 100644 --- a/app/Commands/DeleteShowSongCommand.php +++ b/app/Commands/DeleteShowSongCommand.php @@ -35,7 +35,8 @@ class DeleteShowSongCommand extends CommandBase private $_songToDelete; private $_destinationSong; - public function __construct($songId, $destinationSongId) { + public function __construct($songId, $destinationSongId) + { $this->_songToDelete = ShowSong::find($songId); $this->_destinationSong = ShowSong::find($destinationSongId); } @@ -43,7 +44,8 @@ class DeleteShowSongCommand extends CommandBase /** * @return bool */ - public function authorize() { + public function authorize() + { return Gate::allows('delete', $this->_destinationSong); } @@ -51,7 +53,8 @@ class DeleteShowSongCommand extends CommandBase * @throws \Exception * @return CommandResponse */ - public function execute() { + public function execute() + { $rules = [ 'song_to_delete' => 'required', 'destination_song' => 'required', diff --git a/app/Commands/EditAlbumCommand.php b/app/Commands/EditAlbumCommand.php index 42bbcfe0..af5518c3 100644 --- a/app/Commands/EditAlbumCommand.php +++ b/app/Commands/EditAlbumCommand.php @@ -100,7 +100,7 @@ class EditAlbumCommand extends CommandBase $newid = User::where('username', $this->_input['username'])->first()->id; if ($this->_album->user_id != $newid) { - $this->_album->user_id = $newid; + $this->_album->user_id = $newid; } } diff --git a/app/Commands/EditTrackCommand.php b/app/Commands/EditTrackCommand.php index 796cc444..27c1fcf7 100644 --- a/app/Commands/EditTrackCommand.php +++ b/app/Commands/EditTrackCommand.php @@ -159,8 +159,8 @@ class EditTrackCommand extends CommandBase $newid = User::where('username', $this->_input['username'])->first()->id; if ($track->user_id != $newid) { - $oldid = $track->user_id; - $track->user_id = $newid; + $oldid = $track->user_id; + $track->user_id = $newid; } } diff --git a/app/Commands/GenerateTrackFilesCommand.php b/app/Commands/GenerateTrackFilesCommand.php index b7a3eb8c..228dac75 100644 --- a/app/Commands/GenerateTrackFilesCommand.php +++ b/app/Commands/GenerateTrackFilesCommand.php @@ -84,13 +84,10 @@ class GenerateTrackFilesCommand extends CommandBase if ($isLossyUpload) { if ($codecString === 'mp3') { $masterFormat = 'MP3'; - } else if (Str::startsWith($codecString, 'aac')) { $masterFormat = 'AAC'; - } else if ($codecString === 'vorbis') { $masterFormat = 'OGG Vorbis'; - } else { $this->track->delete(); return CommandResponse::fail(['track' => "The track does not contain audio in a known lossy format. The format read from the file is: {$codecString}"]); @@ -156,7 +153,6 @@ class GenerateTrackFilesCommand extends CommandBase } $this->dispatch(new EncodeTrackFile($trackFile, false, false, $this->isForUpload, $this->isReplacingTrack)); } - } catch (InvalidEncodeOptionsException $e) { // Only delete the track if the track is not being replaced if ($this->isReplacingTrack) { @@ -167,7 +163,6 @@ class GenerateTrackFilesCommand extends CommandBase } return CommandResponse::fail(['track' => [$e->getMessage()]]); } - } catch (\Exception $e) { if ($this->isReplacingTrack) { $this->track->version_upload_status = Track::STATUS_ERROR; diff --git a/app/Commands/MergeAccountsCommand.php b/app/Commands/MergeAccountsCommand.php index d882fd0d..6bde0516 100644 --- a/app/Commands/MergeAccountsCommand.php +++ b/app/Commands/MergeAccountsCommand.php @@ -51,7 +51,7 @@ class MergeAccountsCommand extends CommandBase */ public function execute() { - DB::transaction(function() { + DB::transaction(function () { $accountIds = [$this->sourceAccount->id]; foreach (Album::whereIn('user_id', $accountIds)->get() as $album) { diff --git a/app/Commands/ParseTrackTagsCommand.php b/app/Commands/ParseTrackTagsCommand.php index b5d7613f..f0577a74 100644 --- a/app/Commands/ParseTrackTagsCommand.php +++ b/app/Commands/ParseTrackTagsCommand.php @@ -35,7 +35,6 @@ use Poniverse\Ponyfm\Models\User; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; - class ParseTrackTagsCommand extends CommandBase { private $track; @@ -107,7 +106,8 @@ class ParseTrackTagsCommand extends CommandBase * @param Track * @return Track */ - private function unsetNullVariables($track) { + private function unsetNullVariables($track) + { $vars = $track->getAttributes(); foreach ($vars as $key => $value) { @@ -125,7 +125,8 @@ class ParseTrackTagsCommand extends CommandBase * @param string $genreName * @return int */ - protected function getGenreId(string $genreName) { + protected function getGenreId(string $genreName) + { $existingGenre = Genre::withTrashed() ->where('name', $genreName)->first(); @@ -165,7 +166,8 @@ class ParseTrackTagsCommand extends CommandBase * @param integer|null $coverId * @return int|null */ - protected function getAlbumId(int $artistId, $albumName, $coverId = null) { + protected function getAlbumId(int $artistId, $albumName, $coverId = null) + { if (null !== $albumName) { $album = Album::firstOrNew([ 'user_id' => $artistId, @@ -194,7 +196,8 @@ class ParseTrackTagsCommand extends CommandBase * @return array the "processed" and raw tags extracted from the file * @throws \Exception */ - protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec) { + protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec) + { //========================================================================================================== // Extract the original tags. //========================================================================================================== @@ -208,16 +211,12 @@ class ParseTrackTagsCommand extends CommandBase if ($audioCodec === 'mp3') { list($parsedTags, $rawTags) = $this->getId3Tags($allTags); - } elseif (Str::startsWith($audioCodec, ['aac', 'alac'])) { list($parsedTags, $rawTags) = $this->getAtomTags($allTags); - } elseif (in_array($audioCodec, ['vorbis', 'flac'])) { list($parsedTags, $rawTags) = $this->getVorbisTags($allTags); - } elseif (Str::startsWith($audioCodec, ['pcm', 'adpcm'])) { list($parsedTags, $rawTags) = $this->getAtomTags($allTags); - } else { // Assume the file is untagged if it's in an unknown format. $parsedTags = [ @@ -255,7 +254,6 @@ class ParseTrackTagsCommand extends CommandBase if ($genreName !== null) { $parsedTags['genre_id'] = $this->getGenreId($genreName); - } else { $parsedTags['genre_id'] = null; } @@ -270,10 +268,8 @@ class ParseTrackTagsCommand extends CommandBase if ($image['image_mime'] === 'image/png') { $extension = 'png'; - } elseif ($image['image_mime'] === 'image/jpeg') { $extension = 'jpg'; - } else { throw new BadRequestHttpException('Unknown cover format embedded in the track file!'); } @@ -289,7 +285,6 @@ class ParseTrackTagsCommand extends CommandBase $cover = Image::upload($imageFile, $artist); $coverId = $cover->id; - } else { // no cover art was found - carry on } @@ -318,7 +313,8 @@ class ParseTrackTagsCommand extends CommandBase * @param array $rawTags * @return array */ - protected function getId3Tags($rawTags) { + protected function getId3Tags($rawTags) + { if (array_key_exists('tags', $rawTags) && array_key_exists('id3v2', $rawTags['tags'])) { $tags = $rawTags['tags']['id3v2']; } elseif (array_key_exists('tags', $rawTags) && array_key_exists('id3v1', $rawTags['tags'])) { @@ -364,7 +360,8 @@ class ParseTrackTagsCommand extends CommandBase * @param array $rawTags * @return array */ - protected function getAtomTags($rawTags) { + protected function getAtomTags($rawTags) + { if (array_key_exists('tags', $rawTags) && array_key_exists('quicktime', $rawTags['tags'])) { $tags = $rawTags['tags']['quicktime']; } else { @@ -379,7 +376,6 @@ class ParseTrackTagsCommand extends CommandBase if (isset($tags['release_date'])) { $releaseDate = $this->parseDateString($tags['release_date'][0]); - } elseif (isset($tags['creation_date'])) { $releaseDate = $this->parseDateString($tags['creation_date'][0]); } else { @@ -408,7 +404,8 @@ class ParseTrackTagsCommand extends CommandBase * @param array $rawTags * @return array */ - protected function getVorbisTags($rawTags) { + protected function getVorbisTags($rawTags) + { if (array_key_exists('tags', $rawTags) && array_key_exists('vorbiscomment', $rawTags['tags'])) { $tags = $rawTags['tags']['vorbiscomment']; } else { @@ -452,7 +449,8 @@ class ParseTrackTagsCommand extends CommandBase * @param string $dateString * @return null|Carbon */ - protected function parseDateString(string $dateString) { + protected function parseDateString(string $dateString) + { switch (Str::length($dateString)) { // YYYY case 4: @@ -475,7 +473,6 @@ class ParseTrackTagsCommand extends CommandBase // If not, give up. try { return Carbon::createFromFormat(Carbon::ISO8601, $dateString); - } catch (\InvalidArgumentException $e) { return null; } diff --git a/app/Commands/SaveAccountSettingsCommand.php b/app/Commands/SaveAccountSettingsCommand.php index 8207900b..eb2d8afa 100644 --- a/app/Commands/SaveAccountSettingsCommand.php +++ b/app/Commands/SaveAccountSettingsCommand.php @@ -94,10 +94,8 @@ class SaveAccountSettingsCommand extends CommandBase if (isset($this->_input['avatar_id'])) { $this->_user->avatar_id = $this->_input['avatar_id']; - } elseif (isset($this->_input['avatar'])) { $this->_user->avatar_id = Image::upload($this->_input['avatar'], $this->_user)->id; - } else { $this->_user->avatar_id = null; } diff --git a/app/Commands/UploadTrackCommand.php b/app/Commands/UploadTrackCommand.php index a4ea3340..2bbd221b 100644 --- a/app/Commands/UploadTrackCommand.php +++ b/app/Commands/UploadTrackCommand.php @@ -25,7 +25,7 @@ use Carbon\Carbon; use Config; use Gate; use Illuminate\Foundation\Bus\DispatchesJobs; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\User; use Validator; @@ -73,7 +73,7 @@ class UploadTrackCommand extends CommandBase int $version = 1, $track = null ) { - $userSlug = Input::get('user_slug', null); + $userSlug = Request::get('user_slug', null); $this->_artist = $userSlug !== null ? User::where('slug', $userSlug)->first() @@ -94,9 +94,9 @@ class UploadTrackCommand extends CommandBase */ public function execute() { - $trackFile = Input::file('track', null); + $trackFile = Request::file('track', null); if (!$this->_isReplacingTrack) { - $coverFile = Input::file('cover', null); + $coverFile = Request::file('cover', null); } if (null === $trackFile) { @@ -114,7 +114,7 @@ class UploadTrackCommand extends CommandBase $this->_track->user_id = $this->_artist->id; // The title set here is a placeholder; it'll be replaced by ParseTrackTagsCommand // if the file contains a title tag. - $this->_track->title = Input::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME)); + $this->_track->title = Request::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME)); // The duration/version of the track cannot be changed until the encoding is successful $this->_track->duration = $audio->getDuration(); $this->_track->current_version = $this->_version; @@ -131,7 +131,7 @@ class UploadTrackCommand extends CommandBase } $trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $this->_track->id . 'v' . $this->_version); - $input = Input::all(); + $input = Request::all(); $input['track'] = $trackFile; if (!$this->_isReplacingTrack) { $input['cover'] = $coverFile; @@ -180,7 +180,7 @@ class UploadTrackCommand extends CommandBase if (!$this->_isReplacingTrack) { // If json_decode() isn't called here, Laravel will surround the JSON // string with quotes when storing it in the database, which breaks things. - $this->_track->metadata = json_decode(Input::get('metadata', null)); + $this->_track->metadata = json_decode(Request::get('metadata', null)); } $autoPublish = (bool)($input['auto_publish'] ?? $this->_autoPublishByDefault); $this->_track->source = $this->_customTrackSource ?? 'direct_upload'; diff --git a/app/Console/Commands/ClassifyMLPMA.php b/app/Console/Commands/ClassifyMLPMA.php index 03d453d2..d6c9ef2b 100644 --- a/app/Console/Commands/ClassifyMLPMA.php +++ b/app/Console/Commands/ClassifyMLPMA.php @@ -108,8 +108,12 @@ class ClassifyMLPMA extends Command if (Str::contains(Str::lower($track->filename), 'ingram')) { $this->info('This is an official song remix!'); - list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, true, - $parsedTags); + list($trackType, $linkedSongIds) = $this->classifyTrack( + $track->filename, + $officialSongs, + true, + $parsedTags + ); // If it has "remix" in the name, it's definitely a remix. @@ -117,13 +121,21 @@ class ClassifyMLPMA extends Command if (Str::contains(Str::lower($sanitizedTrackTitle), 'remix')) { $this->info('This is some kind of remix!'); - list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false, - $parsedTags); + list($trackType, $linkedSongIds) = $this->classifyTrack( + $track->filename, + $officialSongs, + false, + $parsedTags + ); // No idea what this is. Have the pony at the terminal figure it out! } else { - list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false, - $parsedTags); + list($trackType, $linkedSongIds) = $this->classifyTrack( + $track->filename, + $officialSongs, + false, + $parsedTags + ); } } @@ -144,7 +156,6 @@ class ClassifyMLPMA extends Command echo PHP_EOL; } - } /** @@ -169,19 +180,15 @@ class ClassifyMLPMA extends Command if ($isRemixOfOfficialTrack && sizeof($officialSongs) === 1) { $linkedSongIds = [$officialSongs[0]->id]; - } else { if ($isRemixOfOfficialTrack && sizeof($officialSongs) > 1) { $this->question('Multiple official songs matched! Please enter the ID of the correct one.'); - } else { if (sizeof($officialSongs) > 0) { $this->question('This looks like a remix of an official song!'); $this->question('Press "r" if the match above is right!'); - } else { $this->question('Exactly what kind of track is this?'); - } } $this->question('If this is a medley, multiple song ID\'s can be separated by commas. '); @@ -228,7 +235,7 @@ class ClassifyMLPMA extends Command default: $trackTypeId = TrackType::OFFICIAL_TRACK_REMIX; $linkedSongIds = explode(',', $input); - $linkedSongIds = array_map(function($item) { + $linkedSongIds = array_map(function ($item) { return (int) $item; }, $linkedSongIds); } diff --git a/app/Console/Commands/ClearTrackCache.php b/app/Console/Commands/ClearTrackCache.php index 50cde6f0..d68d8685 100644 --- a/app/Console/Commands/ClearTrackCache.php +++ b/app/Console/Commands/ClearTrackCache.php @@ -76,13 +76,10 @@ class ClearTrackCache extends Command if (count($trackFiles) === 0) { $this->info('No tracks found. Exiting.'); } else { - if ($this->option('force') || $this->confirm(count($trackFiles) . ' cacheable track files found. Proceed to delete their files if they exist? [y|N]', false)) { - $count = 0; foreach ($trackFiles as $trackFile) { - // Set expiration to null (so can be re-cached upon request) $trackFile->expires_at = null; $trackFile->update(); @@ -94,14 +91,11 @@ class ClearTrackCache extends Command $this->info('Deleted ' . $trackFile->getFile()); } - } $this->info($count . ' files deleted. Deletion complete. Exiting.'); } else { $this->info('Deletion cancelled. Exiting.'); } - } } - } diff --git a/app/Console/Commands/FixMLPMAImages.php b/app/Console/Commands/FixMLPMAImages.php index b21bf5be..b354e800 100644 --- a/app/Console/Commands/FixMLPMAImages.php +++ b/app/Console/Commands/FixMLPMAImages.php @@ -144,7 +144,6 @@ class FixMLPMAImages extends Command $imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']); $cover = Image::upload($imageFile, $artistId, true); $coverId = $cover->id; - } else { $this->comment('No cover art found!'); } diff --git a/app/Console/Commands/MigrateOldData.php b/app/Console/Commands/MigrateOldData.php index c0830d1e..864e0365 100644 --- a/app/Console/Commands/MigrateOldData.php +++ b/app/Console/Commands/MigrateOldData.php @@ -101,8 +101,10 @@ class MigrateOldData extends Command if (!$user->uses_gravatar) { try { $coverFile = $this->getIdDirectory('users', $user->id).'/'.$user->id.'_.png'; - $coverId = Image::upload(new UploadedFile($coverFile, - $user->id.'_.png'), $user->id)->id; + $coverId = Image::upload(new UploadedFile( + $coverFile, + $user->id.'_.png' + ), $user->id)->id; DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]); } catch (\Exception $e) { $this->error('Could copy user avatar '.$user->id.' because '.$e->getMessage()); @@ -176,10 +178,14 @@ class MigrateOldData extends Command $coverId = null; if ($track->cover) { try { - $coverFile = $this->getIdDirectory('tracks', - $track->id).'/'.$track->id.'_'.$track->cover.'.png'; - $coverId = Image::upload(new UploadedFile($coverFile, - $track->id.'_'.$track->cover.'.png'), $track->user_id)->id; + $coverFile = $this->getIdDirectory( + 'tracks', + $track->id + ).'/'.$track->id.'_'.$track->cover.'.png'; + $coverId = Image::upload(new UploadedFile( + $coverFile, + $track->id.'_'.$track->cover.'.png' + ), $track->user_id)->id; } catch (\Exception $e) { $this->error('Could copy track cover '.$track->id.' because '.$e->getMessage()); } @@ -396,5 +402,4 @@ class MigrateOldData extends Command return \Config::get('ponyfm.files_directory').'/'.$type.'/'.$dir; } - } diff --git a/app/Console/Commands/PoniverseApiSetup.php b/app/Console/Commands/PoniverseApiSetup.php index 4144ca5f..7ead9085 100644 --- a/app/Console/Commands/PoniverseApiSetup.php +++ b/app/Console/Commands/PoniverseApiSetup.php @@ -76,12 +76,10 @@ class PoniverseApiSetup extends Command 'auth' => [$username, $password], 'query' => ['app' => 'Pony.fm'] ]); - } catch (ClientException $e) { if ($e->getResponse()->getStatusCode() === 401) { $this->error('Incorrect username or password! Please try again.'); exit(); - } else { var_dump($e->getResponse()->getBody()); throw $e; @@ -100,16 +98,20 @@ class PoniverseApiSetup extends Command } - protected function setEnvironmentVariable($key, $oldValue, $newValue) { + protected function setEnvironmentVariable($key, $oldValue, $newValue) + { $path = base_path('.env'); // Detect the specific "null" value. - if ($oldValue === null) + if ($oldValue === null) { $oldValue = 'null'; + } if (file_exists($path)) { file_put_contents($path, str_replace( - "$key=".$oldValue, "$key=".$newValue, file_get_contents($path) + "$key=".$oldValue, + "$key=".$newValue, + file_get_contents($path) )); } else { $this->error('Please run `vagrant up`!'); diff --git a/app/Console/Commands/RebuildArtists.php b/app/Console/Commands/RebuildArtists.php index 7a2b047b..8a555535 100644 --- a/app/Console/Commands/RebuildArtists.php +++ b/app/Console/Commands/RebuildArtists.php @@ -59,7 +59,7 @@ class RebuildArtists extends Command $bar = $this->output->createProgressBar($numberOfUsers); - foreach(User::with(['tracks' => function($query) { + foreach (User::with(['tracks' => function ($query) { $query->published()->listed(); }])->get() as $user) { $bar->advance(); diff --git a/app/Console/Commands/RebuildFilesizes.php b/app/Console/Commands/RebuildFilesizes.php index bd793d7a..82acf3f7 100644 --- a/app/Console/Commands/RebuildFilesizes.php +++ b/app/Console/Commands/RebuildFilesizes.php @@ -59,11 +59,12 @@ class RebuildFilesizes extends Command { $this->info('This will only rebuild the cache for track files which exist on disk; non-existent files will be skipped.'); - if ($this->option('force') || $this->confirm('Are you sure you want to rebuild the filesize cache? [y|N]', - false) + if ($this->option('force') || $this->confirm( + 'Are you sure you want to rebuild the filesize cache? [y|N]', + false + ) ) { - - TrackFile::chunk(200, function($trackFiles) { + TrackFile::chunk(200, function ($trackFiles) { $this->info('========== Start Chunk =========='); @@ -79,11 +80,9 @@ class RebuildFilesizes extends Command } $this->info('=========== End Chunk ==========='); - }); $this->info('Rebuild complete. Exiting.'); - } else { $this->info('Rebuild cancelled. Exiting.'); } diff --git a/app/Console/Commands/RebuildSearchIndex.php b/app/Console/Commands/RebuildSearchIndex.php index 6e34fd4d..550ac0d6 100644 --- a/app/Console/Commands/RebuildSearchIndex.php +++ b/app/Console/Commands/RebuildSearchIndex.php @@ -66,7 +66,7 @@ class RebuildSearchIndex extends Command $trackProgress = $this->output->createProgressBar($totalTracks); $this->info("Processing tracks..."); - Track::withTrashed()->chunk(200, function(Collection $tracks) use ($trackProgress) { + Track::withTrashed()->chunk(200, function (Collection $tracks) use ($trackProgress) { foreach ($tracks as $track) { /** @var Track $track */ $trackProgress->advance(); @@ -79,7 +79,7 @@ class RebuildSearchIndex extends Command $albumProgress = $this->output->createProgressBar($totalAlbums); $this->info("Processing albums..."); - Album::withTrashed()->chunk(200, function(Collection $albums) use ($albumProgress) { + Album::withTrashed()->chunk(200, function (Collection $albums) use ($albumProgress) { foreach ($albums as $album) { /** @var Album $album */ $albumProgress->advance(); @@ -92,7 +92,7 @@ class RebuildSearchIndex extends Command $playlistProgress = $this->output->createProgressBar($totalPlaylists); $this->info("Processing playlists..."); - Playlist::withTrashed()->chunk(200, function(Collection $playlists) use ($playlistProgress) { + Playlist::withTrashed()->chunk(200, function (Collection $playlists) use ($playlistProgress) { foreach ($playlists as $playlist) { /** @var Playlist $playlist */ $playlistProgress->advance(); @@ -105,7 +105,7 @@ class RebuildSearchIndex extends Command $userProgress = $this->output->createProgressBar($totalUsers); $this->info("Processing users..."); - User::chunk(200, function(Collection $users) use ($userProgress) { + User::chunk(200, function (Collection $users) use ($userProgress) { foreach ($users as $user) { /** @var User $user */ $userProgress->advance(); diff --git a/app/Console/Commands/RebuildTags.php b/app/Console/Commands/RebuildTags.php index 366e12a5..a87a703d 100644 --- a/app/Console/Commands/RebuildTags.php +++ b/app/Console/Commands/RebuildTags.php @@ -59,7 +59,6 @@ class RebuildTags extends Command if ($this->argument('trackId')) { $track = Track::findOrFail($this->argument('trackId')); $tracks = [$track]; - } else { $tracks = Track::whereNotNull('published_at')->withTrashed()->orderBy('id', 'asc')->get(); } @@ -69,7 +68,7 @@ class RebuildTags extends Command $this->info("Updating tags for ${numberOfTracks} tracks..."); $bar = $this->output->createProgressBar($numberOfTracks); - foreach($tracks as $track) { + foreach ($tracks as $track) { /** @var $track Track */ $track->updateTags(); $bar->advance(); diff --git a/app/Console/Commands/RebuildTrack.php b/app/Console/Commands/RebuildTrack.php index a849df74..820bcd3b 100644 --- a/app/Console/Commands/RebuildTrack.php +++ b/app/Console/Commands/RebuildTrack.php @@ -66,7 +66,7 @@ class RebuildTrack extends Command $track = Track::with('trackFiles')->withTrashed()->find((int) $this->argument('trackId')); $this->printTrackInfo($track); - if($this->option('upload')) { + if ($this->option('upload')) { // The track would've been deleted if its original upload failed. // It should be restored so the user can publish the track! $track->restore(); @@ -81,7 +81,6 @@ class RebuildTrack extends Command $this->error("Something went wrong!"); print_r($result->getMessages()); } - } else { $this->info("Re-encoding this track's files - there should be a line of output for each format!"); @@ -94,7 +93,8 @@ class RebuildTrack extends Command } } - private function printTrackInfo(Track $track) { + private function printTrackInfo(Track $track) + { $this->comment("Track info:"); $this->comment(" Title: {$track->title}"); $this->comment(" Uploaded at: {$track->created_at}"); diff --git a/app/Console/Commands/RebuildTrackCache.php b/app/Console/Commands/RebuildTrackCache.php index de8fd4c1..0466228f 100644 --- a/app/Console/Commands/RebuildTrackCache.php +++ b/app/Console/Commands/RebuildTrackCache.php @@ -67,10 +67,11 @@ class RebuildTrackCache extends Command $this->info('If this is your first time running this command, it is *highly* recommended that you ensure the file sizes for all track files have been populated.'); $this->info('***'); - if ($this->option('force') || $this->confirm('Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?', - false) + if ($this->option('force') || $this->confirm( + 'Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?', + false + ) ) { - //========================================================================================================== // Delete previously cached track files //========================================================================================================== @@ -83,7 +84,7 @@ class RebuildTrackCache extends Command // Chunk track files which are cacheable and NOT master TrackFile::where('is_cacheable', true) ->where('is_master', false) - ->chunk(200, function($trackFiles) use (&$count) { + ->chunk(200, function ($trackFiles) use (&$count) { // Delete chunked track files foreach ($trackFiles as $trackFile) { // Clear expiration so will be re-cached on next request @@ -115,7 +116,7 @@ class RebuildTrackCache extends Command TrackFile::where('is_cacheable', false) ->whereIn('format', Track::$CacheableFormats) ->where('is_master', false) - ->chunk(200, function($trackFiles) use (&$trackFileCount, &$formats) { + ->chunk(200, function ($trackFiles) use (&$trackFileCount, &$formats) { $this->output->newLine(1); $this->info('---------- Start Chunk ----------'); @@ -150,7 +151,7 @@ class RebuildTrackCache extends Command // Chunk track files which are NOT meant to be cacheable, but currently cacheable TrackFile::where('is_cacheable', true) ->whereNotIn('format', Track::$CacheableFormats) - ->chunk(200, function($trackFiles) use (&$trackFileCount, &$formats) { + ->chunk(200, function ($trackFiles) use (&$trackFileCount, &$formats) { $this->output->newLine(1); $this->info('---------- Start Chunk ----------'); @@ -188,7 +189,7 @@ class RebuildTrackCache extends Command // Find track files which are cacheable and NOT master TrackFile::whereIn('format', Track::$CacheableFormats) ->where('is_master', false) - ->chunk(200, function($trackFiles) use (&$count, &$trackFileCount) { + ->chunk(200, function ($trackFiles) use (&$count, &$trackFileCount) { $this->output->newLine(1); $this->info('---------- Start Chunk ----------'); @@ -223,36 +224,35 @@ class RebuildTrackCache extends Command // Chunk non-cacheable track files TrackFile::where('is_cacheable', false) ->where('is_master', false) - ->chunk(200, function($trackFiles) use (&$count) { - $this->output->newLine(1); - $this->info('---------- Start Chunk ----------'); + ->chunk(200, function ($trackFiles) use (&$count) { + $this->output->newLine(1); + $this->info('---------- Start Chunk ----------'); // Record the track files which do not exist (i.e., have not been encoded yet) - $emptyTrackFiles = []; + $emptyTrackFiles = []; - foreach ($trackFiles as $trackFile) { - if (!File::exists($trackFile->getFile())) { - $count++; - $emptyTrackFiles[] = $trackFile; + foreach ($trackFiles as $trackFile) { + if (!File::exists($trackFile->getFile())) { + $count++; + $emptyTrackFiles[] = $trackFile; + } } - } // Encode recorded track files - foreach ($emptyTrackFiles as $emptyTrackFile) { - $this->info("Started encoding track file ID {$emptyTrackFile->id}"); - $this->dispatch(new EncodeTrackFile($emptyTrackFile, false)); - } + foreach ($emptyTrackFiles as $emptyTrackFile) { + $this->info("Started encoding track file ID {$emptyTrackFile->id}"); + $this->dispatch(new EncodeTrackFile($emptyTrackFile, false)); + } - $this->info('----------- End Chunk -----------'); - $this->output->newLine(1); - }); + $this->info('----------- End Chunk -----------'); + $this->output->newLine(1); + }); $this->info($count.' track files encoded.'); $this->output->newLine(1); $this->info('Rebuild complete. Exiting.'); - } else { $this->info('Rebuild cancelled. Exiting.'); } diff --git a/app/Console/Commands/VersionFiles.php b/app/Console/Commands/VersionFiles.php index 0489263f..dbc22b46 100644 --- a/app/Console/Commands/VersionFiles.php +++ b/app/Console/Commands/VersionFiles.php @@ -61,7 +61,6 @@ class VersionFiles extends Command $this->info('This will only version track files which exist on disk; non-existent files will be skipped.'); if ($this->option('force') || $this->confirm('Are you sure you want to rename all unversioned track files? [y|N]', false)) { - TrackFile::chunk(200, function ($trackFiles) { $this->info('========== Start Chunk =========='); @@ -81,15 +80,12 @@ class VersionFiles extends Command } else { $this->error('ID ' . $trackFile->id . ' was unable to be renamed'); } - } $this->info('=========== End Chunk ==========='); - }); $this->info('Rebuild complete. Exiting.'); - } else { $this->info('Rebuild cancelled. Exiting.'); } diff --git a/app/Contracts/Commentable.php b/app/Contracts/Commentable.php index 410e7ad2..ebfe391f 100644 --- a/app/Contracts/Commentable.php +++ b/app/Contracts/Commentable.php @@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany; * * @package Poniverse\Ponyfm\Contracts */ -interface Commentable extends GeneratesNotifications { +interface Commentable extends GeneratesNotifications +{ /** * This method returns an Eloquent relation to the entity's comments. * diff --git a/app/Contracts/Favouritable.php b/app/Contracts/Favouritable.php index 29612156..1fad7ccb 100644 --- a/app/Contracts/Favouritable.php +++ b/app/Contracts/Favouritable.php @@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany; * * @package Poniverse\Ponyfm\Contracts */ -interface Favouritable extends GeneratesNotifications { +interface Favouritable extends GeneratesNotifications +{ /** * This method returns an Eloquent relation to the entity's favourites. * diff --git a/app/Contracts/GeneratesNotifications.php b/app/Contracts/GeneratesNotifications.php index 2a58c4d8..ceb2f5de 100644 --- a/app/Contracts/GeneratesNotifications.php +++ b/app/Contracts/GeneratesNotifications.php @@ -29,11 +29,12 @@ use Poniverse\Ponyfm\Models\User; * * @package Poniverse\Ponyfm\Contracts */ -interface GeneratesNotifications { +interface GeneratesNotifications +{ /** * Returns a human-friendly string (lowercase & singular) representing this * type of resource. - * + * * @return string */ public function getResourceType():string; diff --git a/app/Contracts/NotificationHandler.php b/app/Contracts/NotificationHandler.php index 25da4739..6feace47 100644 --- a/app/Contracts/NotificationHandler.php +++ b/app/Contracts/NotificationHandler.php @@ -28,12 +28,13 @@ use Poniverse\Ponyfm\Models\User; /** * Interface NotificationHandler * @package Poniverse\Ponyfm\Contracts - * + * * Each method in this interface represents a type of notification. To add a new * type of notification, add a method for it to this interface and every class * that implements it. Your IDE should be able to help with this. */ -interface NotificationHandler { +interface NotificationHandler +{ /** * @param Track $track * @return void diff --git a/app/Contracts/Searchable.php b/app/Contracts/Searchable.php index 8b81b440..39764c75 100644 --- a/app/Contracts/Searchable.php +++ b/app/Contracts/Searchable.php @@ -20,7 +20,8 @@ namespace Poniverse\Ponyfm\Contracts; -interface Searchable { +interface Searchable +{ /** * Returns this model in Elasticsearch-friendly form. The array returned by * this method should match the current mapping for this model's ES type. diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index d3f61135..9f31bb25 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -22,6 +22,8 @@ namespace Poniverse\Ponyfm\Exceptions; use Exception; use Symfony\Component\HttpKernel\Exception\HttpException; +use Illuminate\Auth\Access\AuthorizationException; +use Illuminate\Validation\ValidationException; use GrahamCampbell\Exceptions\ExceptionHandler as ExceptionHandler; class Handler extends ExceptionHandler @@ -32,6 +34,8 @@ class Handler extends ExceptionHandler * @var array */ protected $dontReport = [ + AuthorizationException::class, + ValidationException::class, HttpException::class, ]; @@ -45,7 +49,7 @@ class Handler extends ExceptionHandler */ public function report(Exception $e) { - return parent::report($e); + parent::report($e); } /** diff --git a/app/Exceptions/InvalidAccessTokenException.php b/app/Exceptions/InvalidAccessTokenException.php index 5b7ca836..39c3f57d 100644 --- a/app/Exceptions/InvalidAccessTokenException.php +++ b/app/Exceptions/InvalidAccessTokenException.php @@ -29,4 +29,6 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; * This exception indicates that an access token we attempted to introspect * through the Poniverse API is expired or otherwise unusable. */ -class InvalidAccessTokenException extends AccessDeniedHttpException {}; +class InvalidAccessTokenException extends AccessDeniedHttpException +{ +}; diff --git a/app/Exceptions/InvalidEncodeOptionsException.php b/app/Exceptions/InvalidEncodeOptionsException.php index 64181efe..a8611c13 100644 --- a/app/Exceptions/InvalidEncodeOptionsException.php +++ b/app/Exceptions/InvalidEncodeOptionsException.php @@ -22,4 +22,6 @@ namespace Poniverse\Ponyfm\Exceptions; use InvalidArgumentException; -class InvalidEncodeOptionsException extends InvalidArgumentException {} +class InvalidEncodeOptionsException extends InvalidArgumentException +{ +} diff --git a/app/Exceptions/TrackFileNotFoundException.php b/app/Exceptions/TrackFileNotFoundException.php index c4eed2e1..aac12fbb 100644 --- a/app/Exceptions/TrackFileNotFoundException.php +++ b/app/Exceptions/TrackFileNotFoundException.php @@ -31,4 +31,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException; * contain tracks for which no lossless master is available (and thus, lossless * `TrackFiles` don't exist for). */ -class TrackFileNotFoundException extends ModelNotFoundException {} +class TrackFileNotFoundException extends ModelNotFoundException +{ +} diff --git a/app/Facades/Notification.php b/app/Facades/Notification.php index 479bd175..11dd6d9d 100644 --- a/app/Facades/Notification.php +++ b/app/Facades/Notification.php @@ -19,10 +19,13 @@ */ namespace Poniverse\Ponyfm\Facades; + use Illuminate\Support\Facades\Facade; -class Notification extends Facade { - protected static function getFacadeAccessor() { +class Notification extends Facade +{ + protected static function getFacadeAccessor() + { return 'notification'; } } diff --git a/app/Http/Controllers/Api/Mobile/TracksController.php b/app/Http/Controllers/Api/Mobile/TracksController.php index 4f1a96f6..9206291b 100644 --- a/app/Http/Controllers/Api/Mobile/TracksController.php +++ b/app/Http/Controllers/Api/Mobile/TracksController.php @@ -35,7 +35,7 @@ class TracksController extends Controller ->published() ->with('user', 'genre', 'cover', 'album', 'album.user')->take(10)->get(); - $tracks = $tracks->map(function(Track $track) { + $tracks = $tracks->map(function (Track $track) { return Track::mapPublicTrackSummary($track); }); diff --git a/app/Http/Controllers/Api/V1/TracksController.php b/app/Http/Controllers/Api/V1/TracksController.php index 18dbc5c0..00b7fdba 100644 --- a/app/Http/Controllers/Api/V1/TracksController.php +++ b/app/Http/Controllers/Api/V1/TracksController.php @@ -28,7 +28,8 @@ use Response; class TracksController extends ApiControllerBase { - public function postUploadTrack() { + public function postUploadTrack() + { session_write_close(); $response = $this->execute(new UploadTrackCommand(true, true, session('api_client_id'), true)); @@ -53,13 +54,13 @@ class TracksController extends ApiControllerBase } - public function getUploadStatus($trackId) { + public function getUploadStatus($trackId) + { $track = Track::findOrFail($trackId); $this->authorize('edit', $track); if ($track->status === Track::STATUS_PROCESSING) { return Response::json(['message' => 'Processing...'], 202); - } elseif ($track->status === Track::STATUS_COMPLETE) { return Response::json([ 'message' => $track->published_at @@ -68,7 +69,6 @@ class TracksController extends ApiControllerBase 'edit_url' => action('ContentController@getTracks', ['id' => $trackId]), 'track_url' => $track->url ], 201); - } else { // something went wrong return Response::json(['error' => 'Processing failed! Please contact logic@pony.fm to figure out what went wrong.'], 500); diff --git a/app/Http/Controllers/Api/Web/AccountController.php b/app/Http/Controllers/Api/Web/AccountController.php index cb952eee..bfb77005 100644 --- a/app/Http/Controllers/Api/Web/AccountController.php +++ b/app/Http/Controllers/Api/Web/AccountController.php @@ -26,7 +26,7 @@ use Poniverse\Ponyfm\Commands\SaveAccountSettingsCommand; use Poniverse\Ponyfm\Models\User; use Gate; use Auth; -use Input; +use Illuminate\Support\Facades\Request; use Response; class AccountController extends ApiControllerBase @@ -77,6 +77,6 @@ class AccountController extends ApiControllerBase public function postSave(User $user) { - return $this->execute(new SaveAccountSettingsCommand(Input::all(), $user)); + return $this->execute(new SaveAccountSettingsCommand(Request::all(), $user)); } } diff --git a/app/Http/Controllers/Api/Web/AlbumsController.php b/app/Http/Controllers/Api/Web/AlbumsController.php index cbc42e93..1a894f03 100644 --- a/app/Http/Controllers/Api/Web/AlbumsController.php +++ b/app/Http/Controllers/Api/Web/AlbumsController.php @@ -30,7 +30,7 @@ use Poniverse\Ponyfm\Models\Image; use Poniverse\Ponyfm\Models\ResourceLogItem; use Auth; use Gate; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Models\User; use Response; use Poniverse\Ponyfm\Models\Track; @@ -39,12 +39,12 @@ class AlbumsController extends ApiControllerBase { public function postCreate() { - return $this->execute(new CreateAlbumCommand(Input::all())); + return $this->execute(new CreateAlbumCommand(Request::all())); } public function postEdit($id) { - return $this->execute(new EditAlbumCommand($id, Input::all())); + return $this->execute(new EditAlbumCommand($id, Request::all())); } public function postDelete($id) @@ -55,7 +55,7 @@ class AlbumsController extends ApiControllerBase public function getShow($id) { $album = Album::with([ - 'tracks' => function($query) { + 'tracks' => function ($query) { $query->userDetails(); }, 'tracks.cover', @@ -75,7 +75,7 @@ class AlbumsController extends ApiControllerBase App::abort(404); } - if (Input::get('log')) { + if (Request::get('log')) { ResourceLogItem::logItem('album', $id, ResourceLogItem::VIEW); $album->view_count++; } @@ -96,7 +96,6 @@ class AlbumsController extends ApiControllerBase try { /** @var Album $album */ $album = Album::with('tracks.trackFiles')->findOrFail($id); - } catch (ModelNotFoundException $e) { return $this->notFound('Album not found!'); } @@ -121,8 +120,8 @@ class AlbumsController extends ApiControllerBase public function getIndex() { $page = 1; - if (Input::has('page')) { - $page = Input::get('page'); + if (Request::has('page')) { + $page = Request::get('page'); } $query = Album::summary() @@ -144,8 +143,10 @@ class AlbumsController extends ApiControllerBase $albums[] = Album::mapPublicAlbumSummary($album); } - return Response::json(["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)], - 200); + return Response::json( + ["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)], + 200 + ); } public function getOwned(User $user) diff --git a/app/Http/Controllers/Api/Web/ArtistsController.php b/app/Http/Controllers/Api/Web/ArtistsController.php index 7c91c2ec..6ef54fd0 100644 --- a/app/Http/Controllers/Api/Web/ArtistsController.php +++ b/app/Http/Controllers/Api/Web/ArtistsController.php @@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\Follower; use App; -use Input; +use Illuminate\Support\Facades\Request; use Response; use ColorThief\ColorThief; use Helpers; @@ -63,7 +63,7 @@ class ArtistsController extends ApiControllerBase 'album' => function ($query) { $query->userDetails(); } - ])->get(); + ])->get(); $tracks = []; $albums = []; @@ -209,8 +209,8 @@ class ArtistsController extends ApiControllerBase public function getIndex() { $page = 1; - if (Input::has('page')) { - $page = Input::get('page'); + if (Request::has('page')) { + $page = Request::get('page'); } $query = User::where('track_count', '>', 0); @@ -227,12 +227,15 @@ class ArtistsController extends ApiControllerBase $users[] = User::mapPublicUserSummary($user); } - return Response::json(["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)], - 200); + return Response::json( + ["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)], + 200 + ); } - public function postIndex() { - $name = Input::json('username'); + public function postIndex() + { + $name = Request::json('username'); return $this->execute(new CreateUserCommand($name, $name, null, true)); } } diff --git a/app/Http/Controllers/Api/Web/CommentsController.php b/app/Http/Controllers/Api/Web/CommentsController.php index 3b82bb1e..73f4f0ac 100644 --- a/app/Http/Controllers/Api/Web/CommentsController.php +++ b/app/Http/Controllers/Api/Web/CommentsController.php @@ -24,14 +24,14 @@ use App; use Poniverse\Ponyfm\Commands\CreateCommentCommand; use Poniverse\Ponyfm\Models\Comment; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; -use Input; +use Illuminate\Support\Facades\Request; use Response; class CommentsController extends ApiControllerBase { public function postCreate($type, $id) { - return $this->execute(new CreateCommentCommand($type, $id, Input::all())); + return $this->execute(new CreateCommentCommand($type, $id, Request::all())); } public function getIndex($type, $id) diff --git a/app/Http/Controllers/Api/Web/DashboardController.php b/app/Http/Controllers/Api/Web/DashboardController.php index 0fdd0e88..8b6bf397 100644 --- a/app/Http/Controllers/Api/Web/DashboardController.php +++ b/app/Http/Controllers/Api/Web/DashboardController.php @@ -39,7 +39,7 @@ class DashboardController extends ApiControllerBase ->orderBy('published_at', 'desc') ->take(30); - $recentQuery->whereHas('user', function($q) { + $recentQuery->whereHas('user', function ($q) { $q->whereIsArchived(false); }); diff --git a/app/Http/Controllers/Api/Web/FavouritesController.php b/app/Http/Controllers/Api/Web/FavouritesController.php index a75fbbff..39533fb2 100644 --- a/app/Http/Controllers/Api/Web/FavouritesController.php +++ b/app/Http/Controllers/Api/Web/FavouritesController.php @@ -27,14 +27,14 @@ use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\Track; use Auth; -use Input; +use Illuminate\Support\Facades\Request; use Response; class FavouritesController extends ApiControllerBase { public function postToggle() { - return $this->execute(new ToggleFavouriteCommand(Input::get('type'), Input::get('id'))); + return $this->execute(new ToggleFavouriteCommand(Request::get('type'), Request::get('id'))); } public function getTracks() @@ -43,7 +43,7 @@ class FavouritesController extends ApiControllerBase ::whereUserId(Auth::user()->id) ->whereNotNull('track_id') ->with([ - 'track' => function($query) { + 'track' => function ($query) { $query ->userDetails() ->published(); @@ -58,8 +58,7 @@ class FavouritesController extends ApiControllerBase $tracks = []; foreach ($query->get() as $fav) { - if ($fav->track == null) // deleted track - { + if ($fav->track == null) { // deleted track continue; } @@ -75,7 +74,7 @@ class FavouritesController extends ApiControllerBase ::whereUserId(Auth::user()->id) ->whereNotNull('album_id') ->with([ - 'album' => function($query) { + 'album' => function ($query) { $query->userDetails(); }, 'album.user', @@ -86,8 +85,7 @@ class FavouritesController extends ApiControllerBase $albums = []; foreach ($query->get() as $fav) { - if ($fav->album == null) // deleted album - { + if ($fav->album == null) { // deleted album continue; } @@ -103,7 +101,7 @@ class FavouritesController extends ApiControllerBase ::whereUserId(Auth::user()->id) ->whereNotNull('playlist_id') ->with([ - 'playlist' => function($query) { + 'playlist' => function ($query) { $query->userDetails(); }, 'playlist.user', @@ -115,8 +113,7 @@ class FavouritesController extends ApiControllerBase $playlists = []; foreach ($query->get() as $fav) { - if ($fav->playlist == null) // deleted playlist - { + if ($fav->playlist == null) { // deleted playlist continue; } diff --git a/app/Http/Controllers/Api/Web/FollowController.php b/app/Http/Controllers/Api/Web/FollowController.php index d0f79595..be0c9809 100644 --- a/app/Http/Controllers/Api/Web/FollowController.php +++ b/app/Http/Controllers/Api/Web/FollowController.php @@ -22,12 +22,12 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; use Poniverse\Ponyfm\Commands\ToggleFollowingCommand; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; -use Input; +use Illuminate\Support\Facades\Request; class FollowController extends ApiControllerBase { public function postToggle() { - return $this->execute(new ToggleFollowingCommand(Input::get('type'), Input::get('id'))); + return $this->execute(new ToggleFollowingCommand(Request::get('type'), Request::get('id'))); } } diff --git a/app/Http/Controllers/Api/Web/GenresController.php b/app/Http/Controllers/Api/Web/GenresController.php index 0de4fb38..07c913ab 100644 --- a/app/Http/Controllers/Api/Web/GenresController.php +++ b/app/Http/Controllers/Api/Web/GenresController.php @@ -20,7 +20,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Commands\CreateGenreCommand; use Poniverse\Ponyfm\Commands\DeleteGenreCommand; use Poniverse\Ponyfm\Commands\RenameGenreCommand; @@ -28,14 +28,13 @@ use Poniverse\Ponyfm\Models\Genre; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Response; - class GenresController extends ApiControllerBase { public function getIndex() { $this->authorize('access-admin-area'); - $genres = Genre::with(['trackCountRelation' => function($query) { + $genres = Genre::with(['trackCountRelation' => function ($query) { $query->withTrashed(); }]) ->orderBy('name', 'asc') @@ -48,20 +47,20 @@ class GenresController extends ApiControllerBase public function postCreate() { - $command = new CreateGenreCommand(Input::get('name')); + $command = new CreateGenreCommand(Request::get('name')); return $this->execute($command); } public function putRename($genreId) { - $command = new RenameGenreCommand($genreId, Input::get('name')); + $command = new RenameGenreCommand($genreId, Request::get('name')); return $this->execute($command); } public function deleteGenre($genreId) { - $command = new DeleteGenreCommand($genreId, Input::get('destination_genre_id')); + $command = new DeleteGenreCommand($genreId, Request::get('destination_genre_id')); return $this->execute($command); } } diff --git a/app/Http/Controllers/Api/Web/NotificationsController.php b/app/Http/Controllers/Api/Web/NotificationsController.php index 3a08f1af..2af3c31b 100644 --- a/app/Http/Controllers/Api/Web/NotificationsController.php +++ b/app/Http/Controllers/Api/Web/NotificationsController.php @@ -21,7 +21,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; use Auth; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Models\Notification; use Poniverse\Ponyfm\Models\Subscription; @@ -56,7 +56,7 @@ class NotificationsController extends ApiControllerBase */ public function putMarkAsRead() { - $notificationIds = Input::json('notification_ids'); + $notificationIds = Request::json('notification_ids'); $numberOfUpdatedRows = Auth::user() ->notifications() ->whereIn('id', $notificationIds) @@ -74,7 +74,7 @@ class NotificationsController extends ApiControllerBase */ public function postSubscribe() { - $input = json_decode(Input::json('subscription')); + $input = json_decode(Request::json('subscription')); if ($input != 'null') { $existing = Subscription::where('endpoint', '=', $input->endpoint) ->where('user_id', '=', Auth::user()->id) @@ -104,7 +104,7 @@ class NotificationsController extends ApiControllerBase */ public function postUnsubscribe() { - $input = json_decode(Input::json('subscription')); + $input = json_decode(Request::json('subscription')); $existing = Subscription::where('endpoint', '=', $input->endpoint) ->where('user_id', '=', Auth::user()->id) diff --git a/app/Http/Controllers/Api/Web/PlaylistsController.php b/app/Http/Controllers/Api/Web/PlaylistsController.php index 1451beac..99c84db1 100644 --- a/app/Http/Controllers/Api/Web/PlaylistsController.php +++ b/app/Http/Controllers/Api/Web/PlaylistsController.php @@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Image; use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\ResourceLogItem; use Auth; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Models\User; use Response; use Poniverse\Ponyfm\Models\Track; @@ -40,12 +40,12 @@ class PlaylistsController extends ApiControllerBase { public function postCreate() { - return $this->execute(new CreatePlaylistCommand(Input::all())); + return $this->execute(new CreatePlaylistCommand(Request::all())); } public function postEdit($id) { - return $this->execute(new EditPlaylistCommand($id, Input::all())); + return $this->execute(new EditPlaylistCommand($id, Request::all())); } public function postDelete($id) @@ -55,27 +55,29 @@ class PlaylistsController extends ApiControllerBase public function postAddTrack($id) { - return $this->execute(new AddTrackToPlaylistCommand($id, Input::get('track_id'))); + return $this->execute(new AddTrackToPlaylistCommand($id, Request::get('track_id'))); } public function postRemoveTrack($id) { - return $this->execute(new RemoveTrackFromPlaylistCommand($id, Input::get('track_id'))); + return $this->execute(new RemoveTrackFromPlaylistCommand($id, Request::get('track_id'))); } public function getIndex() { - $page = Input::has('page') ? Input::get('page') : 1; + $page = Request::has('page') ? Request::get('page') : 1; $query = Playlist::summary() - ->with('user', + ->with( + 'user', 'user.avatar', 'tracks', 'tracks.cover', 'tracks.user', 'tracks.user.avatar', 'tracks.album', - 'tracks.album.user') + 'tracks.album.user' + ) ->userDetails() // A playlist with only one track is not much of a list. ->where('track_count', '>', 1) @@ -106,7 +108,7 @@ class PlaylistsController extends ApiControllerBase 'tracks.genre', 'tracks.cover', 'tracks.album', - 'tracks' => function($query) { + 'tracks' => function ($query) { $query->userDetails(); }, 'tracks.trackFiles', @@ -117,7 +119,7 @@ class PlaylistsController extends ApiControllerBase App::abort('404'); } - if (Input::get('log')) { + if (Request::get('log')) { ResourceLogItem::logItem('playlist', $id, ResourceLogItem::VIEW); $playlist->view_count++; } @@ -161,7 +163,7 @@ class PlaylistsController extends ApiControllerBase $query = Playlist ::userDetails() ->with('tracks', 'tracks.cover', 'tracks.user', 'user') - ->join('pinned_playlists', function($join) { + ->join('pinned_playlists', function ($join) { $join->on('playlist_id', '=', 'playlists.id'); }) ->where('pinned_playlists.user_id', '=', Auth::user()->id) @@ -221,8 +223,8 @@ class PlaylistsController extends ApiControllerBase */ private function applyOrdering($query) { - if (Input::has('order')) { - $order = \Input::get('order'); + if (Request::has('order')) { + $order = \Request::get('order'); $parts = explode(',', $order); $query->orderBy($parts[0], $parts[1]); } diff --git a/app/Http/Controllers/Api/Web/SearchController.php b/app/Http/Controllers/Api/Web/SearchController.php index f2304bf0..d8f5921a 100644 --- a/app/Http/Controllers/Api/Web/SearchController.php +++ b/app/Http/Controllers/Api/Web/SearchController.php @@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; use Elasticsearch; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Library\Search; use Response; @@ -30,7 +30,7 @@ class SearchController extends ApiControllerBase { public function getSearch(Search $search) { - $results = $search->searchAllContent(Input::query('query')); + $results = $search->searchAllContent(Request::query('query')); return Response::json([ 'results' => $results, diff --git a/app/Http/Controllers/Api/Web/ShowSongsController.php b/app/Http/Controllers/Api/Web/ShowSongsController.php index 258b97fd..68ac6a1d 100644 --- a/app/Http/Controllers/Api/Web/ShowSongsController.php +++ b/app/Http/Controllers/Api/Web/ShowSongsController.php @@ -20,7 +20,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Commands\CreateShowSongCommand; use Poniverse\Ponyfm\Commands\DeleteShowSongCommand; use Poniverse\Ponyfm\Commands\RenameShowSongCommand; @@ -28,14 +28,13 @@ use Poniverse\Ponyfm\Models\ShowSong; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Response; - class ShowSongsController extends ApiControllerBase { public function getIndex() { $this->authorize('access-admin-area'); - $songs = ShowSong::with(['trackCountRelation' => function($query) { + $songs = ShowSong::with(['trackCountRelation' => function ($query) { $query->withTrashed(); }]) ->orderBy('title', 'asc') @@ -49,20 +48,20 @@ class ShowSongsController extends ApiControllerBase public function postCreate() { - $command = new CreateShowSongCommand(Input::get('title')); + $command = new CreateShowSongCommand(Request::get('title')); return $this->execute($command); } public function putRename($songId) { - $command = new RenameShowSongCommand($songId, Input::get('title')); + $command = new RenameShowSongCommand($songId, Request::get('title')); return $this->execute($command); } public function deleteSong($songId) { - $command = new DeleteShowSongCommand($songId, Input::get('destination_song_id')); + $command = new DeleteShowSongCommand($songId, Request::get('destination_song_id')); return $this->execute($command); } } diff --git a/app/Http/Controllers/Api/Web/StatsController.php b/app/Http/Controllers/Api/Web/StatsController.php index e7e05a6c..427c3280 100644 --- a/app/Http/Controllers/Api/Web/StatsController.php +++ b/app/Http/Controllers/Api/Web/StatsController.php @@ -32,7 +32,8 @@ use Carbon\Carbon; class StatsController extends ApiControllerBase { - private function getStatsData($id, $hourly = false) { + private function getStatsData($id, $hourly = false) + { $playRange = "'1 MONTH'"; if ($hourly) { @@ -51,7 +52,8 @@ class StatsController extends ApiControllerBase return $statQuery; } - private function sortTrackStatsArray($query, $hourly = false) { + private function sortTrackStatsArray($query, $hourly = false) + { $now = Carbon::now(); $playsArray = []; $output = []; @@ -104,8 +106,9 @@ class StatsController extends ApiControllerBase } } - public function getTrackStats($id) { - $cachedOutput = Cache::remember('track_stats'.$id, 5, function() use ($id) { + public function getTrackStats($id) + { + $cachedOutput = Cache::remember('track_stats'.$id, 5, function () use ($id) { try { $track = Track::published()->findOrFail($id); } catch (ModelNotFoundException $e) { diff --git a/app/Http/Controllers/Api/Web/TaxonomiesController.php b/app/Http/Controllers/Api/Web/TaxonomiesController.php index d92429bf..9ff5b8f9 100644 --- a/app/Http/Controllers/Api/Web/TaxonomiesController.php +++ b/app/Http/Controllers/Api/Web/TaxonomiesController.php @@ -37,12 +37,18 @@ class TaxonomiesController extends ApiControllerBase ->orderBy('name') ->get() ->toArray(), - 'track_types' => TrackType::select('track_types.*', - DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count')) + 'track_types' => TrackType::select( + 'track_types.*', + DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count') + ) ->where('id', '!=', TrackType::UNCLASSIFIED_TRACK) ->get()->toArray(), - 'show_songs' => ShowSong::select('title', 'id', 'slug', - DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count'))->orderBy('title')->get()->toArray() + 'show_songs' => ShowSong::select( + 'title', + 'id', + 'slug', + DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count') + )->orderBy('title')->get()->toArray() ], 200); } } diff --git a/app/Http/Controllers/Api/Web/TracksController.php b/app/Http/Controllers/Api/Web/TracksController.php index f4106a6a..ba6d36df 100644 --- a/app/Http/Controllers/Api/Web/TracksController.php +++ b/app/Http/Controllers/Api/Web/TracksController.php @@ -23,7 +23,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; use Auth; use File; use Illuminate\Database\Eloquent\ModelNotFoundException; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse\Ponyfm\Commands\DeleteTrackCommand; use Poniverse\Ponyfm\Commands\EditTrackCommand; use Poniverse\Ponyfm\Commands\GenerateTrackFilesCommand; @@ -55,10 +55,8 @@ class TracksController extends ApiControllerBase if ($track->status === Track::STATUS_PROCESSING) { return Response::json(['message' => 'Processing...'], 202); - } elseif ($track->status === Track::STATUS_COMPLETE) { return Response::json(['message' => 'Processing complete!'], 201); - } else { // something went wrong return Response::json(['error' => 'Processing failed!'], 500); @@ -72,7 +70,7 @@ class TracksController extends ApiControllerBase public function postEdit($id) { - return $this->execute(new EditTrackCommand($id, Input::all())); + return $this->execute(new EditTrackCommand($id, Request::all())); } public function postUploadNewVersion($trackId) @@ -97,10 +95,8 @@ class TracksController extends ApiControllerBase if ($track->version_upload_status === Track::STATUS_PROCESSING) { return Response::json(['message' => 'Processing...'], 202); - } elseif ($track->version_upload_status === Track::STATUS_COMPLETE) { return Response::json(['message' => 'Processing complete!'], 201); - } else { // something went wrong return Response::json(['error' => 'Processing failed!'], 500); @@ -114,7 +110,7 @@ class TracksController extends ApiControllerBase $versions = []; $trackFiles = $track->trackFilesForAllVersions()->where('is_master', 'true')->get(); - foreach($trackFiles as $trackFile) { + foreach ($trackFiles as $trackFile) { $versions[] = [ 'version' => $trackFile->version, 'url' => '/tracks/' . $track->id . '/version-change/' . $trackFile->version, @@ -151,7 +147,7 @@ class TracksController extends ApiControllerBase return $this->notFound('Track not found!'); } - if (Input::get('log')) { + if (Request::get('log')) { ResourceLogItem::logItem('track', $id, ResourceLogItem::VIEW); $track->view_count++; } @@ -209,8 +205,8 @@ class TracksController extends ApiControllerBase $page = 1; $perPage = 45; - if (Input::has('page')) { - $page = Input::get('page'); + if (Request::has('page')) { + $page = Request::get('page'); } if ($all) { @@ -295,8 +291,8 @@ class TracksController extends ApiControllerBase */ private function applyOrdering($query) { - if (Input::has('order')) { - $order = \Input::get('order'); + if (Request::has('order')) { + $order = \Request::get('order'); $parts = explode(',', $order); $query->orderBy($parts[0], $parts[1]); } @@ -312,8 +308,8 @@ class TracksController extends ApiControllerBase */ private function applyFilters($query, $unknown = false) { - if (Input::has('is_vocal')) { - $isVocal = \Input::get('is_vocal'); + if (Request::has('is_vocal')) { + $isVocal = \Request::get('is_vocal'); if ($isVocal == 'true') { $query->whereIsVocal(true); } else { @@ -321,24 +317,24 @@ class TracksController extends ApiControllerBase } } - if (Input::has('in_album')) { - if (Input::get('in_album') == 'true') { + if (Request::has('in_album')) { + if (Request::get('in_album') == 'true') { $query->whereNotNull('album_id'); } else { $query->whereNull('album_id'); } } - if (Input::has('genres')) { - $query->whereIn('genre_id', Input::get('genres')); + if (Request::has('genres')) { + $query->whereIn('genre_id', Request::get('genres')); } - if (Input::has('types') && !$unknown) { - $query->whereIn('track_type_id', Input::get('types')); + if (Request::has('types') && !$unknown) { + $query->whereIn('track_type_id', Request::get('types')); } if ($unknown) { - $query->where(function($q) { + $query->where(function ($q) { $unknownGenre = Genre::where('name', 'Unknown')->first(); $q->where('track_type_id', TrackType::UNCLASSIFIED_TRACK); @@ -351,14 +347,14 @@ class TracksController extends ApiControllerBase $query->join('mlpma_tracks', 'tracks.id', '=', 'mlpma_tracks.track_id'); } - if (Input::has('songs')) { + if (Request::has('songs')) { // DISTINCT is needed here to avoid duplicate results // when a track is associated with multiple show songs. $query->distinct(); $query->join('show_song_track', function ($join) { $join->on('tracks.id', '=', 'show_song_track.track_id'); }); - $query->whereIn('show_song_track.show_song_id', Input::get('songs')); + $query->whereIn('show_song_track.show_song_id', Request::get('songs')); } return $query; diff --git a/app/Http/Controllers/ArtistsController.php b/app/Http/Controllers/ArtistsController.php index 17a2754e..518bc57a 100644 --- a/app/Http/Controllers/ArtistsController.php +++ b/app/Http/Controllers/ArtistsController.php @@ -32,11 +32,13 @@ class ArtistsController extends Controller return View::make('artists.index'); } - public function getFavourites($slug) { + public function getFavourites($slug) + { return $this->getProfile($slug); } - public function getContent($slug) { + public function getContent($slug) + { return $this->getProfile($slug); } @@ -53,7 +55,7 @@ class ArtistsController extends Controller public function getShortlink($id) { $user = User::find($id); - if (!$user || $user->disabled_at !== NULL) { + if (!$user || $user->disabled_at !== null) { App::abort('404'); } diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index a1c4dd2f..bdb7b0f4 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -24,7 +24,7 @@ use Poniverse\Ponyfm\Models\User; use Auth; use Config; use DB; -use Input; +use Illuminate\Support\Facades\Request; use Poniverse; use Redirect; @@ -60,57 +60,63 @@ class AuthController extends Controller Config::get('poniverse.urls')['token'], 'authorization_code', [ - 'code' => Input::query('code'), + 'code' => Request::query('code'), 'redirect_uri' => action('AuthController@getOAuth') - ]); + ] + ); if ($code['code'] != 200) { if ($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) { return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt')); } - return Redirect::to('/')->with('message', - 'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.'); + return Redirect::to('/')->with( + 'message', + 'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.' + ); } - $this->poniverse->setAccessToken($code['result']['access_token']); - $poniverseUser = $this->poniverse->getUser(); - $token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where('service', '=', - 'poniverse')->first(); + $this->poniverse->setAccessToken($code['result']['access_token']); + $poniverseUser = $this->poniverse->getUser(); + $token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where( + 'service', + '=', + 'poniverse' + )->first(); - $setData = [ + $setData = [ 'access_token' => $code['result']['access_token'], 'expires' => date('Y-m-d H:i:s', strtotime("+".$code['result']['expires_in']." Seconds", time())), 'type' => $code['result']['token_type'], - ]; + ]; - if (isset($code['result']['refresh_token']) && !empty($code['result']['refresh_token'])) { - $setData['refresh_token'] = $code['result']['refresh_token']; - } + if (isset($code['result']['refresh_token']) && !empty($code['result']['refresh_token'])) { + $setData['refresh_token'] = $code['result']['refresh_token']; + } - if ($token) { - //User already exists, update access token and refresh token if provided. - DB::table('oauth2_tokens')->where('id', '=', $token->id)->update($setData); + if ($token) { + //User already exists, update access token and refresh token if provided. + DB::table('oauth2_tokens')->where('id', '=', $token->id)->update($setData); - return $this->loginRedirect(User::find($token->user_id)); - } + return $this->loginRedirect(User::find($token->user_id)); + } // Check by login name to see if they already have an account - $user = User::findOrCreate($poniverseUser['username'], $poniverseUser['display_name'], $poniverseUser['email']); + $user = User::findOrCreate($poniverseUser['username'], $poniverseUser['display_name'], $poniverseUser['email']); - if ($user->wasRecentlyCreated) { - return $this->loginRedirect($user); - } + if ($user->wasRecentlyCreated) { + return $this->loginRedirect($user); + } // We need to insert a new token row :O - $setData['user_id'] = $user->id; - $setData['external_user_id'] = $poniverseUser['id']; - $setData['service'] = 'poniverse'; + $setData['user_id'] = $user->id; + $setData['external_user_id'] = $poniverseUser['id']; + $setData['service'] = 'poniverse'; - DB::table('oauth2_tokens')->insert($setData); + DB::table('oauth2_tokens')->insert($setData); - return $this->loginRedirect($user); + return $this->loginRedirect($user); } protected function loginRedirect($user, $rememberMe = true) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 32706ca0..66e90272 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -21,11 +21,12 @@ namespace Poniverse\Ponyfm\Http\Controllers; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; +use Illuminate\Foundation\Auth\Access\AuthorizesResources; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; -abstract class Controller extends BaseController +class Controller extends BaseController { use DispatchesJobs, ValidatesRequests, AuthorizesRequests; } diff --git a/app/Http/Controllers/TracksController.php b/app/Http/Controllers/TracksController.php index d5501a46..05f60a5f 100644 --- a/app/Http/Controllers/TracksController.php +++ b/app/Http/Controllers/TracksController.php @@ -153,12 +153,16 @@ class TracksController extends Controller if (Config::get('app.sendfile')) { $response->header('X-Sendfile', $filename); - $response->header('Content-Disposition', - 'attachment; filename="'.$trackFile->getDownloadFilename().'"'); + $response->header( + 'Content-Disposition', + 'attachment; filename="'.$trackFile->getDownloadFilename().'"' + ); } else { $response->header('X-Accel-Redirect', $filename); - $response->header('Content-Disposition', - 'attachment; filename="'.$trackFile->getDownloadFilename().'"'); + $response->header( + 'Content-Disposition', + 'attachment; filename="'.$trackFile->getDownloadFilename().'"' + ); } $time = gmdate(filemtime($filename)); diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index fcb5d192..8e59002b 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -31,12 +31,17 @@ class Kernel extends HttpKernel */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, - \Poniverse\Ponyfm\Http\Middleware\EncryptCookies::class, - \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, - \Illuminate\Session\Middleware\StartSession::class, - \Illuminate\View\Middleware\ShareErrorsFromSession::class, - \Poniverse\Ponyfm\Http\Middleware\VerifyCsrfToken::class, - \Poniverse\Ponyfm\Http\Middleware\DisabledAccountCheck::class, + ]; + + protected $middlewareGroups = [ + 'web' => [ + \Poniverse\Ponyfm\Http\Middleware\EncryptCookies::class, + \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, + \Illuminate\Session\Middleware\StartSession::class, + \Illuminate\View\Middleware\ShareErrorsFromSession::class, + \Poniverse\Ponyfm\Http\Middleware\VerifyCsrfToken::class, + \Poniverse\Ponyfm\Http\Middleware\DisabledAccountCheck::class, + ] ]; /** @@ -48,8 +53,10 @@ class Kernel extends HttpKernel 'auth' => \Poniverse\Ponyfm\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'auth.oauth' => \Poniverse\Ponyfm\Http\Middleware\AuthenticateOAuth::class, - 'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class, +// 'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class, 'json-exceptions' => \Poniverse\Ponyfm\Http\Middleware\JsonExceptions::class, + 'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class, 'guest' => \Poniverse\Ponyfm\Http\Middleware\RedirectIfAuthenticated::class, + 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ]; } diff --git a/app/Http/Middleware/AuthenticateOAuth.php b/app/Http/Middleware/AuthenticateOAuth.php index aecde626..8a391e0d 100644 --- a/app/Http/Middleware/AuthenticateOAuth.php +++ b/app/Http/Middleware/AuthenticateOAuth.php @@ -46,7 +46,8 @@ class AuthenticateOAuth */ private $session; - public function __construct(Poniverse $poniverse, Guard $auth, Store $session) { + public function __construct(Poniverse $poniverse, Guard $auth, Store $session) + { $this->poniverse = $poniverse; $this->auth = $auth; $this->session = $session; diff --git a/app/Http/Middleware/DisabledAccountCheck.php b/app/Http/Middleware/DisabledAccountCheck.php index 9b83eb29..3c8e8ef9 100644 --- a/app/Http/Middleware/DisabledAccountCheck.php +++ b/app/Http/Middleware/DisabledAccountCheck.php @@ -37,7 +37,8 @@ class DisabledAccountCheck * * @param Guard $auth */ - public function __construct(Guard $auth) { + public function __construct(Guard $auth) + { $this->auth = $auth; } diff --git a/app/Http/Middleware/JsonExceptions.php b/app/Http/Middleware/JsonExceptions.php index 4d74acdc..d01244f3 100644 --- a/app/Http/Middleware/JsonExceptions.php +++ b/app/Http/Middleware/JsonExceptions.php @@ -43,7 +43,6 @@ class JsonExceptions { try { $response = $next($request); - } catch (HttpException $e) { return \Response::json([ 'message' => $e->getMessage() diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 381736f8..0efea06c 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -21,40 +21,24 @@ namespace Poniverse\Ponyfm\Http\Middleware; use Closure; -use Illuminate\Contracts\Auth\Guard; +use Illuminate\Auth\AuthManager; +use Illuminate\Support\Facades\Auth; class RedirectIfAuthenticated { - /** - * The Guard implementation. - * - * @var Guard - */ - protected $auth; - - /** - * Create a new filter instance. - * - * @param Guard $auth - */ - public function __construct(Guard $auth) - { - $this->auth = $auth; - } - /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next + * @param string|null $guard * @return mixed */ - public function handle($request, Closure $next) + public function handle($request, Closure $next, $guard = null) { - if ($this->auth->check()) { + if (Auth::guard($guard)->check()) { return redirect('/home'); } - return $next($request); } } diff --git a/app/Http/routes.php b/app/Http/routes.php index 3dc0271c..960b7034 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -37,15 +37,15 @@ Route::get('/tracks/random', 'TracksController@getIndex'); Route::get('tracks/{id}-{slug}', 'TracksController@getTrack'); Route::get('tracks/{id}-{slug}/edit', 'TracksController@getEdit'); Route::get('tracks/{id}-{slug}/stats', 'StatsController@getIndex'); -Route::get('t{id}', 'TracksController@getShortlink' )->where('id', '\d+'); -Route::get('t{id}/embed', 'TracksController@getEmbed' ); -Route::get('t{id}/stream.{extension}', 'TracksController@getStream' ); -Route::get('t{id}/dl.{extension}', 'TracksController@getDownload' ); +Route::get('t{id}', 'TracksController@getShortlink')->where('id', '\d+'); +Route::get('t{id}/embed', 'TracksController@getEmbed'); +Route::get('t{id}/stream.{extension}', 'TracksController@getStream'); +Route::get('t{id}/dl.{extension}', 'TracksController@getDownload'); Route::get('albums', 'AlbumsController@getIndex'); Route::get('albums/{id}-{slug}', 'AlbumsController@getShow'); Route::get('a{id}', 'AlbumsController@getShortlink')->where('id', '\d+'); -Route::get('a{id}/dl.{extension}', 'AlbumsController@getDownload' ); +Route::get('a{id}/dl.{extension}', 'AlbumsController@getDownload'); Route::get('artists', 'ArtistsController@getIndex'); Route::get('playlists', 'PlaylistsController@getIndex'); @@ -55,9 +55,15 @@ Route::get('/login', 'AuthController@getLogin'); Route::post('/auth/logout', 'AuthController@postLogout'); Route::get('/auth/oauth', 'AuthController@getOAuth'); -Route::get('/about', function() { return View::make('pages.about'); }); -Route::get('/faq', function() { return View::make('pages.faq'); }); -Route::get('/mlpforums-advertising-program', function() { return View::make('pages.mlpforums-advertising-program'); }); +Route::get('/about', function () { + return View::make('pages.about'); +}); +Route::get('/faq', function () { + return View::make('pages.faq'); +}); +Route::get('/mlpforums-advertising-program', function () { + return View::make('pages.mlpforums-advertising-program'); +}); Route::get('i{id}/{type}.{extension}', 'ImagesController@getImage')->where('id', '\d+'); @@ -69,18 +75,18 @@ Route::get('notifications', 'AccountController@getNotifications'); -Route::group(['prefix' => 'api/v1', 'middleware' => 'json-exceptions'], function() { +Route::group(['prefix' => 'api/v1', 'middleware' => 'json-exceptions'], function () { Route::get('/tracks/radio-details/{hash}', 'Api\V1\TracksController@getTrackRadioDetails'); Route::post('/tracks/radio-details/{hash}', 'Api\V1\TracksController@getTrackRadioDetails'); - Route::group(['middleware' => 'auth.oauth:ponyfm:tracks:upload'], function() { + Route::group(['middleware' => 'auth.oauth:ponyfm:tracks:upload'], function () { Route::post('tracks', 'Api\V1\TracksController@postUploadTrack'); Route::get('/tracks/{id}/upload-status', 'Api\V1\TracksController@getUploadStatus'); }); }); -Route::group(['prefix' => 'api/web'], function() { +Route::group(['prefix' => 'api/web'], function () { Route::get('/taxonomies/all', 'Api\Web\TaxonomiesController@getAll'); Route::get('/search', 'Api\Web\SearchController@getSearch'); @@ -108,7 +114,7 @@ Route::group(['prefix' => 'api/web'], function() { Route::get('/dashboard', 'Api\Web\DashboardController@getIndex'); - Route::group(['middleware' => 'auth'], function() { + Route::group(['middleware' => 'auth'], function () { Route::post('/tracks/upload', 'Api\Web\TracksController@postUpload'); Route::get('/tracks/{id}/upload-status', 'Api\Web\TracksController@getUploadStatus'); Route::post('/tracks/delete/{id}', 'Api\Web\TracksController@postDelete'); @@ -170,7 +176,7 @@ Route::group(['prefix' => 'api/web'], function() { Route::get('/favourites/playlists', 'Api\Web\FavouritesController@getPlaylists'); }); - Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function() { + Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function () { Route::get('/genres', 'Api\Web\GenresController@getIndex'); Route::post('/genres', 'Api\Web\GenresController@postCreate'); Route::put('/genres/{id}', 'Api\Web\GenresController@putRename')->where('id', '\d+'); @@ -189,7 +195,7 @@ Route::group(['prefix' => 'api/web'], function() { }); -Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function() { +Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function () { Route::get('/genres', 'AdminController@getGenres'); Route::get('/tracks', 'AdminController@getTracks'); Route::get('/tracks/unclassified', 'AdminController@getClassifierQueue'); @@ -202,13 +208,13 @@ Route::get('u{id}', 'ArtistsController@getShortlink')->where('id', '\d+'); Route::get('users/{id}-{slug}', 'ArtistsController@getShortlink')->where('id', '\d+'); -Route::group(['prefix' => '{slug}'], function() { +Route::group(['prefix' => '{slug}'], function () { Route::get('/', 'ArtistsController@getProfile'); Route::get('/content', 'ArtistsController@getContent'); Route::get('/favourites', 'ArtistsController@getFavourites'); - Route::group(['prefix' => 'account', 'middleware' => 'auth'], function() { + Route::group(['prefix' => 'account', 'middleware' => 'auth'], function () { Route::get('/tracks', 'ContentController@getTracks'); Route::get('/tracks/edit/{id}', 'ContentController@getTracks'); Route::get('/albums', 'ContentController@getAlbums'); @@ -224,7 +230,7 @@ Route::group(['prefix' => '{slug}'], function() { Route::get('/', 'HomeController@getIndex'); -Route::group(['domain' => 'api.pony.fm'], function() { +Route::group(['domain' => 'api.pony.fm'], function () { Route::get('tracks/latest', ['uses' => 'Api\Mobile\TracksController@latest']); Route::get('tracks/popular', [ 'uses' => 'Api\Mobile\TracksController@popular']); }); diff --git a/app/Jobs/DeleteGenre.php b/app/Jobs/DeleteGenre.php index 94a21ab2..30a33a71 100644 --- a/app/Jobs/DeleteGenre.php +++ b/app/Jobs/DeleteGenre.php @@ -24,12 +24,11 @@ use Auth; use DB; use Poniverse\Ponyfm\Models\Genre; use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; use Poniverse\Ponyfm\Models\Track; use SerializesModels; -class DeleteGenre extends Job implements SelfHandling, ShouldQueue +class DeleteGenre extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; @@ -68,7 +67,7 @@ class DeleteGenre extends Job implements SelfHandling, ShouldQueue // This is done instead of a single UPDATE query in order to // generate revision logs for the change. - $this->genreToDelete->tracks()->chunk(200, function($tracks) { + $this->genreToDelete->tracks()->chunk(200, function ($tracks) { foreach ($tracks as $track) { /** @var Track $track */ diff --git a/app/Jobs/DeleteShowSong.php b/app/Jobs/DeleteShowSong.php index 970a9657..364d88d0 100644 --- a/app/Jobs/DeleteShowSong.php +++ b/app/Jobs/DeleteShowSong.php @@ -24,12 +24,11 @@ use Auth; use DB; use Poniverse\Ponyfm\Models\ShowSong; use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; use Poniverse\Ponyfm\Models\Track; use SerializesModels; -class DeleteShowSong extends Job implements SelfHandling, ShouldQueue +class DeleteShowSong extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; @@ -64,7 +63,7 @@ class DeleteShowSong extends Job implements SelfHandling, ShouldQueue // This is done instead of a single UPDATE query in order to // generate revision logs for the change. - $this->songToDelete->tracks()->chunk(200, function($tracks) { + $this->songToDelete->tracks()->chunk(200, function ($tracks) { foreach ($tracks as $track) { /** @var Track $track */ $oldSongs = $track->showSongs; diff --git a/app/Jobs/EncodeTrackFile.php b/app/Jobs/EncodeTrackFile.php index ad3e88e0..f609e133 100644 --- a/app/Jobs/EncodeTrackFile.php +++ b/app/Jobs/EncodeTrackFile.php @@ -25,7 +25,6 @@ use Carbon\Carbon; use Config; use DB; use File; -use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; @@ -36,7 +35,7 @@ use Poniverse\Ponyfm\Models\TrackFile; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; -class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue +class EncodeTrackFile extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; /** @@ -70,8 +69,7 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue */ public function __construct(TrackFile $trackFile, $isExpirable, $autoPublish = false, $isForUpload = false, $isReplacingTrack = false) { - if ( - (!$isForUpload && $trackFile->is_master) || + if ((!$isForUpload && $trackFile->is_master) || ($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless']) ) { throw new InvalidEncodeOptionsException("Master files cannot be encoded unless we're generating a lossless master file during the upload process."); @@ -97,7 +95,6 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue if ($this->trackFile->status === TrackFile::STATUS_PROCESSING) { Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is already being processed!'); return; - } elseif (!$this->trackFile->is_expired && File::exists($this->trackFile->getFile())) { Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is still valid! No need to re-encode it.'); return; diff --git a/app/Jobs/Job.php b/app/Jobs/Job.php index 4b215d15..2a0a779a 100644 --- a/app/Jobs/Job.php +++ b/app/Jobs/Job.php @@ -44,7 +44,8 @@ abstract class Job * method. It ensures that we don't lose the in-memory database during * testing by disconnecting from it - which causes tests to fail. */ - protected function beforeHandle() { + protected function beforeHandle() + { if (App::environment() !== 'testing') { DB::reconnect(); } diff --git a/app/Jobs/SendNotifications.php b/app/Jobs/SendNotifications.php index 53d1080d..8758d568 100644 --- a/app/Jobs/SendNotifications.php +++ b/app/Jobs/SendNotifications.php @@ -23,14 +23,13 @@ namespace Poniverse\Ponyfm\Jobs; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Poniverse\Ponyfm\Jobs\Job; -use Illuminate\Contracts\Bus\SelfHandling; use Poniverse\Ponyfm\Library\Notifications\Drivers\AbstractDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\NativeDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\PonyfmDriver; use Poniverse\Ponyfm\Models\User; use SerializesModels; -class SendNotifications extends Job implements SelfHandling, ShouldQueue +class SendNotifications extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; diff --git a/app/Jobs/UpdateSearchIndexForEntity.php b/app/Jobs/UpdateSearchIndexForEntity.php index 1e2ca678..ad25cbb0 100644 --- a/app/Jobs/UpdateSearchIndexForEntity.php +++ b/app/Jobs/UpdateSearchIndexForEntity.php @@ -26,10 +26,9 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Queue\InteractsWithQueue; use Poniverse\Ponyfm\Contracts\Searchable; use Poniverse\Ponyfm\Jobs\Job; -use Illuminate\Contracts\Bus\SelfHandling; use SerializesModels; -class UpdateSearchIndexForEntity extends Job implements SelfHandling, ShouldQueue +class UpdateSearchIndexForEntity extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; diff --git a/app/Jobs/UpdateTagsForRenamedGenre.php b/app/Jobs/UpdateTagsForRenamedGenre.php index 2ce9a037..84ccbf10 100644 --- a/app/Jobs/UpdateTagsForRenamedGenre.php +++ b/app/Jobs/UpdateTagsForRenamedGenre.php @@ -26,7 +26,6 @@ use DB; use Log; use Poniverse\Ponyfm\Models\Genre; use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; use Poniverse\Ponyfm\Models\Track; use SerializesModels; @@ -39,7 +38,7 @@ use SerializesModels; * * @package Poniverse\Ponyfm\Jobs */ -class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue +class UpdateTagsForRenamedGenre extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; @@ -77,13 +76,12 @@ class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue Log::info("Tag updates for the \"{$this->genreThatWasRenamed->name}\" genre are currently in progress! Will try again in 30 seconds."); $this->release(30); return; - } else { Cache::forever($this->lockKey, true); } - $this->genreThatWasRenamed->tracks()->chunk(200, function($tracks) { + $this->genreThatWasRenamed->tracks()->chunk(200, function ($tracks) { foreach ($tracks as $track) { /** @var Track $track */ $track->updateTags(); diff --git a/app/Jobs/UpdateTagsForRenamedShowSong.php b/app/Jobs/UpdateTagsForRenamedShowSong.php index 15b84da4..cc511341 100644 --- a/app/Jobs/UpdateTagsForRenamedShowSong.php +++ b/app/Jobs/UpdateTagsForRenamedShowSong.php @@ -25,7 +25,6 @@ use Cache; use Log; use Poniverse\Ponyfm\Models\ShowSong; use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldQueue; use Poniverse\Ponyfm\Models\Track; use SerializesModels; @@ -38,7 +37,7 @@ use SerializesModels; * * @package Poniverse\Ponyfm\Jobs */ -class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQueue +class UpdateTagsForRenamedShowSong extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; @@ -76,13 +75,12 @@ class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQu Log::info("Tag updates for the \"{$this->songThatWasRenamed->title}\" song are currently in progress! Will try again in 30 seconds."); $this->release(30); return; - } else { Cache::forever($this->lockKey, true); } - $this->songThatWasRenamed->tracks()->chunk(200, function($tracks) { + $this->songThatWasRenamed->tracks()->chunk(200, function ($tracks) { foreach ($tracks as $track) { /** @var Track $track */ $track->updateTags(); diff --git a/app/Library/Assets.php b/app/Library/Assets.php index 5c3c1404..e80f3915 100644 --- a/app/Library/Assets.php +++ b/app/Library/Assets.php @@ -20,7 +20,8 @@ class Assets { - public static function scriptIncludes(string $area) { + public static function scriptIncludes(string $area) + { $scriptTags = ''; if ('app' === $area) { diff --git a/app/Library/AudioCache.php b/app/Library/AudioCache.php index aa1440d3..77f29172 100644 --- a/app/Library/AudioCache.php +++ b/app/Library/AudioCache.php @@ -20,7 +20,7 @@ class AudioCache { - private static $_movieCache = array(); + private static $_movieCache = []; public static function get(string $filename):FFmpegMovie { diff --git a/app/Library/File.php b/app/Library/File.php index 2f5034b7..a728f390 100644 --- a/app/Library/File.php +++ b/app/Library/File.php @@ -28,5 +28,4 @@ class File extends \Illuminate\Support\Facades\File return $response; } - } diff --git a/app/Library/Helpers.php b/app/Library/Helpers.php index d9b004c0..b328d7ff 100644 --- a/app/Library/Helpers.php +++ b/app/Library/Helpers.php @@ -47,7 +47,7 @@ class Helpers return '0 MB'; } - $units = array('B', 'KB', 'MB', 'GB', 'TB'); + $units = ['B', 'KB', 'MB', 'GB', 'TB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); @@ -82,7 +82,8 @@ class Helpers * @param array[int] $rgb RGB values in an array * @return string */ - public static function rgb2hex($rgb) { + public static function rgb2hex($rgb) + { $hex = "#"; $hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT); $hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT); diff --git a/app/Library/Notifications/Drivers/AbstractDriver.php b/app/Library/Notifications/Drivers/AbstractDriver.php index f6443850..88b3002d 100644 --- a/app/Library/Notifications/Drivers/AbstractDriver.php +++ b/app/Library/Notifications/Drivers/AbstractDriver.php @@ -25,10 +25,12 @@ use Poniverse\Ponyfm\Contracts\NotificationHandler; use Poniverse\Ponyfm\Library\Notifications\RecipientFinder; use Poniverse\Ponyfm\Models\User; -abstract class AbstractDriver implements NotificationHandler { +abstract class AbstractDriver implements NotificationHandler +{ private $recipientFinder; - public function __construct() { + public function __construct() + { $this->recipientFinder = new RecipientFinder(get_class($this)); } @@ -41,7 +43,8 @@ abstract class AbstractDriver implements NotificationHandler { * @param array $notificationData * @return User[] collection of {@link User} objects */ - protected function getRecipients(string $notificationType, array $notificationData) { + protected function getRecipients(string $notificationType, array $notificationData) + { return call_user_func_array([$this->recipientFinder, $notificationType], $notificationData); } } diff --git a/app/Library/Notifications/Drivers/NativeDriver.php b/app/Library/Notifications/Drivers/NativeDriver.php index c340b5e9..d17674c1 100644 --- a/app/Library/Notifications/Drivers/NativeDriver.php +++ b/app/Library/Notifications/Drivers/NativeDriver.php @@ -20,7 +20,6 @@ namespace Poniverse\Ponyfm\Library\Notifications\Drivers; - use Config; use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Models\Activity; @@ -30,7 +29,8 @@ use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\User; use Minishlink\WebPush\WebPush; -class NativeDriver extends AbstractDriver { +class NativeDriver extends AbstractDriver +{ /** * Method for sending notifications to devices * @@ -40,9 +40,9 @@ class NativeDriver extends AbstractDriver { private function pushNotifications(Activity $activity, $recipients) { if (Config::get('ponyfm.gcm_key') != 'default') { - $apiKeys = array( + $apiKeys = [ 'GCM' => Config::get('ponyfm.gcm_key'), - ); + ]; $webPush = new WebPush($apiKeys); @@ -72,7 +72,8 @@ class NativeDriver extends AbstractDriver { /** * @inheritdoc */ - public function publishedNewTrack(Track $track) { + public function publishedNewTrack(Track $track) + { $activity = Activity::where('user_id', $track->user_id) ->where('activity_type', Activity::TYPE_PUBLISHED_TRACK) ->where('resource_id', $track->id) @@ -85,7 +86,8 @@ class NativeDriver extends AbstractDriver { /** * @inheritdoc */ - public function publishedNewPlaylist(Playlist $playlist) { + public function publishedNewPlaylist(Playlist $playlist) + { $activity = Activity::where('user_id', $playlist->user_id) ->where('activity_type', Activity::TYPE_PUBLISHED_PLAYLIST) ->where('resource_id', $playlist->id) @@ -94,7 +96,8 @@ class NativeDriver extends AbstractDriver { $this->pushNotifications($activity, $this->getRecipients(__FUNCTION__, func_get_args())); } - public function newFollower(User $userBeingFollowed, User $follower) { + public function newFollower(User $userBeingFollowed, User $follower) + { $activity = Activity::where('user_id', $follower->id) ->where('activity_type', Activity::TYPE_NEW_FOLLOWER) ->where('resource_id', $userBeingFollowed->id) @@ -106,7 +109,8 @@ class NativeDriver extends AbstractDriver { /** * @inheritdoc */ - public function newComment(Comment $comment) { + public function newComment(Comment $comment) + { $activity = Activity::where('user_id', $comment->user_id) ->where('activity_type', Activity::TYPE_NEW_COMMENT) ->where('resource_id', $comment->id) @@ -118,7 +122,8 @@ class NativeDriver extends AbstractDriver { /** * @inheritdoc */ - public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { + public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) + { $activity = Activity::where('user_id', $favouriter->id) ->where('activity_type', Activity::TYPE_CONTENT_FAVOURITED) ->where('resource_id', $entityBeingFavourited->id) diff --git a/app/Library/Notifications/Drivers/PonyfmDriver.php b/app/Library/Notifications/Drivers/PonyfmDriver.php index 342db8f8..521bcc82 100644 --- a/app/Library/Notifications/Drivers/PonyfmDriver.php +++ b/app/Library/Notifications/Drivers/PonyfmDriver.php @@ -20,7 +20,6 @@ namespace Poniverse\Ponyfm\Library\Notifications\Drivers; - use ArrayAccess; use Carbon\Carbon; use Poniverse\Ponyfm\Contracts\Favouritable; @@ -31,14 +30,16 @@ use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\User; -class PonyfmDriver extends AbstractDriver { +class PonyfmDriver extends AbstractDriver +{ /** * A helper method for bulk insertion of notification records. * * @param int $activityId * @param User[] $recipients collection of {@link User} objects */ - private function insertNotifications(int $activityId, $recipients) { + private function insertNotifications(int $activityId, $recipients) + { $notifications = []; foreach ($recipients as $recipient) { $notifications[] = [ @@ -52,7 +53,8 @@ class PonyfmDriver extends AbstractDriver { /** * @inheritdoc */ - public function publishedNewTrack(Track $track) { + public function publishedNewTrack(Track $track) + { $activity = Activity::create([ 'created_at' => Carbon::now(), 'user_id' => $track->user_id, @@ -67,7 +69,8 @@ class PonyfmDriver extends AbstractDriver { /** * @inheritdoc */ - public function publishedNewPlaylist(Playlist $playlist) { + public function publishedNewPlaylist(Playlist $playlist) + { $activity = Activity::create([ 'created_at' => Carbon::now(), 'user_id' => $playlist->user_id, @@ -79,7 +82,8 @@ class PonyfmDriver extends AbstractDriver { $this->insertNotifications($activity->id, $this->getRecipients(__FUNCTION__, func_get_args())); } - public function newFollower(User $userBeingFollowed, User $follower) { + public function newFollower(User $userBeingFollowed, User $follower) + { $activity = Activity::create([ 'created_at' => Carbon::now(), 'user_id' => $follower->id, @@ -94,7 +98,8 @@ class PonyfmDriver extends AbstractDriver { /** * @inheritdoc */ - public function newComment(Comment $comment) { + public function newComment(Comment $comment) + { $activity = Activity::create([ 'created_at' => Carbon::now(), 'user_id' => $comment->user_id, @@ -109,7 +114,8 @@ class PonyfmDriver extends AbstractDriver { /** * @inheritdoc */ - public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { + public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) + { $activity = Activity::create([ 'created_at' => Carbon::now(), 'user_id' => $favouriter->id, diff --git a/app/Library/Notifications/NotificationManager.php b/app/Library/Notifications/NotificationManager.php index 13ac744d..aa06a0fa 100644 --- a/app/Library/Notifications/NotificationManager.php +++ b/app/Library/Notifications/NotificationManager.php @@ -20,7 +20,6 @@ namespace Poniverse\Ponyfm\Library\Notifications; - use Illuminate\Foundation\Bus\DispatchesJobs; use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\NotificationHandler; @@ -39,45 +38,52 @@ use Poniverse\Ponyfm\Models\User; * All the heavy lifting happens asynchronously in the {@link SendNotifications} * job and the notification drivers. */ -class NotificationManager implements NotificationHandler { +class NotificationManager implements NotificationHandler +{ use DispatchesJobs; - private function dispatchNotification(string $notificationType, array $notificationData) { - $this->dispatch( (new SendNotifications($notificationType, $notificationData))->onQueue('notifications') ); + private function dispatchNotification(string $notificationType, array $notificationData) + { + $this->dispatch((new SendNotifications($notificationType, $notificationData))->onQueue('notifications')); } /** * @inheritdoc */ - public function publishedNewTrack(Track $track) { + public function publishedNewTrack(Track $track) + { $this->dispatchNotification(__FUNCTION__, func_get_args()); } /** * @inheritdoc */ - public function publishedNewPlaylist(Playlist $playlist) { + public function publishedNewPlaylist(Playlist $playlist) + { $this->dispatchNotification(__FUNCTION__, func_get_args()); } /** * @inheritdoc */ - public function newFollower(User $userBeingFollowed, User $follower) { + public function newFollower(User $userBeingFollowed, User $follower) + { $this->dispatchNotification(__FUNCTION__, func_get_args()); } /** * @inheritdoc */ - public function newComment(Comment $comment) { + public function newComment(Comment $comment) + { $this->dispatchNotification(__FUNCTION__, func_get_args()); } /** * @inheritdoc */ - public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { + public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) + { $this->dispatchNotification(__FUNCTION__, func_get_args()); } } diff --git a/app/Library/Notifications/RecipientFinder.php b/app/Library/Notifications/RecipientFinder.php index 94f8e022..d0710e4c 100644 --- a/app/Library/Notifications/RecipientFinder.php +++ b/app/Library/Notifications/RecipientFinder.php @@ -20,7 +20,6 @@ namespace Poniverse\Ponyfm\Library\Notifications; - use Illuminate\Foundation\Bus\DispatchesJobs; use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\NotificationHandler; @@ -36,28 +35,32 @@ use Poniverse\Ponyfm\Models\User; /** * Class RecipientFinder * @package Poniverse\Ponyfm\Library\Notifications - * + * * This class returns a list of users who are to receive a particular notification. * It is instantiated on a per-driver basis. */ -class RecipientFinder implements NotificationHandler { +class RecipientFinder implements NotificationHandler +{ /** * @var string class name of a notification driver */ private $notificationDriver; - public function __construct(string $notificationDriver) { + public function __construct(string $notificationDriver) + { $this->notificationDriver = $notificationDriver; } - private function fail() { + private function fail() + { throw new \InvalidArgumentException("Unknown notification driver given: {$this->notificationDriver}"); } /** * @inheritdoc */ - public function publishedNewTrack(Track $track) { + public function publishedNewTrack(Track $track) + { switch ($this->notificationDriver) { case PonyfmDriver::class: return $track->user->followers; @@ -84,7 +87,8 @@ class RecipientFinder implements NotificationHandler { /** * @inheritdoc */ - public function publishedNewPlaylist(Playlist $playlist) { + public function publishedNewPlaylist(Playlist $playlist) + { switch ($this->notificationDriver) { case PonyfmDriver::class: return $playlist->user->followers; @@ -111,7 +115,8 @@ class RecipientFinder implements NotificationHandler { /** * @inheritdoc */ - public function newFollower(User $userBeingFollowed, User $follower) { + public function newFollower(User $userBeingFollowed, User $follower) + { switch ($this->notificationDriver) { case PonyfmDriver::class: return [$userBeingFollowed]; @@ -125,7 +130,8 @@ class RecipientFinder implements NotificationHandler { /** * @inheritdoc */ - public function newComment(Comment $comment) { + public function newComment(Comment $comment) + { switch ($this->notificationDriver) { case PonyfmDriver::class: return @@ -142,7 +148,8 @@ class RecipientFinder implements NotificationHandler { /** * @inheritdoc */ - public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { + public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) + { switch ($this->notificationDriver) { case PonyfmDriver::class: return diff --git a/app/Library/PfmValidator.php b/app/Library/PfmValidator.php index 508f2d4d..5635cba7 100644 --- a/app/Library/PfmValidator.php +++ b/app/Library/PfmValidator.php @@ -257,7 +257,7 @@ class PfmValidator extends Illuminate\Validation\Validator /** OLD CODE * public function validate_required_when($attribute, $value, $parameters) * { - * if ( Input::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){ + * if ( Request::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){ * return true; * * } else { @@ -269,7 +269,7 @@ class PfmValidator extends Illuminate\Validation\Validator // custom required_when validator public function validateRequiredWhen($attribute, $value, $parameters) { - if (Input::get($parameters[0]) == $parameters[1]) { + if (Request::get($parameters[0]) == $parameters[1]) { return $this->validate_required($attribute, $value); } diff --git a/app/Library/Poniverse/AccessTokenInfo.php b/app/Library/Poniverse/AccessTokenInfo.php index 6c9d3917..2e522564 100644 --- a/app/Library/Poniverse/AccessTokenInfo.php +++ b/app/Library/Poniverse/AccessTokenInfo.php @@ -28,7 +28,8 @@ namespace Poniverse; * @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06 * @package Poniverse */ -class AccessTokenInfo { +class AccessTokenInfo +{ protected $token; protected $isActive; @@ -42,21 +43,24 @@ class AccessTokenInfo { protected $issuer; protected $tokenType; - public function __construct($accessToken) { + public function __construct($accessToken) + { $this->token = $accessToken; } /** * @return mixed */ - public function getToken() { + public function getToken() + { return $this->token; } /** * @return bool */ - public function getIsActive() { + public function getIsActive() + { return $this->isActive; } @@ -64,7 +68,8 @@ class AccessTokenInfo { * @param bool $isActive * @return AccessTokenInfo */ - public function setIsActive($isActive) { + public function setIsActive($isActive) + { $this->isActive = $isActive; return $this; } @@ -72,7 +77,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getExpiresAt() { + public function getExpiresAt() + { return $this->expiresAt; } @@ -80,7 +86,8 @@ class AccessTokenInfo { * @param mixed $expiresAt * @return AccessTokenInfo */ - public function setExpiresAt($expiresAt) { + public function setExpiresAt($expiresAt) + { $this->expiresAt = $expiresAt; return $this; } @@ -88,7 +95,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getIssuedAt() { + public function getIssuedAt() + { return $this->issuedAt; } @@ -96,7 +104,8 @@ class AccessTokenInfo { * @param mixed $issuedAt * @return AccessTokenInfo */ - public function setIssuedAt($issuedAt) { + public function setIssuedAt($issuedAt) + { $this->issuedAt = $issuedAt; return $this; } @@ -104,7 +113,8 @@ class AccessTokenInfo { /** * @return array */ - public function getScopes() { + public function getScopes() + { return $this->scopes; } @@ -112,7 +122,8 @@ class AccessTokenInfo { * @param array|string $scopes * @return AccessTokenInfo */ - public function setScopes($scopes) { + public function setScopes($scopes) + { if (is_array($scopes)) { $this->scopes = $scopes; } else { @@ -125,7 +136,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getClientId() { + public function getClientId() + { return $this->clientId; } @@ -133,7 +145,8 @@ class AccessTokenInfo { * @param mixed $clientId * @return AccessTokenInfo */ - public function setClientId($clientId) { + public function setClientId($clientId) + { $this->clientId = $clientId; return $this; } @@ -141,7 +154,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getSub() { + public function getSub() + { return $this->sub; } @@ -149,7 +163,8 @@ class AccessTokenInfo { * @param mixed $sub * @return AccessTokenInfo */ - public function setSub($sub) { + public function setSub($sub) + { $this->sub = $sub; return $this; } @@ -157,7 +172,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getUserId() { + public function getUserId() + { return $this->userId; } @@ -165,7 +181,8 @@ class AccessTokenInfo { * @param mixed $userId * @return AccessTokenInfo */ - public function setUserId($userId) { + public function setUserId($userId) + { $this->userId = $userId; return $this; } @@ -173,7 +190,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getIntendedAudience() { + public function getIntendedAudience() + { return $this->intendedAudience; } @@ -181,7 +199,8 @@ class AccessTokenInfo { * @param mixed $intendedAudience * @return AccessTokenInfo */ - public function setIntendedAudience($intendedAudience) { + public function setIntendedAudience($intendedAudience) + { $this->intendedAudience = $intendedAudience; return $this; } @@ -189,7 +208,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getIssuer() { + public function getIssuer() + { return $this->issuer; } @@ -197,7 +217,8 @@ class AccessTokenInfo { * @param mixed $issuer * @return AccessTokenInfo */ - public function setIssuer($issuer) { + public function setIssuer($issuer) + { $this->issuer = $issuer; return $this; } @@ -205,7 +226,8 @@ class AccessTokenInfo { /** * @return mixed */ - public function getTokenType() { + public function getTokenType() + { return $this->tokenType; } @@ -213,7 +235,8 @@ class AccessTokenInfo { * @param mixed $tokenType * @return AccessTokenInfo */ - public function setTokenType($tokenType) { + public function setTokenType($tokenType) + { $this->tokenType = $tokenType; return $this; } diff --git a/app/Library/Poniverse/Poniverse.php b/app/Library/Poniverse/Poniverse.php index b6a5ef90..8a039239 100644 --- a/app/Library/Poniverse/Poniverse.php +++ b/app/Library/Poniverse/Poniverse.php @@ -28,7 +28,8 @@ use Poniverse\Ponyfm\Exceptions\InvalidAccessTokenException; * this class is going to be a simple flat api class. */ -class Poniverse { +class Poniverse +{ protected $clientId; protected $clientSecret; protected $accessToken; @@ -108,7 +109,7 @@ class Poniverse { */ public function getUser() { - $data = \Httpful\Request::get($this->urls['api'] . "users?access_token=" . $this->accessToken ); + $data = \Httpful\Request::get($this->urls['api'] . "users?access_token=" . $this->accessToken); $result = $data->addHeader('Accept', 'application/json')->send(); diff --git a/app/Library/Poniverse/autoloader.php b/app/Library/Poniverse/autoloader.php index 54a20935..d1ee4eb0 100644 --- a/app/Library/Poniverse/autoloader.php +++ b/app/Library/Poniverse/autoloader.php @@ -102,7 +102,7 @@ class SplClassLoader */ public function register() { - spl_autoload_register(array($this, 'loadClass')); + spl_autoload_register([$this, 'loadClass']); } /** @@ -110,7 +110,7 @@ class SplClassLoader */ public function unregister() { - spl_autoload_unregister(array($this, 'loadClass')); + spl_autoload_unregister([$this, 'loadClass']); } /** @@ -131,7 +131,7 @@ class SplClassLoader } $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; - require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; + require($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; } } -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/examples/freebase.php b/app/Library/Poniverse/httpful/examples/freebase.php index bb3b528f..96e4152e 100644 --- a/app/Library/Poniverse/httpful/examples/freebase.php +++ b/app/Library/Poniverse/httpful/examples/freebase.php @@ -9,4 +9,4 @@ $response = \Httpful\Request::get($uri) ->expectsJson() ->sendIt(); -echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n"; \ No newline at end of file +echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n"; diff --git a/app/Library/Poniverse/httpful/examples/github.php b/app/Library/Poniverse/httpful/examples/github.php index 8eb3f3ba..ee98b3e0 100644 --- a/app/Library/Poniverse/httpful/examples/github.php +++ b/app/Library/Poniverse/httpful/examples/github.php @@ -6,4 +6,4 @@ use \Httpful\Request; $uri = 'https://github.com/api/v2/xml/user/show/nategood'; $request = Request::get($uri)->send(); -echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n"; \ No newline at end of file +echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n"; diff --git a/app/Library/Poniverse/httpful/examples/override.php b/app/Library/Poniverse/httpful/examples/override.php index 2c3bdd5c..1a876b4e 100644 --- a/app/Library/Poniverse/httpful/examples/override.php +++ b/app/Library/Poniverse/httpful/examples/override.php @@ -5,7 +5,7 @@ require(__DIR__ . '/../bootstrap.php'); // a parser with different configuration options for a particular mime type // Example setting a namespace for the XMLHandler parser -$conf = array('namespace' => 'http://example.com'); +$conf = ['namespace' => 'http://example.com']; \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); // We can also add the parsers with our own... @@ -41,4 +41,4 @@ class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter } } -\Httpful\Httpful::register('text/csv', new SimpleCsvHandler()); \ No newline at end of file +\Httpful\Httpful::register('text/csv', new SimpleCsvHandler()); diff --git a/app/Library/Poniverse/httpful/examples/showclix.php b/app/Library/Poniverse/httpful/examples/showclix.php index 9c50bf5f..fbc200e0 100644 --- a/app/Library/Poniverse/httpful/examples/showclix.php +++ b/app/Library/Poniverse/httpful/examples/showclix.php @@ -14,11 +14,11 @@ $response = Request::get($uri) echo "The event {$response->body->event} will take place on {$response->body->event_start}\n"; // Example overriding the default JSON handler with one that encodes the response as an array -\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true))); +\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(['decode_as_array' => true])); $response = Request::get($uri) ->expectsType('json') ->sendIt(); // Print out the event details -echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n"; \ No newline at end of file +echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n"; diff --git a/app/Library/Poniverse/httpful/src/Httpful/Bootstrap.php b/app/Library/Poniverse/httpful/src/Httpful/Bootstrap.php index 3bf62ae6..6c304c48 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Bootstrap.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Bootstrap.php @@ -21,7 +21,7 @@ class Bootstrap */ public static function init() { - spl_autoload_register(array('\Httpful\Bootstrap', 'autoload')); + spl_autoload_register(['\Httpful\Bootstrap', 'autoload']); self::registerHandlers(); } @@ -40,7 +40,7 @@ class Bootstrap */ public static function pharInit() { - spl_autoload_register(array('\Httpful\Bootstrap', 'pharAutoload')); + spl_autoload_register(['\Httpful\Bootstrap', 'pharAutoload']); self::registerHandlers(); } @@ -78,17 +78,18 @@ class Bootstrap // @todo check a conf file to load from that instead of // hardcoding into the library? - $handlers = array( + $handlers = [ \Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(), \Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(), \Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(), \Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(), - ); + ]; foreach ($handlers as $mime => $handler) { // Don't overwrite if the handler has already been registered - if (Httpful::hasParserRegistered($mime)) + if (Httpful::hasParserRegistered($mime)) { continue; + } Httpful::register($mime, $handler); } diff --git a/app/Library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php b/app/Library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php index bba73a69..aeeb84a8 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php @@ -1,7 +1,7 @@ -decode_as_array); - if (is_null($parsed)) + if (is_null($parsed)) { throw new \Exception("Unable to parse response as JSON"); + } return $parsed; } @@ -37,4 +39,4 @@ class JsonHandler extends MimeHandlerAdapter { return json_encode($payload); } -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php b/app/Library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php index dd15c04c..868bfb95 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php @@ -10,7 +10,7 @@ namespace Httpful\Handlers; class MimeHandlerAdapter { - public function __construct(array $args = array()) + public function __construct(array $args = []) { $this->init($args); } @@ -40,4 +40,4 @@ class MimeHandlerAdapter { return (string) $payload; } -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/XHtmlHandler.php b/app/Library/Poniverse/httpful/src/Httpful/Handlers/XHtmlHandler.php index 32a4d53a..95376152 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/XHtmlHandler.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Handlers/XHtmlHandler.php @@ -12,4 +12,4 @@ class XHtmlHandler extends MimeHandlerAdapter { // @todo add html specific parsing // see DomDocument::load http://docs.php.net/manual/en/domdocument.loadhtml.php -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php b/app/Library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php index 4b11659b..04610a3f 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php @@ -23,7 +23,7 @@ class XmlHandler extends MimeHandlerAdapter /** * @param array $conf sets configuration options */ - public function __construct(array $conf = array()) + public function __construct(array $conf = []) { $this->namespace = isset($conf['namespace']) ? $conf['namespace'] : ''; $this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0; @@ -36,11 +36,13 @@ class XmlHandler extends MimeHandlerAdapter */ public function parse($body) { - if (empty($body)) + if (empty($body)) { return null; + } $parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace); - if ($parsed === false) + if ($parsed === false) { throw new \Exception("Unable to parse response as XML"); + } return $parsed; } @@ -84,7 +86,7 @@ class XmlHandler extends MimeHandlerAdapter } else { $node->appendChild($dom->createTextNode($value)); } - return array($node, $dom); + return [$node, $dom]; } /** * @author Zack Douglas @@ -100,7 +102,7 @@ class XmlHandler extends MimeHandlerAdapter $parent->appendChild($el); $this->_future_serializeAsXml($v, $el, $dom); } - return array($parent, $dom); + return [$parent, $dom]; } /** * @author Zack Douglas @@ -115,6 +117,6 @@ class XmlHandler extends MimeHandlerAdapter $this->_future_serializeAsXml($pr->getValue($value), $el, $dom); } } - return array($parent, $dom); + return [$parent, $dom]; } -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Http.php b/app/Library/Poniverse/httpful/src/Httpful/Http.php index 59374e93..770a29ed 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Http.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Http.php @@ -21,7 +21,7 @@ class Http */ public static function safeMethods() { - return array(self::HEAD, self::GET, self::OPTIONS, self::TRACE); + return [self::HEAD, self::GET, self::OPTIONS, self::TRACE]; } /** @@ -50,7 +50,7 @@ class Http // Though it is possible to be idempotent, POST // is not guarunteed to be, and more often than // not, it is not. - return array(self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH); + return [self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH]; } /** @@ -80,7 +80,6 @@ class Http */ public static function canHaveBody() { - return array(self::POST, self::PUT, self::PATCH, self::OPTIONS); + return [self::POST, self::PUT, self::PATCH, self::OPTIONS]; } - -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Httpful.php b/app/Library/Poniverse/httpful/src/Httpful/Httpful.php index 98cd75a9..321b0ef2 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Httpful.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Httpful.php @@ -2,10 +2,11 @@ namespace Httpful; -class Httpful { +class Httpful +{ const VERSION = '0.2.4'; - private static $mimeRegistrar = array(); + private static $mimeRegistrar = []; private static $default = null; /** @@ -43,4 +44,4 @@ class Httpful { { return isset(self::$mimeRegistrar[$mimeType]); } -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Mime.php b/app/Library/Poniverse/httpful/src/Httpful/Mime.php index 1a7c4560..5b44b18b 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Mime.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Mime.php @@ -22,7 +22,7 @@ class Mime * Map short name for a mime type * to a full proper mime type */ - public static $mimes = array( + public static $mimes = [ 'json' => self::JSON, 'xml' => self::XML, 'form' => self::FORM, @@ -34,7 +34,7 @@ class Mime 'javascript'=> self::JS, 'yaml' => self::YAML, 'csv' => self::CSV, - ); + ]; /** * Get the full Mime Type name from a "short name". diff --git a/app/Library/Poniverse/httpful/src/Httpful/Request.php b/app/Library/Poniverse/httpful/src/Httpful/Request.php index 63b92ecb..c8ed5e80 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Request.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Request.php @@ -30,12 +30,12 @@ class Request public $uri, $method = Http::GET, - $headers = array(), + $headers = [], $raw_headers = '', $strict_ssl = false, $content_type, $expected_type, - $additional_curl_opts = array(), + $additional_curl_opts = [], $auto_parse = true, $serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART, $username, @@ -46,7 +46,7 @@ class Request $error_callback, $follow_redirects = false, $max_redirects = self::MAX_REDIRECTS_DEFAULT, - $payload_serializers = array(); + $payload_serializers = []; // Options // private $_options = array( @@ -70,7 +70,9 @@ class Request */ private function __construct($attrs = null) { - if (!is_array($attrs)) return; + if (!is_array($attrs)) { + return; + } foreach ($attrs as $attr => $value) { $this->$attr = $value; } @@ -195,8 +197,9 @@ class Request */ public function send() { - if (!$this->hasBeenInitialized()) + if (!$this->hasBeenInitialized()) { $this->_curlPrep(); + } $result = curl_exec($this->_ch); @@ -275,7 +278,8 @@ class Request /** * @return is this request setup for client side cert? */ - public function hasClientSideCert() { + public function hasClientSideCert() + { return isset($this->client_cert) && isset($this->client_key); } @@ -326,7 +330,9 @@ class Request */ public function mime($mime) { - if (empty($mime)) return $this; + if (empty($mime)) { + return $this; + } $this->content_type = $this->expected_type = Mime::getFullMime($mime); return $this; } @@ -349,7 +355,9 @@ class Request */ public function method($method) { - if (empty($method)) return $this; + if (empty($method)) { + return $this; + } $this->method = $method; return $this; } @@ -360,7 +368,9 @@ class Request */ public function expects($mime) { - if (empty($mime)) return $this; + if (empty($mime)) { + return $this; + } $this->expected_type = Mime::getFullMime($mime); return $this; } @@ -376,7 +386,9 @@ class Request */ public function contentType($mime) { - if (empty($mime)) return $this; + if (empty($mime)) { + return $this; + } $this->content_type = Mime::getFullMime($mime); return $this; } @@ -419,9 +431,10 @@ class Request * @param string $auth_username Authentication username. Default null * @param string $auth_password Authentication password. Default null */ - public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null){ + public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null) + { $this->addOnCurlOption(CURLOPT_PROXY, "{$proxy_host}:{$proxy_port}"); - if(in_array($auth_type, array(CURLAUTH_BASIC,CURLAUTH_NTLM)) ){ + if (in_array($auth_type, [CURLAUTH_BASIC,CURLAUTH_NTLM])) { $this->addOnCurlOption(CURLOPT_PROXYAUTH, $auth_type) ->addOnCurlOption(CURLOPT_PROXYUSERPWD, "{$auth_username}:{$auth_password}"); } @@ -431,7 +444,8 @@ class Request /** * @return is this request setup for using proxy? */ - public function hasProxy(){ + public function hasProxy() + { return is_string($this->additional_curl_opts[CURLOPT_PROXY]); } @@ -646,15 +660,17 @@ class Request // This method also adds the custom header support as described in the // method comments - if (count($args) === 0) + if (count($args) === 0) { return; + } // Strip the sugar. If it leads with "with", strip. // This is okay because: No defined HTTP headers begin with with, // and if you are defining a custom header, the standard is to prefix it // with an "X-", so that should take care of any collisions. - if (substr($method, 0, 4) === 'with') + if (substr($method, 0, 4) === 'with') { $method = substr($method, 4); + } // Precede upper case letters with dashes, uppercase the first letter of method $header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY))); @@ -681,7 +697,7 @@ class Request // recusion. Do not use this syntax elsewhere. // It goes against the whole readability // and transparency idea. - self::$_template = new Request(array('method' => Http::GET)); + self::$_template = new Request(['method' => Http::GET]); // This is more like it... self::$_template @@ -695,11 +711,13 @@ class Request */ private function _setDefaults() { - if (!isset(self::$_template)) + if (!isset(self::$_template)) { self::_initializeDefaults(); - foreach (self::$_template as $k=>$v) { - if ($k[0] != '_') + } + foreach (self::$_template as $k => $v) { + if ($k[0] != '_') { $this->$k = $v; + } } return $this; } @@ -725,8 +743,9 @@ class Request Bootstrap::init(); // Setup the default template if need be - if (!isset(self::$_template)) + if (!isset(self::$_template)) { self::_initializeDefaults(); + } $request = new Request(); return $request @@ -745,8 +764,9 @@ class Request public function _curlPrep() { // Check for required stuff - if (!isset($this->uri)) + if (!isset($this->uri)) { throw new \Exception('Attempting to send a request before defining a URI endpoint.'); + } $ch = curl_init($this->uri); @@ -757,18 +777,19 @@ class Request } if ($this->hasClientSideCert()) { - - if (!file_exists($this->client_key)) + if (!file_exists($this->client_key)) { throw new \Exception('Could not read Client Key'); + } - if (!file_exists($this->client_cert)) + if (!file_exists($this->client_cert)) { throw new \Exception('Could not read Client Certificate'); + } - curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding); - curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding); - curl_setopt($ch, CURLOPT_SSLCERT, $this->client_cert); - curl_setopt($ch, CURLOPT_SSLKEY, $this->client_key); - curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->client_passphrase); + curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding); + curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding); + curl_setopt($ch, CURLOPT_SSLCERT, $this->client_cert); + curl_setopt($ch, CURLOPT_SSLKEY, $this->client_key); + curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->client_passphrase); // curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->client_cert_passphrase); } @@ -792,7 +813,7 @@ class Request $this->headers['Content-Length'] = strlen($this->serialized_payload); } - $headers = array(); + $headers = []; // https://github.com/nategood/httpful/issues/37 // Except header removes any HTTP 1.1 Continue from response headers $headers[] = 'Expect:'; @@ -851,7 +872,8 @@ class Request return $this; } - public function buildUserAgent() { + public function buildUserAgent() + { $user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/'; $curl = \curl_version(); @@ -864,8 +886,11 @@ class Request $user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')'; if (isset($_SERVER['SERVER_SOFTWARE'])) { - $user_agent .= ' ' . \preg_replace('~PHP/[\d\.]+~U', '', - $_SERVER['SERVER_SOFTWARE']); + $user_agent .= ' ' . \preg_replace( + '~PHP/[\d\.]+~U', + '', + $_SERVER['SERVER_SOFTWARE'] + ); } else { if (isset($_SERVER['TERM_PROGRAM'])) { $user_agent .= " {$_SERVER['TERM_PROGRAM']}"; @@ -915,12 +940,14 @@ class Request */ private function _serializePayload($payload) { - if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) + if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) { return $payload; + } // When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized - if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) + if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) { return $payload; + } // Use a custom serializer if one is registered for this mime type if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) { diff --git a/app/Library/Poniverse/httpful/src/Httpful/Response.php b/app/Library/Poniverse/httpful/src/Httpful/Response.php index c5199d3e..d130198b 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Response.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Response.php @@ -100,7 +100,7 @@ class Response : $this->parent_type; } - return Httpful::get($parse_with)->parse($body); + return Httpful::get($parse_with)->parse($body); } /** @@ -112,7 +112,7 @@ class Response public function _parseHeaders($headers) { $headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY); - $parse_headers = array(); + $parse_headers = []; for ($i = 1; $i < count($headers); $i++) { list($key, $raw_value) = explode(':', $headers[$i], 2); $key = trim($key); diff --git a/app/Library/Poniverse/httpful/src/Httpful/Response/Headers.php b/app/Library/Poniverse/httpful/src/Httpful/Response/Headers.php index 7abc57dd..f7b1f7ab 100644 --- a/app/Library/Poniverse/httpful/src/Httpful/Response/Headers.php +++ b/app/Library/Poniverse/httpful/src/Httpful/Response/Headers.php @@ -2,7 +2,8 @@ namespace Httpful\Response; -final class Headers implements \ArrayAccess, \Countable { +final class Headers implements \ArrayAccess, \Countable +{ private $headers; @@ -15,7 +16,7 @@ final class Headers implements \ArrayAccess, \Countable { { $lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY); array_shift($lines); // HTTP HEADER - $headers = array(); + $headers = []; foreach ($lines as $line) { list($name, $value) = explode(':', $line, 2); $headers[strtolower(trim($name))] = trim($value); @@ -54,5 +55,4 @@ final class Headers implements \ArrayAccess, \Countable { { return $this->headers; } - -} \ No newline at end of file +} diff --git a/app/Library/Poniverse/httpful/tests/Httpful/HttpfulTest.php b/app/Library/Poniverse/httpful/tests/Httpful/HttpfulTest.php index ac2ab546..0478af2f 100644 --- a/app/Library/Poniverse/httpful/tests/Httpful/HttpfulTest.php +++ b/app/Library/Poniverse/httpful/tests/Httpful/HttpfulTest.php @@ -25,34 +25,34 @@ class HttpfulTest extends \PHPUnit_Framework_TestCase const TEST_URL_400 = 'http://127.0.0.1:8008/400'; const SAMPLE_JSON_HEADER = -"HTTP/1.1 200 OK + "HTTP/1.1 200 OK Content-Type: application/json Connection: keep-alive Transfer-Encoding: chunked\r\n"; const SAMPLE_JSON_RESPONSE = '{"key":"value","object":{"key":"value"},"array":[1,2,3,4]}'; const SAMPLE_CSV_HEADER = -"HTTP/1.1 200 OK + "HTTP/1.1 200 OK Content-Type: text/csv Connection: keep-alive Transfer-Encoding: chunked\r\n"; const SAMPLE_CSV_RESPONSE = -"Key1,Key2 + "Key1,Key2 Value1,Value2 \"40.0\",\"Forty\""; const SAMPLE_XML_RESPONSE = '2a stringTRUE'; const SAMPLE_XML_HEADER = -"HTTP/1.1 200 OK + "HTTP/1.1 200 OK Content-Type: application/xml Connection: keep-alive Transfer-Encoding: chunked\r\n"; const SAMPLE_VENDOR_HEADER = -"HTTP/1.1 200 OK + "HTTP/1.1 200 OK Content-Type: application/vnd.nategood.message+xml Connection: keep-alive Transfer-Encoding: chunked\r\n"; const SAMPLE_VENDOR_TYPE = "application/vnd.nategood.message+xml"; const SAMPLE_MULTI_HEADER = -"HTTP/1.1 200 OK + "HTTP/1.1 200 OK Content-Type: application/json Connection: keep-alive Transfer-Encoding: chunked @@ -60,20 +60,20 @@ X-My-Header:Value1 X-My-Header:Value2\r\n"; function testInit() { - $r = Request::init(); + $r = Request::init(); // Did we get a 'Request' object? - $this->assertEquals('Httpful\Request', get_class($r)); + $this->assertEquals('Httpful\Request', get_class($r)); } function testMethods() { - $valid_methods = array('get', 'post', 'delete', 'put', 'options', 'head'); - $url = 'http://example.com/'; - foreach ($valid_methods as $method) { - $r = call_user_func(array('Httpful\Request', $method), $url); - $this->assertEquals('Httpful\Request', get_class($r)); - $this->assertEquals(strtoupper($method), $r->method); - } + $valid_methods = ['get', 'post', 'delete', 'put', 'options', 'head']; + $url = 'http://example.com/'; + foreach ($valid_methods as $method) { + $r = call_user_func(['Httpful\Request', $method], $url); + $this->assertEquals('Httpful\Request', get_class($r)); + $this->assertEquals(strtoupper($method), $r->method); + } } function testDefaults() @@ -87,19 +87,19 @@ X-My-Header:Value2\r\n"; function testShortMime() { // Valid short ones - $this->assertEquals(Mime::JSON, Mime::getFullMime('json')); - $this->assertEquals(Mime::XML, Mime::getFullMime('xml')); - $this->assertEquals(Mime::HTML, Mime::getFullMime('html')); - $this->assertEquals(Mime::CSV, Mime::getFullMime('csv')); + $this->assertEquals(Mime::JSON, Mime::getFullMime('json')); + $this->assertEquals(Mime::XML, Mime::getFullMime('xml')); + $this->assertEquals(Mime::HTML, Mime::getFullMime('html')); + $this->assertEquals(Mime::CSV, Mime::getFullMime('csv')); // Valid long ones $this->assertEquals(Mime::JSON, Mime::getFullMime(Mime::JSON)); - $this->assertEquals(Mime::XML, Mime::getFullMime(Mime::XML)); + $this->assertEquals(Mime::XML, Mime::getFullMime(Mime::XML)); $this->assertEquals(Mime::HTML, Mime::getFullMime(Mime::HTML)); $this->assertEquals(Mime::CSV, Mime::getFullMime(Mime::CSV)); // No false positives - $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::HTML)); + $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::HTML)); $this->assertNotEquals(Mime::JSON, Mime::getFullMime(Mime::XML)); $this->assertNotEquals(Mime::HTML, Mime::getFullMime(Mime::JSON)); $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::CSV)); @@ -239,7 +239,7 @@ X-My-Header:Value2\r\n"; $this->assertEquals($username, $r->username); $this->assertEquals($password, $r->password); $this->assertTrue($r->hasDigestAuth()); - } + } function testJsonResponseParse() { @@ -407,10 +407,13 @@ Content-Type: text/plain; charset=utf-8\r\n", $req); { // Parent type $request = Request::init()->sendsAndExpects(Mime::XML); - $response = new Response('Nathan', -"HTTP/1.1 200 OK + $response = new Response( + 'Nathan', + "HTTP/1.1 200 OK Connection: keep-alive -Transfer-Encoding: chunked\r\n", $request); +Transfer-Encoding: chunked\r\n", + $request + ); $this->assertEquals("", $response->content_type); } @@ -443,16 +446,17 @@ Transfer-Encoding: chunked\r\n", $request); // Lazy test... $prev = \Httpful\Httpful::get(\Httpful\Mime::XML); $this->assertEquals($prev, new \Httpful\Handlers\XmlHandler()); - $conf = array('namespace' => 'http://example.com'); + $conf = ['namespace' => 'http://example.com']; \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); $new = \Httpful\Httpful::get(\Httpful\Mime::XML); $this->assertNotEquals($prev, $new); } } -class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter { - public function parse($body) { +class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter +{ + public function parse($body) + { return 'custom parse'; } } - diff --git a/app/Library/Poniverse/oauth2/Client.php b/app/Library/Poniverse/oauth2/Client.php index 655595e1..49b8ec8e 100644 --- a/app/Library/Poniverse/oauth2/Client.php +++ b/app/Library/Poniverse/oauth2/Client.php @@ -135,7 +135,7 @@ class Client * * @var array */ - protected $curl_options = array(); + protected $curl_options = []; /** * Construct @@ -189,13 +189,13 @@ class Client * @param array $extra_parameters Array of extra parameters like scope or state (Ex: array('scope' => null, 'state' => '')) * @return string URL used for authentication */ - public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = array()) + public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = []) { - $parameters = array_merge(array( + $parameters = array_merge([ 'response_type' => 'code', 'client_id' => $this->client_id, 'redirect_uri' => $redirect_uri - ), $extra_parameters); + ], $extra_parameters); return $auth_endpoint . '?' . http_build_query($parameters, null, '&'); } @@ -224,7 +224,7 @@ class Client throw new Exception('Unknown constant GRANT_TYPE for class ' . $grantTypeClassName, Exception::GRANT_TYPE_ERROR); } $parameters['grant_type'] = $grantTypeClass::GRANT_TYPE; - $http_headers = array(); + $http_headers = []; switch ($this->client_auth) { case self::AUTH_TYPE_URI: case self::AUTH_TYPE_FORM: @@ -283,7 +283,7 @@ class Client * @param array $options An array specifying which options to set and their values * @return void */ - public function setCurlOptions($options) + public function setCurlOptions($options) { $this->curl_options = array_merge($this->curl_options, $options); } @@ -313,7 +313,7 @@ class Client * @param int $form_content_type HTTP form content type to use * @return array */ - public function fetch($protected_resource_url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = array(), $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) + public function fetch($protected_resource_url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = [], $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) { if ($this->access_token) { switch ($this->access_token_type) { @@ -357,8 +357,7 @@ class Client $timestamp = time(); $nonce = uniqid(); $parsed_url = parse_url($url); - if (!isset($parsed_url['port'])) - { + if (!isset($parsed_url['port'])) { $parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80; } if ($http_method == self::HTTP_METHOD_GET) { @@ -369,14 +368,17 @@ class Client } } - $signature = base64_encode(hash_hmac($this->access_token_algorithm, - $timestamp . "\n" + $signature = base64_encode(hash_hmac( + $this->access_token_algorithm, + $timestamp . "\n" . $nonce . "\n" . $http_method . "\n" . $parsed_url['path'] . "\n" . $parsed_url['host'] . "\n" - . $parsed_url['port'] . "\n\n" - , $this->access_token_secret, true)); + . $parsed_url['port'] . "\n\n", + $this->access_token_secret, + true + )); return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"'; } @@ -391,27 +393,26 @@ class Client * @param int $form_content_type HTTP form content type to use * @return array */ - private function executeRequest($url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) + private function executeRequest($url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) { - $curl_options = array( + $curl_options = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_CUSTOMREQUEST => $http_method - ); + ]; - switch($http_method) { + switch ($http_method) { case self::HTTP_METHOD_POST: $curl_options[CURLOPT_POST] = true; /* No break */ case self::HTTP_METHOD_PUT: case self::HTTP_METHOD_PATCH: - /** * Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, * while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded. * http://php.net/manual/en/function.curl-setopt.php */ - if(is_array($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) { + if (is_array($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) { $parameters = http_build_query($parameters, null, '&'); } $curl_options[CURLOPT_POSTFIELDS] = $parameters; @@ -434,8 +435,8 @@ class Client $curl_options[CURLOPT_URL] = $url; if (is_array($http_headers)) { - $header = array(); - foreach($http_headers as $key => $parsed_urlvalue) { + $header = []; + foreach ($http_headers as $key => $parsed_urlvalue) { $header[] = "$key: $parsed_urlvalue"; } $curl_options[CURLOPT_HTTPHEADER] = $header; @@ -466,11 +467,11 @@ class Client } curl_close($ch); - return array( + return [ 'result' => (null === $json_decode) ? $result : $json_decode, 'code' => $http_code, 'content_type' => $content_type - ); + ]; } /** @@ -493,7 +494,9 @@ class Client private function convertToCamelCase($grant_type) { $parts = explode('_', $grant_type); - array_walk($parts, function(&$item) { $item = ucfirst($item);}); + array_walk($parts, function (&$item) { + $item = ucfirst($item); + }); return implode('', $parts); } } diff --git a/app/Library/Poniverse/oauth2/GrantType/AuthorizationCode.php b/app/Library/Poniverse/oauth2/GrantType/AuthorizationCode.php index f3436e4c..79b79a84 100644 --- a/app/Library/Poniverse/oauth2/GrantType/AuthorizationCode.php +++ b/app/Library/Poniverse/oauth2/GrantType/AuthorizationCode.php @@ -23,15 +23,12 @@ class AuthorizationCode implements IGrantType */ public function validateParameters(&$parameters) { - if (!isset($parameters['code'])) - { + if (!isset($parameters['code'])) { throw new InvalidArgumentException( 'The \'code\' parameter must be defined for the Authorization Code grant type', InvalidArgumentException::MISSING_PARAMETER ); - } - elseif (!isset($parameters['redirect_uri'])) - { + } elseif (!isset($parameters['redirect_uri'])) { throw new InvalidArgumentException( 'The \'redirect_uri\' parameter must be defined for the Authorization Code grant type', InvalidArgumentException::MISSING_PARAMETER diff --git a/app/Library/Poniverse/oauth2/GrantType/ClientCredentials.php b/app/Library/Poniverse/oauth2/GrantType/ClientCredentials.php index c6c81f84..7ccb8586 100644 --- a/app/Library/Poniverse/oauth2/GrantType/ClientCredentials.php +++ b/app/Library/Poniverse/oauth2/GrantType/ClientCredentials.php @@ -2,20 +2,20 @@ namespace OAuth2\GrantType; /** - * Client Credentials Parameters + * Client Credentials Parameters */ class ClientCredentials implements IGrantType { /** * Defines the Grant Type - * - * @var string Defaults to 'client_credentials'. + * + * @var string Defaults to 'client_credentials'. */ const GRANT_TYPE = 'client_credentials'; /** * Adds a specific Handling of the parameters - * + * * @return array of Specific parameters to be sent. * @param mixed $parameters the parameters array (passed by reference) */ diff --git a/app/Library/Poniverse/oauth2/GrantType/IGrantType.php b/app/Library/Poniverse/oauth2/GrantType/IGrantType.php index 60631922..0f9540c4 100644 --- a/app/Library/Poniverse/oauth2/GrantType/IGrantType.php +++ b/app/Library/Poniverse/oauth2/GrantType/IGrantType.php @@ -1,13 +1,14 @@ elasticsearch = $connection; $this->index = $indexName; } @@ -43,7 +45,8 @@ class Search { * @param int $resultsPerContentType * @return array */ - public function searchAllContent(string $query) { + public function searchAllContent(string $query) + { $results = $this->elasticsearch->msearch([ 'index' => $this->index, 'body' => [ @@ -131,7 +134,8 @@ class Search { ]; } - protected function transformTracks(array $searchHits) { + protected function transformTracks(array $searchHits) + { $tracks = $this->transformToEloquent(Track::class, $searchHits); $tracks = $tracks->map(function (Track $track) { return Track::mapPublicTrackSummary($track); @@ -139,7 +143,8 @@ class Search { return $tracks; } - protected function transformAlbums(array $searchHits) { + protected function transformAlbums(array $searchHits) + { $albums = $this->transformToEloquent(Album::class, $searchHits); $albums = $albums->map(function (Album $album) { return Album::mapPublicAlbumSummary($album); @@ -147,7 +152,8 @@ class Search { return $albums; } - protected function transformPlaylists(array $searchHits) { + protected function transformPlaylists(array $searchHits) + { $playlists = $this->transformToEloquent(Playlist::class, $searchHits); $playlists = $playlists->map(function (Playlist $playlist) { return Playlist::mapPublicPlaylistSummary($playlist); @@ -155,7 +161,8 @@ class Search { return $playlists; } - protected function transformUsers(array $searchHits) { + protected function transformUsers(array $searchHits) + { $users = $this->transformToEloquent(User::class, $searchHits); $users = $users->map(function (User $user) { return User::mapPublicUserSummary($user); @@ -173,7 +180,8 @@ class Search { * @param array $searchHits * @return \Illuminate\Database\Eloquent\Collection */ - protected function transformToEloquent(string $modelClass, array $searchHits) { + protected function transformToEloquent(string $modelClass, array $searchHits) + { if (empty($searchHits)) { return new Collection(); } diff --git a/app/Library/SerializesModels.php b/app/Library/SerializesModels.php index 4de788c3..bea36833 100644 --- a/app/Library/SerializesModels.php +++ b/app/Library/SerializesModels.php @@ -27,7 +27,8 @@ use Illuminate\Contracts\Database\ModelIdentifier; * * @link https://github.com/laravel/framework/issues/9347#issuecomment-120803564 */ -trait SerializesModels { +trait SerializesModels +{ use \Illuminate\Queue\SerializesModels; /** @@ -36,7 +37,8 @@ trait SerializesModels { * @param mixed $value * @return mixed */ - protected function getRestoredPropertyValue($value) { + protected function getRestoredPropertyValue($value) + { if ($value instanceof ModelIdentifier) { return method_exists($value->class, 'withTrashed') ? (new $value->class)->withTrashed()->findOrFail($value->id) diff --git a/app/Library/ZipStream.php b/app/Library/ZipStream.php index d3ed6cb1..9696cdbc 100644 --- a/app/Library/ZipStream.php +++ b/app/Library/ZipStream.php @@ -19,7 +19,8 @@ * @link https://github.com/Grandt/PHPZip * @version 1.37 */ -class ZipStream { +class ZipStream +{ const VERSION = 1.37; const ZIP_LOCAL_FILE_HEADER = "\x50\x4b\x03\x04"; // Local file header signature @@ -35,10 +36,10 @@ class ZipStream { private $zipMemoryThreshold = 1048576; // Autocreate tempfile if the zip data exceeds 1048576 bytes (1 MB) private $zipComment = null; - private $cdRec = array(); // central directory + private $cdRec = []; // central directory private $offset = 0; - private $isFinalized = FALSE; - private $addExtraField = TRUE; + private $isFinalized = false; + private $addExtraField = true; private $streamChunkSize = 16384; // 65536; private $streamFilePath = null; @@ -54,15 +55,16 @@ class ZipStream { * @param String $archiveName Name to send to the HTTP client. * @param String $contentType Content mime type. Optional, defaults to "application/zip". */ - function __construct($archiveName = "", $contentType = "application/zip") { + function __construct($archiveName = "", $contentType = "application/zip") + { if (!function_exists('sys_get_temp_dir')) { - die ("ERROR: ZipStream " . self::VERSION . " requires PHP version 5.2.1 or above."); + die("ERROR: ZipStream " . self::VERSION . " requires PHP version 5.2.1 or above."); } $headerFile = null; $headerLine = null; if (!headers_sent($headerFile, $headerLine) or die("

Error: Unable to send file $archiveName. HTML Headers have already been sent from $headerFile in line $headerLine

")) { - if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n

Error: Unable to send file $archiveName.epub. Output buffer contains the following text (typically warnings or errors):
" . ob_get_contents() . "

")) { + if ((ob_get_contents() === false || ob_get_contents() == '') or die("\n

Error: Unable to send file $archiveName.epub. Output buffer contains the following text (typically warnings or errors):
" . ob_get_contents() . "

")) { if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } @@ -80,8 +82,9 @@ class ZipStream { } } - function __destruct() { - $this->isFinalized = TRUE; + function __destruct() + { + $this->isFinalized = true; $this->cdRec = null; exit; } @@ -92,8 +95,9 @@ class ZipStream { * * @param bool $setExtraField TRUE (default) will enable adding of extra fields, anything else will disable it. */ - function setExtraField($setExtraField = TRUE) { - $this->addExtraField = ($setExtraField === TRUE); + function setExtraField($setExtraField = true) + { + $this->addExtraField = ($setExtraField === true); } /** @@ -102,13 +106,14 @@ class ZipStream { * @param string $newComment New comment. null to clear. * @return bool $success */ - public function setComment($newComment = null) { + public function setComment($newComment = null) + { if ($this->isFinalized) { - return FALSE; + return false; } $this->zipComment = $newComment; - return TRUE; + return true; } /** @@ -120,9 +125,10 @@ class ZipStream { * @param string $fileComment (Optional) Comment to be added to the archive for this directory. To use fileComment, timestamp must be given. * @return bool $success */ - public function addDirectory($directoryPath, $timestamp = 0, $fileComment = null) { + public function addDirectory($directoryPath, $timestamp = 0, $fileComment = null) + { if ($this->isFinalized) { - return FALSE; + return false; } $directoryPath = str_replace("\\", "/", $directoryPath); @@ -130,9 +136,9 @@ class ZipStream { if (strlen($directoryPath) > 0) { $this->buildZipEntry($directoryPath.'/', $fileComment, "\x00\x00", "\x00\x00", $timestamp, "\x00\x00\x00\x00", 0, 0, self::EXT_FILE_ATTR_DIR); - return TRUE; + return true; } - return FALSE; + return false; } /** @@ -144,14 +150,15 @@ class ZipStream { * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. * @return bool $success */ - public function addFile($data, $filePath, $timestamp = 0, $fileComment = null) { + public function addFile($data, $filePath, $timestamp = 0, $fileComment = null) + { if ($this->isFinalized) { - return FALSE; + return false; } if (is_resource($data) && get_resource_type($data) == "stream") { $this->addLargeFile($data, $filePath, $timestamp, $fileComment); - return FALSE; + return false; } $gzType = "\x08\x00"; // Compression type 8 = deflate @@ -175,7 +182,7 @@ class ZipStream { print ($gzData); - return TRUE; + return true; } /** @@ -192,7 +199,8 @@ class ZipStream { * If you start the function by parsing an array, the array will be populated with the realPath * and zipPath kay/value pairs added to the archive by the function. */ - public function addDirectoryContent($realPath, $zipPath, $recursive = TRUE, $followSymlinks = TRUE, &$addedFiles = array()) { + public function addDirectoryContent($realPath, $zipPath, $recursive = true, $followSymlinks = true, &$addedFiles = []) + { if (file_exists($realPath) && !isset($addedFiles[realpath($realPath)])) { if (is_dir($realPath)) { $this->addDirectory($zipPath); @@ -208,11 +216,11 @@ class ZipStream { $newRealPath = $file->getPathname(); $newZipPath = self::pathJoin($zipPath, $file->getFilename()); - if (file_exists($newRealPath) && ($followSymlinks === TRUE || !is_link($newRealPath))) { + if (file_exists($newRealPath) && ($followSymlinks === true || !is_link($newRealPath))) { if ($file->isFile()) { $addedFiles[realpath($newRealPath)] = $newZipPath; $this->addLargeFile($newRealPath, $newZipPath); - } else if ($recursive === TRUE) { + } else if ($recursive === true) { $this->addDirectoryContent($newRealPath, $newZipPath, $recursive); } else { $this->addDirectory($zipPath); @@ -231,9 +239,10 @@ class ZipStream { * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. * @return bool $success */ - public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) { + public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) + { if ($this->isFinalized) { - return FALSE; + return false; } if (is_string($dataFile) && is_file($dataFile)) { @@ -247,7 +256,7 @@ class ZipStream { } $this->closeStream($this->addExtraField); } - return TRUE; + return true; } /** @@ -258,13 +267,14 @@ class ZipStream { * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. * @return bool $success */ - public function openStream($filePath, $timestamp = 0, $fileComment = null) { + public function openStream($filePath, $timestamp = 0, $fileComment = null) + { if (!function_exists('sys_get_temp_dir')) { - die ("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used."); + die("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used."); } if ($this->isFinalized) { - return FALSE; + return false; } if (strlen($this->streamFilePath) > 0) { @@ -278,7 +288,7 @@ class ZipStream { $this->streamFileComment = $fileComment; $this->streamFileLength = 0; - return TRUE; + return true; } /** @@ -287,14 +297,15 @@ class ZipStream { * @param String $data * @return $length bytes added or FALSE if the archive is finalized or there are no open stream. */ - public function addStreamData($data) { + public function addStreamData($data) + { if ($this->isFinalized || strlen($this->streamFilePath) == 0) { - return FALSE; + return false; } $length = fwrite($this->streamData, $data, strlen($data)); if ($length != strlen($data)) { - die ("

Length mismatch

\n"); + die("

Length mismatch

\n"); } $this->streamFileLength += $length; @@ -306,9 +317,10 @@ class ZipStream { * * @return bool $success */ - public function closeStream() { + public function closeStream() + { if ($this->isFinalized || strlen($this->streamFilePath) == 0) { - return FALSE; + return false; } fflush($this->streamData); @@ -327,18 +339,19 @@ class ZipStream { $this->streamFile = null; - return TRUE; + return true; } - private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) { + private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) + { if ($this->isFinalized) { - return FALSE; + return false; } $tempzip = tempnam(sys_get_temp_dir(), 'ZipStream'); $zip = new ZipArchive; - if ($zip->open($tempzip) === TRUE) { + if ($zip->open($tempzip) === true) { $zip->addFile($dataFile, 'file'); $zip->close(); } @@ -382,7 +395,8 @@ class ZipStream { * A closed archive can no longer have new files added to it. * @return bool $success */ - public function finalize() { + public function finalize() + { if (!$this->isFinalized) { if (strlen($this->streamFilePath) > 0) { $this->closeStream(); @@ -404,13 +418,13 @@ class ZipStream { flush(); - $this->isFinalized = TRUE; + $this->isFinalized = true; $cd = null; $this->cdRec = null; - return TRUE; + return true; } - return FALSE; + return false; } /** @@ -419,7 +433,8 @@ class ZipStream { * @param int $timestamp * @return 2-byte encoded DOS Date */ - private function getDosTime($timestamp = 0) { + private function getDosTime($timestamp = 0) + { $timestamp = (int)$timestamp; $oldTZ = @date_default_timezone_get(); date_default_timezone_set('UTC'); @@ -445,7 +460,8 @@ class ZipStream { * @param int $dataLength * @param integer $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories. */ - private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) { + private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) + { $filePath = str_replace("\\", "/", $filePath); $fileCommentLength = (empty($fileComment) ? 0 : strlen($fileComment)); $timestamp = (int)$timestamp; @@ -516,7 +532,8 @@ class ZipStream { * @param String $dir * @param String $file */ - public static function pathJoin($dir, $file) { + public static function pathJoin($dir, $file) + { if (empty($dir) || empty($file)) { return self::getRelativePath($dir . $file); } @@ -531,7 +548,8 @@ class ZipStream { * @param String $path The path to clean up * @return String the clean path */ - public static function getRelativePath($path) { + public static function getRelativePath($path) + { $path = preg_replace("#/+\.?/+#", "/", str_replace("\\", "/", $path)); $dirs = explode("/", rtrim(preg_replace('#^(?:\./)+#', '', $path), '/')); @@ -548,7 +566,7 @@ class ZipStream { $dirs = array_splice($dirs, 1); } - $newDirs = array(); + $newDirs = []; foreach ($dirs as $dir) { if ($dir !== "..") { $subOffset--; @@ -570,4 +588,3 @@ class ZipStream { return $root . implode("/", array_slice($newDirs, 0, $offset)); } } -?> diff --git a/app/Library/getid3/demos/demo.audioinfo.class.php b/app/Library/getid3/demos/demo.audioinfo.class.php index dc12a1ea..3409ba92 100644 --- a/app/Library/getid3/demos/demo.audioinfo.class.php +++ b/app/Library/getid3/demos/demo.audioinfo.class.php @@ -43,274 +43,275 @@ require_once('../getid3/getid3.php'); * Class for extracting information from audio files with getID3(). */ -class AudioInfo { +class AudioInfo +{ - /** - * Private variables - */ - var $result = NULL; - var $info = NULL; + /** + * Private variables + */ + var $result = null; + var $info = null; - /** - * Constructor - */ + /** + * Constructor + */ - function AudioInfo() { + function AudioInfo() + { - // Initialize getID3 engine - $this->getID3 = new getID3; - $this->getID3->option_md5_data = true; - $this->getID3->option_md5_data_source = true; - $this->getID3->encoding = 'UTF-8'; - } + // Initialize getID3 engine + $this->getID3 = new getID3; + $this->getID3->option_md5_data = true; + $this->getID3->option_md5_data_source = true; + $this->getID3->encoding = 'UTF-8'; + } - /** - * Extract information - only public function - * - * @access public - * @param string file Audio file to extract info from. - */ + /** + * Extract information - only public function + * + * @access public + * @param string file Audio file to extract info from. + */ - function Info($file) { + function Info($file) + { - // Analyze file - $this->info = $this->getID3->analyze($file); + // Analyze file + $this->info = $this->getID3->analyze($file); - // Exit here on error - if (isset($this->info['error'])) { - return array ('error' => $this->info['error']); - } + // Exit here on error + if (isset($this->info['error'])) { + return ['error' => $this->info['error']]; + } - // Init wrapper object - $this->result = array(); - $this->result['format_name'] = (isset($this->info['fileformat']) ? $this->info['fileformat'] : '').'/'.(isset($this->info['audio']['dataformat']) ? $this->info['audio']['dataformat'] : '').(isset($this->info['video']['dataformat']) ? '/'.$this->info['video']['dataformat'] : ''); - $this->result['encoder_version'] = (isset($this->info['audio']['encoder']) ? $this->info['audio']['encoder'] : ''); - $this->result['encoder_options'] = (isset($this->info['audio']['encoder_options']) ? $this->info['audio']['encoder_options'] : ''); - $this->result['bitrate_mode'] = (isset($this->info['audio']['bitrate_mode']) ? $this->info['audio']['bitrate_mode'] : ''); - $this->result['channels'] = (isset($this->info['audio']['channels']) ? $this->info['audio']['channels'] : ''); - $this->result['sample_rate'] = (isset($this->info['audio']['sample_rate']) ? $this->info['audio']['sample_rate'] : ''); - $this->result['bits_per_sample'] = (isset($this->info['audio']['bits_per_sample']) ? $this->info['audio']['bits_per_sample'] : ''); - $this->result['playing_time'] = (isset($this->info['playtime_seconds']) ? $this->info['playtime_seconds'] : ''); - $this->result['avg_bit_rate'] = (isset($this->info['audio']['bitrate']) ? $this->info['audio']['bitrate'] : ''); - $this->result['tags'] = (isset($this->info['tags']) ? $this->info['tags'] : ''); - $this->result['comments'] = (isset($this->info['comments']) ? $this->info['comments'] : ''); - $this->result['warning'] = (isset($this->info['warning']) ? $this->info['warning'] : ''); - $this->result['md5'] = (isset($this->info['md5_data']) ? $this->info['md5_data'] : ''); + // Init wrapper object + $this->result = []; + $this->result['format_name'] = (isset($this->info['fileformat']) ? $this->info['fileformat'] : '').'/'.(isset($this->info['audio']['dataformat']) ? $this->info['audio']['dataformat'] : '').(isset($this->info['video']['dataformat']) ? '/'.$this->info['video']['dataformat'] : ''); + $this->result['encoder_version'] = (isset($this->info['audio']['encoder']) ? $this->info['audio']['encoder'] : ''); + $this->result['encoder_options'] = (isset($this->info['audio']['encoder_options']) ? $this->info['audio']['encoder_options'] : ''); + $this->result['bitrate_mode'] = (isset($this->info['audio']['bitrate_mode']) ? $this->info['audio']['bitrate_mode'] : ''); + $this->result['channels'] = (isset($this->info['audio']['channels']) ? $this->info['audio']['channels'] : ''); + $this->result['sample_rate'] = (isset($this->info['audio']['sample_rate']) ? $this->info['audio']['sample_rate'] : ''); + $this->result['bits_per_sample'] = (isset($this->info['audio']['bits_per_sample']) ? $this->info['audio']['bits_per_sample'] : ''); + $this->result['playing_time'] = (isset($this->info['playtime_seconds']) ? $this->info['playtime_seconds'] : ''); + $this->result['avg_bit_rate'] = (isset($this->info['audio']['bitrate']) ? $this->info['audio']['bitrate'] : ''); + $this->result['tags'] = (isset($this->info['tags']) ? $this->info['tags'] : ''); + $this->result['comments'] = (isset($this->info['comments']) ? $this->info['comments'] : ''); + $this->result['warning'] = (isset($this->info['warning']) ? $this->info['warning'] : ''); + $this->result['md5'] = (isset($this->info['md5_data']) ? $this->info['md5_data'] : ''); - // Post getID3() data handling based on file format - $method = (isset($this->info['fileformat']) ? $this->info['fileformat'] : '').'Info'; - if ($method && method_exists($this, $method)) { - $this->$method(); - } + // Post getID3() data handling based on file format + $method = (isset($this->info['fileformat']) ? $this->info['fileformat'] : '').'Info'; + if ($method && method_exists($this, $method)) { + $this->$method(); + } - return $this->result; - } + return $this->result; + } - /** - * post-getID3() data handling for AAC files. - * - * @access private - */ + /** + * post-getID3() data handling for AAC files. + * + * @access private + */ - function aacInfo() { - $this->result['format_name'] = 'AAC'; - } + function aacInfo() + { + $this->result['format_name'] = 'AAC'; + } - /** - * post-getID3() data handling for Wave files. - * - * @access private - */ + /** + * post-getID3() data handling for Wave files. + * + * @access private + */ - function riffInfo() { - if ($this->info['audio']['dataformat'] == 'wav') { + function riffInfo() + { + if ($this->info['audio']['dataformat'] == 'wav') { + $this->result['format_name'] = 'Wave'; + } elseif (preg_match('#^mp[1-3]$#', $this->info['audio']['dataformat'])) { + $this->result['format_name'] = strtoupper($this->info['audio']['dataformat']); + } else { + $this->result['format_name'] = 'riff/'.$this->info['audio']['dataformat']; + } + } - $this->result['format_name'] = 'Wave'; - } elseif (preg_match('#^mp[1-3]$#', $this->info['audio']['dataformat'])) { - $this->result['format_name'] = strtoupper($this->info['audio']['dataformat']); - } else { + /** + * * post-getID3() data handling for FLAC files. + * + * @access private + */ - $this->result['format_name'] = 'riff/'.$this->info['audio']['dataformat']; + function flacInfo() + { + $this->result['format_name'] = 'FLAC'; + } - } - } - /** - * * post-getID3() data handling for FLAC files. - * - * @access private - */ + /** + * post-getID3() data handling for Monkey's Audio files. + * + * @access private + */ - function flacInfo() { - $this->result['format_name'] = 'FLAC'; - } + function macInfo() + { + $this->result['format_name'] = 'Monkey\'s Audio'; + } - /** - * post-getID3() data handling for Monkey's Audio files. - * - * @access private - */ + /** + * post-getID3() data handling for Lossless Audio files. + * + * @access private + */ - function macInfo() { - $this->result['format_name'] = 'Monkey\'s Audio'; - } + function laInfo() + { + $this->result['format_name'] = 'La'; + } - /** - * post-getID3() data handling for Lossless Audio files. - * - * @access private - */ + /** + * post-getID3() data handling for Ogg Vorbis files. + * + * @access private + */ - function laInfo() { - $this->result['format_name'] = 'La'; - } + function oggInfo() + { + if ($this->info['audio']['dataformat'] == 'vorbis') { + $this->result['format_name'] = 'Ogg Vorbis'; + } else if ($this->info['audio']['dataformat'] == 'flac') { + $this->result['format_name'] = 'Ogg FLAC'; + } else if ($this->info['audio']['dataformat'] == 'speex') { + $this->result['format_name'] = 'Ogg Speex'; + } else { + $this->result['format_name'] = 'Ogg '.$this->info['audio']['dataformat']; + } + } + /** + * post-getID3() data handling for Musepack files. + * + * @access private + */ - /** - * post-getID3() data handling for Ogg Vorbis files. - * - * @access private - */ + function mpcInfo() + { + $this->result['format_name'] = 'Musepack'; + } - function oggInfo() { - if ($this->info['audio']['dataformat'] == 'vorbis') { - $this->result['format_name'] = 'Ogg Vorbis'; - } else if ($this->info['audio']['dataformat'] == 'flac') { - $this->result['format_name'] = 'Ogg FLAC'; + /** + * post-getID3() data handling for MPEG files. + * + * @access private + */ - } else if ($this->info['audio']['dataformat'] == 'speex') { + function mp3Info() + { + $this->result['format_name'] = 'MP3'; + } - $this->result['format_name'] = 'Ogg Speex'; - } else { - $this->result['format_name'] = 'Ogg '.$this->info['audio']['dataformat']; - } - } + /** + * post-getID3() data handling for MPEG files. + * + * @access private + */ + function mp2Info() + { + $this->result['format_name'] = 'MP2'; + } - /** - * post-getID3() data handling for Musepack files. - * - * @access private - */ - function mpcInfo() { - $this->result['format_name'] = 'Musepack'; - } + /** + * post-getID3() data handling for MPEG files. + * + * @access private + */ + function mp1Info() + { + $this->result['format_name'] = 'MP1'; + } - /** - * post-getID3() data handling for MPEG files. - * - * @access private - */ - function mp3Info() { - $this->result['format_name'] = 'MP3'; - } + /** + * post-getID3() data handling for WMA files. + * + * @access private + */ + function asfInfo() + { + $this->result['format_name'] = strtoupper($this->info['audio']['dataformat']); + } - /** - * post-getID3() data handling for MPEG files. - * - * @access private - */ - function mp2Info() { - $this->result['format_name'] = 'MP2'; - } + /** + * post-getID3() data handling for Real files. + * + * @access private + */ + function realInfo() + { + $this->result['format_name'] = 'Real'; + } - /** - * post-getID3() data handling for MPEG files. - * - * @access private - */ - function mp1Info() { - $this->result['format_name'] = 'MP1'; - } - - - - - /** - * post-getID3() data handling for WMA files. - * - * @access private - */ - - function asfInfo() { - $this->result['format_name'] = strtoupper($this->info['audio']['dataformat']); - } - - - - /** - * post-getID3() data handling for Real files. - * - * @access private - */ - - function realInfo() { - $this->result['format_name'] = 'Real'; - } - - - - - - /** - * post-getID3() data handling for VQF files. - * - * @access private - */ - - function vqfInfo() { - $this->result['format_name'] = 'VQF'; - } + /** + * post-getID3() data handling for VQF files. + * + * @access private + */ + function vqfInfo() + { + $this->result['format_name'] = 'VQF'; + } } diff --git a/app/Library/getid3/demos/demo.browse.php b/app/Library/getid3/demos/demo.browse.php index cde883aa..395e4fe0 100644 --- a/app/Library/getid3/demos/demo.browse.php +++ b/app/Library/getid3/demos/demo.browse.php @@ -14,20 +14,20 @@ ///////////////////////////////////////////////////////////////// die('For security reasons, this demo has been disabled. It can be enabled by removing line '.__LINE__.' in demos/'.basename(__FILE__)); -define('GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK', false); +define('GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK', false); define('GETID3_DEMO_BROWSE_ALLOW_DELETE_LINK', false); -define('GETID3_DEMO_BROWSE_ALLOW_MD5_LINK', false); +define('GETID3_DEMO_BROWSE_ALLOW_MD5_LINK', false); ///////////////////////////////////////////////////////////////// // die if magic_quotes_runtime or magic_quotes_gpc are set if (function_exists('get_magic_quotes_runtime') && get_magic_quotes_runtime()) { - die('magic_quotes_runtime is enabled, getID3 will not run.'); + die('magic_quotes_runtime is enabled, getID3 will not run.'); } if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { - die('magic_quotes_gpc is enabled, getID3 will not run.'); + die('magic_quotes_gpc is enabled, getID3 will not run.'); } if (!defined('ENT_SUBSTITUTE')) { // defined in PHP v5.4.0 - define('ENT_SUBSTITUTE', ENT_QUOTES); + define('ENT_SUBSTITUTE', ENT_QUOTES); } ///////////////////////////////////////////////////////////////// @@ -42,7 +42,7 @@ require_once('../getid3/getid3.php'); // Initialize getID3 engine $getID3 = new getID3; -$getID3->setOption(array('encoding' => $PageEncoding)); +$getID3->setOption(['encoding' => $PageEncoding]); $getID3checkColor_Head = 'CCCCDD'; $getID3checkColor_DirectoryLight = 'FFCCCC'; @@ -65,338 +65,331 @@ echo ''.$deletefilemessage.'
'; - } else { - echo ''; - } + if (file_exists($_REQUEST['deletefile'])) { + if (unlink($_REQUEST['deletefile'])) { + $deletefilemessage = 'Successfully deleted '.addslashes($_REQUEST['deletefile']); + } else { + $deletefilemessage = 'FAILED to delete '.addslashes($_REQUEST['deletefile']).' - error deleting file'; + } + } else { + $deletefilemessage = 'FAILED to delete '.addslashes($_REQUEST['deletefile']).' - file does not exist'; + } + if (isset($_REQUEST['noalert'])) { + echo ''.$deletefilemessage.'
'; + } else { + echo ''; + } } if (isset($_REQUEST['filename'])) { + if (!file_exists($_REQUEST['filename']) || !is_file($_REQUEST['filename'])) { + die(getid3_lib::iconv_fallback('ISO-8859-1', $PageEncoding, $_REQUEST['filename'].' does not exist')); + } + $starttime = microtime(true); - if (!file_exists($_REQUEST['filename']) || !is_file($_REQUEST['filename'])) { - die(getid3_lib::iconv_fallback('ISO-8859-1', $PageEncoding, $_REQUEST['filename'].' does not exist')); - } - $starttime = microtime(true); - - //$getID3->setOption(array( - // 'option_md5_data' => $AutoGetHashes, - // 'option_sha1_data' => $AutoGetHashes, - //)); - $ThisFileInfo = $getID3->analyze($_REQUEST['filename']); - $AutoGetHashes = (bool) (isset($ThisFileInfo['filesize']) && ($ThisFileInfo['filesize'] > 0) && ($ThisFileInfo['filesize'] < (50 * 1048576))); // auto-get md5_data, md5_file, sha1_data, sha1_file if filesize < 50MB, and NOT zero (which may indicate a file>2GB) - $AutoGetHashes = ($AutoGetHashes && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK); - if ($AutoGetHashes) { - $ThisFileInfo['md5_file'] = md5_file($_REQUEST['filename']); - $ThisFileInfo['sha1_file'] = sha1_file($_REQUEST['filename']); - } + //$getID3->setOption(array( + // 'option_md5_data' => $AutoGetHashes, + // 'option_sha1_data' => $AutoGetHashes, + //)); + $ThisFileInfo = $getID3->analyze($_REQUEST['filename']); + $AutoGetHashes = (bool) (isset($ThisFileInfo['filesize']) && ($ThisFileInfo['filesize'] > 0) && ($ThisFileInfo['filesize'] < (50 * 1048576))); // auto-get md5_data, md5_file, sha1_data, sha1_file if filesize < 50MB, and NOT zero (which may indicate a file>2GB) + $AutoGetHashes = ($AutoGetHashes && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK); + if ($AutoGetHashes) { + $ThisFileInfo['md5_file'] = md5_file($_REQUEST['filename']); + $ThisFileInfo['sha1_file'] = sha1_file($_REQUEST['filename']); + } - getid3_lib::CopyTagsToComments($ThisFileInfo); + getid3_lib::CopyTagsToComments($ThisFileInfo); - $listdirectory = dirname($_REQUEST['filename']); - $listdirectory = realpath($listdirectory); // get rid of /../../ references + $listdirectory = dirname($_REQUEST['filename']); + $listdirectory = realpath($listdirectory); // get rid of /../../ references - if (GETID3_OS_ISWINDOWS) { - // this mostly just gives a consistant look to Windows and *nix filesystems - // (windows uses \ as directory seperator, *nix uses /) - $listdirectory = str_replace(DIRECTORY_SEPARATOR, '/', $listdirectory.'/'); - } + if (GETID3_OS_ISWINDOWS) { + // this mostly just gives a consistant look to Windows and *nix filesystems + // (windows uses \ as directory seperator, *nix uses /) + $listdirectory = str_replace(DIRECTORY_SEPARATOR, '/', $listdirectory.'/'); + } - if (strstr($_REQUEST['filename'], 'http://') || strstr($_REQUEST['filename'], 'ftp://')) { - echo 'Cannot browse remote filesystems
'; - } else { - echo 'Browse: '.getid3_lib::iconv_fallback('ISO-8859-1', $PageEncoding, $listdirectory).'
'; - } - - getid3_lib::ksort_recursive($ThisFileInfo); - echo table_var_dump($ThisFileInfo, false, $PageEncoding); - $endtime = microtime(true); - echo 'File parsed in '.number_format($endtime - $starttime, 3).' seconds.
'; + if (strstr($_REQUEST['filename'], 'http://') || strstr($_REQUEST['filename'], 'ftp://')) { + echo 'Cannot browse remote filesystems
'; + } else { + echo 'Browse: '.getid3_lib::iconv_fallback('ISO-8859-1', $PageEncoding, $listdirectory).'
'; + } + getid3_lib::ksort_recursive($ThisFileInfo); + echo table_var_dump($ThisFileInfo, false, $PageEncoding); + $endtime = microtime(true); + echo 'File parsed in '.number_format($endtime - $starttime, 3).' seconds.
'; } else { + $listdirectory = (isset($_REQUEST['listdirectory']) ? $_REQUEST['listdirectory'] : '.'); + $listdirectory = realpath($listdirectory); // get rid of /../../ references + $currentfulldir = $listdirectory.'/'; - $listdirectory = (isset($_REQUEST['listdirectory']) ? $_REQUEST['listdirectory'] : '.'); - $listdirectory = realpath($listdirectory); // get rid of /../../ references - $currentfulldir = $listdirectory.'/'; + if (GETID3_OS_ISWINDOWS) { + // this mostly just gives a consistant look to Windows and *nix filesystems + // (windows uses \ as directory seperator, *nix uses /) + $currentfulldir = str_replace(DIRECTORY_SEPARATOR, '/', $listdirectory.'/'); + } - if (GETID3_OS_ISWINDOWS) { - // this mostly just gives a consistant look to Windows and *nix filesystems - // (windows uses \ as directory seperator, *nix uses /) - $currentfulldir = str_replace(DIRECTORY_SEPARATOR, '/', $listdirectory.'/'); - } + ob_start(); + if ($handle = opendir($listdirectory)) { + ob_end_clean(); + echo str_repeat(' ', 300); // IE buffers the first 300 or so chars, making this progressive display useless - fill the buffer with spaces + echo 'Processing'; - ob_start(); - if ($handle = opendir($listdirectory)) { + $starttime = microtime(true); - ob_end_clean(); - echo str_repeat(' ', 300); // IE buffers the first 300 or so chars, making this progressive display useless - fill the buffer with spaces - echo 'Processing'; + $TotalScannedUnknownFiles = 0; + $TotalScannedKnownFiles = 0; + $TotalScannedPlaytimeFiles = 0; + $TotalScannedBitrateFiles = 0; + $TotalScannedFilesize = 0; + $TotalScannedPlaytime = 0; + $TotalScannedBitrate = 0; + $FilesWithWarnings = 0; + $FilesWithErrors = 0; - $starttime = microtime(true); + while ($file = readdir($handle)) { + $currentfilename = $listdirectory.'/'.$file; + set_time_limit(30); // allocate another 30 seconds to process this file - should go much quicker than this unless intense processing (like bitrate histogram analysis) is enabled + echo ' .'; // progress indicator dot + flush(); // make sure the dot is shown, otherwise it's useless - $TotalScannedUnknownFiles = 0; - $TotalScannedKnownFiles = 0; - $TotalScannedPlaytimeFiles = 0; - $TotalScannedBitrateFiles = 0; - $TotalScannedFilesize = 0; - $TotalScannedPlaytime = 0; - $TotalScannedBitrate = 0; - $FilesWithWarnings = 0; - $FilesWithErrors = 0; + switch ($file) { + case '..': + $ParentDir = realpath($file.'/..').'/'; + if (GETID3_OS_ISWINDOWS) { + $ParentDir = str_replace(DIRECTORY_SEPARATOR, '/', $ParentDir); + } + $DirectoryContents[$currentfulldir]['dir'][$file]['filename'] = $ParentDir; + continue 2; + break; - while ($file = readdir($handle)) { - $currentfilename = $listdirectory.'/'.$file; - set_time_limit(30); // allocate another 30 seconds to process this file - should go much quicker than this unless intense processing (like bitrate histogram analysis) is enabled - echo ' .'; // progress indicator dot - flush(); // make sure the dot is shown, otherwise it's useless + case '.': + // ignore + continue 2; + break; + } + // symbolic-link-resolution enhancements by davidbullock״ech-center*com + $TargetObject = realpath($currentfilename); // Find actual file path, resolve if it's a symbolic link + $TargetObjectType = filetype($TargetObject); // Check file type without examining extension - switch ($file) { - case '..': - $ParentDir = realpath($file.'/..').'/'; - if (GETID3_OS_ISWINDOWS) { - $ParentDir = str_replace(DIRECTORY_SEPARATOR, '/', $ParentDir); - } - $DirectoryContents[$currentfulldir]['dir'][$file]['filename'] = $ParentDir; - continue 2; - break; + if ($TargetObjectType == 'dir') { + $DirectoryContents[$currentfulldir]['dir'][$file]['filename'] = $file; + } elseif ($TargetObjectType == 'file') { + $getID3->setOption(['option_md5_data' => (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK)]); + $fileinformation = $getID3->analyze($currentfilename); - case '.': - // ignore - continue 2; - break; - } - // symbolic-link-resolution enhancements by davidbullock״ech-center*com - $TargetObject = realpath($currentfilename); // Find actual file path, resolve if it's a symbolic link - $TargetObjectType = filetype($TargetObject); // Check file type without examining extension + getid3_lib::CopyTagsToComments($fileinformation); - if ($TargetObjectType == 'dir') { + $TotalScannedFilesize += (isset($fileinformation['filesize']) ? $fileinformation['filesize'] : 0); - $DirectoryContents[$currentfulldir]['dir'][$file]['filename'] = $file; + if (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK) { + $fileinformation['md5_file'] = md5_file($currentfilename); + } - } elseif ($TargetObjectType == 'file') { + if (!empty($fileinformation['fileformat'])) { + $DirectoryContents[$currentfulldir]['known'][$file] = $fileinformation; + $TotalScannedPlaytime += (isset($fileinformation['playtime_seconds']) ? $fileinformation['playtime_seconds'] : 0); + $TotalScannedBitrate += (isset($fileinformation['bitrate']) ? $fileinformation['bitrate'] : 0); + $TotalScannedKnownFiles++; + } else { + $DirectoryContents[$currentfulldir]['other'][$file] = $fileinformation; + $DirectoryContents[$currentfulldir]['other'][$file]['playtime_string'] = '-'; + $TotalScannedUnknownFiles++; + } + if (isset($fileinformation['playtime_seconds']) && ($fileinformation['playtime_seconds'] > 0)) { + $TotalScannedPlaytimeFiles++; + } + if (isset($fileinformation['bitrate']) && ($fileinformation['bitrate'] > 0)) { + $TotalScannedBitrateFiles++; + } + } + } + $endtime = microtime(true); + closedir($handle); + echo 'done
'; + echo 'Directory scanned in '.number_format($endtime - $starttime, 2).' seconds.
'; + flush(); - $getID3->setOption(array('option_md5_data' => (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK))); - $fileinformation = $getID3->analyze($currentfilename); + $columnsintable = 14; + echo ''; - getid3_lib::CopyTagsToComments($fileinformation); + echo ''; + $rowcounter = 0; + foreach ($DirectoryContents as $dirname => $val) { + if (isset($DirectoryContents[$dirname]['dir']) && is_array($DirectoryContents[$dirname]['dir'])) { + uksort($DirectoryContents[$dirname]['dir'], 'MoreNaturalSort'); + foreach ($DirectoryContents[$dirname]['dir'] as $filename => $fileinfo) { + echo ''; + if ($filename == '..') { + echo ''; + } else { + $escaped_filename = htmlentities($filename, ENT_SUBSTITUTE, $PageEncoding); // do filesystems always return filenames in ISO-8859-1? + $escaped_filename = ($escaped_filename ? $escaped_filename : rawurlencode($filename)); + echo ''; + } + echo ''; + } + } - $TotalScannedFilesize += (isset($fileinformation['filesize']) ? $fileinformation['filesize'] : 0); + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + if (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK) { + echo ''; + echo ''; + echo ''; + } else { + echo ''; + } + echo ''; + echo ''; + echo (GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK ? '' : ''); + echo (GETID3_DEMO_BROWSE_ALLOW_DELETE_LINK ? '' : ''); + echo ''; - if (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK) { - $fileinformation['md5_file'] = md5_file($currentfilename); - } + if (isset($DirectoryContents[$dirname]['known']) && is_array($DirectoryContents[$dirname]['known'])) { + uksort($DirectoryContents[$dirname]['known'], 'MoreNaturalSort'); + foreach ($DirectoryContents[$dirname]['known'] as $filename => $fileinfo) { + echo ''; + $escaped_filename = htmlentities($filename, ENT_SUBSTITUTE, $PageEncoding); + $escaped_filename = ($escaped_filename ? $escaped_filename : rawurlencode($filename)); + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + if (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK) { + echo ''; + echo ''; + echo ''; + } else { + echo ''; + } + echo ''; - if (!empty($fileinformation['fileformat'])) { - $DirectoryContents[$currentfulldir]['known'][$file] = $fileinformation; - $TotalScannedPlaytime += (isset($fileinformation['playtime_seconds']) ? $fileinformation['playtime_seconds'] : 0); - $TotalScannedBitrate += (isset($fileinformation['bitrate']) ? $fileinformation['bitrate'] : 0); - $TotalScannedKnownFiles++; - } else { - $DirectoryContents[$currentfulldir]['other'][$file] = $fileinformation; - $DirectoryContents[$currentfulldir]['other'][$file]['playtime_string'] = '-'; - $TotalScannedUnknownFiles++; - } - if (isset($fileinformation['playtime_seconds']) && ($fileinformation['playtime_seconds'] > 0)) { - $TotalScannedPlaytimeFiles++; - } - if (isset($fileinformation['bitrate']) && ($fileinformation['bitrate'] > 0)) { - $TotalScannedBitrateFiles++; - } - } - } - $endtime = microtime(true); - closedir($handle); - echo 'done
'; - echo 'Directory scanned in '.number_format($endtime - $starttime, 2).' seconds.
'; - flush(); + echo ''; - $columnsintable = 14; - echo '
Files in '.getid3_lib::iconv_fallback('ISO-8859-1', $PageEncoding, $currentfulldir).'
'; + echo '
'; + echo 'Parent directory: '; + echo ' '; + echo '
'.$escaped_filename.'
FilenameFile SizeFormatPlaytimeBitrateArtistTitleMD5 File (File) (disable)MD5 Data (File) (disable)MD5 Data (Source) (disable)MD5 Data'.(GETID3_DEMO_BROWSE_ALLOW_MD5_LINK ?' (enable)' : '').'TagsErrors & WarningsEditDelete
'.$escaped_filename.' '.number_format($fileinfo['filesize']).' '.NiceDisplayFiletypeFormat($fileinfo).' '.(isset($fileinfo['playtime_string']) ? $fileinfo['playtime_string'] : '-').' '.(isset($fileinfo['bitrate']) ? BitrateText($fileinfo['bitrate'] / 1000, 0, ((isset($fileinfo['audio']['bitrate_mode']) && ($fileinfo['audio']['bitrate_mode'] == 'vbr')) ? true : false)) : '-').' '.(isset($fileinfo['comments_html']['artist']) ? implode('
', $fileinfo['comments_html']['artist']) : ((isset($fileinfo['video']['resolution_x']) && isset($fileinfo['video']['resolution_y'])) ? $fileinfo['video']['resolution_x'].'x'.$fileinfo['video']['resolution_y'] : '')).'
 '.(isset($fileinfo['comments_html']['title']) ? implode('
', $fileinfo['comments_html']['title']) : (isset($fileinfo['video']['frame_rate']) ? number_format($fileinfo['video']['frame_rate'], 3).'fps' : '')).'
'.(isset($fileinfo['md5_file']) ? $fileinfo['md5_file'] : ' ').''.(isset($fileinfo['md5_data']) ? $fileinfo['md5_data'] : ' ').''.(isset($fileinfo['md5_data_source']) ? $fileinfo['md5_data_source'] : ' ').'- '.(!empty($fileinfo['tags']) ? implode(', ', array_keys($fileinfo['tags'])) : '').' '; + if (!empty($fileinfo['warning'])) { + $FilesWithWarnings++; + echo 'warning
'; + } + if (!empty($fileinfo['error'])) { + $FilesWithErrors++; + echo 'error
'; + } + echo '
'; + if (GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK) { + echo ''; + } + if (GETID3_DEMO_BROWSE_ALLOW_DELETE_LINK) { + echo ''; + } + echo ''; + } + } - echo ''; - $rowcounter = 0; - foreach ($DirectoryContents as $dirname => $val) { - if (isset($DirectoryContents[$dirname]['dir']) && is_array($DirectoryContents[$dirname]['dir'])) { - uksort($DirectoryContents[$dirname]['dir'], 'MoreNaturalSort'); - foreach ($DirectoryContents[$dirname]['dir'] as $filename => $fileinfo) { - echo ''; - if ($filename == '..') { - echo ''; - } else { - $escaped_filename = htmlentities($filename, ENT_SUBSTITUTE, $PageEncoding); // do filesystems always return filenames in ISO-8859-1? - $escaped_filename = ($escaped_filename ? $escaped_filename : rawurlencode($filename)); - echo ''; - } - echo ''; - } - } + if (isset($DirectoryContents[$dirname]['other']) && is_array($DirectoryContents[$dirname]['other'])) { + uksort($DirectoryContents[$dirname]['other'], 'MoreNaturalSort'); + foreach ($DirectoryContents[$dirname]['other'] as $filename => $fileinfo) { + echo ''; + $escaped_filename = htmlentities($filename, ENT_SUBSTITUTE, $PageEncoding); + $escaped_filename = ($escaped_filename ? $escaped_filename : rawurlencode($filename)); + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; // Artist + echo ''; // Title + echo ''; // MD5_data + echo ''; // Tags - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - if (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK) { - echo ''; - echo ''; - echo ''; - } else { - echo ''; - } - echo ''; - echo ''; - echo (GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK ? '' : ''); - echo (GETID3_DEMO_BROWSE_ALLOW_DELETE_LINK ? '' : ''); - echo ''; + //echo ''; // Warning/Error + echo ''; - if (isset($DirectoryContents[$dirname]['known']) && is_array($DirectoryContents[$dirname]['known'])) { - uksort($DirectoryContents[$dirname]['known'], 'MoreNaturalSort'); - foreach ($DirectoryContents[$dirname]['known'] as $filename => $fileinfo) { - echo ''; - $escaped_filename = htmlentities($filename, ENT_SUBSTITUTE, $PageEncoding); - $escaped_filename = ($escaped_filename ? $escaped_filename : rawurlencode($filename)); - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - if (isset($_REQUEST['ShowMD5']) && GETID3_DEMO_BROWSE_ALLOW_MD5_LINK) { - echo ''; - echo ''; - echo ''; - } else { - echo ''; - } - echo ''; + if (GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK) { + echo ''; // Edit + } + if (GETID3_DEMO_BROWSE_ALLOW_DELETE_LINK) { + echo ''; + } + echo ''; + } + } - echo ''; - - if (GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK) { - echo ''; - } - if (GETID3_DEMO_BROWSE_ALLOW_DELETE_LINK) { - echo ''; - } - echo ''; - } - } - - if (isset($DirectoryContents[$dirname]['other']) && is_array($DirectoryContents[$dirname]['other'])) { - uksort($DirectoryContents[$dirname]['other'], 'MoreNaturalSort'); - foreach ($DirectoryContents[$dirname]['other'] as $filename => $fileinfo) { - echo ''; - $escaped_filename = htmlentities($filename, ENT_SUBSTITUTE, $PageEncoding); - $escaped_filename = ($escaped_filename ? $escaped_filename : rawurlencode($filename)); - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; // Artist - echo ''; // Title - echo ''; // MD5_data - echo ''; // Tags - - //echo ''; // Warning/Error - echo ''; - - if (GETID3_DEMO_BROWSE_ALLOW_EDIT_LINK) { - echo ''; // Edit - } - if (GETID3_DEMO_BROWSE_ALLOW_DELETE_LINK) { - echo ''; - } - echo ''; - } - } - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
 '; + $fileinfo['fileformat'] = (isset($fileinfo['fileformat']) ? $fileinfo['fileformat'] : ''); + switch ($fileinfo['fileformat']) { + case 'mp3': + case 'mp2': + case 'mp1': + case 'flac': + case 'mpc': + case 'real': + echo 'edit tags'; + break; + case 'ogg': + if (isset($fileinfo['audio']['dataformat']) && ($fileinfo['audio']['dataformat'] == 'vorbis')) { + echo 'edit tags'; + } + break; + default: + break; + } + echo ' delete
Files in '.getid3_lib::iconv_fallback('ISO-8859-1', $PageEncoding, $currentfulldir).'
'; - echo '
'; - echo 'Parent directory: '; - echo ' '; - echo '
'.$escaped_filename.'
'.$escaped_filename.' '.(isset($fileinfo['filesize']) ? number_format($fileinfo['filesize']) : '-').' '.NiceDisplayFiletypeFormat($fileinfo).' '.(isset($fileinfo['playtime_string']) ? $fileinfo['playtime_string'] : '-').' '.(isset($fileinfo['bitrate']) ? BitrateText($fileinfo['bitrate'] / 1000) : '-').'    
FilenameFile SizeFormatPlaytimeBitrateArtistTitleMD5 File (File) (disable)MD5 Data (File) (disable)MD5 Data (Source) (disable)MD5 Data'.(GETID3_DEMO_BROWSE_ALLOW_MD5_LINK ?' (enable)' : '').'TagsErrors & WarningsEditDelete
  '; + if (!empty($fileinfo['warning'])) { + $FilesWithWarnings++; + echo 'warning
'; + } + if (!empty($fileinfo['error'])) { + if ($fileinfo['error'][0] != 'unable to determine file format') { + $FilesWithErrors++; + echo 'error
'; + } + } + echo '
'.$escaped_filename.' '.number_format($fileinfo['filesize']).' '.NiceDisplayFiletypeFormat($fileinfo).' '.(isset($fileinfo['playtime_string']) ? $fileinfo['playtime_string'] : '-').' '.(isset($fileinfo['bitrate']) ? BitrateText($fileinfo['bitrate'] / 1000, 0, ((isset($fileinfo['audio']['bitrate_mode']) && ($fileinfo['audio']['bitrate_mode'] == 'vbr')) ? true : false)) : '-').' '.(isset($fileinfo['comments_html']['artist']) ? implode('
', $fileinfo['comments_html']['artist']) : ((isset($fileinfo['video']['resolution_x']) && isset($fileinfo['video']['resolution_y'])) ? $fileinfo['video']['resolution_x'].'x'.$fileinfo['video']['resolution_y'] : '')).'
 '.(isset($fileinfo['comments_html']['title']) ? implode('
', $fileinfo['comments_html']['title']) : (isset($fileinfo['video']['frame_rate']) ? number_format($fileinfo['video']['frame_rate'], 3).'fps' : '')).'
'.(isset($fileinfo['md5_file']) ? $fileinfo['md5_file'] : ' ').''.(isset($fileinfo['md5_data']) ? $fileinfo['md5_data'] : ' ').''.(isset($fileinfo['md5_data_source']) ? $fileinfo['md5_data_source'] : ' ').'- '.(!empty($fileinfo['tags']) ? implode(', ', array_keys($fileinfo['tags'])) : '').'  delete
 '; - if (!empty($fileinfo['warning'])) { - $FilesWithWarnings++; - echo 'warning
'; - } - if (!empty($fileinfo['error'])) { - $FilesWithErrors++; - echo 'error
'; - } - echo '
 '; - $fileinfo['fileformat'] = (isset($fileinfo['fileformat']) ? $fileinfo['fileformat'] : ''); - switch ($fileinfo['fileformat']) { - case 'mp3': - case 'mp2': - case 'mp1': - case 'flac': - case 'mpc': - case 'real': - echo 'edit tags'; - break; - case 'ogg': - if (isset($fileinfo['audio']['dataformat']) && ($fileinfo['audio']['dataformat'] == 'vorbis')) { - echo 'edit tags'; - } - break; - default: - break; - } - echo ' delete
'.$escaped_filename.' '.(isset($fileinfo['filesize']) ? number_format($fileinfo['filesize']) : '-').' '.NiceDisplayFiletypeFormat($fileinfo).' '.(isset($fileinfo['playtime_string']) ? $fileinfo['playtime_string'] : '-').' '.(isset($fileinfo['bitrate']) ? BitrateText($fileinfo['bitrate'] / 1000) : '-').'      '; - if (!empty($fileinfo['warning'])) { - $FilesWithWarnings++; - echo 'warning
'; - } - if (!empty($fileinfo['error'])) { - if ($fileinfo['error'][0] != 'unable to determine file format') { - $FilesWithErrors++; - echo 'error
'; - } - } - echo '
  delete
Average:'.number_format($TotalScannedFilesize / max($TotalScannedKnownFiles, 1)).' '.getid3_lib::PlaytimeString($TotalScannedPlaytime / max($TotalScannedPlaytimeFiles, 1)).''.BitrateText(round(($TotalScannedBitrate / 1000) / max($TotalScannedBitrateFiles, 1))).'
Identified Files:'.number_format($TotalScannedKnownFiles).'   Errors:'.number_format($FilesWithErrors).'
Unknown Files:'.number_format($TotalScannedUnknownFiles).'   Warnings:'.number_format($FilesWithWarnings).'
'; - echo '
Total:'.number_format($TotalScannedFilesize).' '.getid3_lib::PlaytimeString($TotalScannedPlaytime).' 
'; - } else { - $errormessage = ob_get_contents(); - ob_end_clean(); - echo 'ERROR: Could not open directory: '.$currentfulldir.'
'; - } + echo ''; + echo 'Average:'; + echo ''.number_format($TotalScannedFilesize / max($TotalScannedKnownFiles, 1)).''; + echo ' '; + echo ''.getid3_lib::PlaytimeString($TotalScannedPlaytime / max($TotalScannedPlaytimeFiles, 1)).''; + echo ''.BitrateText(round(($TotalScannedBitrate / 1000) / max($TotalScannedBitrateFiles, 1))).''; + echo '
Identified Files:'.number_format($TotalScannedKnownFiles).'   Errors:'.number_format($FilesWithErrors).'
Unknown Files:'.number_format($TotalScannedUnknownFiles).'   Warnings:'.number_format($FilesWithWarnings).'
'; + echo ''; + echo ''; + echo 'Total:'; + echo ''.number_format($TotalScannedFilesize).''; + echo ' '; + echo ''.getid3_lib::PlaytimeString($TotalScannedPlaytime).''; + echo ' '; + echo ''; + } + echo ''; + } else { + $errormessage = ob_get_contents(); + ob_end_clean(); + echo 'ERROR: Could not open directory: '.$currentfulldir.'
'; + } } echo PoweredBygetID3().'
'; echo ''; @@ -405,209 +398,216 @@ echo ''; ///////////////////////////////////////////////////////////////// -function RemoveAccents($string) { - // Revised version by markstewardרotmail*com - // Again revised by James Heinrich (19-June-2006) - return strtr( - strtr( - $string, - "\x8A\x8E\x9A\x9E\x9F\xC0\xC1\xC2\xC3\xC4\xC5\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFF", - 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy' - ), - array( - "\xDE" => 'TH', - "\xFE" => 'th', - "\xD0" => 'DH', - "\xF0" => 'dh', - "\xDF" => 'ss', - "\x8C" => 'OE', - "\x9C" => 'oe', - "\xC6" => 'AE', - "\xE6" => 'ae', - "\xB5" => 'u' - ) - ); +function RemoveAccents($string) +{ + // Revised version by markstewardרotmail*com + // Again revised by James Heinrich (19-June-2006) + return strtr( + strtr( + $string, + "\x8A\x8E\x9A\x9E\x9F\xC0\xC1\xC2\xC3\xC4\xC5\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFF", + 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy' + ), + [ + "\xDE" => 'TH', + "\xFE" => 'th', + "\xD0" => 'DH', + "\xF0" => 'dh', + "\xDF" => 'ss', + "\x8C" => 'OE', + "\x9C" => 'oe', + "\xC6" => 'AE', + "\xE6" => 'ae', + "\xB5" => 'u' + ] + ); } -function BitrateColor($bitrate, $BitrateMaxScale=768) { - // $BitrateMaxScale is bitrate of maximum-quality color (bright green) - // below this is gradient, above is solid green +function BitrateColor($bitrate, $BitrateMaxScale = 768) +{ + // $BitrateMaxScale is bitrate of maximum-quality color (bright green) + // below this is gradient, above is solid green - $bitrate *= (256 / $BitrateMaxScale); // scale from 1-[768]kbps to 1-256 - $bitrate = round(min(max($bitrate, 1), 256)); - $bitrate--; // scale from 1-256kbps to 0-255kbps + $bitrate *= (256 / $BitrateMaxScale); // scale from 1-[768]kbps to 1-256 + $bitrate = round(min(max($bitrate, 1), 256)); + $bitrate--; // scale from 1-256kbps to 0-255kbps - $Rcomponent = max(255 - ($bitrate * 2), 0); - $Gcomponent = max(($bitrate * 2) - 255, 0); - if ($bitrate > 127) { - $Bcomponent = max((255 - $bitrate) * 2, 0); - } else { - $Bcomponent = max($bitrate * 2, 0); - } - return str_pad(dechex($Rcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Gcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Bcomponent), 2, '0', STR_PAD_LEFT); + $Rcomponent = max(255 - ($bitrate * 2), 0); + $Gcomponent = max(($bitrate * 2) - 255, 0); + if ($bitrate > 127) { + $Bcomponent = max((255 - $bitrate) * 2, 0); + } else { + $Bcomponent = max($bitrate * 2, 0); + } + return str_pad(dechex($Rcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Gcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Bcomponent), 2, '0', STR_PAD_LEFT); } -function BitrateText($bitrate, $decimals=0, $vbr=false) { - return ''.number_format($bitrate, $decimals).' kbps'; +function BitrateText($bitrate, $decimals = 0, $vbr = false) +{ + return ''.number_format($bitrate, $decimals).' kbps'; } -function string_var_dump($variable) { - if (version_compare(PHP_VERSION, '4.3.0', '>=')) { - return print_r($variable, true); - } - ob_start(); - var_dump($variable); - $dumpedvariable = ob_get_contents(); - ob_end_clean(); - return $dumpedvariable; +function string_var_dump($variable) +{ + if (version_compare(PHP_VERSION, '4.3.0', '>=')) { + return print_r($variable, true); + } + ob_start(); + var_dump($variable); + $dumpedvariable = ob_get_contents(); + ob_end_clean(); + return $dumpedvariable; } -function table_var_dump($variable, $wrap_in_td=false, $encoding='ISO-8859-1') { - $returnstring = ''; - switch (gettype($variable)) { - case 'array': - $returnstring .= ($wrap_in_td ? '' : ''); - $returnstring .= ''; - foreach ($variable as $key => $value) { - $returnstring .= ''."\n"; - $returnstring .= ''."\n".''."\n"; - } else { - $returnstring .= ''."\n".''."\n"; - } - } else { - $returnstring .= ''."\n".table_var_dump($value, true, $encoding).''."\n"; - } - } - $returnstring .= '
'.str_replace("\x00", ' ', $key).''.gettype($value); - if (is_array($value)) { - $returnstring .= ' ('.count($value).')'; - } elseif (is_string($value)) { - $returnstring .= ' ('.strlen($value).')'; - } - //if (($key == 'data') && isset($variable['image_mime']) && isset($variable['dataoffset'])) { - if (($key == 'data') && isset($variable['image_mime'])) { - $imageinfo = array(); - if ($imagechunkcheck = getid3_lib::GetDataImageSize($value, $imageinfo)) { - $returnstring .= '
invalid image data
'."\n"; - $returnstring .= ($wrap_in_td ? ''."\n" : ''); - break; +function table_var_dump($variable, $wrap_in_td = false, $encoding = 'ISO-8859-1') +{ + $returnstring = ''; + switch (gettype($variable)) { + case 'array': + $returnstring .= ($wrap_in_td ? '' : ''); + $returnstring .= ''; + foreach ($variable as $key => $value) { + $returnstring .= ''."\n"; + $returnstring .= ''."\n".''."\n"; + } else { + $returnstring .= ''."\n".''."\n"; + } + } else { + $returnstring .= ''."\n".table_var_dump($value, true, $encoding).''."\n"; + } + } + $returnstring .= '
'.str_replace("\x00", ' ', $key).''.gettype($value); + if (is_array($value)) { + $returnstring .= ' ('.count($value).')'; + } elseif (is_string($value)) { + $returnstring .= ' ('.strlen($value).')'; + } + //if (($key == 'data') && isset($variable['image_mime']) && isset($variable['dataoffset'])) { + if (($key == 'data') && isset($variable['image_mime'])) { + $imageinfo = []; + if ($imagechunkcheck = getid3_lib::GetDataImageSize($value, $imageinfo)) { + $returnstring .= '
invalid image data
'."\n"; + $returnstring .= ($wrap_in_td ? ''."\n" : ''); + break; - case 'boolean': - $returnstring .= ($wrap_in_td ? '' : '').($variable ? 'TRUE' : 'FALSE').($wrap_in_td ? ''."\n" : ''); - break; + case 'boolean': + $returnstring .= ($wrap_in_td ? '' : '').($variable ? 'TRUE' : 'FALSE').($wrap_in_td ? ''."\n" : ''); + break; - case 'integer': - $returnstring .= ($wrap_in_td ? '' : '').$variable.($wrap_in_td ? ''."\n" : ''); - break; + case 'integer': + $returnstring .= ($wrap_in_td ? '' : '').$variable.($wrap_in_td ? ''."\n" : ''); + break; - case 'double': - case 'float': - $returnstring .= ($wrap_in_td ? '' : '').$variable.($wrap_in_td ? ''."\n" : ''); - break; + case 'double': + case 'float': + $returnstring .= ($wrap_in_td ? '' : '').$variable.($wrap_in_td ? ''."\n" : ''); + break; - case 'object': - case 'null': - $returnstring .= ($wrap_in_td ? '' : '').string_var_dump($variable).($wrap_in_td ? ''."\n" : ''); - break; + case 'object': + case 'null': + $returnstring .= ($wrap_in_td ? '' : '').string_var_dump($variable).($wrap_in_td ? ''."\n" : ''); + break; - case 'string': - $returnstring = htmlentities($variable, ENT_QUOTES | ENT_SUBSTITUTE, $encoding); - $returnstring = ($wrap_in_td ? '' : '').nl2br($returnstring).($wrap_in_td ? ''."\n" : ''); - break; + case 'string': + $returnstring = htmlentities($variable, ENT_QUOTES | ENT_SUBSTITUTE, $encoding); + $returnstring = ($wrap_in_td ? '' : '').nl2br($returnstring).($wrap_in_td ? ''."\n" : ''); + break; - default: - $imageinfo = array(); - if (($imagechunkcheck = getid3_lib::GetDataImageSize($variable, $imageinfo)) && ($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) { - $returnstring .= ($wrap_in_td ? '' : ''); - $returnstring .= ''; - $returnstring .= ''."\n"; - $returnstring .= ''."\n"; - $returnstring .= ''."\n"; - $returnstring .= '
type'.getid3_lib::ImageTypesLookup($imagechunkcheck[2]).'
width'.number_format($imagechunkcheck[0]).' px
height'.number_format($imagechunkcheck[1]).' px
size'.number_format(strlen($variable)).' bytes
'."\n"; - $returnstring .= ($wrap_in_td ? ''."\n" : ''); - } else { - $returnstring .= ($wrap_in_td ? '' : '').nl2br(htmlspecialchars(str_replace("\x00", ' ', $variable))).($wrap_in_td ? ''."\n" : ''); - } - break; - } - return $returnstring; + default: + $imageinfo = []; + if (($imagechunkcheck = getid3_lib::GetDataImageSize($variable, $imageinfo)) && ($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) { + $returnstring .= ($wrap_in_td ? '' : ''); + $returnstring .= ''; + $returnstring .= ''."\n"; + $returnstring .= ''."\n"; + $returnstring .= ''."\n"; + $returnstring .= '
type'.getid3_lib::ImageTypesLookup($imagechunkcheck[2]).'
width'.number_format($imagechunkcheck[0]).' px
height'.number_format($imagechunkcheck[1]).' px
size'.number_format(strlen($variable)).' bytes
'."\n"; + $returnstring .= ($wrap_in_td ? ''."\n" : ''); + } else { + $returnstring .= ($wrap_in_td ? '' : '').nl2br(htmlspecialchars(str_replace("\x00", ' ', $variable))).($wrap_in_td ? ''."\n" : ''); + } + break; + } + return $returnstring; } -function NiceDisplayFiletypeFormat(&$fileinfo) { +function NiceDisplayFiletypeFormat(&$fileinfo) +{ - if (empty($fileinfo['fileformat'])) { - return '-'; - } - - $output = $fileinfo['fileformat']; - if (empty($fileinfo['video']['dataformat']) && empty($fileinfo['audio']['dataformat'])) { - return $output; // 'gif' - } - if (empty($fileinfo['video']['dataformat']) && !empty($fileinfo['audio']['dataformat'])) { - if ($fileinfo['fileformat'] == $fileinfo['audio']['dataformat']) { - return $output; // 'mp3' - } - $output .= '.'.$fileinfo['audio']['dataformat']; // 'ogg.flac' - return $output; - } - if (!empty($fileinfo['video']['dataformat']) && empty($fileinfo['audio']['dataformat'])) { - if ($fileinfo['fileformat'] == $fileinfo['video']['dataformat']) { - return $output; // 'mpeg' - } - $output .= '.'.$fileinfo['video']['dataformat']; // 'riff.avi' - return $output; - } - if ($fileinfo['video']['dataformat'] == $fileinfo['audio']['dataformat']) { - if ($fileinfo['fileformat'] == $fileinfo['video']['dataformat']) { - return $output; // 'real' - } - $output .= '.'.$fileinfo['video']['dataformat']; // any examples? - return $output; - } - $output .= '.'.$fileinfo['video']['dataformat']; - $output .= '.'.$fileinfo['audio']['dataformat']; // asf.wmv.wma - return $output; + if (empty($fileinfo['fileformat'])) { + return '-'; + } + $output = $fileinfo['fileformat']; + if (empty($fileinfo['video']['dataformat']) && empty($fileinfo['audio']['dataformat'])) { + return $output; // 'gif' + } + if (empty($fileinfo['video']['dataformat']) && !empty($fileinfo['audio']['dataformat'])) { + if ($fileinfo['fileformat'] == $fileinfo['audio']['dataformat']) { + return $output; // 'mp3' + } + $output .= '.'.$fileinfo['audio']['dataformat']; // 'ogg.flac' + return $output; + } + if (!empty($fileinfo['video']['dataformat']) && empty($fileinfo['audio']['dataformat'])) { + if ($fileinfo['fileformat'] == $fileinfo['video']['dataformat']) { + return $output; // 'mpeg' + } + $output .= '.'.$fileinfo['video']['dataformat']; // 'riff.avi' + return $output; + } + if ($fileinfo['video']['dataformat'] == $fileinfo['audio']['dataformat']) { + if ($fileinfo['fileformat'] == $fileinfo['video']['dataformat']) { + return $output; // 'real' + } + $output .= '.'.$fileinfo['video']['dataformat']; // any examples? + return $output; + } + $output .= '.'.$fileinfo['video']['dataformat']; + $output .= '.'.$fileinfo['audio']['dataformat']; // asf.wmv.wma + return $output; } -function MoreNaturalSort($ar1, $ar2) { - if ($ar1 === $ar2) { - return 0; - } - $len1 = strlen($ar1); - $len2 = strlen($ar2); - $shortest = min($len1, $len2); - if (substr($ar1, 0, $shortest) === substr($ar2, 0, $shortest)) { - // the shorter argument is the beginning of the longer one, like "str" and "string" - if ($len1 < $len2) { - return -1; - } elseif ($len1 > $len2) { - return 1; - } - return 0; - } - $ar1 = RemoveAccents(strtolower(trim($ar1))); - $ar2 = RemoveAccents(strtolower(trim($ar2))); - $translatearray = array('\''=>'', '"'=>'', '_'=>' ', '('=>'', ')'=>'', '-'=>' ', ' '=>' ', '.'=>'', ','=>''); - foreach ($translatearray as $key => $val) { - $ar1 = str_replace($key, $val, $ar1); - $ar2 = str_replace($key, $val, $ar2); - } +function MoreNaturalSort($ar1, $ar2) +{ + if ($ar1 === $ar2) { + return 0; + } + $len1 = strlen($ar1); + $len2 = strlen($ar2); + $shortest = min($len1, $len2); + if (substr($ar1, 0, $shortest) === substr($ar2, 0, $shortest)) { + // the shorter argument is the beginning of the longer one, like "str" and "string" + if ($len1 < $len2) { + return -1; + } elseif ($len1 > $len2) { + return 1; + } + return 0; + } + $ar1 = RemoveAccents(strtolower(trim($ar1))); + $ar2 = RemoveAccents(strtolower(trim($ar2))); + $translatearray = ['\''=>'', '"'=>'', '_'=>' ', '('=>'', ')'=>'', '-'=>' ', ' '=>' ', '.'=>'', ','=>'']; + foreach ($translatearray as $key => $val) { + $ar1 = str_replace($key, $val, $ar1); + $ar2 = str_replace($key, $val, $ar2); + } - if ($ar1 < $ar2) { - return -1; - } elseif ($ar1 > $ar2) { - return 1; - } - return 0; + if ($ar1 < $ar2) { + return -1; + } elseif ($ar1 > $ar2) { + return 1; + } + return 0; } -function PoweredBygetID3($string='') { - global $getID3; - if (!$string) { - $string = '
Powered by getID3() v
http://getid3.sourceforge.net

Running on PHP v'.phpversion().' ('.(ceil(log(PHP_INT_MAX, 2)) + 1).'-bit)
'; - } - return str_replace('', $getID3->version(), $string); +function PoweredBygetID3($string = '') +{ + global $getID3; + if (!$string) { + $string = '
Powered by getID3() v
http://getid3.sourceforge.net

Running on PHP v'.phpversion().' ('.(ceil(log(PHP_INT_MAX, 2)) + 1).'-bit)
'; + } + return str_replace('', $getID3->version(), $string); } diff --git a/app/Library/getid3/demos/demo.joinmp3.php b/app/Library/getid3/demos/demo.joinmp3.php index b819e930..117e856e 100644 --- a/app/Library/getid3/demos/demo.joinmp3.php +++ b/app/Library/getid3/demos/demo.joinmp3.php @@ -33,103 +33,91 @@ // CombineMultipleMP3sTo('sample.mp3', array(array('input.mp3', 0, 30))); // extract first 30 seconds of audio -function CombineMultipleMP3sTo($FilenameOut, $FilenamesIn) { +function CombineMultipleMP3sTo($FilenameOut, $FilenamesIn) +{ - foreach ($FilenamesIn as $nextinputfilename) { - if (is_array($nextinputfilename)) { - $nextinputfilename = $nextinputfilename[0]; - } - if (!is_readable($nextinputfilename)) { - echo 'Cannot read "'.$nextinputfilename.'"
'; - return false; - } - } - if ((file_exists($FilenameOut) && !is_writeable($FilenameOut)) || (!file_exists($FilenameOut) && !is_writeable(dirname($FilenameOut)))) { - echo 'Cannot write "'.$FilenameOut.'"
'; - return false; - } + foreach ($FilenamesIn as $nextinputfilename) { + if (is_array($nextinputfilename)) { + $nextinputfilename = $nextinputfilename[0]; + } + if (!is_readable($nextinputfilename)) { + echo 'Cannot read "'.$nextinputfilename.'"
'; + return false; + } + } + if ((file_exists($FilenameOut) && !is_writeable($FilenameOut)) || (!file_exists($FilenameOut) && !is_writeable(dirname($FilenameOut)))) { + echo 'Cannot write "'.$FilenameOut.'"
'; + return false; + } - require_once(dirname(__FILE__).'/../getid3/getid3.php'); - ob_start(); - if ($fp_output = fopen($FilenameOut, 'wb')) { + require_once(dirname(__FILE__).'/../getid3/getid3.php'); + ob_start(); + if ($fp_output = fopen($FilenameOut, 'wb')) { + ob_end_clean(); + // Initialize getID3 engine + $getID3 = new getID3; + foreach ($FilenamesIn as $nextinputfilename) { + $startoffset = 0; + $length_seconds = 0; + if (is_array($nextinputfilename)) { + @list($nextinputfilename, $startoffset, $length_seconds) = $nextinputfilename; + } + $CurrentFileInfo = $getID3->analyze($nextinputfilename); + if ($CurrentFileInfo['fileformat'] == 'mp3') { + ob_start(); + if ($fp_source = fopen($nextinputfilename, 'rb')) { + ob_end_clean(); + $CurrentOutputPosition = ftell($fp_output); - ob_end_clean(); - // Initialize getID3 engine - $getID3 = new getID3; - foreach ($FilenamesIn as $nextinputfilename) { - $startoffset = 0; - $length_seconds = 0; - if (is_array($nextinputfilename)) { - @list($nextinputfilename, $startoffset, $length_seconds) = $nextinputfilename; - } - $CurrentFileInfo = $getID3->analyze($nextinputfilename); - if ($CurrentFileInfo['fileformat'] == 'mp3') { + // copy audio data from first file + $start_offset_bytes = $CurrentFileInfo['avdataoffset']; + if ($startoffset > 0) { // start X seconds from start of audio + $start_offset_bytes = $CurrentFileInfo['avdataoffset'] + round($CurrentFileInfo['bitrate'] / 8 * $startoffset); + } elseif ($startoffset < 0) { // start X seconds from end of audio + $start_offset_bytes = $CurrentFileInfo['avdataend'] + round($CurrentFileInfo['bitrate'] / 8 * $startoffset); + } + $start_offset_bytes = max($CurrentFileInfo['avdataoffset'], min($CurrentFileInfo['avdataend'], $start_offset_bytes)); - ob_start(); - if ($fp_source = fopen($nextinputfilename, 'rb')) { + $end_offset_bytes = $CurrentFileInfo['avdataend']; + if ($length_seconds > 0) { // seconds from start of audio + $end_offset_bytes = $start_offset_bytes + round($CurrentFileInfo['bitrate'] / 8 * $length_seconds); + } elseif ($length_seconds < 0) { // seconds from start of audio + $end_offset_bytes = $CurrentFileInfo['avdataend'] + round($CurrentFileInfo['bitrate'] / 8 * $startoffset); + } + $end_offset_bytes = max($CurrentFileInfo['avdataoffset'], min($CurrentFileInfo['avdataend'], $end_offset_bytes)); - ob_end_clean(); - $CurrentOutputPosition = ftell($fp_output); + if ($end_offset_bytes <= $start_offset_bytes) { + echo 'failed to copy '.$nextinputfilename.' from '.$startoffset.'-seconds start for '.$length_seconds.'-seconds length (not enough data)'; + fclose($fp_source); + fclose($fp_output); + return false; + } - // copy audio data from first file - $start_offset_bytes = $CurrentFileInfo['avdataoffset']; - if ($startoffset > 0) { // start X seconds from start of audio - $start_offset_bytes = $CurrentFileInfo['avdataoffset'] + round($CurrentFileInfo['bitrate'] / 8 * $startoffset); - } elseif ($startoffset < 0) { // start X seconds from end of audio - $start_offset_bytes = $CurrentFileInfo['avdataend'] + round($CurrentFileInfo['bitrate'] / 8 * $startoffset); - } - $start_offset_bytes = max($CurrentFileInfo['avdataoffset'], min($CurrentFileInfo['avdataend'], $start_offset_bytes)); + fseek($fp_source, $start_offset_bytes, SEEK_SET); + while (!feof($fp_source) && (ftell($fp_source) < $end_offset_bytes)) { + fwrite($fp_output, fread($fp_source, min(32768, $end_offset_bytes - ftell($fp_source)))); + } + fclose($fp_source); + } else { + $errormessage = ob_get_contents(); + ob_end_clean(); + echo 'failed to open '.$nextinputfilename.' for reading'; + fclose($fp_output); + return false; + } + } else { + echo $nextinputfilename.' is not MP3 format'; + fclose($fp_output); + return false; + } + } + } else { + $errormessage = ob_get_contents(); + ob_end_clean(); + echo 'failed to open '.$FilenameOut.' for writing'; + return false; + } - $end_offset_bytes = $CurrentFileInfo['avdataend']; - if ($length_seconds > 0) { // seconds from start of audio - $end_offset_bytes = $start_offset_bytes + round($CurrentFileInfo['bitrate'] / 8 * $length_seconds); - } elseif ($length_seconds < 0) { // seconds from start of audio - $end_offset_bytes = $CurrentFileInfo['avdataend'] + round($CurrentFileInfo['bitrate'] / 8 * $startoffset); - } - $end_offset_bytes = max($CurrentFileInfo['avdataoffset'], min($CurrentFileInfo['avdataend'], $end_offset_bytes)); - - if ($end_offset_bytes <= $start_offset_bytes) { - echo 'failed to copy '.$nextinputfilename.' from '.$startoffset.'-seconds start for '.$length_seconds.'-seconds length (not enough data)'; - fclose($fp_source); - fclose($fp_output); - return false; - } - - fseek($fp_source, $start_offset_bytes, SEEK_SET); - while (!feof($fp_source) && (ftell($fp_source) < $end_offset_bytes)) { - fwrite($fp_output, fread($fp_source, min(32768, $end_offset_bytes - ftell($fp_source)))); - } - fclose($fp_source); - - } else { - - $errormessage = ob_get_contents(); - ob_end_clean(); - echo 'failed to open '.$nextinputfilename.' for reading'; - fclose($fp_output); - return false; - - } - - } else { - - echo $nextinputfilename.' is not MP3 format'; - fclose($fp_output); - return false; - - } - - } - - } else { - - $errormessage = ob_get_contents(); - ob_end_clean(); - echo 'failed to open '.$FilenameOut.' for writing'; - return false; - - } - - fclose($fp_output); - return true; + fclose($fp_output); + return true; } diff --git a/app/Library/getid3/demos/demo.mimeonly.php b/app/Library/getid3/demos/demo.mimeonly.php index 9a381780..57da51e9 100644 --- a/app/Library/getid3/demos/demo.mimeonly.php +++ b/app/Library/getid3/demos/demo.mimeonly.php @@ -20,55 +20,50 @@ echo 'getID3 demos - MIME type only'; if (!empty($_REQUEST['filename'])) { - - echo 'The file "'.htmlentities($_REQUEST['filename']).'" has a MIME type of "'.htmlentities(GetMIMEtype($_REQUEST['filename'])).'"'; - + echo 'The file "'.htmlentities($_REQUEST['filename']).'" has a MIME type of "'.htmlentities(GetMIMEtype($_REQUEST['filename'])).'"'; } else { - - echo 'Usage: '.htmlentities($_SERVER['PHP_SELF']).'?filename=filename.ext'; - + echo 'Usage: '.htmlentities($_SERVER['PHP_SELF']).'?filename=filename.ext'; } -function GetMIMEtype($filename) { - $filename = realpath($filename); - if (!file_exists($filename)) { - echo 'File does not exist: "'.htmlentities($filename).'"
'; - return ''; - } elseif (!is_readable($filename)) { - echo 'File is not readable: "'.htmlentities($filename).'"
'; - return ''; - } +function GetMIMEtype($filename) +{ + $filename = realpath($filename); + if (!file_exists($filename)) { + echo 'File does not exist: "'.htmlentities($filename).'"
'; + return ''; + } elseif (!is_readable($filename)) { + echo 'File is not readable: "'.htmlentities($filename).'"
'; + return ''; + } - // include getID3() library (can be in a different directory if full path is specified) - require_once('../getid3/getid3.php'); - // Initialize getID3 engine - $getID3 = new getID3; + // include getID3() library (can be in a different directory if full path is specified) + require_once('../getid3/getid3.php'); + // Initialize getID3 engine + $getID3 = new getID3; - $DeterminedMIMEtype = ''; - if ($fp = fopen($filename, 'rb')) { - $getID3->openfile($filename); - if (empty($getID3->info['error'])) { + $DeterminedMIMEtype = ''; + if ($fp = fopen($filename, 'rb')) { + $getID3->openfile($filename); + if (empty($getID3->info['error'])) { + // ID3v2 is the only tag format that might be prepended in front of files, and it's non-trivial to skip, easier just to parse it and know where to skip to + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true); + $getid3_id3v2 = new getid3_id3v2($getID3); + $getid3_id3v2->Analyze(); - // ID3v2 is the only tag format that might be prepended in front of files, and it's non-trivial to skip, easier just to parse it and know where to skip to - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true); - $getid3_id3v2 = new getid3_id3v2($getID3); - $getid3_id3v2->Analyze(); + fseek($fp, $getID3->info['avdataoffset'], SEEK_SET); + $formattest = fread($fp, 16); // 16 bytes is sufficient for any format except ISO CD-image + fclose($fp); - fseek($fp, $getID3->info['avdataoffset'], SEEK_SET); - $formattest = fread($fp, 16); // 16 bytes is sufficient for any format except ISO CD-image - fclose($fp); - - $DeterminedFormatInfo = $getID3->GetFileFormat($formattest); - $DeterminedMIMEtype = $DeterminedFormatInfo['mime_type']; - - } else { - echo 'Failed to getID3->openfile "'.htmlentities($filename).'"
'; - } - } else { - echo 'Failed to fopen "'.htmlentities($filename).'"
'; - } - return $DeterminedMIMEtype; + $DeterminedFormatInfo = $getID3->GetFileFormat($formattest); + $DeterminedMIMEtype = $DeterminedFormatInfo['mime_type']; + } else { + echo 'Failed to getID3->openfile "'.htmlentities($filename).'"
'; + } + } else { + echo 'Failed to fopen "'.htmlentities($filename).'"
'; + } + return $DeterminedMIMEtype; } -echo ''; \ No newline at end of file +echo ''; diff --git a/app/Library/getid3/demos/demo.mp3header.php b/app/Library/getid3/demos/demo.mp3header.php index ad5a3d8a..24207154 100644 --- a/app/Library/getid3/demos/demo.mp3header.php +++ b/app/Library/getid3/demos/demo.mp3header.php @@ -1,1349 +1,1405 @@ '; - foreach ($variable as $key => $value) { - $returnstring .= ''.str_replace(chr(0), ' ', $key).''; - $returnstring .= ''.gettype($value); - if (is_array($value)) { - $returnstring .= ' ('.count($value).')'; - } elseif (is_string($value)) { - $returnstring .= ' ('.strlen($value).')'; - } - if (($key == 'data') && isset($variable['image_mime']) && isset($variable['dataoffset'])) { - require_once(GETID3_INCLUDEPATH.'getid3.getimagesize.php'); - $imageinfo = array(); - if ($imagechunkcheck = GetDataImageSize($value, $imageinfo)) { - $DumpedImageSRC = (!empty($_REQUEST['filename']) ? $_REQUEST['filename'] : '.getid3').'.'.$variable['dataoffset'].'.'.ImageTypesLookup($imagechunkcheck[2]); - if ($tempimagefile = fopen($DumpedImageSRC, 'wb')) { - fwrite($tempimagefile, $value); - fclose($tempimagefile); - } - $returnstring .= ''; - } else { - $returnstring .= 'invalid image data'; - } - } else { - $returnstring .= ''.table_var_dump($value).''; - } - } - $returnstring .= ''; - break; + function table_var_dump($variable) + { + $returnstring = ''; + switch (gettype($variable)) { + case 'array': + $returnstring .= ''; + foreach ($variable as $key => $value) { + $returnstring .= ''; + $returnstring .= ''; + } else { + $returnstring .= ''; + } + } else { + $returnstring .= ''; + } + } + $returnstring .= '
'.str_replace(chr(0), ' ', $key).''.gettype($value); + if (is_array($value)) { + $returnstring .= ' ('.count($value).')'; + } elseif (is_string($value)) { + $returnstring .= ' ('.strlen($value).')'; + } + if (($key == 'data') && isset($variable['image_mime']) && isset($variable['dataoffset'])) { + require_once(GETID3_INCLUDEPATH.'getid3.getimagesize.php'); + $imageinfo = []; + if ($imagechunkcheck = GetDataImageSize($value, $imageinfo)) { + $DumpedImageSRC = (!empty($_REQUEST['filename']) ? $_REQUEST['filename'] : '.getid3').'.'.$variable['dataoffset'].'.'.ImageTypesLookup($imagechunkcheck[2]); + if ($tempimagefile = fopen($DumpedImageSRC, 'wb')) { + fwrite($tempimagefile, $value); + fclose($tempimagefile); + } + $returnstring .= '
invalid image data
'.table_var_dump($value).'
'; + break; - case 'boolean': - $returnstring .= ($variable ? 'TRUE' : 'FALSE'); - break; + case 'boolean': + $returnstring .= ($variable ? 'TRUE' : 'FALSE'); + break; - case 'integer': - case 'double': - case 'float': - $returnstring .= $variable; - break; + case 'integer': + case 'double': + case 'float': + $returnstring .= $variable; + break; - case 'object': - case 'null': - $returnstring .= string_var_dump($variable); - break; + case 'object': + case 'null': + $returnstring .= string_var_dump($variable); + break; - case 'string': - $variable = str_replace(chr(0), ' ', $variable); - $varlen = strlen($variable); - for ($i = 0; $i < $varlen; $i++) { - if (preg_match('#['.chr(0x0A).chr(0x0D).' -;0-9A-Za-z]#', $variable{$i})) { - $returnstring .= $variable{$i}; - } else { - $returnstring .= '&#'.str_pad(ord($variable{$i}), 3, '0', STR_PAD_LEFT).';'; - } - } - $returnstring = nl2br($returnstring); - break; + case 'string': + $variable = str_replace(chr(0), ' ', $variable); + $varlen = strlen($variable); + for ($i = 0; $i < $varlen; $i++) { + if (preg_match('#['.chr(0x0A).chr(0x0D).' -;0-9A-Za-z]#', $variable{$i})) { + $returnstring .= $variable{$i}; + } else { + $returnstring .= '&#'.str_pad(ord($variable{$i}), 3, '0', STR_PAD_LEFT).';'; + } + } + $returnstring = nl2br($returnstring); + break; - default: - require_once(GETID3_INCLUDEPATH.'getid3.getimagesize.php'); - $imageinfo = array(); - if (($imagechunkcheck = GetDataImageSize(substr($variable, 0, 32768), $imageinfo)) && ($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) { - $returnstring .= ''; - $returnstring .= ''; - $returnstring .= ''; - $returnstring .= ''; - $returnstring .= '
type'.ImageTypesLookup($imagechunkcheck[2]).'
width'.number_format($imagechunkcheck[0]).' px
height'.number_format($imagechunkcheck[1]).' px
size'.number_format(strlen($variable)).' bytes
'; - } else { - $returnstring .= nl2br(htmlspecialchars(str_replace(chr(0), ' ', $variable))); - } - break; - } - return $returnstring; - } + default: + require_once(GETID3_INCLUDEPATH.'getid3.getimagesize.php'); + $imageinfo = []; + if (($imagechunkcheck = GetDataImageSize(substr($variable, 0, 32768), $imageinfo)) && ($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) { + $returnstring .= ''; + $returnstring .= ''; + $returnstring .= ''; + $returnstring .= ''; + $returnstring .= '
type'.ImageTypesLookup($imagechunkcheck[2]).'
width'.number_format($imagechunkcheck[0]).' px
height'.number_format($imagechunkcheck[1]).' px
size'.number_format(strlen($variable)).' bytes
'; + } else { + $returnstring .= nl2br(htmlspecialchars(str_replace(chr(0), ' ', $variable))); + } + break; + } + return $returnstring; + } } if (!function_exists('string_var_dump')) { - function string_var_dump($variable) { - if (version_compare(PHP_VERSION, '4.3.0', '>=')) { - return print_r($variable, true); - } - ob_start(); - var_dump($variable); - $dumpedvariable = ob_get_contents(); - ob_end_clean(); - return $dumpedvariable; - } + function string_var_dump($variable) + { + if (version_compare(PHP_VERSION, '4.3.0', '>=')) { + return print_r($variable, true); + } + ob_start(); + var_dump($variable); + $dumpedvariable = ob_get_contents(); + ob_end_clean(); + return $dumpedvariable; + } } if (!function_exists('fileextension')) { - function fileextension($filename, $numextensions=1) { - if (strstr($filename, '.')) { - $reversedfilename = strrev($filename); - $offset = 0; - for ($i = 0; $i < $numextensions; $i++) { - $offset = strpos($reversedfilename, '.', $offset + 1); - if ($offset === false) { - return ''; - } - } - return strrev(substr($reversedfilename, 0, $offset)); - } - return ''; - } + function fileextension($filename, $numextensions = 1) + { + if (strstr($filename, '.')) { + $reversedfilename = strrev($filename); + $offset = 0; + for ($i = 0; $i < $numextensions; $i++) { + $offset = strpos($reversedfilename, '.', $offset + 1); + if ($offset === false) { + return ''; + } + } + return strrev(substr($reversedfilename, 0, $offset)); + } + return ''; + } } if (!function_exists('RemoveAccents')) { - function RemoveAccents($string) { - // return strtr($string, 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'); - // Revised version by marksteward@hotmail.com - return strtr(strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'), array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u')); - } + function RemoveAccents($string) + { + // return strtr($string, 'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy'); + // Revised version by marksteward@hotmail.com + return strtr(strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'), ['Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u']); + } } if (!function_exists('MoreNaturalSort')) { - function MoreNaturalSort($ar1, $ar2) { - if ($ar1 === $ar2) { - return 0; - } - $len1 = strlen($ar1); - $len2 = strlen($ar2); - $shortest = min($len1, $len2); - if (substr($ar1, 0, $shortest) === substr($ar2, 0, $shortest)) { - // the shorter argument is the beginning of the longer one, like "str" and "string" - if ($len1 < $len2) { - return -1; - } elseif ($len1 > $len2) { - return 1; - } - return 0; - } - $ar1 = RemoveAccents(strtolower(trim($ar1))); - $ar2 = RemoveAccents(strtolower(trim($ar2))); - $translatearray = array('\''=>'', '"'=>'', '_'=>' ', '('=>'', ')'=>'', '-'=>' ', ' '=>' ', '.'=>'', ','=>''); - foreach ($translatearray as $key => $val) { - $ar1 = str_replace($key, $val, $ar1); - $ar2 = str_replace($key, $val, $ar2); - } + function MoreNaturalSort($ar1, $ar2) + { + if ($ar1 === $ar2) { + return 0; + } + $len1 = strlen($ar1); + $len2 = strlen($ar2); + $shortest = min($len1, $len2); + if (substr($ar1, 0, $shortest) === substr($ar2, 0, $shortest)) { + // the shorter argument is the beginning of the longer one, like "str" and "string" + if ($len1 < $len2) { + return -1; + } elseif ($len1 > $len2) { + return 1; + } + return 0; + } + $ar1 = RemoveAccents(strtolower(trim($ar1))); + $ar2 = RemoveAccents(strtolower(trim($ar2))); + $translatearray = ['\''=>'', '"'=>'', '_'=>' ', '('=>'', ')'=>'', '-'=>' ', ' '=>' ', '.'=>'', ','=>'']; + foreach ($translatearray as $key => $val) { + $ar1 = str_replace($key, $val, $ar1); + $ar2 = str_replace($key, $val, $ar2); + } - if ($ar1 < $ar2) { - return -1; - } elseif ($ar1 > $ar2) { - return 1; - } - return 0; - } + if ($ar1 < $ar2) { + return -1; + } elseif ($ar1 > $ar2) { + return 1; + } + return 0; + } } if (!function_exists('trunc')) { - function trunc($floatnumber) { - // truncates a floating-point number at the decimal point - // returns int (if possible, otherwise float) - if ($floatnumber >= 1) { - $truncatednumber = floor($floatnumber); - } elseif ($floatnumber <= -1) { - $truncatednumber = ceil($floatnumber); - } else { - $truncatednumber = 0; - } - if ($truncatednumber <= pow(2, 30)) { - $truncatednumber = (int) $truncatednumber; - } - return $truncatednumber; - } + function trunc($floatnumber) + { + // truncates a floating-point number at the decimal point + // returns int (if possible, otherwise float) + if ($floatnumber >= 1) { + $truncatednumber = floor($floatnumber); + } elseif ($floatnumber <= -1) { + $truncatednumber = ceil($floatnumber); + } else { + $truncatednumber = 0; + } + if ($truncatednumber <= pow(2, 30)) { + $truncatednumber = (int) $truncatednumber; + } + return $truncatednumber; + } } if (!function_exists('CastAsInt')) { - function CastAsInt($floatnum) { - // convert to float if not already - $floatnum = (float) $floatnum; + function CastAsInt($floatnum) + { + // convert to float if not already + $floatnum = (float) $floatnum; - // convert a float to type int, only if possible - if (trunc($floatnum) == $floatnum) { - // it's not floating point - if ($floatnum <= pow(2, 30)) { - // it's within int range - $floatnum = (int) $floatnum; - } - } - return $floatnum; - } + // convert a float to type int, only if possible + if (trunc($floatnum) == $floatnum) { + // it's not floating point + if ($floatnum <= pow(2, 30)) { + // it's within int range + $floatnum = (int) $floatnum; + } + } + return $floatnum; + } } if (!function_exists('getmicrotime')) { - function getmicrotime() { - list($usec, $sec) = explode(' ', microtime()); - return ((float) $usec + (float) $sec); - } + function getmicrotime() + { + list($usec, $sec) = explode(' ', microtime()); + return ((float) $usec + (float) $sec); + } } if (!function_exists('DecimalBinary2Float')) { - function DecimalBinary2Float($binarynumerator) { - $numerator = Bin2Dec($binarynumerator); - $denominator = Bin2Dec(str_repeat('1', strlen($binarynumerator))); - return ($numerator / $denominator); - } + function DecimalBinary2Float($binarynumerator) + { + $numerator = Bin2Dec($binarynumerator); + $denominator = Bin2Dec(str_repeat('1', strlen($binarynumerator))); + return ($numerator / $denominator); + } } if (!function_exists('NormalizeBinaryPoint')) { - function NormalizeBinaryPoint($binarypointnumber, $maxbits=52) { - // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html - if (strpos($binarypointnumber, '.') === false) { - $binarypointnumber = '0.'.$binarypointnumber; - } elseif ($binarypointnumber{0} == '.') { - $binarypointnumber = '0'.$binarypointnumber; - } - $exponent = 0; - while (($binarypointnumber{0} != '1') || (substr($binarypointnumber, 1, 1) != '.')) { - if (substr($binarypointnumber, 1, 1) == '.') { - $exponent--; - $binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3); - } else { - $pointpos = strpos($binarypointnumber, '.'); - $exponent += ($pointpos - 1); - $binarypointnumber = str_replace('.', '', $binarypointnumber); - $binarypointnumber = $binarypointnumber{0}.'.'.substr($binarypointnumber, 1); - } - } - $binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT); - return array('normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent); - } + function NormalizeBinaryPoint($binarypointnumber, $maxbits = 52) + { + // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html + if (strpos($binarypointnumber, '.') === false) { + $binarypointnumber = '0.'.$binarypointnumber; + } elseif ($binarypointnumber{0} == '.') { + $binarypointnumber = '0'.$binarypointnumber; + } + $exponent = 0; + while (($binarypointnumber{0} != '1') || (substr($binarypointnumber, 1, 1) != '.')) { + if (substr($binarypointnumber, 1, 1) == '.') { + $exponent--; + $binarypointnumber = substr($binarypointnumber, 2, 1).'.'.substr($binarypointnumber, 3); + } else { + $pointpos = strpos($binarypointnumber, '.'); + $exponent += ($pointpos - 1); + $binarypointnumber = str_replace('.', '', $binarypointnumber); + $binarypointnumber = $binarypointnumber{0}.'.'.substr($binarypointnumber, 1); + } + } + $binarypointnumber = str_pad(substr($binarypointnumber, 0, $maxbits + 2), $maxbits + 2, '0', STR_PAD_RIGHT); + return ['normalized'=>$binarypointnumber, 'exponent'=>(int) $exponent]; + } } if (!function_exists('Float2BinaryDecimal')) { - function Float2BinaryDecimal($floatvalue) { - // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html - $maxbits = 128; // to how many bits of precision should the calculations be taken? - $intpart = trunc($floatvalue); - $floatpart = abs($floatvalue - $intpart); - $pointbitstring = ''; - while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) { - $floatpart *= 2; - $pointbitstring .= (string) trunc($floatpart); - $floatpart -= trunc($floatpart); - } - $binarypointnumber = decbin($intpart).'.'.$pointbitstring; - return $binarypointnumber; - } + function Float2BinaryDecimal($floatvalue) + { + // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html + $maxbits = 128; // to how many bits of precision should the calculations be taken? + $intpart = trunc($floatvalue); + $floatpart = abs($floatvalue - $intpart); + $pointbitstring = ''; + while (($floatpart != 0) && (strlen($pointbitstring) < $maxbits)) { + $floatpart *= 2; + $pointbitstring .= (string) trunc($floatpart); + $floatpart -= trunc($floatpart); + } + $binarypointnumber = decbin($intpart).'.'.$pointbitstring; + return $binarypointnumber; + } } if (!function_exists('Float2String')) { - function Float2String($floatvalue, $bits) { - // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html - switch ($bits) { - case 32: - $exponentbits = 8; - $fractionbits = 23; - break; + function Float2String($floatvalue, $bits) + { + // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html + switch ($bits) { + case 32: + $exponentbits = 8; + $fractionbits = 23; + break; - case 64: - $exponentbits = 11; - $fractionbits = 52; - break; + case 64: + $exponentbits = 11; + $fractionbits = 52; + break; - default: - return false; - break; - } - if ($floatvalue >= 0) { - $signbit = '0'; - } else { - $signbit = '1'; - } - $normalizedbinary = NormalizeBinaryPoint(Float2BinaryDecimal($floatvalue), $fractionbits); - $biasedexponent = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent - $exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT); - $fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT); + default: + return false; + break; + } + if ($floatvalue >= 0) { + $signbit = '0'; + } else { + $signbit = '1'; + } + $normalizedbinary = NormalizeBinaryPoint(Float2BinaryDecimal($floatvalue), $fractionbits); + $biasedexponent = pow(2, $exponentbits - 1) - 1 + $normalizedbinary['exponent']; // (127 or 1023) +/- exponent + $exponentbitstring = str_pad(decbin($biasedexponent), $exponentbits, '0', STR_PAD_LEFT); + $fractionbitstring = str_pad(substr($normalizedbinary['normalized'], 2), $fractionbits, '0', STR_PAD_RIGHT); - return BigEndian2String(Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false); - } + return BigEndian2String(Bin2Dec($signbit.$exponentbitstring.$fractionbitstring), $bits % 8, false); + } } if (!function_exists('LittleEndian2Float')) { - function LittleEndian2Float($byteword) { - return BigEndian2Float(strrev($byteword)); - } + function LittleEndian2Float($byteword) + { + return BigEndian2Float(strrev($byteword)); + } } if (!function_exists('BigEndian2Float')) { - function BigEndian2Float($byteword) { - // ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic - // http://www.psc.edu/general/software/packages/ieee/ieee.html - // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html + function BigEndian2Float($byteword) + { + // ANSI/IEEE Standard 754-1985, Standard for Binary Floating Point Arithmetic + // http://www.psc.edu/general/software/packages/ieee/ieee.html + // http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee.html - $bitword = BigEndian2Bin($byteword); - $signbit = $bitword{0}; + $bitword = BigEndian2Bin($byteword); + $signbit = $bitword{0}; - switch (strlen($byteword) * 8) { - case 32: - $exponentbits = 8; - $fractionbits = 23; - break; + switch (strlen($byteword) * 8) { + case 32: + $exponentbits = 8; + $fractionbits = 23; + break; - case 64: - $exponentbits = 11; - $fractionbits = 52; - break; + case 64: + $exponentbits = 11; + $fractionbits = 52; + break; - case 80: - $exponentbits = 16; - $fractionbits = 64; - break; + case 80: + $exponentbits = 16; + $fractionbits = 64; + break; - default: - return false; - break; - } - $exponentstring = substr($bitword, 1, $exponentbits - 1); - $fractionstring = substr($bitword, $exponentbits, $fractionbits); - $exponent = Bin2Dec($exponentstring); - $fraction = Bin2Dec($fractionstring); + default: + return false; + break; + } + $exponentstring = substr($bitword, 1, $exponentbits - 1); + $fractionstring = substr($bitword, $exponentbits, $fractionbits); + $exponent = Bin2Dec($exponentstring); + $fraction = Bin2Dec($fractionstring); - if (($exponentbits == 16) && ($fractionbits == 64)) { - // 80-bit - // As used in Apple AIFF for sample_rate - // A bit of a hack, but it works ;) - return pow(2, ($exponent - 16382)) * DecimalBinary2Float($fractionstring); - } + if (($exponentbits == 16) && ($fractionbits == 64)) { + // 80-bit + // As used in Apple AIFF for sample_rate + // A bit of a hack, but it works ;) + return pow(2, ($exponent - 16382)) * DecimalBinary2Float($fractionstring); + } - if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) { - // Not a Number - $floatvalue = false; - } elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) { - if ($signbit == '1') { - $floatvalue = '-infinity'; - } else { - $floatvalue = '+infinity'; - } - } elseif (($exponent == 0) && ($fraction == 0)) { - if ($signbit == '1') { - $floatvalue = -0; - } else { - $floatvalue = 0; - } - $floatvalue = ($signbit ? 0 : -0); - } elseif (($exponent == 0) && ($fraction != 0)) { - // These are 'unnormalized' values - $floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * DecimalBinary2Float($fractionstring); - if ($signbit == '1') { - $floatvalue *= -1; - } - } elseif ($exponent != 0) { - $floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + DecimalBinary2Float($fractionstring)); - if ($signbit == '1') { - $floatvalue *= -1; - } - } - return (float) $floatvalue; - } + if (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction != 0)) { + // Not a Number + $floatvalue = false; + } elseif (($exponent == (pow(2, $exponentbits) - 1)) && ($fraction == 0)) { + if ($signbit == '1') { + $floatvalue = '-infinity'; + } else { + $floatvalue = '+infinity'; + } + } elseif (($exponent == 0) && ($fraction == 0)) { + if ($signbit == '1') { + $floatvalue = -0; + } else { + $floatvalue = 0; + } + $floatvalue = ($signbit ? 0 : -0); + } elseif (($exponent == 0) && ($fraction != 0)) { + // These are 'unnormalized' values + $floatvalue = pow(2, (-1 * (pow(2, $exponentbits - 1) - 2))) * DecimalBinary2Float($fractionstring); + if ($signbit == '1') { + $floatvalue *= -1; + } + } elseif ($exponent != 0) { + $floatvalue = pow(2, ($exponent - (pow(2, $exponentbits - 1) - 1))) * (1 + DecimalBinary2Float($fractionstring)); + if ($signbit == '1') { + $floatvalue *= -1; + } + } + return (float) $floatvalue; + } } if (!function_exists('BigEndian2Int')) { - function BigEndian2Int($byteword, $synchsafe=false, $signed=false) { - $intvalue = 0; - $bytewordlen = strlen($byteword); - for ($i = 0; $i < $bytewordlen; $i++) { - if ($synchsafe) { // disregard MSB, effectively 7-bit bytes - $intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); - } else { - $intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i)); - } - } - if ($signed && !$synchsafe) { - // synchsafe ints are not allowed to be signed - switch ($bytewordlen) { - case 1: - case 2: - case 3: - case 4: - $signmaskbit = 0x80 << (8 * ($bytewordlen - 1)); - if ($intvalue & $signmaskbit) { - $intvalue = 0 - ($intvalue & ($signmaskbit - 1)); - } - break; + function BigEndian2Int($byteword, $synchsafe = false, $signed = false) + { + $intvalue = 0; + $bytewordlen = strlen($byteword); + for ($i = 0; $i < $bytewordlen; $i++) { + if ($synchsafe) { // disregard MSB, effectively 7-bit bytes + $intvalue = $intvalue | (ord($byteword{$i}) & 0x7F) << (($bytewordlen - 1 - $i) * 7); + } else { + $intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i)); + } + } + if ($signed && !$synchsafe) { + // synchsafe ints are not allowed to be signed + switch ($bytewordlen) { + case 1: + case 2: + case 3: + case 4: + $signmaskbit = 0x80 << (8 * ($bytewordlen - 1)); + if ($intvalue & $signmaskbit) { + $intvalue = 0 - ($intvalue & ($signmaskbit - 1)); + } + break; - default: - die('ERROR: Cannot have signed integers larger than 32-bits in BigEndian2Int()'); - break; - } - } - return CastAsInt($intvalue); - } + default: + die('ERROR: Cannot have signed integers larger than 32-bits in BigEndian2Int()'); + break; + } + } + return CastAsInt($intvalue); + } } if (!function_exists('LittleEndian2Int')) { - function LittleEndian2Int($byteword, $signed=false) { - return BigEndian2Int(strrev($byteword), false, $signed); - } + function LittleEndian2Int($byteword, $signed = false) + { + return BigEndian2Int(strrev($byteword), false, $signed); + } } if (!function_exists('BigEndian2Bin')) { - function BigEndian2Bin($byteword) { - $binvalue = ''; - $bytewordlen = strlen($byteword); - for ($i = 0; $i < $bytewordlen; $i++) { - $binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT); - } - return $binvalue; - } + function BigEndian2Bin($byteword) + { + $binvalue = ''; + $bytewordlen = strlen($byteword); + for ($i = 0; $i < $bytewordlen; $i++) { + $binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT); + } + return $binvalue; + } } if (!function_exists('BigEndian2String')) { - function BigEndian2String($number, $minbytes=1, $synchsafe=false, $signed=false) { - if ($number < 0) { - return false; - } - $maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF); - $intstring = ''; - if ($signed) { - if ($minbytes > 4) { - die('ERROR: Cannot have signed integers larger than 32-bits in BigEndian2String()'); - } - $number = $number & (0x80 << (8 * ($minbytes - 1))); - } - while ($number != 0) { - $quotient = ($number / ($maskbyte + 1)); - $intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring; - $number = floor($quotient); - } - return str_pad($intstring, $minbytes, chr(0), STR_PAD_LEFT); - } + function BigEndian2String($number, $minbytes = 1, $synchsafe = false, $signed = false) + { + if ($number < 0) { + return false; + } + $maskbyte = (($synchsafe || $signed) ? 0x7F : 0xFF); + $intstring = ''; + if ($signed) { + if ($minbytes > 4) { + die('ERROR: Cannot have signed integers larger than 32-bits in BigEndian2String()'); + } + $number = $number & (0x80 << (8 * ($minbytes - 1))); + } + while ($number != 0) { + $quotient = ($number / ($maskbyte + 1)); + $intstring = chr(ceil(($quotient - floor($quotient)) * $maskbyte)).$intstring; + $number = floor($quotient); + } + return str_pad($intstring, $minbytes, chr(0), STR_PAD_LEFT); + } } if (!function_exists('Dec2Bin')) { - function Dec2Bin($number) { - while ($number >= 256) { - $bytes[] = (($number / 256) - (floor($number / 256))) * 256; - $number = floor($number / 256); - } - $bytes[] = $number; - $binstring = ''; - for ($i = 0; $i < count($bytes); $i++) { - $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring; - } - return $binstring; - } + function Dec2Bin($number) + { + while ($number >= 256) { + $bytes[] = (($number / 256) - (floor($number / 256))) * 256; + $number = floor($number / 256); + } + $bytes[] = $number; + $binstring = ''; + for ($i = 0; $i < count($bytes); $i++) { + $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, '0', STR_PAD_LEFT)).$binstring; + } + return $binstring; + } } if (!function_exists('Bin2Dec')) { - function Bin2Dec($binstring) { - $decvalue = 0; - for ($i = 0; $i < strlen($binstring); $i++) { - $decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i); - } - return CastAsInt($decvalue); - } + function Bin2Dec($binstring) + { + $decvalue = 0; + for ($i = 0; $i < strlen($binstring); $i++) { + $decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i); + } + return CastAsInt($decvalue); + } } if (!function_exists('Bin2String')) { - function Bin2String($binstring) { - // return 'hi' for input of '0110100001101001' - $string = ''; - $binstringreversed = strrev($binstring); - for ($i = 0; $i < strlen($binstringreversed); $i += 8) { - $string = chr(Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string; - } - return $string; - } + function Bin2String($binstring) + { + // return 'hi' for input of '0110100001101001' + $string = ''; + $binstringreversed = strrev($binstring); + for ($i = 0; $i < strlen($binstringreversed); $i += 8) { + $string = chr(Bin2Dec(strrev(substr($binstringreversed, $i, 8)))).$string; + } + return $string; + } } if (!function_exists('LittleEndian2String')) { - function LittleEndian2String($number, $minbytes=1, $synchsafe=false) { - $intstring = ''; - while ($number > 0) { - if ($synchsafe) { - $intstring = $intstring.chr($number & 127); - $number >>= 7; - } else { - $intstring = $intstring.chr($number & 255); - $number >>= 8; - } - } - return str_pad($intstring, $minbytes, chr(0), STR_PAD_RIGHT); - } + function LittleEndian2String($number, $minbytes = 1, $synchsafe = false) + { + $intstring = ''; + while ($number > 0) { + if ($synchsafe) { + $intstring = $intstring.chr($number & 127); + $number >>= 7; + } else { + $intstring = $intstring.chr($number & 255); + $number >>= 8; + } + } + return str_pad($intstring, $minbytes, chr(0), STR_PAD_RIGHT); + } } if (!function_exists('Bool2IntString')) { - function Bool2IntString($intvalue) { - return ($intvalue ? '1' : '0'); - } + function Bool2IntString($intvalue) + { + return ($intvalue ? '1' : '0'); + } } if (!function_exists('IntString2Bool')) { - function IntString2Bool($char) { - if ($char == '1') { - return true; - } elseif ($char == '0') { - return false; - } - return null; - } + function IntString2Bool($char) + { + if ($char == '1') { + return true; + } elseif ($char == '0') { + return false; + } + return null; + } } if (!function_exists('InverseBoolean')) { - function InverseBoolean($value) { - return ($value ? false : true); - } + function InverseBoolean($value) + { + return ($value ? false : true); + } } if (!function_exists('DeUnSynchronise')) { - function DeUnSynchronise($data) { - return str_replace(chr(0xFF).chr(0x00), chr(0xFF), $data); - } + function DeUnSynchronise($data) + { + return str_replace(chr(0xFF).chr(0x00), chr(0xFF), $data); + } } if (!function_exists('Unsynchronise')) { - function Unsynchronise($data) { - // Whenever a false synchronisation is found within the tag, one zeroed - // byte is inserted after the first false synchronisation byte. The - // format of a correct sync that should be altered by ID3 encoders is as - // follows: - // %11111111 111xxxxx - // And should be replaced with: - // %11111111 00000000 111xxxxx - // This has the side effect that all $FF 00 combinations have to be - // altered, so they won't be affected by the decoding process. Therefore - // all the $FF 00 combinations have to be replaced with the $FF 00 00 - // combination during the unsynchronisation. + function Unsynchronise($data) + { + // Whenever a false synchronisation is found within the tag, one zeroed + // byte is inserted after the first false synchronisation byte. The + // format of a correct sync that should be altered by ID3 encoders is as + // follows: + // %11111111 111xxxxx + // And should be replaced with: + // %11111111 00000000 111xxxxx + // This has the side effect that all $FF 00 combinations have to be + // altered, so they won't be affected by the decoding process. Therefore + // all the $FF 00 combinations have to be replaced with the $FF 00 00 + // combination during the unsynchronisation. - $data = str_replace(chr(0xFF).chr(0x00), chr(0xFF).chr(0x00).chr(0x00), $data); - $unsyncheddata = ''; - for ($i = 0; $i < strlen($data); $i++) { - $thischar = $data{$i}; - $unsyncheddata .= $thischar; - if ($thischar == chr(255)) { - $nextchar = ord(substr($data, $i + 1, 1)); - if (($nextchar | 0xE0) == 0xE0) { - // previous byte = 11111111, this byte = 111????? - $unsyncheddata .= chr(0); - } - } - } - return $unsyncheddata; - } + $data = str_replace(chr(0xFF).chr(0x00), chr(0xFF).chr(0x00).chr(0x00), $data); + $unsyncheddata = ''; + for ($i = 0; $i < strlen($data); $i++) { + $thischar = $data{$i}; + $unsyncheddata .= $thischar; + if ($thischar == chr(255)) { + $nextchar = ord(substr($data, $i + 1, 1)); + if (($nextchar | 0xE0) == 0xE0) { + // previous byte = 11111111, this byte = 111????? + $unsyncheddata .= chr(0); + } + } + } + return $unsyncheddata; + } } if (!function_exists('is_hash')) { - function is_hash($var) { - // written by dev-null@christophe.vg - // taken from http://www.php.net/manual/en/function.array-merge-recursive.php - if (is_array($var)) { - $keys = array_keys($var); - $all_num = true; - for ($i = 0; $i < count($keys); $i++) { - if (is_string($keys[$i])) { - return true; - } - } - } - return false; - } + function is_hash($var) + { + // written by dev-null@christophe.vg + // taken from http://www.php.net/manual/en/function.array-merge-recursive.php + if (is_array($var)) { + $keys = array_keys($var); + $all_num = true; + for ($i = 0; $i < count($keys); $i++) { + if (is_string($keys[$i])) { + return true; + } + } + } + return false; + } } if (!function_exists('array_join_merge')) { - function array_join_merge($arr1, $arr2) { - // written by dev-null@christophe.vg - // taken from http://www.php.net/manual/en/function.array-merge-recursive.php - if (is_array($arr1) && is_array($arr2)) { - // the same -> merge - $new_array = array(); + function array_join_merge($arr1, $arr2) + { + // written by dev-null@christophe.vg + // taken from http://www.php.net/manual/en/function.array-merge-recursive.php + if (is_array($arr1) && is_array($arr2)) { + // the same -> merge + $new_array = []; - if (is_hash($arr1) && is_hash($arr2)) { - // hashes -> merge based on keys - $keys = array_merge(array_keys($arr1), array_keys($arr2)); - foreach ($keys as $key) { - $arr1[$key] = (isset($arr1[$key]) ? $arr1[$key] : ''); - $arr2[$key] = (isset($arr2[$key]) ? $arr2[$key] : ''); - $new_array[$key] = array_join_merge($arr1[$key], $arr2[$key]); - } - } else { - // two real arrays -> merge - $new_array = array_reverse(array_unique(array_reverse(array_merge($arr1,$arr2)))); - } - return $new_array; - } else { - // not the same ... take new one if defined, else the old one stays - return $arr2 ? $arr2 : $arr1; - } - } + if (is_hash($arr1) && is_hash($arr2)) { + // hashes -> merge based on keys + $keys = array_merge(array_keys($arr1), array_keys($arr2)); + foreach ($keys as $key) { + $arr1[$key] = (isset($arr1[$key]) ? $arr1[$key] : ''); + $arr2[$key] = (isset($arr2[$key]) ? $arr2[$key] : ''); + $new_array[$key] = array_join_merge($arr1[$key], $arr2[$key]); + } + } else { + // two real arrays -> merge + $new_array = array_reverse(array_unique(array_reverse(array_merge($arr1, $arr2)))); + } + return $new_array; + } else { + // not the same ... take new one if defined, else the old one stays + return $arr2 ? $arr2 : $arr1; + } + } } if (!function_exists('array_merge_clobber')) { - function array_merge_clobber($array1, $array2) { - // written by kc@hireability.com - // taken from http://www.php.net/manual/en/function.array-merge-recursive.php - if (!is_array($array1) || !is_array($array2)) { - return false; - } - $newarray = $array1; - foreach ($array2 as $key => $val) { - if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) { - $newarray[$key] = array_merge_clobber($newarray[$key], $val); - } else { - $newarray[$key] = $val; - } - } - return $newarray; - } + function array_merge_clobber($array1, $array2) + { + // written by kc@hireability.com + // taken from http://www.php.net/manual/en/function.array-merge-recursive.php + if (!is_array($array1) || !is_array($array2)) { + return false; + } + $newarray = $array1; + foreach ($array2 as $key => $val) { + if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) { + $newarray[$key] = array_merge_clobber($newarray[$key], $val); + } else { + $newarray[$key] = $val; + } + } + return $newarray; + } } if (!function_exists('array_merge_noclobber')) { - function array_merge_noclobber($array1, $array2) { - if (!is_array($array1) || !is_array($array2)) { - return false; - } - $newarray = $array1; - foreach ($array2 as $key => $val) { - if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) { - $newarray[$key] = array_merge_noclobber($newarray[$key], $val); - } elseif (!isset($newarray[$key])) { - $newarray[$key] = $val; - } - } - return $newarray; - } + function array_merge_noclobber($array1, $array2) + { + if (!is_array($array1) || !is_array($array2)) { + return false; + } + $newarray = $array1; + foreach ($array2 as $key => $val) { + if (is_array($val) && isset($newarray[$key]) && is_array($newarray[$key])) { + $newarray[$key] = array_merge_noclobber($newarray[$key], $val); + } elseif (!isset($newarray[$key])) { + $newarray[$key] = $val; + } + } + return $newarray; + } } if (!function_exists('RoughTranslateUnicodeToASCII')) { - function RoughTranslateUnicodeToASCII($rawdata, $frame_textencoding) { - // rough translation of data for application that can't handle Unicode data + function RoughTranslateUnicodeToASCII($rawdata, $frame_textencoding) + { + // rough translation of data for application that can't handle Unicode data - $tempstring = ''; - switch ($frame_textencoding) { - case 0: // ISO-8859-1. Terminated with $00. - $asciidata = $rawdata; - break; + $tempstring = ''; + switch ($frame_textencoding) { + case 0: // ISO-8859-1. Terminated with $00. + $asciidata = $rawdata; + break; - case 1: // UTF-16 encoded Unicode with BOM. Terminated with $00 00. - $asciidata = $rawdata; - if (substr($asciidata, 0, 2) == chr(0xFF).chr(0xFE)) { - // remove BOM, only if present (it should be, but...) - $asciidata = substr($asciidata, 2); - } - if (substr($asciidata, strlen($asciidata) - 2, 2) == chr(0).chr(0)) { - $asciidata = substr($asciidata, 0, strlen($asciidata) - 2); // remove terminator, only if present (it should be, but...) - } - for ($i = 0; $i < strlen($asciidata); $i += 2) { - if ((ord($asciidata{$i}) <= 0x7F) || (ord($asciidata{$i}) >= 0xA0)) { - $tempstring .= $asciidata{$i}; - } else { - $tempstring .= '?'; - } - } - $asciidata = $tempstring; - break; + case 1: // UTF-16 encoded Unicode with BOM. Terminated with $00 00. + $asciidata = $rawdata; + if (substr($asciidata, 0, 2) == chr(0xFF).chr(0xFE)) { + // remove BOM, only if present (it should be, but...) + $asciidata = substr($asciidata, 2); + } + if (substr($asciidata, strlen($asciidata) - 2, 2) == chr(0).chr(0)) { + $asciidata = substr($asciidata, 0, strlen($asciidata) - 2); // remove terminator, only if present (it should be, but...) + } + for ($i = 0; $i < strlen($asciidata); $i += 2) { + if ((ord($asciidata{$i}) <= 0x7F) || (ord($asciidata{$i}) >= 0xA0)) { + $tempstring .= $asciidata{$i}; + } else { + $tempstring .= '?'; + } + } + $asciidata = $tempstring; + break; - case 2: // UTF-16BE encoded Unicode without BOM. Terminated with $00 00. - $asciidata = $rawdata; - if (substr($asciidata, strlen($asciidata) - 2, 2) == chr(0).chr(0)) { - $asciidata = substr($asciidata, 0, strlen($asciidata) - 2); // remove terminator, only if present (it should be, but...) - } - for ($i = 0; $i < strlen($asciidata); $i += 2) { - if ((ord($asciidata{$i}) <= 0x7F) || (ord($asciidata{$i}) >= 0xA0)) { - $tempstring .= $asciidata{$i}; - } else { - $tempstring .= '?'; - } - } - $asciidata = $tempstring; - break; + case 2: // UTF-16BE encoded Unicode without BOM. Terminated with $00 00. + $asciidata = $rawdata; + if (substr($asciidata, strlen($asciidata) - 2, 2) == chr(0).chr(0)) { + $asciidata = substr($asciidata, 0, strlen($asciidata) - 2); // remove terminator, only if present (it should be, but...) + } + for ($i = 0; $i < strlen($asciidata); $i += 2) { + if ((ord($asciidata{$i}) <= 0x7F) || (ord($asciidata{$i}) >= 0xA0)) { + $tempstring .= $asciidata{$i}; + } else { + $tempstring .= '?'; + } + } + $asciidata = $tempstring; + break; - case 3: // UTF-8 encoded Unicode. Terminated with $00. - $asciidata = utf8_decode($rawdata); - break; + case 3: // UTF-8 encoded Unicode. Terminated with $00. + $asciidata = utf8_decode($rawdata); + break; - case 255: // Unicode, Big-Endian. Terminated with $00 00. - $asciidata = $rawdata; - if (substr($asciidata, strlen($asciidata) - 2, 2) == chr(0).chr(0)) { - $asciidata = substr($asciidata, 0, strlen($asciidata) - 2); // remove terminator, only if present (it should be, but...) - } - for ($i = 0; ($i + 1) < strlen($asciidata); $i += 2) { - if ((ord($asciidata{($i + 1)}) <= 0x7F) || (ord($asciidata{($i + 1)}) >= 0xA0)) { - $tempstring .= $asciidata{($i + 1)}; - } else { - $tempstring .= '?'; - } - } - $asciidata = $tempstring; - break; + case 255: // Unicode, Big-Endian. Terminated with $00 00. + $asciidata = $rawdata; + if (substr($asciidata, strlen($asciidata) - 2, 2) == chr(0).chr(0)) { + $asciidata = substr($asciidata, 0, strlen($asciidata) - 2); // remove terminator, only if present (it should be, but...) + } + for ($i = 0; ($i + 1) < strlen($asciidata); $i += 2) { + if ((ord($asciidata{($i + 1)}) <= 0x7F) || (ord($asciidata{($i + 1)}) >= 0xA0)) { + $tempstring .= $asciidata{($i + 1)}; + } else { + $tempstring .= '?'; + } + } + $asciidata = $tempstring; + break; - default: - // shouldn't happen, but in case $frame_textencoding is not 1 <= $frame_textencoding <= 4 - // just pass the data through unchanged. - $asciidata = $rawdata; - break; - } - if (substr($asciidata, strlen($asciidata) - 1, 1) == chr(0)) { - // remove null terminator, if present - $asciidata = NoNullString($asciidata); - } - return $asciidata; - // return str_replace(chr(0), '', $asciidata); // just in case any nulls slipped through - } + default: + // shouldn't happen, but in case $frame_textencoding is not 1 <= $frame_textencoding <= 4 + // just pass the data through unchanged. + $asciidata = $rawdata; + break; + } + if (substr($asciidata, strlen($asciidata) - 1, 1) == chr(0)) { + // remove null terminator, if present + $asciidata = NoNullString($asciidata); + } + return $asciidata; + // return str_replace(chr(0), '', $asciidata); // just in case any nulls slipped through + } } if (!function_exists('PlaytimeString')) { - function PlaytimeString($playtimeseconds) { - $contentseconds = round((($playtimeseconds / 60) - floor($playtimeseconds / 60)) * 60); - $contentminutes = floor($playtimeseconds / 60); - if ($contentseconds >= 60) { - $contentseconds -= 60; - $contentminutes++; - } - return number_format($contentminutes).':'.str_pad($contentseconds, 2, 0, STR_PAD_LEFT); - } + function PlaytimeString($playtimeseconds) + { + $contentseconds = round((($playtimeseconds / 60) - floor($playtimeseconds / 60)) * 60); + $contentminutes = floor($playtimeseconds / 60); + if ($contentseconds >= 60) { + $contentseconds -= 60; + $contentminutes++; + } + return number_format($contentminutes).':'.str_pad($contentseconds, 2, 0, STR_PAD_LEFT); + } } if (!function_exists('CloseMatch')) { - function CloseMatch($value1, $value2, $tolerance) { - return (abs($value1 - $value2) <= $tolerance); - } + function CloseMatch($value1, $value2, $tolerance) + { + return (abs($value1 - $value2) <= $tolerance); + } } if (!function_exists('ID3v1matchesID3v2')) { - function ID3v1matchesID3v2($id3v1, $id3v2) { + function ID3v1matchesID3v2($id3v1, $id3v2) + { - $requiredindices = array('title', 'artist', 'album', 'year', 'genre', 'comment'); - foreach ($requiredindices as $requiredindex) { - if (!isset($id3v1["$requiredindex"])) { - $id3v1["$requiredindex"] = ''; - } - if (!isset($id3v2["$requiredindex"])) { - $id3v2["$requiredindex"] = ''; - } - } + $requiredindices = ['title', 'artist', 'album', 'year', 'genre', 'comment']; + foreach ($requiredindices as $requiredindex) { + if (!isset($id3v1["$requiredindex"])) { + $id3v1["$requiredindex"] = ''; + } + if (!isset($id3v2["$requiredindex"])) { + $id3v2["$requiredindex"] = ''; + } + } - if (trim($id3v1['title']) != trim(substr($id3v2['title'], 0, 30))) { - return false; - } - if (trim($id3v1['artist']) != trim(substr($id3v2['artist'], 0, 30))) { - return false; - } - if (trim($id3v1['album']) != trim(substr($id3v2['album'], 0, 30))) { - return false; - } - if (trim($id3v1['year']) != trim(substr($id3v2['year'], 0, 4))) { - return false; - } - if (trim($id3v1['genre']) != trim($id3v2['genre'])) { - return false; - } - if (isset($id3v1['track'])) { - if (!isset($id3v1['track']) || (trim($id3v1['track']) != trim($id3v2['track']))) { - return false; - } - if (trim($id3v1['comment']) != trim(substr($id3v2['comment'], 0, 28))) { - return false; - } - } else { - if (trim($id3v1['comment']) != trim(substr($id3v2['comment'], 0, 30))) { - return false; - } - } - return true; - } + if (trim($id3v1['title']) != trim(substr($id3v2['title'], 0, 30))) { + return false; + } + if (trim($id3v1['artist']) != trim(substr($id3v2['artist'], 0, 30))) { + return false; + } + if (trim($id3v1['album']) != trim(substr($id3v2['album'], 0, 30))) { + return false; + } + if (trim($id3v1['year']) != trim(substr($id3v2['year'], 0, 4))) { + return false; + } + if (trim($id3v1['genre']) != trim($id3v2['genre'])) { + return false; + } + if (isset($id3v1['track'])) { + if (!isset($id3v1['track']) || (trim($id3v1['track']) != trim($id3v2['track']))) { + return false; + } + if (trim($id3v1['comment']) != trim(substr($id3v2['comment'], 0, 28))) { + return false; + } + } else { + if (trim($id3v1['comment']) != trim(substr($id3v2['comment'], 0, 30))) { + return false; + } + } + return true; + } } if (!function_exists('FILETIMEtoUNIXtime')) { - function FILETIMEtoUNIXtime($FILETIME, $round=true) { - // FILETIME is a 64-bit unsigned integer representing - // the number of 100-nanosecond intervals since January 1, 1601 - // UNIX timestamp is number of seconds since January 1, 1970 - // 116444736000000000 = 10000000 * 60 * 60 * 24 * 365 * 369 + 89 leap days - if ($round) { - return round(($FILETIME - 116444736000000000) / 10000000); - } - return ($FILETIME - 116444736000000000) / 10000000; - } + function FILETIMEtoUNIXtime($FILETIME, $round = true) + { + // FILETIME is a 64-bit unsigned integer representing + // the number of 100-nanosecond intervals since January 1, 1601 + // UNIX timestamp is number of seconds since January 1, 1970 + // 116444736000000000 = 10000000 * 60 * 60 * 24 * 365 * 369 + 89 leap days + if ($round) { + return round(($FILETIME - 116444736000000000) / 10000000); + } + return ($FILETIME - 116444736000000000) / 10000000; + } } if (!function_exists('GUIDtoBytestring')) { - function GUIDtoBytestring($GUIDstring) { - // Microsoft defines these 16-byte (128-bit) GUIDs in the strangest way: - // first 4 bytes are in little-endian order - // next 2 bytes are appended in little-endian order - // next 2 bytes are appended in little-endian order - // next 2 bytes are appended in big-endian order - // next 6 bytes are appended in big-endian order + function GUIDtoBytestring($GUIDstring) + { + // Microsoft defines these 16-byte (128-bit) GUIDs in the strangest way: + // first 4 bytes are in little-endian order + // next 2 bytes are appended in little-endian order + // next 2 bytes are appended in little-endian order + // next 2 bytes are appended in big-endian order + // next 6 bytes are appended in big-endian order - // AaBbCcDd-EeFf-GgHh-IiJj-KkLlMmNnOoPp is stored as this 16-byte string: - // $Dd $Cc $Bb $Aa $Ff $Ee $Hh $Gg $Ii $Jj $Kk $Ll $Mm $Nn $Oo $Pp + // AaBbCcDd-EeFf-GgHh-IiJj-KkLlMmNnOoPp is stored as this 16-byte string: + // $Dd $Cc $Bb $Aa $Ff $Ee $Hh $Gg $Ii $Jj $Kk $Ll $Mm $Nn $Oo $Pp - $hexbytecharstring = chr(hexdec(substr($GUIDstring, 6, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 4, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 2, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 0, 2))); + $hexbytecharstring = chr(hexdec(substr($GUIDstring, 6, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 4, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 2, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 0, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 11, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 9, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 11, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 9, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 16, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 14, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 16, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 14, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 19, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 21, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 19, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 21, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 24, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 26, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 28, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 30, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 32, 2))); - $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 34, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 24, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 26, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 28, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 30, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 32, 2))); + $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 34, 2))); - return $hexbytecharstring; - } + return $hexbytecharstring; + } } if (!function_exists('BytestringToGUID')) { - function BytestringToGUID($Bytestring) { - $GUIDstring = str_pad(dechex(ord($Bytestring{3})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{2})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{1})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{0})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= '-'; - $GUIDstring .= str_pad(dechex(ord($Bytestring{5})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{4})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= '-'; - $GUIDstring .= str_pad(dechex(ord($Bytestring{7})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{6})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= '-'; - $GUIDstring .= str_pad(dechex(ord($Bytestring{8})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{9})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= '-'; - $GUIDstring .= str_pad(dechex(ord($Bytestring{10})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{11})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{12})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{13})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{14})), 2, '0', STR_PAD_LEFT); - $GUIDstring .= str_pad(dechex(ord($Bytestring{15})), 2, '0', STR_PAD_LEFT); + function BytestringToGUID($Bytestring) + { + $GUIDstring = str_pad(dechex(ord($Bytestring{3})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{2})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{1})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{0})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= '-'; + $GUIDstring .= str_pad(dechex(ord($Bytestring{5})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{4})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= '-'; + $GUIDstring .= str_pad(dechex(ord($Bytestring{7})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{6})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= '-'; + $GUIDstring .= str_pad(dechex(ord($Bytestring{8})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{9})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= '-'; + $GUIDstring .= str_pad(dechex(ord($Bytestring{10})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{11})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{12})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{13})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{14})), 2, '0', STR_PAD_LEFT); + $GUIDstring .= str_pad(dechex(ord($Bytestring{15})), 2, '0', STR_PAD_LEFT); - return strtoupper($GUIDstring); - } + return strtoupper($GUIDstring); + } } if (!function_exists('BitrateColor')) { - function BitrateColor($bitrate) { - $bitrate /= 3; // scale from 1-768kbps to 1-256kbps - $bitrate--; // scale from 1-256kbps to 0-255kbps - $bitrate = max($bitrate, 0); - $bitrate = min($bitrate, 255); - //$bitrate = max($bitrate, 32); - //$bitrate = min($bitrate, 143); - //$bitrate = ($bitrate * 2) - 32; + function BitrateColor($bitrate) + { + $bitrate /= 3; // scale from 1-768kbps to 1-256kbps + $bitrate--; // scale from 1-256kbps to 0-255kbps + $bitrate = max($bitrate, 0); + $bitrate = min($bitrate, 255); + //$bitrate = max($bitrate, 32); + //$bitrate = min($bitrate, 143); + //$bitrate = ($bitrate * 2) - 32; - $Rcomponent = max(255 - ($bitrate * 2), 0); - $Gcomponent = max(($bitrate * 2) - 255, 0); - if ($bitrate > 127) { - $Bcomponent = max((255 - $bitrate) * 2, 0); - } else { - $Bcomponent = max($bitrate * 2, 0); - } - return str_pad(dechex($Rcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Gcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Bcomponent), 2, '0', STR_PAD_LEFT); - } + $Rcomponent = max(255 - ($bitrate * 2), 0); + $Gcomponent = max(($bitrate * 2) - 255, 0); + if ($bitrate > 127) { + $Bcomponent = max((255 - $bitrate) * 2, 0); + } else { + $Bcomponent = max($bitrate * 2, 0); + } + return str_pad(dechex($Rcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Gcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Bcomponent), 2, '0', STR_PAD_LEFT); + } } if (!function_exists('BitrateText')) { - function BitrateText($bitrate) { - return ''.round($bitrate).' kbps'; - } + function BitrateText($bitrate) + { + return ''.round($bitrate).' kbps'; + } } if (!function_exists('image_type_to_mime_type')) { - function image_type_to_mime_type($imagetypeid) { - // only available in PHP v4.3.0+ - static $image_type_to_mime_type = array(); - if (empty($image_type_to_mime_type)) { - $image_type_to_mime_type[1] = 'image/gif'; // GIF - $image_type_to_mime_type[2] = 'image/jpeg'; // JPEG - $image_type_to_mime_type[3] = 'image/png'; // PNG - $image_type_to_mime_type[4] = 'application/x-shockwave-flash'; // Flash - $image_type_to_mime_type[5] = 'image/psd'; // PSD - $image_type_to_mime_type[6] = 'image/bmp'; // BMP - $image_type_to_mime_type[7] = 'image/tiff'; // TIFF: little-endian (Intel) - $image_type_to_mime_type[8] = 'image/tiff'; // TIFF: big-endian (Motorola) - //$image_type_to_mime_type[9] = 'image/jpc'; // JPC - //$image_type_to_mime_type[10] = 'image/jp2'; // JPC - //$image_type_to_mime_type[11] = 'image/jpx'; // JPC - //$image_type_to_mime_type[12] = 'image/jb2'; // JPC - $image_type_to_mime_type[13] = 'application/x-shockwave-flash'; // Shockwave - $image_type_to_mime_type[14] = 'image/iff'; // IFF - } - return (isset($image_type_to_mime_type[$imagetypeid]) ? $image_type_to_mime_type[$imagetypeid] : 'application/octet-stream'); - } + function image_type_to_mime_type($imagetypeid) + { + // only available in PHP v4.3.0+ + static $image_type_to_mime_type = []; + if (empty($image_type_to_mime_type)) { + $image_type_to_mime_type[1] = 'image/gif'; // GIF + $image_type_to_mime_type[2] = 'image/jpeg'; // JPEG + $image_type_to_mime_type[3] = 'image/png'; // PNG + $image_type_to_mime_type[4] = 'application/x-shockwave-flash'; // Flash + $image_type_to_mime_type[5] = 'image/psd'; // PSD + $image_type_to_mime_type[6] = 'image/bmp'; // BMP + $image_type_to_mime_type[7] = 'image/tiff'; // TIFF: little-endian (Intel) + $image_type_to_mime_type[8] = 'image/tiff'; // TIFF: big-endian (Motorola) + //$image_type_to_mime_type[9] = 'image/jpc'; // JPC + //$image_type_to_mime_type[10] = 'image/jp2'; // JPC + //$image_type_to_mime_type[11] = 'image/jpx'; // JPC + //$image_type_to_mime_type[12] = 'image/jb2'; // JPC + $image_type_to_mime_type[13] = 'application/x-shockwave-flash'; // Shockwave + $image_type_to_mime_type[14] = 'image/iff'; // IFF + } + return (isset($image_type_to_mime_type[$imagetypeid]) ? $image_type_to_mime_type[$imagetypeid] : 'application/octet-stream'); + } } if (!function_exists('utf8_decode')) { - // PHP has this function built-in if it's configured with the --with-xml option - // This version of the function is only provided in case XML isn't installed - function utf8_decode($utf8text) { - // http://www.php.net/manual/en/function.utf8-encode.php - // bytes bits representation - // 1 7 0bbbbbbb - // 2 11 110bbbbb 10bbbbbb - // 3 16 1110bbbb 10bbbbbb 10bbbbbb - // 4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb + // PHP has this function built-in if it's configured with the --with-xml option + // This version of the function is only provided in case XML isn't installed + function utf8_decode($utf8text) + { + // http://www.php.net/manual/en/function.utf8-encode.php + // bytes bits representation + // 1 7 0bbbbbbb + // 2 11 110bbbbb 10bbbbbb + // 3 16 1110bbbb 10bbbbbb 10bbbbbb + // 4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb - $utf8length = strlen($utf8text); - $decodedtext = ''; - for ($i = 0; $i < $utf8length; $i++) { - if ((ord($utf8text{$i}) & 0x80) == 0) { - $decodedtext .= $utf8text{$i}; - } elseif ((ord($utf8text{$i}) & 0xF0) == 0xF0) { - $decodedtext .= '?'; - $i += 3; - } elseif ((ord($utf8text{$i}) & 0xE0) == 0xE0) { - $decodedtext .= '?'; - $i += 2; - } elseif ((ord($utf8text{$i}) & 0xC0) == 0xC0) { - // 2 11 110bbbbb 10bbbbbb - $decodedchar = Bin2Dec(substr(Dec2Bin(ord($utf8text{$i})), 3, 5).substr(Dec2Bin(ord($utf8text{($i + 1)})), 2, 6)); - if ($decodedchar <= 255) { - $decodedtext .= chr($decodedchar); - } else { - $decodedtext .= '?'; - } - $i += 1; - } - } - return $decodedtext; - } + $utf8length = strlen($utf8text); + $decodedtext = ''; + for ($i = 0; $i < $utf8length; $i++) { + if ((ord($utf8text{$i}) & 0x80) == 0) { + $decodedtext .= $utf8text{$i}; + } elseif ((ord($utf8text{$i}) & 0xF0) == 0xF0) { + $decodedtext .= '?'; + $i += 3; + } elseif ((ord($utf8text{$i}) & 0xE0) == 0xE0) { + $decodedtext .= '?'; + $i += 2; + } elseif ((ord($utf8text{$i}) & 0xC0) == 0xC0) { + // 2 11 110bbbbb 10bbbbbb + $decodedchar = Bin2Dec(substr(Dec2Bin(ord($utf8text{$i})), 3, 5).substr(Dec2Bin(ord($utf8text{($i + 1)})), 2, 6)); + if ($decodedchar <= 255) { + $decodedtext .= chr($decodedchar); + } else { + $decodedtext .= '?'; + } + $i += 1; + } + } + return $decodedtext; + } } if (!function_exists('DateMac2Unix')) { - function DateMac2Unix($macdate) { - // Macintosh timestamp: seconds since 00:00h January 1, 1904 - // UNIX timestamp: seconds since 00:00h January 1, 1970 - return CastAsInt($macdate - 2082844800); - } + function DateMac2Unix($macdate) + { + // Macintosh timestamp: seconds since 00:00h January 1, 1904 + // UNIX timestamp: seconds since 00:00h January 1, 1970 + return CastAsInt($macdate - 2082844800); + } } if (!function_exists('FixedPoint8_8')) { - function FixedPoint8_8($rawdata) { - return BigEndian2Int(substr($rawdata, 0, 1)) + (float) (BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8)); - } + function FixedPoint8_8($rawdata) + { + return BigEndian2Int(substr($rawdata, 0, 1)) + (float) (BigEndian2Int(substr($rawdata, 1, 1)) / pow(2, 8)); + } } if (!function_exists('FixedPoint16_16')) { - function FixedPoint16_16($rawdata) { - return BigEndian2Int(substr($rawdata, 0, 2)) + (float) (BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16)); - } + function FixedPoint16_16($rawdata) + { + return BigEndian2Int(substr($rawdata, 0, 2)) + (float) (BigEndian2Int(substr($rawdata, 2, 2)) / pow(2, 16)); + } } if (!function_exists('FixedPoint2_30')) { - function FixedPoint2_30($rawdata) { - $binarystring = BigEndian2Bin($rawdata); - return Bin2Dec(substr($binarystring, 0, 2)) + (float) (Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30)); - } + function FixedPoint2_30($rawdata) + { + $binarystring = BigEndian2Bin($rawdata); + return Bin2Dec(substr($binarystring, 0, 2)) + (float) (Bin2Dec(substr($binarystring, 2, 30)) / pow(2, 30)); + } } if (!function_exists('Pascal2String')) { - function Pascal2String($pascalstring) { - // Pascal strings have 1 byte at the beginning saying how many chars are in the string - return substr($pascalstring, 1); - } + function Pascal2String($pascalstring) + { + // Pascal strings have 1 byte at the beginning saying how many chars are in the string + return substr($pascalstring, 1); + } } if (!function_exists('NoNullString')) { - function NoNullString($nullterminatedstring) { - // remove the single null terminator on null terminated strings - if (substr($nullterminatedstring, strlen($nullterminatedstring) - 1, 1) === chr(0)) { - return substr($nullterminatedstring, 0, strlen($nullterminatedstring) - 1); - } - return $nullterminatedstring; - } + function NoNullString($nullterminatedstring) + { + // remove the single null terminator on null terminated strings + if (substr($nullterminatedstring, strlen($nullterminatedstring) - 1, 1) === chr(0)) { + return substr($nullterminatedstring, 0, strlen($nullterminatedstring) - 1); + } + return $nullterminatedstring; + } } if (!function_exists('FileSizeNiceDisplay')) { - function FileSizeNiceDisplay($filesize, $precision=2) { - if ($filesize < 1000) { - $sizeunit = 'bytes'; - $precision = 0; - } else { - $filesize /= 1024; - $sizeunit = 'kB'; - } - if ($filesize >= 1000) { - $filesize /= 1024; - $sizeunit = 'MB'; - } - if ($filesize >= 1000) { - $filesize /= 1024; - $sizeunit = 'GB'; - } - return number_format($filesize, $precision).' '.$sizeunit; - } + function FileSizeNiceDisplay($filesize, $precision = 2) + { + if ($filesize < 1000) { + $sizeunit = 'bytes'; + $precision = 0; + } else { + $filesize /= 1024; + $sizeunit = 'kB'; + } + if ($filesize >= 1000) { + $filesize /= 1024; + $sizeunit = 'MB'; + } + if ($filesize >= 1000) { + $filesize /= 1024; + $sizeunit = 'GB'; + } + return number_format($filesize, $precision).' '.$sizeunit; + } } if (!function_exists('DOStime2UNIXtime')) { - function DOStime2UNIXtime($DOSdate, $DOStime) { - // wFatDate - // Specifies the MS-DOS date. The date is a packed 16-bit value with the following format: - // Bits Contents - // 0-4 Day of the month (1-31) - // 5-8 Month (1 = January, 2 = February, and so on) - // 9-15 Year offset from 1980 (add 1980 to get actual year) + function DOStime2UNIXtime($DOSdate, $DOStime) + { + // wFatDate + // Specifies the MS-DOS date. The date is a packed 16-bit value with the following format: + // Bits Contents + // 0-4 Day of the month (1-31) + // 5-8 Month (1 = January, 2 = February, and so on) + // 9-15 Year offset from 1980 (add 1980 to get actual year) - $UNIXday = ($DOSdate & 0x001F); - $UNIXmonth = (($DOSdate & 0x01E0) >> 5); - $UNIXyear = (($DOSdate & 0xFE00) >> 9) + 1980; + $UNIXday = ($DOSdate & 0x001F); + $UNIXmonth = (($DOSdate & 0x01E0) >> 5); + $UNIXyear = (($DOSdate & 0xFE00) >> 9) + 1980; - // wFatTime - // Specifies the MS-DOS time. The time is a packed 16-bit value with the following format: - // Bits Contents - // 0-4 Second divided by 2 - // 5-10 Minute (0-59) - // 11-15 Hour (0-23 on a 24-hour clock) + // wFatTime + // Specifies the MS-DOS time. The time is a packed 16-bit value with the following format: + // Bits Contents + // 0-4 Second divided by 2 + // 5-10 Minute (0-59) + // 11-15 Hour (0-23 on a 24-hour clock) - $UNIXsecond = ($DOStime & 0x001F) * 2; - $UNIXminute = (($DOStime & 0x07E0) >> 5); - $UNIXhour = (($DOStime & 0xF800) >> 11); + $UNIXsecond = ($DOStime & 0x001F) * 2; + $UNIXminute = (($DOStime & 0x07E0) >> 5); + $UNIXhour = (($DOStime & 0xF800) >> 11); - return mktime($UNIXhour, $UNIXminute, $UNIXsecond, $UNIXmonth, $UNIXday, $UNIXyear); - } + return mktime($UNIXhour, $UNIXminute, $UNIXsecond, $UNIXmonth, $UNIXday, $UNIXyear); + } } if (!function_exists('CreateDeepArray')) { - function CreateDeepArray($ArrayPath, $Separator, $Value) { - // assigns $Value to a nested array path: - // $foo = CreateDeepArray('/path/to/my', '/', 'file.txt') - // is the same as: - // $foo = array('path'=>array('to'=>'array('my'=>array('file.txt')))); - // or - // $foo['path']['to']['my'] = 'file.txt'; - while ($ArrayPath{0} == $Separator) { - $ArrayPath = substr($ArrayPath, 1); - } - if (($pos = strpos($ArrayPath, $Separator)) !== false) { - $ReturnedArray[substr($ArrayPath, 0, $pos)] = CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value); - } else { - $ReturnedArray["$ArrayPath"] = $Value; - } - return $ReturnedArray; - } + function CreateDeepArray($ArrayPath, $Separator, $Value) + { + // assigns $Value to a nested array path: + // $foo = CreateDeepArray('/path/to/my', '/', 'file.txt') + // is the same as: + // $foo = array('path'=>array('to'=>'array('my'=>array('file.txt')))); + // or + // $foo['path']['to']['my'] = 'file.txt'; + while ($ArrayPath{0} == $Separator) { + $ArrayPath = substr($ArrayPath, 1); + } + if (($pos = strpos($ArrayPath, $Separator)) !== false) { + $ReturnedArray[substr($ArrayPath, 0, $pos)] = CreateDeepArray(substr($ArrayPath, $pos + 1), $Separator, $Value); + } else { + $ReturnedArray["$ArrayPath"] = $Value; + } + return $ReturnedArray; + } } if (!function_exists('md5_file')) { - // Allan Hansen - // md5_file() exists in PHP 4.2.0. - // The following works under UNIX only, but dies on windows - function md5_file($file) { - if (substr(php_uname(), 0, 7) == 'Windows') { - die('PHP 4.2.0 or newer required for md5_file()'); - } + // Allan Hansen + // md5_file() exists in PHP 4.2.0. + // The following works under UNIX only, but dies on windows + function md5_file($file) + { + if (substr(php_uname(), 0, 7) == 'Windows') { + die('PHP 4.2.0 or newer required for md5_file()'); + } - $file = str_replace('`', '\\`', $file); - if (preg_match("#^([0-9a-f]{32})[ \t\n\r]#i", `md5sum "$file"`, $r)) { - return $r[1]; - } - return false; - } + $file = str_replace('`', '\\`', $file); + if (preg_match("#^([0-9a-f]{32})[ \t\n\r]#i", `md5sum "$file"`, $r)) { + return $r[1]; + } + return false; + } } if (!function_exists('md5_data')) { - // Allan Hansen - // md5_data() - returns md5sum for a file from startuing position to absolute end position + // Allan Hansen + // md5_data() - returns md5sum for a file from startuing position to absolute end position - function md5_data($file, $offset, $end, $invertsign=false) { - // first try and create a temporary file in the same directory as the file being scanned - if (($dataMD5filename = tempnam(dirname($file), preg_replace('#[^[:alnum:]]#i', '', basename($file)))) === false) { - // if that fails, create a temporary file in the system temp directory - if (($dataMD5filename = tempnam('/tmp', 'getID3')) === false) { - // if that fails, create a temporary file in the current directory - if (($dataMD5filename = tempnam('.', preg_replace('#[^[:alnum:]]#i', '', basename($file)))) === false) { - // can't find anywhere to create a temp file, just die - return false; - } - } - } - $md5 = false; - set_time_limit(max(filesize($file) / 1000000, 30)); + function md5_data($file, $offset, $end, $invertsign = false) + { + // first try and create a temporary file in the same directory as the file being scanned + if (($dataMD5filename = tempnam(dirname($file), preg_replace('#[^[:alnum:]]#i', '', basename($file)))) === false) { + // if that fails, create a temporary file in the system temp directory + if (($dataMD5filename = tempnam('/tmp', 'getID3')) === false) { + // if that fails, create a temporary file in the current directory + if (($dataMD5filename = tempnam('.', preg_replace('#[^[:alnum:]]#i', '', basename($file)))) === false) { + // can't find anywhere to create a temp file, just die + return false; + } + } + } + $md5 = false; + set_time_limit(max(filesize($file) / 1000000, 30)); - // copy parts of file - ob_start(); - if ($fp = fopen($file, 'rb')) { - ob_end_clean(); + // copy parts of file + ob_start(); + if ($fp = fopen($file, 'rb')) { + ob_end_clean(); - ob_start(); - if ($MD5fp = fopen($dataMD5filename, 'wb')) { + ob_start(); + if ($MD5fp = fopen($dataMD5filename, 'wb')) { + ob_end_clean(); + if ($invertsign) { + // Load conversion lookup strings for 8-bit unsigned->signed conversion below + $from = ''; + $to = ''; + for ($i = 0; $i < 128; $i++) { + $from .= chr($i); + $to .= chr($i + 128); + } + for ($i = 128; $i < 256; $i++) { + $from .= chr($i); + $to .= chr($i - 128); + } + } - ob_end_clean(); - if ($invertsign) { - // Load conversion lookup strings for 8-bit unsigned->signed conversion below - $from = ''; - $to = ''; - for ($i = 0; $i < 128; $i++) { - $from .= chr($i); - $to .= chr($i + 128); - } - for ($i = 128; $i < 256; $i++) { - $from .= chr($i); - $to .= chr($i - 128); - } - } + fseek($fp, $offset, SEEK_SET); + $byteslefttowrite = $end - $offset; + while (($byteslefttowrite > 0) && ($buffer = fread($fp, 32768))) { + if ($invertsign) { + // Possibly FLAC-specific (?) + // FLAC calculates the MD5sum of the source data of 8-bit files + // not on the actual byte values in the source file, but of those + // values converted from unsigned to signed, or more specifcally, + // with the MSB inverted. ex: 01 -> 81; F5 -> 75; etc - fseek($fp, $offset, SEEK_SET); - $byteslefttowrite = $end - $offset; - while (($byteslefttowrite > 0) && ($buffer = fread($fp, 32768))) { - if ($invertsign) { - // Possibly FLAC-specific (?) - // FLAC calculates the MD5sum of the source data of 8-bit files - // not on the actual byte values in the source file, but of those - // values converted from unsigned to signed, or more specifcally, - // with the MSB inverted. ex: 01 -> 81; F5 -> 75; etc + // Therefore, 8-bit WAV data has to be converted before getting the + // md5_data value so as to match the FLAC value - // Therefore, 8-bit WAV data has to be converted before getting the - // md5_data value so as to match the FLAC value - - // Flip the MSB for each byte in the buffer before copying - $buffer = strtr($buffer, $from, $to); - } - $byteswritten = fwrite($MD5fp, $buffer, $byteslefttowrite); - $byteslefttowrite -= $byteswritten; - } - fclose($MD5fp); - $md5 = md5_file($dataMD5filename); - - } else { - $errormessage = ob_get_contents(); - ob_end_clean(); - } - fclose($fp); - - } else { - $errormessage = ob_get_contents(); - ob_end_clean(); - } - unlink($dataMD5filename); - return $md5; - } + // Flip the MSB for each byte in the buffer before copying + $buffer = strtr($buffer, $from, $to); + } + $byteswritten = fwrite($MD5fp, $buffer, $byteslefttowrite); + $byteslefttowrite -= $byteswritten; + } + fclose($MD5fp); + $md5 = md5_file($dataMD5filename); + } else { + $errormessage = ob_get_contents(); + ob_end_clean(); + } + fclose($fp); + } else { + $errormessage = ob_get_contents(); + ob_end_clean(); + } + unlink($dataMD5filename); + return $md5; + } } if (!function_exists('TwosCompliment2Decimal')) { - function TwosCompliment2Decimal($BinaryValue) { - // http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html - // First check if the number is negative or positive by looking at the sign bit. - // If it is positive, simply convert it to decimal. - // If it is negative, make it positive by inverting the bits and adding one. - // Then, convert the result to decimal. - // The negative of this number is the value of the original binary. + function TwosCompliment2Decimal($BinaryValue) + { + // http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html + // First check if the number is negative or positive by looking at the sign bit. + // If it is positive, simply convert it to decimal. + // If it is negative, make it positive by inverting the bits and adding one. + // Then, convert the result to decimal. + // The negative of this number is the value of the original binary. - if ($BinaryValue & 0x80) { - - // negative number - return (0 - ((~$BinaryValue & 0xFF) + 1)); - - } else { - - // positive number - return $BinaryValue; - - } - - } + if ($BinaryValue & 0x80) { + // negative number + return (0 - ((~$BinaryValue & 0xFF) + 1)); + } else { + // positive number + return $BinaryValue; + } + } } if (!function_exists('LastArrayElement')) { - function LastArrayElement($MyArray) { - if (!is_array($MyArray)) { - return false; - } - if (empty($MyArray)) { - return null; - } - foreach ($MyArray as $key => $value) { - } - return $value; - } + function LastArrayElement($MyArray) + { + if (!is_array($MyArray)) { + return false; + } + if (empty($MyArray)) { + return null; + } + foreach ($MyArray as $key => $value) { + } + return $value; + } } if (!function_exists('safe_inc')) { - function safe_inc(&$variable, $increment=1) { - if (isset($variable)) { - $variable += $increment; - } else { - $variable = $increment; - } - return true; - } + function safe_inc(&$variable, $increment = 1) + { + if (isset($variable)) { + $variable += $increment; + } else { + $variable = $increment; + } + return true; + } } if (!function_exists('CalculateCompressionRatioVideo')) { - function CalculateCompressionRatioVideo(&$ThisFileInfo) { - if (empty($ThisFileInfo['video'])) { - return false; - } - if (empty($ThisFileInfo['video']['resolution_x']) || empty($ThisFileInfo['video']['resolution_y'])) { - return false; - } - if (empty($ThisFileInfo['video']['bits_per_sample'])) { - return false; - } + function CalculateCompressionRatioVideo(&$ThisFileInfo) + { + if (empty($ThisFileInfo['video'])) { + return false; + } + if (empty($ThisFileInfo['video']['resolution_x']) || empty($ThisFileInfo['video']['resolution_y'])) { + return false; + } + if (empty($ThisFileInfo['video']['bits_per_sample'])) { + return false; + } - switch ($ThisFileInfo['video']['dataformat']) { - case 'bmp': - case 'gif': - case 'jpeg': - case 'jpg': - case 'png': - case 'tiff': - $FrameRate = 1; - $PlaytimeSeconds = 1; - $BitrateCompressed = $ThisFileInfo['filesize'] * 8; - break; + switch ($ThisFileInfo['video']['dataformat']) { + case 'bmp': + case 'gif': + case 'jpeg': + case 'jpg': + case 'png': + case 'tiff': + $FrameRate = 1; + $PlaytimeSeconds = 1; + $BitrateCompressed = $ThisFileInfo['filesize'] * 8; + break; - default: - if (!empty($ThisFileInfo['video']['frame_rate'])) { - $FrameRate = $ThisFileInfo['video']['frame_rate']; - } else { - return false; - } - if (!empty($ThisFileInfo['playtime_seconds'])) { - $PlaytimeSeconds = $ThisFileInfo['playtime_seconds']; - } else { - return false; - } - if (!empty($ThisFileInfo['video']['bitrate'])) { - $BitrateCompressed = $ThisFileInfo['video']['bitrate']; - } else { - return false; - } - break; - } - $BitrateUncompressed = $ThisFileInfo['video']['resolution_x'] * $ThisFileInfo['video']['resolution_y'] * $ThisFileInfo['video']['bits_per_sample'] * $FrameRate; + default: + if (!empty($ThisFileInfo['video']['frame_rate'])) { + $FrameRate = $ThisFileInfo['video']['frame_rate']; + } else { + return false; + } + if (!empty($ThisFileInfo['playtime_seconds'])) { + $PlaytimeSeconds = $ThisFileInfo['playtime_seconds']; + } else { + return false; + } + if (!empty($ThisFileInfo['video']['bitrate'])) { + $BitrateCompressed = $ThisFileInfo['video']['bitrate']; + } else { + return false; + } + break; + } + $BitrateUncompressed = $ThisFileInfo['video']['resolution_x'] * $ThisFileInfo['video']['resolution_y'] * $ThisFileInfo['video']['bits_per_sample'] * $FrameRate; - $ThisFileInfo['video']['compression_ratio'] = $BitrateCompressed / $BitrateUncompressed; - return true; - } + $ThisFileInfo['video']['compression_ratio'] = $BitrateCompressed / $BitrateUncompressed; + return true; + } } if (!function_exists('CalculateCompressionRatioAudio')) { - function CalculateCompressionRatioAudio(&$ThisFileInfo) { - if (empty($ThisFileInfo['audio']['bitrate']) || empty($ThisFileInfo['audio']['channels']) || empty($ThisFileInfo['audio']['sample_rate']) || empty($ThisFileInfo['audio']['bits_per_sample'])) { - return false; - } - $ThisFileInfo['audio']['compression_ratio'] = $ThisFileInfo['audio']['bitrate'] / ($ThisFileInfo['audio']['channels'] * $ThisFileInfo['audio']['sample_rate'] * $ThisFileInfo['audio']['bits_per_sample']); - return true; - } + function CalculateCompressionRatioAudio(&$ThisFileInfo) + { + if (empty($ThisFileInfo['audio']['bitrate']) || empty($ThisFileInfo['audio']['channels']) || empty($ThisFileInfo['audio']['sample_rate']) || empty($ThisFileInfo['audio']['bits_per_sample'])) { + return false; + } + $ThisFileInfo['audio']['compression_ratio'] = $ThisFileInfo['audio']['bitrate'] / ($ThisFileInfo['audio']['channels'] * $ThisFileInfo['audio']['sample_rate'] * $ThisFileInfo['audio']['bits_per_sample']); + return true; + } } if (!function_exists('IsValidMIMEstring')) { - function IsValidMIMEstring($mimestring) { - if ((strlen($mimestring) >= 3) && (strpos($mimestring, '/') > 0) && (strpos($mimestring, '/') < (strlen($mimestring) - 1))) { - return true; - } - return false; - } + function IsValidMIMEstring($mimestring) + { + if ((strlen($mimestring) >= 3) && (strpos($mimestring, '/') > 0) && (strpos($mimestring, '/') < (strlen($mimestring) - 1))) { + return true; + } + return false; + } } if (!function_exists('IsWithinBitRange')) { - function IsWithinBitRange($number, $maxbits, $signed=false) { - if ($signed) { - if (($number > (0 - pow(2, $maxbits - 1))) && ($number <= pow(2, $maxbits - 1))) { - return true; - } - } else { - if (($number >= 0) && ($number <= pow(2, $maxbits))) { - return true; - } - } - return false; - } + function IsWithinBitRange($number, $maxbits, $signed = false) + { + if ($signed) { + if (($number > (0 - pow(2, $maxbits - 1))) && ($number <= pow(2, $maxbits - 1))) { + return true; + } + } else { + if (($number >= 0) && ($number <= pow(2, $maxbits))) { + return true; + } + } + return false; + } } if (!function_exists('safe_parse_url')) { - function safe_parse_url($url) { - ob_start(); - $parts = parse_url($url); - $errormessage = ob_get_contents(); - ob_end_clean(); - $parts['scheme'] = (isset($parts['scheme']) ? $parts['scheme'] : ''); - $parts['host'] = (isset($parts['host']) ? $parts['host'] : ''); - $parts['user'] = (isset($parts['user']) ? $parts['user'] : ''); - $parts['pass'] = (isset($parts['pass']) ? $parts['pass'] : ''); - $parts['path'] = (isset($parts['path']) ? $parts['path'] : ''); - $parts['query'] = (isset($parts['query']) ? $parts['query'] : ''); - return $parts; - } + function safe_parse_url($url) + { + ob_start(); + $parts = parse_url($url); + $errormessage = ob_get_contents(); + ob_end_clean(); + $parts['scheme'] = (isset($parts['scheme']) ? $parts['scheme'] : ''); + $parts['host'] = (isset($parts['host']) ? $parts['host'] : ''); + $parts['user'] = (isset($parts['user']) ? $parts['user'] : ''); + $parts['pass'] = (isset($parts['pass']) ? $parts['pass'] : ''); + $parts['path'] = (isset($parts['path']) ? $parts['path'] : ''); + $parts['query'] = (isset($parts['query']) ? $parts['query'] : ''); + return $parts; + } } if (!function_exists('IsValidURL')) { - function IsValidURL($url, $allowUserPass=false) { - if ($url == '') { - return false; - } - if ($allowUserPass !== true) { - if (strstr($url, '@')) { - // in the format http://user:pass@example.com or http://user@example.com - // but could easily be somebody incorrectly entering an email address in place of a URL - return false; - } - } - if ($parts = safe_parse_url($url)) { - if (($parts['scheme'] != 'http') && ($parts['scheme'] != 'https') && ($parts['scheme'] != 'ftp') && ($parts['scheme'] != 'gopher')) { - return false; - } elseif (!preg_match("#^[[:alnum:]]([-.]?[0-9a-z])*\.[a-z]{2,3}#i$", $parts['host'], $regs) && !preg_match('#^[0-9]{1,3}(\.[0-9]{1,3}){3}$#', $parts['host'])) { - return false; - } elseif (!preg_match("#^([[:alnum:]-]|[\_])*$#i", $parts['user'], $regs)) { - return false; - } elseif (!preg_match("#^([[:alnum:]-]|[\_])*$#i", $parts['pass'], $regs)) { - return false; - } elseif (!preg_match("#^[[:alnum:]/_\.@~-]*$#i", $parts['path'], $regs)) { - return false; - } elseif (!preg_match("#^[[:alnum:]?&=+:;_()%#/,\.-]*$#i", $parts['query'], $regs)) { - return false; - } else { - return true; - } - } - return false; - } + function IsValidURL($url, $allowUserPass = false) + { + if ($url == '') { + return false; + } + if ($allowUserPass !== true) { + if (strstr($url, '@')) { + // in the format http://user:pass@example.com or http://user@example.com + // but could easily be somebody incorrectly entering an email address in place of a URL + return false; + } + } + if ($parts = safe_parse_url($url)) { + if (($parts['scheme'] != 'http') && ($parts['scheme'] != 'https') && ($parts['scheme'] != 'ftp') && ($parts['scheme'] != 'gopher')) { + return false; + } elseif (!preg_match("#^[[:alnum:]]([-.]?[0-9a-z])*\.[a-z]{2,3}#i$", $parts['host'], $regs) && !preg_match('#^[0-9]{1,3}(\.[0-9]{1,3}){3}$#', $parts['host'])) { + return false; + } elseif (!preg_match("#^([[:alnum:]-]|[\_])*$#i", $parts['user'], $regs)) { + return false; + } elseif (!preg_match("#^([[:alnum:]-]|[\_])*$#i", $parts['pass'], $regs)) { + return false; + } elseif (!preg_match("#^[[:alnum:]/_\.@~-]*$#i", $parts['path'], $regs)) { + return false; + } elseif (!preg_match("#^[[:alnum:]?&=+:;_()%#/,\.-]*$#i", $parts['query'], $regs)) { + return false; + } else { + return true; + } + } + return false; + } } echo '
'; @@ -1356,31 +1412,31 @@ echo ''; -$MPEGgenerateValues = array( - 'version'=>array('1', '2', '2.5'), - 'layer'=>array('I', 'II', 'III'), - 'protection'=>array('Y', 'N'), - 'bitrate'=>array('free', '8', '16', '24', '32', '40', '48', '56', '64', '80', '96', '112', '128', '144', '160', '176', '192', '224', '256', '288', '320', '352', '384', '416', '448'), - 'frequency'=>array('8000', '11025', '12000', '16000', '22050', '24000', '32000', '44100', '48000'), - 'padding'=>array('Y', 'N'), - 'private'=>array('Y', 'N'), - 'channelmode'=>array('stereo', 'joint stereo', 'dual channel', 'mono'), - 'modeextension'=>array('none', 'IS', 'MS', 'IS+MS', '4-31', '8-31', '12-31', '16-31'), - 'copyright'=>array('Y', 'N'), - 'original'=>array('Y', 'N'), - 'emphasis'=>array('none', '50/15ms', 'CCIT J.17') - ); +$MPEGgenerateValues = [ + 'version'=>['1', '2', '2.5'], + 'layer'=>['I', 'II', 'III'], + 'protection'=>['Y', 'N'], + 'bitrate'=>['free', '8', '16', '24', '32', '40', '48', '56', '64', '80', '96', '112', '128', '144', '160', '176', '192', '224', '256', '288', '320', '352', '384', '416', '448'], + 'frequency'=>['8000', '11025', '12000', '16000', '22050', '24000', '32000', '44100', '48000'], + 'padding'=>['Y', 'N'], + 'private'=>['Y', 'N'], + 'channelmode'=>['stereo', 'joint stereo', 'dual channel', 'mono'], + 'modeextension'=>['none', 'IS', 'MS', 'IS+MS', '4-31', '8-31', '12-31', '16-31'], + 'copyright'=>['Y', 'N'], + 'original'=>['Y', 'N'], + 'emphasis'=>['none', '50/15ms', 'CCIT J.17'] + ]; foreach ($MPEGgenerateValues as $name => $dataarray) { - echo ''.$name.':'; + echo ''.$name.':'; } if (isset($_POST['bitrate'])) { - echo 'Frame Length:'.(int) MPEGaudioFrameLength($_POST['bitrate'], $_POST['version'], $_POST['layer'], (($_POST['padding'] == 'Y') ? '1' : '0'), $_POST['frequency']).''; + echo 'Frame Length:'.(int) MPEGaudioFrameLength($_POST['bitrate'], $_POST['version'], $_POST['layer'], (($_POST['padding'] == 'Y') ? '1' : '0'), $_POST['frequency']).''; } echo ''; echo '
'; @@ -1388,185 +1444,185 @@ echo '
'; if (isset($_POST['Analyze']) && $_POST['HeaderHexBytes']) { + $headerbytearray = explode(' ', $_POST['HeaderHexBytes']); + if (count($headerbytearray) != 4) { + die('Invalid byte pattern'); + } + $headerstring = ''; + foreach ($headerbytearray as $textbyte) { + $headerstring .= chr(hexdec($textbyte)); + } - $headerbytearray = explode(' ', $_POST['HeaderHexBytes']); - if (count($headerbytearray) != 4) { - die('Invalid byte pattern'); - } - $headerstring = ''; - foreach ($headerbytearray as $textbyte) { - $headerstring .= chr(hexdec($textbyte)); - } + $MP3fileInfo['error'] = ''; - $MP3fileInfo['error'] = ''; + $MPEGheaderRawArray = MPEGaudioHeaderDecode(substr($headerstring, 0, 4)); - $MPEGheaderRawArray = MPEGaudioHeaderDecode(substr($headerstring, 0, 4)); + if (MPEGaudioHeaderValid($MPEGheaderRawArray, true)) { + $MP3fileInfo['raw'] = $MPEGheaderRawArray; - if (MPEGaudioHeaderValid($MPEGheaderRawArray, true)) { + $MP3fileInfo['version'] = MPEGaudioVersionLookup($MP3fileInfo['raw']['version']); + $MP3fileInfo['layer'] = MPEGaudioLayerLookup($MP3fileInfo['raw']['layer']); + $MP3fileInfo['protection'] = MPEGaudioCRCLookup($MP3fileInfo['raw']['protection']); + $MP3fileInfo['bitrate'] = MPEGaudioBitrateLookup($MP3fileInfo['version'], $MP3fileInfo['layer'], $MP3fileInfo['raw']['bitrate']); + $MP3fileInfo['frequency'] = MPEGaudioFrequencyLookup($MP3fileInfo['version'], $MP3fileInfo['raw']['sample_rate']); + $MP3fileInfo['padding'] = (bool) $MP3fileInfo['raw']['padding']; + $MP3fileInfo['private'] = (bool) $MP3fileInfo['raw']['private']; + $MP3fileInfo['channelmode'] = MPEGaudioChannelModeLookup($MP3fileInfo['raw']['channelmode']); + $MP3fileInfo['channels'] = (($MP3fileInfo['channelmode'] == 'mono') ? 1 : 2); + $MP3fileInfo['modeextension'] = MPEGaudioModeExtensionLookup($MP3fileInfo['layer'], $MP3fileInfo['raw']['modeextension']); + $MP3fileInfo['copyright'] = (bool) $MP3fileInfo['raw']['copyright']; + $MP3fileInfo['original'] = (bool) $MP3fileInfo['raw']['original']; + $MP3fileInfo['emphasis'] = MPEGaudioEmphasisLookup($MP3fileInfo['raw']['emphasis']); - $MP3fileInfo['raw'] = $MPEGheaderRawArray; + if ($MP3fileInfo['protection']) { + $MP3fileInfo['crc'] = BigEndian2Int(substr($headerstring, 4, 2)); + } - $MP3fileInfo['version'] = MPEGaudioVersionLookup($MP3fileInfo['raw']['version']); - $MP3fileInfo['layer'] = MPEGaudioLayerLookup($MP3fileInfo['raw']['layer']); - $MP3fileInfo['protection'] = MPEGaudioCRCLookup($MP3fileInfo['raw']['protection']); - $MP3fileInfo['bitrate'] = MPEGaudioBitrateLookup($MP3fileInfo['version'], $MP3fileInfo['layer'], $MP3fileInfo['raw']['bitrate']); - $MP3fileInfo['frequency'] = MPEGaudioFrequencyLookup($MP3fileInfo['version'], $MP3fileInfo['raw']['sample_rate']); - $MP3fileInfo['padding'] = (bool) $MP3fileInfo['raw']['padding']; - $MP3fileInfo['private'] = (bool) $MP3fileInfo['raw']['private']; - $MP3fileInfo['channelmode'] = MPEGaudioChannelModeLookup($MP3fileInfo['raw']['channelmode']); - $MP3fileInfo['channels'] = (($MP3fileInfo['channelmode'] == 'mono') ? 1 : 2); - $MP3fileInfo['modeextension'] = MPEGaudioModeExtensionLookup($MP3fileInfo['layer'], $MP3fileInfo['raw']['modeextension']); - $MP3fileInfo['copyright'] = (bool) $MP3fileInfo['raw']['copyright']; - $MP3fileInfo['original'] = (bool) $MP3fileInfo['raw']['original']; - $MP3fileInfo['emphasis'] = MPEGaudioEmphasisLookup($MP3fileInfo['raw']['emphasis']); + if ($MP3fileInfo['frequency'] > 0) { + $MP3fileInfo['framelength'] = MPEGaudioFrameLength($MP3fileInfo['bitrate'], $MP3fileInfo['version'], $MP3fileInfo['layer'], (int) $MP3fileInfo['padding'], $MP3fileInfo['frequency']); + } + if ($MP3fileInfo['bitrate'] != 'free') { + $MP3fileInfo['bitrate'] *= 1000; + } + } else { + $MP3fileInfo['error'] .= "\n".'Invalid MPEG audio header'; + } - if ($MP3fileInfo['protection']) { - $MP3fileInfo['crc'] = BigEndian2Int(substr($headerstring, 4, 2)); - } - - if ($MP3fileInfo['frequency'] > 0) { - $MP3fileInfo['framelength'] = MPEGaudioFrameLength($MP3fileInfo['bitrate'], $MP3fileInfo['version'], $MP3fileInfo['layer'], (int) $MP3fileInfo['padding'], $MP3fileInfo['frequency']); - } - if ($MP3fileInfo['bitrate'] != 'free') { - $MP3fileInfo['bitrate'] *= 1000; - } - - } else { - - $MP3fileInfo['error'] .= "\n".'Invalid MPEG audio header'; - - } - - if (!$MP3fileInfo['error']) { - unset($MP3fileInfo['error']); - } - - echo table_var_dump($MP3fileInfo); + if (!$MP3fileInfo['error']) { + unset($MP3fileInfo['error']); + } + echo table_var_dump($MP3fileInfo); } elseif (isset($_POST['Generate'])) { + // AAAA AAAA AAAB BCCD EEEE FFGH IIJJ KLMM - // AAAA AAAA AAAB BCCD EEEE FFGH IIJJ KLMM + $headerbitstream = '11111111111'; // A - Frame sync (all bits set) - $headerbitstream = '11111111111'; // A - Frame sync (all bits set) + $MPEGversionLookup = ['2.5'=>'00', '2'=>'10', '1'=>'11']; + $headerbitstream .= $MPEGversionLookup[$_POST['version']]; // B - MPEG Audio version ID - $MPEGversionLookup = array('2.5'=>'00', '2'=>'10', '1'=>'11'); - $headerbitstream .= $MPEGversionLookup[$_POST['version']]; // B - MPEG Audio version ID + $MPEGlayerLookup = ['III'=>'01', 'II'=>'10', 'I'=>'11']; + $headerbitstream .= $MPEGlayerLookup[$_POST['layer']]; // C - Layer description - $MPEGlayerLookup = array('III'=>'01', 'II'=>'10', 'I'=>'11'); - $headerbitstream .= $MPEGlayerLookup[$_POST['layer']]; // C - Layer description + $headerbitstream .= (($_POST['protection'] == 'Y') ? '0' : '1'); // D - Protection bit - $headerbitstream .= (($_POST['protection'] == 'Y') ? '0' : '1'); // D - Protection bit + $MPEGaudioBitrateLookup['1']['I'] = ['free'=>'0000', '32'=>'0001', '64'=>'0010', '96'=>'0011', '128'=>'0100', '160'=>'0101', '192'=>'0110', '224'=>'0111', '256'=>'1000', '288'=>'1001', '320'=>'1010', '352'=>'1011', '384'=>'1100', '416'=>'1101', '448'=>'1110']; + $MPEGaudioBitrateLookup['1']['II'] = ['free'=>'0000', '32'=>'0001', '48'=>'0010', '56'=>'0011', '64'=>'0100', '80'=>'0101', '96'=>'0110', '112'=>'0111', '128'=>'1000', '160'=>'1001', '192'=>'1010', '224'=>'1011', '256'=>'1100', '320'=>'1101', '384'=>'1110']; + $MPEGaudioBitrateLookup['1']['III'] = ['free'=>'0000', '32'=>'0001', '40'=>'0010', '48'=>'0011', '56'=>'0100', '64'=>'0101', '80'=>'0110', '96'=>'0111', '112'=>'1000', '128'=>'1001', '160'=>'1010', '192'=>'1011', '224'=>'1100', '256'=>'1101', '320'=>'1110']; + $MPEGaudioBitrateLookup['2']['I'] = ['free'=>'0000', '32'=>'0001', '48'=>'0010', '56'=>'0011', '64'=>'0100', '80'=>'0101', '96'=>'0110', '112'=>'0111', '128'=>'1000', '144'=>'1001', '160'=>'1010', '176'=>'1011', '192'=>'1100', '224'=>'1101', '256'=>'1110']; + $MPEGaudioBitrateLookup['2']['II'] = ['free'=>'0000', '8'=>'0001', '16'=>'0010', '24'=>'0011', '32'=>'0100', '40'=>'0101', '48'=>'0110', '56'=>'0111', '64'=>'1000', '80'=>'1001', '96'=>'1010', '112'=>'1011', '128'=>'1100', '144'=>'1101', '160'=>'1110']; + $MPEGaudioBitrateLookup['2']['III'] = $MPEGaudioBitrateLookup['2']['II']; + $MPEGaudioBitrateLookup['2.5']['I'] = $MPEGaudioBitrateLookup['2']['I']; + $MPEGaudioBitrateLookup['2.5']['II'] = $MPEGaudioBitrateLookup['2']['II']; + $MPEGaudioBitrateLookup['2.5']['III'] = $MPEGaudioBitrateLookup['2']['II']; + if (isset($MPEGaudioBitrateLookup[$_POST['version']][$_POST['layer']][$_POST['bitrate']])) { + $headerbitstream .= $MPEGaudioBitrateLookup[$_POST['version']][$_POST['layer']][$_POST['bitrate']]; // E - Bitrate index + } else { + die('Invalid Bitrate'); + } - $MPEGaudioBitrateLookup['1']['I'] = array('free'=>'0000', '32'=>'0001', '64'=>'0010', '96'=>'0011', '128'=>'0100', '160'=>'0101', '192'=>'0110', '224'=>'0111', '256'=>'1000', '288'=>'1001', '320'=>'1010', '352'=>'1011', '384'=>'1100', '416'=>'1101', '448'=>'1110'); - $MPEGaudioBitrateLookup['1']['II'] = array('free'=>'0000', '32'=>'0001', '48'=>'0010', '56'=>'0011', '64'=>'0100', '80'=>'0101', '96'=>'0110', '112'=>'0111', '128'=>'1000', '160'=>'1001', '192'=>'1010', '224'=>'1011', '256'=>'1100', '320'=>'1101', '384'=>'1110'); - $MPEGaudioBitrateLookup['1']['III'] = array('free'=>'0000', '32'=>'0001', '40'=>'0010', '48'=>'0011', '56'=>'0100', '64'=>'0101', '80'=>'0110', '96'=>'0111', '112'=>'1000', '128'=>'1001', '160'=>'1010', '192'=>'1011', '224'=>'1100', '256'=>'1101', '320'=>'1110'); - $MPEGaudioBitrateLookup['2']['I'] = array('free'=>'0000', '32'=>'0001', '48'=>'0010', '56'=>'0011', '64'=>'0100', '80'=>'0101', '96'=>'0110', '112'=>'0111', '128'=>'1000', '144'=>'1001', '160'=>'1010', '176'=>'1011', '192'=>'1100', '224'=>'1101', '256'=>'1110'); - $MPEGaudioBitrateLookup['2']['II'] = array('free'=>'0000', '8'=>'0001', '16'=>'0010', '24'=>'0011', '32'=>'0100', '40'=>'0101', '48'=>'0110', '56'=>'0111', '64'=>'1000', '80'=>'1001', '96'=>'1010', '112'=>'1011', '128'=>'1100', '144'=>'1101', '160'=>'1110'); - $MPEGaudioBitrateLookup['2']['III'] = $MPEGaudioBitrateLookup['2']['II']; - $MPEGaudioBitrateLookup['2.5']['I'] = $MPEGaudioBitrateLookup['2']['I']; - $MPEGaudioBitrateLookup['2.5']['II'] = $MPEGaudioBitrateLookup['2']['II']; - $MPEGaudioBitrateLookup['2.5']['III'] = $MPEGaudioBitrateLookup['2']['II']; - if (isset($MPEGaudioBitrateLookup[$_POST['version']][$_POST['layer']][$_POST['bitrate']])) { - $headerbitstream .= $MPEGaudioBitrateLookup[$_POST['version']][$_POST['layer']][$_POST['bitrate']]; // E - Bitrate index - } else { - die('Invalid Bitrate'); - } + $MPEGaudioFrequencyLookup['1'] = ['44100'=>'00', '48000'=>'01', '32000'=>'10']; + $MPEGaudioFrequencyLookup['2'] = ['22050'=>'00', '24000'=>'01', '16000'=>'10']; + $MPEGaudioFrequencyLookup['2.5'] = ['11025'=>'00', '12000'=>'01', '8000'=>'10']; + if (isset($MPEGaudioFrequencyLookup[$_POST['version']][$_POST['frequency']])) { + $headerbitstream .= $MPEGaudioFrequencyLookup[$_POST['version']][$_POST['frequency']]; // F - Sampling rate frequency index + } else { + die('Invalid Frequency'); + } - $MPEGaudioFrequencyLookup['1'] = array('44100'=>'00', '48000'=>'01', '32000'=>'10'); - $MPEGaudioFrequencyLookup['2'] = array('22050'=>'00', '24000'=>'01', '16000'=>'10'); - $MPEGaudioFrequencyLookup['2.5'] = array('11025'=>'00', '12000'=>'01', '8000'=>'10'); - if (isset($MPEGaudioFrequencyLookup[$_POST['version']][$_POST['frequency']])) { - $headerbitstream .= $MPEGaudioFrequencyLookup[$_POST['version']][$_POST['frequency']]; // F - Sampling rate frequency index - } else { - die('Invalid Frequency'); - } + $headerbitstream .= (($_POST['padding'] == 'Y') ? '1' : '0'); // G - Padding bit - $headerbitstream .= (($_POST['padding'] == 'Y') ? '1' : '0'); // G - Padding bit + $headerbitstream .= (($_POST['private'] == 'Y') ? '1' : '0'); // H - Private bit - $headerbitstream .= (($_POST['private'] == 'Y') ? '1' : '0'); // H - Private bit + $MPEGaudioChannelModeLookup = ['stereo'=>'00', 'joint stereo'=>'01', 'dual channel'=>'10', 'mono'=>'11']; + $headerbitstream .= $MPEGaudioChannelModeLookup[$_POST['channelmode']]; // I - Channel Mode - $MPEGaudioChannelModeLookup = array('stereo'=>'00', 'joint stereo'=>'01', 'dual channel'=>'10', 'mono'=>'11'); - $headerbitstream .= $MPEGaudioChannelModeLookup[$_POST['channelmode']]; // I - Channel Mode + $MPEGaudioModeExtensionLookup['I'] = ['4-31'=>'00', '8-31'=>'01', '12-31'=>'10', '16-31'=>'11']; + $MPEGaudioModeExtensionLookup['II'] = $MPEGaudioModeExtensionLookup['I']; + $MPEGaudioModeExtensionLookup['III'] = ['none'=>'00', 'IS'=>'01', 'MS'=>'10', 'IS+MS'=>'11']; + if ($_POST['channelmode'] != 'joint stereo') { + $headerbitstream .= '00'; + } elseif (isset($MPEGaudioModeExtensionLookup[$_POST['layer']][$_POST['modeextension']])) { + $headerbitstream .= $MPEGaudioModeExtensionLookup[$_POST['layer']][$_POST['modeextension']]; // J - Mode extension (Only if Joint stereo) + } else { + die('Invalid Mode Extension'); + } - $MPEGaudioModeExtensionLookup['I'] = array('4-31'=>'00', '8-31'=>'01', '12-31'=>'10', '16-31'=>'11'); - $MPEGaudioModeExtensionLookup['II'] = $MPEGaudioModeExtensionLookup['I']; - $MPEGaudioModeExtensionLookup['III'] = array('none'=>'00', 'IS'=>'01', 'MS'=>'10', 'IS+MS'=>'11'); - if ($_POST['channelmode'] != 'joint stereo') { - $headerbitstream .= '00'; - } elseif (isset($MPEGaudioModeExtensionLookup[$_POST['layer']][$_POST['modeextension']])) { - $headerbitstream .= $MPEGaudioModeExtensionLookup[$_POST['layer']][$_POST['modeextension']]; // J - Mode extension (Only if Joint stereo) - } else { - die('Invalid Mode Extension'); - } + $headerbitstream .= (($_POST['copyright'] == 'Y') ? '1' : '0'); // K - Copyright - $headerbitstream .= (($_POST['copyright'] == 'Y') ? '1' : '0'); // K - Copyright + $headerbitstream .= (($_POST['original'] == 'Y') ? '1' : '0'); // L - Original - $headerbitstream .= (($_POST['original'] == 'Y') ? '1' : '0'); // L - Original - - $MPEGaudioEmphasisLookup = array('none'=>'00', '50/15ms'=>'01', 'CCIT J.17'=>'11'); - if (isset($MPEGaudioEmphasisLookup[$_POST['emphasis']])) { - $headerbitstream .= $MPEGaudioEmphasisLookup[$_POST['emphasis']]; // M - Emphasis - } else { - die('Invalid Emphasis'); - } - - echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 0, 8))), 2, '0', STR_PAD_LEFT)).' '; - echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 8, 8))), 2, '0', STR_PAD_LEFT)).' '; - echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 16, 8))), 2, '0', STR_PAD_LEFT)).' '; - echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 24, 8))), 2, '0', STR_PAD_LEFT)).'
'; + $MPEGaudioEmphasisLookup = ['none'=>'00', '50/15ms'=>'01', 'CCIT J.17'=>'11']; + if (isset($MPEGaudioEmphasisLookup[$_POST['emphasis']])) { + $headerbitstream .= $MPEGaudioEmphasisLookup[$_POST['emphasis']]; // M - Emphasis + } else { + die('Invalid Emphasis'); + } + echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 0, 8))), 2, '0', STR_PAD_LEFT)).' '; + echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 8, 8))), 2, '0', STR_PAD_LEFT)).' '; + echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 16, 8))), 2, '0', STR_PAD_LEFT)).' '; + echo strtoupper(str_pad(dechex(bindec(substr($headerbitstream, 24, 8))), 2, '0', STR_PAD_LEFT)).'
'; } -function MPEGaudioVersionLookup($rawversion) { - $MPEGaudioVersionLookup = array('2.5', FALSE, '2', '1'); - return (isset($MPEGaudioVersionLookup["$rawversion"]) ? $MPEGaudioVersionLookup["$rawversion"] : FALSE); +function MPEGaudioVersionLookup($rawversion) +{ + $MPEGaudioVersionLookup = ['2.5', false, '2', '1']; + return (isset($MPEGaudioVersionLookup["$rawversion"]) ? $MPEGaudioVersionLookup["$rawversion"] : false); } -function MPEGaudioLayerLookup($rawlayer) { - $MPEGaudioLayerLookup = array(FALSE, 'III', 'II', 'I'); - return (isset($MPEGaudioLayerLookup["$rawlayer"]) ? $MPEGaudioLayerLookup["$rawlayer"] : FALSE); +function MPEGaudioLayerLookup($rawlayer) +{ + $MPEGaudioLayerLookup = [false, 'III', 'II', 'I']; + return (isset($MPEGaudioLayerLookup["$rawlayer"]) ? $MPEGaudioLayerLookup["$rawlayer"] : false); } -function MPEGaudioBitrateLookup($version, $layer, $rawbitrate) { - static $MPEGaudioBitrateLookup; - if (empty($MPEGaudioBitrateLookup)) { - $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); - } - return (isset($MPEGaudioBitrateLookup["$version"]["$layer"]["$rawbitrate"]) ? $MPEGaudioBitrateLookup["$version"]["$layer"]["$rawbitrate"] : FALSE); +function MPEGaudioBitrateLookup($version, $layer, $rawbitrate) +{ + static $MPEGaudioBitrateLookup; + if (empty($MPEGaudioBitrateLookup)) { + $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); + } + return (isset($MPEGaudioBitrateLookup["$version"]["$layer"]["$rawbitrate"]) ? $MPEGaudioBitrateLookup["$version"]["$layer"]["$rawbitrate"] : false); } -function MPEGaudioFrequencyLookup($version, $rawfrequency) { - static $MPEGaudioFrequencyLookup; - if (empty($MPEGaudioFrequencyLookup)) { - $MPEGaudioFrequencyLookup = MPEGaudioFrequencyArray(); - } - return (isset($MPEGaudioFrequencyLookup["$version"]["$rawfrequency"]) ? $MPEGaudioFrequencyLookup["$version"]["$rawfrequency"] : FALSE); +function MPEGaudioFrequencyLookup($version, $rawfrequency) +{ + static $MPEGaudioFrequencyLookup; + if (empty($MPEGaudioFrequencyLookup)) { + $MPEGaudioFrequencyLookup = MPEGaudioFrequencyArray(); + } + return (isset($MPEGaudioFrequencyLookup["$version"]["$rawfrequency"]) ? $MPEGaudioFrequencyLookup["$version"]["$rawfrequency"] : false); } -function MPEGaudioChannelModeLookup($rawchannelmode) { - $MPEGaudioChannelModeLookup = array('stereo', 'joint stereo', 'dual channel', 'mono'); - return (isset($MPEGaudioChannelModeLookup["$rawchannelmode"]) ? $MPEGaudioChannelModeLookup["$rawchannelmode"] : FALSE); +function MPEGaudioChannelModeLookup($rawchannelmode) +{ + $MPEGaudioChannelModeLookup = ['stereo', 'joint stereo', 'dual channel', 'mono']; + return (isset($MPEGaudioChannelModeLookup["$rawchannelmode"]) ? $MPEGaudioChannelModeLookup["$rawchannelmode"] : false); } -function MPEGaudioModeExtensionLookup($layer, $rawmodeextension) { - $MPEGaudioModeExtensionLookup['I'] = array('4-31', '8-31', '12-31', '16-31'); - $MPEGaudioModeExtensionLookup['II'] = array('4-31', '8-31', '12-31', '16-31'); - $MPEGaudioModeExtensionLookup['III'] = array('', 'IS', 'MS', 'IS+MS'); - return (isset($MPEGaudioModeExtensionLookup["$layer"]["$rawmodeextension"]) ? $MPEGaudioModeExtensionLookup["$layer"]["$rawmodeextension"] : FALSE); +function MPEGaudioModeExtensionLookup($layer, $rawmodeextension) +{ + $MPEGaudioModeExtensionLookup['I'] = ['4-31', '8-31', '12-31', '16-31']; + $MPEGaudioModeExtensionLookup['II'] = ['4-31', '8-31', '12-31', '16-31']; + $MPEGaudioModeExtensionLookup['III'] = ['', 'IS', 'MS', 'IS+MS']; + return (isset($MPEGaudioModeExtensionLookup["$layer"]["$rawmodeextension"]) ? $MPEGaudioModeExtensionLookup["$layer"]["$rawmodeextension"] : false); } -function MPEGaudioEmphasisLookup($rawemphasis) { - $MPEGaudioEmphasisLookup = array('none', '50/15ms', FALSE, 'CCIT J.17'); - return (isset($MPEGaudioEmphasisLookup["$rawemphasis"]) ? $MPEGaudioEmphasisLookup["$rawemphasis"] : FALSE); +function MPEGaudioEmphasisLookup($rawemphasis) +{ + $MPEGaudioEmphasisLookup = ['none', '50/15ms', false, 'CCIT J.17']; + return (isset($MPEGaudioEmphasisLookup["$rawemphasis"]) ? $MPEGaudioEmphasisLookup["$rawemphasis"] : false); } -function MPEGaudioCRCLookup($CRCbit) { - // inverse boolean cast :) - if ($CRCbit == '0') { - return TRUE; - } else { - return FALSE; - } +function MPEGaudioCRCLookup($CRCbit) +{ + // inverse boolean cast :) + if ($CRCbit == '0') { + return true; + } else { + return false; + } } ///////////////////////////////////////////////////////////////// @@ -1586,1304 +1642,1267 @@ function MPEGaudioCRCLookup($CRCbit) { // mpeg-audio streams define('MPEG_VALID_CHECK_FRAMES', 35); -function getMP3headerFilepointer(&$fd, &$ThisFileInfo) { +function getMP3headerFilepointer(&$fd, &$ThisFileInfo) +{ - getOnlyMPEGaudioInfo($fd, $ThisFileInfo, $ThisFileInfo['avdataoffset']); + getOnlyMPEGaudioInfo($fd, $ThisFileInfo, $ThisFileInfo['avdataoffset']); - if (isset($ThisFileInfo['mpeg']['audio']['bitrate_mode'])) { - $ThisFileInfo['audio']['bitrate_mode'] = strtolower($ThisFileInfo['mpeg']['audio']['bitrate_mode']); - } + if (isset($ThisFileInfo['mpeg']['audio']['bitrate_mode'])) { + $ThisFileInfo['audio']['bitrate_mode'] = strtolower($ThisFileInfo['mpeg']['audio']['bitrate_mode']); + } - if (((isset($ThisFileInfo['id3v2']) && ($ThisFileInfo['avdataoffset'] > $ThisFileInfo['id3v2']['headerlength'])) || (!isset($ThisFileInfo['id3v2']) && ($ThisFileInfo['avdataoffset'] > 0)))) { + if (((isset($ThisFileInfo['id3v2']) && ($ThisFileInfo['avdataoffset'] > $ThisFileInfo['id3v2']['headerlength'])) || (!isset($ThisFileInfo['id3v2']) && ($ThisFileInfo['avdataoffset'] > 0)))) { + $ThisFileInfo['warning'] .= "\n".'Unknown data before synch '; + if (isset($ThisFileInfo['id3v2']['headerlength'])) { + $ThisFileInfo['warning'] .= '(ID3v2 header ends at '.$ThisFileInfo['id3v2']['headerlength'].', then '.($ThisFileInfo['avdataoffset'] - $ThisFileInfo['id3v2']['headerlength']).' bytes garbage, '; + } else { + $ThisFileInfo['warning'] .= '(should be at beginning of file, '; + } + $ThisFileInfo['warning'] .= 'synch detected at '.$ThisFileInfo['avdataoffset'].')'; + if ($ThisFileInfo['audio']['bitrate_mode'] == 'cbr') { + if (!empty($ThisFileInfo['id3v2']['headerlength']) && (($ThisFileInfo['avdataoffset'] - $ThisFileInfo['id3v2']['headerlength']) == $ThisFileInfo['mpeg']['audio']['framelength'])) { + $ThisFileInfo['warning'] .= '. This is a known problem with some versions of LAME (3.91, 3.92) DLL in CBR mode.'; + $ThisFileInfo['audio']['codec'] = 'LAME'; + } elseif (empty($ThisFileInfo['id3v2']['headerlength']) && ($ThisFileInfo['avdataoffset'] == $ThisFileInfo['mpeg']['audio']['framelength'])) { + $ThisFileInfo['warning'] .= '. This is a known problem with some versions of LAME (3.91, 3.92) DLL in CBR mode.'; + $ThisFileInfo['audio']['codec'] = 'LAME'; + } + } + } - $ThisFileInfo['warning'] .= "\n".'Unknown data before synch '; - if (isset($ThisFileInfo['id3v2']['headerlength'])) { - $ThisFileInfo['warning'] .= '(ID3v2 header ends at '.$ThisFileInfo['id3v2']['headerlength'].', then '.($ThisFileInfo['avdataoffset'] - $ThisFileInfo['id3v2']['headerlength']).' bytes garbage, '; - } else { - $ThisFileInfo['warning'] .= '(should be at beginning of file, '; - } - $ThisFileInfo['warning'] .= 'synch detected at '.$ThisFileInfo['avdataoffset'].')'; - if ($ThisFileInfo['audio']['bitrate_mode'] == 'cbr') { - if (!empty($ThisFileInfo['id3v2']['headerlength']) && (($ThisFileInfo['avdataoffset'] - $ThisFileInfo['id3v2']['headerlength']) == $ThisFileInfo['mpeg']['audio']['framelength'])) { - $ThisFileInfo['warning'] .= '. This is a known problem with some versions of LAME (3.91, 3.92) DLL in CBR mode.'; - $ThisFileInfo['audio']['codec'] = 'LAME'; - } elseif (empty($ThisFileInfo['id3v2']['headerlength']) && ($ThisFileInfo['avdataoffset'] == $ThisFileInfo['mpeg']['audio']['framelength'])) { - $ThisFileInfo['warning'] .= '. This is a known problem with some versions of LAME (3.91, 3.92) DLL in CBR mode.'; - $ThisFileInfo['audio']['codec'] = 'LAME'; - } - } + if (isset($ThisFileInfo['mpeg']['audio']['layer']) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'II')) { + $ThisFileInfo['audio']['dataformat'] = 'mp2'; + } elseif (isset($ThisFileInfo['mpeg']['audio']['layer']) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'I')) { + $ThisFileInfo['audio']['dataformat'] = 'mp1'; + } + if ($ThisFileInfo['fileformat'] == 'mp3') { + switch ($ThisFileInfo['audio']['dataformat']) { + case 'mp1': + case 'mp2': + case 'mp3': + $ThisFileInfo['fileformat'] = $ThisFileInfo['audio']['dataformat']; + break; - } + default: + $ThisFileInfo['warning'] .= "\n".'Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$ThisFileInfo['audio']['dataformat'].'"'; + break; + } + } - if (isset($ThisFileInfo['mpeg']['audio']['layer']) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'II')) { - $ThisFileInfo['audio']['dataformat'] = 'mp2'; - } elseif (isset($ThisFileInfo['mpeg']['audio']['layer']) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'I')) { - $ThisFileInfo['audio']['dataformat'] = 'mp1'; - } - if ($ThisFileInfo['fileformat'] == 'mp3') { - switch ($ThisFileInfo['audio']['dataformat']) { - case 'mp1': - case 'mp2': - case 'mp3': - $ThisFileInfo['fileformat'] = $ThisFileInfo['audio']['dataformat']; - break; + if (empty($ThisFileInfo['fileformat'])) { + $ThisFileInfo['error'] .= "\n".'Synch not found'; + unset($ThisFileInfo['fileformat']); + unset($ThisFileInfo['audio']['bitrate_mode']); + unset($ThisFileInfo['avdataoffset']); + unset($ThisFileInfo['avdataend']); + return false; + } - default: - $ThisFileInfo['warning'] .= "\n".'Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$ThisFileInfo['audio']['dataformat'].'"'; - break; - } - } + $ThisFileInfo['mime_type'] = 'audio/mpeg'; + $ThisFileInfo['audio']['lossless'] = false; - if (empty($ThisFileInfo['fileformat'])) { - $ThisFileInfo['error'] .= "\n".'Synch not found'; - unset($ThisFileInfo['fileformat']); - unset($ThisFileInfo['audio']['bitrate_mode']); - unset($ThisFileInfo['avdataoffset']); - unset($ThisFileInfo['avdataend']); - return false; - } + // Calculate playtime + if (!isset($ThisFileInfo['playtime_seconds']) && isset($ThisFileInfo['audio']['bitrate']) && ($ThisFileInfo['audio']['bitrate'] > 0)) { + $ThisFileInfo['playtime_seconds'] = ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']) * 8 / $ThisFileInfo['audio']['bitrate']; + } - $ThisFileInfo['mime_type'] = 'audio/mpeg'; - $ThisFileInfo['audio']['lossless'] = false; + if (isset($ThisFileInfo['mpeg']['audio']['LAME'])) { + $ThisFileInfo['audio']['codec'] = 'LAME'; + if (!empty($ThisFileInfo['mpeg']['audio']['LAME']['long_version'])) { + $ThisFileInfo['audio']['encoder'] = trim($ThisFileInfo['mpeg']['audio']['LAME']['long_version']); + } + } - // Calculate playtime - if (!isset($ThisFileInfo['playtime_seconds']) && isset($ThisFileInfo['audio']['bitrate']) && ($ThisFileInfo['audio']['bitrate'] > 0)) { - $ThisFileInfo['playtime_seconds'] = ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']) * 8 / $ThisFileInfo['audio']['bitrate']; - } - - if (isset($ThisFileInfo['mpeg']['audio']['LAME'])) { - $ThisFileInfo['audio']['codec'] = 'LAME'; - if (!empty($ThisFileInfo['mpeg']['audio']['LAME']['long_version'])) { - $ThisFileInfo['audio']['encoder'] = trim($ThisFileInfo['mpeg']['audio']['LAME']['long_version']); - } - } - - return true; + return true; } -function decodeMPEGaudioHeader($fd, $offset, &$ThisFileInfo, $recursivesearch=true, $ScanAsCBR=false, $FastMPEGheaderScan=false) { - - static $MPEGaudioVersionLookup; - static $MPEGaudioLayerLookup; - static $MPEGaudioBitrateLookup; - static $MPEGaudioFrequencyLookup; - static $MPEGaudioChannelModeLookup; - static $MPEGaudioModeExtensionLookup; - static $MPEGaudioEmphasisLookup; - if (empty($MPEGaudioVersionLookup)) { - $MPEGaudioVersionLookup = MPEGaudioVersionArray(); - $MPEGaudioLayerLookup = MPEGaudioLayerArray(); - $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); - $MPEGaudioFrequencyLookup = MPEGaudioFrequencyArray(); - $MPEGaudioChannelModeLookup = MPEGaudioChannelModeArray(); - $MPEGaudioModeExtensionLookup = MPEGaudioModeExtensionArray(); - $MPEGaudioEmphasisLookup = MPEGaudioEmphasisArray(); - } - - if ($offset >= $ThisFileInfo['avdataend']) { - $ThisFileInfo['error'] .= "\n".'end of file encounter looking for MPEG synch'; - return false; - } - fseek($fd, $offset, SEEK_SET); - $headerstring = fread($fd, 1441); // worse-case max length = 32kHz @ 320kbps layer 3 = 1441 bytes/frame - - // MP3 audio frame structure: - // $aa $aa $aa $aa [$bb $bb] $cc... - // where $aa..$aa is the four-byte mpeg-audio header (below) - // $bb $bb is the optional 2-byte CRC - // and $cc... is the audio data - - $head4 = substr($headerstring, 0, 4); - - static $MPEGaudioHeaderDecodeCache = array(); - if (isset($MPEGaudioHeaderDecodeCache[$head4])) { - $MPEGheaderRawArray = $MPEGaudioHeaderDecodeCache[$head4]; - } else { - $MPEGheaderRawArray = MPEGaudioHeaderDecode($head4); - $MPEGaudioHeaderDecodeCache[$head4] = $MPEGheaderRawArray; - } - - static $MPEGaudioHeaderValidCache = array(); - - // Not in cache - if (!isset($MPEGaudioHeaderValidCache[$head4])) { - $MPEGaudioHeaderValidCache[$head4] = MPEGaudioHeaderValid($MPEGheaderRawArray); - } - - if ($MPEGaudioHeaderValidCache[$head4]) { - $ThisFileInfo['mpeg']['audio']['raw'] = $MPEGheaderRawArray; - } else { - $ThisFileInfo['error'] .= "\n".'Invalid MPEG audio header at offset '.$offset; - return false; - } - - if (!$FastMPEGheaderScan) { - - $ThisFileInfo['mpeg']['audio']['version'] = $MPEGaudioVersionLookup[$ThisFileInfo['mpeg']['audio']['raw']['version']]; - $ThisFileInfo['mpeg']['audio']['layer'] = $MPEGaudioLayerLookup[$ThisFileInfo['mpeg']['audio']['raw']['layer']]; - - $ThisFileInfo['mpeg']['audio']['channelmode'] = $MPEGaudioChannelModeLookup[$ThisFileInfo['mpeg']['audio']['raw']['channelmode']]; - $ThisFileInfo['mpeg']['audio']['channels'] = (($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') ? 1 : 2); - $ThisFileInfo['mpeg']['audio']['sample_rate'] = $MPEGaudioFrequencyLookup[$ThisFileInfo['mpeg']['audio']['version']][$ThisFileInfo['mpeg']['audio']['raw']['sample_rate']]; - $ThisFileInfo['mpeg']['audio']['protection'] = !$ThisFileInfo['mpeg']['audio']['raw']['protection']; - $ThisFileInfo['mpeg']['audio']['private'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['private']; - $ThisFileInfo['mpeg']['audio']['modeextension'] = $MPEGaudioModeExtensionLookup[$ThisFileInfo['mpeg']['audio']['layer']][$ThisFileInfo['mpeg']['audio']['raw']['modeextension']]; - $ThisFileInfo['mpeg']['audio']['copyright'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['copyright']; - $ThisFileInfo['mpeg']['audio']['original'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['original']; - $ThisFileInfo['mpeg']['audio']['emphasis'] = $MPEGaudioEmphasisLookup[$ThisFileInfo['mpeg']['audio']['raw']['emphasis']]; - - $ThisFileInfo['audio']['channels'] = $ThisFileInfo['mpeg']['audio']['channels']; - $ThisFileInfo['audio']['sample_rate'] = $ThisFileInfo['mpeg']['audio']['sample_rate']; - - if ($ThisFileInfo['mpeg']['audio']['protection']) { - $ThisFileInfo['mpeg']['audio']['crc'] = BigEndian2Int(substr($headerstring, 4, 2)); - } - - } - - if ($ThisFileInfo['mpeg']['audio']['raw']['bitrate'] == 15) { - // http://www.hydrogenaudio.org/?act=ST&f=16&t=9682&st=0 - $ThisFileInfo['warning'] .= "\n".'Invalid bitrate index (15), this is a known bug in free-format MP3s encoded by LAME v3.90 - 3.93.1'; - $ThisFileInfo['mpeg']['audio']['raw']['bitrate'] = 0; - } - $ThisFileInfo['mpeg']['audio']['padding'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['padding']; - $ThisFileInfo['mpeg']['audio']['bitrate'] = $MPEGaudioBitrateLookup[$ThisFileInfo['mpeg']['audio']['version']][$ThisFileInfo['mpeg']['audio']['layer']][$ThisFileInfo['mpeg']['audio']['raw']['bitrate']]; - - if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && ($offset == $ThisFileInfo['avdataoffset'])) { - // only skip multiple frame check if free-format bitstream found at beginning of file - // otherwise is quite possibly simply corrupted data - $recursivesearch = false; - } - - // For Layer II there are some combinations of bitrate and mode which are not allowed. - if (!$FastMPEGheaderScan && ($ThisFileInfo['mpeg']['audio']['layer'] == 'II')) { - - $ThisFileInfo['audio']['dataformat'] = 'mp2'; - switch ($ThisFileInfo['mpeg']['audio']['channelmode']) { - - case 'mono': - if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') || ($ThisFileInfo['mpeg']['audio']['bitrate'] <= 192)) { - // these are ok - } else { - $ThisFileInfo['error'] .= "\n".$ThisFileInfo['mpeg']['audio']['bitrate'].'kbps not allowed in Layer II, '.$ThisFileInfo['mpeg']['audio']['channelmode'].'.'; - return false; - } - break; - - case 'stereo': - case 'joint stereo': - case 'dual channel': - if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') || ($ThisFileInfo['mpeg']['audio']['bitrate'] == 64) || ($ThisFileInfo['mpeg']['audio']['bitrate'] >= 96)) { - // these are ok - } else { - $ThisFileInfo['error'] .= "\n".$ThisFileInfo['mpeg']['audio']['bitrate'].'kbps not allowed in Layer II, '.$ThisFileInfo['mpeg']['audio']['channelmode'].'.'; - return false; - } - break; - - } - - } - - - if ($ThisFileInfo['audio']['sample_rate'] > 0) { - $ThisFileInfo['mpeg']['audio']['framelength'] = MPEGaudioFrameLength($ThisFileInfo['mpeg']['audio']['bitrate'], $ThisFileInfo['mpeg']['audio']['version'], $ThisFileInfo['mpeg']['audio']['layer'], (int) $ThisFileInfo['mpeg']['audio']['padding'], $ThisFileInfo['audio']['sample_rate']); - } - - if ($ThisFileInfo['mpeg']['audio']['bitrate'] != 'free') { - - $ThisFileInfo['audio']['bitrate'] = 1000 * $ThisFileInfo['mpeg']['audio']['bitrate']; - - if (isset($ThisFileInfo['mpeg']['audio']['framelength'])) { - $nextframetestoffset = $offset + $ThisFileInfo['mpeg']['audio']['framelength']; - } else { - $ThisFileInfo['error'] .= "\n".'Frame at offset('.$offset.') is has an invalid frame length.'; - return false; - } - - } - - $ExpectedNumberOfAudioBytes = 0; - - //////////////////////////////////////////////////////////////////////////////////// - // Variable-bitrate headers - - if (substr($headerstring, 4 + 32, 4) == 'VBRI') { - // Fraunhofer VBR header is hardcoded 'VBRI' at offset 0x24 (36) - // specs taken from http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html - - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; - $ThisFileInfo['mpeg']['audio']['VBR_method'] = 'Fraunhofer'; - $ThisFileInfo['audio']['codec'] = 'Fraunhofer'; - - $SideInfoData = substr($headerstring, 4 + 2, 32); - - $FraunhoferVBROffset = 36; - - $ThisFileInfo['mpeg']['audio']['VBR_encoder_version'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 4, 2)); - $ThisFileInfo['mpeg']['audio']['VBR_encoder_delay'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 6, 2)); - $ThisFileInfo['mpeg']['audio']['VBR_quality'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 8, 2)); - $ThisFileInfo['mpeg']['audio']['VBR_bytes'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 10, 4)); - $ThisFileInfo['mpeg']['audio']['VBR_frames'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 14, 4)); - $ThisFileInfo['mpeg']['audio']['VBR_seek_offsets'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 18, 2)); - //$ThisFileInfo['mpeg']['audio']['reserved'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 20, 4)); // hardcoded $00 $01 $00 $02 - purpose unknown - $ThisFileInfo['mpeg']['audio']['VBR_seek_offsets_stride'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 24, 2)); - - $ExpectedNumberOfAudioBytes = $ThisFileInfo['mpeg']['audio']['VBR_bytes']; - - $previousbyteoffset = $offset; - for ($i = 0; $i < $ThisFileInfo['mpeg']['audio']['VBR_seek_offsets']; $i++) { - $Fraunhofer_OffsetN = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset, 2)); - $FraunhoferVBROffset += 2; - $ThisFileInfo['mpeg']['audio']['VBR_offsets_relative'][$i] = $Fraunhofer_OffsetN; - $ThisFileInfo['mpeg']['audio']['VBR_offsets_absolute'][$i] = $Fraunhofer_OffsetN + $previousbyteoffset; - $previousbyteoffset += $Fraunhofer_OffsetN; - } - - - } else { - - // Xing VBR header is hardcoded 'Xing' at a offset 0x0D (13), 0x15 (21) or 0x24 (36) - // depending on MPEG layer and number of channels - - if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { - if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { - // MPEG-1 (mono) - $VBRidOffset = 4 + 17; // 0x15 - $SideInfoData = substr($headerstring, 4 + 2, 17); - } else { - // MPEG-1 (stereo, joint-stereo, dual-channel) - $VBRidOffset = 4 + 32; // 0x24 - $SideInfoData = substr($headerstring, 4 + 2, 32); - } - } else { // 2 or 2.5 - if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { - // MPEG-2, MPEG-2.5 (mono) - $VBRidOffset = 4 + 9; // 0x0D - $SideInfoData = substr($headerstring, 4 + 2, 9); - } else { - // MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel) - $VBRidOffset = 4 + 17; // 0x15 - $SideInfoData = substr($headerstring, 4 + 2, 17); - } - } - - if ((substr($headerstring, $VBRidOffset, strlen('Xing')) == 'Xing') || (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Info')) { - // 'Xing' is traditional Xing VBR frame - // 'Info' is LAME-encoded CBR (This was done to avoid CBR files to be recognized as traditional Xing VBR files by some decoders.) - - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; - $ThisFileInfo['mpeg']['audio']['VBR_method'] = 'Xing'; - - $ThisFileInfo['mpeg']['audio']['xing_flags_raw'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 4, 4)); - - $ThisFileInfo['mpeg']['audio']['xing_flags']['frames'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000001); - $ThisFileInfo['mpeg']['audio']['xing_flags']['bytes'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000002); - $ThisFileInfo['mpeg']['audio']['xing_flags']['toc'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000004); - $ThisFileInfo['mpeg']['audio']['xing_flags']['vbr_scale'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000008); - - if ($ThisFileInfo['mpeg']['audio']['xing_flags']['frames']) { - $ThisFileInfo['mpeg']['audio']['VBR_frames'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 8, 4)); - } - if ($ThisFileInfo['mpeg']['audio']['xing_flags']['bytes']) { - $ThisFileInfo['mpeg']['audio']['VBR_bytes'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 12, 4)); - } - - if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && !empty($ThisFileInfo['mpeg']['audio']['VBR_frames']) && !empty($ThisFileInfo['mpeg']['audio']['VBR_bytes'])) { - $framelengthfloat = $ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']; - if ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { - // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12 - $ThisFileInfo['audio']['bitrate'] = ((($framelengthfloat / 4) - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 12; - } else { - // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144 - $ThisFileInfo['audio']['bitrate'] = (($framelengthfloat - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 144; - } - $ThisFileInfo['mpeg']['audio']['framelength'] = floor($framelengthfloat); - } - - if ($ThisFileInfo['mpeg']['audio']['xing_flags']['toc']) { - $LAMEtocData = substr($headerstring, $VBRidOffset + 16, 100); - for ($i = 0; $i < 100; $i++) { - $ThisFileInfo['mpeg']['audio']['toc'][$i] = ord($LAMEtocData{$i}); - } - } - if ($ThisFileInfo['mpeg']['audio']['xing_flags']['vbr_scale']) { - $ThisFileInfo['mpeg']['audio']['VBR_scale'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 116, 4)); - } - - // http://gabriel.mp3-tech.org/mp3infotag.html - if (substr($headerstring, $VBRidOffset + 120, 4) == 'LAME') { - $ThisFileInfo['mpeg']['audio']['LAME']['long_version'] = substr($headerstring, $VBRidOffset + 120, 20); - $ThisFileInfo['mpeg']['audio']['LAME']['short_version'] = substr($ThisFileInfo['mpeg']['audio']['LAME']['long_version'], 0, 9); - $ThisFileInfo['mpeg']['audio']['LAME']['long_version'] = rtrim($ThisFileInfo['mpeg']['audio']['LAME']['long_version'], "\x55\xAA"); - - if ($ThisFileInfo['mpeg']['audio']['LAME']['short_version'] >= 'LAME3.90.') { - - // It the LAME tag was only introduced in LAME v3.90 - // http://www.hydrogenaudio.org/?act=ST&f=15&t=9933 - - // Offsets of various bytes in http://gabriel.mp3-tech.org/mp3infotag.html - // are assuming a 'Xing' identifier offset of 0x24, which is the case for - // MPEG-1 non-mono, but not for other combinations - $LAMEtagOffsetContant = $VBRidOffset - 0x24; - - // byte $9B VBR Quality - // This field is there to indicate a quality level, although the scale was not precised in the original Xing specifications. - // Actually overwrites original Xing bytes - unset($ThisFileInfo['mpeg']['audio']['VBR_scale']); - $ThisFileInfo['mpeg']['audio']['LAME']['vbr_quality'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0x9B, 1)); - - // bytes $9C-$A4 Encoder short VersionString - $ThisFileInfo['mpeg']['audio']['LAME']['short_version'] = substr($headerstring, $LAMEtagOffsetContant + 0x9C, 9); - $ThisFileInfo['mpeg']['audio']['LAME']['long_version'] = $ThisFileInfo['mpeg']['audio']['LAME']['short_version']; - - // byte $A5 Info Tag revision + VBR method - $LAMEtagRevisionVBRmethod = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA5, 1)); - - $ThisFileInfo['mpeg']['audio']['LAME']['tag_revision'] = ($LAMEtagRevisionVBRmethod & 0xF0) >> 4; - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] = $LAMEtagRevisionVBRmethod & 0x0F; - $ThisFileInfo['mpeg']['audio']['LAME']['vbr_method'] = LAMEvbrMethodLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method']); - - // byte $A6 Lowpass filter value - $ThisFileInfo['mpeg']['audio']['LAME']['lowpass_frequency'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA6, 1)) * 100; - - // bytes $A7-$AE Replay Gain - // http://privatewww.essex.ac.uk/~djmrob/replaygain/rg_data_format.html - // bytes $A7-$AA : 32 bit floating point "Peak signal amplitude" - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] = BigEndian2Float(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4)); - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAB, 2)); - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAD, 2)); - - if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] == 0) { - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] = false; - } - - if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] != 0) { - require_once(GETID3_INCLUDEPATH.'getid3.rgad.php'); - - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['name'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0xE000) >> 13; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['originator'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x1C00) >> 10; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['sign_bit'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x0200) >> 9; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['gain_adjust'] = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x01FF; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['name'] = RGADnameLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['name']); - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['originator'] = RGADoriginatorLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['originator']); - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['gain_db'] = RGADadjustmentLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['gain_adjust'], $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['sign_bit']); - - if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] !== false) { - $ThisFileInfo['replay_gain']['radio']['peak'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude']; - } - $ThisFileInfo['replay_gain']['radio']['originator'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['originator']; - $ThisFileInfo['replay_gain']['radio']['adjustment'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['gain_db']; - } - if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] != 0) { - require_once(GETID3_INCLUDEPATH.'getid3.rgad.php'); - - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['name'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0xE000) >> 13; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['originator'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x1C00) >> 10; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['sign_bit'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x0200) >> 9; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['gain_adjust'] = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x01FF; - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['name'] = RGADnameLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['name']); - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['originator'] = RGADoriginatorLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['originator']); - $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['gain_db'] = RGADadjustmentLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['gain_adjust'], $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['sign_bit']); - - if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] !== false) { - $ThisFileInfo['replay_gain']['audiophile']['peak'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude']; - } - $ThisFileInfo['replay_gain']['audiophile']['originator'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['originator']; - $ThisFileInfo['replay_gain']['audiophile']['adjustment'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['gain_db']; - } - - - // byte $AF Encoding flags + ATH Type - $EncodingFlagsATHtype = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAF, 1)); - $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nspsytune'] = (bool) ($EncodingFlagsATHtype & 0x10); - $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nssafejoint'] = (bool) ($EncodingFlagsATHtype & 0x20); - $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nogap_next'] = (bool) ($EncodingFlagsATHtype & 0x40); - $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nogap_prev'] = (bool) ($EncodingFlagsATHtype & 0x80); - $ThisFileInfo['mpeg']['audio']['LAME']['ath_type'] = $EncodingFlagsATHtype & 0x0F; - - // byte $B0 if ABR {specified bitrate} else {minimal bitrate} - $ABRbitrateMinBitrate = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB0, 1)); - if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] == 2) { // Average BitRate (ABR) - $ThisFileInfo['mpeg']['audio']['LAME']['bitrate_abr'] = $ABRbitrateMinBitrate; - } elseif ($ABRbitrateMinBitrate > 0) { // Variable BitRate (VBR) - minimum bitrate - $ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min'] = $ABRbitrateMinBitrate; - } - - // bytes $B1-$B3 Encoder delays - $EncoderDelays = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB1, 3)); - $ThisFileInfo['mpeg']['audio']['LAME']['encoder_delay'] = ($EncoderDelays & 0xFFF000) >> 12; - $ThisFileInfo['mpeg']['audio']['LAME']['end_padding'] = $EncoderDelays & 0x000FFF; - - // byte $B4 Misc - $MiscByte = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB4, 1)); - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['noise_shaping'] = ($MiscByte & 0x03); - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['stereo_mode'] = ($MiscByte & 0x1C) >> 2; - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['not_optimal_quality'] = ($MiscByte & 0x20) >> 5; - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['source_sample_freq'] = ($MiscByte & 0xC0) >> 6; - $ThisFileInfo['mpeg']['audio']['LAME']['noise_shaping'] = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['noise_shaping']; - $ThisFileInfo['mpeg']['audio']['LAME']['stereo_mode'] = LAMEmiscStereoModeLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['stereo_mode']); - $ThisFileInfo['mpeg']['audio']['LAME']['not_optimal_quality'] = (bool) $ThisFileInfo['mpeg']['audio']['LAME']['raw']['not_optimal_quality']; - $ThisFileInfo['mpeg']['audio']['LAME']['source_sample_freq'] = LAMEmiscSourceSampleFrequencyLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['source_sample_freq']); - - // byte $B5 MP3 Gain - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['mp3_gain'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB5, 1), false, true); - $ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_db'] = 1.5 * $ThisFileInfo['mpeg']['audio']['LAME']['raw']['mp3_gain']; - $ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_factor'] = pow(2, ($ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_db'] / 6)); - - // bytes $B6-$B7 Preset and surround info - $PresetSurroundBytes = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB6, 2)); - // Reserved = ($PresetSurroundBytes & 0xC000); - $ThisFileInfo['mpeg']['audio']['LAME']['raw']['surround_info'] = ($PresetSurroundBytes & 0x3800); - $ThisFileInfo['mpeg']['audio']['LAME']['surround_info'] = LAMEsurroundInfoLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['surround_info']); - $ThisFileInfo['mpeg']['audio']['LAME']['preset_used_id'] = ($PresetSurroundBytes & 0x07FF); - - // bytes $B8-$BB MusicLength - $ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB8, 4)); - $ExpectedNumberOfAudioBytes = (($ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] > 0) ? $ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] : $ThisFileInfo['mpeg']['audio']['VBR_bytes']); - - // bytes $BC-$BD MusicCRC - $ThisFileInfo['mpeg']['audio']['LAME']['music_crc'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBC, 2)); - - // bytes $BE-$BF CRC-16 of Info Tag - $ThisFileInfo['mpeg']['audio']['LAME']['lame_tag_crc'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2)); - - - // LAME CBR - if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] == 1) { - - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; - if (empty($ThisFileInfo['mpeg']['audio']['bitrate']) || ($ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min'] != 255)) { - $ThisFileInfo['mpeg']['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min']; - } - - } - - } - } - - } else { - - // not Fraunhofer or Xing VBR methods, most likely CBR (but could be VBR with no header) - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; - if ($recursivesearch) { - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; - if (RecursiveFrameScanning($fd, $ThisFileInfo, $offset, $nextframetestoffset, true)) { - $recursivesearch = false; - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; - } - if ($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') { - $ThisFileInfo['warning'] .= "\n".'VBR file with no VBR header. Bitrate values calculated from actual frame bitrates.'; - } - } - - } - - } - - if (($ExpectedNumberOfAudioBytes > 0) && ($ExpectedNumberOfAudioBytes != ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']))) { - if (($ExpectedNumberOfAudioBytes - ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])) == 1) { - $ThisFileInfo['warning'] .= "\n".'Last byte of data truncated (this is a known bug in Meracl ID3 Tag Writer before v1.3.5)'; - } elseif ($ExpectedNumberOfAudioBytes > ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])) { - $ThisFileInfo['warning'] .= "\n".'Probable truncated file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, only found '.($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']).' (short by '.($ExpectedNumberOfAudioBytes - ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])).' bytes)'; - } else { - $ThisFileInfo['warning'] .= "\n".'Too much data in file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, found '.($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']).' ('.(($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']) - $ExpectedNumberOfAudioBytes).' bytes too many)'; - } - } - - if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && empty($ThisFileInfo['audio']['bitrate'])) { - if (($offset == $ThisFileInfo['avdataoffset']) && empty($ThisFileInfo['mpeg']['audio']['VBR_frames'])) { - $framebytelength = FreeFormatFrameLength($fd, $offset, $ThisFileInfo, true); - if ($framebytelength > 0) { - $ThisFileInfo['mpeg']['audio']['framelength'] = $framebytelength; - if ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { - // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12 - $ThisFileInfo['audio']['bitrate'] = ((($framebytelength / 4) - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 12; - } else { - // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144 - $ThisFileInfo['audio']['bitrate'] = (($framebytelength - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 144; - } - } else { - $ThisFileInfo['error'] .= "\n".'Error calculating frame length of free-format MP3 without Xing/LAME header'; - } - } - } - - if (($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') && isset($ThisFileInfo['mpeg']['audio']['VBR_frames']) && ($ThisFileInfo['mpeg']['audio']['VBR_frames'] > 1)) { - $ThisFileInfo['mpeg']['audio']['VBR_frames']--; // don't count the Xing / VBRI frame - if (($ThisFileInfo['mpeg']['audio']['version'] == '1') && ($ThisFileInfo['mpeg']['audio']['layer'] == 'I')) { - $ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 384)) / 1000; - } elseif ((($ThisFileInfo['mpeg']['audio']['version'] == '2') || ($ThisFileInfo['mpeg']['audio']['version'] == '2.5')) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'III')) { - $ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 576)) / 1000; - } else { - $ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 1152)) / 1000; - } - if ($ThisFileInfo['mpeg']['audio']['VBR_bitrate'] > 0) { - $ThisFileInfo['audio']['bitrate'] = 1000 * $ThisFileInfo['mpeg']['audio']['VBR_bitrate']; - $ThisFileInfo['mpeg']['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['VBR_bitrate']; // to avoid confusion - } - } - - // End variable-bitrate headers - //////////////////////////////////////////////////////////////////////////////////// - - if ($recursivesearch) { - - if (!RecursiveFrameScanning($fd, $ThisFileInfo, $offset, $nextframetestoffset, $ScanAsCBR)) { - return false; - } - - } - - - //if (false) { - // // experimental side info parsing section - not returning anything useful yet - // - // $SideInfoBitstream = BigEndian2Bin($SideInfoData); - // $SideInfoOffset = 0; - // - // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { - // if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { - // // MPEG-1 (mono) - // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9); - // $SideInfoOffset += 9; - // $SideInfoOffset += 5; - // } else { - // // MPEG-1 (stereo, joint-stereo, dual-channel) - // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9); - // $SideInfoOffset += 9; - // $SideInfoOffset += 3; - // } - // } else { // 2 or 2.5 - // if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { - // // MPEG-2, MPEG-2.5 (mono) - // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8); - // $SideInfoOffset += 8; - // $SideInfoOffset += 1; - // } else { - // // MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel) - // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8); - // $SideInfoOffset += 8; - // $SideInfoOffset += 2; - // } - // } - // - // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { - // for ($channel = 0; $channel < $ThisFileInfo['audio']['channels']; $channel++) { - // for ($scfsi_band = 0; $scfsi_band < 4; $scfsi_band++) { - // $ThisFileInfo['mpeg']['audio']['scfsi'][$channel][$scfsi_band] = substr($SideInfoBitstream, $SideInfoOffset, 1); - // $SideInfoOffset += 2; - // } - // } - // } - // for ($granule = 0; $granule < (($ThisFileInfo['mpeg']['audio']['version'] == '1') ? 2 : 1); $granule++) { - // for ($channel = 0; $channel < $ThisFileInfo['audio']['channels']; $channel++) { - // $ThisFileInfo['mpeg']['audio']['part2_3_length'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 12); - // $SideInfoOffset += 12; - // $ThisFileInfo['mpeg']['audio']['big_values'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9); - // $SideInfoOffset += 9; - // $ThisFileInfo['mpeg']['audio']['global_gain'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 8); - // $SideInfoOffset += 8; - // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { - // $ThisFileInfo['mpeg']['audio']['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4); - // $SideInfoOffset += 4; - // } else { - // $ThisFileInfo['mpeg']['audio']['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9); - // $SideInfoOffset += 9; - // } - // $ThisFileInfo['mpeg']['audio']['window_switching_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); - // $SideInfoOffset += 1; - // - // if ($ThisFileInfo['mpeg']['audio']['window_switching_flag'][$granule][$channel] == '1') { - // - // $ThisFileInfo['mpeg']['audio']['block_type'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 2); - // $SideInfoOffset += 2; - // $ThisFileInfo['mpeg']['audio']['mixed_block_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); - // $SideInfoOffset += 1; - // - // for ($region = 0; $region < 2; $region++) { - // $ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5); - // $SideInfoOffset += 5; - // } - // $ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][2] = 0; - // - // for ($window = 0; $window < 3; $window++) { - // $ThisFileInfo['mpeg']['audio']['subblock_gain'][$granule][$channel][$window] = substr($SideInfoBitstream, $SideInfoOffset, 3); - // $SideInfoOffset += 3; - // } - // - // } else { - // - // for ($region = 0; $region < 3; $region++) { - // $ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5); - // $SideInfoOffset += 5; - // } - // - // $ThisFileInfo['mpeg']['audio']['region0_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4); - // $SideInfoOffset += 4; - // $ThisFileInfo['mpeg']['audio']['region1_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 3); - // $SideInfoOffset += 3; - // $ThisFileInfo['mpeg']['audio']['block_type'][$granule][$channel] = 0; - // } - // - // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { - // $ThisFileInfo['mpeg']['audio']['preflag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); - // $SideInfoOffset += 1; - // } - // $ThisFileInfo['mpeg']['audio']['scalefac_scale'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); - // $SideInfoOffset += 1; - // $ThisFileInfo['mpeg']['audio']['count1table_select'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); - // $SideInfoOffset += 1; - // } - // } - //} - - return true; +function decodeMPEGaudioHeader($fd, $offset, &$ThisFileInfo, $recursivesearch = true, $ScanAsCBR = false, $FastMPEGheaderScan = false) +{ + + static $MPEGaudioVersionLookup; + static $MPEGaudioLayerLookup; + static $MPEGaudioBitrateLookup; + static $MPEGaudioFrequencyLookup; + static $MPEGaudioChannelModeLookup; + static $MPEGaudioModeExtensionLookup; + static $MPEGaudioEmphasisLookup; + if (empty($MPEGaudioVersionLookup)) { + $MPEGaudioVersionLookup = MPEGaudioVersionArray(); + $MPEGaudioLayerLookup = MPEGaudioLayerArray(); + $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); + $MPEGaudioFrequencyLookup = MPEGaudioFrequencyArray(); + $MPEGaudioChannelModeLookup = MPEGaudioChannelModeArray(); + $MPEGaudioModeExtensionLookup = MPEGaudioModeExtensionArray(); + $MPEGaudioEmphasisLookup = MPEGaudioEmphasisArray(); + } + + if ($offset >= $ThisFileInfo['avdataend']) { + $ThisFileInfo['error'] .= "\n".'end of file encounter looking for MPEG synch'; + return false; + } + fseek($fd, $offset, SEEK_SET); + $headerstring = fread($fd, 1441); // worse-case max length = 32kHz @ 320kbps layer 3 = 1441 bytes/frame + + // MP3 audio frame structure: + // $aa $aa $aa $aa [$bb $bb] $cc... + // where $aa..$aa is the four-byte mpeg-audio header (below) + // $bb $bb is the optional 2-byte CRC + // and $cc... is the audio data + + $head4 = substr($headerstring, 0, 4); + + static $MPEGaudioHeaderDecodeCache = []; + if (isset($MPEGaudioHeaderDecodeCache[$head4])) { + $MPEGheaderRawArray = $MPEGaudioHeaderDecodeCache[$head4]; + } else { + $MPEGheaderRawArray = MPEGaudioHeaderDecode($head4); + $MPEGaudioHeaderDecodeCache[$head4] = $MPEGheaderRawArray; + } + + static $MPEGaudioHeaderValidCache = []; + + // Not in cache + if (!isset($MPEGaudioHeaderValidCache[$head4])) { + $MPEGaudioHeaderValidCache[$head4] = MPEGaudioHeaderValid($MPEGheaderRawArray); + } + + if ($MPEGaudioHeaderValidCache[$head4]) { + $ThisFileInfo['mpeg']['audio']['raw'] = $MPEGheaderRawArray; + } else { + $ThisFileInfo['error'] .= "\n".'Invalid MPEG audio header at offset '.$offset; + return false; + } + + if (!$FastMPEGheaderScan) { + $ThisFileInfo['mpeg']['audio']['version'] = $MPEGaudioVersionLookup[$ThisFileInfo['mpeg']['audio']['raw']['version']]; + $ThisFileInfo['mpeg']['audio']['layer'] = $MPEGaudioLayerLookup[$ThisFileInfo['mpeg']['audio']['raw']['layer']]; + + $ThisFileInfo['mpeg']['audio']['channelmode'] = $MPEGaudioChannelModeLookup[$ThisFileInfo['mpeg']['audio']['raw']['channelmode']]; + $ThisFileInfo['mpeg']['audio']['channels'] = (($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') ? 1 : 2); + $ThisFileInfo['mpeg']['audio']['sample_rate'] = $MPEGaudioFrequencyLookup[$ThisFileInfo['mpeg']['audio']['version']][$ThisFileInfo['mpeg']['audio']['raw']['sample_rate']]; + $ThisFileInfo['mpeg']['audio']['protection'] = !$ThisFileInfo['mpeg']['audio']['raw']['protection']; + $ThisFileInfo['mpeg']['audio']['private'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['private']; + $ThisFileInfo['mpeg']['audio']['modeextension'] = $MPEGaudioModeExtensionLookup[$ThisFileInfo['mpeg']['audio']['layer']][$ThisFileInfo['mpeg']['audio']['raw']['modeextension']]; + $ThisFileInfo['mpeg']['audio']['copyright'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['copyright']; + $ThisFileInfo['mpeg']['audio']['original'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['original']; + $ThisFileInfo['mpeg']['audio']['emphasis'] = $MPEGaudioEmphasisLookup[$ThisFileInfo['mpeg']['audio']['raw']['emphasis']]; + + $ThisFileInfo['audio']['channels'] = $ThisFileInfo['mpeg']['audio']['channels']; + $ThisFileInfo['audio']['sample_rate'] = $ThisFileInfo['mpeg']['audio']['sample_rate']; + + if ($ThisFileInfo['mpeg']['audio']['protection']) { + $ThisFileInfo['mpeg']['audio']['crc'] = BigEndian2Int(substr($headerstring, 4, 2)); + } + } + + if ($ThisFileInfo['mpeg']['audio']['raw']['bitrate'] == 15) { + // http://www.hydrogenaudio.org/?act=ST&f=16&t=9682&st=0 + $ThisFileInfo['warning'] .= "\n".'Invalid bitrate index (15), this is a known bug in free-format MP3s encoded by LAME v3.90 - 3.93.1'; + $ThisFileInfo['mpeg']['audio']['raw']['bitrate'] = 0; + } + $ThisFileInfo['mpeg']['audio']['padding'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['padding']; + $ThisFileInfo['mpeg']['audio']['bitrate'] = $MPEGaudioBitrateLookup[$ThisFileInfo['mpeg']['audio']['version']][$ThisFileInfo['mpeg']['audio']['layer']][$ThisFileInfo['mpeg']['audio']['raw']['bitrate']]; + + if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && ($offset == $ThisFileInfo['avdataoffset'])) { + // only skip multiple frame check if free-format bitstream found at beginning of file + // otherwise is quite possibly simply corrupted data + $recursivesearch = false; + } + + // For Layer II there are some combinations of bitrate and mode which are not allowed. + if (!$FastMPEGheaderScan && ($ThisFileInfo['mpeg']['audio']['layer'] == 'II')) { + $ThisFileInfo['audio']['dataformat'] = 'mp2'; + switch ($ThisFileInfo['mpeg']['audio']['channelmode']) { + case 'mono': + if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') || ($ThisFileInfo['mpeg']['audio']['bitrate'] <= 192)) { + // these are ok + } else { + $ThisFileInfo['error'] .= "\n".$ThisFileInfo['mpeg']['audio']['bitrate'].'kbps not allowed in Layer II, '.$ThisFileInfo['mpeg']['audio']['channelmode'].'.'; + return false; + } + break; + + case 'stereo': + case 'joint stereo': + case 'dual channel': + if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') || ($ThisFileInfo['mpeg']['audio']['bitrate'] == 64) || ($ThisFileInfo['mpeg']['audio']['bitrate'] >= 96)) { + // these are ok + } else { + $ThisFileInfo['error'] .= "\n".$ThisFileInfo['mpeg']['audio']['bitrate'].'kbps not allowed in Layer II, '.$ThisFileInfo['mpeg']['audio']['channelmode'].'.'; + return false; + } + break; + } + } + + + if ($ThisFileInfo['audio']['sample_rate'] > 0) { + $ThisFileInfo['mpeg']['audio']['framelength'] = MPEGaudioFrameLength($ThisFileInfo['mpeg']['audio']['bitrate'], $ThisFileInfo['mpeg']['audio']['version'], $ThisFileInfo['mpeg']['audio']['layer'], (int) $ThisFileInfo['mpeg']['audio']['padding'], $ThisFileInfo['audio']['sample_rate']); + } + + if ($ThisFileInfo['mpeg']['audio']['bitrate'] != 'free') { + $ThisFileInfo['audio']['bitrate'] = 1000 * $ThisFileInfo['mpeg']['audio']['bitrate']; + + if (isset($ThisFileInfo['mpeg']['audio']['framelength'])) { + $nextframetestoffset = $offset + $ThisFileInfo['mpeg']['audio']['framelength']; + } else { + $ThisFileInfo['error'] .= "\n".'Frame at offset('.$offset.') is has an invalid frame length.'; + return false; + } + } + + $ExpectedNumberOfAudioBytes = 0; + + //////////////////////////////////////////////////////////////////////////////////// + // Variable-bitrate headers + + if (substr($headerstring, 4 + 32, 4) == 'VBRI') { + // Fraunhofer VBR header is hardcoded 'VBRI' at offset 0x24 (36) + // specs taken from http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html + + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; + $ThisFileInfo['mpeg']['audio']['VBR_method'] = 'Fraunhofer'; + $ThisFileInfo['audio']['codec'] = 'Fraunhofer'; + + $SideInfoData = substr($headerstring, 4 + 2, 32); + + $FraunhoferVBROffset = 36; + + $ThisFileInfo['mpeg']['audio']['VBR_encoder_version'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 4, 2)); + $ThisFileInfo['mpeg']['audio']['VBR_encoder_delay'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 6, 2)); + $ThisFileInfo['mpeg']['audio']['VBR_quality'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 8, 2)); + $ThisFileInfo['mpeg']['audio']['VBR_bytes'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 10, 4)); + $ThisFileInfo['mpeg']['audio']['VBR_frames'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 14, 4)); + $ThisFileInfo['mpeg']['audio']['VBR_seek_offsets'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 18, 2)); + //$ThisFileInfo['mpeg']['audio']['reserved'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 20, 4)); // hardcoded $00 $01 $00 $02 - purpose unknown + $ThisFileInfo['mpeg']['audio']['VBR_seek_offsets_stride'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 24, 2)); + + $ExpectedNumberOfAudioBytes = $ThisFileInfo['mpeg']['audio']['VBR_bytes']; + + $previousbyteoffset = $offset; + for ($i = 0; $i < $ThisFileInfo['mpeg']['audio']['VBR_seek_offsets']; $i++) { + $Fraunhofer_OffsetN = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset, 2)); + $FraunhoferVBROffset += 2; + $ThisFileInfo['mpeg']['audio']['VBR_offsets_relative'][$i] = $Fraunhofer_OffsetN; + $ThisFileInfo['mpeg']['audio']['VBR_offsets_absolute'][$i] = $Fraunhofer_OffsetN + $previousbyteoffset; + $previousbyteoffset += $Fraunhofer_OffsetN; + } + } else { + // Xing VBR header is hardcoded 'Xing' at a offset 0x0D (13), 0x15 (21) or 0x24 (36) + // depending on MPEG layer and number of channels + + if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { + if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { + // MPEG-1 (mono) + $VBRidOffset = 4 + 17; // 0x15 + $SideInfoData = substr($headerstring, 4 + 2, 17); + } else { + // MPEG-1 (stereo, joint-stereo, dual-channel) + $VBRidOffset = 4 + 32; // 0x24 + $SideInfoData = substr($headerstring, 4 + 2, 32); + } + } else { // 2 or 2.5 + if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { + // MPEG-2, MPEG-2.5 (mono) + $VBRidOffset = 4 + 9; // 0x0D + $SideInfoData = substr($headerstring, 4 + 2, 9); + } else { + // MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel) + $VBRidOffset = 4 + 17; // 0x15 + $SideInfoData = substr($headerstring, 4 + 2, 17); + } + } + + if ((substr($headerstring, $VBRidOffset, strlen('Xing')) == 'Xing') || (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Info')) { + // 'Xing' is traditional Xing VBR frame + // 'Info' is LAME-encoded CBR (This was done to avoid CBR files to be recognized as traditional Xing VBR files by some decoders.) + + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; + $ThisFileInfo['mpeg']['audio']['VBR_method'] = 'Xing'; + + $ThisFileInfo['mpeg']['audio']['xing_flags_raw'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 4, 4)); + + $ThisFileInfo['mpeg']['audio']['xing_flags']['frames'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000001); + $ThisFileInfo['mpeg']['audio']['xing_flags']['bytes'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000002); + $ThisFileInfo['mpeg']['audio']['xing_flags']['toc'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000004); + $ThisFileInfo['mpeg']['audio']['xing_flags']['vbr_scale'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000008); + + if ($ThisFileInfo['mpeg']['audio']['xing_flags']['frames']) { + $ThisFileInfo['mpeg']['audio']['VBR_frames'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 8, 4)); + } + if ($ThisFileInfo['mpeg']['audio']['xing_flags']['bytes']) { + $ThisFileInfo['mpeg']['audio']['VBR_bytes'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 12, 4)); + } + + if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && !empty($ThisFileInfo['mpeg']['audio']['VBR_frames']) && !empty($ThisFileInfo['mpeg']['audio']['VBR_bytes'])) { + $framelengthfloat = $ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']; + if ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { + // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12 + $ThisFileInfo['audio']['bitrate'] = ((($framelengthfloat / 4) - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 12; + } else { + // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144 + $ThisFileInfo['audio']['bitrate'] = (($framelengthfloat - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 144; + } + $ThisFileInfo['mpeg']['audio']['framelength'] = floor($framelengthfloat); + } + + if ($ThisFileInfo['mpeg']['audio']['xing_flags']['toc']) { + $LAMEtocData = substr($headerstring, $VBRidOffset + 16, 100); + for ($i = 0; $i < 100; $i++) { + $ThisFileInfo['mpeg']['audio']['toc'][$i] = ord($LAMEtocData{$i}); + } + } + if ($ThisFileInfo['mpeg']['audio']['xing_flags']['vbr_scale']) { + $ThisFileInfo['mpeg']['audio']['VBR_scale'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 116, 4)); + } + + // http://gabriel.mp3-tech.org/mp3infotag.html + if (substr($headerstring, $VBRidOffset + 120, 4) == 'LAME') { + $ThisFileInfo['mpeg']['audio']['LAME']['long_version'] = substr($headerstring, $VBRidOffset + 120, 20); + $ThisFileInfo['mpeg']['audio']['LAME']['short_version'] = substr($ThisFileInfo['mpeg']['audio']['LAME']['long_version'], 0, 9); + $ThisFileInfo['mpeg']['audio']['LAME']['long_version'] = rtrim($ThisFileInfo['mpeg']['audio']['LAME']['long_version'], "\x55\xAA"); + + if ($ThisFileInfo['mpeg']['audio']['LAME']['short_version'] >= 'LAME3.90.') { + // It the LAME tag was only introduced in LAME v3.90 + // http://www.hydrogenaudio.org/?act=ST&f=15&t=9933 + + // Offsets of various bytes in http://gabriel.mp3-tech.org/mp3infotag.html + // are assuming a 'Xing' identifier offset of 0x24, which is the case for + // MPEG-1 non-mono, but not for other combinations + $LAMEtagOffsetContant = $VBRidOffset - 0x24; + + // byte $9B VBR Quality + // This field is there to indicate a quality level, although the scale was not precised in the original Xing specifications. + // Actually overwrites original Xing bytes + unset($ThisFileInfo['mpeg']['audio']['VBR_scale']); + $ThisFileInfo['mpeg']['audio']['LAME']['vbr_quality'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0x9B, 1)); + + // bytes $9C-$A4 Encoder short VersionString + $ThisFileInfo['mpeg']['audio']['LAME']['short_version'] = substr($headerstring, $LAMEtagOffsetContant + 0x9C, 9); + $ThisFileInfo['mpeg']['audio']['LAME']['long_version'] = $ThisFileInfo['mpeg']['audio']['LAME']['short_version']; + + // byte $A5 Info Tag revision + VBR method + $LAMEtagRevisionVBRmethod = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA5, 1)); + + $ThisFileInfo['mpeg']['audio']['LAME']['tag_revision'] = ($LAMEtagRevisionVBRmethod & 0xF0) >> 4; + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] = $LAMEtagRevisionVBRmethod & 0x0F; + $ThisFileInfo['mpeg']['audio']['LAME']['vbr_method'] = LAMEvbrMethodLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method']); + + // byte $A6 Lowpass filter value + $ThisFileInfo['mpeg']['audio']['LAME']['lowpass_frequency'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA6, 1)) * 100; + + // bytes $A7-$AE Replay Gain + // http://privatewww.essex.ac.uk/~djmrob/replaygain/rg_data_format.html + // bytes $A7-$AA : 32 bit floating point "Peak signal amplitude" + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] = BigEndian2Float(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4)); + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAB, 2)); + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAD, 2)); + + if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] == 0) { + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] = false; + } + + if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] != 0) { + require_once(GETID3_INCLUDEPATH.'getid3.rgad.php'); + + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['name'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0xE000) >> 13; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['originator'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x1C00) >> 10; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['sign_bit'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x0200) >> 9; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['gain_adjust'] = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x01FF; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['name'] = RGADnameLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['name']); + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['originator'] = RGADoriginatorLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['originator']); + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['gain_db'] = RGADadjustmentLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['gain_adjust'], $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['sign_bit']); + + if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] !== false) { + $ThisFileInfo['replay_gain']['radio']['peak'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude']; + } + $ThisFileInfo['replay_gain']['radio']['originator'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['originator']; + $ThisFileInfo['replay_gain']['radio']['adjustment'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['gain_db']; + } + if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] != 0) { + require_once(GETID3_INCLUDEPATH.'getid3.rgad.php'); + + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['name'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0xE000) >> 13; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['originator'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x1C00) >> 10; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['sign_bit'] = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x0200) >> 9; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['gain_adjust'] = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x01FF; + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['name'] = RGADnameLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['name']); + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['originator'] = RGADoriginatorLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['originator']); + $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['gain_db'] = RGADadjustmentLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['gain_adjust'], $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['sign_bit']); + + if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] !== false) { + $ThisFileInfo['replay_gain']['audiophile']['peak'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude']; + } + $ThisFileInfo['replay_gain']['audiophile']['originator'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['originator']; + $ThisFileInfo['replay_gain']['audiophile']['adjustment'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['gain_db']; + } + + + // byte $AF Encoding flags + ATH Type + $EncodingFlagsATHtype = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAF, 1)); + $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nspsytune'] = (bool) ($EncodingFlagsATHtype & 0x10); + $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nssafejoint'] = (bool) ($EncodingFlagsATHtype & 0x20); + $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nogap_next'] = (bool) ($EncodingFlagsATHtype & 0x40); + $ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nogap_prev'] = (bool) ($EncodingFlagsATHtype & 0x80); + $ThisFileInfo['mpeg']['audio']['LAME']['ath_type'] = $EncodingFlagsATHtype & 0x0F; + + // byte $B0 if ABR {specified bitrate} else {minimal bitrate} + $ABRbitrateMinBitrate = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB0, 1)); + if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] == 2) { // Average BitRate (ABR) + $ThisFileInfo['mpeg']['audio']['LAME']['bitrate_abr'] = $ABRbitrateMinBitrate; + } elseif ($ABRbitrateMinBitrate > 0) { // Variable BitRate (VBR) - minimum bitrate + $ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min'] = $ABRbitrateMinBitrate; + } + + // bytes $B1-$B3 Encoder delays + $EncoderDelays = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB1, 3)); + $ThisFileInfo['mpeg']['audio']['LAME']['encoder_delay'] = ($EncoderDelays & 0xFFF000) >> 12; + $ThisFileInfo['mpeg']['audio']['LAME']['end_padding'] = $EncoderDelays & 0x000FFF; + + // byte $B4 Misc + $MiscByte = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB4, 1)); + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['noise_shaping'] = ($MiscByte & 0x03); + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['stereo_mode'] = ($MiscByte & 0x1C) >> 2; + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['not_optimal_quality'] = ($MiscByte & 0x20) >> 5; + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['source_sample_freq'] = ($MiscByte & 0xC0) >> 6; + $ThisFileInfo['mpeg']['audio']['LAME']['noise_shaping'] = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['noise_shaping']; + $ThisFileInfo['mpeg']['audio']['LAME']['stereo_mode'] = LAMEmiscStereoModeLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['stereo_mode']); + $ThisFileInfo['mpeg']['audio']['LAME']['not_optimal_quality'] = (bool) $ThisFileInfo['mpeg']['audio']['LAME']['raw']['not_optimal_quality']; + $ThisFileInfo['mpeg']['audio']['LAME']['source_sample_freq'] = LAMEmiscSourceSampleFrequencyLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['source_sample_freq']); + + // byte $B5 MP3 Gain + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['mp3_gain'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB5, 1), false, true); + $ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_db'] = 1.5 * $ThisFileInfo['mpeg']['audio']['LAME']['raw']['mp3_gain']; + $ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_factor'] = pow(2, ($ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_db'] / 6)); + + // bytes $B6-$B7 Preset and surround info + $PresetSurroundBytes = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB6, 2)); + // Reserved = ($PresetSurroundBytes & 0xC000); + $ThisFileInfo['mpeg']['audio']['LAME']['raw']['surround_info'] = ($PresetSurroundBytes & 0x3800); + $ThisFileInfo['mpeg']['audio']['LAME']['surround_info'] = LAMEsurroundInfoLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['surround_info']); + $ThisFileInfo['mpeg']['audio']['LAME']['preset_used_id'] = ($PresetSurroundBytes & 0x07FF); + + // bytes $B8-$BB MusicLength + $ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB8, 4)); + $ExpectedNumberOfAudioBytes = (($ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] > 0) ? $ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] : $ThisFileInfo['mpeg']['audio']['VBR_bytes']); + + // bytes $BC-$BD MusicCRC + $ThisFileInfo['mpeg']['audio']['LAME']['music_crc'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBC, 2)); + + // bytes $BE-$BF CRC-16 of Info Tag + $ThisFileInfo['mpeg']['audio']['LAME']['lame_tag_crc'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2)); + + + // LAME CBR + if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] == 1) { + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; + if (empty($ThisFileInfo['mpeg']['audio']['bitrate']) || ($ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min'] != 255)) { + $ThisFileInfo['mpeg']['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min']; + } + } + } + } + } else { + // not Fraunhofer or Xing VBR methods, most likely CBR (but could be VBR with no header) + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; + if ($recursivesearch) { + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; + if (RecursiveFrameScanning($fd, $ThisFileInfo, $offset, $nextframetestoffset, true)) { + $recursivesearch = false; + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; + } + if ($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') { + $ThisFileInfo['warning'] .= "\n".'VBR file with no VBR header. Bitrate values calculated from actual frame bitrates.'; + } + } + } + } + + if (($ExpectedNumberOfAudioBytes > 0) && ($ExpectedNumberOfAudioBytes != ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']))) { + if (($ExpectedNumberOfAudioBytes - ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])) == 1) { + $ThisFileInfo['warning'] .= "\n".'Last byte of data truncated (this is a known bug in Meracl ID3 Tag Writer before v1.3.5)'; + } elseif ($ExpectedNumberOfAudioBytes > ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])) { + $ThisFileInfo['warning'] .= "\n".'Probable truncated file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, only found '.($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']).' (short by '.($ExpectedNumberOfAudioBytes - ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])).' bytes)'; + } else { + $ThisFileInfo['warning'] .= "\n".'Too much data in file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, found '.($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']).' ('.(($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']) - $ExpectedNumberOfAudioBytes).' bytes too many)'; + } + } + + if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && empty($ThisFileInfo['audio']['bitrate'])) { + if (($offset == $ThisFileInfo['avdataoffset']) && empty($ThisFileInfo['mpeg']['audio']['VBR_frames'])) { + $framebytelength = FreeFormatFrameLength($fd, $offset, $ThisFileInfo, true); + if ($framebytelength > 0) { + $ThisFileInfo['mpeg']['audio']['framelength'] = $framebytelength; + if ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { + // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12 + $ThisFileInfo['audio']['bitrate'] = ((($framebytelength / 4) - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 12; + } else { + // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144 + $ThisFileInfo['audio']['bitrate'] = (($framebytelength - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 144; + } + } else { + $ThisFileInfo['error'] .= "\n".'Error calculating frame length of free-format MP3 without Xing/LAME header'; + } + } + } + + if (($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') && isset($ThisFileInfo['mpeg']['audio']['VBR_frames']) && ($ThisFileInfo['mpeg']['audio']['VBR_frames'] > 1)) { + $ThisFileInfo['mpeg']['audio']['VBR_frames']--; // don't count the Xing / VBRI frame + if (($ThisFileInfo['mpeg']['audio']['version'] == '1') && ($ThisFileInfo['mpeg']['audio']['layer'] == 'I')) { + $ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 384)) / 1000; + } elseif ((($ThisFileInfo['mpeg']['audio']['version'] == '2') || ($ThisFileInfo['mpeg']['audio']['version'] == '2.5')) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'III')) { + $ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 576)) / 1000; + } else { + $ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 1152)) / 1000; + } + if ($ThisFileInfo['mpeg']['audio']['VBR_bitrate'] > 0) { + $ThisFileInfo['audio']['bitrate'] = 1000 * $ThisFileInfo['mpeg']['audio']['VBR_bitrate']; + $ThisFileInfo['mpeg']['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['VBR_bitrate']; // to avoid confusion + } + } + + // End variable-bitrate headers + //////////////////////////////////////////////////////////////////////////////////// + + if ($recursivesearch) { + if (!RecursiveFrameScanning($fd, $ThisFileInfo, $offset, $nextframetestoffset, $ScanAsCBR)) { + return false; + } + } + + + //if (false) { + // // experimental side info parsing section - not returning anything useful yet + // + // $SideInfoBitstream = BigEndian2Bin($SideInfoData); + // $SideInfoOffset = 0; + // + // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { + // if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { + // // MPEG-1 (mono) + // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9); + // $SideInfoOffset += 9; + // $SideInfoOffset += 5; + // } else { + // // MPEG-1 (stereo, joint-stereo, dual-channel) + // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9); + // $SideInfoOffset += 9; + // $SideInfoOffset += 3; + // } + // } else { // 2 or 2.5 + // if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') { + // // MPEG-2, MPEG-2.5 (mono) + // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8); + // $SideInfoOffset += 8; + // $SideInfoOffset += 1; + // } else { + // // MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel) + // $ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8); + // $SideInfoOffset += 8; + // $SideInfoOffset += 2; + // } + // } + // + // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { + // for ($channel = 0; $channel < $ThisFileInfo['audio']['channels']; $channel++) { + // for ($scfsi_band = 0; $scfsi_band < 4; $scfsi_band++) { + // $ThisFileInfo['mpeg']['audio']['scfsi'][$channel][$scfsi_band] = substr($SideInfoBitstream, $SideInfoOffset, 1); + // $SideInfoOffset += 2; + // } + // } + // } + // for ($granule = 0; $granule < (($ThisFileInfo['mpeg']['audio']['version'] == '1') ? 2 : 1); $granule++) { + // for ($channel = 0; $channel < $ThisFileInfo['audio']['channels']; $channel++) { + // $ThisFileInfo['mpeg']['audio']['part2_3_length'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 12); + // $SideInfoOffset += 12; + // $ThisFileInfo['mpeg']['audio']['big_values'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9); + // $SideInfoOffset += 9; + // $ThisFileInfo['mpeg']['audio']['global_gain'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 8); + // $SideInfoOffset += 8; + // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { + // $ThisFileInfo['mpeg']['audio']['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4); + // $SideInfoOffset += 4; + // } else { + // $ThisFileInfo['mpeg']['audio']['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9); + // $SideInfoOffset += 9; + // } + // $ThisFileInfo['mpeg']['audio']['window_switching_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); + // $SideInfoOffset += 1; + // + // if ($ThisFileInfo['mpeg']['audio']['window_switching_flag'][$granule][$channel] == '1') { + // + // $ThisFileInfo['mpeg']['audio']['block_type'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 2); + // $SideInfoOffset += 2; + // $ThisFileInfo['mpeg']['audio']['mixed_block_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); + // $SideInfoOffset += 1; + // + // for ($region = 0; $region < 2; $region++) { + // $ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5); + // $SideInfoOffset += 5; + // } + // $ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][2] = 0; + // + // for ($window = 0; $window < 3; $window++) { + // $ThisFileInfo['mpeg']['audio']['subblock_gain'][$granule][$channel][$window] = substr($SideInfoBitstream, $SideInfoOffset, 3); + // $SideInfoOffset += 3; + // } + // + // } else { + // + // for ($region = 0; $region < 3; $region++) { + // $ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5); + // $SideInfoOffset += 5; + // } + // + // $ThisFileInfo['mpeg']['audio']['region0_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4); + // $SideInfoOffset += 4; + // $ThisFileInfo['mpeg']['audio']['region1_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 3); + // $SideInfoOffset += 3; + // $ThisFileInfo['mpeg']['audio']['block_type'][$granule][$channel] = 0; + // } + // + // if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { + // $ThisFileInfo['mpeg']['audio']['preflag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); + // $SideInfoOffset += 1; + // } + // $ThisFileInfo['mpeg']['audio']['scalefac_scale'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); + // $SideInfoOffset += 1; + // $ThisFileInfo['mpeg']['audio']['count1table_select'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); + // $SideInfoOffset += 1; + // } + // } + //} + + return true; } -function RecursiveFrameScanning(&$fd, &$ThisFileInfo, &$offset, &$nextframetestoffset, $ScanAsCBR) { - for ($i = 0; $i < MPEG_VALID_CHECK_FRAMES; $i++) { - // check next MPEG_VALID_CHECK_FRAMES frames for validity, to make sure we haven't run across a false synch - if (($nextframetestoffset + 4) >= $ThisFileInfo['avdataend']) { - // end of file - return true; - } +function RecursiveFrameScanning(&$fd, &$ThisFileInfo, &$offset, &$nextframetestoffset, $ScanAsCBR) +{ + for ($i = 0; $i < MPEG_VALID_CHECK_FRAMES; $i++) { + // check next MPEG_VALID_CHECK_FRAMES frames for validity, to make sure we haven't run across a false synch + if (($nextframetestoffset + 4) >= $ThisFileInfo['avdataend']) { + // end of file + return true; + } - $nextframetestarray = array('error'=>'', 'warning'=>'', 'avdataend'=>$ThisFileInfo['avdataend'], 'avdataoffset'=>$ThisFileInfo['avdataoffset']); - if (decodeMPEGaudioHeader($fd, $nextframetestoffset, $nextframetestarray, false)) { - if ($ScanAsCBR) { - // force CBR mode, used for trying to pick out invalid audio streams with - // valid(?) VBR headers, or VBR streams with no VBR header - if (!isset($nextframetestarray['mpeg']['audio']['bitrate']) || !isset($ThisFileInfo['mpeg']['audio']['bitrate']) || ($nextframetestarray['mpeg']['audio']['bitrate'] != $ThisFileInfo['mpeg']['audio']['bitrate'])) { - return false; - } - } + $nextframetestarray = ['error'=>'', 'warning'=>'', 'avdataend'=>$ThisFileInfo['avdataend'], 'avdataoffset'=>$ThisFileInfo['avdataoffset']]; + if (decodeMPEGaudioHeader($fd, $nextframetestoffset, $nextframetestarray, false)) { + if ($ScanAsCBR) { + // force CBR mode, used for trying to pick out invalid audio streams with + // valid(?) VBR headers, or VBR streams with no VBR header + if (!isset($nextframetestarray['mpeg']['audio']['bitrate']) || !isset($ThisFileInfo['mpeg']['audio']['bitrate']) || ($nextframetestarray['mpeg']['audio']['bitrate'] != $ThisFileInfo['mpeg']['audio']['bitrate'])) { + return false; + } + } - // next frame is OK, get ready to check the one after that - if (isset($nextframetestarray['mpeg']['audio']['framelength']) && ($nextframetestarray['mpeg']['audio']['framelength'] > 0)) { - $nextframetestoffset += $nextframetestarray['mpeg']['audio']['framelength']; - } else { - $ThisFileInfo['error'] .= "\n".'Frame at offset ('.$offset.') is has an invalid frame length.'; - return false; - } + // next frame is OK, get ready to check the one after that + if (isset($nextframetestarray['mpeg']['audio']['framelength']) && ($nextframetestarray['mpeg']['audio']['framelength'] > 0)) { + $nextframetestoffset += $nextframetestarray['mpeg']['audio']['framelength']; + } else { + $ThisFileInfo['error'] .= "\n".'Frame at offset ('.$offset.') is has an invalid frame length.'; + return false; + } + } else { + // next frame is not valid, note the error and fail, so scanning can contiue for a valid frame sequence + $ThisFileInfo['error'] .= "\n".'Frame at offset ('.$offset.') is valid, but the next one at ('.$nextframetestoffset.') is not.'; - } else { - - // next frame is not valid, note the error and fail, so scanning can contiue for a valid frame sequence - $ThisFileInfo['error'] .= "\n".'Frame at offset ('.$offset.') is valid, but the next one at ('.$nextframetestoffset.') is not.'; - - return false; - } - } - return true; + return false; + } + } + return true; } -function FreeFormatFrameLength($fd, $offset, &$ThisFileInfo, $deepscan=false) { - fseek($fd, $offset, SEEK_SET); - $MPEGaudioData = fread($fd, 32768); +function FreeFormatFrameLength($fd, $offset, &$ThisFileInfo, $deepscan = false) +{ + fseek($fd, $offset, SEEK_SET); + $MPEGaudioData = fread($fd, 32768); - $SyncPattern1 = substr($MPEGaudioData, 0, 4); - // may be different pattern due to padding - $SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) | 0x02).$SyncPattern1{3}; - if ($SyncPattern2 === $SyncPattern1) { - $SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) & 0xFD).$SyncPattern1{3}; - } + $SyncPattern1 = substr($MPEGaudioData, 0, 4); + // may be different pattern due to padding + $SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) | 0x02).$SyncPattern1{3}; + if ($SyncPattern2 === $SyncPattern1) { + $SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) & 0xFD).$SyncPattern1{3}; + } - $framelength = false; - $framelength1 = strpos($MPEGaudioData, $SyncPattern1, 4); - $framelength2 = strpos($MPEGaudioData, $SyncPattern2, 4); - if ($framelength1 > 4) { - $framelength = $framelength1; - } - if (($framelength2 > 4) && ($framelength2 < $framelength1)) { - $framelength = $framelength2; - } - if (!$framelength) { + $framelength = false; + $framelength1 = strpos($MPEGaudioData, $SyncPattern1, 4); + $framelength2 = strpos($MPEGaudioData, $SyncPattern2, 4); + if ($framelength1 > 4) { + $framelength = $framelength1; + } + if (($framelength2 > 4) && ($framelength2 < $framelength1)) { + $framelength = $framelength2; + } + if (!$framelength) { + // LAME 3.88 has a different value for modeextension on the first frame vs the rest + $framelength1 = strpos($MPEGaudioData, substr($SyncPattern1, 0, 3), 4); + $framelength2 = strpos($MPEGaudioData, substr($SyncPattern2, 0, 3), 4); - // LAME 3.88 has a different value for modeextension on the first frame vs the rest - $framelength1 = strpos($MPEGaudioData, substr($SyncPattern1, 0, 3), 4); - $framelength2 = strpos($MPEGaudioData, substr($SyncPattern2, 0, 3), 4); + if ($framelength1 > 4) { + $framelength = $framelength1; + } + if (($framelength2 > 4) && ($framelength2 < $framelength1)) { + $framelength = $framelength2; + } + if (!$framelength) { + $ThisFileInfo['error'] .= "\n".'Cannot find next free-format synch pattern ('.PrintHexBytes($SyncPattern1).' or '.PrintHexBytes($SyncPattern2).') after offset '.$offset; + return false; + } else { + $ThisFileInfo['warning'] .= "\n".'ModeExtension varies between first frame and other frames (known free-format issue in LAME 3.88)'; + $ThisFileInfo['audio']['codec'] = 'LAME'; + $ThisFileInfo['audio']['encoder'] = 'LAME3.88'; + $SyncPattern1 = substr($SyncPattern1, 0, 3); + $SyncPattern2 = substr($SyncPattern2, 0, 3); + } + } - if ($framelength1 > 4) { - $framelength = $framelength1; - } - if (($framelength2 > 4) && ($framelength2 < $framelength1)) { - $framelength = $framelength2; - } - if (!$framelength) { - $ThisFileInfo['error'] .= "\n".'Cannot find next free-format synch pattern ('.PrintHexBytes($SyncPattern1).' or '.PrintHexBytes($SyncPattern2).') after offset '.$offset; - return false; - } else { - $ThisFileInfo['warning'] .= "\n".'ModeExtension varies between first frame and other frames (known free-format issue in LAME 3.88)'; - $ThisFileInfo['audio']['codec'] = 'LAME'; - $ThisFileInfo['audio']['encoder'] = 'LAME3.88'; - $SyncPattern1 = substr($SyncPattern1, 0, 3); - $SyncPattern2 = substr($SyncPattern2, 0, 3); - } - } - - if ($deepscan) { - - $ActualFrameLengthValues = array(); - $nextoffset = $offset + $framelength; - while ($nextoffset < ($ThisFileInfo['avdataend'] - 6)) { - fseek($fd, $nextoffset - 1, SEEK_SET); - $NextSyncPattern = fread($fd, 6); - if ((substr($NextSyncPattern, 1, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 1, strlen($SyncPattern2)) == $SyncPattern2)) { - // good - found where expected - $ActualFrameLengthValues[] = $framelength; - } elseif ((substr($NextSyncPattern, 0, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 0, strlen($SyncPattern2)) == $SyncPattern2)) { - // ok - found one byte earlier than expected (last frame wasn't padded, first frame was) - $ActualFrameLengthValues[] = ($framelength - 1); - $nextoffset--; - } elseif ((substr($NextSyncPattern, 2, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 2, strlen($SyncPattern2)) == $SyncPattern2)) { - // ok - found one byte later than expected (last frame was padded, first frame wasn't) - $ActualFrameLengthValues[] = ($framelength + 1); - $nextoffset++; - } else { - $ThisFileInfo['error'] .= "\n".'Did not find expected free-format sync pattern at offset '.$nextoffset; - return false; - } - $nextoffset += $framelength; - } - if (count($ActualFrameLengthValues) > 0) { - $framelength = round(array_sum($ActualFrameLengthValues) / count($ActualFrameLengthValues)); - } - } - return $framelength; + if ($deepscan) { + $ActualFrameLengthValues = []; + $nextoffset = $offset + $framelength; + while ($nextoffset < ($ThisFileInfo['avdataend'] - 6)) { + fseek($fd, $nextoffset - 1, SEEK_SET); + $NextSyncPattern = fread($fd, 6); + if ((substr($NextSyncPattern, 1, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 1, strlen($SyncPattern2)) == $SyncPattern2)) { + // good - found where expected + $ActualFrameLengthValues[] = $framelength; + } elseif ((substr($NextSyncPattern, 0, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 0, strlen($SyncPattern2)) == $SyncPattern2)) { + // ok - found one byte earlier than expected (last frame wasn't padded, first frame was) + $ActualFrameLengthValues[] = ($framelength - 1); + $nextoffset--; + } elseif ((substr($NextSyncPattern, 2, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 2, strlen($SyncPattern2)) == $SyncPattern2)) { + // ok - found one byte later than expected (last frame was padded, first frame wasn't) + $ActualFrameLengthValues[] = ($framelength + 1); + $nextoffset++; + } else { + $ThisFileInfo['error'] .= "\n".'Did not find expected free-format sync pattern at offset '.$nextoffset; + return false; + } + $nextoffset += $framelength; + } + if (count($ActualFrameLengthValues) > 0) { + $framelength = round(array_sum($ActualFrameLengthValues) / count($ActualFrameLengthValues)); + } + } + return $framelength; } -function getOnlyMPEGaudioInfo($fd, &$ThisFileInfo, $avdataoffset, $BitrateHistogram=false) { - // looks for synch, decodes MPEG audio header +function getOnlyMPEGaudioInfo($fd, &$ThisFileInfo, $avdataoffset, $BitrateHistogram = false) +{ + // looks for synch, decodes MPEG audio header - fseek($fd, $avdataoffset, SEEK_SET); - $header = ''; - $SynchSeekOffset = 0; + fseek($fd, $avdataoffset, SEEK_SET); + $header = ''; + $SynchSeekOffset = 0; - if (!defined('CONST_FF')) { - define('CONST_FF', chr(0xFF)); - define('CONST_E0', chr(0xE0)); - } + if (!defined('CONST_FF')) { + define('CONST_FF', chr(0xFF)); + define('CONST_E0', chr(0xE0)); + } - static $MPEGaudioVersionLookup; - static $MPEGaudioLayerLookup; - static $MPEGaudioBitrateLookup; - if (empty($MPEGaudioVersionLookup)) { - $MPEGaudioVersionLookup = MPEGaudioVersionArray(); - $MPEGaudioLayerLookup = MPEGaudioLayerArray(); - $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); + static $MPEGaudioVersionLookup; + static $MPEGaudioLayerLookup; + static $MPEGaudioBitrateLookup; + if (empty($MPEGaudioVersionLookup)) { + $MPEGaudioVersionLookup = MPEGaudioVersionArray(); + $MPEGaudioLayerLookup = MPEGaudioLayerArray(); + $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); + } - } + $header_len = strlen($header) - round(32768 / 2); + while (true) { + if (($SynchSeekOffset > $header_len) && (($avdataoffset + $SynchSeekOffset) < $ThisFileInfo['avdataend']) && !feof($fd)) { + if ($SynchSeekOffset > 131072) { + // if a synch's not found within the first 128k bytes, then give up + $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch within the first 131072 bytes'; + if (isset($ThisFileInfo['audio']['bitrate'])) { + unset($ThisFileInfo['audio']['bitrate']); + } + if (isset($ThisFileInfo['mpeg']['audio'])) { + unset($ThisFileInfo['mpeg']['audio']); + } + if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || (count($ThisFileInfo['mpeg']) == 0))) { + unset($ThisFileInfo['mpeg']); + } + return false; + } elseif ($header .= fread($fd, 32768)) { + // great + $header_len = strlen($header) - round(32768 / 2); + } else { + $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file'; + if (isset($ThisFileInfo['audio']['bitrate'])) { + unset($ThisFileInfo['audio']['bitrate']); + } + if (isset($ThisFileInfo['mpeg']['audio'])) { + unset($ThisFileInfo['mpeg']['audio']); + } + if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || (count($ThisFileInfo['mpeg']) == 0))) { + unset($ThisFileInfo['mpeg']); + } + return false; + } + } - $header_len = strlen($header) - round(32768 / 2); - while (true) { + if (($SynchSeekOffset + 1) >= strlen($header)) { + $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file'; + return false; + } - if (($SynchSeekOffset > $header_len) && (($avdataoffset + $SynchSeekOffset) < $ThisFileInfo['avdataend']) && !feof($fd)) { + if (($header{$SynchSeekOffset} == CONST_FF) && ($header{($SynchSeekOffset + 1)} > CONST_E0)) { // synch detected - if ($SynchSeekOffset > 131072) { - // if a synch's not found within the first 128k bytes, then give up - $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch within the first 131072 bytes'; - if (isset($ThisFileInfo['audio']['bitrate'])) { - unset($ThisFileInfo['audio']['bitrate']); - } - if (isset($ThisFileInfo['mpeg']['audio'])) { - unset($ThisFileInfo['mpeg']['audio']); - } - if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || (count($ThisFileInfo['mpeg']) == 0))) { - unset($ThisFileInfo['mpeg']); - } - return false; + if (!isset($FirstFrameThisfileInfo) && !isset($ThisFileInfo['mpeg']['audio'])) { + $FirstFrameThisfileInfo = $ThisFileInfo; + $FirstFrameAVDataOffset = $avdataoffset + $SynchSeekOffset; + if (!decodeMPEGaudioHeader($fd, $avdataoffset + $SynchSeekOffset, $FirstFrameThisfileInfo, false)) { + // if this is the first valid MPEG-audio frame, save it in case it's a VBR header frame and there's + // garbage between this frame and a valid sequence of MPEG-audio frames, to be restored below + unset($FirstFrameThisfileInfo); + } + } + $dummy = $ThisFileInfo; // only overwrite real data if valid header found - } elseif ($header .= fread($fd, 32768)) { + if (decodeMPEGaudioHeader($fd, $avdataoffset + $SynchSeekOffset, $dummy, true)) { + $ThisFileInfo = $dummy; + $ThisFileInfo['avdataoffset'] = $avdataoffset + $SynchSeekOffset; + switch ($ThisFileInfo['fileformat']) { + case '': + case 'id3': + case 'ape': + case 'mp3': + $ThisFileInfo['fileformat'] = 'mp3'; + $ThisFileInfo['audio']['dataformat'] = 'mp3'; + } + if (isset($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode']) && ($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr')) { + if (!CloseMatch($ThisFileInfo['audio']['bitrate'], $FirstFrameThisfileInfo['audio']['bitrate'], 1)) { + // If there is garbage data between a valid VBR header frame and a sequence + // of valid MPEG-audio frames the VBR data is no longer discarded. + $ThisFileInfo = $FirstFrameThisfileInfo; + $ThisFileInfo['avdataoffset'] = $FirstFrameAVDataOffset; + $ThisFileInfo['fileformat'] = 'mp3'; + $ThisFileInfo['audio']['dataformat'] = 'mp3'; + $dummy = $ThisFileInfo; + unset($dummy['mpeg']['audio']); + $GarbageOffsetStart = $FirstFrameAVDataOffset + $FirstFrameThisfileInfo['mpeg']['audio']['framelength']; + $GarbageOffsetEnd = $avdataoffset + $SynchSeekOffset; + if (decodeMPEGaudioHeader($fd, $GarbageOffsetEnd, $dummy, true, true)) { + $ThisFileInfo = $dummy; + $ThisFileInfo['avdataoffset'] = $GarbageOffsetEnd; + $ThisFileInfo['warning'] .= "\n".'apparently-valid VBR header not used because could not find '.MPEG_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.'), but did find valid CBR stream starting at '.$GarbageOffsetEnd; + } else { + $ThisFileInfo['warning'] .= "\n".'using data from VBR header even though could not find '.MPEG_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.')'; + } + } + } - // great - $header_len = strlen($header) - round(32768 / 2); + if (isset($ThisFileInfo['mpeg']['audio']['bitrate_mode']) && ($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') && !isset($ThisFileInfo['mpeg']['audio']['VBR_method'])) { + // VBR file with no VBR header + $BitrateHistogram = true; + } - } else { + if ($BitrateHistogram) { + $ThisFileInfo['mpeg']['audio']['stereo_distribution'] = ['stereo'=>0, 'joint stereo'=>0, 'dual channel'=>0, 'mono'=>0]; + $ThisFileInfo['mpeg']['audio']['version_distribution'] = ['1'=>0, '2'=>0, '2.5'=>0]; - $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file'; - if (isset($ThisFileInfo['audio']['bitrate'])) { - unset($ThisFileInfo['audio']['bitrate']); - } - if (isset($ThisFileInfo['mpeg']['audio'])) { - unset($ThisFileInfo['mpeg']['audio']); - } - if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || (count($ThisFileInfo['mpeg']) == 0))) { - unset($ThisFileInfo['mpeg']); - } - return false; + if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { + if ($ThisFileInfo['mpeg']['audio']['layer'] == 'III') { + $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = ['free'=>0, 32=>0, 40=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 320=>0]; + } elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'II') { + $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = ['free'=>0, 32=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 320=>0, 384=>0]; + } elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { + $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = ['free'=>0, 32=>0, 64=>0, 96=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 288=>0, 320=>0, 352=>0, 384=>0, 416=>0, 448=>0]; + } + } elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { + $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = ['free'=>0, 32=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 144=>0, 160=>0, 176=>0, 192=>0, 224=>0, 256=>0]; + } else { + $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = ['free'=>0, 8=>0, 16=>0, 24=>0, 32=>0, 40=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 144=>0, 160=>0]; + } - } - } + $dummy = ['error'=>$ThisFileInfo['error'], 'warning'=>$ThisFileInfo['warning'], 'avdataend'=>$ThisFileInfo['avdataend'], 'avdataoffset'=>$ThisFileInfo['avdataoffset']]; + $synchstartoffset = $ThisFileInfo['avdataoffset']; - if (($SynchSeekOffset + 1) >= strlen($header)) { - $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file'; - return false; - } + $FastMode = false; + while (decodeMPEGaudioHeader($fd, $synchstartoffset, $dummy, false, false, $FastMode)) { + $FastMode = true; + $thisframebitrate = $MPEGaudioBitrateLookup[$MPEGaudioVersionLookup[$dummy['mpeg']['audio']['raw']['version']]][$MPEGaudioLayerLookup[$dummy['mpeg']['audio']['raw']['layer']]][$dummy['mpeg']['audio']['raw']['bitrate']]; - if (($header{$SynchSeekOffset} == CONST_FF) && ($header{($SynchSeekOffset + 1)} > CONST_E0)) { // synch detected - - if (!isset($FirstFrameThisfileInfo) && !isset($ThisFileInfo['mpeg']['audio'])) { - $FirstFrameThisfileInfo = $ThisFileInfo; - $FirstFrameAVDataOffset = $avdataoffset + $SynchSeekOffset; - if (!decodeMPEGaudioHeader($fd, $avdataoffset + $SynchSeekOffset, $FirstFrameThisfileInfo, false)) { - // if this is the first valid MPEG-audio frame, save it in case it's a VBR header frame and there's - // garbage between this frame and a valid sequence of MPEG-audio frames, to be restored below - unset($FirstFrameThisfileInfo); - } - } - $dummy = $ThisFileInfo; // only overwrite real data if valid header found - - if (decodeMPEGaudioHeader($fd, $avdataoffset + $SynchSeekOffset, $dummy, true)) { - - $ThisFileInfo = $dummy; - $ThisFileInfo['avdataoffset'] = $avdataoffset + $SynchSeekOffset; - switch ($ThisFileInfo['fileformat']) { - case '': - case 'id3': - case 'ape': - case 'mp3': - $ThisFileInfo['fileformat'] = 'mp3'; - $ThisFileInfo['audio']['dataformat'] = 'mp3'; - } - if (isset($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode']) && ($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr')) { - if (!CloseMatch($ThisFileInfo['audio']['bitrate'], $FirstFrameThisfileInfo['audio']['bitrate'], 1)) { - // If there is garbage data between a valid VBR header frame and a sequence - // of valid MPEG-audio frames the VBR data is no longer discarded. - $ThisFileInfo = $FirstFrameThisfileInfo; - $ThisFileInfo['avdataoffset'] = $FirstFrameAVDataOffset; - $ThisFileInfo['fileformat'] = 'mp3'; - $ThisFileInfo['audio']['dataformat'] = 'mp3'; - $dummy = $ThisFileInfo; - unset($dummy['mpeg']['audio']); - $GarbageOffsetStart = $FirstFrameAVDataOffset + $FirstFrameThisfileInfo['mpeg']['audio']['framelength']; - $GarbageOffsetEnd = $avdataoffset + $SynchSeekOffset; - if (decodeMPEGaudioHeader($fd, $GarbageOffsetEnd, $dummy, true, true)) { - - $ThisFileInfo = $dummy; - $ThisFileInfo['avdataoffset'] = $GarbageOffsetEnd; - $ThisFileInfo['warning'] .= "\n".'apparently-valid VBR header not used because could not find '.MPEG_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.'), but did find valid CBR stream starting at '.$GarbageOffsetEnd; - - } else { - - $ThisFileInfo['warning'] .= "\n".'using data from VBR header even though could not find '.MPEG_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.')'; - - } - } - } - - if (isset($ThisFileInfo['mpeg']['audio']['bitrate_mode']) && ($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') && !isset($ThisFileInfo['mpeg']['audio']['VBR_method'])) { - // VBR file with no VBR header - $BitrateHistogram = true; - } - - if ($BitrateHistogram) { - - $ThisFileInfo['mpeg']['audio']['stereo_distribution'] = array('stereo'=>0, 'joint stereo'=>0, 'dual channel'=>0, 'mono'=>0); - $ThisFileInfo['mpeg']['audio']['version_distribution'] = array('1'=>0, '2'=>0, '2.5'=>0); - - if ($ThisFileInfo['mpeg']['audio']['version'] == '1') { - if ($ThisFileInfo['mpeg']['audio']['layer'] == 'III') { - $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 40=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 320=>0); - } elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'II') { - $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 320=>0, 384=>0); - } elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { - $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 64=>0, 96=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 288=>0, 320=>0, 352=>0, 384=>0, 416=>0, 448=>0); - } - } elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') { - $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 144=>0, 160=>0, 176=>0, 192=>0, 224=>0, 256=>0); - } else { - $ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 8=>0, 16=>0, 24=>0, 32=>0, 40=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 144=>0, 160=>0); - } - - $dummy = array('error'=>$ThisFileInfo['error'], 'warning'=>$ThisFileInfo['warning'], 'avdataend'=>$ThisFileInfo['avdataend'], 'avdataoffset'=>$ThisFileInfo['avdataoffset']); - $synchstartoffset = $ThisFileInfo['avdataoffset']; - - $FastMode = false; - while (decodeMPEGaudioHeader($fd, $synchstartoffset, $dummy, false, false, $FastMode)) { - $FastMode = true; - $thisframebitrate = $MPEGaudioBitrateLookup[$MPEGaudioVersionLookup[$dummy['mpeg']['audio']['raw']['version']]][$MPEGaudioLayerLookup[$dummy['mpeg']['audio']['raw']['layer']]][$dummy['mpeg']['audio']['raw']['bitrate']]; - - $ThisFileInfo['mpeg']['audio']['bitrate_distribution'][$thisframebitrate]++; - $ThisFileInfo['mpeg']['audio']['stereo_distribution'][$dummy['mpeg']['audio']['channelmode']]++; - $ThisFileInfo['mpeg']['audio']['version_distribution'][$dummy['mpeg']['audio']['version']]++; - if (empty($dummy['mpeg']['audio']['framelength'])) { - $ThisFileInfo['warning'] .= "\n".'Invalid/missing framelength in histogram analysis - aborting'; -$synchstartoffset += 4; + $ThisFileInfo['mpeg']['audio']['bitrate_distribution'][$thisframebitrate]++; + $ThisFileInfo['mpeg']['audio']['stereo_distribution'][$dummy['mpeg']['audio']['channelmode']]++; + $ThisFileInfo['mpeg']['audio']['version_distribution'][$dummy['mpeg']['audio']['version']]++; + if (empty($dummy['mpeg']['audio']['framelength'])) { + $ThisFileInfo['warning'] .= "\n".'Invalid/missing framelength in histogram analysis - aborting'; + $synchstartoffset += 4; // return false; - } - $synchstartoffset += $dummy['mpeg']['audio']['framelength']; - } + } + $synchstartoffset += $dummy['mpeg']['audio']['framelength']; + } - $bittotal = 0; - $framecounter = 0; - foreach ($ThisFileInfo['mpeg']['audio']['bitrate_distribution'] as $bitratevalue => $bitratecount) { - $framecounter += $bitratecount; - if ($bitratevalue != 'free') { - $bittotal += ($bitratevalue * $bitratecount); - } - } - if ($framecounter == 0) { - $ThisFileInfo['error'] .= "\n".'Corrupt MP3 file: framecounter == zero'; - return false; - } - $ThisFileInfo['mpeg']['audio']['frame_count'] = $framecounter; - $ThisFileInfo['mpeg']['audio']['bitrate'] = 1000 * ($bittotal / $framecounter); + $bittotal = 0; + $framecounter = 0; + foreach ($ThisFileInfo['mpeg']['audio']['bitrate_distribution'] as $bitratevalue => $bitratecount) { + $framecounter += $bitratecount; + if ($bitratevalue != 'free') { + $bittotal += ($bitratevalue * $bitratecount); + } + } + if ($framecounter == 0) { + $ThisFileInfo['error'] .= "\n".'Corrupt MP3 file: framecounter == zero'; + return false; + } + $ThisFileInfo['mpeg']['audio']['frame_count'] = $framecounter; + $ThisFileInfo['mpeg']['audio']['bitrate'] = 1000 * ($bittotal / $framecounter); - $ThisFileInfo['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['bitrate']; + $ThisFileInfo['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['bitrate']; - // Definitively set VBR vs CBR, even if the Xing/LAME/VBRI header says differently - $distinct_bitrates = 0; - foreach ($ThisFileInfo['mpeg']['audio']['bitrate_distribution'] as $bitrate_value => $bitrate_count) { - if ($bitrate_count > 0) { - $distinct_bitrates++; - } - } - if ($distinct_bitrates > 1) { - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; - } else { - $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; - } - $ThisFileInfo['audio']['bitrate_mode'] = $ThisFileInfo['mpeg']['audio']['bitrate_mode']; + // Definitively set VBR vs CBR, even if the Xing/LAME/VBRI header says differently + $distinct_bitrates = 0; + foreach ($ThisFileInfo['mpeg']['audio']['bitrate_distribution'] as $bitrate_value => $bitrate_count) { + if ($bitrate_count > 0) { + $distinct_bitrates++; + } + } + if ($distinct_bitrates > 1) { + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr'; + } else { + $ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr'; + } + $ThisFileInfo['audio']['bitrate_mode'] = $ThisFileInfo['mpeg']['audio']['bitrate_mode']; + } - } + break; // exit while() + } + } - break; // exit while() - } - } + $SynchSeekOffset++; + if (($avdataoffset + $SynchSeekOffset) >= $ThisFileInfo['avdataend']) { + // end of file/data - $SynchSeekOffset++; - if (($avdataoffset + $SynchSeekOffset) >= $ThisFileInfo['avdataend']) { - // end of file/data - - if (empty($ThisFileInfo['mpeg']['audio'])) { - - $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file'; - if (isset($ThisFileInfo['audio']['bitrate'])) { - unset($ThisFileInfo['audio']['bitrate']); - } - if (isset($ThisFileInfo['mpeg']['audio'])) { - unset($ThisFileInfo['mpeg']['audio']); - } - if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || empty($ThisFileInfo['mpeg']))) { - unset($ThisFileInfo['mpeg']); - } - return false; - - } - break; - } - - } - $ThisFileInfo['audio']['bits_per_sample'] = 16; - $ThisFileInfo['audio']['channels'] = $ThisFileInfo['mpeg']['audio']['channels']; - $ThisFileInfo['audio']['channelmode'] = $ThisFileInfo['mpeg']['audio']['channelmode']; - $ThisFileInfo['audio']['sample_rate'] = $ThisFileInfo['mpeg']['audio']['sample_rate']; - return true; + if (empty($ThisFileInfo['mpeg']['audio'])) { + $ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file'; + if (isset($ThisFileInfo['audio']['bitrate'])) { + unset($ThisFileInfo['audio']['bitrate']); + } + if (isset($ThisFileInfo['mpeg']['audio'])) { + unset($ThisFileInfo['mpeg']['audio']); + } + if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || empty($ThisFileInfo['mpeg']))) { + unset($ThisFileInfo['mpeg']); + } + return false; + } + break; + } + } + $ThisFileInfo['audio']['bits_per_sample'] = 16; + $ThisFileInfo['audio']['channels'] = $ThisFileInfo['mpeg']['audio']['channels']; + $ThisFileInfo['audio']['channelmode'] = $ThisFileInfo['mpeg']['audio']['channelmode']; + $ThisFileInfo['audio']['sample_rate'] = $ThisFileInfo['mpeg']['audio']['sample_rate']; + return true; } -function MPEGaudioVersionArray() { - static $MPEGaudioVersion = array('2.5', false, '2', '1'); - return $MPEGaudioVersion; +function MPEGaudioVersionArray() +{ + static $MPEGaudioVersion = ['2.5', false, '2', '1']; + return $MPEGaudioVersion; } -function MPEGaudioLayerArray() { - static $MPEGaudioLayer = array(false, 'III', 'II', 'I'); - return $MPEGaudioLayer; +function MPEGaudioLayerArray() +{ + static $MPEGaudioLayer = [false, 'III', 'II', 'I']; + return $MPEGaudioLayer; } -function MPEGaudioBitrateArray() { - static $MPEGaudioBitrate; - if (empty($MPEGaudioBitrate)) { - $MPEGaudioBitrate['1']['I'] = array('free', 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448); - $MPEGaudioBitrate['1']['II'] = array('free', 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384); - $MPEGaudioBitrate['1']['III'] = array('free', 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320); - $MPEGaudioBitrate['2']['I'] = array('free', 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256); - $MPEGaudioBitrate['2']['II'] = array('free', 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160); - $MPEGaudioBitrate['2']['III'] = $MPEGaudioBitrate['2']['II']; - $MPEGaudioBitrate['2.5']['I'] = $MPEGaudioBitrate['2']['I']; - $MPEGaudioBitrate['2.5']['II'] = $MPEGaudioBitrate['2']['II']; - $MPEGaudioBitrate['2.5']['III'] = $MPEGaudioBitrate['2']['III']; - } - return $MPEGaudioBitrate; +function MPEGaudioBitrateArray() +{ + static $MPEGaudioBitrate; + if (empty($MPEGaudioBitrate)) { + $MPEGaudioBitrate['1']['I'] = ['free', 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448]; + $MPEGaudioBitrate['1']['II'] = ['free', 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384]; + $MPEGaudioBitrate['1']['III'] = ['free', 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]; + $MPEGaudioBitrate['2']['I'] = ['free', 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256]; + $MPEGaudioBitrate['2']['II'] = ['free', 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; + $MPEGaudioBitrate['2']['III'] = $MPEGaudioBitrate['2']['II']; + $MPEGaudioBitrate['2.5']['I'] = $MPEGaudioBitrate['2']['I']; + $MPEGaudioBitrate['2.5']['II'] = $MPEGaudioBitrate['2']['II']; + $MPEGaudioBitrate['2.5']['III'] = $MPEGaudioBitrate['2']['III']; + } + return $MPEGaudioBitrate; } -function MPEGaudioFrequencyArray() { - static $MPEGaudioFrequency; - if (empty($MPEGaudioFrequency)) { - $MPEGaudioFrequency['1'] = array(44100, 48000, 32000); - $MPEGaudioFrequency['2'] = array(22050, 24000, 16000); - $MPEGaudioFrequency['2.5'] = array(11025, 12000, 8000); - } - return $MPEGaudioFrequency; +function MPEGaudioFrequencyArray() +{ + static $MPEGaudioFrequency; + if (empty($MPEGaudioFrequency)) { + $MPEGaudioFrequency['1'] = [44100, 48000, 32000]; + $MPEGaudioFrequency['2'] = [22050, 24000, 16000]; + $MPEGaudioFrequency['2.5'] = [11025, 12000, 8000]; + } + return $MPEGaudioFrequency; } -function MPEGaudioChannelModeArray() { - static $MPEGaudioChannelMode = array('stereo', 'joint stereo', 'dual channel', 'mono'); - return $MPEGaudioChannelMode; +function MPEGaudioChannelModeArray() +{ + static $MPEGaudioChannelMode = ['stereo', 'joint stereo', 'dual channel', 'mono']; + return $MPEGaudioChannelMode; } -function MPEGaudioModeExtensionArray() { - static $MPEGaudioModeExtension; - if (empty($MPEGaudioModeExtension)) { - $MPEGaudioModeExtension['I'] = array('4-31', '8-31', '12-31', '16-31'); - $MPEGaudioModeExtension['II'] = array('4-31', '8-31', '12-31', '16-31'); - $MPEGaudioModeExtension['III'] = array('', 'IS', 'MS', 'IS+MS'); - } - return $MPEGaudioModeExtension; +function MPEGaudioModeExtensionArray() +{ + static $MPEGaudioModeExtension; + if (empty($MPEGaudioModeExtension)) { + $MPEGaudioModeExtension['I'] = ['4-31', '8-31', '12-31', '16-31']; + $MPEGaudioModeExtension['II'] = ['4-31', '8-31', '12-31', '16-31']; + $MPEGaudioModeExtension['III'] = ['', 'IS', 'MS', 'IS+MS']; + } + return $MPEGaudioModeExtension; } -function MPEGaudioEmphasisArray() { - static $MPEGaudioEmphasis = array('none', '50/15ms', false, 'CCIT J.17'); - return $MPEGaudioEmphasis; +function MPEGaudioEmphasisArray() +{ + static $MPEGaudioEmphasis = ['none', '50/15ms', false, 'CCIT J.17']; + return $MPEGaudioEmphasis; } -function MPEGaudioHeaderBytesValid($head4) { - return MPEGaudioHeaderValid(MPEGaudioHeaderDecode($head4)); +function MPEGaudioHeaderBytesValid($head4) +{ + return MPEGaudioHeaderValid(MPEGaudioHeaderDecode($head4)); } -function MPEGaudioHeaderValid($rawarray, $echoerrors=false) { +function MPEGaudioHeaderValid($rawarray, $echoerrors = false) +{ - if (($rawarray['synch'] & 0x0FFE) != 0x0FFE) { - return false; - } + if (($rawarray['synch'] & 0x0FFE) != 0x0FFE) { + return false; + } - static $MPEGaudioVersionLookup; - static $MPEGaudioLayerLookup; - static $MPEGaudioBitrateLookup; - static $MPEGaudioFrequencyLookup; - static $MPEGaudioChannelModeLookup; - static $MPEGaudioModeExtensionLookup; - static $MPEGaudioEmphasisLookup; - if (empty($MPEGaudioVersionLookup)) { - $MPEGaudioVersionLookup = MPEGaudioVersionArray(); - $MPEGaudioLayerLookup = MPEGaudioLayerArray(); - $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); - $MPEGaudioFrequencyLookup = MPEGaudioFrequencyArray(); - $MPEGaudioChannelModeLookup = MPEGaudioChannelModeArray(); - $MPEGaudioModeExtensionLookup = MPEGaudioModeExtensionArray(); - $MPEGaudioEmphasisLookup = MPEGaudioEmphasisArray(); - } + static $MPEGaudioVersionLookup; + static $MPEGaudioLayerLookup; + static $MPEGaudioBitrateLookup; + static $MPEGaudioFrequencyLookup; + static $MPEGaudioChannelModeLookup; + static $MPEGaudioModeExtensionLookup; + static $MPEGaudioEmphasisLookup; + if (empty($MPEGaudioVersionLookup)) { + $MPEGaudioVersionLookup = MPEGaudioVersionArray(); + $MPEGaudioLayerLookup = MPEGaudioLayerArray(); + $MPEGaudioBitrateLookup = MPEGaudioBitrateArray(); + $MPEGaudioFrequencyLookup = MPEGaudioFrequencyArray(); + $MPEGaudioChannelModeLookup = MPEGaudioChannelModeArray(); + $MPEGaudioModeExtensionLookup = MPEGaudioModeExtensionArray(); + $MPEGaudioEmphasisLookup = MPEGaudioEmphasisArray(); + } - if (isset($MPEGaudioVersionLookup[$rawarray['version']])) { - $decodedVersion = $MPEGaudioVersionLookup[$rawarray['version']]; - } else { - if ($echoerrors) { - echo "\n".'invalid Version ('.$rawarray['version'].')'; - } - return false; - } - if (isset($MPEGaudioLayerLookup[$rawarray['layer']])) { - $decodedLayer = $MPEGaudioLayerLookup[$rawarray['layer']]; - } else { - if ($echoerrors) { - echo "\n".'invalid Layer ('.$rawarray['layer'].')'; - } - return false; - } - if (!isset($MPEGaudioBitrateLookup[$decodedVersion][$decodedLayer][$rawarray['bitrate']])) { - if ($echoerrors) { - echo "\n".'invalid Bitrate ('.$rawarray['bitrate'].')'; - } - if ($rawarray['bitrate'] == 15) { - // known issue in LAME 3.90 - 3.93.1 where free-format has bitrate ID of 15 instead of 0 - // let it go through here otherwise file will not be identified - } else { - return false; - } - } - if (!isset($MPEGaudioFrequencyLookup[$decodedVersion][$rawarray['sample_rate']])) { - if ($echoerrors) { - echo "\n".'invalid Frequency ('.$rawarray['sample_rate'].')'; - } - return false; - } - if (!isset($MPEGaudioChannelModeLookup[$rawarray['channelmode']])) { - if ($echoerrors) { - echo "\n".'invalid ChannelMode ('.$rawarray['channelmode'].')'; - } - return false; - } - if (!isset($MPEGaudioModeExtensionLookup[$decodedLayer][$rawarray['modeextension']])) { - if ($echoerrors) { - echo "\n".'invalid Mode Extension ('.$rawarray['modeextension'].')'; - } - return false; - } - if (!isset($MPEGaudioEmphasisLookup[$rawarray['emphasis']])) { - if ($echoerrors) { - echo "\n".'invalid Emphasis ('.$rawarray['emphasis'].')'; - } - return false; - } - // These are just either set or not set, you can't mess that up :) - // $rawarray['protection']; - // $rawarray['padding']; - // $rawarray['private']; - // $rawarray['copyright']; - // $rawarray['original']; + if (isset($MPEGaudioVersionLookup[$rawarray['version']])) { + $decodedVersion = $MPEGaudioVersionLookup[$rawarray['version']]; + } else { + if ($echoerrors) { + echo "\n".'invalid Version ('.$rawarray['version'].')'; + } + return false; + } + if (isset($MPEGaudioLayerLookup[$rawarray['layer']])) { + $decodedLayer = $MPEGaudioLayerLookup[$rawarray['layer']]; + } else { + if ($echoerrors) { + echo "\n".'invalid Layer ('.$rawarray['layer'].')'; + } + return false; + } + if (!isset($MPEGaudioBitrateLookup[$decodedVersion][$decodedLayer][$rawarray['bitrate']])) { + if ($echoerrors) { + echo "\n".'invalid Bitrate ('.$rawarray['bitrate'].')'; + } + if ($rawarray['bitrate'] == 15) { + // known issue in LAME 3.90 - 3.93.1 where free-format has bitrate ID of 15 instead of 0 + // let it go through here otherwise file will not be identified + } else { + return false; + } + } + if (!isset($MPEGaudioFrequencyLookup[$decodedVersion][$rawarray['sample_rate']])) { + if ($echoerrors) { + echo "\n".'invalid Frequency ('.$rawarray['sample_rate'].')'; + } + return false; + } + if (!isset($MPEGaudioChannelModeLookup[$rawarray['channelmode']])) { + if ($echoerrors) { + echo "\n".'invalid ChannelMode ('.$rawarray['channelmode'].')'; + } + return false; + } + if (!isset($MPEGaudioModeExtensionLookup[$decodedLayer][$rawarray['modeextension']])) { + if ($echoerrors) { + echo "\n".'invalid Mode Extension ('.$rawarray['modeextension'].')'; + } + return false; + } + if (!isset($MPEGaudioEmphasisLookup[$rawarray['emphasis']])) { + if ($echoerrors) { + echo "\n".'invalid Emphasis ('.$rawarray['emphasis'].')'; + } + return false; + } + // These are just either set or not set, you can't mess that up :) + // $rawarray['protection']; + // $rawarray['padding']; + // $rawarray['private']; + // $rawarray['copyright']; + // $rawarray['original']; - return true; + return true; } -function MPEGaudioHeaderDecode($Header4Bytes) { - // AAAA AAAA AAAB BCCD EEEE FFGH IIJJ KLMM - // A - Frame sync (all bits set) - // B - MPEG Audio version ID - // C - Layer description - // D - Protection bit - // E - Bitrate index - // F - Sampling rate frequency index - // G - Padding bit - // H - Private bit - // I - Channel Mode - // J - Mode extension (Only if Joint stereo) - // K - Copyright - // L - Original - // M - Emphasis +function MPEGaudioHeaderDecode($Header4Bytes) +{ + // AAAA AAAA AAAB BCCD EEEE FFGH IIJJ KLMM + // A - Frame sync (all bits set) + // B - MPEG Audio version ID + // C - Layer description + // D - Protection bit + // E - Bitrate index + // F - Sampling rate frequency index + // G - Padding bit + // H - Private bit + // I - Channel Mode + // J - Mode extension (Only if Joint stereo) + // K - Copyright + // L - Original + // M - Emphasis - if (strlen($Header4Bytes) != 4) { - return false; - } + if (strlen($Header4Bytes) != 4) { + return false; + } - $MPEGrawHeader['synch'] = (BigEndian2Int(substr($Header4Bytes, 0, 2)) & 0xFFE0) >> 4; - $MPEGrawHeader['version'] = (ord($Header4Bytes{1}) & 0x18) >> 3; // BB - $MPEGrawHeader['layer'] = (ord($Header4Bytes{1}) & 0x06) >> 1; // CC - $MPEGrawHeader['protection'] = (ord($Header4Bytes{1}) & 0x01); // D - $MPEGrawHeader['bitrate'] = (ord($Header4Bytes{2}) & 0xF0) >> 4; // EEEE - $MPEGrawHeader['sample_rate'] = (ord($Header4Bytes{2}) & 0x0C) >> 2; // FF - $MPEGrawHeader['padding'] = (ord($Header4Bytes{2}) & 0x02) >> 1; // G - $MPEGrawHeader['private'] = (ord($Header4Bytes{2}) & 0x01); // H - $MPEGrawHeader['channelmode'] = (ord($Header4Bytes{3}) & 0xC0) >> 6; // II - $MPEGrawHeader['modeextension'] = (ord($Header4Bytes{3}) & 0x30) >> 4; // JJ - $MPEGrawHeader['copyright'] = (ord($Header4Bytes{3}) & 0x08) >> 3; // K - $MPEGrawHeader['original'] = (ord($Header4Bytes{3}) & 0x04) >> 2; // L - $MPEGrawHeader['emphasis'] = (ord($Header4Bytes{3}) & 0x03); // MM + $MPEGrawHeader['synch'] = (BigEndian2Int(substr($Header4Bytes, 0, 2)) & 0xFFE0) >> 4; + $MPEGrawHeader['version'] = (ord($Header4Bytes{1}) & 0x18) >> 3; // BB + $MPEGrawHeader['layer'] = (ord($Header4Bytes{1}) & 0x06) >> 1; // CC + $MPEGrawHeader['protection'] = (ord($Header4Bytes{1}) & 0x01); // D + $MPEGrawHeader['bitrate'] = (ord($Header4Bytes{2}) & 0xF0) >> 4; // EEEE + $MPEGrawHeader['sample_rate'] = (ord($Header4Bytes{2}) & 0x0C) >> 2; // FF + $MPEGrawHeader['padding'] = (ord($Header4Bytes{2}) & 0x02) >> 1; // G + $MPEGrawHeader['private'] = (ord($Header4Bytes{2}) & 0x01); // H + $MPEGrawHeader['channelmode'] = (ord($Header4Bytes{3}) & 0xC0) >> 6; // II + $MPEGrawHeader['modeextension'] = (ord($Header4Bytes{3}) & 0x30) >> 4; // JJ + $MPEGrawHeader['copyright'] = (ord($Header4Bytes{3}) & 0x08) >> 3; // K + $MPEGrawHeader['original'] = (ord($Header4Bytes{3}) & 0x04) >> 2; // L + $MPEGrawHeader['emphasis'] = (ord($Header4Bytes{3}) & 0x03); // MM - return $MPEGrawHeader; + return $MPEGrawHeader; } -function MPEGaudioFrameLength(&$bitrate, &$version, &$layer, $padding, &$samplerate) { - static $AudioFrameLengthCache = array(); +function MPEGaudioFrameLength(&$bitrate, &$version, &$layer, $padding, &$samplerate) +{ + static $AudioFrameLengthCache = []; - if (!isset($AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate])) { - $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = false; - if ($bitrate != 'free') { + if (!isset($AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate])) { + $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = false; + if ($bitrate != 'free') { + if ($version == '1') { + if ($layer == 'I') { + // For Layer I slot is 32 bits long + $FrameLengthCoefficient = 48; + $SlotLength = 4; + } else { // Layer II / III - if ($version == '1') { + // for Layer II and Layer III slot is 8 bits long. + $FrameLengthCoefficient = 144; + $SlotLength = 1; + } + } else { // MPEG-2 / MPEG-2.5 - if ($layer == 'I') { + if ($layer == 'I') { + // For Layer I slot is 32 bits long + $FrameLengthCoefficient = 24; + $SlotLength = 4; + } elseif ($layer == 'II') { + // for Layer II and Layer III slot is 8 bits long. + $FrameLengthCoefficient = 144; + $SlotLength = 1; + } else { // III - // For Layer I slot is 32 bits long - $FrameLengthCoefficient = 48; - $SlotLength = 4; + // for Layer II and Layer III slot is 8 bits long. + $FrameLengthCoefficient = 72; + $SlotLength = 1; + } + } - } else { // Layer II / III - - // for Layer II and Layer III slot is 8 bits long. - $FrameLengthCoefficient = 144; - $SlotLength = 1; - - } - - } else { // MPEG-2 / MPEG-2.5 - - if ($layer == 'I') { - - // For Layer I slot is 32 bits long - $FrameLengthCoefficient = 24; - $SlotLength = 4; - - } elseif ($layer == 'II') { - - // for Layer II and Layer III slot is 8 bits long. - $FrameLengthCoefficient = 144; - $SlotLength = 1; - - } else { // III - - // for Layer II and Layer III slot is 8 bits long. - $FrameLengthCoefficient = 72; - $SlotLength = 1; - - } - - } - - // FrameLengthInBytes = ((Coefficient * BitRate) / SampleRate) + Padding - // http://66.96.216.160/cgi-bin/YaBB.pl?board=c&action=display&num=1018474068 - // -> [Finding the next frame synch] on www.r3mix.net forums if the above link goes dead - if ($samplerate > 0) { - $NewFramelength = ($FrameLengthCoefficient * $bitrate * 1000) / $samplerate; - $NewFramelength = floor($NewFramelength / $SlotLength) * $SlotLength; // round to next-lower multiple of SlotLength (1 byte for Layer II/III, 4 bytes for Layer I) - if ($padding) { - $NewFramelength += $SlotLength; - } - $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = (int) $NewFramelength; - } - } - } - return $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate]; + // FrameLengthInBytes = ((Coefficient * BitRate) / SampleRate) + Padding + // http://66.96.216.160/cgi-bin/YaBB.pl?board=c&action=display&num=1018474068 + // -> [Finding the next frame synch] on www.r3mix.net forums if the above link goes dead + if ($samplerate > 0) { + $NewFramelength = ($FrameLengthCoefficient * $bitrate * 1000) / $samplerate; + $NewFramelength = floor($NewFramelength / $SlotLength) * $SlotLength; // round to next-lower multiple of SlotLength (1 byte for Layer II/III, 4 bytes for Layer I) + if ($padding) { + $NewFramelength += $SlotLength; + } + $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = (int) $NewFramelength; + } + } + } + return $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate]; } -function LAMEvbrMethodLookup($VBRmethodID) { - static $LAMEvbrMethodLookup = array(); - if (empty($LAMEvbrMethodLookup)) { - $LAMEvbrMethodLookup[0x00] = 'unknown'; - $LAMEvbrMethodLookup[0x01] = 'cbr'; - $LAMEvbrMethodLookup[0x02] = 'abr'; - $LAMEvbrMethodLookup[0x03] = 'vbr-old / vbr-rh'; - $LAMEvbrMethodLookup[0x04] = 'vbr-mtrh'; - $LAMEvbrMethodLookup[0x05] = 'vbr-new / vbr-mt'; - } - return (isset($LAMEvbrMethodLookup[$VBRmethodID]) ? $LAMEvbrMethodLookup[$VBRmethodID] : ''); +function LAMEvbrMethodLookup($VBRmethodID) +{ + static $LAMEvbrMethodLookup = []; + if (empty($LAMEvbrMethodLookup)) { + $LAMEvbrMethodLookup[0x00] = 'unknown'; + $LAMEvbrMethodLookup[0x01] = 'cbr'; + $LAMEvbrMethodLookup[0x02] = 'abr'; + $LAMEvbrMethodLookup[0x03] = 'vbr-old / vbr-rh'; + $LAMEvbrMethodLookup[0x04] = 'vbr-mtrh'; + $LAMEvbrMethodLookup[0x05] = 'vbr-new / vbr-mt'; + } + return (isset($LAMEvbrMethodLookup[$VBRmethodID]) ? $LAMEvbrMethodLookup[$VBRmethodID] : ''); } -function LAMEmiscStereoModeLookup($StereoModeID) { - static $LAMEmiscStereoModeLookup = array(); - if (empty($LAMEmiscStereoModeLookup)) { - $LAMEmiscStereoModeLookup[0] = 'mono'; - $LAMEmiscStereoModeLookup[1] = 'stereo'; - $LAMEmiscStereoModeLookup[2] = 'dual'; - $LAMEmiscStereoModeLookup[3] = 'joint'; - $LAMEmiscStereoModeLookup[4] = 'forced'; - $LAMEmiscStereoModeLookup[5] = 'auto'; - $LAMEmiscStereoModeLookup[6] = 'intensity'; - $LAMEmiscStereoModeLookup[7] = 'other'; - } - return (isset($LAMEmiscStereoModeLookup[$StereoModeID]) ? $LAMEmiscStereoModeLookup[$StereoModeID] : ''); +function LAMEmiscStereoModeLookup($StereoModeID) +{ + static $LAMEmiscStereoModeLookup = []; + if (empty($LAMEmiscStereoModeLookup)) { + $LAMEmiscStereoModeLookup[0] = 'mono'; + $LAMEmiscStereoModeLookup[1] = 'stereo'; + $LAMEmiscStereoModeLookup[2] = 'dual'; + $LAMEmiscStereoModeLookup[3] = 'joint'; + $LAMEmiscStereoModeLookup[4] = 'forced'; + $LAMEmiscStereoModeLookup[5] = 'auto'; + $LAMEmiscStereoModeLookup[6] = 'intensity'; + $LAMEmiscStereoModeLookup[7] = 'other'; + } + return (isset($LAMEmiscStereoModeLookup[$StereoModeID]) ? $LAMEmiscStereoModeLookup[$StereoModeID] : ''); } -function LAMEmiscSourceSampleFrequencyLookup($SourceSampleFrequencyID) { - static $LAMEmiscSourceSampleFrequencyLookup = array(); - if (empty($LAMEmiscSourceSampleFrequencyLookup)) { - $LAMEmiscSourceSampleFrequencyLookup[0] = '<= 32 kHz'; - $LAMEmiscSourceSampleFrequencyLookup[1] = '44.1 kHz'; - $LAMEmiscSourceSampleFrequencyLookup[2] = '48 kHz'; - $LAMEmiscSourceSampleFrequencyLookup[3] = '> 48kHz'; - } - return (isset($LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID]) ? $LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID] : ''); +function LAMEmiscSourceSampleFrequencyLookup($SourceSampleFrequencyID) +{ + static $LAMEmiscSourceSampleFrequencyLookup = []; + if (empty($LAMEmiscSourceSampleFrequencyLookup)) { + $LAMEmiscSourceSampleFrequencyLookup[0] = '<= 32 kHz'; + $LAMEmiscSourceSampleFrequencyLookup[1] = '44.1 kHz'; + $LAMEmiscSourceSampleFrequencyLookup[2] = '48 kHz'; + $LAMEmiscSourceSampleFrequencyLookup[3] = '> 48kHz'; + } + return (isset($LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID]) ? $LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID] : ''); } -function LAMEsurroundInfoLookup($SurroundInfoID) { - static $LAMEsurroundInfoLookup = array(); - if (empty($LAMEsurroundInfoLookup)) { - $LAMEsurroundInfoLookup[0] = 'no surround info'; - $LAMEsurroundInfoLookup[1] = 'DPL encoding'; - $LAMEsurroundInfoLookup[2] = 'DPL2 encoding'; - $LAMEsurroundInfoLookup[3] = 'Ambisonic encoding'; - } - return (isset($LAMEsurroundInfoLookup[$SurroundInfoID]) ? $LAMEsurroundInfoLookup[$SurroundInfoID] : 'reserved'); +function LAMEsurroundInfoLookup($SurroundInfoID) +{ + static $LAMEsurroundInfoLookup = []; + if (empty($LAMEsurroundInfoLookup)) { + $LAMEsurroundInfoLookup[0] = 'no surround info'; + $LAMEsurroundInfoLookup[1] = 'DPL encoding'; + $LAMEsurroundInfoLookup[2] = 'DPL2 encoding'; + $LAMEsurroundInfoLookup[3] = 'Ambisonic encoding'; + } + return (isset($LAMEsurroundInfoLookup[$SurroundInfoID]) ? $LAMEsurroundInfoLookup[$SurroundInfoID] : 'reserved'); } for ($i = 0x00; $i <= 0xFF; $i++) { - $head4 = "\xFF\xFE".chr($i)."\x00"; - $isvalid = MPEGaudioHeaderBytesValid($head4); - echo '
'.str_pad(strtoupper(dechex($i)), 2, '0', STR_PAD_LEFT).' = '.htmlentities(chr($i)).' = '.($isvalid ? 'valid' : 'INVALID').'
'; + $head4 = "\xFF\xFE".chr($i)."\x00"; + $isvalid = MPEGaudioHeaderBytesValid($head4); + echo '
'.str_pad(strtoupper(dechex($i)), 2, '0', STR_PAD_LEFT).' = '.htmlentities(chr($i)).' = '.($isvalid ? 'valid' : 'INVALID').'
'; } diff --git a/app/Library/getid3/demos/demo.mysql.php b/app/Library/getid3/demos/demo.mysql.php index 24443994..bff1fc9b 100644 --- a/app/Library/getid3/demos/demo.mysql.php +++ b/app/Library/getid3/demos/demo.mysql.php @@ -21,2117 +21,1933 @@ $getid3_demo_mysql_encoding = 'ISO-8859-1'; $getid3_demo_mysql_md5_data = false; // All data hashes are by far the slowest part of scanning $getid3_demo_mysql_md5_file = false; -define('GETID3_DB_HOST', 'localhost'); -define('GETID3_DB_USER', 'root'); -define('GETID3_DB_PASS', 'password'); -define('GETID3_DB_DB', 'getid3'); +define('GETID3_DB_HOST', 'localhost'); +define('GETID3_DB_USER', 'root'); +define('GETID3_DB_PASS', 'password'); +define('GETID3_DB_DB', 'getid3'); define('GETID3_DB_TABLE', 'files'); // CREATE DATABASE `getid3`; ob_start(); if (!mysql_connect(GETID3_DB_HOST, GETID3_DB_USER, GETID3_DB_PASS)) { - $errormessage = ob_get_contents(); - ob_end_clean(); - die('Could not connect to MySQL host:
'.mysql_error().'
'); + $errormessage = ob_get_contents(); + ob_end_clean(); + die('Could not connect to MySQL host:
'.mysql_error().'
'); } if (!mysql_select_db(GETID3_DB_DB)) { - $errormessage = ob_get_contents(); - ob_end_clean(); - die('Could not select database:
'.mysql_error().'
'); + $errormessage = ob_get_contents(); + ob_end_clean(); + die('Could not select database:
'.mysql_error().'
'); } ob_end_clean(); $getid3PHP_filename = realpath('../getid3/getid3.php'); if (!file_exists($getid3PHP_filename) || !include_once($getid3PHP_filename)) { - die('Cannot open '.$getid3PHP_filename); + die('Cannot open '.$getid3PHP_filename); } // Initialize getID3 engine $getID3 = new getID3; -$getID3->setOption(array( - 'option_md5_data' => $getid3_demo_mysql_md5_data, - 'encoding' => $getid3_demo_mysql_encoding, -)); +$getID3->setOption([ + 'option_md5_data' => $getid3_demo_mysql_md5_data, + 'encoding' => $getid3_demo_mysql_encoding, +]); -function RemoveAccents($string) { - // Revised version by markstewardØhotmail*com - return strtr(strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'), array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u')); +function RemoveAccents($string) +{ + // Revised version by markstewardØhotmail*com + return strtr(strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'), ['Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u']); } -function BitrateColor($bitrate, $BitrateMaxScale=768) { - // $BitrateMaxScale is bitrate of maximum-quality color (bright green) - // below this is gradient, above is solid green +function BitrateColor($bitrate, $BitrateMaxScale = 768) +{ + // $BitrateMaxScale is bitrate of maximum-quality color (bright green) + // below this is gradient, above is solid green - $bitrate *= (256 / $BitrateMaxScale); // scale from 1-[768]kbps to 1-256 - $bitrate = round(min(max($bitrate, 1), 256)); - $bitrate--; // scale from 1-256kbps to 0-255kbps + $bitrate *= (256 / $BitrateMaxScale); // scale from 1-[768]kbps to 1-256 + $bitrate = round(min(max($bitrate, 1), 256)); + $bitrate--; // scale from 1-256kbps to 0-255kbps - $Rcomponent = max(255 - ($bitrate * 2), 0); - $Gcomponent = max(($bitrate * 2) - 255, 0); - if ($bitrate > 127) { - $Bcomponent = max((255 - $bitrate) * 2, 0); - } else { - $Bcomponent = max($bitrate * 2, 0); - } - return str_pad(dechex($Rcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Gcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Bcomponent), 2, '0', STR_PAD_LEFT); + $Rcomponent = max(255 - ($bitrate * 2), 0); + $Gcomponent = max(($bitrate * 2) - 255, 0); + if ($bitrate > 127) { + $Bcomponent = max((255 - $bitrate) * 2, 0); + } else { + $Bcomponent = max($bitrate * 2, 0); + } + return str_pad(dechex($Rcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Gcomponent), 2, '0', STR_PAD_LEFT).str_pad(dechex($Bcomponent), 2, '0', STR_PAD_LEFT); } -function BitrateText($bitrate, $decimals=0) { - return ''.number_format($bitrate, $decimals).' kbps'; +function BitrateText($bitrate, $decimals = 0) +{ + return ''.number_format($bitrate, $decimals).' kbps'; } -function fileextension($filename, $numextensions=1) { - if (strstr($filename, '.')) { - $reversedfilename = strrev($filename); - $offset = 0; - for ($i = 0; $i < $numextensions; $i++) { - $offset = strpos($reversedfilename, '.', $offset + 1); - if ($offset === false) { - return ''; - } - } - return strrev(substr($reversedfilename, 0, $offset)); - } - return ''; +function fileextension($filename, $numextensions = 1) +{ + if (strstr($filename, '.')) { + $reversedfilename = strrev($filename); + $offset = 0; + for ($i = 0; $i < $numextensions; $i++) { + $offset = strpos($reversedfilename, '.', $offset + 1); + if ($offset === false) { + return ''; + } + } + return strrev(substr($reversedfilename, 0, $offset)); + } + return ''; } -function RenameFileFromTo($from, $to, &$results) { - $success = true; - if ($from === $to) { - $results = 'Source and Destination filenames identical
FAILED to rename'; - } elseif (!file_exists($from)) { - $results = 'Source file does not exist
FAILED to rename'; - } elseif (file_exists($to) && (strtolower($from) !== strtolower($to))) { - $results = 'Destination file already exists
FAILED to rename'; - } else { - ob_start(); - if (rename($from, $to)) { - ob_end_clean(); - $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($from).'")'; - mysql_query_safe($SQLquery); - $results = 'Successfully renamed'; - } else { - $errormessage = ob_get_contents(); - ob_end_clean(); - $results = '
FAILED to rename'; - $success = false; - } - } - $results .= ' from:
'.$from.'
to:
'.$to.'

'; - return $success; +function RenameFileFromTo($from, $to, &$results) +{ + $success = true; + if ($from === $to) { + $results = 'Source and Destination filenames identical
FAILED to rename'; + } elseif (!file_exists($from)) { + $results = 'Source file does not exist
FAILED to rename'; + } elseif (file_exists($to) && (strtolower($from) !== strtolower($to))) { + $results = 'Destination file already exists
FAILED to rename'; + } else { + ob_start(); + if (rename($from, $to)) { + ob_end_clean(); + $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($from).'")'; + mysql_query_safe($SQLquery); + $results = 'Successfully renamed'; + } else { + $errormessage = ob_get_contents(); + ob_end_clean(); + $results = '
FAILED to rename'; + $success = false; + } + } + $results .= ' from:
'.$from.'
to:
'.$to.'

'; + return $success; } if (!empty($_REQUEST['renamefilefrom']) && !empty($_REQUEST['renamefileto'])) { - - $results = ''; - RenameFileFromTo($_REQUEST['renamefilefrom'], $_REQUEST['renamefileto'], $results); - echo $results; - exit; - + $results = ''; + RenameFileFromTo($_REQUEST['renamefilefrom'], $_REQUEST['renamefileto'], $results); + echo $results; + exit; } elseif (!empty($_REQUEST['m3ufilename'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - echo WindowsShareSlashTranslate($_REQUEST['m3ufilename'])."\n"; - exit; - + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + echo WindowsShareSlashTranslate($_REQUEST['m3ufilename'])."\n"; + exit; } elseif (!isset($_REQUEST['m3u']) && !isset($_REQUEST['m3uartist']) && !isset($_REQUEST['m3utitle'])) { - - echo ''; - echo 'getID3() demo - /demo/mysql.php'; - + echo ''; + echo 'getID3() demo - /demo/mysql.php'; } -function WindowsShareSlashTranslate($filename) { - if (substr($filename, 0, 2) == '//') { - return str_replace('/', '\\', $filename); - } - return $filename; +function WindowsShareSlashTranslate($filename) +{ + if (substr($filename, 0, 2) == '//') { + return str_replace('/', '\\', $filename); + } + return $filename; } -function mysql_query_safe($SQLquery) { - static $TimeSpentQuerying = 0; - if ($SQLquery === null) { - return $TimeSpentQuerying; - } - $starttime = microtime(true); - $result = mysql_query($SQLquery); - $TimeSpentQuerying += (microtime(true) - $starttime); - if (mysql_error()) { - die('
SQL error:
'.htmlentities(mysql_error()).'

'.htmlentities($SQLquery).'
'); - } - return $result; +function mysql_query_safe($SQLquery) +{ + static $TimeSpentQuerying = 0; + if ($SQLquery === null) { + return $TimeSpentQuerying; + } + $starttime = microtime(true); + $result = mysql_query($SQLquery); + $TimeSpentQuerying += (microtime(true) - $starttime); + if (mysql_error()) { + die('
SQL error:
'.htmlentities(mysql_error()).'

'.htmlentities($SQLquery).'
'); + } + return $result; } -function mysql_table_exists($tablename) { - return (bool) mysql_query('DESCRIBE '.$tablename); +function mysql_table_exists($tablename) +{ + return (bool) mysql_query('DESCRIBE '.$tablename); } -function AcceptableExtensions($fileformat, $audio_dataformat='', $video_dataformat='') { - static $AcceptableExtensionsAudio = array(); - if (empty($AcceptableExtensionsAudio)) { - $AcceptableExtensionsAudio['mp3']['mp3'] = array('mp3'); - $AcceptableExtensionsAudio['mp2']['mp2'] = array('mp2'); - $AcceptableExtensionsAudio['mp1']['mp1'] = array('mp1'); - $AcceptableExtensionsAudio['asf']['asf'] = array('asf'); - $AcceptableExtensionsAudio['asf']['wma'] = array('wma'); - $AcceptableExtensionsAudio['riff']['mp3'] = array('wav'); - $AcceptableExtensionsAudio['riff']['wav'] = array('wav'); - } - static $AcceptableExtensionsVideo = array(); - if (empty($AcceptableExtensionsVideo)) { - $AcceptableExtensionsVideo['mp3']['mp3'] = array('mp3'); - $AcceptableExtensionsVideo['mp2']['mp2'] = array('mp2'); - $AcceptableExtensionsVideo['mp1']['mp1'] = array('mp1'); - $AcceptableExtensionsVideo['asf']['asf'] = array('asf'); - $AcceptableExtensionsVideo['asf']['wmv'] = array('wmv'); - $AcceptableExtensionsVideo['gif']['gif'] = array('gif'); - $AcceptableExtensionsVideo['jpg']['jpg'] = array('jpg'); - $AcceptableExtensionsVideo['png']['png'] = array('png'); - $AcceptableExtensionsVideo['bmp']['bmp'] = array('bmp'); - } - if (!empty($video_dataformat)) { - return (isset($AcceptableExtensionsVideo[$fileformat][$video_dataformat]) ? $AcceptableExtensionsVideo[$fileformat][$video_dataformat] : array()); - } else { - return (isset($AcceptableExtensionsAudio[$fileformat][$audio_dataformat]) ? $AcceptableExtensionsAudio[$fileformat][$audio_dataformat] : array()); - } +function AcceptableExtensions($fileformat, $audio_dataformat = '', $video_dataformat = '') +{ + static $AcceptableExtensionsAudio = []; + if (empty($AcceptableExtensionsAudio)) { + $AcceptableExtensionsAudio['mp3']['mp3'] = ['mp3']; + $AcceptableExtensionsAudio['mp2']['mp2'] = ['mp2']; + $AcceptableExtensionsAudio['mp1']['mp1'] = ['mp1']; + $AcceptableExtensionsAudio['asf']['asf'] = ['asf']; + $AcceptableExtensionsAudio['asf']['wma'] = ['wma']; + $AcceptableExtensionsAudio['riff']['mp3'] = ['wav']; + $AcceptableExtensionsAudio['riff']['wav'] = ['wav']; + } + static $AcceptableExtensionsVideo = []; + if (empty($AcceptableExtensionsVideo)) { + $AcceptableExtensionsVideo['mp3']['mp3'] = ['mp3']; + $AcceptableExtensionsVideo['mp2']['mp2'] = ['mp2']; + $AcceptableExtensionsVideo['mp1']['mp1'] = ['mp1']; + $AcceptableExtensionsVideo['asf']['asf'] = ['asf']; + $AcceptableExtensionsVideo['asf']['wmv'] = ['wmv']; + $AcceptableExtensionsVideo['gif']['gif'] = ['gif']; + $AcceptableExtensionsVideo['jpg']['jpg'] = ['jpg']; + $AcceptableExtensionsVideo['png']['png'] = ['png']; + $AcceptableExtensionsVideo['bmp']['bmp'] = ['bmp']; + } + if (!empty($video_dataformat)) { + return (isset($AcceptableExtensionsVideo[$fileformat][$video_dataformat]) ? $AcceptableExtensionsVideo[$fileformat][$video_dataformat] : []); + } else { + return (isset($AcceptableExtensionsAudio[$fileformat][$audio_dataformat]) ? $AcceptableExtensionsAudio[$fileformat][$audio_dataformat] : []); + } } if (!empty($_REQUEST['scan'])) { - if (mysql_table_exists(GETID3_DB_TABLE)) { - $SQLquery = 'DROP TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - mysql_query_safe($SQLquery); - } + if (mysql_table_exists(GETID3_DB_TABLE)) { + $SQLquery = 'DROP TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + mysql_query_safe($SQLquery); + } } if (!mysql_table_exists(GETID3_DB_TABLE)) { - $SQLquery = "CREATE TABLE `".mysql_real_escape_string(GETID3_DB_TABLE)."` ("; - $SQLquery .= " `ID` int(11) unsigned NOT NULL auto_increment,"; - $SQLquery .= " `filename` text NOT NULL,"; - $SQLquery .= " `last_modified` int(11) NOT NULL default '0',"; - $SQLquery .= " `md5_file` varchar(32) NOT NULL default '',"; - $SQLquery .= " `md5_data` varchar(32) NOT NULL default '',"; - $SQLquery .= " `md5_data_source` varchar(32) NOT NULL default '',"; - $SQLquery .= " `filesize` int(10) unsigned NOT NULL default '0',"; - $SQLquery .= " `fileformat` varchar(255) NOT NULL default '',"; - $SQLquery .= " `audio_dataformat` varchar(255) NOT NULL default '',"; - $SQLquery .= " `video_dataformat` varchar(255) NOT NULL default '',"; - $SQLquery .= " `audio_bitrate` float NOT NULL default '0',"; - $SQLquery .= " `video_bitrate` float NOT NULL default '0',"; - $SQLquery .= " `playtime_seconds` varchar(255) NOT NULL default '',"; - $SQLquery .= " `tags` varchar(255) NOT NULL default '',"; - $SQLquery .= " `artist` varchar(255) NOT NULL default '',"; - $SQLquery .= " `title` varchar(255) NOT NULL default '',"; - $SQLquery .= " `remix` varchar(255) NOT NULL default '',"; - $SQLquery .= " `album` varchar(255) NOT NULL default '',"; - $SQLquery .= " `genre` varchar(255) NOT NULL default '',"; - $SQLquery .= " `comment` text NOT NULL,"; - $SQLquery .= " `track` varchar(7) NOT NULL default '',"; - $SQLquery .= " `comments_all` longtext NOT NULL,"; - $SQLquery .= " `comments_id3v2` longtext NOT NULL,"; - $SQLquery .= " `comments_ape` longtext NOT NULL,"; - $SQLquery .= " `comments_lyrics3` longtext NOT NULL,"; - $SQLquery .= " `comments_id3v1` text NOT NULL,"; - $SQLquery .= " `warning` longtext NOT NULL,"; - $SQLquery .= " `error` longtext NOT NULL,"; - $SQLquery .= " `track_volume` float NOT NULL default '0',"; - $SQLquery .= " `encoder_options` varchar(255) NOT NULL default '',"; - $SQLquery .= " `vbr_method` varchar(255) NOT NULL default '',"; - $SQLquery .= " PRIMARY KEY (`ID`)"; - $SQLquery .= ")"; - mysql_query_safe($SQLquery); + $SQLquery = "CREATE TABLE `".mysql_real_escape_string(GETID3_DB_TABLE)."` ("; + $SQLquery .= " `ID` int(11) unsigned NOT NULL auto_increment,"; + $SQLquery .= " `filename` text NOT NULL,"; + $SQLquery .= " `last_modified` int(11) NOT NULL default '0',"; + $SQLquery .= " `md5_file` varchar(32) NOT NULL default '',"; + $SQLquery .= " `md5_data` varchar(32) NOT NULL default '',"; + $SQLquery .= " `md5_data_source` varchar(32) NOT NULL default '',"; + $SQLquery .= " `filesize` int(10) unsigned NOT NULL default '0',"; + $SQLquery .= " `fileformat` varchar(255) NOT NULL default '',"; + $SQLquery .= " `audio_dataformat` varchar(255) NOT NULL default '',"; + $SQLquery .= " `video_dataformat` varchar(255) NOT NULL default '',"; + $SQLquery .= " `audio_bitrate` float NOT NULL default '0',"; + $SQLquery .= " `video_bitrate` float NOT NULL default '0',"; + $SQLquery .= " `playtime_seconds` varchar(255) NOT NULL default '',"; + $SQLquery .= " `tags` varchar(255) NOT NULL default '',"; + $SQLquery .= " `artist` varchar(255) NOT NULL default '',"; + $SQLquery .= " `title` varchar(255) NOT NULL default '',"; + $SQLquery .= " `remix` varchar(255) NOT NULL default '',"; + $SQLquery .= " `album` varchar(255) NOT NULL default '',"; + $SQLquery .= " `genre` varchar(255) NOT NULL default '',"; + $SQLquery .= " `comment` text NOT NULL,"; + $SQLquery .= " `track` varchar(7) NOT NULL default '',"; + $SQLquery .= " `comments_all` longtext NOT NULL,"; + $SQLquery .= " `comments_id3v2` longtext NOT NULL,"; + $SQLquery .= " `comments_ape` longtext NOT NULL,"; + $SQLquery .= " `comments_lyrics3` longtext NOT NULL,"; + $SQLquery .= " `comments_id3v1` text NOT NULL,"; + $SQLquery .= " `warning` longtext NOT NULL,"; + $SQLquery .= " `error` longtext NOT NULL,"; + $SQLquery .= " `track_volume` float NOT NULL default '0',"; + $SQLquery .= " `encoder_options` varchar(255) NOT NULL default '',"; + $SQLquery .= " `vbr_method` varchar(255) NOT NULL default '',"; + $SQLquery .= " PRIMARY KEY (`ID`)"; + $SQLquery .= ")"; + mysql_query_safe($SQLquery); } -$ExistingTableFields = array(); +$ExistingTableFields = []; $result = mysql_query_safe('DESCRIBE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); while ($row = mysql_fetch_array($result)) { - $ExistingTableFields[$row['Field']] = $row; + $ExistingTableFields[$row['Field']] = $row; } if (!isset($ExistingTableFields['encoder_options'])) { // Added in 1.7.0b2 - echo 'adding field `encoder_options`
'; - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `encoder_options` VARCHAR(255) default "" NOT NULL AFTER `error`'); - mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); + echo 'adding field `encoder_options`
'; + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `encoder_options` VARCHAR(255) default "" NOT NULL AFTER `error`'); + mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); } if (isset($ExistingTableFields['track']) && ($ExistingTableFields['track']['Type'] != 'varchar(7)')) { // Changed in 1.7.0b2 - echo 'changing field `track` to VARCHAR(7)
'; - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `track` `track` VARCHAR(7) default "" NOT NULL'); - mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); + echo 'changing field `track` to VARCHAR(7)
'; + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `track` `track` VARCHAR(7) default "" NOT NULL'); + mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); } if (!isset($ExistingTableFields['track_volume'])) { // Added in 1.7.0b5 - echo '

WARNING! You should erase your database and rescan everything because the comment storing has been changed since the last version


'; - echo 'adding field `track_volume`
'; - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `track_volume` FLOAT NOT NULL AFTER `error`'); - mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); + echo '

WARNING! You should erase your database and rescan everything because the comment storing has been changed since the last version


'; + echo 'adding field `track_volume`
'; + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `track_volume` FLOAT NOT NULL AFTER `error`'); + mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); } if (!isset($ExistingTableFields['remix'])) { // Added in 1.7.3b1 - echo 'adding field `encoder_options`, `alternate_name`, `parody`
'; - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `remix` VARCHAR(255) default "" NOT NULL AFTER `title`'); - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `alternate_name` VARCHAR(255) default "" NOT NULL AFTER `track`'); - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `parody` VARCHAR(255) default "" NOT NULL AFTER `alternate_name`'); - mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); + echo 'adding field `encoder_options`, `alternate_name`, `parody`
'; + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `remix` VARCHAR(255) default "" NOT NULL AFTER `title`'); + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `alternate_name` VARCHAR(255) default "" NOT NULL AFTER `track`'); + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` ADD `parody` VARCHAR(255) default "" NOT NULL AFTER `alternate_name`'); + mysql_query_safe('OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'); } if (isset($ExistingTableFields['comments_all']) && ($ExistingTableFields['comments_all']['Type'] != 'longtext')) { // Changed in 1.9.0 - echo 'changing comments fields from text to longtext
'; - // no need to change id3v1 - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_all` `comments_all` LONGTEXT NOT NULL'); - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_id3v2` `comments_id3v2` LONGTEXT NOT NULL'); - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_ape` `comments_ape` LONGTEXT NOT NULL'); - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_lyrics3` `comments_lyrics3` LONGTEXT NOT NULL'); - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `warning` `warning` LONGTEXT NOT NULL'); - mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `error` `error` LONGTEXT NOT NULL'); + echo 'changing comments fields from text to longtext
'; + // no need to change id3v1 + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_all` `comments_all` LONGTEXT NOT NULL'); + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_id3v2` `comments_id3v2` LONGTEXT NOT NULL'); + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_ape` `comments_ape` LONGTEXT NOT NULL'); + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `comments_lyrics3` `comments_lyrics3` LONGTEXT NOT NULL'); + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `warning` `warning` LONGTEXT NOT NULL'); + mysql_query_safe('ALTER TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` CHANGE `error` `error` LONGTEXT NOT NULL'); } -function SynchronizeAllTags($filename, $synchronizefrom='all', $synchronizeto='A12', &$errors) { - global $getID3; +function SynchronizeAllTags($filename, $synchronizefrom = 'all', $synchronizeto = 'A12', &$errors) +{ + global $getID3; - set_time_limit(30); + set_time_limit(30); - $ThisFileInfo = $getID3->analyze($filename); - getid3_lib::CopyTagsToComments($ThisFileInfo); + $ThisFileInfo = $getID3->analyze($filename); + getid3_lib::CopyTagsToComments($ThisFileInfo); - if ($synchronizefrom == 'all') { - $SourceArray = (!empty($ThisFileInfo['comments']) ? $ThisFileInfo['comments'] : array()); - } elseif (!empty($ThisFileInfo['tags'][$synchronizefrom])) { - $SourceArray = (!empty($ThisFileInfo['tags'][$synchronizefrom]) ? $ThisFileInfo['tags'][$synchronizefrom] : array()); - } else { - die('ERROR: $ThisFileInfo[tags]['.$synchronizefrom.'] does not exist'); - } + if ($synchronizefrom == 'all') { + $SourceArray = (!empty($ThisFileInfo['comments']) ? $ThisFileInfo['comments'] : []); + } elseif (!empty($ThisFileInfo['tags'][$synchronizefrom])) { + $SourceArray = (!empty($ThisFileInfo['tags'][$synchronizefrom]) ? $ThisFileInfo['tags'][$synchronizefrom] : []); + } else { + die('ERROR: $ThisFileInfo[tags]['.$synchronizefrom.'] does not exist'); + } - $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($filename).'")'; - mysql_query_safe($SQLquery); + $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($filename).'")'; + mysql_query_safe($SQLquery); - $TagFormatsToWrite = array(); - if ((strpos($synchronizeto, '2') !== false) && ($synchronizefrom != 'id3v2')) { - $TagFormatsToWrite[] = 'id3v2.3'; - } - if ((strpos($synchronizeto, 'A') !== false) && ($synchronizefrom != 'ape')) { - $TagFormatsToWrite[] = 'ape'; - } - if ((strpos($synchronizeto, 'L') !== false) && ($synchronizefrom != 'lyrics3')) { - $TagFormatsToWrite[] = 'lyrics3'; - } - if ((strpos($synchronizeto, '1') !== false) && ($synchronizefrom != 'id3v1')) { - $TagFormatsToWrite[] = 'id3v1'; - } + $TagFormatsToWrite = []; + if ((strpos($synchronizeto, '2') !== false) && ($synchronizefrom != 'id3v2')) { + $TagFormatsToWrite[] = 'id3v2.3'; + } + if ((strpos($synchronizeto, 'A') !== false) && ($synchronizefrom != 'ape')) { + $TagFormatsToWrite[] = 'ape'; + } + if ((strpos($synchronizeto, 'L') !== false) && ($synchronizefrom != 'lyrics3')) { + $TagFormatsToWrite[] = 'lyrics3'; + } + if ((strpos($synchronizeto, '1') !== false) && ($synchronizefrom != 'id3v1')) { + $TagFormatsToWrite[] = 'id3v1'; + } - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'write.php', __FILE__, true); - $tagwriter = new getid3_writetags; - $tagwriter->filename = $filename; - $tagwriter->tagformats = $TagFormatsToWrite; - $tagwriter->overwrite_tags = true; - $tagwriter->tag_encoding = $getID3->encoding; - $tagwriter->tag_data = $SourceArray; + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'write.php', __FILE__, true); + $tagwriter = new getid3_writetags; + $tagwriter->filename = $filename; + $tagwriter->tagformats = $TagFormatsToWrite; + $tagwriter->overwrite_tags = true; + $tagwriter->tag_encoding = $getID3->encoding; + $tagwriter->tag_data = $SourceArray; - if ($tagwriter->WriteTags()) { - $errors = $tagwriter->errors; - return true; - } - $errors = $tagwriter->errors; - return false; + if ($tagwriter->WriteTags()) { + $errors = $tagwriter->errors; + return true; + } + $errors = $tagwriter->errors; + return false; } -$IgnoreNoTagFormats = array('', 'png', 'jpg', 'gif', 'bmp', 'swf', 'pdf', 'zip', 'rar', 'mid', 'mod', 'xm', 'it', 's3m'); +$IgnoreNoTagFormats = ['', 'png', 'jpg', 'gif', 'bmp', 'swf', 'pdf', 'zip', 'rar', 'mid', 'mod', 'xm', 'it', 's3m']; if (!empty($_REQUEST['scan']) || !empty($_REQUEST['newscan']) || !empty($_REQUEST['rescanerrors'])) { + $SQLquery = 'DELETE from `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` = "")'; + mysql_query_safe($SQLquery); - $SQLquery = 'DELETE from `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` = "")'; - mysql_query_safe($SQLquery); + $FilesInDir = []; - $FilesInDir = array(); + if (!empty($_REQUEST['rescanerrors'])) { + echo 'abort
'; - if (!empty($_REQUEST['rescanerrors'])) { + echo 'Re-scanning all media files already in database that had errors and/or warnings in last scan
'; - echo 'abort
'; + $SQLquery = 'SELECT `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`error` <> "")'; + $SQLquery .= ' OR (`warning` <> "")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + while ($row = mysql_fetch_array($result)) { + if (!file_exists($row['filename'])) { + echo 'File missing: '.$row['filename'].'
'; + $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; + mysql_query_safe($SQLquery); + } else { + $FilesInDir[] = $row['filename']; + } + } + } elseif (!empty($_REQUEST['scan']) || !empty($_REQUEST['newscan'])) { + echo 'abort
'; - echo 'Re-scanning all media files already in database that had errors and/or warnings in last scan
'; + echo 'Scanning all media files in '.str_replace('\\', '/', realpath(!empty($_REQUEST['scan']) ? $_REQUEST['scan'] : $_REQUEST['newscan'])).' (and subdirectories)
'; - $SQLquery = 'SELECT `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`error` <> "")'; - $SQLquery .= ' OR (`warning` <> "")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - while ($row = mysql_fetch_array($result)) { + $SQLquery = 'SELECT COUNT(*) AS `num`, `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' GROUP BY `filename`'; + $SQLquery .= ' HAVING (`num` > 1)'; + $SQLquery .= ' ORDER BY `num` DESC'; + $result = mysql_query_safe($SQLquery); + $DupesDeleted = 0; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE `filename` LIKE "'.mysql_real_escape_string($row['filename']).'"'; + mysql_query_safe($SQLquery); + $DupesDeleted++; + } + if ($DupesDeleted > 0) { + echo 'Deleted '.number_format($DupesDeleted).' duplicate filenames
'; + } - if (!file_exists($row['filename'])) { - echo 'File missing: '.$row['filename'].'
'; - $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; - mysql_query_safe($SQLquery); - } else { - $FilesInDir[] = $row['filename']; - } + if (!empty($_REQUEST['newscan'])) { + $AlreadyInDatabase = []; + set_time_limit(60); + $SQLquery = 'SELECT `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + while ($row = mysql_fetch_array($result)) { + //$AlreadyInDatabase[] = strtolower($row['filename']); + $AlreadyInDatabase[] = $row['filename']; + } + } - } + $DirectoriesToScan = [!empty($_REQUEST['scan']) ? $_REQUEST['scan'] : $_REQUEST['newscan']]; + $DirectoriesScanned = []; + while (count($DirectoriesToScan) > 0) { + foreach ($DirectoriesToScan as $DirectoryKey => $startingdir) { + if ($dir = opendir($startingdir)) { + set_time_limit(30); + echo ''.str_replace('\\', '/', $startingdir).'
'; + flush(); + while (($file = readdir($dir)) !== false) { + if (($file != '.') && ($file != '..')) { + $RealPathName = realpath($startingdir.'/'.$file); + if (is_dir($RealPathName)) { + if (!in_array($RealPathName, $DirectoriesScanned) && !in_array($RealPathName, $DirectoriesToScan)) { + $DirectoriesToScan[] = $RealPathName; + } + } elseif (is_file($RealPathName)) { + if (!empty($_REQUEST['newscan'])) { + if (!in_array(str_replace('\\', '/', $RealPathName), $AlreadyInDatabase)) { + $FilesInDir[] = $RealPathName; + } + } elseif (!empty($_REQUEST['scan'])) { + $FilesInDir[] = $RealPathName; + } + } + } + } + closedir($dir); + } else { + echo '
Failed to open directory "'.htmlentities($startingdir).'"

'; + } + $DirectoriesScanned[] = $startingdir; + unset($DirectoriesToScan[$DirectoryKey]); + } + } + echo 'List of files to scan complete (added '.number_format(count($FilesInDir)).' files to scan)
'; + flush(); + } - } elseif (!empty($_REQUEST['scan']) || !empty($_REQUEST['newscan'])) { + $FilesInDir = array_unique($FilesInDir); + sort($FilesInDir); - echo 'abort
'; + $starttime = time(); + $rowcounter = 0; + $totaltoprocess = count($FilesInDir); - echo 'Scanning all media files in '.str_replace('\\', '/', realpath(!empty($_REQUEST['scan']) ? $_REQUEST['scan'] : $_REQUEST['newscan'])).' (and subdirectories)
'; + foreach ($FilesInDir as $filename) { + set_time_limit(300); - $SQLquery = 'SELECT COUNT(*) AS `num`, `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' GROUP BY `filename`'; - $SQLquery .= ' HAVING (`num` > 1)'; - $SQLquery .= ' ORDER BY `num` DESC'; - $result = mysql_query_safe($SQLquery); - $DupesDeleted = 0; - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE `filename` LIKE "'.mysql_real_escape_string($row['filename']).'"'; - mysql_query_safe($SQLquery); - $DupesDeleted++; - } - if ($DupesDeleted > 0) { - echo 'Deleted '.number_format($DupesDeleted).' duplicate filenames
'; - } + echo '
'.date('H:i:s').' ['.number_format(++$rowcounter).' / '.number_format($totaltoprocess).'] '.str_replace('\\', '/', $filename); - if (!empty($_REQUEST['newscan'])) { - $AlreadyInDatabase = array(); - set_time_limit(60); - $SQLquery = 'SELECT `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - while ($row = mysql_fetch_array($result)) { - //$AlreadyInDatabase[] = strtolower($row['filename']); - $AlreadyInDatabase[] = $row['filename']; - } - } + $ThisFileInfo = $getID3->analyze($filename); + getid3_lib::CopyTagsToComments($ThisFileInfo); - $DirectoriesToScan = array(!empty($_REQUEST['scan']) ? $_REQUEST['scan'] : $_REQUEST['newscan']); - $DirectoriesScanned = array(); - while (count($DirectoriesToScan) > 0) { - foreach ($DirectoriesToScan as $DirectoryKey => $startingdir) { - if ($dir = opendir($startingdir)) { - set_time_limit(30); - echo ''.str_replace('\\', '/', $startingdir).'
'; - flush(); - while (($file = readdir($dir)) !== false) { - if (($file != '.') && ($file != '..')) { - $RealPathName = realpath($startingdir.'/'.$file); - if (is_dir($RealPathName)) { - if (!in_array($RealPathName, $DirectoriesScanned) && !in_array($RealPathName, $DirectoriesToScan)) { - $DirectoriesToScan[] = $RealPathName; - } - } elseif (is_file($RealPathName)) { - if (!empty($_REQUEST['newscan'])) { - if (!in_array(str_replace('\\', '/', $RealPathName), $AlreadyInDatabase)) { - $FilesInDir[] = $RealPathName; - } - } elseif (!empty($_REQUEST['scan'])) { - $FilesInDir[] = $RealPathName; - } - } - } - } - closedir($dir); - } else { - echo '
Failed to open directory "'.htmlentities($startingdir).'"

'; - } - $DirectoriesScanned[] = $startingdir; - unset($DirectoriesToScan[$DirectoryKey]); - } - } - echo 'List of files to scan complete (added '.number_format(count($FilesInDir)).' files to scan)
'; - flush(); - } + if (file_exists($filename)) { + $ThisFileInfo['file_modified_time'] = filemtime($filename); + $ThisFileInfo['md5_file'] = ($getid3_demo_mysql_md5_file ? md5_file($filename) : ''); + } - $FilesInDir = array_unique($FilesInDir); - sort($FilesInDir); + if (empty($ThisFileInfo['fileformat'])) { + echo ' (unknown file type)'; + } else { + if (!empty($ThisFileInfo['error'])) { + echo ' (errors)'; + } elseif (!empty($ThisFileInfo['warning'])) { + echo ' (warnings)'; + } else { + echo ' (OK)'; + } - $starttime = time(); - $rowcounter = 0; - $totaltoprocess = count($FilesInDir); + $this_track_track = ''; + if (!empty($ThisFileInfo['comments']['track'])) { + foreach ($ThisFileInfo['comments']['track'] as $key => $value) { + if (strlen($value) > strlen($this_track_track)) { + $this_track_track = str_pad($value, 2, '0', STR_PAD_LEFT); + } + } + if (preg_match('#^([0-9]+)/([0-9]+)$#', $this_track_track, $matches)) { + // change "1/5"->"01/05", "3/12"->"03/12", etc + $this_track_track = str_pad($matches[1], 2, '0', STR_PAD_LEFT).'/'.str_pad($matches[2], 2, '0', STR_PAD_LEFT); + } + } - foreach ($FilesInDir as $filename) { - set_time_limit(300); + $this_track_remix = ''; + $this_track_title = ''; + if (!empty($ThisFileInfo['comments']['title'])) { + foreach ($ThisFileInfo['comments']['title'] as $possible_title) { + if (strlen($possible_title) > strlen($this_track_title)) { + $this_track_title = $possible_title; + } + } + } - echo '
'.date('H:i:s').' ['.number_format(++$rowcounter).' / '.number_format($totaltoprocess).'] '.str_replace('\\', '/', $filename); - - $ThisFileInfo = $getID3->analyze($filename); - getid3_lib::CopyTagsToComments($ThisFileInfo); - - if (file_exists($filename)) { - $ThisFileInfo['file_modified_time'] = filemtime($filename); - $ThisFileInfo['md5_file'] = ($getid3_demo_mysql_md5_file ? md5_file($filename) : ''); - } - - if (empty($ThisFileInfo['fileformat'])) { - - echo ' (unknown file type)'; - - } else { - - if (!empty($ThisFileInfo['error'])) { - echo ' (errors)'; - } elseif (!empty($ThisFileInfo['warning'])) { - echo ' (warnings)'; - } else { - echo ' (OK)'; - } - - $this_track_track = ''; - if (!empty($ThisFileInfo['comments']['track'])) { - foreach ($ThisFileInfo['comments']['track'] as $key => $value) { - if (strlen($value) > strlen($this_track_track)) { - $this_track_track = str_pad($value, 2, '0', STR_PAD_LEFT); - } - } - if (preg_match('#^([0-9]+)/([0-9]+)$#', $this_track_track, $matches)) { - // change "1/5"->"01/05", "3/12"->"03/12", etc - $this_track_track = str_pad($matches[1], 2, '0', STR_PAD_LEFT).'/'.str_pad($matches[2], 2, '0', STR_PAD_LEFT); - } - } - - $this_track_remix = ''; - $this_track_title = ''; - if (!empty($ThisFileInfo['comments']['title'])) { - foreach ($ThisFileInfo['comments']['title'] as $possible_title) { - if (strlen($possible_title) > strlen($this_track_title)) { - $this_track_title = $possible_title; - } - } - } - - $ParenthesesPairs = array('()', '[]', '{}'); - foreach ($ParenthesesPairs as $pair) { - if (preg_match_all('/(.*) '.preg_quote($pair{0}).'(([^'.preg_quote($pair).']*[\- '.preg_quote($pair{0}).'])?(cut|dub|edit|version|live|reprise|[a-z]*mix))'.preg_quote($pair{1}).'/iU', $this_track_title, $matches)) { - $this_track_title = $matches[1][0]; - $this_track_remix = implode("\t", $matches[2]); - } - } + $ParenthesesPairs = ['()', '[]', '{}']; + foreach ($ParenthesesPairs as $pair) { + if (preg_match_all('/(.*) '.preg_quote($pair{0}).'(([^'.preg_quote($pair).']*[\- '.preg_quote($pair{0}).'])?(cut|dub|edit|version|live|reprise|[a-z]*mix))'.preg_quote($pair{1}).'/iU', $this_track_title, $matches)) { + $this_track_title = $matches[1][0]; + $this_track_remix = implode("\t", $matches[2]); + } + } - if (!empty($_REQUEST['rescanerrors'])) { + if (!empty($_REQUEST['rescanerrors'])) { + $SQLquery = 'UPDATE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` SET '; + $SQLquery .= ' `last_modified` = "'. mysql_real_escape_string(!empty($ThisFileInfo['file_modified_time']) ? $ThisFileInfo['file_modified_time'] : '').'"'; + $SQLquery .= ', `md5_file` = "'. mysql_real_escape_string(!empty($ThisFileInfo['md5_file']) ? $ThisFileInfo['md5_file'] : '').'"'; + $SQLquery .= ', `md5_data` = "'. mysql_real_escape_string(!empty($ThisFileInfo['md5_data']) ? $ThisFileInfo['md5_data'] : '').'"'; + $SQLquery .= ', `md5_data_source` = "'. mysql_real_escape_string(!empty($ThisFileInfo['md5_data_source']) ? $ThisFileInfo['md5_data_source'] : '').'"'; + $SQLquery .= ', `filesize` = "'. mysql_real_escape_string(!empty($ThisFileInfo['filesize']) ? $ThisFileInfo['filesize'] : 0).'"'; + $SQLquery .= ', `fileformat` = "'. mysql_real_escape_string(!empty($ThisFileInfo['fileformat']) ? $ThisFileInfo['fileformat'] : '').'"'; + $SQLquery .= ', `audio_dataformat` = "'.mysql_real_escape_string(!empty($ThisFileInfo['audio']['dataformat']) ? $ThisFileInfo['audio']['dataformat'] : '').'"'; + $SQLquery .= ', `video_dataformat` = "'.mysql_real_escape_string(!empty($ThisFileInfo['video']['dataformat']) ? $ThisFileInfo['video']['dataformat'] : '').'"'; + $SQLquery .= ', `vbr_method` = "'. mysql_real_escape_string(!empty($ThisFileInfo['mpeg']['audio']['VBR_method']) ? $ThisFileInfo['mpeg']['audio']['VBR_method'] : '').'"'; + $SQLquery .= ', `audio_bitrate` = "'. mysql_real_escape_string(!empty($ThisFileInfo['audio']['bitrate']) ? floatval($ThisFileInfo['audio']['bitrate']) : 0).'"'; + $SQLquery .= ', `video_bitrate` = "'. mysql_real_escape_string(!empty($ThisFileInfo['video']['bitrate']) ? floatval($ThisFileInfo['video']['bitrate']) : 0).'"'; + $SQLquery .= ', `playtime_seconds` = "'.mysql_real_escape_string(!empty($ThisFileInfo['playtime_seconds']) ? floatval($ThisFileInfo['playtime_seconds']) : 0).'"'; + $SQLquery .= ', `track_volume` = "'. mysql_real_escape_string(!empty($ThisFileInfo['replay_gain']['track']['volume']) ? floatval($ThisFileInfo['replay_gain']['track']['volume']) : 0).'"'; + $SQLquery .= ', `comments_all` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']) ? serialize($ThisFileInfo['comments']) : '').'"'; + $SQLquery .= ', `comments_id3v2` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v2']) ? serialize($ThisFileInfo['tags']['id3v2']) : '').'"'; + $SQLquery .= ', `comments_ape` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags']['ape']) ? serialize($ThisFileInfo['tags']['ape']) : '').'"'; + $SQLquery .= ', `comments_lyrics3` = "'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['lyrics3']) ? serialize($ThisFileInfo['tags']['lyrics3']) : '').'"'; + $SQLquery .= ', `comments_id3v1` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v1']) ? serialize($ThisFileInfo['tags']['id3v1']) : '').'"'; + $SQLquery .= ', `warning` = "'. mysql_real_escape_string(!empty($ThisFileInfo['warning']) ? implode("\t", $ThisFileInfo['warning']) : '').'"'; + $SQLquery .= ', `error` = "'. mysql_real_escape_string(!empty($ThisFileInfo['error']) ? implode("\t", $ThisFileInfo['error']) : '').'"'; + $SQLquery .= ', `album` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['album']) ? implode("\t", $ThisFileInfo['comments']['album']) : '').'"'; + $SQLquery .= ', `genre` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['genre']) ? implode("\t", $ThisFileInfo['comments']['genre']) : '').'"'; + $SQLquery .= ', `comment` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['comment']) ? implode("\t", $ThisFileInfo['comments']['comment']) : '').'"'; + $SQLquery .= ', `artist` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['artist']) ? implode("\t", $ThisFileInfo['comments']['artist']) : '').'"'; + $SQLquery .= ', `tags` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags']) ? implode("\t", array_keys($ThisFileInfo['tags'])) : '').'"'; + $SQLquery .= ', `encoder_options` = "'. mysql_real_escape_string(trim((!empty($ThisFileInfo['audio']['encoder']) ? $ThisFileInfo['audio']['encoder'] : '').' '.(!empty($ThisFileInfo['audio']['encoder_options']) ? $ThisFileInfo['audio']['encoder_options'] : ''))).'"'; + $SQLquery .= ', `title` = "'. mysql_real_escape_string($this_track_title).'"'; + $SQLquery .= ', `remix` = "'. mysql_real_escape_string($this_track_remix).'"'; + $SQLquery .= ', `track` = "'. mysql_real_escape_string($this_track_track).'"'; + $SQLquery .= 'WHERE (`filename` = "'. mysql_real_escape_string(isset($ThisFileInfo['filenamepath']) ? $ThisFileInfo['filenamepath'] : '').'")'; + } elseif (!empty($_REQUEST['scan']) || !empty($_REQUEST['newscan'])) { + //$SQLquery = 'INSERT INTO `'.mysql_real_escape_string(GETID3_DB_TABLE).'` (`filename`, `last_modified`, `md5_file`, `md5_data`, `md5_data_source`, `filesize`, `fileformat`, `audio_dataformat`, `video_dataformat`, `audio_bitrate`, `video_bitrate`, `playtime_seconds`, `artist`, `title`, `remix`, `album`, `genre`, `comment`, `track`, `comments_all`, `comments_id3v2`, `comments_ape`, `comments_lyrics3`, `comments_id3v1`, `warning`, `error`, `encoder_options`, `vbr_method`, `track_volume`) VALUES ('; + $SQLquery = 'INSERT INTO `'.mysql_real_escape_string(GETID3_DB_TABLE).'` (`filename`, `last_modified`, `md5_file`, `md5_data`, `md5_data_source`, `filesize`, `fileformat`, `audio_dataformat`, `video_dataformat`, `audio_bitrate`, `video_bitrate`, `playtime_seconds`, `tags`, `artist`, `title`, `remix`, `album`, `genre`, `comment`, `track`, `comments_all`, `comments_id3v2`, `comments_ape`, `comments_lyrics3`, `comments_id3v1`, `warning`, `error`, `encoder_options`, `vbr_method`, `track_volume`) VALUES ('; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['filenamepath']) ? $ThisFileInfo['filenamepath'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['file_modified_time']) ? $ThisFileInfo['file_modified_time'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['md5_file']) ? $ThisFileInfo['md5_file'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['md5_data']) ? $ThisFileInfo['md5_data'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['md5_data_source']) ? $ThisFileInfo['md5_data_source'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['filesize']) ? $ThisFileInfo['filesize'] : 0).'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['fileformat']) ? $ThisFileInfo['fileformat'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['audio']['dataformat']) ? $ThisFileInfo['audio']['dataformat'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['video']['dataformat']) ? $ThisFileInfo['video']['dataformat'] : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['audio']['bitrate']) ? floatval($ThisFileInfo['audio']['bitrate']) : 0).'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['video']['bitrate']) ? floatval($ThisFileInfo['video']['bitrate']) : 0).'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['playtime_seconds']) ? floatval($ThisFileInfo['playtime_seconds']) : 0).'", '; + //$SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags'] ) ? implode("\t", $ThisFileInfo['tags']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']) ? implode("\t", array_keys($ThisFileInfo['tags'])) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['artist']) ? implode("\t", $ThisFileInfo['comments']['artist']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string($this_track_title).'", '; + $SQLquery .= '"'.mysql_real_escape_string($this_track_remix).'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['album']) ? implode("\t", $ThisFileInfo['comments']['album']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['genre']) ? implode("\t", $ThisFileInfo['comments']['genre']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['comment']) ? implode("\t", $ThisFileInfo['comments']['comment']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string($this_track_track).'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']) ? serialize($ThisFileInfo['comments']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v2']) ? serialize($ThisFileInfo['tags']['id3v2']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['ape']) ? serialize($ThisFileInfo['tags']['ape']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['lyrics3']) ? serialize($ThisFileInfo['tags']['lyrics3']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v1']) ? serialize($ThisFileInfo['tags']['id3v1']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['warning']) ? implode("\t", $ThisFileInfo['warning']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['error']) ? implode("\t", $ThisFileInfo['error']) : '').'", '; + $SQLquery .= '"'.mysql_real_escape_string(trim((!empty($ThisFileInfo['audio']['encoder']) ? $ThisFileInfo['audio']['encoder'] : '').' '.(!empty($ThisFileInfo['audio']['encoder_options']) ? $ThisFileInfo['audio']['encoder_options'] : ''))).'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['mpeg']['audio']['LAME']) ? 'LAME' : (!empty($ThisFileInfo['mpeg']['audio']['VBR_method']) ? $ThisFileInfo['mpeg']['audio']['VBR_method'] : '')).'", '; + $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['replay_gain']['track']['volume']) ? floatval($ThisFileInfo['replay_gain']['track']['volume']) : 0).'")'; + } + flush(); + mysql_query_safe($SQLquery); + } + } - $SQLquery = 'UPDATE `'.mysql_real_escape_string(GETID3_DB_TABLE).'` SET '; - $SQLquery .= ' `last_modified` = "'. mysql_real_escape_string(!empty($ThisFileInfo['file_modified_time'] ) ? $ThisFileInfo['file_modified_time'] : '').'"'; - $SQLquery .= ', `md5_file` = "'. mysql_real_escape_string(!empty($ThisFileInfo['md5_file'] ) ? $ThisFileInfo['md5_file'] : '').'"'; - $SQLquery .= ', `md5_data` = "'. mysql_real_escape_string(!empty($ThisFileInfo['md5_data'] ) ? $ThisFileInfo['md5_data'] : '').'"'; - $SQLquery .= ', `md5_data_source` = "'. mysql_real_escape_string(!empty($ThisFileInfo['md5_data_source'] ) ? $ThisFileInfo['md5_data_source'] : '').'"'; - $SQLquery .= ', `filesize` = "'. mysql_real_escape_string(!empty($ThisFileInfo['filesize'] ) ? $ThisFileInfo['filesize'] : 0).'"'; - $SQLquery .= ', `fileformat` = "'. mysql_real_escape_string(!empty($ThisFileInfo['fileformat'] ) ? $ThisFileInfo['fileformat'] : '').'"'; - $SQLquery .= ', `audio_dataformat` = "'.mysql_real_escape_string(!empty($ThisFileInfo['audio']['dataformat'] ) ? $ThisFileInfo['audio']['dataformat'] : '').'"'; - $SQLquery .= ', `video_dataformat` = "'.mysql_real_escape_string(!empty($ThisFileInfo['video']['dataformat'] ) ? $ThisFileInfo['video']['dataformat'] : '').'"'; - $SQLquery .= ', `vbr_method` = "'. mysql_real_escape_string(!empty($ThisFileInfo['mpeg']['audio']['VBR_method'] ) ? $ThisFileInfo['mpeg']['audio']['VBR_method'] : '').'"'; - $SQLquery .= ', `audio_bitrate` = "'. mysql_real_escape_string(!empty($ThisFileInfo['audio']['bitrate'] ) ? floatval($ThisFileInfo['audio']['bitrate']) : 0).'"'; - $SQLquery .= ', `video_bitrate` = "'. mysql_real_escape_string(!empty($ThisFileInfo['video']['bitrate'] ) ? floatval($ThisFileInfo['video']['bitrate']) : 0).'"'; - $SQLquery .= ', `playtime_seconds` = "'.mysql_real_escape_string(!empty($ThisFileInfo['playtime_seconds'] ) ? floatval($ThisFileInfo['playtime_seconds']) : 0).'"'; - $SQLquery .= ', `track_volume` = "'. mysql_real_escape_string(!empty($ThisFileInfo['replay_gain']['track']['volume']) ? floatval($ThisFileInfo['replay_gain']['track']['volume']) : 0).'"'; - $SQLquery .= ', `comments_all` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments'] ) ? serialize($ThisFileInfo['comments']) : '').'"'; - $SQLquery .= ', `comments_id3v2` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v2'] ) ? serialize($ThisFileInfo['tags']['id3v2']) : '').'"'; - $SQLquery .= ', `comments_ape` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags']['ape'] ) ? serialize($ThisFileInfo['tags']['ape']) : '').'"'; - $SQLquery .= ', `comments_lyrics3` = "'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['lyrics3'] ) ? serialize($ThisFileInfo['tags']['lyrics3']) : '').'"'; - $SQLquery .= ', `comments_id3v1` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v1'] ) ? serialize($ThisFileInfo['tags']['id3v1']) : '').'"'; - $SQLquery .= ', `warning` = "'. mysql_real_escape_string(!empty($ThisFileInfo['warning'] ) ? implode("\t", $ThisFileInfo['warning']) : '').'"'; - $SQLquery .= ', `error` = "'. mysql_real_escape_string(!empty($ThisFileInfo['error'] ) ? implode("\t", $ThisFileInfo['error']) : '').'"'; - $SQLquery .= ', `album` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['album'] ) ? implode("\t", $ThisFileInfo['comments']['album']) : '').'"'; - $SQLquery .= ', `genre` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['genre'] ) ? implode("\t", $ThisFileInfo['comments']['genre']) : '').'"'; - $SQLquery .= ', `comment` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['comment'] ) ? implode("\t", $ThisFileInfo['comments']['comment']) : '').'"'; - $SQLquery .= ', `artist` = "'. mysql_real_escape_string(!empty($ThisFileInfo['comments']['artist'] ) ? implode("\t", $ThisFileInfo['comments']['artist']) : '').'"'; - $SQLquery .= ', `tags` = "'. mysql_real_escape_string(!empty($ThisFileInfo['tags'] ) ? implode("\t", array_keys($ThisFileInfo['tags'])) : '').'"'; - $SQLquery .= ', `encoder_options` = "'. mysql_real_escape_string(trim((!empty($ThisFileInfo['audio']['encoder']) ? $ThisFileInfo['audio']['encoder'] : '').' '.(!empty($ThisFileInfo['audio']['encoder_options']) ? $ThisFileInfo['audio']['encoder_options'] : ''))).'"'; - $SQLquery .= ', `title` = "'. mysql_real_escape_string($this_track_title).'"'; - $SQLquery .= ', `remix` = "'. mysql_real_escape_string($this_track_remix).'"'; - $SQLquery .= ', `track` = "'. mysql_real_escape_string($this_track_track).'"'; - $SQLquery .= 'WHERE (`filename` = "'. mysql_real_escape_string(isset($ThisFileInfo['filenamepath']) ? $ThisFileInfo['filenamepath'] : '').'")'; - - } elseif (!empty($_REQUEST['scan']) || !empty($_REQUEST['newscan'])) { - - //$SQLquery = 'INSERT INTO `'.mysql_real_escape_string(GETID3_DB_TABLE).'` (`filename`, `last_modified`, `md5_file`, `md5_data`, `md5_data_source`, `filesize`, `fileformat`, `audio_dataformat`, `video_dataformat`, `audio_bitrate`, `video_bitrate`, `playtime_seconds`, `artist`, `title`, `remix`, `album`, `genre`, `comment`, `track`, `comments_all`, `comments_id3v2`, `comments_ape`, `comments_lyrics3`, `comments_id3v1`, `warning`, `error`, `encoder_options`, `vbr_method`, `track_volume`) VALUES ('; - $SQLquery = 'INSERT INTO `'.mysql_real_escape_string(GETID3_DB_TABLE).'` (`filename`, `last_modified`, `md5_file`, `md5_data`, `md5_data_source`, `filesize`, `fileformat`, `audio_dataformat`, `video_dataformat`, `audio_bitrate`, `video_bitrate`, `playtime_seconds`, `tags`, `artist`, `title`, `remix`, `album`, `genre`, `comment`, `track`, `comments_all`, `comments_id3v2`, `comments_ape`, `comments_lyrics3`, `comments_id3v1`, `warning`, `error`, `encoder_options`, `vbr_method`, `track_volume`) VALUES ('; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['filenamepath'] ) ? $ThisFileInfo['filenamepath'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['file_modified_time'] ) ? $ThisFileInfo['file_modified_time'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['md5_file'] ) ? $ThisFileInfo['md5_file'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['md5_data'] ) ? $ThisFileInfo['md5_data'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['md5_data_source'] ) ? $ThisFileInfo['md5_data_source'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['filesize'] ) ? $ThisFileInfo['filesize'] : 0).'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['fileformat'] ) ? $ThisFileInfo['fileformat'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['audio']['dataformat'] ) ? $ThisFileInfo['audio']['dataformat'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['video']['dataformat'] ) ? $ThisFileInfo['video']['dataformat'] : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['audio']['bitrate'] ) ? floatval($ThisFileInfo['audio']['bitrate']) : 0).'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['video']['bitrate'] ) ? floatval($ThisFileInfo['video']['bitrate']) : 0).'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['playtime_seconds'] ) ? floatval($ThisFileInfo['playtime_seconds']) : 0).'", '; - //$SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags'] ) ? implode("\t", $ThisFileInfo['tags']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags'] ) ? implode("\t", array_keys($ThisFileInfo['tags'])) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['artist'] ) ? implode("\t", $ThisFileInfo['comments']['artist']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string($this_track_title).'", '; - $SQLquery .= '"'.mysql_real_escape_string($this_track_remix).'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['album'] ) ? implode("\t", $ThisFileInfo['comments']['album']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['genre'] ) ? implode("\t", $ThisFileInfo['comments']['genre']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments']['comment'] ) ? implode("\t", $ThisFileInfo['comments']['comment']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string($this_track_track).'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['comments'] ) ? serialize($ThisFileInfo['comments']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v2'] ) ? serialize($ThisFileInfo['tags']['id3v2']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['ape'] ) ? serialize($ThisFileInfo['tags']['ape']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['lyrics3'] ) ? serialize($ThisFileInfo['tags']['lyrics3']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['tags']['id3v1'] ) ? serialize($ThisFileInfo['tags']['id3v1']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['warning'] ) ? implode("\t", $ThisFileInfo['warning']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['error'] ) ? implode("\t", $ThisFileInfo['error']) : '').'", '; - $SQLquery .= '"'.mysql_real_escape_string(trim((!empty($ThisFileInfo['audio']['encoder']) ? $ThisFileInfo['audio']['encoder'] : '').' '.(!empty($ThisFileInfo['audio']['encoder_options']) ? $ThisFileInfo['audio']['encoder_options'] : ''))).'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['mpeg']['audio']['LAME']) ? 'LAME' : (!empty($ThisFileInfo['mpeg']['audio']['VBR_method']) ? $ThisFileInfo['mpeg']['audio']['VBR_method'] : '')).'", '; - $SQLquery .= '"'.mysql_real_escape_string(!empty($ThisFileInfo['replay_gain']['track']['volume']) ? floatval($ThisFileInfo['replay_gain']['track']['volume']) : 0).'")'; - - } - flush(); - mysql_query_safe($SQLquery); - } - - } - - $SQLquery = 'OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - mysql_query_safe($SQLquery); - - echo '
Done scanning!
'; + $SQLquery = 'OPTIMIZE TABLE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + mysql_query_safe($SQLquery); + echo '
Done scanning!
'; } elseif (!empty($_REQUEST['missingtrackvolume'])) { - - $MissingTrackVolumeFilesScanned = 0; - $MissingTrackVolumeFilesAdjusted = 0; - $MissingTrackVolumeFilesDeleted = 0; - $SQLquery = 'SELECT `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`track_volume` = 0)'; - $SQLquery .= ' AND (`audio_bitrate` > 0)'; - $result = mysql_query_safe($SQLquery); - echo 'Scanning 0 / '.number_format(mysql_num_rows($result)).' files for track volume information:
'; - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - echo '. '; - flush(); - if (file_exists($row['filename'])) { - - $ThisFileInfo = $getID3->analyze($row['filename']); - if (!empty($ThisFileInfo['replay_gain']['track']['volume'])) { - $MissingTrackVolumeFilesAdjusted++; - $SQLquery = 'UPDATE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' SET `track_volume` = "'.$ThisFileInfo['replay_gain']['track']['volume'].'"'; - $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; - mysql_query_safe($SQLquery); - } - - } else { - - $MissingTrackVolumeFilesDeleted++; - $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; - mysql_query_safe($SQLquery); - - } - } - echo '
Scanned '.number_format($MissingTrackVolumeFilesScanned).' files with no track volume information.
'; - echo 'Found track volume information for '.number_format($MissingTrackVolumeFilesAdjusted).' of them (could not find info for '.number_format($MissingTrackVolumeFilesScanned - $MissingTrackVolumeFilesAdjusted).' files; deleted '.number_format($MissingTrackVolumeFilesDeleted).' records of missing files)
'; - + $MissingTrackVolumeFilesScanned = 0; + $MissingTrackVolumeFilesAdjusted = 0; + $MissingTrackVolumeFilesDeleted = 0; + $SQLquery = 'SELECT `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`track_volume` = 0)'; + $SQLquery .= ' AND (`audio_bitrate` > 0)'; + $result = mysql_query_safe($SQLquery); + echo 'Scanning 0 / '.number_format(mysql_num_rows($result)).' files for track volume information:
'; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + echo '. '; + flush(); + if (file_exists($row['filename'])) { + $ThisFileInfo = $getID3->analyze($row['filename']); + if (!empty($ThisFileInfo['replay_gain']['track']['volume'])) { + $MissingTrackVolumeFilesAdjusted++; + $SQLquery = 'UPDATE `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' SET `track_volume` = "'.$ThisFileInfo['replay_gain']['track']['volume'].'"'; + $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; + mysql_query_safe($SQLquery); + } + } else { + $MissingTrackVolumeFilesDeleted++; + $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; + mysql_query_safe($SQLquery); + } + } + echo '
Scanned '.number_format($MissingTrackVolumeFilesScanned).' files with no track volume information.
'; + echo 'Found track volume information for '.number_format($MissingTrackVolumeFilesAdjusted).' of them (could not find info for '.number_format($MissingTrackVolumeFilesScanned - $MissingTrackVolumeFilesAdjusted).' files; deleted '.number_format($MissingTrackVolumeFilesDeleted).' records of missing files)
'; } elseif (!empty($_REQUEST['deadfilescheck'])) { + $SQLquery = 'SELECT COUNT(*) AS `num`, `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' GROUP BY `filename`'; + $SQLquery .= ' ORDER BY `num` DESC'; + $result = mysql_query_safe($SQLquery); + $DupesDeleted = 0; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + if ($row['num'] <= 1) { + break; + } + echo '
'.htmlentities($row['filename']).' (duplicate)'; + $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE `filename` LIKE "'.mysql_real_escape_string($row['filename']).'"'; + mysql_query_safe($SQLquery); + $DupesDeleted++; + } + if ($DupesDeleted > 0) { + echo '
Deleted '.number_format($DupesDeleted).' duplicate filenames
'; + } - $SQLquery = 'SELECT COUNT(*) AS `num`, `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' GROUP BY `filename`'; - $SQLquery .= ' ORDER BY `num` DESC'; - $result = mysql_query_safe($SQLquery); - $DupesDeleted = 0; - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - if ($row['num'] <= 1) { - break; - } - echo '
'.htmlentities($row['filename']).' (duplicate)'; - $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE `filename` LIKE "'.mysql_real_escape_string($row['filename']).'"'; - mysql_query_safe($SQLquery); - $DupesDeleted++; - } - if ($DupesDeleted > 0) { - echo '
Deleted '.number_format($DupesDeleted).' duplicate filenames
'; - } + $SQLquery = 'SELECT `filename`, `filesize`, `last_modified`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + $totalchecked = 0; + $totalremoved = 0; + $previousdir = ''; + while ($row = mysql_fetch_array($result)) { + $totalchecked++; + set_time_limit(30); + $reason = ''; + if (!file_exists($row['filename'])) { + $reason = 'deleted'; + } elseif (filesize($row['filename']) != $row['filesize']) { + $reason = 'filesize changed'; + } elseif (filemtime($row['filename']) != $row['last_modified']) { + if (abs(filemtime($row['filename']) - $row['last_modified']) != 3600) { + // off by exactly one hour == daylight savings time + $reason = 'last-modified time changed'; + } + } - $SQLquery = 'SELECT `filename`, `filesize`, `last_modified`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - $totalchecked = 0; - $totalremoved = 0; - $previousdir = ''; - while ($row = mysql_fetch_array($result)) { - $totalchecked++; - set_time_limit(30); - $reason = ''; - if (!file_exists($row['filename'])) { - $reason = 'deleted'; - } elseif (filesize($row['filename']) != $row['filesize']) { - $reason = 'filesize changed'; - } elseif (filemtime($row['filename']) != $row['last_modified']) { - if (abs(filemtime($row['filename']) - $row['last_modified']) != 3600) { - // off by exactly one hour == daylight savings time - $reason = 'last-modified time changed'; - } - } - - $thisdir = dirname($row['filename']); - if ($reason) { - - $totalremoved++; - echo '
'.htmlentities($row['filename']).' ('.$reason.')'; - flush(); - $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; - mysql_query_safe($SQLquery); - - } elseif ($thisdir != $previousdir) { - - echo '. '; - flush(); - - } - $previousdir = $thisdir; - } - - echo '
'.number_format($totalremoved).' of '.number_format($totalchecked).' files in database no longer exist, or have been altered since last scan. Removed from database.
'; + $thisdir = dirname($row['filename']); + if ($reason) { + $totalremoved++; + echo '
'.htmlentities($row['filename']).' ('.$reason.')'; + flush(); + $SQLquery = 'DELETE FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`filename` = "'.mysql_real_escape_string($row['filename']).'")'; + mysql_query_safe($SQLquery); + } elseif ($thisdir != $previousdir) { + echo '. '; + flush(); + } + $previousdir = $thisdir; + } + echo '
'.number_format($totalremoved).' of '.number_format($totalchecked).' files in database no longer exist, or have been altered since last scan. Removed from database.
'; } elseif (!empty($_REQUEST['encodedbydistribution'])) { + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - - $SQLquery = 'SELECT `filename`, `comments_id3v2`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`encoder_options` = "'.mysql_real_escape_string($_REQUEST['encodedbydistribution']).'")'; - $result = mysql_query_safe($SQLquery); - $NonBlankEncodedBy = ''; - $BlankEncodedBy = ''; - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - $CommentArray = unserialize($row['comments_id3v2']); - if (isset($CommentArray['encoded_by'][0])) { - $NonBlankEncodedBy .= WindowsShareSlashTranslate($row['filename'])."\n"; - } else { - $BlankEncodedBy .= WindowsShareSlashTranslate($row['filename'])."\n"; - } - } - echo $NonBlankEncodedBy; - echo $BlankEncodedBy; - exit; - - } elseif (!empty($_REQUEST['showfiles'])) { - - echo 'show all
'; - echo ''; - - $SQLquery = 'SELECT `filename`, `comments_id3v2`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $result = mysql_query_safe($SQLquery); - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - $CommentArray = unserialize($row['comments_id3v2']); - if (($_REQUEST['encodedbydistribution'] == '%') || (!empty($CommentArray['encoded_by'][0]) && ($_REQUEST['encodedbydistribution'] == $CommentArray['encoded_by'][0]))) { - echo ''; - echo ''; - } - } - echo '
m3u'.htmlentities($row['filename']).'
'; - - } else { - - $SQLquery = 'SELECT `encoder_options`, `comments_id3v2`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' ORDER BY (`encoder_options` LIKE "LAME%") DESC, (`encoder_options` LIKE "CBR%") DESC'; - $result = mysql_query_safe($SQLquery); - $EncodedBy = array(); - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - $CommentArray = unserialize($row['comments_id3v2']); - if (isset($CommentArray['encoded_by'][0])) { - if (isset($EncodedBy[$row['encoder_options']][$CommentArray['encoded_by'][0]])) { - $EncodedBy[$row['encoder_options']][$CommentArray['encoded_by'][0]]++; - } else { - $EncodedBy[$row['encoder_options']][$CommentArray['encoded_by'][0]] = 1; - } - } - } - echo '.m3u version
'; - echo ''; - foreach ($EncodedBy as $key => $value) { - echo ''; - echo ''; - echo ''; - } - echo '
m3uEncoder OptionsEncoded By (ID3v2)
m3u'.$key.''; - arsort($value); - foreach ($value as $string => $count) { - echo ''; - echo ''; - } - echo '
'.number_format($count).' '.$string.'
'; - - } + $SQLquery = 'SELECT `filename`, `comments_id3v2`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`encoder_options` = "'.mysql_real_escape_string($_REQUEST['encodedbydistribution']).'")'; + $result = mysql_query_safe($SQLquery); + $NonBlankEncodedBy = ''; + $BlankEncodedBy = ''; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + $CommentArray = unserialize($row['comments_id3v2']); + if (isset($CommentArray['encoded_by'][0])) { + $NonBlankEncodedBy .= WindowsShareSlashTranslate($row['filename'])."\n"; + } else { + $BlankEncodedBy .= WindowsShareSlashTranslate($row['filename'])."\n"; + } + } + echo $NonBlankEncodedBy; + echo $BlankEncodedBy; + exit; + } elseif (!empty($_REQUEST['showfiles'])) { + echo 'show all
'; + echo ''; + $SQLquery = 'SELECT `filename`, `comments_id3v2`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $result = mysql_query_safe($SQLquery); + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + $CommentArray = unserialize($row['comments_id3v2']); + if (($_REQUEST['encodedbydistribution'] == '%') || (!empty($CommentArray['encoded_by'][0]) && ($_REQUEST['encodedbydistribution'] == $CommentArray['encoded_by'][0]))) { + echo ''; + echo ''; + } + } + echo '
m3u'.htmlentities($row['filename']).'
'; + } else { + $SQLquery = 'SELECT `encoder_options`, `comments_id3v2`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' ORDER BY (`encoder_options` LIKE "LAME%") DESC, (`encoder_options` LIKE "CBR%") DESC'; + $result = mysql_query_safe($SQLquery); + $EncodedBy = []; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + $CommentArray = unserialize($row['comments_id3v2']); + if (isset($CommentArray['encoded_by'][0])) { + if (isset($EncodedBy[$row['encoder_options']][$CommentArray['encoded_by'][0]])) { + $EncodedBy[$row['encoder_options']][$CommentArray['encoded_by'][0]]++; + } else { + $EncodedBy[$row['encoder_options']][$CommentArray['encoded_by'][0]] = 1; + } + } + } + echo '.m3u version
'; + echo ''; + foreach ($EncodedBy as $key => $value) { + echo ''; + echo ''; + echo ''; + } + echo '
m3uEncoder OptionsEncoded By (ID3v2)
m3u'.$key.''; + arsort($value); + foreach ($value as $string => $count) { + echo ''; + echo ''; + } + echo '
'.number_format($count).' '.$string.'
'; + } } elseif (!empty($_REQUEST['audiobitrates'])) { + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.mp3.php', __FILE__, true); + $BitrateDistribution = []; + $SQLquery = 'SELECT ROUND(audio_bitrate / 1000) AS `RoundBitrate`, COUNT(*) AS `num`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`audio_bitrate` > 0)'; + $SQLquery .= ' GROUP BY `RoundBitrate`'; + $result = mysql_query_safe($SQLquery); + while ($row = mysql_fetch_array($result)) { + $this_bitrate = getid3_mp3::ClosestStandardMP3Bitrate($row['RoundBitrate'] * 1000); + if (isset($BitrateDistribution[$this_bitrate])) { + $BitrateDistribution[$this_bitrate] += $row['num']; + } else { + $BitrateDistribution[$this_bitrate] = $row['num']; + } + } - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.mp3.php', __FILE__, true); - $BitrateDistribution = array(); - $SQLquery = 'SELECT ROUND(audio_bitrate / 1000) AS `RoundBitrate`, COUNT(*) AS `num`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`audio_bitrate` > 0)'; - $SQLquery .= ' GROUP BY `RoundBitrate`'; - $result = mysql_query_safe($SQLquery); - while ($row = mysql_fetch_array($result)) { - $this_bitrate = getid3_mp3::ClosestStandardMP3Bitrate($row['RoundBitrate'] * 1000); - if (isset($BitrateDistribution[$this_bitrate])) { - $BitrateDistribution[$this_bitrate] += $row['num']; - } else { - $BitrateDistribution[$this_bitrate] = $row['num']; - } - } - - echo ''; - echo ''; - foreach ($BitrateDistribution as $Bitrate => $Count) { - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
BitrateCount
'.round($Bitrate / 1000).' kbps'.number_format($Count).'
'; - - + echo ''; + echo ''; + foreach ($BitrateDistribution as $Bitrate => $Count) { + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
BitrateCount
'.round($Bitrate / 1000).' kbps'.number_format($Count).'
'; } elseif (!empty($_REQUEST['emptygenres'])) { + $SQLquery = 'SELECT `fileformat`, `filename`, `genre`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`genre` = "")'; + $SQLquery .= ' OR (`genre` = "Unknown")'; + $SQLquery .= ' OR (`genre` = "Other")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); - $SQLquery = 'SELECT `fileformat`, `filename`, `genre`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`genre` = "")'; - $SQLquery .= ' OR (`genre` = "Unknown")'; - $SQLquery .= ' OR (`genre` = "Other")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - if (!in_array($row['fileformat'], $IgnoreNoTagFormats)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - } - exit; - - } else { - - echo '.m3u version
'; - $EmptyGenreCounter = 0; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - if (!in_array($row['fileformat'], $IgnoreNoTagFormats)) { - $EmptyGenreCounter++; - echo ''; - echo ''; - echo ''; - echo ''; - } - } - echo '
m3ufilename
m3u'.htmlentities($row['filename']).'
'; - echo ''.number_format($EmptyGenreCounter).' files with empty genres'; - - } - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + if (!in_array($row['fileformat'], $IgnoreNoTagFormats)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + } + exit; + } else { + echo '.m3u version
'; + $EmptyGenreCounter = 0; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + if (!in_array($row['fileformat'], $IgnoreNoTagFormats)) { + $EmptyGenreCounter++; + echo ''; + echo ''; + echo ''; + echo ''; + } + } + echo '
m3ufilename
m3u'.htmlentities($row['filename']).'
'; + echo ''.number_format($EmptyGenreCounter).' files with empty genres'; + } } elseif (!empty($_REQUEST['nonemptycomments'])) { + $SQLquery = 'SELECT `filename`, `comment`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`comment` <> "")'; + $SQLquery .= ' ORDER BY `comment` ASC'; + $result = mysql_query_safe($SQLquery); - $SQLquery = 'SELECT `filename`, `comment`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`comment` <> "")'; - $SQLquery .= ' ORDER BY `comment` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } else { - - $NonEmptyCommentsCounter = 0; - echo '.m3u version
'; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - $NonEmptyCommentsCounter++; - echo ''; - echo ''; - echo ''; - if (strlen(trim($row['comment'])) > 0) { - echo ''; - } else { - echo ''; - } - echo ''; - } - echo '
m3ufilenamecomments
m3u'.htmlentities($row['filename']).''.htmlentities($row['comment']).'space
'; - echo ''.number_format($NonEmptyCommentsCounter).' files with non-empty comments'; - - } - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } else { + $NonEmptyCommentsCounter = 0; + echo '.m3u version
'; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + $NonEmptyCommentsCounter++; + echo ''; + echo ''; + echo ''; + if (strlen(trim($row['comment'])) > 0) { + echo ''; + } else { + echo ''; + } + echo ''; + } + echo '
m3ufilenamecomments
m3u'.htmlentities($row['filename']).''.htmlentities($row['comment']).'space
'; + echo ''.number_format($NonEmptyCommentsCounter).' files with non-empty comments'; + } } elseif (!empty($_REQUEST['trackzero'])) { + $SQLquery = 'SELECT `filename`, `track`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`track` <> "")'; + $SQLquery .= ' AND ((`track` < "1")'; + $SQLquery .= ' OR (`track` > "99"))'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); - $SQLquery = 'SELECT `filename`, `track`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`track` <> "")'; - $SQLquery .= ' AND ((`track` < "1")'; - $SQLquery .= ' OR (`track` > "99"))'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - if ((strlen($row['track']) > 0) && ($row['track'] < 1) || ($row['track'] > 99)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - } - exit; - - } else { - - echo '.m3u version
'; - $TrackZeroCounter = 0; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - if ((strlen($row['track']) > 0) && ($row['track'] < 1) || ($row['track'] > 99)) { - $TrackZeroCounter++; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - } - echo '
m3ufilenametrack
m3u'.htmlentities($row['filename']).''.htmlentities($row['track']).'
'; - echo ''.number_format($TrackZeroCounter).' files with track "zero"'; - - } - - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + if ((strlen($row['track']) > 0) && ($row['track'] < 1) || ($row['track'] > 99)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + } + exit; + } else { + echo '.m3u version
'; + $TrackZeroCounter = 0; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + if ((strlen($row['track']) > 0) && ($row['track'] < 1) || ($row['track'] > 99)) { + $TrackZeroCounter++; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + } + echo '
m3ufilenametrack
m3u'.htmlentities($row['filename']).''.htmlentities($row['track']).'
'; + echo ''.number_format($TrackZeroCounter).' files with track "zero"'; + } } elseif (!empty($_REQUEST['titlefeat'])) { + $SQLquery = 'SELECT `filename`, `title`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`title` LIKE "%feat.%")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); - $SQLquery = 'SELECT `filename`, `title`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`title` LIKE "%feat.%")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } else { - - echo ''.number_format(mysql_num_rows($result)).' files with "feat." in the title (instead of the artist)

'; - echo '.m3u version
'; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
m3ufilenametitle
m3u'.htmlentities($row['filename']).''.preg_replace('#(feat\. .*)#i', '\\1', htmlentities($row['title'])).'
'; - - } - - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } else { + echo ''.number_format(mysql_num_rows($result)).' files with "feat." in the title (instead of the artist)

'; + echo '.m3u version
'; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
m3ufilenametitle
m3u'.htmlentities($row['filename']).''.preg_replace('#(feat\. .*)#i', '\\1', htmlentities($row['title'])).'
'; + } } elseif (!empty($_REQUEST['tracknoalbum'])) { + $SQLquery = 'SELECT `filename`, `track`, `album`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`track` <> "")'; + $SQLquery .= ' AND (`album` = "")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); - $SQLquery = 'SELECT `filename`, `track`, `album`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`track` <> "")'; - $SQLquery .= ' AND (`album` = "")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } else { - - echo ''.number_format(mysql_num_rows($result)).' files with a track number, but no album

'; - echo '.m3u version
'; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
m3ufilenametrackalbum
m3u'.htmlentities($row['filename']).''.htmlentities($row['track']).''.htmlentities($row['album']).'
'; - - } - - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } else { + echo ''.number_format(mysql_num_rows($result)).' files with a track number, but no album

'; + echo '.m3u version
'; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
m3ufilenametrackalbum
m3u'.htmlentities($row['filename']).''.htmlentities($row['track']).''.htmlentities($row['album']).'
'; + } } elseif (!empty($_REQUEST['synchronizetagsfrom']) && !empty($_REQUEST['filename'])) { - - echo 'Applying new tags from '.$_REQUEST['synchronizetagsfrom'].' in '.htmlentities($_REQUEST['filename']).'
    '; - $errors = array(); - if (SynchronizeAllTags($_REQUEST['filename'], $_REQUEST['synchronizetagsfrom'], 'A12', $errors)) { - echo '
  • Sucessfully wrote tags
  • '; - } else { - echo '
  • Tag writing had errors:
    • '.implode('
    • ', $errors).'
  • '; - } - echo '
'; - - + echo 'Applying new tags from '.$_REQUEST['synchronizetagsfrom'].' in '.htmlentities($_REQUEST['filename']).'
    '; + $errors = []; + if (SynchronizeAllTags($_REQUEST['filename'], $_REQUEST['synchronizetagsfrom'], 'A12', $errors)) { + echo '
  • Sucessfully wrote tags
  • '; + } else { + echo '
  • Tag writing had errors:
    • '.implode('
    • ', $errors).'
  • '; + } + echo '
'; } elseif (!empty($_REQUEST['unsynchronizedtags'])) { + $NotOKfiles = 0; + $Autofixedfiles = 0; + $FieldsToCompare = ['title', 'artist', 'album', 'year', 'genre', 'comment', 'track']; + $TagsToCompare = ['id3v2'=>false, 'ape'=>false, 'lyrics3'=>false, 'id3v1'=>false]; + $ID3v1FieldLengths = ['title'=>30, 'artist'=>30, 'album'=>30, 'year'=>4, 'genre'=>99, 'comment'=>28]; + if (strpos($_REQUEST['unsynchronizedtags'], '2') !== false) { + $TagsToCompare['id3v2'] = true; + } + if (strpos($_REQUEST['unsynchronizedtags'], 'A') !== false) { + $TagsToCompare['ape'] = true; + } + if (strpos($_REQUEST['unsynchronizedtags'], 'L') !== false) { + $TagsToCompare['lyrics3'] = true; + } + if (strpos($_REQUEST['unsynchronizedtags'], '1') !== false) { + $TagsToCompare['id3v1'] = true; + } - $NotOKfiles = 0; - $Autofixedfiles = 0; - $FieldsToCompare = array('title', 'artist', 'album', 'year', 'genre', 'comment', 'track'); - $TagsToCompare = array('id3v2'=>false, 'ape'=>false, 'lyrics3'=>false, 'id3v1'=>false); - $ID3v1FieldLengths = array('title'=>30, 'artist'=>30, 'album'=>30, 'year'=>4, 'genre'=>99, 'comment'=>28); - if (strpos($_REQUEST['unsynchronizedtags'], '2') !== false) { - $TagsToCompare['id3v2'] = true; - } - if (strpos($_REQUEST['unsynchronizedtags'], 'A') !== false) { - $TagsToCompare['ape'] = true; - } - if (strpos($_REQUEST['unsynchronizedtags'], 'L') !== false) { - $TagsToCompare['lyrics3'] = true; - } - if (strpos($_REQUEST['unsynchronizedtags'], '1') !== false) { - $TagsToCompare['id3v1'] = true; - } + echo 'Auto-fix empty tags

'; + echo '
'; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + if ($TagsToCompare['id3v2']) { + echo ''; + } + if ($TagsToCompare['ape']) { + echo ''; + } + if ($TagsToCompare['lyrics3']) { + echo ''; + } + if ($TagsToCompare['id3v1']) { + echo ''; + } + echo ''; - echo 'Auto-fix empty tags

'; - echo '
'; - echo '
ViewFilenameCombinedID3v2APELyrics3ID3v1
'; - echo ''; - echo ''; - echo ''; - echo ''; - if ($TagsToCompare['id3v2']) { - echo ''; - } - if ($TagsToCompare['ape']) { - echo ''; - } - if ($TagsToCompare['lyrics3']) { - echo ''; - } - if ($TagsToCompare['id3v1']) { - echo ''; - } - echo ''; + $SQLquery = 'SELECT `filename`, `comments_all`, `comments_id3v2`, `comments_ape`, `comments_lyrics3`, `comments_id3v1`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` = "mp3")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + $lastdir = ''; + $serializedCommentsFields = ['all', 'id3v2', 'ape', 'lyrics3', 'id3v1']; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + if ($lastdir != dirname($row['filename'])) { + echo ''; + flush(); + } - $SQLquery = 'SELECT `filename`, `comments_all`, `comments_id3v2`, `comments_ape`, `comments_lyrics3`, `comments_id3v1`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` = "mp3")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - $lastdir = ''; - $serializedCommentsFields = array('all', 'id3v2', 'ape', 'lyrics3', 'id3v1'); - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - if ($lastdir != dirname($row['filename'])) { - echo ''; - flush(); - } + $FileOK = true; + $Mismatched = ['id3v2'=>false, 'ape'=>false, 'lyrics3'=>false, 'id3v1'=>false]; + $SemiMatched = ['id3v2'=>false, 'ape'=>false, 'lyrics3'=>false, 'id3v1'=>false]; + $EmptyTags = ['id3v2'=>true, 'ape'=>true, 'lyrics3'=>true, 'id3v1'=>true]; - $FileOK = true; - $Mismatched = array('id3v2'=>false, 'ape'=>false, 'lyrics3'=>false, 'id3v1'=>false); - $SemiMatched = array('id3v2'=>false, 'ape'=>false, 'lyrics3'=>false, 'id3v1'=>false); - $EmptyTags = array('id3v2'=>true, 'ape'=>true, 'lyrics3'=>true, 'id3v1'=>true); + foreach ($serializedCommentsFields as $field) { + $Comments[$field] = []; + ob_start(); + if ($unserialized = unserialize($row['comments_'.$field])) { + $Comments[$field] = $unserialized; + } + $errormessage = ob_get_contents(); + ob_end_clean(); + } - foreach ($serializedCommentsFields as $field) { - $Comments[$field] = array(); - ob_start(); - if ($unserialized = unserialize($row['comments_'.$field])) { - $Comments[$field] = $unserialized; - } - $errormessage = ob_get_contents(); - ob_end_clean(); - } + if (isset($Comments['ape']['tracknumber'])) { + $Comments['ape']['track'] = $Comments['ape']['tracknumber']; + unset($Comments['ape']['tracknumber']); + } + if (isset($Comments['ape']['track_number'])) { + $Comments['ape']['track'] = $Comments['ape']['track_number']; + unset($Comments['ape']['track_number']); + } + if (isset($Comments['id3v2']['track_number'])) { + $Comments['id3v2']['track'] = $Comments['id3v2']['track_number']; + unset($Comments['id3v2']['track_number']); + } + if (!empty($Comments['all']['track'])) { + $besttrack = ''; + foreach ($Comments['all']['track'] as $key => $value) { + if (strlen($value) > strlen($besttrack)) { + $besttrack = $value; + } + } + $Comments['all']['track'] = [0=>$besttrack]; + } - if (isset($Comments['ape']['tracknumber'])) { - $Comments['ape']['track'] = $Comments['ape']['tracknumber']; - unset($Comments['ape']['tracknumber']); - } - if (isset($Comments['ape']['track_number'])) { - $Comments['ape']['track'] = $Comments['ape']['track_number']; - unset($Comments['ape']['track_number']); - } - if (isset($Comments['id3v2']['track_number'])) { - $Comments['id3v2']['track'] = $Comments['id3v2']['track_number']; - unset($Comments['id3v2']['track_number']); - } - if (!empty($Comments['all']['track'])) { - $besttrack = ''; - foreach ($Comments['all']['track'] as $key => $value) { - if (strlen($value) > strlen($besttrack)) { - $besttrack = $value; - } - } - $Comments['all']['track'] = array(0=>$besttrack); - } + $ThisLine = ''; + $ThisLine .= ''; + $ThisLine .= ''; + $tagvalues = ''; + foreach ($FieldsToCompare as $fieldname) { + $tagvalues .= $fieldname.' = '.(!empty($Comments['all'][$fieldname]) ? implode(" \n", $Comments['all'][$fieldname]) : '')." \n"; + } + $ThisLine .= ''; + foreach ($TagsToCompare as $tagtype => $CompareThisTagType) { + if ($CompareThisTagType) { + $tagvalues = ''; + foreach ($FieldsToCompare as $fieldname) { + if ($tagtype == 'id3v1') { + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); + if (($fieldname == 'genre') && !empty($Comments['all'][$fieldname][0]) && !getid3_id3v1::LookupGenreID($Comments['all'][$fieldname][0])) { + // non-standard genres can never match, so just ignore + $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; + } elseif ($fieldname == 'comment') { + if (isset($Comments[$tagtype][$fieldname][0]) && isset($Comments['all'][$fieldname][0]) && (rtrim(substr($Comments[$tagtype][$fieldname][0], 0, 28)) != rtrim(substr($Comments['all'][$fieldname][0], 0, 28)))) { + $tagvalues .= $fieldname.' = [['.$Comments[$tagtype][$fieldname][0].']]'."\n"; + if (trim(strtolower(RemoveAccents(substr($Comments[$tagtype][$fieldname][0], 0, 28)))) == trim(strtolower(RemoveAccents(substr($Comments['all'][$fieldname][0], 0, 28))))) { + $SemiMatched[$tagtype] = true; + } else { + $Mismatched[$tagtype] = true; + } + $FileOK = false; + } else { + $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; + } + } elseif ($fieldname == 'track') { + // intval('01/20') == intval('1') + $trackA = (isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''); + $trackB = (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''); + if (intval($trackA) != intval($trackB)) { + $tagvalues .= $fieldname.' = [['.$trackA.']]'."\n"; + $Mismatched[$tagtype] = true; + $FileOK = false; + } else { + $tagvalues .= $fieldname.' = '.$trackA."\n"; + } + } elseif ((isset($Comments[$tagtype][$fieldname][0]) ? rtrim(substr($Comments[$tagtype][$fieldname][0], 0, 30)) : '') != (isset($Comments['all'][$fieldname][0]) ? rtrim(substr($Comments['all'][$fieldname][0], 0, 30)) : '')) { + $tagvalues .= $fieldname.' = [['.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '').']]'."\n"; + if (strtolower(RemoveAccents(trim(substr((isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''), 0, 30)))) == strtolower(RemoveAccents(trim(substr((isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''), 0, 30))))) { + $SemiMatched[$tagtype] = true; + } else { + $Mismatched[$tagtype] = true; + } + $FileOK = false; + if (!empty($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { + $EmptyTags[$tagtype] = false; + } + } else { + $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; + if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { + $EmptyTags[$tagtype] = false; + } + } + } elseif (($tagtype == 'ape') && ($fieldname == 'year')) { + if (((isset($Comments['ape']['date'][0]) ? $Comments['ape']['date'][0] : '') != (isset($Comments['all']['year'][0]) ? $Comments['all']['year'][0] : '')) && ((isset($Comments['ape']['year'][0]) ? $Comments['ape']['year'][0] : '') != (isset($Comments['all']['year'][0]) ? $Comments['all']['year'][0] : ''))) { + $tagvalues .= $fieldname.' = [['.(isset($Comments['ape']['date'][0]) ? $Comments['ape']['date'][0] : '').']]'."\n"; + $Mismatched[$tagtype] = true; + $FileOK = false; + if (isset($Comments['ape']['date'][0]) && (strlen(trim($Comments['ape']['date'][0])) > 0)) { + $EmptyTags[$tagtype] = false; + } + } else { + $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; + if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { + $EmptyTags[$tagtype] = false; + } + } + } elseif (($fieldname == 'genre') && !empty($Comments['all'][$fieldname]) && !empty($Comments[$tagtype][$fieldname]) && in_array($Comments[$tagtype][$fieldname][0], $Comments['all'][$fieldname])) { + $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; + if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { + $EmptyTags[$tagtype] = false; + } + } elseif ((isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '') != (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : '')) { + $skiptracknumberfield = false; + switch ($fieldname) { + case 'track': + case 'tracknumber': + case 'track_number': + $trackA = (isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''); + $trackB = (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''); + if (intval($trackA) == intval($trackB)) { + $skiptracknumberfield = true; + } + break; + } + if (!$skiptracknumberfield) { + $tagvalues .= $fieldname.' = [['.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '').']]'."\n"; + $tagA = (isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''); + $tagB = (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''); + if (trim(strtolower(RemoveAccents($tagA))) == trim(strtolower(RemoveAccents($tagB)))) { + $SemiMatched[$tagtype] = true; + } else { + $Mismatched[$tagtype] = true; + } + $FileOK = false; + if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { + $EmptyTags[$tagtype] = false; + } + } + } else { + $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; + if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { + $EmptyTags[$tagtype] = false; + } + } + } - $ThisLine = ''; - $ThisLine .= ''; - $ThisLine .= ''; - $tagvalues = ''; - foreach ($FieldsToCompare as $fieldname) { - $tagvalues .= $fieldname.' = '.(!empty($Comments['all'][$fieldname]) ? implode(" \n", $Comments['all'][$fieldname]) : '')." \n"; - } - $ThisLine .= ''; - foreach ($TagsToCompare as $tagtype => $CompareThisTagType) { - if ($CompareThisTagType) { - $tagvalues = ''; - foreach ($FieldsToCompare as $fieldname) { + if ($EmptyTags[$tagtype]) { + $FileOK = false; + $ThisLine .= ''; + } + } + $ThisLine .= ''; - if ($tagtype == 'id3v1') { + if (!$FileOK) { + $NotOKfiles++; - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); - if (($fieldname == 'genre') && !empty($Comments['all'][$fieldname][0]) && !getid3_id3v1::LookupGenreID($Comments['all'][$fieldname][0])) { + echo ''; + flush(); - // non-standard genres can never match, so just ignore - $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; + if (!empty($_REQUEST['autofix'])) { + $AnyMismatched = false; + foreach ($Mismatched as $key => $value) { + if ($value && ($EmptyTags["$key"] === false)) { + $AnyMismatched = true; + } + } + if ($AnyMismatched && empty($_REQUEST['autofixforcesource'])) { + echo $ThisLine; + } else { + $TagsToSynch = ''; + foreach ($EmptyTags as $key => $value) { + if ($value) { + switch ($key) { + case 'id3v1': + $TagsToSynch .= '1'; + break; + case 'id3v2': + $TagsToSynch .= '2'; + break; + case 'ape': + $TagsToSynch .= 'A'; + break; + } + } + } - } elseif ($fieldname == 'comment') { + $autofixforcesource = (!empty($_REQUEST['autofixforcesource']) ? $_REQUEST['autofixforcesource'] : 'all'); + $TagsToSynch = (!empty($_REQUEST['autofixforcedest']) ? $_REQUEST['autofixforcedest'] : $TagsToSynch); - if (isset($Comments[$tagtype][$fieldname][0]) && isset($Comments['all'][$fieldname][0]) && (rtrim(substr($Comments[$tagtype][$fieldname][0], 0, 28)) != rtrim(substr($Comments['all'][$fieldname][0], 0, 28)))) { - $tagvalues .= $fieldname.' = [['.$Comments[$tagtype][$fieldname][0].']]'."\n"; - if (trim(strtolower(RemoveAccents(substr($Comments[$tagtype][$fieldname][0], 0, 28)))) == trim(strtolower(RemoveAccents(substr($Comments['all'][$fieldname][0], 0, 28))))) { - $SemiMatched[$tagtype] = true; - } else { - $Mismatched[$tagtype] = true; - } - $FileOK = false; - } else { - $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; - } - - } elseif ($fieldname == 'track') { - - // intval('01/20') == intval('1') - $trackA = (isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''); - $trackB = (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''); - if (intval($trackA) != intval($trackB)) { - $tagvalues .= $fieldname.' = [['.$trackA.']]'."\n"; - $Mismatched[$tagtype] = true; - $FileOK = false; - } else { - $tagvalues .= $fieldname.' = '.$trackA."\n"; - } - - } elseif ((isset($Comments[$tagtype][$fieldname][0]) ? rtrim(substr($Comments[$tagtype][$fieldname][0], 0, 30)) : '') != (isset($Comments['all'][$fieldname][0]) ? rtrim(substr($Comments['all'][$fieldname][0], 0, 30)) : '')) { - - $tagvalues .= $fieldname.' = [['.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '').']]'."\n"; - if (strtolower(RemoveAccents(trim(substr((isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''), 0, 30)))) == strtolower(RemoveAccents(trim(substr((isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''), 0, 30))))) { - $SemiMatched[$tagtype] = true; - } else { - $Mismatched[$tagtype] = true; - } - $FileOK = false; - if (!empty($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { - $EmptyTags[$tagtype] = false; - } - - } else { - - $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; - if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { - $EmptyTags[$tagtype] = false; - } - - } - - } elseif (($tagtype == 'ape') && ($fieldname == 'year')) { - - if (((isset($Comments['ape']['date'][0]) ? $Comments['ape']['date'][0] : '') != (isset($Comments['all']['year'][0]) ? $Comments['all']['year'][0] : '')) && ((isset($Comments['ape']['year'][0]) ? $Comments['ape']['year'][0] : '') != (isset($Comments['all']['year'][0]) ? $Comments['all']['year'][0] : ''))) { - - $tagvalues .= $fieldname.' = [['.(isset($Comments['ape']['date'][0]) ? $Comments['ape']['date'][0] : '').']]'."\n"; - $Mismatched[$tagtype] = true; - $FileOK = false; - if (isset($Comments['ape']['date'][0]) && (strlen(trim($Comments['ape']['date'][0])) > 0)) { - $EmptyTags[$tagtype] = false; - } - - } else { - - $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; - if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { - $EmptyTags[$tagtype] = false; - } - - } - - } elseif (($fieldname == 'genre') && !empty($Comments['all'][$fieldname]) && !empty($Comments[$tagtype][$fieldname]) && in_array($Comments[$tagtype][$fieldname][0], $Comments['all'][$fieldname])) { - - $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; - if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { - $EmptyTags[$tagtype] = false; - } - - } elseif ((isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '') != (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : '')) { - - $skiptracknumberfield = false; - switch ($fieldname) { - case 'track': - case 'tracknumber': - case 'track_number': - $trackA = (isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''); - $trackB = (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''); - if (intval($trackA) == intval($trackB)) { - $skiptracknumberfield = true; - } - break; - } - if (!$skiptracknumberfield) { - $tagvalues .= $fieldname.' = [['.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '').']]'."\n"; - $tagA = (isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : ''); - $tagB = (isset($Comments['all'][$fieldname][0]) ? $Comments['all'][$fieldname][0] : ''); - if (trim(strtolower(RemoveAccents($tagA))) == trim(strtolower(RemoveAccents($tagB)))) { - $SemiMatched[$tagtype] = true; - } else { - $Mismatched[$tagtype] = true; - } - $FileOK = false; - if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { - $EmptyTags[$tagtype] = false; - } - } - - } else { - - $tagvalues .= $fieldname.' = '.(isset($Comments[$tagtype][$fieldname][0]) ? $Comments[$tagtype][$fieldname][0] : '')."\n"; - if (isset($Comments[$tagtype][$fieldname][0]) && (strlen(trim($Comments[$tagtype][$fieldname][0])) > 0)) { - $EmptyTags[$tagtype] = false; - } - - } - } - - if ($EmptyTags[$tagtype]) { - $FileOK = false; - $ThisLine .= ''; - } - } - $ThisLine .= ''; - - if (!$FileOK) { - $NotOKfiles++; - - echo ''; - flush(); - - if (!empty($_REQUEST['autofix'])) { - - $AnyMismatched = false; - foreach ($Mismatched as $key => $value) { - if ($value && ($EmptyTags["$key"] === false)) { - $AnyMismatched = true; - } - } - if ($AnyMismatched && empty($_REQUEST['autofixforcesource'])) { - - echo $ThisLine; - - } else { - - $TagsToSynch = ''; - foreach ($EmptyTags as $key => $value) { - if ($value) { - switch ($key) { - case 'id3v1': - $TagsToSynch .= '1'; - break; - case 'id3v2': - $TagsToSynch .= '2'; - break; - case 'ape': - $TagsToSynch .= 'A'; - break; - } - } - } - - $autofixforcesource = (!empty($_REQUEST['autofixforcesource']) ? $_REQUEST['autofixforcesource'] : 'all'); - $TagsToSynch = (!empty($_REQUEST['autofixforcedest']) ? $_REQUEST['autofixforcedest'] : $TagsToSynch); - - $errors = array(); - if (SynchronizeAllTags($row['filename'], $autofixforcesource, $TagsToSynch, $errors)) { - $Autofixedfiles++; - echo ''; - } else { - echo ''; - } - echo ''; - echo ''; - } - - } else { - - echo $ThisLine; - - } - } - } - - echo '
ViewFilenameCombinedID3v2APELyrics3ID3v1
view'.htmlentities($row['filename']).'all
view'.htmlentities($row['filename']).'all'; + } elseif ($SemiMatched[$tagtype]) { + $ThisLine .= ''; + } elseif ($Mismatched[$tagtype]) { + $ThisLine .= ''; + } else { + $ThisLine .= ''; + } + $ThisLine .= ''.$tagtype.''; + $ThisLine .= '
'; - } elseif ($SemiMatched[$tagtype]) { - $ThisLine .= ''; - } elseif ($Mismatched[$tagtype]) { - $ThisLine .= ''; - } else { - $ThisLine .= ''; - } - $ThisLine .= ''.$tagtype.''; - $ThisLine .= '
 '; - echo ''.htmlentities($row['filename']).''; - echo ''; - echo '
'.$TagsToSynch.'

'; - echo ''; - echo 'Found '.number_format($NotOKfiles).' files with unsynchronized tags, and auto-fixed '.number_format($Autofixedfiles).' of them.'; + $errors = []; + if (SynchronizeAllTags($row['filename'], $autofixforcesource, $TagsToSynch, $errors)) { + $Autofixedfiles++; + echo ''; + } else { + echo ''; + } + echo ' '; + echo ''.htmlentities($row['filename']).''; + echo ''; + echo ''; + echo '
'.$TagsToSynch.'
'; + } + } else { + echo $ThisLine; + } + } + } + echo '
'; + echo ''; + echo 'Found '.number_format($NotOKfiles).' files with unsynchronized tags, and auto-fixed '.number_format($Autofixedfiles).' of them.'; } elseif (!empty($_REQUEST['filenamepattern'])) { + $patterns['A'] = 'artist'; + $patterns['T'] = 'title'; + $patterns['M'] = 'album'; + $patterns['N'] = 'track'; + $patterns['G'] = 'genre'; + $patterns['R'] = 'remix'; - $patterns['A'] = 'artist'; - $patterns['T'] = 'title'; - $patterns['M'] = 'album'; - $patterns['N'] = 'track'; - $patterns['G'] = 'genre'; - $patterns['R'] = 'remix'; + $FieldsToUse = explode(' ', wordwrap(preg_replace('#[^A-Z]#i', '', $_REQUEST['filenamepattern']), 1, ' ', 1)); + //$FieldsToUse = explode(' ', wordwrap($_REQUEST['filenamepattern'], 1, ' ', 1)); + foreach ($FieldsToUse as $FieldID) { + $FieldNames[] = $patterns["$FieldID"]; + } - $FieldsToUse = explode(' ', wordwrap(preg_replace('#[^A-Z]#i', '', $_REQUEST['filenamepattern']), 1, ' ', 1)); - //$FieldsToUse = explode(' ', wordwrap($_REQUEST['filenamepattern'], 1, ' ', 1)); - foreach ($FieldsToUse as $FieldID) { - $FieldNames[] = $patterns["$FieldID"]; - } + $SQLquery = 'SELECT `filename`, `fileformat`, '.implode(', ', $FieldNames); + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + echo 'Files that do not match naming pattern: (auto-fix)
'; + echo ''; + echo ''; + $nonmatchingfilenames = 0; + $Pattern = $_REQUEST['filenamepattern']; + $PatternLength = strlen($Pattern); + while ($row = mysql_fetch_array($result)) { + set_time_limit(10); + $PatternFilename = ''; + for ($i = 0; $i < $PatternLength; $i++) { + if (isset($patterns[$Pattern{$i}])) { + $PatternFilename .= trim(strtr($row[$patterns[$Pattern{$i}]], ':\\*<>|', ';-¤«»¦'), ' '); + } else { + $PatternFilename .= $Pattern{$i}; + } + } - $SQLquery = 'SELECT `filename`, `fileformat`, '.implode(', ', $FieldNames); - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - echo 'Files that do not match naming pattern: (auto-fix)
'; - echo '
viewWhyActual filename
(click to play/edit file)
Correct filename (based on tags)'.(empty($_REQUEST['autofix']) ? '
(click to rename file to this)' : '').'
'; - echo ''; - $nonmatchingfilenames = 0; - $Pattern = $_REQUEST['filenamepattern']; - $PatternLength = strlen($Pattern); - while ($row = mysql_fetch_array($result)) { - set_time_limit(10); - $PatternFilename = ''; - for ($i = 0; $i < $PatternLength; $i++) { - if (isset($patterns[$Pattern{$i}])) { - $PatternFilename .= trim(strtr($row[$patterns[$Pattern{$i}]], ':\\*<>|', ';-¤«»¦'), ' '); - } else { - $PatternFilename .= $Pattern{$i}; - } - } + // Replace "~" with "-" if characters immediately before and after are both numbers, + // "/" has been replaced with "~" above which is good for multi-song medley dividers, + // but for things like 24/7, 7/8ths, etc it looks better if it's 24-7, 7-8ths, etc. + $PatternFilename = preg_replace('#([ a-z]+)/([ a-z]+)#i', '\\1~\\2', $PatternFilename); + $PatternFilename = str_replace('/', '×', $PatternFilename); - // Replace "~" with "-" if characters immediately before and after are both numbers, - // "/" has been replaced with "~" above which is good for multi-song medley dividers, - // but for things like 24/7, 7/8ths, etc it looks better if it's 24-7, 7-8ths, etc. - $PatternFilename = preg_replace('#([ a-z]+)/([ a-z]+)#i', '\\1~\\2', $PatternFilename); - $PatternFilename = str_replace('/', '×', $PatternFilename); - - $PatternFilename = str_replace('?', '¿', $PatternFilename); - $PatternFilename = str_replace(' "', ' “', $PatternFilename); - $PatternFilename = str_replace('("', '(“', $PatternFilename); - $PatternFilename = str_replace('-"', '-“', $PatternFilename); - $PatternFilename = str_replace('" ', '” ', $PatternFilename.' '); - $PatternFilename = str_replace('"', '”', $PatternFilename); - $PatternFilename = str_replace(' ', ' ', $PatternFilename); + $PatternFilename = str_replace('?', '¿', $PatternFilename); + $PatternFilename = str_replace(' "', ' “', $PatternFilename); + $PatternFilename = str_replace('("', '(“', $PatternFilename); + $PatternFilename = str_replace('-"', '-“', $PatternFilename); + $PatternFilename = str_replace('" ', '” ', $PatternFilename.' '); + $PatternFilename = str_replace('"', '”', $PatternFilename); + $PatternFilename = str_replace(' ', ' ', $PatternFilename); - $ParenthesesPairs = array('()', '[]', '{}'); - foreach ($ParenthesesPairs as $pair) { + $ParenthesesPairs = ['()', '[]', '{}']; + foreach ($ParenthesesPairs as $pair) { + // multiple remixes are stored tab-seperated in the database. + // change "{2000 Version\tSomebody Remix}" into "{2000 Version} {Somebody Remix}" + while (preg_match('#^(.*)'.preg_quote($pair{0}).'([^'.preg_quote($pair{1}).']*)('."\t".')([^'.preg_quote($pair{0}).']*)'.preg_quote($pair{1}).'#', $PatternFilename, $matches)) { + $PatternFilename = $matches[1].$pair{0}.$matches[2].$pair{1}.' '.$pair{0}.$matches[4].$pair{1}; + } - // multiple remixes are stored tab-seperated in the database. - // change "{2000 Version\tSomebody Remix}" into "{2000 Version} {Somebody Remix}" - while (preg_match('#^(.*)'.preg_quote($pair{0}).'([^'.preg_quote($pair{1}).']*)('."\t".')([^'.preg_quote($pair{0}).']*)'.preg_quote($pair{1}).'#', $PatternFilename, $matches)) { - $PatternFilename = $matches[1].$pair{0}.$matches[2].$pair{1}.' '.$pair{0}.$matches[4].$pair{1}; - } + // remove empty parenthesized pairs (probably where no track numbers, remix version, etc) + $PatternFilename = preg_replace('#'.preg_quote($pair).'#', '', $PatternFilename); - // remove empty parenthesized pairs (probably where no track numbers, remix version, etc) - $PatternFilename = preg_replace('#'.preg_quote($pair).'#', '', $PatternFilename); + // "[01] - Title With No Artist.mp3" ==> "[01] Title With No Artist.mp3" + $PatternFilename = preg_replace('#'.preg_quote($pair{1}).' +\- #', $pair{1}.' ', $PatternFilename); + } - // "[01] - Title With No Artist.mp3" ==> "[01] Title With No Artist.mp3" - $PatternFilename = preg_replace('#'.preg_quote($pair{1}).' +\- #', $pair{1}.' ', $PatternFilename); + // get rid of leading & trailing spaces if end items (artist or title for example) are missing + $PatternFilename = trim($PatternFilename, ' -'); - } + if (!$PatternFilename) { + // no tags to create a filename from -- skip this file + continue; + } + $PatternFilename .= '.'.$row['fileformat']; - // get rid of leading & trailing spaces if end items (artist or title for example) are missing - $PatternFilename = trim($PatternFilename, ' -'); - - if (!$PatternFilename) { - // no tags to create a filename from -- skip this file - continue; - } - $PatternFilename .= '.'.$row['fileformat']; - - $ActualFilename = basename($row['filename']); - if ($ActualFilename != $PatternFilename) { - - $NotMatchedReasons = ''; - if (strtolower($ActualFilename) === strtolower($PatternFilename)) { - $NotMatchedReasons .= 'Aa '; - } elseif (RemoveAccents($ActualFilename) === RemoveAccents($PatternFilename)) { - $NotMatchedReasons .= 'ée '; - } + $ActualFilename = basename($row['filename']); + if ($ActualFilename != $PatternFilename) { + $NotMatchedReasons = ''; + if (strtolower($ActualFilename) === strtolower($PatternFilename)) { + $NotMatchedReasons .= 'Aa '; + } elseif (RemoveAccents($ActualFilename) === RemoveAccents($PatternFilename)) { + $NotMatchedReasons .= 'ée '; + } - $actualExt = '.'.fileextension($ActualFilename); - $patternExt = '.'.fileextension($PatternFilename); - $ActualFilenameNoExt = (($actualExt != '.') ? substr($ActualFilename, 0, 0 - strlen($actualExt)) : $ActualFilename); - $PatternFilenameNoExt = (($patternExt != '.') ? substr($PatternFilename, 0, 0 - strlen($patternExt)) : $PatternFilename); + $actualExt = '.'.fileextension($ActualFilename); + $patternExt = '.'.fileextension($PatternFilename); + $ActualFilenameNoExt = (($actualExt != '.') ? substr($ActualFilename, 0, 0 - strlen($actualExt)) : $ActualFilename); + $PatternFilenameNoExt = (($patternExt != '.') ? substr($PatternFilename, 0, 0 - strlen($patternExt)) : $PatternFilename); - if (strpos($PatternFilenameNoExt, $ActualFilenameNoExt) !== false) { - $DifferenceBoldedName = str_replace($ActualFilenameNoExt, ''.$ActualFilenameNoExt.'', $PatternFilenameNoExt); - } else { - $ShortestNameLength = min(strlen($ActualFilenameNoExt), strlen($PatternFilenameNoExt)); - for ($DifferenceOffset = 0; $DifferenceOffset < $ShortestNameLength; $DifferenceOffset++) { - if ($ActualFilenameNoExt{$DifferenceOffset} !== $PatternFilenameNoExt{$DifferenceOffset}) { - break; - } - } - $DifferenceBoldedName = ''.substr($PatternFilenameNoExt, 0, $DifferenceOffset).''.substr($PatternFilenameNoExt, $DifferenceOffset); - } - $DifferenceBoldedName .= (($actualExt == $patternExt) ? ''.$patternExt.'' : $patternExt); + if (strpos($PatternFilenameNoExt, $ActualFilenameNoExt) !== false) { + $DifferenceBoldedName = str_replace($ActualFilenameNoExt, ''.$ActualFilenameNoExt.'', $PatternFilenameNoExt); + } else { + $ShortestNameLength = min(strlen($ActualFilenameNoExt), strlen($PatternFilenameNoExt)); + for ($DifferenceOffset = 0; $DifferenceOffset < $ShortestNameLength; $DifferenceOffset++) { + if ($ActualFilenameNoExt{$DifferenceOffset} !== $PatternFilenameNoExt{$DifferenceOffset}) { + break; + } + } + $DifferenceBoldedName = ''.substr($PatternFilenameNoExt, 0, $DifferenceOffset).''.substr($PatternFilenameNoExt, $DifferenceOffset); + } + $DifferenceBoldedName .= (($actualExt == $patternExt) ? ''.$patternExt.'' : $patternExt); - echo ''; - echo ''; - echo ''; - echo ''; - - if (!empty($_REQUEST['autofix'])) { - - $results = ''; - if (RenameFileFromTo($row['filename'], dirname($row['filename']).'/'.$PatternFilename, $results)) { - echo ''; - - - } else { - - echo ''; - - } - echo ''; - - $nonmatchingfilenames++; - } - } - echo '
viewWhyActual filename
(click to play/edit file)
Correct filename (based on tags)'.(empty($_REQUEST['autofix']) ? '
(click to rename file to this)' : '').'
view '.$NotMatchedReasons.''.htmlentities($ActualFilename).''; - } else { - echo ''; - } - echo ''.$DifferenceBoldedName.''; - echo ''.$DifferenceBoldedName.'

'; - echo 'Found '.number_format($nonmatchingfilenames).' files that do not match naming pattern
'; + echo ''; + echo 'view'; + echo ' '.$NotMatchedReasons.''; + echo ''.htmlentities($ActualFilename).''; + if (!empty($_REQUEST['autofix'])) { + $results = ''; + if (RenameFileFromTo($row['filename'], dirname($row['filename']).'/'.$PatternFilename, $results)) { + echo ''; + } else { + echo ''; + } + echo ''.$DifferenceBoldedName.''; + } else { + echo ''; + echo ''.$DifferenceBoldedName.''; + } + echo ''; + $nonmatchingfilenames++; + } + } + echo '
'; + echo 'Found '.number_format($nonmatchingfilenames).' files that do not match naming pattern
'; } elseif (!empty($_REQUEST['encoderoptionsdistribution'])) { + if (isset($_REQUEST['showtagfiles'])) { + $SQLquery = 'SELECT `filename`, `encoder_options` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`encoder_options` LIKE "'.mysql_real_escape_string($_REQUEST['showtagfiles']).'")'; + $SQLquery .= ' AND (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); - if (isset($_REQUEST['showtagfiles'])) { - $SQLquery = 'SELECT `filename`, `encoder_options` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`encoder_options` LIKE "'.mysql_real_escape_string($_REQUEST['showtagfiles']).'")'; - $SQLquery .= ' AND (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } else { - - echo 'Show all Encoder Options
'; - echo 'Files with Encoder Options '.$_REQUEST['showtagfiles'].':
'; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
'.htmlentities($row['filename']).''.$row['encoder_options'].'
'; - - } - - } elseif (!isset($_REQUEST['m3u'])) { - - $SQLquery = 'SELECT `encoder_options`, COUNT(*) AS `num` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; - $SQLquery .= ' GROUP BY `encoder_options`'; - $SQLquery .= ' ORDER BY (`encoder_options` LIKE "LAME%") DESC, (`encoder_options` LIKE "CBR%") DESC, `num` DESC, `encoder_options` ASC'; - $result = mysql_query_safe($SQLquery); - echo 'Files with Encoder Options:
'; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
Encoder OptionsCountM3U
'.$row['encoder_options'].''.number_format($row['num']).'m3u

'; - - } - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } else { + echo 'Show all Encoder Options
'; + echo 'Files with Encoder Options '.$_REQUEST['showtagfiles'].':
'; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
'.htmlentities($row['filename']).''.$row['encoder_options'].'
'; + } + } elseif (!isset($_REQUEST['m3u'])) { + $SQLquery = 'SELECT `encoder_options`, COUNT(*) AS `num` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; + $SQLquery .= ' GROUP BY `encoder_options`'; + $SQLquery .= ' ORDER BY (`encoder_options` LIKE "LAME%") DESC, (`encoder_options` LIKE "CBR%") DESC, `num` DESC, `encoder_options` ASC'; + $result = mysql_query_safe($SQLquery); + echo 'Files with Encoder Options:
'; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
Encoder OptionsCountM3U
'.$row['encoder_options'].''.number_format($row['num']).'m3u

'; + } } elseif (!empty($_REQUEST['tagtypes'])) { + if (!isset($_REQUEST['m3u'])) { + $SQLquery = 'SELECT `tags`, COUNT(*) AS `num` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; + $SQLquery .= ' GROUP BY `tags`'; + $SQLquery .= ' ORDER BY `num` DESC'; + $result = mysql_query_safe($SQLquery); + echo 'Files with tags:
'; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
TagsCountM3U
'.$row['tags'].''.number_format($row['num']).'m3u

'; + } - if (!isset($_REQUEST['m3u'])) { - $SQLquery = 'SELECT `tags`, COUNT(*) AS `num` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; - $SQLquery .= ' GROUP BY `tags`'; - $SQLquery .= ' ORDER BY `num` DESC'; - $result = mysql_query_safe($SQLquery); - echo 'Files with tags:
'; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
TagsCountM3U
'.$row['tags'].''.number_format($row['num']).'m3u

'; - } - - if (isset($_REQUEST['showtagfiles'])) { - $SQLquery = 'SELECT `filename`, `tags` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`tags` LIKE "'.mysql_real_escape_string($_REQUEST['showtagfiles']).'")'; - $SQLquery .= ' AND (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } else { - - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
'.htmlentities($row['filename']).''.$row['tags'].'
'; - - } - } - + if (isset($_REQUEST['showtagfiles'])) { + $SQLquery = 'SELECT `filename`, `tags` FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`tags` LIKE "'.mysql_real_escape_string($_REQUEST['showtagfiles']).'")'; + $SQLquery .= ' AND (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } else { + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
'.htmlentities($row['filename']).''.$row['tags'].'
'; + } + } } elseif (!empty($_REQUEST['md5datadupes'])) { + $OtherFormats = ''; + $AVFormats = ''; - $OtherFormats = ''; - $AVFormats = ''; + $SQLquery = 'SELECT `md5_data`, `filename`, COUNT(*) AS `num`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`md5_data` <> "")'; + $SQLquery .= ' GROUP BY `md5_data`'; + $SQLquery .= ' ORDER BY `num` DESC'; + $result = mysql_query_safe($SQLquery); + while (($row = mysql_fetch_array($result)) && ($row['num'] > 1)) { + set_time_limit(30); - $SQLquery = 'SELECT `md5_data`, `filename`, COUNT(*) AS `num`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`md5_data` <> "")'; - $SQLquery .= ' GROUP BY `md5_data`'; - $SQLquery .= ' ORDER BY `num` DESC'; - $result = mysql_query_safe($SQLquery); - while (($row = mysql_fetch_array($result)) && ($row['num'] > 1)) { - set_time_limit(30); - - $filenames = array(); - $tags = array(); - $md5_data = array(); - $SQLquery = 'SELECT `fileformat`, `filename`, `tags`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`md5_data` = "'.mysql_real_escape_string($row['md5_data']).'")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result2 = mysql_query_safe($SQLquery); - while ($row2 = mysql_fetch_array($result2)) { - $thisfileformat = $row2['fileformat']; - $filenames[] = $row2['filename']; - $tags[] = $row2['tags']; - $md5_data[] = $row['md5_data']; - } - - $thisline = ''; - $thisline .= ''.implode('
', $md5_data).''; - $thisline .= ''.implode('
', $tags).''; - $thisline .= ''.implode('
', $filenames).''; - $thisline .= ''; - - if (in_array($thisfileformat, $IgnoreNoTagFormats)) { - $OtherFormats .= $thisline; - } else { - $AVFormats .= $thisline; - } - } - echo 'Duplicated MD5_DATA (Audio/Video files):'; - echo $AVFormats.'

'; - echo 'Duplicated MD5_DATA (Other files):'; - echo $OtherFormats.'

'; + $filenames = []; + $tags = []; + $md5_data = []; + $SQLquery = 'SELECT `fileformat`, `filename`, `tags`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`md5_data` = "'.mysql_real_escape_string($row['md5_data']).'")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result2 = mysql_query_safe($SQLquery); + while ($row2 = mysql_fetch_array($result2)) { + $thisfileformat = $row2['fileformat']; + $filenames[] = $row2['filename']; + $tags[] = $row2['tags']; + $md5_data[] = $row['md5_data']; + } + $thisline = ''; + $thisline .= ''.implode('
', $md5_data).''; + $thisline .= ''.implode('
', $tags).''; + $thisline .= ''.implode('
', $filenames).''; + $thisline .= ''; + if (in_array($thisfileformat, $IgnoreNoTagFormats)) { + $OtherFormats .= $thisline; + } else { + $AVFormats .= $thisline; + } + } + echo 'Duplicated MD5_DATA (Audio/Video files):'; + echo $AVFormats.'

'; + echo 'Duplicated MD5_DATA (Other files):'; + echo $OtherFormats.'

'; } elseif (!empty($_REQUEST['artisttitledupes'])) { + if (isset($_REQUEST['m3uartist']) && isset($_REQUEST['m3utitle'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + $SQLquery = 'SELECT `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`artist` = "'.mysql_real_escape_string($_REQUEST['m3uartist']).'")'; + $SQLquery .= ' AND (`title` = "'.mysql_real_escape_string($_REQUEST['m3utitle']).'")'; + $SQLquery .= ' ORDER BY `playtime_seconds` ASC, `remix` ASC, `filename` ASC'; + $result = mysql_query_safe($SQLquery); + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } - if (isset($_REQUEST['m3uartist']) && isset($_REQUEST['m3utitle'])) { + $SQLquery = 'SELECT `artist`, `title`, `filename`, COUNT(*) AS `num`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`artist` <> "")'; + $SQLquery .= ' AND (`title` <> "")'; + $SQLquery .= ' GROUP BY `artist`, `title`'.(!empty($_REQUEST['samemix']) ? ', `remix`' : ''); + $SQLquery .= ' ORDER BY `num` DESC, `artist` ASC, `title` ASC, `playtime_seconds` ASC, `remix` ASC'; + $result = mysql_query_safe($SQLquery); + $uniquetitles = 0; + $uniquefiles = 0; - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - $SQLquery = 'SELECT `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`artist` = "'.mysql_real_escape_string($_REQUEST['m3uartist']).'")'; - $SQLquery .= ' AND (`title` = "'.mysql_real_escape_string($_REQUEST['m3utitle']).'")'; - $SQLquery .= ' ORDER BY `playtime_seconds` ASC, `remix` ASC, `filename` ASC'; - $result = mysql_query_safe($SQLquery); - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while (($row = mysql_fetch_array($result)) && ($row['num'] > 1)) { + $SQLquery = 'SELECT `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`artist` = "'.mysql_real_escape_string($row['artist']).'")'; + $SQLquery .= ' AND (`title` = "'.mysql_real_escape_string($row['title']).'")'; + if (!empty($_REQUEST['samemix'])) { + $SQLquery .= ' AND (`remix` = "'.mysql_real_escape_string($row['remix']).'")'; + } + $SQLquery .= ' ORDER BY `playtime_seconds` ASC, `remix` ASC, `filename` ASC'; + $result2 = mysql_query_safe($SQLquery); + while ($row2 = mysql_fetch_array($result2)) { + echo WindowsShareSlashTranslate($row2['filename'])."\n"; + } + } + exit; + } else { + echo 'Duplicated aritst + title: (Identical Mix/Version only)
'; + echo '(.m3u version)
'; + echo ''; + echo ''; - } + while (($row = mysql_fetch_array($result)) && ($row['num'] > 1)) { + $uniquetitles++; + set_time_limit(30); - $SQLquery = 'SELECT `artist`, `title`, `filename`, COUNT(*) AS `num`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`artist` <> "")'; - $SQLquery .= ' AND (`title` <> "")'; - $SQLquery .= ' GROUP BY `artist`, `title`'.(!empty($_REQUEST['samemix']) ? ', `remix`' : ''); - $SQLquery .= ' ORDER BY `num` DESC, `artist` ASC, `title` ASC, `playtime_seconds` ASC, `remix` ASC'; - $result = mysql_query_safe($SQLquery); - $uniquetitles = 0; - $uniquefiles = 0; + $filenames = []; + $artists = []; + $titles = []; + $remixes = []; + $bitrates = []; + $playtimes = []; + $SQLquery = 'SELECT `filename`, `artist`, `title`, `remix`, `audio_bitrate`, `vbr_method`, `playtime_seconds`, `encoder_options`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`artist` = "'.mysql_real_escape_string($row['artist']).'")'; + $SQLquery .= ' AND (`title` = "'.mysql_real_escape_string($row['title']).'")'; + $SQLquery .= ' ORDER BY `playtime_seconds` ASC, `remix` ASC, `filename` ASC'; + $result2 = mysql_query_safe($SQLquery); + while ($row2 = mysql_fetch_array($result2)) { + $uniquefiles++; + $filenames[] = $row2['filename']; + $artists[] = $row2['artist']; + $titles[] = $row2['title']; + $remixes[] = $row2['remix']; + if ($row2['vbr_method']) { + $bitrates[] = ''.BitrateText($row2['audio_bitrate'] / 1000).''; + } else { + $bitrates[] = BitrateText($row2['audio_bitrate'] / 1000); + } + $playtimes[] = getid3_lib::PlaytimeString($row2['playtime_seconds']); + } - if (!empty($_REQUEST['m3u'])) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while (($row = mysql_fetch_array($result)) && ($row['num'] > 1)) { - $SQLquery = 'SELECT `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`artist` = "'.mysql_real_escape_string($row['artist']).'")'; - $SQLquery .= ' AND (`title` = "'.mysql_real_escape_string($row['title']).'")'; - if (!empty($_REQUEST['samemix'])) { - $SQLquery .= ' AND (`remix` = "'.mysql_real_escape_string($row['remix']).'")'; - } - $SQLquery .= ' ORDER BY `playtime_seconds` ASC, `remix` ASC, `filename` ASC'; - $result2 = mysql_query_safe($SQLquery); - while ($row2 = mysql_fetch_array($result2)) { - echo WindowsShareSlashTranslate($row2['filename'])."\n"; - } - } - exit; - - } else { - - echo 'Duplicated aritst + title: (Identical Mix/Version only)
'; - echo '(.m3u version)
'; - echo '
 ArtistTitleVersion  Filename
'; + foreach ($filenames as $file) { + echo 'delete
'; + } + echo '
'; + foreach ($filenames as $file) { + echo 'play
'; + } + echo '
play all'.implode('
', $artists).'
'.implode('
', $titles).'
'.implode('
', $remixes).'
'.implode('
', $bitrates).'
'.implode('
', $playtimes).'
'; - echo ''; - - while (($row = mysql_fetch_array($result)) && ($row['num'] > 1)) { - $uniquetitles++; - set_time_limit(30); - - $filenames = array(); - $artists = array(); - $titles = array(); - $remixes = array(); - $bitrates = array(); - $playtimes = array(); - $SQLquery = 'SELECT `filename`, `artist`, `title`, `remix`, `audio_bitrate`, `vbr_method`, `playtime_seconds`, `encoder_options`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`artist` = "'.mysql_real_escape_string($row['artist']).'")'; - $SQLquery .= ' AND (`title` = "'.mysql_real_escape_string($row['title']).'")'; - $SQLquery .= ' ORDER BY `playtime_seconds` ASC, `remix` ASC, `filename` ASC'; - $result2 = mysql_query_safe($SQLquery); - while ($row2 = mysql_fetch_array($result2)) { - $uniquefiles++; - $filenames[] = $row2['filename']; - $artists[] = $row2['artist']; - $titles[] = $row2['title']; - $remixes[] = $row2['remix']; - if ($row2['vbr_method']) { - $bitrates[] = ''.BitrateText($row2['audio_bitrate'] / 1000).''; - } else { - $bitrates[] = BitrateText($row2['audio_bitrate'] / 1000); - } - $playtimes[] = getid3_lib::PlaytimeString($row2['playtime_seconds']); - } - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - - echo ''; - - echo ''; - } - - } - echo '
 ArtistTitleVersion  Filename
'; - foreach ($filenames as $file) { - echo 'delete
'; - } - echo '
'; - foreach ($filenames as $file) { - echo 'play
'; - } - echo '
play all'.implode('
', $artists).'
'.implode('
', $titles).'
'.implode('
', $remixes).'
'.implode('
', $bitrates).'
'.implode('
', $playtimes).'
'; - foreach ($filenames as $file) { - echo ''; - } - echo '
'.dirname($file).'/'.basename($file).'
'; - echo number_format($uniquefiles).' files with '.number_format($uniquetitles).' unique aritst + title
'; - echo '
'; + echo ''; + foreach ($filenames as $file) { + echo ''; + } + echo '
'.dirname($file).'/'.basename($file).'
'; + echo ''; + } + } + echo ''; + echo number_format($uniquefiles).' files with '.number_format($uniquetitles).' unique aritst + title
'; + echo '
'; } elseif (!empty($_REQUEST['filetypelist'])) { - - list($fileformat, $audioformat) = explode('|', $_REQUEST['filetypelist']); - $SQLquery = 'SELECT `filename`, `fileformat`, `audio_dataformat`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` = "'.mysql_real_escape_string($fileformat).'")'; - $SQLquery .= ' AND (`audio_dataformat` = "'.mysql_real_escape_string($audioformat).'")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - echo 'Files of format '.$fileformat.'.'.$audioformat.':'; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
fileaudiofilename
'.$row['fileformat'].''.$row['audio_dataformat'].''.htmlentities($row['filename']).'

'; - + list($fileformat, $audioformat) = explode('|', $_REQUEST['filetypelist']); + $SQLquery = 'SELECT `filename`, `fileformat`, `audio_dataformat`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` = "'.mysql_real_escape_string($fileformat).'")'; + $SQLquery .= ' AND (`audio_dataformat` = "'.mysql_real_escape_string($audioformat).'")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + echo 'Files of format '.$fileformat.'.'.$audioformat.':'; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
fileaudiofilename
'.$row['fileformat'].''.$row['audio_dataformat'].''.htmlentities($row['filename']).'

'; } elseif (!empty($_REQUEST['trackinalbum'])) { + $SQLquery = 'SELECT `filename`, `album`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`album` LIKE "% [%")'; + $SQLquery .= ' ORDER BY `album` ASC, `filename` ASC'; + $result = mysql_query_safe($SQLquery); + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } elseif (!empty($_REQUEST['autofix'])) { + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true); - $SQLquery = 'SELECT `filename`, `album`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`album` LIKE "% [%")'; - $SQLquery .= ' ORDER BY `album` ASC, `filename` ASC'; - $result = mysql_query_safe($SQLquery); - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } elseif (!empty($_REQUEST['autofix'])) { - - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true); - - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - $ThisFileInfo = $getID3->analyze($filename); - getid3_lib::CopyTagsToComments($ThisFileInfo); - - if (!empty($ThisFileInfo['tags'])) { - - $Album = trim(str_replace(strstr($ThisFileInfo['comments']['album'][0], ' ['), '', $ThisFileInfo['comments']['album'][0])); - $Track = (string) intval(str_replace(' [', '', str_replace(']', '', strstr($ThisFileInfo['comments']['album'][0], ' [')))); - if ($Track == '0') { - $Track = ''; - } - if ($Album && $Track) { - echo '
'.htmlentities($row['filename']).'
'; - echo ''.htmlentities($Album).' (track #'.$Track.')
'; - echo 'ID3v2: '.(RemoveID3v2($row['filename'], false) ? 'removed' : 'REMOVAL FAILED!').', '; - $WriteID3v1_title = (isset($ThisFileInfo['comments']['title'][0]) ? $ThisFileInfo['comments']['title'][0] : ''); - $WriteID3v1_artist = (isset($ThisFileInfo['comments']['artist'][0]) ? $ThisFileInfo['comments']['artist'][0] : ''); - $WriteID3v1_year = (isset($ThisFileInfo['comments']['year'][0]) ? $ThisFileInfo['comments']['year'][0] : ''); - $WriteID3v1_comment = (isset($ThisFileInfo['comments']['comment'][0]) ? $ThisFileInfo['comments']['comment'][0] : ''); - $WriteID3v1_genreid = (isset($ThisFileInfo['comments']['genreid'][0]) ? $ThisFileInfo['comments']['genreid'][0] : ''); - echo 'ID3v1: '.(WriteID3v1($row['filename'], $WriteID3v1_title, $WriteID3v1_artist, $Album, $WriteID3v1_year, $WriteID3v1_comment, $WriteID3v1_genreid, $Track, false) ? 'updated' : 'UPDATE FAILED').'
'; - } else { - echo ' . '; - } - - } else { - - echo '
FAILED
'.htmlentities($row['filename']).'
'; - - } - flush(); - } - - } else { - - echo ''.number_format(mysql_num_rows($result)).' files with [??]-format track numbers in album field:
'; - if (mysql_num_rows($result) > 0) { - echo '(.m3u version)
'; - echo 'Try to auto-fix
'; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
'.$row['album'].''.htmlentities($row['filename']).'
'; - } - echo '
'; - - } + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + $ThisFileInfo = $getID3->analyze($filename); + getid3_lib::CopyTagsToComments($ThisFileInfo); + if (!empty($ThisFileInfo['tags'])) { + $Album = trim(str_replace(strstr($ThisFileInfo['comments']['album'][0], ' ['), '', $ThisFileInfo['comments']['album'][0])); + $Track = (string) intval(str_replace(' [', '', str_replace(']', '', strstr($ThisFileInfo['comments']['album'][0], ' [')))); + if ($Track == '0') { + $Track = ''; + } + if ($Album && $Track) { + echo '
'.htmlentities($row['filename']).'
'; + echo ''.htmlentities($Album).' (track #'.$Track.')
'; + echo 'ID3v2: '.(RemoveID3v2($row['filename'], false) ? 'removed' : 'REMOVAL FAILED!').', '; + $WriteID3v1_title = (isset($ThisFileInfo['comments']['title'][0]) ? $ThisFileInfo['comments']['title'][0] : ''); + $WriteID3v1_artist = (isset($ThisFileInfo['comments']['artist'][0]) ? $ThisFileInfo['comments']['artist'][0] : ''); + $WriteID3v1_year = (isset($ThisFileInfo['comments']['year'][0]) ? $ThisFileInfo['comments']['year'][0] : ''); + $WriteID3v1_comment = (isset($ThisFileInfo['comments']['comment'][0]) ? $ThisFileInfo['comments']['comment'][0] : ''); + $WriteID3v1_genreid = (isset($ThisFileInfo['comments']['genreid'][0]) ? $ThisFileInfo['comments']['genreid'][0] : ''); + echo 'ID3v1: '.(WriteID3v1($row['filename'], $WriteID3v1_title, $WriteID3v1_artist, $Album, $WriteID3v1_year, $WriteID3v1_comment, $WriteID3v1_genreid, $Track, false) ? 'updated' : 'UPDATE FAILED').'
'; + } else { + echo ' . '; + } + } else { + echo '
FAILED
'.htmlentities($row['filename']).'
'; + } + flush(); + } + } else { + echo ''.number_format(mysql_num_rows($result)).' files with [??]-format track numbers in album field:
'; + if (mysql_num_rows($result) > 0) { + echo '(.m3u version)
'; + echo 'Try to auto-fix
'; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
'.$row['album'].''.htmlentities($row['filename']).'
'; + } + echo '
'; + } } elseif (!empty($_REQUEST['fileextensions'])) { + $SQLquery = 'SELECT `filename`, `fileformat`, `audio_dataformat`, `video_dataformat`, `tags`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + $invalidextensionfiles = 0; + $invalidextensionline = ''; + $invalidextensionline .= ''; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); - $SQLquery = 'SELECT `filename`, `fileformat`, `audio_dataformat`, `video_dataformat`, `tags`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - $invalidextensionfiles = 0; - $invalidextensionline = '
fileaudiovideotagsactualcorrectfilename
'; - $invalidextensionline .= ''; - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - - $acceptableextensions = AcceptableExtensions($row['fileformat'], $row['audio_dataformat'], $row['video_dataformat']); - $actualextension = strtolower(fileextension($row['filename'])); - if ($acceptableextensions && !in_array($actualextension, $acceptableextensions)) { - $invalidextensionfiles++; - - $invalidextensionline .= ''; - $invalidextensionline .= ''; - $invalidextensionline .= ''; - $invalidextensionline .= ''; - $invalidextensionline .= ''; - $invalidextensionline .= ''; - $invalidextensionline .= ''; - $invalidextensionline .= ''; - $invalidextensionline .= ''; - } - } - $invalidextensionline .= '
fileaudiovideotagsactualcorrectfilename
'.$row['fileformat'].''.$row['audio_dataformat'].''.$row['video_dataformat'].''.$row['tags'].''.$actualextension.''.implode('; ', $acceptableextensions).''.htmlentities($row['filename']).'

'; - echo number_format($invalidextensionfiles).' files with incorrect filename extension:
'; - echo $invalidextensionline; + $acceptableextensions = AcceptableExtensions($row['fileformat'], $row['audio_dataformat'], $row['video_dataformat']); + $actualextension = strtolower(fileextension($row['filename'])); + if ($acceptableextensions && !in_array($actualextension, $acceptableextensions)) { + $invalidextensionfiles++; + $invalidextensionline .= ''; + $invalidextensionline .= ''.$row['fileformat'].''; + $invalidextensionline .= ''.$row['audio_dataformat'].''; + $invalidextensionline .= ''.$row['video_dataformat'].''; + $invalidextensionline .= ''.$row['tags'].''; + $invalidextensionline .= ''.$actualextension.''; + $invalidextensionline .= ''.implode('; ', $acceptableextensions).''; + $invalidextensionline .= ''.htmlentities($row['filename']).''; + $invalidextensionline .= ''; + } + } + $invalidextensionline .= '
'; + echo number_format($invalidextensionfiles).' files with incorrect filename extension:
'; + echo $invalidextensionline; } elseif (isset($_REQUEST['genredistribution'])) { - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - $SQLquery = 'SELECT `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (BINARY `genre` = "'.$_REQUEST['genredistribution'].'")'; - $SQLquery .= ' AND (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } else { - - if ($_REQUEST['genredistribution'] == '%') { - - $SQLquery = 'SELECT COUNT(*) AS `num`, `genre`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; - $SQLquery .= ' GROUP BY `genre`'; - $SQLquery .= ' ORDER BY `num` DESC'; - $result = mysql_query_safe($SQLquery); - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - $GenreID = getid3_id3v1::LookupGenreID($row['genre']); - if (is_numeric($GenreID)) { - echo ''; - } else { - echo ''; - } - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
CountGenrem3u
'.number_format($row['num']).''.str_replace("\t", '
', $row['genre']).'
.m3u

'; - - } else { - - $SQLquery = 'SELECT `filename`, `genre`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`genre` LIKE "'.mysql_real_escape_string($_REQUEST['genredistribution']).'")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - echo 'All Genres
'; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
Genrem3uFilename
'.str_replace("\t", '
', $row['genre']).'
m3u'.htmlentities($row['filename']).'

'; - - } - - - } - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + $SQLquery = 'SELECT `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (BINARY `genre` = "'.$_REQUEST['genredistribution'].'")'; + $SQLquery .= ' AND (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } else { + if ($_REQUEST['genredistribution'] == '%') { + $SQLquery = 'SELECT COUNT(*) AS `num`, `genre`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` NOT LIKE "'.implode('") AND (`fileformat` NOT LIKE "', $IgnoreNoTagFormats).'")'; + $SQLquery .= ' GROUP BY `genre`'; + $SQLquery .= ' ORDER BY `num` DESC'; + $result = mysql_query_safe($SQLquery); + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + $GenreID = getid3_id3v1::LookupGenreID($row['genre']); + if (is_numeric($GenreID)) { + echo ''; + } else { + echo ''; + } + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
CountGenrem3u
'.number_format($row['num']).''.str_replace("\t", '
', $row['genre']).'
.m3u

'; + } else { + $SQLquery = 'SELECT `filename`, `genre`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`genre` LIKE "'.mysql_real_escape_string($_REQUEST['genredistribution']).'")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + echo 'All Genres
'; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
Genrem3uFilename
'.str_replace("\t", '
', $row['genre']).'
m3u'.htmlentities($row['filename']).'

'; + } + } } elseif (!empty($_REQUEST['formatdistribution'])) { - - $SQLquery = 'SELECT `fileformat`, `audio_dataformat`, COUNT(*) AS `num`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' GROUP BY `fileformat`, `audio_dataformat`'; - $SQLquery .= ' ORDER BY `num` DESC'; - $result = mysql_query_safe($SQLquery); - echo 'File format distribution:'; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
NumberFormat
'.number_format($row['num']).''.($row['fileformat'] ? $row['fileformat'] : 'unknown').(($row['audio_dataformat'] && ($row['audio_dataformat'] != $row['fileformat'])) ? '.'.$row['audio_dataformat'] : '').'

'; - + $SQLquery = 'SELECT `fileformat`, `audio_dataformat`, COUNT(*) AS `num`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' GROUP BY `fileformat`, `audio_dataformat`'; + $SQLquery .= ' ORDER BY `num` DESC'; + $result = mysql_query_safe($SQLquery); + echo 'File format distribution:'; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
NumberFormat
'.number_format($row['num']).''.($row['fileformat'] ? $row['fileformat'] : 'unknown').(($row['audio_dataformat'] && ($row['audio_dataformat'] != $row['fileformat'])) ? '.'.$row['audio_dataformat'] : '').'

'; } elseif (!empty($_REQUEST['errorswarnings'])) { + $SQLquery = 'SELECT `filename`, `error`, `warning`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`error` <> "")'; + $SQLquery .= ' OR (`warning` <> "")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); - $SQLquery = 'SELECT `filename`, `error`, `warning`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`error` <> "")'; - $SQLquery .= ' OR (`warning` <> "")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - - if (!empty($_REQUEST['m3u'])) { - - header('Content-type: audio/x-mpegurl'); - echo '#EXTM3U'."\n"; - while ($row = mysql_fetch_array($result)) { - echo WindowsShareSlashTranslate($row['filename'])."\n"; - } - exit; - - } else { - - echo number_format(mysql_num_rows($result)).' files with errors or warnings:
'; - echo '(.m3u version)
'; - echo ''; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - } - echo '
FilenameErrorWarning
'.htmlentities($row['filename']).''.(!empty($row['error']) ? '
  • '.str_replace("\t", '
  • ', htmlentities($row['error'])).'
  • ' : ' ').'
    '.(!empty($row['warning']) ? '
  • '.str_replace("\t", '
  • ', htmlentities($row['warning'])).'
  • ' : ' ').'

    '; - + if (!empty($_REQUEST['m3u'])) { + header('Content-type: audio/x-mpegurl'); + echo '#EXTM3U'."\n"; + while ($row = mysql_fetch_array($result)) { + echo WindowsShareSlashTranslate($row['filename'])."\n"; + } + exit; + } else { + echo number_format(mysql_num_rows($result)).' files with errors or warnings:
    '; + echo '(.m3u version)
    '; + echo ''; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + } + echo '
    FilenameErrorWarning
    '.htmlentities($row['filename']).''.(!empty($row['error']) ? '
  • '.str_replace("\t", '
  • ', htmlentities($row['error'])).'
  • ' : ' ').'
    '.(!empty($row['warning']) ? '
  • '.str_replace("\t", '
  • ', htmlentities($row['warning'])).'
  • ' : ' ').'

    '; } elseif (!empty($_REQUEST['fixid3v1padding'])) { + getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'write.id3v1.php', __FILE__, true); + $id3v1_writer = new getid3_write_id3v1; - getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'write.id3v1.php', __FILE__, true); - $id3v1_writer = new getid3_write_id3v1; - - $SQLquery = 'SELECT `filename`, `error`, `warning`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` = "mp3")'; - $SQLquery .= ' AND (`warning` <> "")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - $totaltofix = mysql_num_rows($result); - $rowcounter = 0; - while ($row = mysql_fetch_array($result)) { - set_time_limit(30); - if (strpos($row['warning'], 'Some ID3v1 fields do not use NULL characters for padding') !== false) { - set_time_limit(30); - $id3v1_writer->filename = $row['filename']; - echo ($id3v1_writer->FixID3v1Padding() ? 'fixed - ' : 'error - '); - } else { - echo 'No error? - '; - } - echo '['.++$rowcounter.' / '.$totaltofix.'] '; - echo htmlentities($row['filename']).'
    '; - flush(); - } - + $SQLquery = 'SELECT `filename`, `error`, `warning`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` = "mp3")'; + $SQLquery .= ' AND (`warning` <> "")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + $totaltofix = mysql_num_rows($result); + $rowcounter = 0; + while ($row = mysql_fetch_array($result)) { + set_time_limit(30); + if (strpos($row['warning'], 'Some ID3v1 fields do not use NULL characters for padding') !== false) { + set_time_limit(30); + $id3v1_writer->filename = $row['filename']; + echo ($id3v1_writer->FixID3v1Padding() ? 'fixed - ' : 'error - '); + } else { + echo 'No error? - '; + } + echo '['.++$rowcounter.' / '.$totaltofix.'] '; + echo htmlentities($row['filename']).'
    '; + flush(); + } } elseif (!empty($_REQUEST['vbrmethod'])) { - - if ($_REQUEST['vbrmethod'] == '1') { - - $SQLquery = 'SELECT COUNT(*) AS `num`, `vbr_method`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' GROUP BY `vbr_method`'; - $SQLquery .= ' ORDER BY `vbr_method`'; - $result = mysql_query_safe($SQLquery); - echo 'VBR methods:'; - echo ''; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - if ($row['vbr_method']) { - echo ''; - } else { - echo ''; - } - echo ''; - } - echo '
    CountVBR Method
    '.htmlentities(number_format($row['num'])).''.htmlentities($row['vbr_method']).'CBR
    '; - - } else { - - $SQLquery = 'SELECT `filename`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`vbr_method` = "'.mysql_real_escape_string($_REQUEST['vbrmethod']).'")'; - $result = mysql_query_safe($SQLquery); - echo number_format(mysql_num_rows($result)).' files with VBR_method of "'.$_REQUEST['vbrmethod'].'":'; - while ($row = mysql_fetch_array($result)) { - echo ''; - echo ''; - } - echo '
    m3u'.htmlentities($row['filename']).'
    '; - - } - echo '
    '; - + if ($_REQUEST['vbrmethod'] == '1') { + $SQLquery = 'SELECT COUNT(*) AS `num`, `vbr_method`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' GROUP BY `vbr_method`'; + $SQLquery .= ' ORDER BY `vbr_method`'; + $result = mysql_query_safe($SQLquery); + echo 'VBR methods:'; + echo ''; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + if ($row['vbr_method']) { + echo ''; + } else { + echo ''; + } + echo ''; + } + echo '
    CountVBR Method
    '.htmlentities(number_format($row['num'])).''.htmlentities($row['vbr_method']).'CBR
    '; + } else { + $SQLquery = 'SELECT `filename`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`vbr_method` = "'.mysql_real_escape_string($_REQUEST['vbrmethod']).'")'; + $result = mysql_query_safe($SQLquery); + echo number_format(mysql_num_rows($result)).' files with VBR_method of "'.$_REQUEST['vbrmethod'].'":'; + while ($row = mysql_fetch_array($result)) { + echo ''; + echo ''; + } + echo '
    m3u'.htmlentities($row['filename']).'
    '; + } + echo '
    '; } elseif (!empty($_REQUEST['correctcase'])) { - - $SQLquery = 'SELECT `filename`, `fileformat`'; - $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; - $SQLquery .= ' WHERE (`fileformat` <> "")'; - $SQLquery .= ' ORDER BY `filename` ASC'; - $result = mysql_query_safe($SQLquery); - echo 'Copy and paste the following into a DOS batch file. You may have to run this script more than once to catch all the changes (remember to scan for deleted/changed files and rescan directory between scans)
    '; - echo '
    ';
    -	$lastdir = '';
    -	while ($row = mysql_fetch_array($result)) {
    -		set_time_limit(30);
    -		$CleanedFilename = CleanUpFileName($row['filename']);
    -		if ($row['filename'] != $CleanedFilename) {
    -			if (strtolower($lastdir) != strtolower(str_replace('/', '\\', dirname($row['filename'])))) {
    -				$lastdir = str_replace('/', '\\', dirname($row['filename']));
    -				echo 'cd "'.$lastdir.'"'."\n";
    -			}
    -			echo 'ren "'.basename($row['filename']).'" "'.basename(CleanUpFileName($row['filename'])).'"'."\n";
    -		}
    -	}
    -	echo '
    '; - echo '
    '; - + $SQLquery = 'SELECT `filename`, `fileformat`'; + $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; + $SQLquery .= ' WHERE (`fileformat` <> "")'; + $SQLquery .= ' ORDER BY `filename` ASC'; + $result = mysql_query_safe($SQLquery); + echo 'Copy and paste the following into a DOS batch file. You may have to run this script more than once to catch all the changes (remember to scan for deleted/changed files and rescan directory between scans)
    '; + echo '
    ';
    +    $lastdir = '';
    +    while ($row = mysql_fetch_array($result)) {
    +        set_time_limit(30);
    +        $CleanedFilename = CleanUpFileName($row['filename']);
    +        if ($row['filename'] != $CleanedFilename) {
    +            if (strtolower($lastdir) != strtolower(str_replace('/', '\\', dirname($row['filename'])))) {
    +                $lastdir = str_replace('/', '\\', dirname($row['filename']));
    +                echo 'cd "'.$lastdir.'"'."\n";
    +            }
    +            echo 'ren "'.basename($row['filename']).'" "'.basename(CleanUpFileName($row['filename'])).'"'."\n";
    +        }
    +    }
    +    echo '
    '; + echo '
    '; } -function CleanUpFileName($filename) { - $DirectoryName = dirname($filename); - $FileExtension = fileextension(basename($filename)); - $BaseFilename = basename($filename, '.'.$FileExtension); +function CleanUpFileName($filename) +{ + $DirectoryName = dirname($filename); + $FileExtension = fileextension(basename($filename)); + $BaseFilename = basename($filename, '.'.$FileExtension); - $BaseFilename = strtolower($BaseFilename); - $BaseFilename = str_replace('_', ' ', $BaseFilename); - //$BaseFilename = str_replace('-', ' - ', $BaseFilename); - $BaseFilename = str_replace('(', ' (', $BaseFilename); - $BaseFilename = str_replace('( ', '(', $BaseFilename); - $BaseFilename = str_replace(')', ') ', $BaseFilename); - $BaseFilename = str_replace(' )', ')', $BaseFilename); - $BaseFilename = str_replace(' \'\'', ' “', $BaseFilename); - $BaseFilename = str_replace('\'\' ', '” ', $BaseFilename); - $BaseFilename = str_replace(' vs ', ' vs. ', $BaseFilename); - while (strstr($BaseFilename, ' ') !== false) { - $BaseFilename = str_replace(' ', ' ', $BaseFilename); - } - $BaseFilename = trim($BaseFilename); + $BaseFilename = strtolower($BaseFilename); + $BaseFilename = str_replace('_', ' ', $BaseFilename); + //$BaseFilename = str_replace('-', ' - ', $BaseFilename); + $BaseFilename = str_replace('(', ' (', $BaseFilename); + $BaseFilename = str_replace('( ', '(', $BaseFilename); + $BaseFilename = str_replace(')', ') ', $BaseFilename); + $BaseFilename = str_replace(' )', ')', $BaseFilename); + $BaseFilename = str_replace(' \'\'', ' “', $BaseFilename); + $BaseFilename = str_replace('\'\' ', '” ', $BaseFilename); + $BaseFilename = str_replace(' vs ', ' vs. ', $BaseFilename); + while (strstr($BaseFilename, ' ') !== false) { + $BaseFilename = str_replace(' ', ' ', $BaseFilename); + } + $BaseFilename = trim($BaseFilename); - return $DirectoryName.'/'.BetterUCwords($BaseFilename).'.'.strtolower($FileExtension); + return $DirectoryName.'/'.BetterUCwords($BaseFilename).'.'.strtolower($FileExtension); } -function BetterUCwords($string) { - $stringlength = strlen($string); +function BetterUCwords($string) +{ + $stringlength = strlen($string); - $string{0} = strtoupper($string{0}); - for ($i = 1; $i < $stringlength; $i++) { - if (($string{$i - 1} == '\'') && ($i > 1) && (($string{$i - 2} == 'O') || ($string{$i - 2} == ' '))) { - // O'Clock, 'Em - $string{$i} = strtoupper($string{$i}); - } elseif (preg_match('#^[\'A-Za-z0-9À-ÿ]$#', $string{$i - 1})) { - $string{$i} = strtolower($string{$i}); - } else { - $string{$i} = strtoupper($string{$i}); - } - } + $string{0} = strtoupper($string{0}); + for ($i = 1; $i < $stringlength; $i++) { + if (($string{$i - 1} == '\'') && ($i > 1) && (($string{$i - 2} == 'O') || ($string{$i - 2} == ' '))) { + // O'Clock, 'Em + $string{$i} = strtoupper($string{$i}); + } elseif (preg_match('#^[\'A-Za-z0-9À-ÿ]$#', $string{$i - 1})) { + $string{$i} = strtolower($string{$i}); + } else { + $string{$i} = strtoupper($string{$i}); + } + } - static $LowerCaseWords = array('vs.', 'feat.'); - static $UpperCaseWords = array('DJ', 'USA', 'II', 'MC', 'CD', 'TV', '\'N\''); + static $LowerCaseWords = ['vs.', 'feat.']; + static $UpperCaseWords = ['DJ', 'USA', 'II', 'MC', 'CD', 'TV', '\'N\'']; - $OutputListOfWords = array(); - $ListOfWords = explode(' ', $string); - foreach ($ListOfWords as $ThisWord) { - if (in_array(strtolower(str_replace('(', '', $ThisWord)), $LowerCaseWords)) { - $ThisWord = strtolower($ThisWord); - } elseif (in_array(strtoupper(str_replace('(', '', $ThisWord)), $UpperCaseWords)) { - $ThisWord = strtoupper($ThisWord); - } elseif ((substr($ThisWord, 0, 2) == 'Mc') && (strlen($ThisWord) > 2)) { - $ThisWord{2} = strtoupper($ThisWord{2}); - } elseif ((substr($ThisWord, 0, 3) == 'Mac') && (strlen($ThisWord) > 3)) { - $ThisWord{3} = strtoupper($ThisWord{3}); - } - $OutputListOfWords[] = $ThisWord; - } - $UCstring = implode(' ', $OutputListOfWords); - $UCstring = str_replace(' From “', ' from “', $UCstring); - $UCstring = str_replace(' \'n\' ', ' \'N\' ', $UCstring); + $OutputListOfWords = []; + $ListOfWords = explode(' ', $string); + foreach ($ListOfWords as $ThisWord) { + if (in_array(strtolower(str_replace('(', '', $ThisWord)), $LowerCaseWords)) { + $ThisWord = strtolower($ThisWord); + } elseif (in_array(strtoupper(str_replace('(', '', $ThisWord)), $UpperCaseWords)) { + $ThisWord = strtoupper($ThisWord); + } elseif ((substr($ThisWord, 0, 2) == 'Mc') && (strlen($ThisWord) > 2)) { + $ThisWord{2} = strtoupper($ThisWord{2}); + } elseif ((substr($ThisWord, 0, 3) == 'Mac') && (strlen($ThisWord) > 3)) { + $ThisWord{3} = strtoupper($ThisWord{3}); + } + $OutputListOfWords[] = $ThisWord; + } + $UCstring = implode(' ', $OutputListOfWords); + $UCstring = str_replace(' From “', ' from “', $UCstring); + $UCstring = str_replace(' \'n\' ', ' \'N\' ', $UCstring); - return $UCstring; + return $UCstring; } @@ -2178,19 +1994,19 @@ $SQLquery = 'SELECT COUNT(*) AS `TotalFiles`, SUM(`playtime_seconds`) AS `Total $SQLquery .= ' FROM `'.mysql_real_escape_string(GETID3_DB_TABLE).'`'; $result = mysql_query_safe($SQLquery); if ($row = mysql_fetch_array($result)) { - echo '
    '; - echo '
    '; - echo 'Spent '.number_format(mysql_query_safe(null), 3).' seconds querying the database
    '; - echo '
    '; - echo 'Currently in the database:'; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '
    Total Files'.number_format($row['TotalFiles']).'
    Total Filesize'.number_format($row['TotalFilesize'] / 1048576).' MB
    Total Playtime'.number_format($row['TotalPlaytime'] / 3600, 1).' hours
    Average Filesize'.number_format($row['AvgFilesize'] / 1048576, 1).' MB
    Average Playtime'.getid3_lib::PlaytimeString($row['AvgPlaytime']).'
    Average Bitrate'.BitrateText($row['AvgBitrate'] / 1000, 1).'
    '; - echo '
    '; + echo '
    '; + echo '
    '; + echo 'Spent '.number_format(mysql_query_safe(null), 3).' seconds querying the database
    '; + echo '
    '; + echo 'Currently in the database:'; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo '
    Total Files'.number_format($row['TotalFiles']).'
    Total Filesize'.number_format($row['TotalFilesize'] / 1048576).' MB
    Total Playtime'.number_format($row['TotalPlaytime'] / 3600, 1).' hours
    Average Filesize'.number_format($row['AvgFilesize'] / 1048576, 1).' MB
    Average Playtime'.getid3_lib::PlaytimeString($row['AvgPlaytime']).'
    Average Bitrate'.BitrateText($row['AvgBitrate'] / 1000, 1).'
    '; + echo '
    '; } -echo ''; \ No newline at end of file +echo ''; diff --git a/app/Library/getid3/demos/demo.simple.php b/app/Library/getid3/demos/demo.simple.php index dbaf7bb6..39b69944 100644 --- a/app/Library/getid3/demos/demo.simple.php +++ b/app/Library/getid3/demos/demo.simple.php @@ -32,24 +32,24 @@ $dir = opendir($DirectoryToScan); echo ''; echo ''; while (($file = readdir($dir)) !== false) { - $FullFileName = realpath($DirectoryToScan.'/'.$file); - if ((substr($file, 0, 1) != '.') && is_file($FullFileName)) { - set_time_limit(30); + $FullFileName = realpath($DirectoryToScan.'/'.$file); + if ((substr($file, 0, 1) != '.') && is_file($FullFileName)) { + set_time_limit(30); - $ThisFileInfo = $getID3->analyze($FullFileName); + $ThisFileInfo = $getID3->analyze($FullFileName); - getid3_lib::CopyTagsToComments($ThisFileInfo); + getid3_lib::CopyTagsToComments($ThisFileInfo); - // output desired information in whatever format you want - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } + // output desired information in whatever format you want + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } } echo '
    FilenameArtistTitleBitratePlaytime
    '.htmlentities($ThisFileInfo['filenamepath']).'' .htmlentities(!empty($ThisFileInfo['comments_html']['artist']) ? implode('
    ', $ThisFileInfo['comments_html']['artist']) : chr(160)).'
    ' .htmlentities(!empty($ThisFileInfo['comments_html']['title']) ? implode('
    ', $ThisFileInfo['comments_html']['title']) : chr(160)).'
    '.htmlentities(!empty($ThisFileInfo['audio']['bitrate']) ? round($ThisFileInfo['audio']['bitrate'] / 1000).' kbps' : chr(160)).''.htmlentities(!empty($ThisFileInfo['playtime_string']) ? $ThisFileInfo['playtime_string'] : chr(160)).'
    '.htmlentities($ThisFileInfo['filenamepath']).'' .htmlentities(!empty($ThisFileInfo['comments_html']['artist']) ? implode('
    ', $ThisFileInfo['comments_html']['artist']) : chr(160)).'
    ' .htmlentities(!empty($ThisFileInfo['comments_html']['title']) ? implode('
    ', $ThisFileInfo['comments_html']['title']) : chr(160)).'
    '.htmlentities(!empty($ThisFileInfo['audio']['bitrate']) ? round($ThisFileInfo['audio']['bitrate'] / 1000).' kbps' : chr(160)).''.htmlentities(!empty($ThisFileInfo['playtime_string']) ? $ThisFileInfo['playtime_string'] : chr(160)).'
    '; -echo ''; \ No newline at end of file +echo ''; diff --git a/app/Library/getid3/demos/demo.simple.write.php b/app/Library/getid3/demos/demo.simple.write.php index 73d38bba..5cfd7975 100644 --- a/app/Library/getid3/demos/demo.simple.write.php +++ b/app/Library/getid3/demos/demo.simple.write.php @@ -19,7 +19,7 @@ $TextEncoding = 'UTF-8'; require_once('../getid3/getid3.php'); // Initialize getID3 engine $getID3 = new getID3; -$getID3->setOption(array('encoding'=>$TextEncoding)); +$getID3->setOption(['encoding'=>$TextEncoding]); require_once('../getid3/write.php'); // Initialize getID3 tag-writing module @@ -28,7 +28,7 @@ $tagwriter = new getid3_writetags; $tagwriter->filename = 'c:/file.mp3'; //$tagwriter->tagformats = array('id3v1', 'id3v2.3'); -$tagwriter->tagformats = array('id3v2.3'); +$tagwriter->tagformats = ['id3v2.3']; // set various options (optional) $tagwriter->overwrite_tags = true; // if true will erase existing tag data and write only passed data; if false will merge passed data with existing tag data (experimental) @@ -37,24 +37,24 @@ $tagwriter->tag_encoding = $TextEncoding; $tagwriter->remove_other_tags = true; // populate data array -$TagData = array( - 'title' => array('My Song'), - 'artist' => array('The Artist'), - 'album' => array('Greatest Hits'), - 'year' => array('2004'), - 'genre' => array('Rock'), - 'comment' => array('excellent!'), - 'track' => array('04/16'), - 'popularimeter' => array('email'=>'user@example.net', 'rating'=>128, 'data'=>0), -); +$TagData = [ + 'title' => ['My Song'], + 'artist' => ['The Artist'], + 'album' => ['Greatest Hits'], + 'year' => ['2004'], + 'genre' => ['Rock'], + 'comment' => ['excellent!'], + 'track' => ['04/16'], + 'popularimeter' => ['email'=>'user@example.net', 'rating'=>128, 'data'=>0], +]; $tagwriter->tag_data = $TagData; // write tags if ($tagwriter->WriteTags()) { - echo 'Successfully wrote tags
    '; - if (!empty($tagwriter->warnings)) { - echo 'There were some warnings:
    '.implode('

    ', $tagwriter->warnings); - } + echo 'Successfully wrote tags
    '; + if (!empty($tagwriter->warnings)) { + echo 'There were some warnings:
    '.implode('

    ', $tagwriter->warnings); + } } else { - echo 'Failed to write tags!
    '.implode('

    ', $tagwriter->errors); + echo 'Failed to write tags!
    '.implode('

    ', $tagwriter->errors); } diff --git a/app/Library/getid3/demos/demo.write.php b/app/Library/getid3/demos/demo.write.php index c15394b3..32671e84 100644 --- a/app/Library/getid3/demos/demo.write.php +++ b/app/Library/getid3/demos/demo.write.php @@ -25,7 +25,7 @@ echo 'getID3() - Sample tag writer