<?php

/*
Скрипт загруз центра для JohnCMS
Автор: Максим (simba)
ICQ: 61590077
Сайт: http://symbos.su
R866920725287
Z117468354234
*/

/*
Tag Editor by Koenig
*/

/*
Tag Editor Translation & Modification by Debendra
http://www.debendra.cf
debendraoli@gmail.com
*/

define('_IN_JOHNCMS', 1);
$headmod = 'editid3';
$textl = 'Tags editor';
require_once '../incfiles/core.php';
require_once '../incfiles/head.php';
require_once 'functions.php';

if ($rights < 7) {
die('Access deny');    
}

spl_autoload_register('dnlautoload');   
function dnlautoload($class) {
$file = 'lib' . DIRECTORY_SEPARATOR . 'getid3' . DIRECTORY_SEPARATOR . strtolower($class) . '.php';
if (file_exists($file)) {
require_once($file);
} else {
die('Class - ' . $class . ' not found');  
}
}

$TaggingFormat = 'UTF-8';

#require_once('../getid3/getid3.php');

$getID3 = new getID3;
$getID3->setOption(array('encoding'=>$TaggingFormat));
getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'write.php', __FILE__, true);

$Filename = isset($_GET['file']) ? $_GET['file'] : die('Error');

if (isset($_POST['WriteTags'])) {

    $TagFormatsToWrite = (isset($_POST['TagFormatsToWrite']) ? $_POST['TagFormatsToWrite'] : array());
    if (!empty($TagFormatsToWrite)) {
        $tagwriter = new getid3_writetags;
        $tagwriter->filename       = $Filename;
        $tagwriter->tagformats     = $TagFormatsToWrite;
        $tagwriter->overwrite_tags = true;
        $tagwriter->tag_encoding   = $TaggingFormat;
        if (!empty($_POST['remove_other_tags'])) {
            $tagwriter->remove_other_tags = true;
        }

        $commonkeysarray = array('Title', 'Artist', 'Album', 'Year', 'Comment');
        foreach ($commonkeysarray as $key) {
            if (!empty($_POST[$key])) {
                $TagData[strtolower($key)][] = $_POST[$key];
            }
        }
        if (!empty($_POST['Genre'])) {
            $TagData['genre'][] = $_POST['Genre'];
        }
        if (!empty($_POST['GenreOther'])) {
            $TagData['genre'][] = $_POST['GenreOther'];
        }
        if (!empty($_POST['Track'])) {
            $TagData['track'][] = $_POST['Track'].(!empty($_POST['TracksTotal']) ? '/'.$_POST['TracksTotal'] : '');
        }

        if (!empty($_FILES['userfile']['tmp_name'])) {
            if (in_array('id3v2.4', $tagwriter->tagformats) || in_array('id3v2.3', $tagwriter->tagformats) || in_array('id3v2.2', $tagwriter->tagformats)) {
                if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
                    ob_start();
                    if ($fd = fopen($_FILES['userfile']['tmp_name'], 'rb')) {
                        ob_end_clean();
                        $APICdata = fread($fd, filesize($_FILES['userfile']['tmp_name']));
                        fclose ($fd);

                        list($APIC_width, $APIC_height, $APIC_imageTypeID) = GetImageSize($_FILES['userfile']['tmp_name']);
                        $imagetypes = array(1=>'gif', 2=>'jpeg', 3=>'png');
                        if (isset($imagetypes[$APIC_imageTypeID])) {

                            $TagData['attached_picture'][0]['data']          = $APICdata;
                            $TagData['attached_picture'][0]['picturetypeid'] = $_POST['APICpictureType'];
                            $TagData['attached_picture'][0]['description']   = $_FILES['userfile']['name'];
                            $TagData['attached_picture'][0]['mime']          = 'image/'.$imagetypes[$APIC_imageTypeID];

                        } else {
                            echo $lng_dl['void_img'];
                        }
                    } else {
                        $errormessage = ob_get_contents();
                        ob_end_clean();
                        echo '<b>' . $lng_dl['failed_open'] . $_FILES['userfile']['tmp_name'] . '</b><br>';
                    }
                } else {
                    echo '<b>!is_uploaded_file('.$_FILES['userfile']['tmp_name'].')</b><br>';
                }
            } else {
                echo $lng_dl['warn_embeding'];
            }
        }

        $tagwriter->tag_data = $TagData;
        if ($tagwriter->WriteTags()) {
            echo $lng_dl['success_tagging'];
            if (!empty($tagwriter->warnings)) {
                echo functions::display_error(implode('<br /><br />', $tagwriter->warnings));
                }
        } else {
            echo functions::display_error(implode('<br /><br />', $tagwriter->errors));
            }

    } else {

        echo $lng_dl['no_support'];

    }
    echo '<hr />';

}

