Example #1
0
 static function url($urls, $albumID = 0)
 {
     $error = false;
     # Parse
     $urls = str_replace(' ', '%20', $urls);
     $urls = explode(',', $urls);
     foreach ($urls as &$url) {
         # Verify extension
         $extension = getExtension($url);
         if (!in_array(strtolower($extension), Photo::$validExtensions, true)) {
             $error = true;
             continue;
         }
         # Verify image
         $type = @exif_imagetype($url);
         if (!in_array($type, Photo::$validTypes, true)) {
             $error = true;
             continue;
         }
         $pathinfo = pathinfo($url);
         $filename = $pathinfo['filename'] . '.' . $pathinfo['extension'];
         $tmp_name = LYCHEE_DATA . $filename;
         if (@copy($url, $tmp_name) === false) {
             $error = true;
         }
     }
     $import = Import::server($albumID, LYCHEE_DATA);
     if ($error === false && $import === true) {
         return true;
     } else {
         return false;
     }
 }
Example #2
0
function validate_language_form($data)
{
    define("ICON_MAX_SIZE", "100");
    $error = '';
    if ($data['country'] == '' || empty($data['country'])) {
        $error .= "Country field required!!<br>";
    }
    if ($data['language'] == '' || empty($data['language'])) {
        $error .= "Language field required!!<br>";
    }
    if ($data['currency'] == '' || empty($data['currency'])) {
        $error .= "Currency field required!!<br>";
    }
    $filename = stripslashes($data['icon']['name']);
    if ($filename) {
        $extension = getExtension($filename);
        $extension = strtolower($extension);
        if ($extension != "jpg" && $extension != "jpeg" && $extension != "png" && $extension != "gif") {
            $error .= "Upload language icon unknown extension!!<br>";
        } else {
            $size = $data['icon']['size'];
            if ($size > ICON_MAX_SIZE * 1024) {
                $error .= "Upload language icon exceeded the size limit!!<br>";
            }
            list($width, $height) = getimagesize($data['icon']['tmp_name']);
            if ($width > 50 || $height > 50) {
                $error .= "Upload language icon size must 50 * 50!!<br>";
            }
        }
    } else {
        $error .= "Upload language icon field required!!<br>";
    }
    return $error;
}
Example #3
0
function hinzufuegen($bildseite, $datenbank)
{
    if (hinzufuegenVariablenVorhanden()) {
        if ($extension = getExtension()) {
            // ZeigenAb wurde angegeben
            if (strtotime($_POST["zeigenAb"]) !== false) {
                // ZeigenBis wurde angegeben
                if (strtotime($_POST["zeigenBis"]) !== false) {
                    $bildseite->create($datenbank, $extension, $_POST["beschriftung"], $_POST["layout"], date("Y-m-d H:i:s", strtotime($_POST["zeigenAb"])), date("Y-m-d H:i:s", strtotime($_POST["zeigenBis"])));
                    // ZeigenBis wurde nicht angegeben
                } else {
                    $bildseite->create($datenbank, $extension, $_POST["beschriftung"], $_POST["layout"], date("Y-m-d H:i:s", strtotime($_POST["zeigenAb"])));
                }
                // ZeigenAb wurde nicht angegeben
            } else {
                $bildseite->create($datenbank, $extension, $_POST["beschriftung"], $_POST["layout"]);
            }
            dateiVerschieben($bildseite->id, $extension);
            zurueck();
        } else {
            echo "Datei wurde nicht erfolgreich hochgeladen :/";
        }
    } else {
        echo "Nicht alle oder ungültige Daten übertragen :/";
    }
}
 /**
  * Bootstraps the application.
  *
  * This method is called after all services are registers
  * and should be used for "dynamic" configuration (whenever
  * a service must be requested).
  */
 public function boot(Application $app)
 {
     if (isset($app['translator'])) {
         $paths = $app['resources']->getPaths();
         $app['translator']->addLoader('yml', new TranslationLoader\YamlFileLoader());
         // Directory to look for translation file(s)
         $translationDir = $paths['apppath'] . '/resources/translations/' . $app['locale'];
         if (is_dir($translationDir)) {
             $iterator = new \DirectoryIterator($translationDir);
             /**
              * @var \SplFileInfo $fileInfo
              */
             foreach ($iterator as $fileInfo) {
                 if ($fileInfo->isFile() && getExtension($fileInfo->getFilename()) == "yml") {
                     $fnameParts = explode(".", $fileInfo->getFilename());
                     $domain = $fnameParts[0];
                     $app['translator']->addResource('yml', $fileInfo->getRealPath(), $app['locale'], $domain);
                 }
             }
         }
         // Load fallback for infos domain
         $infosfilename = dirname(dirname(dirname(__DIR__))) . '/resources/translations/en/infos.en.yml';
         if (is_readable($infosfilename)) {
             $app['translator']->addResource('yml', $infosfilename, 'en', 'infos');
         }
     }
 }
