Subversion Repositories travelsized

Rev

Rev 454 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * This file is part of Travelsized CMS
 *              A content management system with modules, based on wiki syntax
 *
 * Author: Dan Jensen <admin@leinir.dk>
 * Copyright 2003/2004
 *
 * 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
 * (at your option) any later version.
 *
 * The GNU General Public License is available at: http://www.gnu.org/copyleft/
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


function fileGet( $filename )
{
        if( !function_exists("file_get_contents") )
        {
                if( file_exists($filename) )
                {
                        $fp = fopen( $filename, "r" );
                        $contents = fread( $fp, filesize($filename) );
                        fclose($fp);
                }
                else
                        $contents = false;
               
        }
        else
                $contents = file_get_contents($filename);
       
        return $contents;
}

function fileSave( $filename, $content )
{
        if (!function_exists("file_put_contents"))
        {
                touch($filename);
                if( is_writable($filename) )
                {
                        if( !$handle = fopen( $filename, 'a' ) )
                                return false;
                       
                        // Write $somecontent to our opened file.
                        if( fwrite( $handle, $content ) === false )
                                return false;
                       
                        fclose($handle);
                        return true;
                }
                else
                        return false;
        }
        else
                return file_put_contents($filename, $content);
}

/**
 * Get a textual representation of the size of a file.
 *
 * @param     filename       A string containing the filename of the file to get the filesize of
 *
 * @return    A string containing the file size in human-readable format
 */

function fileweight( $filename ) {
        //thanks to dave at birko dot cjb dot net on the php.net manual site for this bit :)
        $a = array("B", "KB", "MB", "GB", "TB", "PB");
        $pos = 0;
        $size = filesize($filename);
        while ($size >= 1024) {
                $size /= 1024;
                $pos++;
        }
        return round($size,2) . " " . $a[$pos];
}

/**
 * Delete a file, or a folder and its contents
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.0.1
 * @param       string   $dirname    Directory to delete
 * @return      bool     Returns TRUE on success, FALSE on failure
 */

function rmdirr($dirname)
{
    // Sanity check
    if (!file_exists($dirname)) {
        return false;
    }

    // Simple delete for a file
    if (is_file($dirname)) {
        return unlink($dirname);
    }

    // Loop through the folder
    $dir = dir($dirname);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }

        // Deep delete directories      
        if (is_dir("$dirname/$entry")) {
            rmdirr("$dirname/$entry");
        } else {
            unlink("$dirname/$entry");
        }
    }

    // Clean up
    $dir->close();
    return rmdir($dirname);
}

/**
 * Delete files with a wildcard
 */

function unlink_multiple($str) {
        foreach(glob($str) as $fn) {
                if (!unlink($fn)) return false;
        }
        return true;
}

/**
 * Move files containing with names containing the string $needle
 * from the folder $from to the folder $target
 */

function rename_multiple($from, $target, $needle) {
        $dir = dir($from);
        while (false !== $entry = $dir->read()) {
                // Skip pointers, and files not containing the needle
                if ($entry == '.' || $entry == '..' || strpos($entry, $needle) === false) {
                        continue;
                } else {
                        if (!rename("$from/$entry", "$target/$entry")) return false;
                }
        }
        $dir->close();
        return true;
}

/**
 * RecursiveMkdir function for generating new folders recursively
 * Courtesy of David Pullen in the comments in the PHP manual on PHP.net
 *
 * @param       string  $path   The path you wish to be created
 * @param       int     $mode   Optional. The mode in which you wish it to be created
 */

