Location: PHPKode > scripts > class_playlist > class_playlist/class_playlist.php
<?php
/****************************************************************
*****************************************************************

class_log.php: create to work with log file (create and search).
Copyright (C) 2003  Matthieu MARY hide@address.com

This program 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 2
of the License, or any later version.

This program is distributed in the hope that it 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 this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

You can found more information about GPL licence at:
http://www.gnu.org/licenses/gpl.html

for contact me: hide@address.com
****************************************************************
****************************************************************/
/**
 * latest version of this class can be donwload at http://www.phpclasses.org/browse.html/package/1228.html
 * create the : july 9th 2003.
 * @author      Matthieu MARY &lt;<a href="mailto:hide@address.com">hide@address.com</a>&gt;
 * @version     1.0.7
 */
require_once "class_dir.php";
include "template.inc";
require_once "class_audioFile_data.php";

class playlist extends dir
{
	/**
	 * @shortdesc log events
	 * @private
	 * @type array
	 */
	var $aLog;
	/**
	 * @shortdesc log errors
	 * @private
	 * @type array
	 */
	var $aErrors;
	/**
	 * @shortdesc path to the template of playlist
	 * @private
	 * @type string
	 */
	var $sTemplate;
	/**
	 * @shortdesc have the audio extensions selected
	 * @private
	 * @type arrays
	 */
	var $oAudiotype;
	/**
	 * @shortdesc path to for the audiofile of the playlist
	 * @private
	 * @type string
	 */
	var $sPath;
	/**
	 * @shortdesc bandname of your playlist
	 * @private
	 * @type string
	 */
	var $sBandname;
   	/**
	 * @shortdesc infos on playlist file
	 * @private
	 * @type array
	 */
    var $dPlaylist;
   	/**
	 * @shortdesc playlist const
	 * @private
	 * @type array
	 */
    var $dPlaylist_const;
   	/**
	 * @shortdesc invalid caracters
	 * @private
	 * @type array
	 */
    var $dInvalids;
   	/**
	 * @shortdesc replacement chars
	 * @private
	 * @type array
	 */
    var $dRemplacement;	
    /**
	 * Builder
	 *
	 * @param string sPath required. the path which have the file for playlist
	 * @param string SBandname required. the name of the band for playlist
	 * @param string sSavepath optional default value 'playlist.b4s'. folder+filename for the playlist will be create
	 * @param array aAudiotypes optional default array('mp3'). the type of audio file you wants in you playlist
     * @public
	 * @type void
     */
	function playlist($sPath,$sBandname,$sSavepath='playlist.b4s',$aAudiotypes = array('mp3'))
    {
	     $this->dInvalids = array("/é/","/É/","/Ü/","/ü/","/ï/","/û/","/à/","/ê/","/è/","/&/","/â/","/ç/","/ô/","/'/");
	     $this->dRemplacement = array("e","E","U","u","i","u","a","e","e","and",'a','c','o',' ');
         $this->dPlaylist_const = array(
	                            'b4s' => 'playlistb4s.tpl',
                                'm3u' => 'playlistm3u.tpl',
                                'pls' => 'playlistpls.tpl');
       
        //-------------------------------------------
		// check if path is ok
		//-------------------------------------------
		if (trim($sPath)=='') return $this->_log('you must specify a path for audio files',TRUE);
	
		if (!is_dir(realpath($sPath))) return $this->_log('path ['.$sPath.'] is not a valid folder',TRUE);

        $this->sPath = realpath($sPath);
        if (strcmp($this->sPath,$this->_remove_bad_chars($this->sPath))) return $this->_log('folder ['.$this->sPath.'] have invalid characters, abort',TRUE);

        //---------------------------
		// check if audiotypes are ok
		//---------------------------
		$this->oAudiotypes = array();
		$aAudioext = array('mp3','mp2','wma');
		foreach($aAudiotypes as $id => $sExtension){
			if (in_array(strtolower($sExtension),$aAudioext)) $this->oAudiotypes[] = $sExtension;
		}//foreach
		if (count($this->oAudiotypes)==0) return $this->_log('no audiotypes found in your selection',TRUE);

        //---------------------------
		// check the bandname
		//---------------------------
		if (trim($sBandname)=='') return $this->_log("you muse specify second parameters");

		$this->sBandname = $this->_remove_bad_chars($sBandname);
		if(strcmp($this->sBandname,$sBandname)){
		    $this->_log('change parameter ['.$sBandname.'] to ['.$this->sBandname .'] for playlist compatibility');
		}

		//--------------------------------
		// get the file list for playlist
		//--------------------------------
		$dir = new dir($this->sPath);
		if ($dir->DATA_errors_size()){
			$this->aErrors = $dir->DATA_errors();
			return;
		}
		$aFilelist = $dir->LIST_get(FALSE,$this->oAudiotypes);
		if ($dir->DATA_errors_size()){
			$this->aErrors = $dir->DATA_errors();
			return;
		}
		if (count($aFilelist)==0) return $this->_log('path ['.$this->sPath.'] have any of you selection audio files ['.implode(',',$this->oAudiotypes).']',TRUE);

		//---------------------------------------------------------
		// rename file with char that induce winamp playlist errors
		//---------------------------------------------------------		
		$aFiles_to_remove = array();
		$aKeys = array_keys($aFilelist);
		for ($i = 0; $i < count($aKeys);$i++){
            $id = $aKeys[$i];
            $sPath = $aFilelist[$id];
			$dPathinfos = pathinfo($sPath);
			$sFilename_new = $this->_remove_bad_chars($dPathinfos['basename']);
			if(strcmp($dPathinfos['basename'],$sFilename_new)){
				if (@rename($sPath,$dPathinfos['dirname'].$dir->cSep.$sFilename_new)){
                     $this->_log('rename ['.$dPathinfos['basename'].'] to ['.$sFilename_new.'] for playlist compatibility');
                     $aFilelist[$id] = $dPathinfos['dirname'].$dir->cSep.$sFilename_new;
                }
				else{
				    $this->_log('unable to rename ['.$dPathinfos['basename'].'] for playlist compatibility: file exclude from playlist');
                    unset($aFiles_to_remove[$id]);
				}//else
				
			}//if 
		}//for

		if (count($aFilelist)==0) return $this->_log('all filename have bad chars and script is unable to rename them; unable to create playlist',TRUE);
	
		//----------------------------------------
		// check the playlist infos
		//----------------------------------------
		// get the album name
        $aSubdirs = explode($dir->cSep,$this->sPath);
        $sAlbum = $aSubdirs[(count($aSubdirs)-1)];

        // is the dir valid?
        $dPsave = pathinfo($sSavepath);
        $this->dPlaylist = pathinfo($sSavepath);
        $this->dPlaylist['path'] = $sSavepath;
        if(!in_array(strtolower($this->dPlaylist['extension']),array_keys($this->dPlaylist_const))){
            return $this->_log('your extension of your playlist ['.$this->dPlaylist['extension']."] isn't recognize in the list ".implode('-',array_keys($this->dPlaylist_const))."",TRUE);
        }
        //-------------------------------------------
		// check if the template model really exists
		//-------------------------------------------
		$this->sTemplate = $this->dPlaylist_const[strtolower($this->dPlaylist['extension'])];
		if (!file_exists($this->sTemplate)) return $this->_log('template ['.$this->sTemplate."] doesn't exist in current folder; exit",TRUE);

		//----------------------------------------
		// check if playlist already exists
		//----------------------------------------
		if (file_exists($this->dPlaylist['path'])) return $this->_log('playlist ['.$this->dPlaylist['path'].'] already exists; abort',TRUE);

		//----------------------------------------
		// get the contents of the playlist
		//----------------------------------------
        // block output
        ob_start();
        $bOK = TRUE;
        // create new objects template
        $t = new Template();
        // set template file
        $t->set_file('playlist',$this->sTemplate);
        // set var
        $t->set_block('playlist','FILE','one_file');
        $t->set_var("numentries",count($aFilelist));
        $t->set_var("label",htmlspecialchars($sAlbum));
        reset($aFilelist);
        while (list($id,$pathfile)=each($aFilelist)) {
         $dpathinfos = pathinfo($pathfile);
         clearstatcache ();
         $size = @filesize($pathfile);
         $name = substr($dpathinfos['basename'],0,((strlen($dpathinfos['basename']))-(strlen($dpathinfos['extension'])+1)));
         if (!$size){
              $this->_log('filesize 0 for ['.$pathfile.']; abord building for ['.$name.']');
              $bOK = FALSE;
              break;
         }
         $AF = new audiofile_data($pathfile);
         $t->set_var(array(
           "path" => eregi_replace("[\]{1}","/",$pathfile),
           "length" => floor($AF->GET_length()),
           "num" => ($id+1),
           "name"=>$name,
           "size"=>$size));
         $t->parse("one_file","FILE",true);
         $AF->clear();
         unset($AF);
        } //while
        //write output
        $t->pparse("contents","playlist");
        // get output
        $content = ob_get_contents();
        ob_end_clean();
        unset($t);
        
		//----------------------------------------
		// make playlist file
		//----------------------------------------
		if (!$bOK) return;
        $fp = fopen($sSavepath,"w");
        if (!$fp) return $this->_log("unable to create [".$this->dPlaylist['path']."]",TRUE);

        fputs($fp,$content);
        fclose($fp);
        $this->_log("[".date("Y-m-d m:s")."] - create playlist [".$sSavepath."] with succes");
        return;
	}//builder

    /**
	 * add a string in the log array
	 *
	 * @param string sString required. the string to add
	 * @param bool bToError optional. does the string must be add to error array?
     * @private
	 * @type bool (false)
	 */
	 function _log($sString,$bToError=FALSE)
     {
	          $this->aLog[] = $sString;
	          if ($bToError) $this->aErrors[] = $sString;
	          return FALSE;
	 }

	/**
	 * Function that change bad characters that give errors in a playlist in a string
	 *
	 * @param string sString required. the string to test
     * @private
	 * @type string
	 */
	function _remove_bad_chars($sString){
		return preg_replace($this->dInvalids,$this->dRemplacement,$sString);
	}
	/**
	 * Function that return the size of the error array
	 *
	 * @public
	 * @type int
	 */
	 function DATA_error_size(){
	    return count($this->aErrors);
	 }

    /**
	 * Function that the array errors
	 *
	 * @public
	 * @type array
	 */
	 function DATA_error(){
	    return $this->aErrors;
	 }
    /**
	 * Function returning the log
	 *
	 * @public
	 * @type array
	 */
	 function DATA_log(){
	    return $this->aLog;
	 }
	 
	 
}//playlist
?>
Return current item: class_playlist