Example #5
0
File: lib.php Project: LeonB/site
function findFilesHelper($additional, &$files, $term = '', $extensions = array())
{
    $basefolder = __DIR__ . '/../../files/';
    $currentfolder = realpath($basefolder . '/' . $additional);
    $dir = dir($currentfolder);
    $ignored = array('.', '..', '.DS_Store', '.gitignore', '.htaccess');
    while (false !== ($entry = $dir->read())) {
        if (in_array($entry, $ignored) || substr($entry, 0, 2) == '._') {
            continue;
        }
        if (is_file($currentfolder . '/' . $entry) && is_readable($currentfolder . '/' . $entry)) {
            // Check for 'term'..
            if (!empty($term) && strpos(strtolower($currentfolder . '/' . $entry), $term) === false) {
                continue;
                // skip this one..
            }
            // Check for correct extensions..
            if (!empty($extensions) && !in_array(getExtension($entry), $extensions)) {
                continue;
                // Skip files without correct extension..
            }
            if (!empty($additional)) {
                $filename = $additional . '/' . $entry;
            } else {
                $filename = $entry;
            }
            $files[] = $filename;
        }
        if (is_dir($currentfolder . '/' . $entry)) {
            findFilesHelper($additional . '/' . $entry, $files, $term, $extensions);
        }
    }
    $dir->close();
}
Example #6
0
function resizeImage($filename, $newfilename, $max_width = '', $max_height = '', $withSampling = true)
{
    // if($newfilename=="")
    //     $newfilename=$filename;
    // Get new sizes
    list($width, $height) = getimagesize($filename);
    if ($max_width == '' && $max_height == '') {
        exit("You must set a max height or width");
    }
    if ($max_width != '') {
        $percent = $max_width / $width;
    } else {
        if ($max_height != '') {
            $percent = $max_height / $height;
        }
    }
    //-- dont resize if the width of the image is smaller or equal than the new size.
    // if($width<=$max_width)
    //     $max_width=$width;
    // $percent = $max_width/$width;
    $newwidth = $width * $percent;
    $newheight = $height * $percent;
    // if($max_height=='') {
    // } else
    // $newheight = $max_height;
    // Load
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $ext = strtolower(getExtension($filename));
    // print $ext;
    // exit();
    if ($ext == 'jpg' || $ext == 'jpeg') {
        $source = imagecreatefromjpeg($filename);
    } else {
        if ($ext == 'gif') {
            $source = imagecreatefromgif($filename);
        } else {
            if ($ext == 'png') {
                $source = imagecreatefrompng($filename);
            }
        }
    }
    // Resize
    if ($withSampling) {
        imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    } else {
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    }
    // imagedestroy($thumb);
    // Output
    if ($ext == 'jpg' || $ext == 'jpeg') {
        return imagejpeg($thumb, $newfilename);
    }
    if ($ext == 'gif') {
        return imagegif($thumb, $newfilename);
    }
    if ($ext == 'png') {
        return imagepng($thumb, $newfilename);
    }
}
Example #7
0
function changeFileNameImage($filename)
{
    $file = getFilename($filename);
    $str = strtotime(date('Y-m-d H:i:s'));
    $fileNameAfter = $file . '-' . $str;
    $extension = getExtension($filename);
    return $fileNameAfter . '.' . $extension;
}
function check_upload_extension($filename,$allow_list){
	$sExtension	= getExtension($filename);
	$allow_arr	= explode(",", $allow_list);
	$pass = 0;
	for($i=0; $i<count($allow_arr); $i++){
		if($sExtension == $allow_arr[$i]) $pass = 1;
	}
	return $pass;
}
Example #9
0
function post_image()
{
    //$errors=0;
    //checks if the form has been submitted
    if (isset($_POST['Submit'])) {
        //reads the name of the file the user submitted for uploading
        $image = $_FILES['image']['name'];
        //echo $image;
        //if it is not empty
        if ($image) {
            //get the original name of the file from the clients machine
            $filename = stripslashes($_FILES['image']['name']);
            //get the extension of the file in a lower case format
            $extension = getExtension($filename);
            $extension = strtolower($extension);
            //if it is not a known extension, we will suppose it is an error and will not  upload the file,
            //otherwise we will do more tests
            //echo $filename;
            //echo $extension;
            if ($extension != "jpg" && $extension != "jpeg" && $extension != "png" && $extension != "gif") {
                //print error message
                echo '<h1>Unknown extension!</h1>';
                //$errors=1;
                return false;
            } else {
                //get the size of the image in bytes
                //$_FILES['image']['tmp_name'] is the temporary filename of the file
                //in which the uploaded file was stored on the server
                $size = filesize($_FILES['image']['tmp_name']);
                //compare the size with the maxim size we defined and print error if bigger
                if ($size > MAX_SIZE * 1024) {
                    echo '<h1>File over size limit (1.5 mb).</h1>';
                    $errors = 1;
                    return false;
                }
                $image_name = time() . make_random() . '.' . $extension;
                //echo "image name var ".$image_name;
                //the new name will be containing the full path where will be stored (images folder)
                $newname = "img_db/" . $image_name;
                //we verify if the image has been uploaded, and print error instead
                $copied = copy($_FILES['image']['tmp_name'], $newname);
                if (!$copied) {
                    echo '<h1>Copy unsuccessfull!</h1>';
                    $errors = 1;
                    return false;
                } else {
                    //echo "accepted";
                    $GLOBALS['newname'] = $newname;
                    return true;
                }
            }
            //else for extension known.
        }
        //make sure image is not empty
    }
    //recheck is POST isset
}
Example #10
0
function upload($file, $allow = array('gif', 'png', 'jpeg', 'jpg'))
{
    //1.对$file进行判断,如果不是数组就不存在上传文件
    if (!is_array($file)) {
        return array(false, '当前不是上传的文件信息!');
    }
    //2. 判断文件是否上传成功
    //定义一个错误字符串
    $errorinfo = '';
    switch ($file['error']) {
        case 1:
            $errorinfo = '文件大小超过限制,最大上传大小为' . ini_get('upload_max_filesize');
            break;
        case 2:
            $errorinfo = '文件超过浏览器允许大小';
            break;
        case 3:
            $errorinfo = '文件只上传成功一部分';
            break;
        case 4:
            $errorinfo = '没有选中要上传的文件';
            break;
        case 6:
            $errorinfo = '找不到服务器临时目录';
            break;
        case 7:
            $errorinfo = '文件上传路径不可写';
            break;
    }
    if ($errorinfo) {
        return array(false, $errorinfo);
    }
    //3.判断文件类型
    $extension = getExtension($file['name']);
    //3.1 判断文件后缀是否存在
    if (!$extension) {
        //文件后缀名不存在
        return array(false, '当前文件没有后缀名!');
    }
    //3.2 当前文件是否允许上传
    if (!in_array($extension, $allow)) {
        return array(false, '当前文件类型不允许上传!');
    }
    //4.上传文件
    //4.1重命名文件:获取一个随机的文件名字
    $filename = getRanomFilename();
    //拼凑问价全名
    $filename .= '.' . $extension;
    //4.2移动文件
    if (!@move_uploaded_file($file['tmp_name'], $filename)) {
        //写错误日志
        return array(false, '文件上传失败');
    } else {
        return getcwd() . '\\' . $filename;
    }
}
Example #11
0
 static function generateThumbnail($item)
 {
     $stats = self::generateStats($item['ups'], $item['favs'], $item['downs'], $item['safety']);
     $extension = getExtension($item['filename']);
     if ($extension == 'webm') {
         $item['filename'] .= '.png';
         $extension = 'png';
     }
     return intermix(self::$code, [$item['media_ID'], $item['filename'], $extension, $stats]);
 }
