PHP

Rackspace class to upload, delete, show, list files and images on rackspace

Rackspace class that has functions in to connect, upload, delete, show and list files and images on rackspace


Rackspace class to upload, delete, show, list files and images on rackspace

This is a Rackspace class that has functions in to connect, upload, delete, show and list files and images on rackspace. It consist of the base class - with also have a class that extends the base class and deals with all the actions required. There might be functions in here that deal with updating the model and database of the application it comes from. Please note: this is for relative advanced developers.

Rackspace Base class

<?php

namespace Rackspace\Component;
// in a framework you will need to adjust the namespace here

class Rackspace
{
    //Scoped Variables
    const USERNAME = " "; // username
    const KEY = " "; // api key
    const CONTAINER = " "; // Pinpoint Container
    const HANDSET_CACHE_CONTAINER = " ";
    const HANDSET_CACHE_DEV_CONTAINER = " ";
    const HANDSET_SECURE_URL = "https://... ....rackcdn.com/";
    const HANDSET_SECURE_DEV_URL = "https://... ....rackcdn.com/";
    const URL = "https://... ....rackcdn.com/";
    const SECURE_URL = "https://... ....rackcdn.com/";


    public static function determineHandsetContainer()
    {
        if (false === getenv('FORCE_DEV_CDN')) {
            return Rackspace::CACHE_CONTAINER;
        }

        return Rackspace::CACHE_DEV_CONTAINER;
    }

    public static function determineHandsetURL()
    {
        if (false === getenv('FORCE_DEV_CDN')) {
            return Rackspace::RACKSPACE_SECURE_URL;
        }

        return Rackspace::RACKSPACE_SECURE_DEV_URL;
    }

    public function listFiles()
    {
        $container = $this->connect();
        return $container->list_objects();
    }

    public function findFileByName($fileName)
    {
        $url = null;

        $files = $this->listFiles();

        if (is_array($files)) {
            $pos = strpos(implode('|', $files), $fileName);
            if ($pos > 0) {
                $url = self::URL . '/' . $fileName;
            }
        }

        return $url;
    }

    public function uploadRawFileData($fileData, $filename)
    {
        $container = $this->connect();

        // upload file data to Rackspace
        $object = $container->create_object($filename);

        //Prevent attempted md5 checksum of file data
        $object->set_etag(null);

        //Prevent attempt to determine mime type based on non-existent extension
        $object->content_type = "image/png";
        $uploadToRackspace = $object->write($fileData, (float)strlen($fileData));

        return $uploadToRackspace;
    }

    /**
     * @return bool|string
     */
    private function connect()
    {
        $auth = new \CF_Authentication(self::USERNAME, self::KEY);
        $auth->authenticate();
        $conn = new \CF_Connection($auth);
        return $conn->get_container(self::CONTAINER);
    }

    public function uploadFile($localFile, $filename)
    {
        $container = $this->connect();

        $object = $container->create_object($filename);

        if (!$object->content_type && (string)is_file($localFile) && function_exists("mime_content_type")) {
            $object->content_type = @mime_content_type($filename);

        } else {
            $extension = end(explode('.', $filename));
            $object->content_type = $this->getMimeTypeFromExtension($extension) ;

        }

        $extension = end(explode('.', $filename));
        $this->allowExtension($extension);

        return $object->load_from_filename($localFile);

    }

    private function allowExtension($extension, $extentionlist=null)
{
    $extentionlist = array("jpg", "jpeg", "jpe", "png");
    if ((in_array($extension, $extentionlist))) {

    } else {
        die ("File extention is not on our list.");
    }
}