$newDirHelp = true;
function RecursiveMkdir($path, $mode = 0777) {
        global $systemOptions, $globalError;
        // This function creates the specified directory using mkdir().  Note
        // that the recursive feature on mkdir() is broken with PHP 5.0.4 for
        // Windows, so I have to do the recursion myself.
        if (!file_exists($path))
        {
                // The directory doesn't exist.  Recurse, passing in the parent
                // directory so that it gets created.
                if(!RecursiveMkdir(dirname($path)))
                        return false;
               
                if( ini_get( "safe_mode" ) == true )
                {
                        // The horriblest of hacky hacks - no choice but to do all this through ftp in safe_mode, the only thing that works across the different stupid level
                       
                        if( ! array_key_exists( "ftp_host", $systemOptions ) || $systemOptions["ftp_host"] == "" )
                        {
                                /// TODO: Do a bit more informative help here... linkage perhaps...
                                global $newDirHelp;
                                if($newDirHelp)
                                {
                                        $newDirHelp = false;
                                        $globalError .= renderErrorBox( i18n("PHP Safe Mode"), i18n("Before Travelsized is able to create directories, please enter the host information in site setup."), false );
                                }
                                return;
                        }
                       
                        $error = "";
                        $connectionID = ftp_connect( $systemOptions["ftp_host"], $systemOptions["ftp_port"] );
                        if($connectionID)
                        {
                                $loginResult = ftp_login( $connectionID, $systemOptions["ftp_user"], $systemOptions["ftp_password"] );
                                if($loginResult)
                                {
                                        $newPath = $systemOptions["ftp_dir"] . "/" . $path;
                                        $createResult = ftp_mkdir( $connectionID, $newPath );
                                        if($createResult)
                                        {
                                                $modResult = ftp_chmod( $connectionID, $mode, $newPath );
                                                if( !$modResult )
                                                        $error .= "FAIL: Could not set the new permissions ($mode) on $newPath\n";
                                        }
                                        else
                                                $error .= "FAIL: Could not create the directory $newPath\n";
                                }
                                else
                                        $error .= "FAIL: Could not log in to remote server - tried to log in as " . $systemOptions["ftp_user"] . "\n";
                               
                                ftp_close($connectionID);
                        }
                        else
                                $error .= "FAIL: Could not connect to server - tried to connect to " . $systemOptions["ftp_host"] . " on port " . $systemOptions["ftp_port"] . "\n";
                       
                        if( $error != "" )
                        {
                                $globalError .= renderErrorBox( i18n("Error creating directory"), $error . " while attempting to create $path", false );
                                return false;
                        }
                }
                else
                {
                        $old_umask = umask(0);
                        mkdir($path, $mode);
                        umask($old_umask);
                }
        }
        return true;
}

/**
 * Get a filename for a file (used for uploading files). Returns a different filename if the filename already exists.
 *
 * @param string    filename            The filename of the file you wish to find a name for
 * @param string    destination         The destination directory for the file (check against this list of files)
 *
 * @return  string  A string containing the suggested filename
 */

function suggestFilename( $filename, $destination )
{
        $origin = $filename;
        $fulldest = $destination . "/" . $origin;
        $newfilename = $origin;
       
        $fileext = (strpos($origin,'.')===false?'':'.'.substr(strrchr($origin, "."), 1));
        for ($i=1; file_exists($fulldest); $i++)
        {
                $newfilename = substr($origin, 0, strlen($origin)-strlen($fileext)).'['.$i.']'.$fileext;
                $fulldest = $destination . "/" . $newfilename;
        }
       
        return $newfilename;
}


/**
  * Gets the mime data of a specified file according to its suffix (dirty, dirty method)
  *
  * @param string $filename
  *
  * @return {String} mime-type of the given file
  */