Example #12
0
 /**
  * Checks if a given file is acceptable for upload.
  */
 public function allowedUpload($originalFilename)
 {
     // no UNIX-hidden files
     if ($originalFilename[0] === '.') {
         return false;
     }
     // only whitelisted extensions
     $extension = strtolower(getExtension($originalFilename));
     $allowedExtensions = $this->getAllowedUploadExtensions();
     return in_array($extension, $allowedExtensions);
 }
Example #13
0
 public function url($urls, $albumID = 0)
 {
     # Check dependencies
     self::dependencies(isset($this->database, $urls));
     # Call plugins
     $this->plugins(__METHOD__, 0, func_get_args());
     $error = false;
     # Parse URLs
     $urls = str_replace(' ', '%20', $urls);
     $urls = explode(',', $urls);
     foreach ($urls as &$url) {
         # Validate photo type and extension even when $this->photo (=> $photo->add) will do the same.
         # This prevents us from downloading invalid photos.
         # Verify extension
         $extension = getExtension($url);
         if (!in_array(strtolower($extension), Photo::$validExtensions, true)) {
             $error = true;
             Log::error($this->database, __METHOD__, __LINE__, 'Photo format not supported (' . $url . ')');
             continue;
         }
         # Verify image
         $type = @exif_imagetype($url);
         if (!in_array($type, Photo::$validTypes, true)) {
             $error = true;
             Log::error($this->database, __METHOD__, __LINE__, 'Photo type not supported (' . $url . ')');
             continue;
         }
         $pathinfo = pathinfo($url);
         $filename = $pathinfo['filename'] . '.' . $pathinfo['extension'];
         $tmp_name = LYCHEE_DATA . $filename;
         if (@copy($url, $tmp_name) === false) {
             $error = true;
             Log::error($this->database, __METHOD__, __LINE__, 'Could not copy file (' . $tmp_name . ') to temp-folder (' . $tmp_name . ')');
             continue;
         }
         # Import photo
         if (!$this->photo($tmp_name, $albumID)) {
             $error = true;
             Log::error($this->database, __METHOD__, __LINE__, 'Could not import file: ' . $tmp_name);
             continue;
         }
     }
     # Call plugins
     $this->plugins(__METHOD__, 1, func_get_args());
     if ($error === false) {
         return true;
     }
     return false;
 }