    private function getMimeTypeFromExtension($extension)
    {
        switch ($extension) {
            case "js":
                return "application/x-javascript";

            case "json":
                return "application/json";

            case "jpg":
            case "jpeg":
            case "jpe":
                return "image/jpg";

            case "png":
            case "gif":
            case "bmp":
            case "tiff":
                return "image/" . $extension;

            case "css":
                return "text/css";

            case "xml":
                return "application/xml";

            case "doc":
            case "docx":
                return "application/msword";

            case "xls":
            case "xlt":
            case "xlm":
            case "xld":
            case "xla":
            case "xlc":
            case "xlw":
            case "xll":
                return "application/vnd.ms-excel";

            case "ppt":
            case "pps":
                return "application/vnd.ms-powerpoint";

            case "rtf":
                return "application/rtf";

            case "pdf":
                return "application/pdf";

            case "html":
            case "htm":
            case "php":
                return "text/html";

            case "txt":
                return "text/plain";

            case "mpeg":
            case "mpg":
            case "mpe":
                return "video/mpeg";

            case "mp3":
                return "audio/mpeg3";

            case "wav":
                return "audio/wav";

            case "aiff":
            case "aif":
                return "audio/aiff";

            case "avi":
                return "video/msvideo";

            case "wmv":
                return "video/x-ms-wmv";

            case "mov":
                return "video/quicktime";

            case "zip":
                return "application/zip";

            case "tar":
                return "application/x-tar";

            case "swf":
                return "application/x-shockwave-flash";

            default:
                if (function_exists("mime_content_type")) {
                    $extension = mime_content_type($extension);
                }

                return "unknown/" . trim($extension, ".");
        }
    }


    /**
     * @param $filename
     * @return bool|string
     */
    public function deleteFile($filename)
    {
        $container = $this->connect();

        try {
            $container->delete_object($filename);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return true;
    }

}

Rackspace base class extended wrapper

<?php

namespace Rackspace\Component;
// in a framework you will need to adjust the namespace here


class RackspaceFileHandler extends Rackspace
{
    protected $isLive;
    protected $fileSizeLimit;
    protected $fileImgMaxWidth;
    protected $fileImgMaxHeight;
    protected $exactSize;

    public function __construct(
        $isLive = true,
        $fileSizeLimit = 5,
        $fileImgMaxWidth = null,
        $fileImgMaxHeight = null,
        $exactSize = false
    ) {
        $this->isLive = $isLive;
        $this->fileSizeLimit = $fileSizeLimit;
        $this->fileImgMaxWidth = $fileImgMaxWidth;
        $this->fileImgMaxHeight = $fileImgMaxHeight;
        $this->exactSize = $exactSize;
    }

    public function uploadToRackspaceImage($fileKey, $fileDirectory, $filename, $fileIndex = null)
    {
        $cloudFileKey = $this->createCloudFileKey($fileKey, $fileDirectory, $filename, $fileIndex);

        if ($cloudFileKey !== null) {
            $resultData = $this->uploadImageWithCloudKey($fileKey, $cloudFileKey, $fileIndex);

            if ($resultData['success'] === true) {
                $resultData['cloudFileKey'] = $cloudFileKey;
            }
            return $resultData;
        }
    }


    public function deleteFileFromRackspace($cloudFileKey)
    {
        if (!empty($cloudFileKey)) {
            return $this->deleteFile($cloudFileKey);
        }
        $result['error'][] = "File could not be deleted.";
    }

    public function showFileFromRackspace($cloudFileKey)
    {
        if (!empty($cloudFileKey)) {
            return $this->findFileByName($cloudFileKey);
        } else {
            $result['error'][] = "Image could not be displayed.";
        }
    }

    protected function createCloudFileKey($fileKey, $fileDirectory, $filename, $fileIndex = null)
    {
        if (!is_null($fileIndex)) {
            $tmpName = $_FILES[$fileKey]['tmp_name'][$fileIndex];
            $fileType = $_FILES[$fileKey]['type'][$fileIndex];
        } else {
            $tmpName = $_FILES[$fileKey]['tmp_name'];
            $fileType = $_FILES[$fileKey]['type'];
        }

        if (empty($tmpName) === false) {
            $fileMd5 = md5_file($tmpName);
            $filename = preg_replace("/[^a-z0-9]/", '', strtolower($filename));
            $fileExt = end(explode('/', $fileType));
            return $fileDirectory . $fileMd5 . '_' . $filename . '.' . $fileExt;
        }
        return null;
    }

