Example #1
0
/**
 * Prompts user for direct download of HTTP attachment.
 * @param	string	$content
 * @param	string	$ext
 * @return	void
 */
function download_file($content = '', $ext = '', $filename = NULL)
{
    //Try to get the mime type
    if (!($mime = mime_type($ext))) {
        $mime = 'application/octet-stream';
    }
    //Create a random filename
    if (!$filename) {
        $filename = time() . '.' . $ext;
    }
    // Generate the server headers
    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header("Content-Transfer-Encoding: binary");
        header('Pragma: public');
        header("Content-Length: " . strlen($data));
    } else {
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Pragma: no-cache');
        header("Content-Length: " . strlen($data));
    }
    //Send file
    exit($content);
}
Example #2
0
function _outputFile($_file)
{
    Kurogo::log(LOG_DEBUG, "Output file {$_file}", 'kurogo');
    if ($file = Watchdog::safePath($_file)) {
        CacheHeaders($file);
        header('Content-type: ' . mime_type($file));
        readfile($file);
        exit;
    }
    _404();
}
Example #3
0
function test_file_mime_type()
{
    $mimes = mime_type();
    assert_true(is_array($mimes));
    assert_not_empty($mimes);
    assert_empty(mime_type(''));
    assert_equal(mime_type('txt'), 'text/plain');
    assert_equal(mime_type('TXT'), 'text/plain');
    assert_equal(mime_type('jpg'), 'image/jpeg');
    assert_equal(mime_type('JPG'), 'image/jpeg');
}
 function mime_type_from_path($path)
 {
     $result = FALSE;
     if ($path) {
         $mime = mime_from_path($path);
         if ($mime) {
             $result = mime_type($mime);
         }
     }
     return $result;
 }