Example #14
0
 public function getErrors($postarr = array())
 {
     //Получение ошибок при регистрации
     $this->name = $postarr['name'];
     $this->surname = $postarr['surname'];
     $this->email = $postarr['email'];
     $this->login = $postarr['login'];
     $this->password = $postarr['password'];
     $this->confirmpass = $postarr['confirmpass'];
     $this->age = $postarr['age'];
     $this->filename = $postarr['filename'];
     $this->filesize = $postarr['filesize'];
     if (!empty($this->filename)) {
         //проверяем расширение файла
         function getExtension($filename)
         {
             return end(explode(".", $filename));
         }
         $extension = getExtension($this->filename);
         //Проверка, существует ли пользователь с таким логином
     }
     $errors = array();
     if (empty($this->login)) {
         array_push($errors, "Заполните поле логин");
     } elseif (strlen($this->login) < 3) {
         array_push($errors, "Логин слишком короткий. Логин должен быть длиннее 3 символов");
     } elseif (empty($this->password)) {
         array_push($errors, "Заполните поле пароль");
     } elseif (empty($this->confirmpass)) {
         array_push($errors, "Заполните поле подтверждение пароля");
     } elseif (empty($this->email)) {
         array_push($errors, "Заполните поле Email");
     } elseif ($this->password != $this->confirmpass) {
         array_push($errors, "Пароли не совпадают");
     } elseif (strlen($this->password) < 6) {
         array_push($errors, "Пароль слишком короткий. Пароль должен быть длиннее 6 символов");
     } elseif ($this->age > 99) {
         array_push($errors, "Возраст введен не корректно.");
     } elseif (!is_numeric($this->age)) {
         array_push($errors, "Возраст должен быть указан в цифрах");
     } elseif ($this->filesize > 1048576 * 5) {
         array_push($errors, "Размер файла должен быть меньше 5 мегабайт");
     } elseif (isset($extension)) {
         if ($extension != 'jpg' && $extension != 'png' && $extension != 'gif') {
             array_push($errors, "Допускается загрузка файлов в формате gif/jpg/png");
         }
     }
     return $errors;
 }
Example #15
0
 /**
  * Bootstraps the application.
  *
  * This method is called after all services are registers
  * and should be used for "dynamic" configuration (whenever
  * a service must be requested).
  */
 public function boot(\Silex\Application $app)
 {
     if (isset($app['translator'])) {
         $loaders = array('csv' => new TranslationLoader\CsvFileLoader(), 'ini' => new TranslationLoader\IniFileLoader(), 'mo' => new TranslationLoader\MoFileLoader(), 'php' => new TranslationLoader\PhpFileLoader(), 'xlf' => new TranslationLoader\XliffFileLoader(), 'yml' => new TranslationLoader\YamlFileLoader());
         $registeredLoaders = array();
         // Directory to look for translation file(s)
         $translationDir = dirname(dirname(__DIR__)) . '/resources/translations/' . $app['locale'];
         if (is_dir($translationDir)) {
             $iterator = new \DirectoryIterator($translationDir);
             /**
              * @var \SplFileInfo $fileInfo
              */
             foreach ($iterator as $fileInfo) {
                 if ($fileInfo->isFile()) {
                     $extension = getExtension($fileInfo->getFilename());
                     // $extension = $fileInfo->getExtension(); -- not available before 5.3.7.
                     if (array_key_exists($extension, $loaders)) {
                         if (!array_key_exists($extension, $registeredLoaders)) {
                             // TranslationFileLoader not yet registered
                             $app['translator']->addLoader($extension, $loaders[$extension]);
                         }
                         // There's a file, there's a loader, let's try
                         $fnameParts = explode(".", $fileInfo->getFilename());
                         $domain = $fnameParts[0];
                         $app['translator']->addResource($extension, $fileInfo->getRealPath(), $app['locale'], $domain);
                     }
                 }
             }
         }
         // load fallback for infos domain
         $locale_fb = $app['locale_fallback'];
         $translationDir = dirname(dirname(__DIR__)) . '/resources/translations/' . $locale_fb;
         if (is_dir($translationDir)) {
             $extension = 'yml';
             $domain = 'infos';
             $infosfilename = "{$translationDir}/{$domain}.{$locale_fb}.{$extension}";
             if (is_readable($infosfilename)) {
                 if (array_key_exists($extension, $loaders)) {
                     if (!array_key_exists($extension, $registeredLoaders)) {
                         // TranslationFileLoader not yet registered
                         $app['translator']->addLoader($extension, $loaders[$extension]);
                     }
                     $app['translator']->addResource($extension, $infosfilename, $locale_fb, $domain);
                 }
             }
         }
     }
 }
Example #16
0
 /**
  * @return boolean Returns true when successful.
  */
 public function url($urls, $albumID = 0)
 {
     // Call plugins
     Plugins::get()->activate(__METHOD__, 0, func_get_args());
     $error = false;
     // Parse URLs
     $urls = str_replace(' ', '%20', $urls);
     $urls = explode(',', $urls);
     foreach ($urls as &$url) {
         // Validate photo type and extension even when $this->photo (=> $photo->add) will do the same.
         // This prevents us from downloading invalid photos.
         // Verify extension
         $extension = getExtension($url, true);
         if (!in_array(strtolower($extension), Photo::$validExtensions, true)) {
             $error = true;
             Log::error(Database::get(), __METHOD__, __LINE__, 'Photo format not supported (' . $url . ')');
             continue;
         }
         // Verify image
         $type = @exif_imagetype($url);
         if (!in_array($type, Photo::$validTypes, true)) {
             $error = true;
             Log::error(Database::get(), __METHOD__, __LINE__, 'Photo type not supported (' . $url . ')');
             continue;
         }
         $filename = pathinfo($url, PATHINFO_FILENAME) . $extension;
         $tmp_name = LYCHEE_DATA . $filename;
         if (@copy($url, $tmp_name) === false) {
             $error = true;
             Log::error(Database::get(), __METHOD__, __LINE__, 'Could not copy file (' . $url . ') to temp-folder (' . $tmp_name . ')');
             continue;
         }
         // Import photo
         if (!$this->photo($tmp_name, $albumID)) {
             $error = true;
             Log::error(Database::get(), __METHOD__, __LINE__, 'Could not import file (' . $tmp_name . ')');
             continue;
         }
     }
     // Call plugins
     Plugins::get()->activate(__METHOD__, 1, func_get_args());
     if ($error === false) {
         return true;
     }
     return false;
 }