    protected function uploadImageWithCloudKey($fileKey, $cloudFileKey, $fileIndex = null)
    {
        $result = array('success' => false);

        if ($fileIndex !== null) {
            $fileName = $_FILES[$fileKey]['name'][$fileIndex];
            $fileTmpName = $_FILES[$fileKey]['tmp_name'][$fileIndex];
            $fileType = $_FILES[$fileKey]['type'][$fileIndex];
            $fileSize = $_FILES[$fileKey]['size'][$fileIndex];
            $fileError = $_FILES[$fileKey]['error'][$fileIndex];
        } else {
            $fileName = $_FILES[$fileKey]['name'];
            $fileTmpName = $_FILES[$fileKey]['tmp_name'];
            $fileType = $_FILES[$fileKey]['type'];
            $fileSize = $_FILES[$fileKey]['size'];
            $fileError = $_FILES[$fileKey]['error'];
        }

        if (empty($fileName)) {
            return array('success' => false);
        }

        try {
            if ($fileSize / 1024 / 1024 > $this->fileSizeLimit) {
                $result['error'][] = "Image size exceeds " . $this->fileSizeLimit . " MB";
            }

            if ($this->fileImgMaxWidth || $this->fileImgMaxHeight) {
                $imageData = getimagesize($fileTmpName);
                if (empty($imageData) === false) {
                    $imageWidth = $imageData[0];
                    $imageHeight = $imageData[1];

                    if (!$this->exactSize) {
                        if ($this->fileImgMaxWidth && $imageWidth > $this->fileImgMaxWidth) {
                            $result['error'][] = "Image width exceeds max value of " . $this->fileImgMaxWidth . "px";
                        }
                        if ($this->fileImgMaxHeight && $imageHeight > $this->fileImgMaxHeight) {
                            $result['error'][] = "Image height exceeds " . $this->fileImgMaxHeight . " px";
                        }
                    } else {
                        if ($this->fileImgMaxWidth && $imageWidth !== $this->fileImgMaxWidth) {
                            $result['error'][] = "Image width must be " . $this->fileImgMaxWidth . "px";
                        }
                        if ($this->fileImgMaxHeight && $imageHeight !== $this->fileImgMaxHeight) {
                            $result['error'][] = "Image height must be " . $this->fileImgMaxHeight . " px";
                        }
                    }
                }
            }

            if ($fileError > 0) {
                switch ($fileError) {
                    case UPLOAD_ERR_INI_SIZE:
                        $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                        break;
                    case UPLOAD_ERR_FORM_SIZE:
                        $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                        break;
                    case UPLOAD_ERR_PARTIAL:
                        $message = "The uploaded file was only partially uploaded";
                        break;
                    case UPLOAD_ERR_NO_FILE:
                        $message = "No file was uploaded";
                        break;
                    case UPLOAD_ERR_NO_TMP_DIR:
                        $message = "Missing a temporary folder";
                        break;
                    case UPLOAD_ERR_CANT_WRITE:
                        $message = "Failed to write file to disk";
                        break;
                    case UPLOAD_ERR_EXTENSION:
                        $message = "File upload stopped by extension";
                        break;

                    default:
                        $message = "Unknown upload error";
                        break;
                }
                $result['error'][] = "Error(s) uploading file '$fileName':<br>$message<br>";
            }

            if (count($result['error']) > 0) {
                return $result;
            }

            if ($this->isLive === true) {
                $isUploaded = $this->uploadFile($fileTmpName, $cloudFileKey);
            } else {
                $isUploaded = $this->uploadToLocal($fileKey, $cloudFileKey);
            }

            if (!$isUploaded) {
                $result['error'][] = "Error uploading image to cloud.";
            } else {
                $result['success'] = true;
            }
        } catch (\Exception $e) {
            $result['error'][] = "Error uploading file to cloud.  See error log for details.";
            error_log($e);
        }

        return $result;
    }

    protected function uploadToLocal($fileKey, $cloudFileKey)
    {
        $uploadDir = __DIR__ . '/../tests/uploads';

        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileDirectories = $uploadDir . '/' . dirname($cloudFileKey);

        if (file_exists($fileDirectories) === false) {
            mkdir($fileDirectories, 0755, true);
        }

        $uploadFilePath = $uploadDir . '/' . $cloudFileKey;

        return move_uploaded_file($_FILES[$fileKey]["tmp_name"], $uploadFilePath);
    }
}

 

Published: 22nd March 2017 by

Adverts