if (!empty($Filename)) {
    echo '<form class="form-horizontal" action="?file=' . $Filename . '" method="post" enctype="multipart/form-data">
	<fieldset>';
    if (file_exists($Filename)) {
// Initialize getID3 engine
        $getID3 = new getID3;
        $OldThisFileInfo = $getID3->analyze($Filename);
        getid3_lib::CopyTagsToComments($OldThisFileInfo);

        switch ($OldThisFileInfo['fileformat']) {
            case 'mp3':
            $ValidTagTypes = array('id3v1', 'id3v2.3');
                break;
            default:
                $ValidTagTypes = array();
                break;
        }
        echo '<div class="form-group">
                <label for="title" class="col-lg-2 control-label">' . $lng_dl['title'] . '</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" id="title" name="Title" value="'.htmlentities((!empty($OldThisFileInfo['comments']['title'])  ? implode(', ', $OldThisFileInfo['comments']['title'] ) : ''), ENT_QUOTES).'" />
                </div></div>
				<div class="form-group">
<label for="artist" class="col-lg-2 control-label">Ijrochi</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" id="artist" name="Artist" value="'.htmlentities((!empty($OldThisFileInfo['comments']['artist'])  ? implode(', ', $OldThisFileInfo['comments']['artist'] ) : ''), ENT_QUOTES).'" />
                </div></div>
				<div class="form-group">
<label for="album" class="col-lg-2 control-label">Albom 
</label>
                <div class="col-lg-10">
                    <input type="text" class="form-control" id="album" name="Album" value="'.htmlentities((!empty($OldThisFileInfo['comments']['album'])  ? implode(', ', $OldThisFileInfo['comments']['album'] ) : ''), ENT_QUOTES).'" />
                </div></div>
				<div class="form-group">
<label for="year" class="col-lg-2 control-label">Yil</label>
                <div class="col-lg-5">
                    <input type="text" id="year" name="Year" size="5" value="'.htmlentities((!empty($OldThisFileInfo['comments']['year'])  ? implode(', ', $OldThisFileInfo['comments']['year'] ) : ''), ENT_QUOTES).'" />
                </div></div>';
        $TracksTotal = '';
        $TrackNumber = '';
        if (!empty($OldThisFileInfo['comments']['track_number']) && is_array($OldThisFileInfo['comments']['track_number'])) {
            $RawTrackNumberArray = $OldThisFileInfo['comments']['track_number'];
        } elseif (!empty($OldThisFileInfo['comments']['track']) && is_array($OldThisFileInfo['comments']['track'])) {
            $RawTrackNumberArray = $OldThisFileInfo['comments']['track'];
        } else {
            $RawTrackNumberArray = array();
        }
        foreach ($RawTrackNumberArray as $key => $value) {
            if (strlen($value) > strlen($TrackNumber)) {
                // ID3v1 may store track as "3" but ID3v2/APE would store as "03/16"
                $TrackNumber = $value;
            }
        }
        if (strstr($TrackNumber, '/')) {
            list($TrackNumber, $TracksTotal) = explode('/', $TrackNumber);
        }
        echo '<div class="form-group">
                <label for="tracks" class="col-lg-2 control-label">' . $lng_dl['track'] . '</label>
                <div class="col-lg-5"><input type="text" id="tracks" size="2" name="Track" value="'.htmlentities($TrackNumber, ENT_QUOTES).'" /> of <input type="text" id="tracks" size="2" name="TracksTotal" value="'.htmlentities($TracksTotal, ENT_QUOTES).'" /></div></div>';

        $ArrayOfGenresTemp = getid3_id3v1::ArrayOfGenres();   // get the array of genres
        foreach ($ArrayOfGenresTemp as $key => $value) {      // change keys to match displayed value
            $ArrayOfGenres[$value] = $value;
        }
        unset($ArrayOfGenresTemp);                            // remove temporary array
        unset($ArrayOfGenres['Cover']);                       // take off these special cases
        unset($ArrayOfGenres['Remix']);
        unset($ArrayOfGenres['Unknown']);
        $ArrayOfGenres['']      = '- Unknown -';              // Add special cases back in with renamed key/value
        $ArrayOfGenres['Cover'] = '-Cover-';
        $ArrayOfGenres['Remix'] = '-Remix-';
        asort($ArrayOfGenres);                                // sort into alphabetical order
        echo '<div class="form-group">
<label for="genre" class="col-lg-2 control-label">Janr</label>
                <div class="col-lg-10">
                    <select name="Genre" class="form-control" id="genre">';
	        $AllGenresArray = (!empty($OldThisFileInfo['comments']['genre']) ? $OldThisFileInfo['comments']['genre'] : array());
        foreach ($ArrayOfGenres as $key => $value) {
            echo '<option value="'.htmlentities($key, ENT_QUOTES).'"';
            if (in_array($key, $AllGenresArray)) {
                echo ' selected="selected"';
                unset($AllGenresArray[array_search($key, $AllGenresArray)]);
                sort($AllGenresArray);
            }
            echo '>'.htmlentities($value).'</option>';
        }
        echo '</select>
		<div><input type="text" class="form-control" id="genre" name="GenreOther" value="'.htmlentities((!empty($AllGenresArray[0]) ? $AllGenresArray[0] : ''), ENT_QUOTES).'" /></div>
                </div>
            </div>';

        echo '<div class="form-group">
                <label for="format" class="col-lg-2 control-label">' . $lng_dl['tag_ver'] . '</label>
                <div class="col-lg-10">
                    <select name="TagFormatsToWrite[]" class="form-control" id="format">';
        foreach ($ValidTagTypes as $ValidTagType) {
            echo '<option value="' . $ValidTagType . '"';
            if (count($ValidTagTypes) == 1) {
                echo ' selected="selected"';
            } else {
                switch ($ValidTagType) {
                    case 'id3v2.2':
                    case 'id3v2.3':
                    case 'id3v2.4':
                        if (isset($OldThisFileInfo['tags']['id3v2'])) {
                            echo ' selected="selected"';
                        }
                        break;

                    default:
                        if (isset($OldThisFileInfo['tags'][$ValidTagType])) {
                            echo ' selected="selected"';
                        }
                        break;
                }
            }
            echo ' >'.$ValidTagType.'</option>';
        }
		echo '</select>';
        if (count($ValidTagTypes) > 1) {
echo '<div class="chexbox"><label><input type="checkbox" name="remove_other_tags" value="1" /> Delete unmarked version tag</label></div></div>';
        }
        
        echo '<div class="form-group">
<label for="comment" class="col-lg-2 control-label">Komentariya</label>
                <div class="col-lg-10">
                    <textarea class="form-control" name="Comment" rows="3" id="comment">'.((isset($OldThisFileInfo['comments']['comment']) && is_array($OldThisFileInfo['comments']['comment'])) ? implode("\n", $OldThisFileInfo['comments']['comment']) : '').'</textarea>
                </div>
            </div>
			<div class="form-group">
<label for="arttype" class="col-lg-2 control-label">Janr</label>
                <div class="col-lg-10">
                    <select name="APICpictureType" class="form-control" id="arttype">';
        $APICtypes = getid3_id3v2::APICPictureTypeLookup('', true);
        foreach ($APICtypes as $key => $value) {
            echo '<option value="'.htmlentities($key, ENT_QUOTES).'">'.htmlentities($value).'</option>';
        }
        echo '</select></div></div>
        <div class="form-group">
    <label for="art">' . $lng_dl['cover_art'] . '</label>
	<input type="file" class="form-control" id="art" name="userfile" accept="image/jpeg, image/gif, image/png">
    <span class="help-block">ID3v2 only</span>
     </div>
        
		<div class="container">
		<div class="row">
      <img id="FileImage" class="img-rounded" src="data:' . $OldThisFileInfo['comments']['picture'][0]['image_mime'] . ' ;charset=utf-8;base64,' . base64_encode($OldThisFileInfo['comments']['picture'][0]['data']) . '" width="280" alt="Album art">
	  </div></div>
	  <div class="form-group">
                <div class="col-lg-10 col-lg-offset-2">
                    <button type="submit" name="WriteTags" class="btn btn-primary" value="' . $lng_dl['write_tag'] . '">' . $lng_dl['write_tag'] . '</button>
                </div>
            </div>
        </fieldset></form>';
    } else {
        echo '<div class="alert alert-dismissible alert-warning">' . $lng_dl['tagging_err'] . ' <b>'.htmlentities($Filename).'</b> ' . $lng_dl['not_found'] . '</div>';
    }
}
echo '<div><a href="./">' . $lng_dl['back'] . '</a></div>';

require_once '../incfiles/end.php';