Example #17
0
function checkUpload($myFILE, $file_extensions, $mime_types, $maxsize, $ordner)
{
    $errors = array();
    switch ($myFILE['error']) {
        case 1:
            $errors[] = "Wähle eine Datei aus, die <b>kleiner als " . ini_get('upload_max_filesize') . "</b> ist.";
            break;
        case 2:
            $errors[] = "Wähle eine Datei aus, die <b>kleiner als " . $maxsize / (1024 * 1024) . " MB</b> ist.";
            break;
        case 3:
            $errors[] = "Die Datei wurde nur teilweise hochgeladen.";
            break;
        case 4:
            $errors[] = "Es wurde keine Datei ausgewählt.";
            return $errors;
            break;
        default:
            break;
    }
    //MIME-Type prüfen
    if (count($mime_types) != 0 and !in_array(strtolower($myFILE['type']), $mime_types)) {
        $fehler = "Falscher MIME-Type (" . $myFILE['type'] . ").<br />" . "Erlaubte Typen sind:<br />\n";
        foreach ($mime_types as $type) {
            $fehler .= " - " . $type . "\n<br />";
        }
        $errors[] = $fehler;
    }
    //Dateiendung prüfen
    if ($myFILE['name'] == '' or count($file_extensions) != 0 and !in_array(strtolower(getExtension($myFILE['name'])), $file_extensions)) {
        $fehler = "Falsche Dateiendung (" . getExtension($myFILE['name']) . ").<br />" . "Erlaubte Endungen sind:<br />\n";
        foreach ($file_extensions as $extension) {
            $fehler .= " - " . $extension . "\n<br />";
        }
        $errors[] = $fehler;
    }
    //Dateigröße prüfen
    if ($myFILE['size'] > $maxsize) {
        $errors[] = "Datei zu groß (" . sprintf('%.2f', $myFILE['size'] / (1024 * 1024)) . " MB).<br />" . "Erlaubte Größe: " . $maxsize / (1024 * 1024) . " MB\n";
    }
    //Dateiexistenz prüfen
    if (file_exists($ordner . $myFILE['name'])) {
        $errors[] = $myFILE['name'] . " existiert bereits im Zielordner.";
    }
    return $errors;
}
Example #18
0
function createThumb($source, $destination, $saveName, $targetWidth, $targetHeight)
{
    // Get image size
    $originalSize = getimagesize($source);
    // Set thumb image size
    $targetSize = setWidthHeight($originalSize[0], $originalSize[1], $targetWidth, $targetHeight);
    // Get image extension
    $ext = getExtension($source);
    // Determine source image type
    if ($ext == 'gif') {
        $src = imagecreatefromgif($source);
    } elseif ($ext == 'png') {
        $src = imagecreatefrompng($source);
    } elseif ($ext == 'jpg' || $ext == 'jpeg') {
        $src = imagecreatefromjpeg($source);
    } else {
        return 'Unknow image type !';
    }
    // Copy image
    $dst = imagecreatetruecolor($targetSize[0], $targetSize[1]);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $targetSize[0], $targetSize[1], $originalSize[0], $originalSize[1]);
    if (!file_exists($destination)) {
        if (!createRDir($destination)) {
            return 'Unabled to create destination folder !';
        }
    }
    // destination + fileName
    $thumbName = $destination . '/' . $saveName . '.' . $ext;
    if ($ext == 'gif') {
        imagegif($dst, $thumbName);
    } else {
        if ($ext == 'png') {
            imagepng($dst, $thumbName);
        } else {
            if ($ext == 'jpg' || $ext == 'jpeg') {
                imagejpeg($dst, $thumbName, 100);
            } else {
                return 'Fail to create thumb !';
            }
        }
    }
    imagedestroy($dst);
    imagedestroy($src);
    return $thumbName;
}
Example #19
0
function deleteExtensionFiles($dir, $extension)
{
    $dirs = scandir($dir);
    // Do not scan current and parent dir:
    $exceptDirs = array('.', '..');
    foreach ($dirs as $key => $value) {
        if (!in_array($value, $exceptDirs)) {
            if (is_dir($dir . DS . $value)) {
                $dd = deleteExtensionFiles($dir . DS . $value, $extension);
            } else {
                $ext = getExtension($value);
                if ($ext == $extension) {
                    @unlink($value);
                }
            }
        }
    }
}
Example #20
0
function make_thumb($img_name, $filename, $new_w, $new_h)
{
    //get image extension.
    $ext = getExtension($img_name);
    //creates the new image using the appropriate function from gd library
    if (!strcmp("jpg", $ext) || !strcmp("jpeg", $ext)) {
        $src_img = imagecreatefromjpeg($img_name);
    }
    if (!strcmp("png", $ext)) {
        $src_img = imagecreatefrompng($img_name);
    }
    //gets the dimmensions of the image
    $old_x = imageSX($src_img);
    $old_y = imageSY($src_img);
    // next we will calculate the new dimmensions for the thumbnail image
    // the next steps will be taken:
    // 1. calculate the ratio by dividing the old dimmensions with the new ones
    // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
    // and the height will be calculated so the image ratio will not change
    // 3. otherwise we will use the height ratio for the image
    // as a result, only one of the dimmensions will be from the fixed ones
    $ratio1 = $old_x / $new_w;
    $ratio2 = $old_y / $new_h;
    if ($ratio1 > $ratio2) {
        $thumb_w = $new_w;
        $thumb_h = $old_y / $ratio1;
    } else {
        $thumb_h = $new_h;
        $thumb_w = $old_x / $ratio2;
    }
    // we create a new image with the new dimmensions
    $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
    // resize the big image to the new created one
    imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
    // output the created image to the file. Now we will have the thumbnail into the file named by $filename
    if (!strcmp("png", $ext)) {
        imagepng($dst_img, $filename);
    } else {
        imagejpeg($dst_img, $filename);
    }
    //destroys source and destination images.
    imagedestroy($dst_img);
    imagedestroy($src_img);
}
Example #21
0
function thumb_creator($source, $filename, $uploaddir)
{
    $extension = "." . getExtension($filename);
    $new_images = "thumb_" . date(YmdHis) . $extension;
    $tmp_img = $source['tmp_name'];
    $src_size = getimagesize($tmp_img);
    $width = 150;
    $height = round($width * $src_size[1] / $src_size[0]);
    if ($src_size['mime'] === 'image/jpeg') {
        $src = imagecreatefromjpeg($tmp_img);
    } else {
        if ($src_size['mime'] === 'image/jpg') {
            $src = imagecreatefromjpeg($tmp_img);
        } else {
            if ($src_size['mime'] === 'image/png') {
                $src = imagecreatefrompng($tmp_img);
            } else {
                if ($src_size['mime'] === 'image/gif') {
                    $src = imagecreatefromgif($tmp_img);
                }
            }
        }
    }
    $photoX = ImagesX($src);
    $photoY = ImagesY($src);
    $images_fin = ImageCreateTrueColor($width, $height);
    ImageCopyResampled($images_fin, $src, 0, 0, 0, 0, $width + 1, $height + 1, $photoX, $photoY);
    if ($src_size['mime'] === 'image/jpeg') {
        ImageJPEG($images_fin, $uploaddir . "/" . $new_images);
    } else {
        if ($src_size['mime'] === 'image/jpg') {
            ImageJPEG($images_fin, $uploaddir . "/" . $new_images);
        } else {
            if ($src_size['mime'] === 'image/png') {
                ImagePNG($images_fin, $uploaddir . "/" . $new_images);
            } else {
                if ($src_size['mime'] === 'image/gif') {
                    ImageGIF($images_fin, $uploaddir . "/" . $new_images);
                }
            }
        }
    }
}
Example #22
0
 public function url($urls, $albumID = 0)
 {
     # Check dependencies
     self::dependencies(isset($urls));
     $error = false;
     # Parse URLs
     $urls = str_replace(' ', '%20', $urls);
     $urls = explode(',', $urls);
     foreach ($urls as &$url) {
         # Validate photo type and extension even when $this->photo (=> $photo->add) will do the same.
         # This prevents us from downloading invalid photos.
         # Verify extension
         $extension = getExtension($url);
         if (!in_array(strtolower($extension), Photo::$validExtensions, true)) {
             $error = true;
             continue;
         }
         # Verify image
         $type = @exif_imagetype($url);
         if (!in_array($type, Photo::$validTypes, true)) {
             $error = true;
             continue;
         }
         $pathinfo = pathinfo($url);
         $filename = $pathinfo['filename'] . '.' . $pathinfo['extension'];
         $tmp_name = LYCHEE_DATA . $filename;
         if (@copy($url, $tmp_name) === false) {
             $error = true;
             continue;
         }
         # Import photo
         if (!$this->photo($tmp_name, $albumID)) {
             $error = true;
             continue;
         }
     }
     if ($error === false) {
         return true;
     }
     return false;
 }
