<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/private/createAutoSoundArt.inc.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
function createAutoSoundArt($name,&$xml,$requestName,$current_path,$firstNode,$firstNodePath){
	
	require_once(dirname(__FILE__)."/../file/file_functions.inc.php");
	require_once(dirname(__FILE__)."/../file/file_config.inc.php");
	require_once(dirname(__FILE__)."/../common/getid3/getid3.php");
	require_once(dirname(__FILE__)."/../private/metaSearch.inc.php");
	
	$db_conn =db_connect();
	
	// checking the module exists and the user has rights to create 
	$moduleInfo = moduleInfo('sound_art');
	if ($moduleInfo->loaded==FALSE){
		$query_result = generateMsgXML(1,"The informations about the module couldn't be found.",0,'',$name);
		//echo $this->_lastError."<br/>";
		return $query_result;
	}
	if(!$moduleInfo->getActionSecurity("CREATE",array('Type')=>'Track')){
		$query_result = generateMsgXML(3,"You're not authorized to create elements in this module.",0,'',$name);
		return $query_result;
	}
	// checking the file permissions
	$target = $xml->getData($firstNodePath."/@source");
	$target = transformPath(unhtmlentities($target));
	$right =  getPathSecurityRight($target);
	if ($right===0)
		return generateMsgXML(3,"You're not authorized to handle this file.",0,'',$name);
	$path = $directoryRoot.$target;
	
	// checking an album has not already been imported using this directory
	$sql = 'SELECT * FROM '.$moduleInfo->tableName.' WHERE Directory="'.$xml->getData($firstNodePath."/@source").'" AND Activity=1;';
	$row = $db_conn->GetRow($sql);
		
	if (file_exists($path) && !$row){
		$getID3 = new getID3;
		if (is_dir($path)){
			if (substr($path,-1)!='/')
				$path = $path.'/';
			if (substr($target,-1)!='/')
				$target = $target.'/';
			$now = date("Y-m-d");
			$total_duration = 0;
			$dir = @opendir($path);
			/* loop once for each name in the directory */
			while($file = readdir($dir)) {
				$isFileVisible=true;
				// if the name is not a directory and the name is not the name of this program file
				if($file == "." || $file == ".." || $file == "$ThisFileName")
					$isFileVisible = false;
				if (!is_dir($path.$file) && $isFileVisible){
					$right =  getPathSecurityRight($target.$file);
					if ( $right===0 )
						$isFileVisible = false;
					//if this file is hidden, do net show it
					if (!hidecheck($file))
						$isFileVisible=false;
					// if there were no matches the file should not be hidden
					if($isFileVisible && (getFileExt($file)=='mp3' || getFileExt($file)=='MP3')) {
						if ($file=="sample.mp3"){
							$sample_file = reTransformPath($target.$file);
						}else{
							// we take it as a sound_art
							//echo "File is mp3 <br/>";
							$file_info = $getID3->analyze($path.$file);
							getid3_lib::CopyTagsToComments($file_info);
							if (empty($fileinfo['error'])){
								$tracks.="<SOUND_ART><INFO>";
								$tracks.="<TYPE>track</TYPE>";
								if ($file_info['comments_html']['title'][0])
								$tracks.="<TITLE>".unhtmlentities($file_info['comments_html']['title'][0])."</TITLE>";
								else
								$tracks.="<TITLE>".getFilenameWithoutExt($file)."</TITLE>";
								$tracks.="<ARTIST>".unhtmlentities($file_info['comments_html']['artist'][0])."</ARTIST>";
								$tracks.="<FILE>".reTransformPath($target.$file)."</FILE>";
								$tracks.="<DATE>".$now."</DATE>";
								$duration = date("H:i:s",strtotime("00:".$file_info['playtime_string']));
								$tracks.="<DURATION>".$duration."</DURATION>";
								// adding the hours
								$total_duration+=substr($duration,0,2)*60*60;
								// adding the minutes
								$total_duration+=substr($duration,3,2)*60;
								// adding the seconds
								$total_duration+=substr($duration,-2);
								$tracks.="</INFO></SOUND_ART>";
							}
						}
					}
				}
			}
			$filename = basename($path);
			$informations = explode('-',$filename);
			$query.= '<CREATE><SOUND_ART><INFO>';
			$query.="<TYPE>album</TYPE>";
			$query.="<FILE>$sample_file</FILE>";
			$query.="<DIRECTORY>".reTransformPath($target)."</DIRECTORY>";
			$hours = sprintf("%02d",floor($total_duration/3600));
			$total_duration-= $hours*3600;
			$minutes = sprintf("%02d",floor($total_duration/60));
			$total_duration-= $minutes*60;
			$seconds = sprintf("%02d",$total_duration);
			$query.="<DURATION>".$hours.":".$minutes.":".$seconds."</DURATION>";
			$query.="<ARTIST>".trim($informations[0])."</ARTIST>";
			if (isset($informations[1]))
			$query.="<TITLE>".trim($informations[1])."</TITLE>";
			else
			$query.="<TITLE>".trim($informations[0])."</TITLE>";
			$query.="<DATE>".$now."</DATE>";
			$query.='</INFO><DEPENDENCIES><DEPENDENCY type="sound_artTrack">'.$tracks.'</DEPENDENCY></DEPENDENCIES></SOUND_ART></CREATE>';
			
			$nqlOp = new createElement('auto-soundart',false);
			$nqlOp->setNQL($query);
			$create_result = $nqlOp->execute();
			$sound_artID = $nqlOp->getID();
			$row = getInfo($moduleInfo,$sound_artID);
		}
	}else if (!$row) // there is no album yet and the file doesn't exist
		return generateMsgXML(1,"File doesn't exist.".$path,0,'',$name);
	
	
	if ($row){ // it's the album that was already there (detected with the Directory) or the one just created
		
		$query_result=generateXMLOutput($row,$moduleInfo,array('profile_name'=>'complete'),2);
		if ($name)
			$attributes.=" name='$name'";
		return '<RESULTS '.$attributes.'>'.$query_result.'</RESULTS>';
	}else
		return generateMsgXML(1,"Creation failed : ".encode_to_xml($query),0,$sound_artID,$name);
}
?>