function getMimeBySuffix($filename)
{
        $returnVal = "";
        // Get File extension for a better match
        $fileSuffixes = explode( ".", $filename );
        $fileSuffix = strtolower(end($fileSuffixes));
       
        switch( $fileSuffix )
        {
        case "js":
                $returnVal .= "application/x-javascript";
                break;
        case "json":
                $returnVal .= "application/json";
                break;
        case "jpg":
        case "jpeg":
        case "jpe":
                $returnVal .= "image/jpeg";
                break;
        case "png":
        case "gif":
        case "bmp":
        case "tiff":
                $returnVal .= "image/" . strtolower( $fileSuffix[1] );
                break;
        case "css":
                $returnVal .= "text/css";
                break;
        case "xml":
                $returnVal .= "application/xml";
                break;
        case "doc":
        case "docx":
                $returnVal .= "application/msword";
                break;
        case "xls":
        case "xlt":
        case "xlm":
        case "xld":
        case "xla":
        case "xlc":
        case "xlw":
        case "xll":
                $returnVal .= "application/vnd.ms-excel";
                break;
        case "ppt":
        case "pps":
                $returnVal .= "application/vnd.ms-powerpoint";
                break;
        case "rtf":
                $returnVal .= "application/rtf";
                break;
        case "pdf":
                $returnVal .= "application/pdf";
                break;
        case "html":
        case "htm":
        case "php":
                $returnVal .= "text/html";
                break;
        case "txt":
                $returnVal .= "text/plain";
                break;
        case "mpeg":
        case "mpg":
        case "mpe":
                $returnVal .= "video/mpeg";
                break;
        case "mp3":
                $returnVal .= "audio/mpeg3";
                break;
        case "wav":
                $returnVal .= "audio/wav";
                break;
        case "aiff":
        case "aif":
                $returnVal .= "audio/aiff";
                break;
        case "avi":
                $returnVal .= "video/msvideo";
                break;
        case "wmv":
                $returnVal .= "video/x-ms-wmv";
                break;
        case "mov":
                $returnVal .= "video/quicktime";
                break;
        case "zip":
                $returnVal .= "application/zip";
                break;
        case "tar":
                $returnVal .= "application/x-tar";
                break;
        case "swf":
                $returnVal .= "application/x-shockwave-flash";
                break;
        default:
                $returnVal .= "application/octet-stream";
                break;
        }
       
        return $returnVal;
}

/**
  * Tries to get mime data of the file.
  *
  * @param string $filename
  *
  * @return {String} mime-type of the given file
  */

function getMime($filename, $originalFilename = null)
{
        $returnVal = "";
       
        if( $originalFilename == null)
                $originalFilename = $filename;
       
        // if mime_content_type exists use it.
        if(function_exists( "mime_content_type" ))
        {
                $returnVal .= mime_content_type($filename);
        }
        // if Pecl installed use it
        else if( function_exists( "finfo_open" ) )
        {
                $finfo = finfo_open(FILEINFO_MIME);
                $returnVal .= finfo_file($finfo, $filename);
                finfo_close($finfo);
        }
        // if nothing left try shell
        else
        {
                // Nothing to do on windows
                if( strstr( $_SERVER['HTTP_USER_AGENT'], "Windows" ) )
                        $returnVal .= getMimeBySuffix( $filename );
                // Correct output on macs
                else if( strstr( $_SERVER['HTTP_USER_AGENT'], "Macintosh") )
                        $returnVal .= trim( exec( 'file -b --mime ' . escapeshellarg( $filename ) ) );
                // Regular unix systems
                else
                        $returnVal .= trim( exec( 'file -bi ' . escapeshellarg( $filename ) ) );
        }
        $returnVal = split( ";", $returnVal );
        $returnVal = trim( $returnVal[0] );
       
        // If we reach here without a proper mimetype let's try and fake one...
        if( $returnVal == "application/octet-stream" || $returnVal == "text/plain" || $returnVal == "" )
                $returnVal = getMimeBySuffix( $originalFilename );
       
        return $returnVal;
}

/**
 * Function for checking the filetype of a file
 *
 * @param string $filename      The filename of the file to check the mimetype of
 *
 * @return bool|string Returns false if not an image, and otherwise returns a string with the image type
 */

function checkImageMimetype( $filename, $originalFilename = "" )
{
        $mimetype = getMime( $filename, $originalFilename );
        $returnVal = "";
        switch( $mimetype )
        {
        case "image/jpeg":
        case "image/jpg":
                $returnVal .= "jpg";
                break;
        case "image/gif":
                $returnVal .= "gif";
                break;
        case "image/png":
                $returnVal .= "png";
                break;
        default:
                $returnVal = false;
                break;
        }
        return $returnVal;
}

?>