function check_image($path, $filename){
	$sExtension = getExtension($filename);
	//Check image file type extensiton
	$checkImg = true;
	switch($sExtension){
		case "gif":
			$checkImg = @imagecreatefromgif($path . $filename);
			break;
		case $sExtension == "jpg" || $sExtension == "jpe" || $sExtension == "jpeg":
			$checkImg = @imagecreatefromjpeg($path . $filename);
			break;
		case "png":
			$checkImg = @imagecreatefrompng($path . $filename);
			break;
	}
	if(!$checkImg){
		delete_file($path, $filename);
		return 0;
	}
	return 1;
}
Example #24
0
function compress_js_output($input, $fileflag = false, $level = 9)
{
    if ($fileflag) {
        if (in_array(getExtension($input), array('.js'))) {
            $all = compress_file(PATH_ . $input, xConfig::get('GLOBAL', 'output_js_compress'));
        } else {
            $all = gzencode($all, $level);
        }
    } elseif (xConfig::get('GLOBAL', 'output_js_compress')) {
        $all = gzencode($input, $level);
    } else {
        echo $input;
        return;
    }
    if (!IE() && xConfig::get('GLOBAL', 'output_js_compress')) {
        if (@$_SERVER["HTTP_ACCEPT_ENCODING"] && FALSE !== strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip')) {
            header('Content-Encoding: gzip');
            header('Content-Length: ' . strlen($all));
        }
    }
    echo $all;
}
function getExtension($extension)
{
    $result = array();
    $keys = array_keys($extension);
    if ($extension["_t"] == "LanguageBuilder") {
        $languageAttr = $extension["LanguageAttributes"];
        $ks = array_keys($languageAttr);
        foreach ($ks as $k) {
            array_push($result, $languageAttr[$k]);
        }
    } else {
        foreach ($keys as $key) {
            if (is_array($extension[$key])) {
                if (array_key_exists("_t", $extension[$key])) {
                    return getExtension($extension[$key]);
                }
            }
        }
        array_push($result, $extension);
    }
    return $result;
}
 public function addVehicle($numplate, $make, $model, $engine, $mileage, $year, $color, $bodytype, $doors, $fueltype, $geartype, $price)
 {
     $numplateEx = strtoupper($numplate);
     $this->db->query("INSERT INTO `vehicles` (`numplate`, `make`, `model`, `engine`, `mileage`, `year`, `color`, `bodytype`, `doors`, `fueltype`, `geartype`, `price`) VALUES ('" . $numplateEx . "', '" . $make . "', '" . $model . "', '" . $engine . "', '" . $mileage . "', '" . $year . "', '" . $color . "', '" . $bodytype . "', '" . $doors . "', '" . $fueltype . "', '" . $geartype . "', '" . $price . "')");
     if (!is_dir("images/{$numplateEx}")) {
         mkdir("images/{$numplateEx}");
     }
     $upload_dir = "images/{$numplateEx}/";
     foreach ($_FILES['inp_image']['name'] as $name => $value) {
         $filename = stripslashes($_FILES['inp_image']['name'][$name]);
         $extension = getExtension($filename);
         $extension = strtolower($extension);
         if ($extension != "jpg" && $extension != "jpeg" && $extension != "png" && $extension != "gif") {
         } else {
             $size = filesize($_FILES['inp_image']['tmp_name'][$name]);
         }
         $image_name = $filename . '.' . $extension;
         $newname = $upload_dir . $image_name;
         $copied = copy($_FILES['inp_image']['tmp_name'][$name], $newname);
         if (!$copied) {
         }
     }
 }
