<?php

/*

Kontackt License Agreement (DMCA License)

Copyright (c) 2015, Alex Dobrovolscki (dobriisasa@gmail.com)
All rights reserved.

* Redistributions of source code is strictly forbidden.

* By using Kontackt you may have your own purchase copy, if you are not own a license, you can buy one from https://codecanyon.net/user/dobrovolscki/portfolio.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/


 
 
$upload_media = true;
// engine file
require_once('../inc/_core.php');
	// build engine
	$core = new _SOCIALPLUS;
	
	$this = $core;
	Upload();
// upload files
function Upload(){
global $this;
//define variables
$count   = 0;
$searchG = "bad";
$singer  = $this->singer; // from settings
$this->vimeo   = new phpVimeo($this->VIMEO_APP_ID, $this->VIMEO_APP_SECRET);
$artist  = $song = $album = $year = $comment = $genre = $recCover = $srchim = $message = $b0 = $db_video = $ex_v = $id_video = $cover_file = "";
$dir_cov = str_replace('..','',__FILE_COVER_DIR);

// upload
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
    
    // Loop $_FILES to execute all files
    foreach ($_FILES['files']['name'] as $f => $name) {
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }
        if ($_FILES['files']['error'][$f] == 0) {
            if ($_FILES['files']['size'][$f] > $this->max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            } elseif (!in_array(pathinfo(strtolower($name), PATHINFO_EXTENSION), $this->valid_formats)) {
                $message[] = "$name is not a valid format, only " . $this->valid_formats[1];
                continue; // Skip invalid file formats
                
            } else {
                
                $temp    = explode('.', $_FILES['files']['name'][$f]);
                $newName = mt_rand().mt_rand().mt_rand() . '.' . end($temp);

                // No error found! Move uploaded files 
                if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $this->output_dir . $newName)) {
                    $count++; // Number of successfully uploaded files
                    
                    /* analyze the file and get details of it */
                    
                    $name_m   = $_FILES["files"]["name"][$f];
                    $name_n   = explode(".", $name_m);
                    $filename = $newName;
                    $nameb    = explode(".", $filename);
                    
                    // build getId3
                    $getID3 = new getID3;
                    $getID3->encoding = 'UTF-8';      

                    $uploadedFile = $this->output_dir . $filename;
                    $ThisFileInfo = $getID3->analyze($uploadedFile);
                    
		    // check if file contain tags and bitrate not less 128kbs
		    if(isset($ThisFileInfo['error'][0]) || (!$ThisFileInfo['audio']['bitrate'] || $ThisFileInfo['audio']['bitrate'] < 128000)){
		    @unlink($uploadedFile);
		    die('Sorry, the file ['.$name.'] should meet the following technical requirements: bit rate not less than
			 128kbps, sampling frequency not less than 44,1 kHz.');
		    }
                    
                    if (isset($ThisFileInfo['tags'][0]['id3v1']['title'][0])) {
                        $song = $this->ch($this->esc($ThisFileInfo['tags'][0]['id3v1']['title'][0]));
                    } else if (isset($ThisFileInfo['tags']['id3v2']['title'][0])) {
                        $song = $this->ch($this->esc($ThisFileInfo['tags']['id3v2']['title'][0]));
                    } else {
                        $song = "unknown";
                    }
                    
                    if (isset($ThisFileInfo['tags']['id3v2']['artist'][0])) {
                        $artist = $this->ch($this->esc($ThisFileInfo['tags']['id3v2']['artist'][0]));
			$artist_ch = $ThisFileInfo['tags']['id3v2']['artist'][0];
                    } else if (isset($ThisFileInfo['tags']['id3v1']['artist'][0])) {
                        $artist = $this->ch($this->esc($ThisFileInfo['tags']['id3v1']['artist'][0]));
			$artist_ch = $ThisFileInfo['tags']['id3v1']['artist'][0];
                    } else {
                        $artist = "Unknown Artist";
			$artist_ch = $artist;
                    }
                    
                    if (isset($ThisFileInfo['tags']['id3v2']['album'][0])) {
                        $album = $this->ch($this->esc($ThisFileInfo['tags']['id3v2']['album'][0]));
                    } else if (isset($ThisFileInfo['tags']['id3v1']['album'][0])) {
                        $album = $this->ch($this->esc($ThisFileInfo['tags']['id3v1']['album'][0]));
                    } else {
                        $album = "unknown album";
                    }
                    
                    if (isset($ThisFileInfo['tags']['id3v1']['year'][0])) {
                        $year = $this->esc($ThisFileInfo['tags']['id3v1']['year'][0]);
                    } else if (isset($ThisFileInfo['tags']['id3v2']['year'][0])) {
                        $year = $this->esc($ThisFileInfo['tags']['id3v2']['year'][0]);
                    } else {
                        $year = "unknown";
                    }
                    
                    
                    if (isset($ThisFileInfo['tags']['id3v2']['comment'][0])) {
                        $comment = $this->ch($this->esc($ThisFileInfo['tags']['id3v2']['comment'][0]));
                    } else if (isset($ThisFileInfo['tags']['id3v1']['comment'][0])) {
                        $comment = $this->ch($this->esc($ThisFileInfo['tags']['id3v1']['comment'][0]));
                    } else {
                        $comment = $artist;
                    }
                    
                    if (isset($ThisFileInfo['tags']['id3v2']['genre'][0])) {
                        $genre = $this->esc($ThisFileInfo['tags']['id3v2']['genre'][0]);
                    } else if (isset($ThisFileInfo['tags']['id3v1']['genre'][0])) {
                        $genre = $this->esc($ThisFileInfo['tags']['id3v1']['genre'][0]);
                    } else {
                        $genre = "unknown";
                    }
                    
                    if (isset($ThisFileInfo['id3v2']['COMM'][0]['languagename'])) {
                        $language = $this->esc($ThisFileInfo['id3v2']['COMM'][0]['languagename']);
                    } else {
                        $language = "unknown";
                    }
                    
                    if (isset($ThisFileInfo['playtime_string']))
                        $duration = $this->esc($ThisFileInfo['playtime_string']);
                    else
                        $duration = "unknown";
                    
// create cover from file [implemented in v1.5]
if(!file_exists(__FILE_COVER_DIR.$this->rplchr($this->clean_string($artist)).'___'.$this->rplchr($this->clean_string($album)).'.png')){
if (isset($getID3->info['id3v2']['APIC'][0]['data'])) { 
   $cover_file = $getID3->info['id3v2']['APIC'][0]['data']; 
} elseif (isset($getID3->info['id3v2']['PIC'][0]['data'])) { 
   $cover_file = $getID3->info['id3v2']['PIC'][0]['data']; 
} else { 
   $cover_file = ''; 
} 
if (isset($getID3->info['id3v2']['APIC'][0]['image_mime'])) { 
   $mimetype = $getID3->info['id3v2']['APIC'][0]['image_mime']; 
} else { 
   $mimetype = 'image/jpeg';
} 

if (!empty($cover_file)) {


// Send file 
header("Content-Type: " . $mimetype); 

if (isset($getID3->info['id3v2']['APIC'][0]['image_bytes'])) { 
    header("Content-Length: " . $getID3->info['id3v2']['APIC'][0]['image_bytes']); 
} 
if(file_put_contents(__FILE_COVER_DIR.$this->rplchr($this->clean_string($artist)).'___'.$this->rplchr($this->clean_string($album)).'.png', $cover_file)){
$recCover = '/music/'.$dir_cov.$this->rplchr($this->clean_string($artist)).'___'.$this->rplchr($this->clean_string($album)).'.png';
}else
$recCover = $this->defaultCover;

} else {


                    // receive name of the cover and send in rapidapi
                    if ($artist !== $name_n[0] && $artist !== 'Unknown Artist') {
                        $searchG      = "ok";
                        $cover_search = $this->es_rus($artist_ch);///$this->rplchr($this->rpl($artist));
                    } else if ($song != "unknown") {
                        $searchG      = "bad";
                        $cover_search = $this->rplchr($this->rpl($song));
                    } else if ($album != "unknown") {
                        $searchG      = "bad";
                        $cover_search = $this->rplchr($this->rpl($album));
                    } else {
                        $searchG = "bad";
                        $b0      = $this->rplchr($this->rpl($artist));
						
                        if (!empty($b0)) {
                            $searchG      = "bad";
                            $cover_search = $this->rplchr($this->rpl($artist));
                        }
                        
                    }
                                 
               
                    // get cover from rapidapi
                    if ($searchG !== 'bad') {
                       
						$images = $this->search_for_covers($cover_search,99,false);       
                      ///  $images = $this->google_get_cover($cover_search);
						$images = $images['value'];
                        $c = count($images);
           
                        //generate a random cover from an array result given by rapidapi
                        for ($i = 0; $i < $c; $i++) {
                            $i = rand(0, $c);
                            $recCover = isset($images[$i]['url']) ? $images[$i]['url'] : '';
                        }
                        

                    } else {
                        
                        $recCover = $this->defaultCover;
                    }
                    
} // else [ if file has no cover ]

}else // else [ if for current uploading song exist already cover ]
$recCover = '/music/'.$dir_cov.$this->rplchr($this->clean_string($artist)).'___'.$this->rplchr($this->clean_string($album)).'.png';

                    // get video from vimeo
                    $v_art  = preg_replace("/\([^)]+\)/", "", $artist);
                    $v_song = preg_replace("/\([^)]+\)/", "", $song); 
					$v_art_song = $v_art.' '.$v_song;
					$id_video = $title_video = $video_community = '';
                   /* if ($v_art !== 'Unknown Artist' && $v_song !== 'unknown')
                        $video = $this->searchForVideo($this->rplchr($v_art),$this->rplchr($v_song));//$this->vimeo_get_video($this->rplchr($v_art) . ' ' . $this->rplchr($v_song));
                    else
                        $video = '0';*/
                    
					if ($v_art !== 'Unknown Artist' && $v_song !== 'unknown'){
						$video = $this->searchForVideo($v_art,$v_song);
						
						 
						if( $video ){
							
						 
						$video = $video['0'];
                        $id_video    = $video['id'];
                        $title_video = $video['title'];
						$video_community = $video['video_community'];
							//echo $title_video;die;
						}
						
					} else
                        $video = '0';
					
						
					
						
						
						
					
					
					/*
					
					
                    if ($video !== '0' && array_key_exists('0', $video) && $video['0']->embed_privacy == 'anywhere') {
                        $video       = $video['0'];
                        $id_video    = $video->id;
                        $title_video = $video->title;
                    } else if ($video !== '0' && array_key_exists('1', $video) && $video['1']->embed_privacy == 'anywhere') {
                        $video       = $video['1'];
                        $title_video = $video->title;
                        $id_video    = $video->id;
                    } else if ($video !== '0' && array_key_exists('2', $video) && $video['2']->embed_privacy == 'anywhere') {
                        $video       = $video['2'];
                        $id_video    = $video->id;
                        $title_video = $video->title;
                    }*/
                    	///print_r($video);die;
                    if ($id_video && $title_video){
						
							$str_video_txt = ($this->l_mb_string($title_video));
							$str_mp3_txt = ($this->l_mb_string($v_art_song));

							$str_video = array();
							$c_find_word = 0;
							$confirmed_is_video = false;
							
							$str_video = @preg_split("/[\s,-]+/", $str_video_txt);
							$str_mp3 = @preg_split("/[\s,-]+/", $str_mp3_txt);

					 
							if (carray($str_mp3) && count($str_mp3)){
							foreach($str_mp3 as $word):
							$confirmed_is_video = true;
							if( strstr($str_video_txt,$word) )
							$c_find_word++;

							endforeach;
							}
							

							$db_video = ($c_find_word == count($str_video)) && $confirmed_is_video ? $id_video : '0';
						
						
					}
					
				
					////strpos(strtolower(trim($title_video)), strtolower(trim($v_art_song, " "))) || strpos( strtolower(trim($v_art_song, " ")), strtolower(trim($title_video))) ? $id_video : '0';
                    
					//echo $db_video;die;// strtolower(trim($title_video)).' ----- '.strtolower(trim($v_art_song, " "));
                    $path     = $newName;
                    $time     = $this->esc($duration);
                    $cover    = $this->esc($recCover);
                    $title    = $song;
                    $added    = time();
                    $uploader = $this->esc($this->USER['id']);
                    $method   = $_POST['uploadin'];
		    $pl_covr  = isset($_POST['pl_cover']) ? $_POST['pl_cover'] : '';
		    $artist   = $artist !== 'Unknown Artist' ? $artist : $name;
		    $artist_x   = str_replace('+', '&', $artist);
		    $song     = str_replace('+', '&', $song);
		    $album    = str_replace('+', '&', $album);
		    $artist   = str_replace('&amp;', '&', $artist_x);

		    // Escape artist, album ,song
         	    $artist   = $this->core->test_input($artist);
		    $song     = $this->core->test_input($song);
		    $album    = $this->core->test_input($album);

                    //insert into db                   
                    $insert     = $this->__om_query_insert("insert into ".nobil_om_songs." set 
                          				   `artist`='{$artist}',`title`='{$song}',`time`='{$time}',`video_community`='{$video_community}',`genre`='{$genre}',`album`='{$album}',`cover`='{$cover}',`video`='{$db_video}',`language`='{$language}',`year`='{$year}',`comment`='{$comment}',`added`='{$added}',`uploader`='{$uploader}',`path`='{$path}'");
                    $insertedId = $insert; // new inserted id
                    
                    if ($method === 'mymusic'){
                        $insertIntoMyMusic = $this->__om_query_insert("insert into ".nobil_om_my_music." SET `musid`='{$insertedId}',`uploader`='{$uploader}',`added`='{$added}',`owner`='" . $this->USER['id']."'");
						$this->toFeed($insertedId);
					} else {

                        $insertIntoPlaylist_a = $this->__om_query_insert("insert into ".nobil_om_playlist_pos." SET `trackid`='{$insertedId}',`playlistid`='{$method}'");
                        $insertIntoPlaylist = $this->__om_query_update("update ".nobil_om_playlists." SET `updates`='yes' where `originalpid`='{$method}'");
						$this->toFeed($insertedId,$method);
						
			// set to playlist cover if it haven't
			if(($pl_covr == $this->collection_img || $pl_covr == $this->defaultCover || !$pl_covr) && $cover)
			$this->__om_query_update("update ".nobil_om_playlists." SET `favorite_cover`='{$cover}' where id=".$method);

                    }
                    if (!$insertedId) {
                        @unlink($uploadedFile);
                        $message[] = "Error! [ Connect to database ], the file have been deleted, please try again.";
                    }
                    
                    
                }
            }
        }
    }
}

if ($message) {
    
    foreach ($message as $msg)
        echo $msg;
    
} else
    echo 'OK';


}