Example #5
0
function _outputFileLoaderFile($matches) {
  $fullPath = FileLoader::load($matches[1]);
  
  if ($fullPath) {
    CacheHeaders($fullPath);    
    header('Content-type: '.mime_type($fullPath));
    echo file_get_contents($fullPath);
    exit;
  }

  _404();
}
Example #6
0
            }
            $tmp = "";
            //do we have an audio file? link to it here!
            if ($audiothere) {
                $tmp .= "<p><a href=\"" . $audiourl . "\">File Download ";
                $tmp .= "(" . getminutes($comfields['audio_length']) . " min / " . getmegabyte($comfields['audio_size']) . " MB)</a>";
            }
            echo trim(htmlspecialchars($tmp, ENT_QUOTES));
            echo "</content:encoded>\n";
            //date of publication
            echo "    <pubDate>" . date("r", strtotime($comfields['posted'])) . "</pubDate>\n\n";
            //do we add an enclosure?
            if ($audiothere) {
                echo "    <enclosure url=\"" . $audiourl . "\" ";
                echo "length=\"" . $comfields['audio_size'] . "\" ";
                echo "type=\"" . mime_type($comfields['audio_type']) . "\" />\n";
                echo "    <itunes:duration>" . getitunesduration($comfields['audio_length']) . "</itunes:duration>\n";
            }
            echo "</item>\n\n";
        }
    }
}
echo "\n\n</channel>\n\n</rss>";
// ------------------------------------- FUNCTIONS -----------------------------
function showcats($fields)
{
    global $settings;
    global $cat_table;
    //iTunes Categories
    $allcats = array($settings['feedcat1'], $settings['feedcat2'], $settings['feedcat3'], $settings['feedcat4']);
    $tunecats = "";
function handleUpload()
{
    /***
     * Determine the type of file upload handler that needs to be
     * used, then pass things along accordingly.
     ***/
    if (empty($_FILES)) {
        return array('status' => false,'error' => 'No files provided','human_error' => 'Please provide a file to upload');
    }
    $temp = $_FILES['file']['tmp_name'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $temp);
    finfo_close($finfo);
    $file = $_FILES['file']['name'];
    $mime_error = "";
    if(empty($mime)) {
        # Just the fallback that is based purely on extension
        # Only used when finfo can't find a mime type
        try {
            $mime = mime_type($file);
        } catch (Exception $e) {
            $mime_error = $e->getMessage();
            $mime = null;
        }
    }
    # Look at the MIME prefix
    $mime_types = explode('/', $mime);
    $mime_class = $mime_types[0];

    # Now, call the actual uploader function based on the mime class
    # (eg, image/, audio/, video/ ... )
    switch ($mime_class) {
    case 'image':
        return doUploadImage($mime);
        break;
    case 'audio':
        return doUploadAudio($mime);
        break;
    case 'video':
        return doUploadVideo($mime);
        break;
    default:
        # return array('status' => false,'error' => "Unrecognized MIME type '".$mime."' for file '".$file."' (".$mime_error.")", 'human_error' => 'Unsupported file format', "dumb_type"=>mime_type($file));
        $temp = $_FILES['file']['tmp_name'];
        $uploadPath = $_REQUEST['uploadpath'];
        $savePath = dirname(__FILE__).'/'.$uploadPath;
        if (!file_exists($savePath)) {
            if(!mkdir($savePath)) {
            return array(
                'status' => false,
                'error' => "Bad path '$savePath'",
                'human_error' => 'There is a server misconfiguration preventing your file from being uploaded',
            );
            }
        }
        $file = $_FILES['file']['name'];
        $exploded = explode('.', $file);
        $extension = array_pop($exploded);
        $fileName = md5($file.microtime_float());
        $newFilePath = $fileName.'.'.$extension;
        $fileWritePath = $savePath.$newFilePath;
        # We want to suppress the warning on move_uploaded_file, or else
        # it'll return an invalid JSON response
        #error_reporting(0); # Disable this for debugging
        $status = move_uploaded_file($temp, $fileWritePath);
        $uploadStatus = array('status' => $status,'original_file' => $file,'wrote_file' => $newFilePath,'full_path' => getRelativePath($fileWritePath), "mime_provided"=>$mime);
        return $uploadStatus;
    }
}
Example #8
0
function _show_existing_object_class(&$images, &$cache, &$app, $table, $id, $only_local, $id_class, $class, $descr, $e_edit_data)
{
    $p =& $app->ui;
    $tmp = '';
    if (!isset($cache[$id_class][0])) {
        return '';
    }
    $obj = $cache[$id_class][0];
    $found_local = $obj['_table'] == $table && $obj['_id'] == $id;
    if ($obj['is_local'] && $found_local == false) {
        return '';
    }
    if ($only_local && !$found_local && substr($class, 0, 2) != 'u_') {
        return '';
    }
    if (isset($cms_object_views[$class])) {
        $objviews[$class] = array($table, $id);
    }
    $color = $found_local ? '#0000CC' : '#009000';
    $stat = '';
    if ($obj['is_public'] || $obj['is_local']) {
        $stat = ' (';
        if ($obj['is_public']) {
            $stat .= '<FONT COLOR="RED">' . $lang['public'] . '</FONT>';
        }
        if ($obj['is_public'] && $obj['is_local']) {
            $stat .= ', ';
        }
        if ($obj['is_local']) {
            $stat .= $lang['local'];
        }
        $stat .= ')';
    }
    if (mime_type($obj['mime']) == 'image') {
        $imagename = $obj['filename'];
        if ($imagename == '') {
            $imagename = $obj['mime'];
        }
        $images .= '<td><table border="1" cellpadding="2" cellspacing="0">' . '<tr><td align="center">' . '<a href="' . $app->url($e_edit_data);
        '"><img border="0" src="' . $p->filelink('obj_data', 'data', $obj['mime'], $obj['id'], $obj['data']) . "\" alt=\"{$imagename}\"></a><br>" . '<FONT COLOR="' . $color . '">' . $descr . ", {$imagename}</FONT>{$stat}" . '</td></tr>' . '</table></td>' . "\n";
        return '';
    }
    return '[' . $p->_looselink("<FONT COLOR=\"{$color}\">{$descr}</FONT>{$stat}", $e_edit_data) . "]\n";
}
Example #9
0
 /**
  * Detect MIME Content-type for a file
  *
  * @param string $filename Path to the tested file.
  * @return string
  */
 function mime_content_type($filename)
 {
     $ext = strtolower(array_pop(explode('.', $filename)));
     if ($mime = mime_type($ext)) {
         return $mime;
     } elseif (function_exists('finfo_open')) {
         $finfo = finfo_open(FILEINFO_MIME);
         $mime = finfo_file($finfo, $filename);
         finfo_close($finfo);
         return $mime;
     } else {
         return 'application/octet-stream';
     }
 }
function validateDataset($dataPath, $projectLink, $fimsAuthCookiesAsString = null, $continue = false)
{
    try {
        $fimsValidateUrl = 'http://www.biscicol.org/biocode-fims/rest/validate';
        # See
        # http://biscicol.org/biocode-fims/rest/fims.wadl#idp1379817744
        # https://fims.readthedocs.org/en/latest/amphibian_disease_example.html#validate-dataset
        if ($continue == true) {
            $fimsStatusUrl = $fimsValidateUrl . '/status';
            $fimsContinueUrl = $fimsValidateUrl . '/continue';
            $params = array('http' => array('method' => 'GET', 'header' => implode("\r\n", array('Content-type: application/x-www-form-urlencoded', 'Accept: application/json', 'User-Agent: amphibian disease portal')) . "\r\n"));
            $params['http']['header'] .= "Cookie: " . $cookiesString . "\r\n";
            $ctx = stream_context_create($params);
            $rawResponse = file_get_contents($fimsStatusUrl, false, $ctx);
            if ($rawResponse === false) {
                throw new Exception("Fatal FIMS communication error 007 (No Response)");
            }
            $rawResponse2 = file_get_contents($fimsContinueUrl, false, $ctx);
            $resp = json_decode($rawResponse, true);
            $resp2 = json_decode($rawResponse2, true);
            return array('status' => true, 'responses' => array('status' => $resp, 'continue' => $resp2), 'cookies' => $cookiesString);
        }
        # $data = smart_decode64($dataset, false);
        $datasrc = decode64($dataPath);
        $file = realpath($datasrc);
        if (!file_exists($file)) {
            return array('status' => false, 'error' => 'INVALID_FILE_PATH', 'human_error' => "Sorry, we couldn't validate your uploaded file", 'provided' => array('path' => $datasrc, 'computed_path' => $file));
        }
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $file);
        finfo_close($finfo);
        if (empty($mime) || $mime == 'application/zip') {
            # Just the fallback that is based purely on extension
            # Only used when finfo can't find a mime type
            try {
                include_once dirname(__FILE__) . '/helpers/js-dragdrop/manual_mime.php';
                $mime = mime_type($file);
            } catch (Exception $e) {
                $mime_error = $e->getMessage();
                $mime = null;
            }
        }
        # https://secure.php.net/manual/en/function.curl-file-create.php
        $dataUploadObj = curl_file_create($file, $mime);
        # Remove the invalid "fims_extra" data
        // foreach($data as $k=>$row) {
        //     unset($row["fimsExtra"]);
        //     $data[$k] = $row;
        // }
        # The POST object
        $fimsValidateData = array('dataset' => $dataUploadObj, 'projectId' => 26, 'expeditionCode' => $projectLink);
        # Login
        if (empty($fimsAuthCookiesAsString)) {
            global $fimsPassword;
            $fimsPassCredential = $fimsPassword;
            $fimsUserCredential = 'amphibiaweb';
            # AmphibianDisease
            $fimsAuthUrl = 'http://www.biscicol.org/biocode-fims/rest/authenticationService/login';
            $fimsAuthData = array('username' => $fimsUserCredential, 'password' => $fimsPassCredential);
            # Post the login
            $params = array('http' => array('method' => 'POST', 'content' => http_build_query($fimsAuthData), 'header' => implode("\r\n", array('Content-type: application/x-www-form-urlencoded', 'Accept: application/json', 'User-Agent: amphibian disease portal')) . "\r\n"));
            $ctx = stream_context_create($params);
            $rawResponse = file_get_contents($fimsAuthUrl, false, $ctx);
            if ($rawResponse === false) {
                throw new Exception("Fatal FIMS communication error 008 (No Response)");
            }
            $loginHeaders = $http_response_header;
            $cookies = array();
            $cookiesString = '';
            foreach ($http_response_header as $hdr) {
                if (preg_match('/^Set-Cookie:\\s*([^;]+)/', $hdr, $matches)) {
                    $cookiesString .= $matches[1] . ';';
                    parse_str($matches[1], $tmp);
                    $cookies += $tmp;
                }
            }
            $loginResponse = json_decode($rawResponse, true);
            if (empty($loginResponse['url'])) {
                throw new Exception('Invalid Login Response E004');
            }
        } else {
            $loginResponse = 'NO_LOGIN_CREDENTIALS_PROVIDED';
            $cookiesString = $fimsAuthCookiesAsString;
            $params = array('http' => array('method' => 'POST'));
        }
        # Post the args
        $headers = array();
        $headers[] = 'Content-type: multipart/form-data';
        $headers[] = 'Accept: application/json';
        $headers[] = 'User-Agent: amphibian disease portal';
        $params = array('http' => array('method' => 'POST', 'header' => $headers, 'content' => http_build_query($fimsValidateData)));
        # https://fims.readthedocs.org/en/latest/amphibian_disease_example.html#validate-dataset
        $ch = curl_init($fimsValidateUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
        // required as of PHP 5.6.0
        # Also auto sets header to "multipart/form-data"
        # Must be an array for file uploads
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fimsValidateData);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIE, $cookiesString);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        #curl_setopt($ch, CURLOPT_USERAGENT, "amphibian disease portal");
        #curl_setopt( $ch, CURLOPT_HEADER, 1);
        $rawResponse = curl_exec($ch);
        curl_close($ch);
        $resp = json_decode($rawResponse, true);
        $status = true;
        $validateStatus = true;
        # Check the response for errors
        try {
            if (isset($resp['done']['worksheets'][0]['Samples'])) {
                $hasError = !empty($resp['done']['worksheets'][0]['Samples']['errors']);
                $hasWarning = !empty($resp['done']['worksheets'][0]['Samples']['warnings']);
            } else {
                $hasError = false;
                $hasWarning = false;
            }
        } catch (Exception $e) {
            $hasError = false;
            $hasWarning = false;
        }
        if (empty($resp) || !isset($resp['done']['worksheets'][0])) {
            $validateStatus = 'FIMS_SERVER_DOWN';
        } elseif ($hasError) {
            $mainError = $resp['done']['worksheets'][0]['Samples']['errors'][0];
            $meK = key($mainError);
            $errorMessage = $meK . ': ' . $mainError[$meK][0];
            if (!empty($mainError[0][0])) {
                $errorMessage .= $mainError[0][0];
            }
            $validateStatus = array('status' => false, 'error' => $errorMessage, 'main_error' => $mainError, 'errors' => $resp['done']['worksheets'][0]['Samples']['errors'], 'warnings' => $resp['done']['worksheets'][0]['Samples']['warnings']);
        }
        # Make the response
        $response = array('status' => $status, 'validate_status' => $validateStatus, 'responses' => array('login_response' => array('response' => $loginResponse, 'cookies' => $cookiesString), 'validate_response' => $resp, 'raw_response' => $rawResponse, 'validate_has_error' => $hasError), 'post_params' => array('file_sent' => $dataUploadObj, 'header_params' => $params), 'data' => array('data_sent' => $fimsValidateData, 'data_mime' => array('mime' => $mime, 'mime_error' => $mime_error)));
        return $response;
    } catch (Exception $e) {
        return array('status' => true, 'validate_status' => 'FIMS_SERVER_DOWN', 'error' => $e->getMessage(), 'human_error' => 'There was a problem communicating with the FIMS project. Please try again later.');
    }
}
Example #11
0
$src = cleanSource($src);
// last modified time (for caching)
$lastModified = filemtime($src);
// get properties
$new_width = preg_replace("/[^0-9]+/", '', get_request('w', 0));
$new_height = preg_replace("/[^0-9]+/", '', get_request('h', 0));
$zoom_crop = preg_replace("/[^0-9]+/", '', get_request('zc', 1));
$quality = preg_replace("/[^0-9]+/", '', get_request('q', 80));
$filters = get_request('f', '');
$sharpen = get_request('s', 0);
if ($new_width == 0 && $new_height == 0) {
    $new_width = 100;
    $new_height = 100;
}
// get mime type of src
$mime_type = mime_type($src);
// check to see if this image is in the cache already
check_cache($mime_type);
// if not in cache then clear some space and generate a new file
cleanCache();
ini_set('memory_limit', '50M');
// make sure that the src is gif/jpg/png
if (!valid_src_mime_type($mime_type)) {
    displayError('Invalid src mime type: ' . $mime_type);
}
if (strlen($src) && file_exists($src)) {
    // open the existing image
    $image = open_image($mime_type, $src);
    if ($image === false) {
        displayError('Unable to open image : ' . $src);
    }
        }
    }
}
if (!$err) {
    // make sure we can determine mime type and extension from file name
    $file_name = stripslashes($file['name']);
    $file_size = $file['size'];
    $file_extension = file_extension($file_name);
    $mime = mime_from_path($file_name);
    if (!($mime && $file_extension)) {
        $err = 'Could not determine mime type or extension';
    }
}
if (!$err) {
    // make sure mime type is supported
    $file_type = mime_type($mime);
    switch ($file_type) {
        case 'audio':
        case 'video':
        case 'image':
            break;
        default:
            $err = 'Only audio, image and video files supported';
    }
}
if (!$err) {
    // make sure type and extension match
    if ($type != $file_type) {
        $err = 'Type ' . $file_type . ' was not the expected type ' . $type;
    } else {
        if ($extension != $file_extension) {
 protected function processMedia($value, $key, $thumbnail = true)
 {
     $image = null;
     $type = null;
     if (is_array($value)) {
         $attributes = Kurogo::arrayVal($value, '@attributes', array());
         if (!($url = Kurogo::arrayVal($attributes, 'url'))) {
             return null;
         }
         if (!($type = Kurogo::arrayVal($attributes, 'type'))) {
             if ($medium = Kurogo::arrayVal($attributes, 'medium')) {
                 $type = $medium;
             } else {
                 $bits = parse_url($url);
                 $type = mime_type(Kurogo::arrayVal($bits, 'path'));
             }
         }
     } elseif (is_scalar($value)) {
         //assume it's a url_stat
         $url = $value;
         $bits = parse_url($url);
         $type = mime_type(Kurogo::arrayVal($bits, 'path'));
     }
     if ($this->typeIsImage($type)) {
         $image = new $this->imageClass();
         $image->setURL($url);
         $image->setThumbnail($thumbnail);
         $image->init($this->initArgs);
     }
     return $image;
 }
 function testMimeType()
 {
     $this->assertEquals(mime_type('foo.tar.gz'), 'application/x-gzip');
     $this->assertEquals(mime_type('foo.tar.gz', 'text/plain'), 'application/x-gzip');
     $this->assertEquals(mime_type('foo.bar'), 'application/octet-stream');
     $this->assertEquals(mime_type('foo.bar', 'text/plain'), 'text/plain');
     $this->assertEquals(mime_type('TODO'), 'application/octet-stream');
     $this->assertEquals(mime_type('TODO', 'text/plain'), 'text/plain');
 }
Example #15
0
function send_file($file, $name = null)
{
    if (strpos($file, "http") === 0) {
        /* HTTP link, redirect… */
        header('Location:' . $file);
        die("You are being redirected...");
    } else {
        if (strpos($file, '/plugins/files/') === 0 && @$USE_CDN) {
            // use a redirect instead of an echo so that the CDN can cache the content
            header('Location: http://cdn.qsapp.com' . $file);
            die("You are being redirected...");
        } else {
            $file_path = file_root($file) . $file;
            $type = mime_type($file_path);
            $size = filesize($file_path);
            debug("sending file \"{$file}\" ({$file_path}) with name \"{$name}\", type: {$type},  size: {$size}");
            header("Content-Type: " . $type);
            header("Content-Length: " . $size);
            if ($name) {
                header("Content-Disposition: attachment; filename=\"" . $name . "\"");
            }
            $contents = file_get_contents($file_path);
            if (!$contents) {
                return false;
            }
            echo $contents;
            die;
        }
    }
    return true;
}
Example #16
0
 function add_file($filename)
 {
     if (!file_exists($filename)) {
         return;
     }
     $fp = @fopen($filename, "rb");
     $contents = fread($fp, filesize($filename));
     fclose($fp);
     $this->attachment(basename($filename), $contents, mime_type($filename));
 }
Example #17
0
     $file_fspath = $file_fspath2;
 } elseif (file_exists($old_style)) {
     $file_fspath = $old_style;
 }
 if (file_exists($file_fspath)) {
     $file_size = filesize($file_fspath);
     $fp = fopen($file_fspath, 'r');
     if ($fp && $file_size != -1) {
         $ext = substr($filename, strrpos($filename, '.') + 1);
         if (in_array($ext, $inlinefiles)) {
             $inline = TRUE;
         } else {
             $inline = FALSE;
         }
         if ($inline) {
             header("Content-Type: " . mime_type($file_fspath));
         } else {
             header("Content-Type: application/octet-stream");
         }
         header("Content-Length: {$file_size}");
         if ($inline) {
             header("Content-Disposition: inline; filename=\"{$filename}\"");
         } else {
             header("Content-Disposition: attachment; filename=\"{$filename}\"");
         }
         header("Content-Transfer-Encoding: binary");
         if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE") and $_SERVER['HTTPS']) {
             header('Cache-Control: private');
             header('Pragma: private');
         }
         $buffer = '';
Example #18
0
function k_resize_image($src, $dest = 0, $new_width = 0, $new_height = 0, $zoom_crop = 1, $enforce_max = 0, $quality = 80, $crop_position = 'middle', $check_thumb_exists = 0)
{
    global $FUNCS;
    // check to see if GD function exist
    if (!function_exists('imagecreatetruecolor')) {
        return displayError('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
    }
    if (trim($src) == '') {
        return displayError('Source image not set');
    }
    // get mime type of src
    $mime_type = mime_type($src);
    ini_set('memory_limit', "50M");
    // make sure that the src is gif/jpg/png
    if (!valid_src_mime_type($mime_type)) {
        return displayError("Invalid src mime type: " . $mime_type);
    }
    if (strlen($src) && file_exists($src)) {
        // open the existing image
        $image = open_image($mime_type, $src);
        if ($image === false) {
            return displayError('Unable to open image : ' . $src);
        }
        // Get original width and height
        $width = imagesx($image);
        $height = imagesy($image);
        // generate new w/h if not provided
        if ($new_width && !$new_height) {
            $new_height = $height * ($new_width / $width);
        } elseif ($new_height && !$new_width) {
            $new_width = $width * ($new_height / $height);
        } elseif (!$new_width && !$new_height) {
            $new_width = $width;
            $new_height = $height;
        }
        // If new dimensions cannot exceed certain values
        if ($enforce_max) {
            // the supplied width and height were actually the max permissible values.
            $max_width = $new_width;
            $max_height = $new_height;
            // make the new values the same as that of the source image
            $new_width = $width;
            $new_height = $height;
            // if new dimensions already within bounds (and this not a thumbnail that we are creating), return.
            if ($dest && $new_width <= $max_width && $new_height <= $max_height) {
                return;
            }
            if ($new_width > $max_width) {
                if (!$zoom_crop) {
                    $ratio = (double) ($max_width / $new_width);
                    $new_width = (int) ($new_width * $ratio);
                    $new_height = (int) ($new_height * $ratio);
                } else {
                    $new_width = $max_width;
                }
            }
            // if new height still overshoots maximum value
            if ($new_height > $max_height) {
                if (!$zoom_crop) {
                    $ratio = (double) ($max_height / $new_height);
                    $new_width = (int) ($new_width * $ratio);
                    $new_height = (int) ($new_height * $ratio);
                } else {
                    $new_height = $max_height;
                }
            }
        }
        // Create filename if not provided one (happens only for thumbnails)
        if (!$dest) {
            $path_parts = $FUNCS->pathinfo($src);
            $thumb_name = $path_parts['filename'] . '-' . round($new_width) . 'x' . round($new_height) . '.' . $path_parts['extension'];
            $thumbnail = $path_parts['dirname'] . '/' . $thumb_name;
            if ($check_thumb_exists && file_exists($thumbnail)) {
                return $thumb_name;
            }
        }
        // create a new true color image
        $canvas = imagecreatetruecolor($new_width, $new_height);
        imagealphablending($canvas, false);
        // Create a new transparent color for image
        $color = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
        // Completely fill the background of the new image with allocated color.
        imagefill($canvas, 0, 0, $color);
        // Restore transparency blending
        imagesavealpha($canvas, true);
        if ($zoom_crop) {
            $src_x = $src_y = 0;
            $src_w = $width;
            $src_h = $height;
            $cmp_x = $width / $new_width;
            $cmp_y = $height / $new_height;
            // if new dimensions equal to the original (and this not a thumbnail that we are creating), return.
            if ($dest && $cmp_x == 1 && $cmp_y == 1) {
                return;
            }
            // calculate x or y coordinate and width or height of source
            if ($cmp_x > $cmp_y) {
                $src_w = round($width / $cmp_x * $cmp_y);
                $src_x = round(($width - $width / $cmp_x * $cmp_y) / 2);
            } elseif ($cmp_y > $cmp_x) {
                $src_h = round($height / $cmp_y * $cmp_x);
                $src_y = round(($height - $height / $cmp_y * $cmp_x) / 2);
            }
            switch ($crop_position) {
                case 'top_left':
                    $src_x = 0;
                    $src_y = 0;
                    break;
                case 'top_center':
                    $src_y = 0;
                    break;
                case 'top_right':
                    $src_x *= 2;
                    $src_y = 0;
                    break;
                case 'middle_left':
                    $src_x = 0;
                    break;
                case 'middle':
                    break;
                case 'middle_right':
                    $src_x *= 2;
                    break;
                case 'bottom_left':
                    $src_x = 0;
                    $src_y *= 2;
                    break;
                case 'bottom_center':
                    $src_y *= 2;
                    break;
                case 'bottom_right':
                    $src_x *= 2;
                    $src_y *= 2;
                    break;
            }
            imagecopyresampled($canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
        } else {
            // copy and resize part of an image with resampling
            imagecopyresampled($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        }
        if (!$dest) {
            $dest = $thumbnail;
        }
        // output image to browser based on mime type
        save_image($mime_type, $canvas, $dest, $quality);
        // remove image from memory
        imagedestroy($canvas);
        return $thumb_name;
    } else {
        if (strlen($src)) {
            return displayError("image " . $src . " not found");
        } else {
            return displayError("no source specified");
        }
    }
    return;
}
Example #19
0
    exit;
}
if (isset($_GET["disk-ismounted"])) {
    disk_ismounted();
    exit;
}
if (isset($_GET["filesize"])) {
    file_size();
    exit;
}
if (isset($_GET["filetype"])) {
    file_type();
    exit;
}
if (isset($_GET["mime-type"])) {
    mime_type();
    exit;
}
if (isset($_GET["sync-remote-smtp-artica"])) {
    postfix_sync_artica();
    exit;
}
//etc/hosts
if (isset($_GET["etc-hosts-open"])) {
    etc_hosts_open();
    exit;
}
if (isset($_GET["etc-hosts-add"])) {
    etc_hosts_add();
    exit;
}
Example #20
0
/**
 * Check if the _Accept_ header is present, and includes the given `type`.
 *
 * When the _Accept_ header is not present `true` is returned. Otherwise
 * the given `type` is matched by an exact match, and then subtypes. You
 * may pass the subtype such as "html" which is then converted internally
 * to "text/html" using the mime lookup table.
 *
 * @param string $type
 * @param string $env 
 * @return bool
 */
function http_ua_accepts($type, $env = null)
{
    if (is_null($env)) {
        $env = env();
    }
    $accept = array_key_exists('HTTP_ACCEPT', $env['SERVER']) ? $env['SERVER']['HTTP_ACCEPT'] : null;
    if (!$accept || $accept === '*/*') {
        return true;
    }
    if ($type) {
        // Allow "html" vs "text/html" etc
        if (!strpos($type, '/')) {
            $type = mime_type($type);
        }
        // Check if we have a direct match
        if (strpos($accept, $type) > -1) {
            return true;
        }
        // Check if we have type/*
        $type_parts = explode('/', $type);
        $type = $type_parts[0] . '/*';
        return strpos($accept, $type) > -1;
    }
    return false;
}
 function service_import_init($import, $config = array())
 {
     $result = array();
     if (!$config) {
         $config = config_get();
     }
     log_file(print_r($import, 1), $config);
     $err = config_error($config);
     // should wind up calling __service_load
     if (!$err) {
         $function_name = $config['file'] . '_file_import_init';
         if (!function_exists($function_name)) {
             $err = $function_name . ' is not defined';
         }
     }
     if (!$err && empty($import['size'])) {
         $err = 'Import option size required';
     }
     if (!$err && empty($import['file'])) {
         $err = 'Import option file required';
     }
     if (!$err && empty($import['extension'])) {
         $import['extension'] = file_extension($import['file']);
         if (!$import['extension']) {
             $err = 'Import option extension required';
         }
     }
     if (!$err && empty($import['mime'])) {
         $import['mime'] = mime_from_path($import['file']);
         if (!$import['mime']) {
             $err = 'Import option mime required';
         }
     }
     if (!$err && empty($import['type'])) {
         $import['type'] = mime_type($import['mime']);
         if (!$import['type']) {
             $err = 'Import option type required';
         } else {
             switch ($import['type']) {
                 case 'audio':
                 case 'video':
                 case 'image':
                     break;
                 default:
                     $err = 'Import type ' . $import['type'] . ' unsupported';
             }
         }
     }
     if (!$err) {
         // enforce size limit from configuration, if defined
         $max = empty($config["max_meg_{$import['type']}"]) ? '' : $config["max_meg_{$import['type']}"];
         if ($max) {
             $file_megs = round($import['size'] / (1024 * 1024));
             if ($file_megs > $max) {
                 $err = $import['type'] . ' files must be less than ' . $max . ' meg';
             }
         }
     }
     if (!$err && empty($import['label'])) {
         $import['label'] = $import['file'];
     }
     //$err = $function_name;
     if (!$err) {
         $result = $function_name($import, $config);
     }
     if ($err) {
         $result['error'] = $err;
     }
     return $result;
 }
Example #22
0
<?php

define('IN_PHPATM', true);
include 'include/conf.php';
include 'include/functions.' . $phpExt;
$image = $_GET['image'];
$imagepath = clean_path("{$uploads_folder_name}/{$image}");
if (!file_exists($imagepath)) {
    header('Status: 404 Not Found');
    exit;
}
$mime_type = mime_type($image);
if ($mime_type != '') {
    header("Content-type: {$mime_type}");
    header("Content-Disposition: attachment; filename=\"{$image}\"");
    @readfile($imagepath);
} else {
    header('Status: 404 Not Found');
}
Example #23
0
/**
 * Detect MIME Content-type for a file
 *
 * @param string $filename Path to the tested file.
 * @return string
 */
function file_mime_content_type($filename)
{
    $ext = file_extension($filename);
    /* strtolower isn't necessary */
    if ($mime = mime_type($ext)) {
        return $mime;
    } elseif (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME);
        $mime = finfo_file($finfo, $filename);
        finfo_close($finfo);
        return $mime;
    } else {
        return 'application/octet-stream';
    }
}
Example #24
0
 
 
 $resizeObj7 = new resize($root_month . $image);
 $resizeObj7->resizeImage(188, 144, 'crop');
 $resizeObj7->saveImage($root_month . vnit_change_title($title) . '188x144.' . $ext, 100);
 unset($resizeObj7);
 */
 // Post Attachment
 $post_attachment = array('post_title' => $title, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => mime_type($ext), 'post_author' => 1, 'post_date' => date("Y-m-d H:i:s"), 'post_date_gmt' => date("Y-m-d H:i:s"), 'post_name' => vnit_change_title($title), 'post_modified' => date("Y-m-d H:i:s"), 'post_modified_gmt' => date("Y-m-d H:i:s"), 'guid' => 'http://masterapk.com/dungml/' . vnit_change_title($title) . '/' . vnit_change_title($title) . '-2/');
 $db->insert("wp_posts", $post_attachment);
 $_post_thumbnail_id = $db->insert_id();
 $data_attach['width'] = '300';
 $data_attach['height'] = '300';
 $data_attach['height'] = '300';
 $data_attach['height'] = $dir_root . $slug . '.' . $ext;
 $data_attach['sizes'] = array('thumbnail' => array('file' => $slug . '150x150.' . $ext, 'width' => '150', 'height' => '150', 'mime-type' => mime_type($ext), 'wp_smushit' => 'ERROR: posting to Smush.it'), 'medium' => array('file' => $slug . '300x300.' . $ext, 'width' => '300', 'height' => '300', 'mime-type' => mime_type($ext), 'wp_smushit' => 'ERROR: posting to Smush.it'), 'mag-image' => array('file' => $slug . '300x160.' . $ext, 'width' => '300', 'height' => '160', 'mime-type' => mime_type($ext), 'wp_smushit' => 'ERROR: posting to Smush.it'), 'blog-image' => array('file' => $slug . '220x180.' . $ext, 'width' => '220', 'height' => '180', 'mime-type' => mime_type($ext), 'wp_smushit' => 'ERROR: posting to Smush.it'), 'sb-post-thumbnail' => array('file' => $slug . '70x70.' . $ext, 'width' => '70', 'height' => '70', 'mime-type' => mime_type($ext), 'wp_smushit' => 'ERROR: posting to Smush.it'), 'sb-post-big-thumbnail' => array('file' => $slug . '300x192.' . $ext, 'width' => '300', 'height' => '192', 'mime-type' => mime_type($ext), 'wp_smushit' => 'ERROR: posting to Smush.it'), 'sb-post-small-thumbnail' => array('file' => $slug . '188x144.' . $ext, 'width' => '188', 'height' => '144', 'mime-type' => mime_type($ext), 'wp_smushit' => 'ERROR: posting to Smush.it'));
 $data_attach['image_meta'] = array('aperture' => 0, 'credit' => '', 'camera' => '', 'caption' => '', 'created_timestamp' => 0, 'copyright' => '', 'focal_length' => 0, 'iso' => 0, 'shutter_speed' => 0, 'title' => "", 'orientation' => 0);
 $data_attach['wp_smushit'] = 'ERROR: posting to Smush.it';
 $data_ar_img = serialize($data_attach);
 $_wp_attachment_metadata["post_id"] = $_post_thumbnail_id;
 $_wp_attachment_metadata["meta_key"] = "_wp_attachment_metadata";
 $_wp_attachment_metadata["meta_value"] = $data_ar_img;
 $db->insert("wp_postmeta", $_wp_attachment_metadata);
 $_wp_attached_file["post_id"] = $_post_thumbnail_id;
 $_wp_attached_file["meta_key"] = "_wp_attached_file";
 $_wp_attached_file["meta_value"] = $dir_root . $slug . '.' . $ext;
 $db->insert("wp_postmeta", $_wp_attached_file);
 $_thumbnail_ids = $db->insert_id();
 $vattach["post_id"] = $post_id;
 $vattach["meta_key"] = "_thumbnail_id";
 $vattach["meta_value"] = $_post_thumbnail_id;
Example #25
0
 /**
  * Return the file mimetype
  *
  * @return string The mimetype
  */
 public function getMimetype()
 {
     $mimetype = 'application/octet-stream';
     $mimes = mime_type();
     $ext = $this->getExtension();
     if (array_key_exists($ext, $mimes)) {
         $mimetype = $mimes[$ext];
     } else {
         if (function_exists('finfo_file')) {
             $file = finfo_open(FILEINFO_MIME_TYPE);
             $mimetype = finfo_file($file, $this->getOnDiskLocation(), FILEINFO_MIME_TYPE);
             finfo_close($file);
         }
     }
     return $mimetype;
 }
Example #26
0
if(isset($_GET["read-file"])){ReadFromfile();exit;}



if(isset($_GET["lvs-all"])){LVM_lVS_INFO_ALL();exit;}
if(isset($_GET["lv-resize-add"])){LVM_LV_ADDSIZE();exit;}
if(isset($_GET["lv-resize-red"])){LVM_LV_DELSIZE();exit;}
if(isset($_GET["disk-ismounted"])){disk_ismounted();exit;}
if(isset($_GET["disks-quotas-list"])){disks_quotas_list();exit;}
if(isset($_GET["dfmoinshdev"])){disks_dfmoinshdev();exit;}



if(isset($_GET["filesize"])){file_size();exit;}
if(isset($_GET["filetype"])){file_type();exit;}
if(isset($_GET["mime-type"])){mime_type();exit;}

if(isset($_GET["sync-remote-smtp-artica"])){postfix_sync_artica();exit;}

//etc/hosts
if(isset($_GET["etc-hosts-open"])){etc_hosts_open();exit;}
if(isset($_GET["etc-hosts-add"])){etc_hosts_add();exit;}
if(isset($_GET["etc-hosts-del"])){etc_hosts_del();exit;}
if(isset($_GET["etc-hosts-del-by-values"])){etc_hosts_del_by_values();exit;}



if(isset($_GET["full-hostname"])){hostname_full();exit;}

//computers
if(isset($_GET["nmap-scan"])){nmap_scan();exit;}