Example #27
0
 /**
  * List browse on the server, so we can insert them in the file input.
  *
  * @param $path
  * @param  Silex\Application $app
  * @param  Request           $request
  * @return mixed
  */
 public function browse($path, Silex\Application $app, Request $request)
 {
     $files = array();
     $folders = array();
     // $key is linked to the fieldname of the original field, so we can
     // Set the selected value in the proper field
     $key = $app['request']->get('key');
     $basefolder = $app['resources']->getPath('files');
     $path = stripTrailingSlash(str_replace("..", "", $path));
     if ($path == 'files') {
         $path = '';
     }
     $currentfolder = realpath($basefolder . $path);
     $ignored = array(".", "..", ".DS_Store", ".gitignore", ".htaccess");
     // Get the pathsegments, so we can show the path..
     $pathsegments = array();
     $cumulative = "";
     if (!empty($path)) {
         foreach (explode("/", $path) as $segment) {
             $cumulative .= $segment . "/";
             $pathsegments[$cumulative] = $segment;
         }
     }
     if (file_exists($currentfolder)) {
         $d = dir($currentfolder);
         while (false !== ($entry = $d->read())) {
             if (in_array($entry, $ignored)) {
                 continue;
             }
             $fullfilename = $currentfolder . "/" . $entry;
             if (is_file($fullfilename)) {
                 $relativepath = str_replace("files/", "", $path . "/" . $entry);
                 $files[$entry] = array('path' => $path, 'filename' => $entry, 'newpath' => $path . "/" . $entry, 'relativepath' => $relativepath, 'writable' => is_writable($fullfilename), 'readable' => is_readable($fullfilename), 'type' => strtolower(getExtension($entry)), 'filesize' => formatFilesize(filesize($fullfilename)), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)), 'permissions' => \util::full_permissions($fullfilename));
                 if (in_array(strtolower(getExtension($entry)), array('gif', 'jpg', 'png', 'jpeg'))) {
                     $size = getimagesize($fullfilename);
                     $files[$entry]['imagesize'] = sprintf("%s × %s", $size[0], $size[1]);
                 }
             }
             if (is_dir($fullfilename)) {
                 $folders[$entry] = array('path' => $path, 'foldername' => $entry, 'newpath' => $path . "/" . $entry, 'writable' => is_writable($fullfilename), 'modified' => date("Y/m/d H:i:s", filemtime($fullfilename)));
             }
         }
         $d->close();
     } else {
         $app['session']->getFlashBag()->set('error', __("Folder '%s' could not be found, or is not readable.", array('%s' => $path)));
     }
     $app['twig']->addGlobal('title', __("Files in %s", array('%s' => $path)));
     // Make sure the files and folders are sorted properly.
     ksort($files);
     ksort($folders);
     return $app['render']->render('files_async.twig', array('path' => $path, 'files' => $files, 'folders' => $folders, 'pathsegments' => $pathsegments, 'key' => $key));
 }
Example #28
0
 /**
  * Handle an transload.
  *
  * @param string $url
  * @param mixed $tags
  * @param string $source
  * @param string $replace
  * @return bool Returns TRUE on transload successful.
  */
 private function try_transload($url, $tags, $source, $replace = '')
 {
     global $page, $config, $user;
     $ok = true;
     // Checks if user is admin > check if you want locked.
     if ($user->can("edit_image_lock") && !empty($_GET['locked'])) {
         $locked = bool_escape($_GET['locked']);
     }
     // Checks if url contains rating, also checks if the rating extension is enabled.
     if ($config->get_string("transload_engine", "none") != "none" && class_exists("Ratings") && !empty($_GET['rating'])) {
         // Rating event will validate that this is s/q/e/u
         $rating = strtolower($_GET['rating']);
         $rating = $rating[0];
     } else {
         $rating = "";
     }
     $tmp_filename = tempnam(ini_get('upload_tmp_dir'), "shimmie_transload");
     // transload() returns Array or Bool, depending on the transload_engine.
     $headers = transload($url, $tmp_filename);
     $s_filename = is_array($headers) ? findHeader($headers, 'Content-Disposition') : null;
     $h_filename = $s_filename ? preg_replace('/^.*filename="([^ ]+)"/i', '$1', $s_filename) : null;
     $filename = $h_filename ?: basename($url);
     if (!$headers) {
         $this->theme->display_upload_error($page, "Error with " . html_escape($filename), "Error reading from " . html_escape($url));
         return false;
     }
     if (filesize($tmp_filename) == 0) {
         $this->theme->display_upload_error($page, "Error with " . html_escape($filename), "No data found -- perhaps the site has hotlink protection?");
         $ok = false;
     } else {
         $pathinfo = pathinfo($url);
         $metadata = array();
         $metadata['filename'] = $filename;
         $metadata['extension'] = getExtension(findHeader($headers, 'Content-Type')) ?: $pathinfo['extension'];
         $metadata['tags'] = $tags;
         $metadata['source'] = $url == $source && !$config->get_bool('upload_tlsource') ? "" : $source;
         /* check for locked > adds to metadata if it has */
         if (!empty($locked)) {
             $metadata['locked'] = $locked ? "on" : "";
         }
         /* check for rating > adds to metadata if it has */
         if (!empty($rating)) {
             $metadata['rating'] = $rating;
         }
         /* check if we have been given an image ID to replace */
         if (!empty($replace)) {
             $metadata['replace'] = $replace;
         }
         $event = new DataUploadEvent($tmp_filename, $metadata);
         try {
             send_event($event);
         } catch (UploadException $ex) {
             $this->theme->display_upload_error($page, "Error with " . html_escape($url), $ex->getMessage());
             $ok = false;
         }
     }
     unlink($tmp_filename);
     return $ok;
 }
Example #29
0
 public function getArchive()
 {
     # Functions starts a download of a photo
     # Returns the following:
     # (boolean + output) true = Success
     # (boolean) false = Failure
     # Check dependencies
     self::dependencies(isset($this->database, $this->photoIDs));
     # Call plugins
     $this->plugins(__METHOD__, 0, func_get_args());
     # Get photo
     $query = Database::prepare($this->database, "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
     $photos = $this->database->query($query);
     $photo = $photos->fetch_object();
     # Error in database query
     if (!$photos) {
         Log::error($this->database, __METHOD__, __LINE__, $this->database->error);
         return false;
     }
     # Photo not found
     if ($photo === null) {
         Log::error($this->database, __METHOD__, __LINE__, 'Album not found. Cannot start download.');
         return false;
     }
     # Get extension
     $extension = getExtension($photo->url);
     if ($extension === false) {
         Log::error($this->database, __METHOD__, __LINE__, 'Invalid photo extension');
         return false;
     }
     # Illicit chars
     $badChars = array_merge(array_map('chr', range(0, 31)), array("<", ">", ":", '"', "/", "\\", "|", "?", "*"));
     # Parse title
     if ($photo->title == '') {
         $photo->title = 'Untitled';
     }
     # Escape title
     $photo->title = str_replace($badChars, '', $photo->title);
     # Set headers
     header("Content-Type: application/octet-stream");
     header("Content-Disposition: attachment; filename=\"" . $photo->title . $extension . "\"");
     header("Content-Length: " . filesize(LYCHEE_UPLOADS_BIG . $photo->url));
     # Send file
     readfile(LYCHEE_UPLOADS_BIG . $photo->url);
     # Call plugins
     $this->plugins(__METHOD__, 1, func_get_args());
     return true;
 }
Example #30
0
/**
 *  setup download headers and return ready flag to exportSettings
 *  @param  $exportFile     Name of the new file to be created
 *  @param  $exportType     Export type
 *  @param  $target         target window where the download would happen (_self/_blank/_parent/_top/window name)
 *  @return     An array containing exportSettings and ready flag
 */
function setupDownload($exportFile, $exportType, $target = "_self")
{
    $exportType = strtolower($exportType);
    // get mime type list parsing MIMETYPES constant declared in Export Resource PHP file
    $mimeList = bang(@MIMETYPES);
    // get the associated extension for the export type
    $ext = getExtension($exportType);
    // set content-type header
    header('Content-type:' . $mimeList[$exportType]);
    // set content-disposition header
    // when target is _self the type is 'attachment'
    // when target is other than self type is 'inline'
    // NOTE : you can comment this line in order to replace present window (_self) content with the image/PDF
    header('Content-Disposition: ' . (strtolower($target == "_self") ? "attachment" : "inline") . '; filename="' . $exportFile . '.' . $ext . '"');
    // return exportSetting array. Ready should be set to download
    return array('ready' => 'download', "type" => $exportType);
}