/**
  * Establish and set the dataFormat
  * if not set directly.
  *
  * @throws \LogicException
  */
 protected function completeDataFormat()
 {
     $dataFormatIsSetDirectly = isset($this->dataFormat);
     $fileHasExtension = !empty($this->file->getExtension());
     if (!$dataFormatIsSetDirectly && $fileHasExtension) {
         $this->dataFormat = strtolower($this->file->getExtension());
     } elseif (!$dataFormatIsSetDirectly) {
         throw new \LogicException('File has no extension and format has not been set directly. ' . 'File format cannot be established.');
     }
 }
Example #2
0
 public function __get($var)
 {
     switch ($var) {
         case "name":
             return $this->name;
             break;
         case "size":
             return filesize($this->fullpath);
             break;
         case "fullPath":
             return $this->folder->slashTerm($this->folder->path) . $this->name;
         case "extension":
             return File::getExtension($this->name);
             break;
         case "lastAccess":
             return filemtime($this->fullPath);
             break;
         case "lastChange":
             return filemtime($this->fullPath);
             break;
         case "folder":
             return $this->folder;
             break;
         default:
             return false;
     }
     return false;
 }
 public function index($file, $parameters = array())
 {
     $file = Path::assemble(BASE_PATH, $file);
     if (File::exists($file)) {
         $fileSize = File::getSize(BASE_PATH . $file);
         switch ($parameters) {
             case "file_ext":
                 return File::getExtension($file);
                 break;
             case "file_size":
                 return File::getSize(BASE_PATH . $file);
                 break;
             case "file_size_kilobytes":
                 return number_format($fileSize / 1024);
                 break;
             case "file_size_human":
                 return self::format_bytes_human($fileSize);
                 break;
             default:
                 return File::getExtension($file);
         }
     } else {
         Log::error("File does not exist or is not readable", "fileinfo_modifier", $file);
     }
 }
Example #4
0
 public static function compileDir($dir, $destFile)
 {
     $dh = opendir($dir);
     if (!$dh) {
         throw new Exception('Unknown dir: ' . $dir);
     }
     while ($file = readdir($dh)) {
         if ($file[0] == '.') {
             continue;
         }
         $absfile = Dir::normalize($dir) . $file;
         if (is_file($absfile) && File::getExtension($file) == 'js') {
             File::append($destFile, "//FILE: {$file}" . chr(10));
             if (filesize($absfile) > 200000) {
                 File::append($destFile, file_get_contents($absfile));
             } else {
                 File::append($destFile, self::minify($absfile));
             }
             File::append($destFile, chr(10) . chr(10));
         } else {
             if (is_dir($absfile)) {
                 self::compileDir($absfile, $destFile);
             }
         }
     }
     closedir($dh);
 }
Example #5
0
 public function index()
 {
     $file = $this->fetchParam("file", null, null, null, false);
     $fileSize = File::getSize(BASE_PATH . $file);
     $file_info = array("file_ext" => File::getExtension(BASE_PATH . $file), "file_size" => $fileSize, "file_size_kilobytes" => number_format($fileSize / 1024), "file_size_human" => self::format_bytes_human($fileSize));
     return $file_info;
 }
Example #6
0
 function __construct($fileName = null)
 {
     if ($fileName) {
         $this->fileName = $fileName;
         $this->extension = strToLower(File::getExtension($fileName));
         $this->load();
     }
 }
Example #7
0
 public static function download($path, $content_type = null, $new_name = null)
 {
     $file = new File($path);
     header('Content-Type: ' . $content_type ? $content_type : $file->getMime());
     header('Content-Disposition: attachment; filename="' . ($new_name ? $new_name : uniqid() . '.' . $file->getExtension()) . '"');
     readfile($path);
     exit;
 }
Example #8
0
 /**
  * Méthode de chargement de décodage d'un fichier au format spécifique
  * @param String $pFile
  * @return Array
  */
 static function import($pFile)
 {
     switch (strtolower(File::getExtension($pFile))) {
         case "xlsx":
             return self::import_xlsx($pFile);
             break;
     }
     return false;
 }
Example #9
0
 function testExtensionFullAndLast()
 {
     $f_txt = new File("/" . FRAMEWORK_CORE_PATH . "tests/io/test_dir/content_dir/test_file.txt");
     $this->assertEqual("txt", $f_txt->getFullExtension());
     $this->assertEqual("txt", $f_txt->getExtension());
     $f_css = new File("/" . FRAMEWORK_CORE_PATH . "tests/io/test_dir/content_dir/css_test.css");
     $this->assertEqual("css", $f_css->getFullExtension());
     $this->assertEqual("css", $f_css->getExtension());
     $f_plug_txt = new File("/" . FRAMEWORK_CORE_PATH . "tests/io/test_dir/content_dir/ext_test.plug.txt");
     $this->assertEqual("plug.txt", $f_plug_txt->getFullExtension());
     $this->assertEqual("txt", $f_plug_txt->getExtension());
 }
 /**
  * Executes the widget.
  */
 public function run()
 {
     if ($this->item->href != '') {
         $this->render('libraryLink', array('item' => $this->item, 'category' => $this->category, 'editable' => $this->editable));
     } else {
         $files = File::getFilesOfObject($this->item);
         $file = array_pop($files);
         // If there is no file attached, deliver a dummy object. That's better than completely breaking the rendering.
         if (!is_object($file)) {
             $file = new File();
         }
         $mime = HHtml::getMimeIconClassByExtension($file->getExtension());
         $this->render('libraryDocument', array('file' => $file, 'mime' => $mime, 'item' => $this->item, 'category' => $this->category, 'editable' => $this->editable));
     }
 }
 public function control()
 {
     $this->redirectToSternIndiaEndPoint();
     $config = Config::getInstance();
     if (isset($_POST['upload']) && $_POST['upload'] == 'Upload') {
         $target_dir = new FileSystem('upload/');
         $file = new File('foo', $target_dir);
         $name = date('D_d_m_Y_H_m_s_');
         $name = $name . $file->getName();
         $file->setName($name);
         $config = Config::getInstance();
         $file->addValidations(array(new Mimetype($config->getMimeTypes()), new Size('5M')));
         $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5());
         try {
             // /Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data);
             $file->upload();
             //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data);
         } catch (Exception $e) {
             $errors = $file->getErrors();
         }
         $csvReader = new CSVReader();
         $destinationFile = $target_dir->directory . $file->getNameWithExtension();
         $data = $csvReader->parse_file($destinationFile);
         //$country= DAOFactory::getDAO('LocationDAO');
         foreach ($data as $loc_arr) {
             Utils::processLocation($loc_arr);
         }
         //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__);
         $target_dir = "uploads/";
         $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
         $uploadOk = 1;
         $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
         // Check if image file is a actual image or fake image
         if (isset($_POST["submit"])) {
             $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
             if ($check !== false) {
                 echo "File is an image - " . $check["mime"] . ".";
                 $uploadOk = 1;
             } else {
                 echo "File is not an image.";
                 $uploadOk = 0;
             }
         }
     }
     return $this->generateView();
 }
Example #12
0
 public function index($file, $parameters = array())
 {
     switch ($parameters) {
         case "file_ext":
             return File::getExtension();
             break;
         case "file_size":
             return File::getSize(BASE_PATH . $file);
             break;
         case "file_size_kilobytes":
             return number_format($fileSize / 1024);
             break;
         case "file_size_human":
             return self::format_bytes_human($fileSize);
             break;
         default:
             return File::getExtension();
     }
 }
Example #13
0
 public function createResource($file)
 {
     $this->type = File::getExtension($file);
     switch ($this->type) {
         case 'jpg':
         case 'jpeg':
             $this->resource = imagecreatefromjpeg($file);
             break;
         case 'gif':
             $this->resource = imagecreatefromgif($file);
             break;
         case 'png':
             $this->resource = imagecreatefrompng($file);
             break;
         case 'bmp':
             $this->resource = imagecreatefromwbmp($file);
             break;
     }
 }
Example #14
0
 /**
  * Make the text under the image to say what size preview
  *
  * @param $params Array parameters for thumbnail
  * @param $sizeLinkBigImagePreview HTML for the current size
  * @return string HTML output
  */
 private function getThumbPrevText($params, $sizeLinkBigImagePreview)
 {
     if ($sizeLinkBigImagePreview) {
         // Show a different message of preview is different format from original.
         $previewTypeDiffers = false;
         $origExt = $thumbExt = $this->displayImg->getExtension();
         if ($this->displayImg->getHandler()) {
             $origMime = $this->displayImg->getMimeType();
             $typeParams = $params;
             $this->displayImg->getHandler()->normaliseParams($this->displayImg, $typeParams);
             list($thumbExt, $thumbMime) = $this->displayImg->getHandler()->getThumbType($origExt, $origMime, $typeParams);
             if ($thumbMime !== $origMime) {
                 $previewTypeDiffers = true;
             }
         }
         if ($previewTypeDiffers) {
             return $this->getContext()->msg('show-big-image-preview-differ')->rawParams($sizeLinkBigImagePreview)->params(strtoupper($origExt))->params(strtoupper($thumbExt))->parse();
         } else {
             return $this->getContext()->msg('show-big-image-preview')->rawParams($sizeLinkBigImagePreview)->parse();
         }
     } else {
         return '';
     }
 }
 /**
  * Given a File object, create an array of its properties and values
  * ready to be transformed to JSON
  * 	
  * @param  Folder $folder
  * @return array
  */
 public function createFileJSON(File $file, $folder = null)
 {
     $isImage = $file instanceof Image;
     $w = $isImage ? self::IMAGE_WIDTH : self::ICON_SIZE;
     $h = $isImage ? self::IMAGE_HEIGHT : self::ICON_SIZE;
     $folder = $folder ?: $file->Parent();
     return array('id' => $file->ID, 'parentID' => $file->ParentID, 'title' => $file->Title, 'filename' => basename($file->Filename), 'path' => $file->Filename, 'filesize' => $file->getAbsoluteSize(), 'folderName' => $folder->Filename, 'type' => $isImage ? 'image' : 'file', 'extension' => $file->getExtension(), 'created' => $file->Created, 'updated' => $file->LastEdited, 'iconURL' => $file->getPreviewThumbnail($w, $h)->URL, 'canEdit' => $file->canEdit(), 'canCreate' => $file->canCreate(), 'canDelete' => $file->canDelete());
 }
Example #16
0
 /**
  * Filter-out "Tenp_file_" images from list of URLs to purge
  *
  * @param File $file image to purge
  * @param array $urls URLs to purge generated by MW core
  */
 static function onLocalFileExecuteUrls(File $file, array &$urls)
 {
     if (strpos($file->getName(), 'Temp_file_') === 0 && $file->getExtension() === '') {
         wfDebug(__METHOD__ . ": removed {$file->getName()} from the purger queue\n");
         $urls = [];
     }
     return true;
 }
Example #17
0
 public static function getByFileName($contentID)
 {
     $extension = File::getExtension($contentID);
     return self::getByExtension($extension);
 }
Example #18
0
 public static function getByFile(File $file)
 {
     return self::getByExtension($file->getExtension());
 }
Example #19
0
    protected function openShowImage()
    {
        global $wgImageLimits, $wgEnableUploads, $wgSend404Code;
        $this->loadFile();
        $out = $this->getContext()->getOutput();
        $user = $this->getContext()->getUser();
        $lang = $this->getContext()->getLanguage();
        $dirmark = $lang->getDirMarkEntity();
        $request = $this->getContext()->getRequest();
        $max = $this->getImageLimitsFromOption($user, 'imagesize');
        $maxWidth = $max[0];
        $maxHeight = $max[1];
        if ($this->displayImg->exists()) {
            # image
            $page = $request->getIntOrNull('page');
            if (is_null($page)) {
                $params = array();
                $page = 1;
            } else {
                $params = array('page' => $page);
            }
            $renderLang = $request->getVal('lang');
            if (!is_null($renderLang)) {
                $handler = $this->displayImg->getHandler();
                if ($handler && $handler->validateParam('lang', $renderLang)) {
                    $params['lang'] = $renderLang;
                } else {
                    $renderLang = null;
                }
            }
            $width_orig = $this->displayImg->getWidth($page);
            $width = $width_orig;
            $height_orig = $this->displayImg->getHeight($page);
            $height = $height_orig;
            $filename = wfEscapeWikiText($this->displayImg->getName());
            $linktext = $filename;
            wfRunHooks('ImageOpenShowImageInlineBefore', array(&$this, &$out));
            if ($this->displayImg->allowInlineDisplay()) {
                # image
                # "Download high res version" link below the image
                # $msgsize = wfMessage( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime )->escaped();
                # We'll show a thumbnail of this image
                if ($width > $maxWidth || $height > $maxHeight) {
                    # Calculate the thumbnail size.
                    # First case, the limiting factor is the width, not the height.
                    if ($width / $height >= $maxWidth / $maxHeight) {
                        // FIXME: Possible division by 0. bug 36911
                        $height = round($height * $maxWidth / $width);
                        // FIXME: Possible division by 0. bug 36911
                        $width = $maxWidth;
                        # Note that $height <= $maxHeight now.
                    } else {
                        $newwidth = floor($width * $maxHeight / $height);
                        // FIXME: Possible division by 0. bug 36911
                        $height = round($height * $newwidth / $width);
                        // FIXME: Possible division by 0. bug 36911
                        $width = $newwidth;
                        # Note that $height <= $maxHeight now, but might not be identical
                        # because of rounding.
                    }
                    $linktext = wfMessage('show-big-image')->escaped();
                    if ($this->displayImg->getRepo()->canTransformVia404()) {
                        $thumbSizes = $wgImageLimits;
                        // Also include the full sized resolution in the list, so
                        // that users know they can get it. This will link to the
                        // original file asset if mustRender() === false. In the case
                        // that we mustRender, some users have indicated that they would
                        // find it useful to have the full size image in the rendered
                        // image format.
                        $thumbSizes[] = array($width_orig, $height_orig);
                    } else {
                        # Creating thumb links triggers thumbnail generation.
                        # Just generate the thumb for the current users prefs.
                        $thumbSizes = array($this->getImageLimitsFromOption($user, 'thumbsize'));
                        if (!$this->displayImg->mustRender()) {
                            // We can safely include a link to the "full-size" preview,
                            // without actually rendering.
                            $thumbSizes[] = array($width_orig, $height_orig);
                        }
                    }
                    # Generate thumbnails or thumbnail links as needed...
                    $otherSizes = array();
                    foreach ($thumbSizes as $size) {
                        // We include a thumbnail size in the list, if it is
                        // less than or equal to the original size of the image
                        // asset ($width_orig/$height_orig). We also exclude
                        // the current thumbnail's size ($width/$height)
                        // since that is added to the message separately, so
                        // it can be denoted as the current size being shown.
                        if ($size[0] <= $width_orig && $size[1] <= $height_orig && $size[0] != $width && $size[1] != $height) {
                            $sizeLink = $this->makeSizeLink($params, $size[0], $size[1]);
                            if ($sizeLink) {
                                $otherSizes[] = $sizeLink;
                            }
                        }
                    }
                    $otherSizes = array_unique($otherSizes);
                    $msgsmall = '';
                    $sizeLinkBigImagePreview = $this->makeSizeLink($params, $width, $height);
                    if ($sizeLinkBigImagePreview) {
                        $msgsmall .= wfMessage('show-big-image-preview')->rawParams($sizeLinkBigImagePreview)->parse();
                    }
                    if (count($otherSizes)) {
                        $msgsmall .= ' ' . Html::rawElement('span', array('class' => 'mw-filepage-other-resolutions'), wfMessage('show-big-image-other')->rawParams($lang->pipeList($otherSizes))->params(count($otherSizes))->parse());
                    }
                } elseif ($width == 0 && $height == 0) {
                    # Some sort of audio file that doesn't have dimensions
                    # Don't output a no hi res message for such a file
                    $msgsmall = '';
                } elseif ($this->displayImg->isVectorized()) {
                    # For vectorized images, full size is just the frame size
                    $msgsmall = '';
                } else {
                    # Image is small enough to show full size on image page
                    $msgsmall = wfMessage('file-nohires')->parse();
                }
                $params['width'] = $width;
                $params['height'] = $height;
                $thumbnail = $this->displayImg->transform($params);
                Linker::processResponsiveImages($this->displayImg, $thumbnail, $params);
                $anchorclose = Html::rawElement('div', array('class' => 'mw-filepage-resolutioninfo'), $msgsmall);
                $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
                if ($isMulti) {
                    $out->addModules('mediawiki.page.image.pagination');
                    $out->addHTML('<table class="multipageimage"><tr><td>');
                }
                if ($thumbnail) {
                    $options = array('alt' => $this->displayImg->getTitle()->getPrefixedText(), 'file-link' => true);
                    $out->addHTML('<div class="fullImageLink" id="file">' . $thumbnail->toHtml($options) . $anchorclose . "</div>\n");
                }
                if ($isMulti) {
                    $count = $this->displayImg->pageCount();
                    if ($page > 1) {
                        $label = $out->parse(wfMessage('imgmultipageprev')->text(), false);
                        // on the client side, this link is generated in ajaxifyPageNavigation()
                        // in the mediawiki.page.image.pagination module
                        $link = Linker::linkKnown($this->getTitle(), $label, array(), array('page' => $page - 1));
                        $thumb1 = Linker::makeThumbLinkObj($this->getTitle(), $this->displayImg, $link, $label, 'none', array('page' => $page - 1));
                    } else {
                        $thumb1 = '';
                    }
                    if ($page < $count) {
                        $label = wfMessage('imgmultipagenext')->text();
                        $link = Linker::linkKnown($this->getTitle(), $label, array(), array('page' => $page + 1));
                        $thumb2 = Linker::makeThumbLinkObj($this->getTitle(), $this->displayImg, $link, $label, 'none', array('page' => $page + 1));
                    } else {
                        $thumb2 = '';
                    }
                    global $wgScript;
                    $formParams = array('name' => 'pageselector', 'action' => $wgScript);
                    $options = array();
                    for ($i = 1; $i <= $count; $i++) {
                        $options[] = Xml::option($lang->formatNum($i), $i, $i == $page);
                    }
                    $select = Xml::tags('select', array('id' => 'pageselector', 'name' => 'page'), implode("\n", $options));
                    $out->addHTML('</td><td><div class="multipageimagenavbox">' . Xml::openElement('form', $formParams) . Html::hidden('title', $this->getTitle()->getPrefixedDBkey()) . wfMessage('imgmultigoto')->rawParams($select)->parse() . Xml::submitButton(wfMessage('imgmultigo')->text()) . Xml::closeElement('form') . "<hr />{$thumb1}\n{$thumb2}<br style=\"clear: both\" /></div></td></tr></table>");
                }
            } elseif ($this->displayImg->isSafeFile()) {
                # if direct link is allowed but it's not a renderable image, show an icon.
                $icon = $this->displayImg->iconThumb();
                $out->addHTML('<div class="fullImageLink" id="file">' . $icon->toHtml(array('file-link' => true)) . "</div>\n");
            }
            $longDesc = wfMessage('parentheses', $this->displayImg->getLongDesc())->text();
            $medialink = "[[Media:{$filename}|{$linktext}]]";
            if (!$this->displayImg->isSafeFile()) {
                $warning = wfMessage('mediawarning')->plain();
                // dirmark is needed here to separate the file name, which
                // most likely ends in Latin characters, from the description,
                // which may begin with the file type. In RTL environment
                // this will get messy.
                // The dirmark, however, must not be immediately adjacent
                // to the filename, because it can get copied with it.
                // See bug 25277.
                $out->addWikiText(<<<EOT
<div class="fullMedia"><span class="dangerousLink">{$medialink}</span> {$dirmark}<span class="fileInfo">{$longDesc}</span></div>
<div class="mediaWarning">{$warning}</div>
EOT
);
            } else {
                $out->addWikiText(<<<EOT
<div class="fullMedia">{$medialink} {$dirmark}<span class="fileInfo">{$longDesc}</span>
</div>
EOT
);
            }
            $renderLangOptions = $this->displayImg->getAvailableLanguages();
            if (count($renderLangOptions) >= 1) {
                $currentLanguage = $renderLang;
                $defaultLang = $this->displayImg->getDefaultRenderLanguage();
                if (is_null($currentLanguage)) {
                    $currentLanguage = $defaultLang;
                }
                $out->addHtml($this->doRenderLangOpt($renderLangOptions, $currentLanguage, $defaultLang));
            }
            // Add cannot animate thumbnail warning
            if (!$this->displayImg->canAnimateThumbIfAppropriate()) {
                // Include the extension so wiki admins can
                // customize it on a per file-type basis
                // (aka say things like use format X instead).
                // additionally have a specific message for
                // file-no-thumb-animation-gif
                $ext = $this->displayImg->getExtension();
                $noAnimMesg = wfMessageFallback('file-no-thumb-animation-' . $ext, 'file-no-thumb-animation')->plain();
                $out->addWikiText(<<<EOT
<div class="mw-noanimatethumb">{$noAnimMesg}</div>
EOT
);
            }
            if (!$this->displayImg->isLocal()) {
                $this->printSharedImageText();
            }
        } else {
            # Image does not exist
            if (!$this->getID()) {
                # No article exists either
                # Show deletion log to be consistent with normal articles
                LogEventsList::showLogExtract($out, array('delete', 'move'), $this->getTitle()->getPrefixedText(), '', array('lim' => 10, 'conds' => array("log_action != 'revision'"), 'showIfEmpty' => false, 'msgKey' => array('moveddeleted-notice')));
            }
            if ($wgEnableUploads && $user->isAllowed('upload')) {
                // Only show an upload link if the user can upload
                $uploadTitle = SpecialPage::getTitleFor('Upload');
                $nofile = array('filepage-nofile-link', $uploadTitle->getFullURL(array('wpDestFile' => $this->mPage->getFile()->getName())));
            } else {
                $nofile = 'filepage-nofile';
            }
            // Note, if there is an image description page, but
            // no image, then this setRobotPolicy is overridden
            // by Article::View().
            $out->setRobotPolicy('noindex,nofollow');
            $out->wrapWikiMsg("<div id='mw-imagepage-nofile' class='plainlinks'>\n\$1\n</div>", $nofile);
            if (!$this->getID() && $wgSend404Code) {
                // If there is no image, no shared image, and no description page,
                // output a 404, to be consistent with articles.
                $request->response()->header('HTTP/1.1 404 Not Found');
            }
        }
        $out->setFileVersion($this->displayImg);
    }
Example #20
0
 /**
  * Attach a file to a post
  *
  * @param int $post_id		Post's id
  * @param string $filepath	Path of the tmp file
  * @param string $thumbpath	Path of the thumb (optional)
  */
 public function attachFile($post_id, $filepath, $name, $thumbpath = null, $mobilepath = null)
 {
     $ext = strtolower(File::getExtension($filepath));
     // In the DB
     $file_id = DB::createQuery('attachments')->set(array('post_id' => $post_id, 'name' => $name, 'ext' => $ext))->insert();
     // File, and optionally thumb
     $newfilepath = self::getAttachedFilePath($file_id, $ext);
     if (!File::exists(File::getPath($newfilepath))) {
         File::makeDir(File::getPath($newfilepath), 0777, true);
     }
     File::rename($filepath, $newfilepath);
     if (isset($thumbpath)) {
         File::rename($thumbpath, self::getAttachedFilePath($file_id, 'jpg', 'thumb'));
     }
     if (isset($mobilepath)) {
         File::rename($mobilepath, self::getAttachedFilePath($file_id, 'jpg', 'mobile'));
     }
 }
Example #21
0
    public function index()
    {

        /*
        |--------------------------------------------------------------------------
        | Check for image
        |--------------------------------------------------------------------------
        |
        | Transform just needs the path to an image to get started. If it exists,
        | the fun begins.
        |
        | The way to do this changes depending on whether its an internal or
        | external file.
        |
        */

        $image_src = $this->fetchParam('src', null, false, false, false);

        // External URL
        if ($is_external = URL::isExternalUrl($image_src)) {

            $image_path = $image_src;

            // Check if file is an image before doing anything.
            // @TODO: Maybe check that the file exists.
            $img_info = pathinfo($image_src);
            $is_image = in_array($img_info['extension'], array('jpg', 'jpeg', 'png', 'gif'));

            if ( ! $is_image) {
                Log::error("Requested file is not an image: " . $image_path, "core", "Transform");

                return;
            }

        }

        // Internal URL
        else {

            // Set full system path
            $image_path = Path::standardize(Path::fromAsset($image_src));

            // Check if image exists before doing anything.
            if ( ! File::isImage($image_path)) {
                Log::error("Could not find requested image to transform: " . $image_path, "core", "Transform");

                return;
            }

        }


        /*
        |--------------------------------------------------------------------------
        | Resizing and cropping options
        |--------------------------------------------------------------------------
        |
        | The first transformations we want to run is for size to reduce the
        | memory usage for future effects.
        |
        */

        $width  = $this->fetchParam('width', null, 'is_numeric');
        $height = $this->fetchParam('height', null, 'is_numeric');

        // resize specific
        $ratio  = $this->fetchParam('ratio', true, false, true);
        $upsize = $this->fetchParam('upsize', true, false, true);

        // crop specific
        $pos_x  = $this->fetchParam('pos_x', 0, 'is_numeric');
        $pos_y  = $this->fetchParam('pos_y', 0, 'is_numeric');

        $quality = $this->fetchParam('quality', '75', 'is_numeric');


        /*
        |--------------------------------------------------------------------------
        | Action
        |--------------------------------------------------------------------------
        |
        | Available actions: resize, crop, and guess.
        |
        | "Guess" will find the best fitting aspect ratio of your given width and
        | height on the current image automatically, cut it out and resize it to
        | the given dimension.
        |
        */

        $action = $this->fetchParam('action', 'resize');


        /*
        |--------------------------------------------------------------------------
        | Extra bits
        |--------------------------------------------------------------------------
        |
        | Delicious and probably rarely used options.
        |
        */

        $angle     = $this->fetchParam('rotate', false);
        $flip_side = $this->fetchParam('flip' , false);
        $blur      = $this->fetchParam('blur', false, 'is_numeric');
        $pixelate  = $this->fetchParam('pixelate', false, 'is_numeric');
        $greyscale = $this->fetchParam(array('greyscale', 'grayscale'), false, false, true);
        $watermark = $this->fetchParam('watermark', false, false, false, false);


        /*
        |--------------------------------------------------------------------------
        | Assemble filename and check for duplicate
        |--------------------------------------------------------------------------
        |
        | We need to make sure we don't already have this image created, so we
        | defer any action until we've processed the parameters, which create
        | a unique filename.
        |
        */

        // Late modified time of original image
        $last_modified = ($is_external) ? false : File::getLastModified($image_path);

        // Find .jpg, .png, etc
        $extension = File::getExtension($image_path);

        // Filename with the extension removed so we can append our unique filename flags
        $stripped_image_path = str_replace('.' . $extension, '', $image_path);

        // The possible filename flags
        $parameter_flags = array(
            'width'     => $width,
            'height'    => $height,
            'quality'   => $quality,
            'rotate'    => $angle,
            'flip'      => $flip_side,
            'pos_x'     => $pos_x,
            'pos_y'     => $pos_y,
            'blur'      => $blur,
            'pixelate'  => $pixelate,
            'greyscale' => $greyscale,
            'modified'  => $last_modified
        );

        // Start with a 1 character action flag
        $file_breadcrumbs = '-'.$action[0];

        foreach ($parameter_flags as $param => $value) {
            if ($value) {
                $flag = is_bool($value) ? '' : $value; // don't show boolean flags
                $file_breadcrumbs .= '-' . $param[0] . $flag;
            }
        }

        // Allow converting filetypes (jpg, png, gif)
        $extension = $this->fetchParam('type', $extension);

        // Allow saving in a different directory
        $destination = $this->fetchParam('destination', Config::get('transform_destination', false), false, false, false);


        if ($destination) {

            $destination = Path::tidy(BASE_PATH . '/' . $destination);

            // Method checks to see if folder exists before creating it
            Folder::make($destination);

            $stripped_image_path = Path::tidy($destination . '/' . basename($stripped_image_path));
        }

        // Reassembled filename with all flags filtered and delimited
        $new_image_path = $stripped_image_path . $file_breadcrumbs . '.' . $extension;

        // Check if we've already built this image before
        if (File::exists($new_image_path)) {
            return Path::toAsset($new_image_path);
        }

        /*
        |--------------------------------------------------------------------------
        | Create Image
        |--------------------------------------------------------------------------
        |
        | Transform just needs the path to an image to get started. The image is
        | created in memory so we can start manipulating it.
        |
        */

        $image = Image::make($image_path);


        /*
        |--------------------------------------------------------------------------
        | Perform Actions
        |--------------------------------------------------------------------------
        |
        | This is fresh transformation. Time to work the magic!
        |
        */

        if ($action === 'resize' && ($width || $height) ) {
            $image->resize($width, $height, $ratio, $upsize);
        }

        if ($action === 'crop' && $width && $height) {
            $image->crop($width, $height, $pos_x, $pos_y);
        }

        if ($action === 'smart') {
            $image->grab($width, $height);
        }

        $resize  = $this->fetchParam('resize', null);

        if ($resize) {
            $resize_options = Helper::explodeOptions($resize, true);

            $image->resize(
                array_get($resize_options, 'width'),
                array_get($resize_options, 'height'),
                array_get($resize_options, 'ratio', true),
                array_get($resize_options, 'upsize', true)
            );
        }

        $crop = $this->fetchParam('crop', null);

        if ($crop) {
            $crop_options = Helper::explodeOptions($crop, true);

            $image->crop(
                array_get($crop_options, 'width'),
                array_get($crop_options, 'height'),
                array_get($crop_options, 'x'),
                array_get($crop_options, 'y')
            );
        }

        if ($angle) {
            $image->rotate($angle);
        }

        if ($flip_side === 'h' || $flip_side === 'v') {
            $image->flip($flip_side);
        }

        if ($greyscale) {
            $image->greyscale();
        }

        if ($blur) {
            $image->blur($blur);
        }

        if ($pixelate) {
            $image->pixelate($pixelate);
        }

        // Positioning options via ordered pipe settings:
        // source|position|x offset|y offset
        if ($watermark) {
            $watermark_options = Helper::explodeOptions($watermark);

            $source = Path::tidy(BASE_PATH . '/' . array_get($watermark_options, 0, null));
            $anchor = array_get($watermark_options, 1, null);
            $pos_x  = array_get($watermark_options, 2, 0);
            $pos_y  = array_get($watermark_options, 3, 0);

            $image->insert($source, $pos_x, $pos_y, $anchor);
        }


        /*
        |--------------------------------------------------------------------------
        | Save
        |--------------------------------------------------------------------------
        |
        | Get out of dodge!
        |
        */

        try {
            $image->save($new_image_path, $quality);
        } catch(Exception $e) {
            Log::fatal('Could not write new images. Try checking your file permissions.', 'core', 'Transform');
            throw new Exception('Could not write new images. Try checking your file permissions.');
        }

        return File::cleanURL($new_image_path);
    }
 /**
  * writeViewData
  * @param File $objFile
  * @author Cornelius Hansjakob <*****@*****.**>
  * @version 1.0
  */
 private function writeViewData(File &$objFile)
 {
     $this->core->logger->debug('media->controllers->UploadController->writeViewData()');
     $this->view->assign('fileId', $objFile->getId());
     $this->view->assign('fileFileId', $objFile->getFileId());
     $this->view->assign('fileExtension', $objFile->getExtension());
     $this->view->assign('fileTitle', $objFile->getTitle());
     $this->view->assign('mimeType', $objFile->getMimeType());
     $this->view->assign('strDefaultDescription', 'Beschreibung hinzufügen...');
     // TODO : guiTexts
     $this->view->assign('languageId', 1);
     // TODO : language
 }
Example #23
0
$app->get('/_add-ons/(:segments+)', function($segments = array()) use ($app) {

    // reset any content service caching that's been done
    ContentService::resetCaches();

    // clean segments
    $segments = URL::sanitize($segments);
    $file_requested = implode($segments, '/');
    
    $bundle_folder  = APP_PATH . "/core/bundles/" . $segments[0];
    $file = APP_PATH . "/core/bundles/" . $file_requested;

    $file = realpath($file);
    
    // prevent bad access of files
    if (strpos($file_requested, '../') !== false || File::getExtension($file) === 'php') {
        $app->pass();
        return;
    }

    if (Folder::exists($bundle_folder) && File::exists($file)) {
        // determine mime type
        $mime = File::resolveMime($file);

        // set last modified header
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

        // if configured, set expires header
        if (Config::get('http_cache_expires', false)) {
            header("Expires: " . gmdate("D, d M Y H:i:s", strtotime('+' . Config::get('http_cache_expires', '30 minutes'))) . " GMT");
        }
Example #24
0
 /**
  * Récupère la liste des matchsettings en local à partir d'un chemin
  *
  * @param string $path -> Le chemin du dossier à lister
  * @return array
  */
 public static function getLocalMatchSettingList($directory, $currentPath)
 {
     $out = array();
     if (is_array($directory)) {
         if (!empty($directory['files'])) {
             $mapsDirectoryPath = self::getMapsDirectoryPath();
             foreach ($directory['files'] as $file => $values) {
                 if (in_array(File::getExtension($file), AdminServConfig::$MATCHSET_EXTENSION)) {
                     $matchsetData = self::getMatchSettingsData($mapsDirectoryPath . $currentPath . $file, array('maps'));
                     $matchsetNbmCount = 0;
                     if (isset($matchsetData['maps'])) {
                         $matchsetNbmCount = count($matchsetData['maps']);
                     }
                     $matchsetNbmTitle = $matchsetNbmCount > 1 ? Utils::t('maps') : Utils::t('map');
                     $out['lst'][$file]['Name'] = substr($file, 0, -4);
                     $out['lst'][$file]['FileName'] = $currentPath . $file;
                     $out['lst'][$file]['Nbm'] = $matchsetNbmCount . ' ' . $matchsetNbmTitle;
                     $out['lst'][$file]['Mtime'] = $values['mtime'];
                     $out['lst'][$file]['Recent'] = $values['recent'];
                 }
             }
         }
         // Nombre de matchsettings
         if (isset($out['lst']) && is_array($out['lst'])) {
             $out['nbm']['count'] = count($out['lst']);
             $out['nbm']['title'] = $out['nbm']['count'] > 1 ? Utils::t('matchsettings') : Utils::t('matchsetting');
         } else {
             $out['nbm']['count'] = 0;
             $out['nbm']['title'] = Utils::t('matchsetting');
         }
         if ($out['nbm']['count'] == 0) {
             $out['lst'] = Utils::t('No matchsetting');
         }
     } else {
         // Retour des erreurs de la méthode read
         $out = $directory;
     }
     return $out;
 }
 /**
  * writeViewData
  * @param File $objFile
  * @author Cornelius Hansjakob <*****@*****.**>
  * @version 1.0
  */
 private function writeViewData(File &$objFile)
 {
     $this->core->logger->debug('media->controllers->UploadController->writeViewData()');
     $this->view->assign('fileId', $objFile->getId());
     $this->view->assign('fileFileId', $objFile->getFileId());
     $this->view->assign('fileExtension', $objFile->getExtension());
     $this->view->assign('fileTitle', $objFile->getTitle());
     $this->view->assign('fileVersion', $objFile->getVersion());
     $this->view->assign('filePath', sprintf($this->core->sysConfig->media->paths->icon32, $objFile->getSegmentPath()));
     $this->view->assign('mimeType', $objFile->getMimeType());
     $this->view->assign('strDefaultDescription', $this->core->translate->_('Add_description_'));
     $this->view->assign('languageId', $this->intLanguageId);
 }
Example #26
0
 /**
  * Handles a single upload by given CUploadedFile and returns an array
  * of informations.
  *
  * The 'error' attribute of the array, indicates there was an error.
  *
  * Informations on error:
  *       - error: true
  *       - errorMessage: some message
  *       - name: name of the file
  *       - size: file size
  *
  * Informations on success:
  *      - error: false
  *      - name: name of the uploaded file
  *      - size: file size
  *      - guid: of the file
  *      - url: url to the file
  *      - thumbnailUrl: url to the thumbnail if exists
  *
  * @param type $cFile
  * @return Array Informations about the uploaded file
  */
 protected function handleFileUpload($cFile, $object = null, $publicAccess = false)
 {
     $output = array();
     $file = new File();
     $file->setUploadedFile($cFile);
     $file->public_access = $publicAccess;
     if ($object != null) {
         $file->object_id = $object->getPrimaryKey();
         $file->object_model = get_class($object);
     }
     if ($file->validate() && $file->save()) {
         $output['error'] = false;
         $output['guid'] = $file->guid;
         $output['name'] = $file->file_name;
         $output['title'] = $file->title;
         $output['size'] = $file->size;
         $output['mimeIcon'] = HHtml::getMimeIconClassByExtension($file->getExtension());
         $output['mimeBaseType'] = $file->getMimeBaseType();
         $output['mimeSubType'] = $file->getMimeSubType();
         $output['url'] = $file->getUrl("", false);
         $output['thumbnailUrl'] = $file->getPreviewImageUrl(200, 200);
     } else {
         $output['error'] = true;
         $output['errors'] = $file->getErrors();
     }
     $output['name'] = $file->file_name;
     $output['size'] = $file->size;
     $output['deleteUrl'] = "";
     $output['deleteType'] = "";
     $output['thumbnailUrl'] = "";
     return $output;
 }
Example #27
0
 /**
  * Moves an image from a safe private location
  * Caller is responsible for clearing caches
  * @param File $oimage
  * @returns mixed, string timestamp on success, false on failure
  */
 function makeOldImagePublic($oimage)
 {
     $transaction = new FSTransaction();
     if (!FileStore::lock()) {
         wfDebug(__METHOD__ . " could not acquire filestore lock\n");
         return false;
     }
     $store = FileStore::get('deleted');
     if (!$store) {
         wfDebug(__METHOD__ . ": skipping row with no file.\n");
         return false;
     }
     $key = $oimage->sha1 . '.' . $oimage->getExtension();
     $destDir = $oimage->getArchivePath();
     if (!is_dir($destDir)) {
         wfMkdirParents($destDir);
     }
     $destPath = $destDir . DIRECTORY_SEPARATOR . $oimage->archive_name;
     // Check if any other stored revisions use this file;
     // if so, we shouldn't remove the file from the hidden
     // archives so they will still work. Check hidden files first.
     $useCount = $this->dbw->selectField('oldimage', '1', array('oi_sha1' => $oimage->sha1, 'oi_deleted & ' . File::DELETED_FILE => File::DELETED_FILE), __METHOD__, array('FOR UPDATE'));
     // Check the rest of the deleted archives too.
     // (these are the ones that don't show in the image history)
     if (!$useCount) {
         $useCount = $this->dbw->selectField('filearchive', '1', array('fa_storage_group' => 'deleted', 'fa_storage_key' => $key), __METHOD__, array('FOR UPDATE'));
     }
     if ($useCount == 0) {
         wfDebug(__METHOD__ . ": nothing else using {$oimage->sha1}, will deleting after\n");
         $flags = FileStore::DELETE_ORIGINAL;
     } else {
         $flags = 0;
     }
     $transaction->add($store->export($key, $destPath, $flags));
     wfDebug(__METHOD__ . ": set db items, applying file transactions\n");
     $transaction->commit();
     FileStore::unlock();
     $m = explode('!', $oimage->archive_name, 2);
     $timestamp = $m[0];
     return $timestamp;
 }
Example #28
0
 private function getImageRessource($image)
 {
     if (is_resource($image)) {
         return $image;
     } elseif (is_file($image)) {
         switch (File::getExtension($image)) {
             case 'jpeg':
             case 'jpg':
                 return imagecreatefromjpeg($image);
                 break;
             case 'gif':
                 return imagecreatefromgif($image);
                 break;
             case 'bmp':
                 return imagecreatefromwbmp($image);
                 break;
             case 'png':
                 $img = imagecreatefrompng($image);
                 imagesavealpha($img, true);
                 imagealphablending($img, true);
                 return $img;
                 break;
             default:
                 throw new Exception(T("Ukendt filtype: %s", File::getExtension($image)));
         }
     } elseif (is_string($image)) {
         return imagecreatefromstring($data);
     }
 }
Example #29
0
 public function index()
 {
     /*
     |--------------------------------------------------------------------------
     | Check for image
     |--------------------------------------------------------------------------
     |
     | Transform just needs the path to an image to get started. If it exists,
     | the fun begins.
     |
     */
     $image_src = $this->fetchParam('src', null, false, false, false);
     // Set full system path
     $image_path = Path::tidy(BASE_PATH . '/' . $image_src);
     // Check if image exists before doing anything.
     if (!File::isImage($image_path)) {
         Log::error("Could not find requested image to transform: " . $image_path, "core", "Transform");
         return;
     }
     /*
     |--------------------------------------------------------------------------
     | Resizing and cropping options
     |--------------------------------------------------------------------------
     |
     | The first transformations we want to run is for size to reduce the
     | memory usage for future effects.
     |
     */
     $width = $this->fetchParam('width', null, 'is_numeric');
     $height = $this->fetchParam('height', null, 'is_numeric');
     // resize specific
     $ratio = $this->fetchParam('ratio', true, false, true);
     $upsize = $this->fetchParam('upsize', true, false, true);
     // crop specific
     $pos_x = $this->fetchParam('pos_x', 0, 'is_numeric');
     $pos_y = $this->fetchParam('pos_y', 0, 'is_numeric');
     $quality = $this->fetchParam('quality', '75', 'is_numeric');
     /*
     |--------------------------------------------------------------------------
     | Action
     |--------------------------------------------------------------------------
     |
     | Available actions: resize, crop, and guess.
     |
     | "Guess" will find the best fitting aspect ratio of your given width and
     | height on the current image automatically, cut it out and resize it to
     | the given dimension.
     |
     */
     $action = $this->fetchParam('action', 'resize');
     /*
     |--------------------------------------------------------------------------
     | Extra bits
     |--------------------------------------------------------------------------
     |
     | Delicious and probably rarely used options.
     |
     */
     $angle = $this->fetchParam('rotate', false);
     $flip_side = $this->fetchParam('flip', false);
     $blur = $this->fetchParam('blur', false, 'is_numeric');
     $pixelate = $this->fetchParam('pixelate', false, 'is_numeric');
     $grayscale = $this->fetchParam('grayscale', false, false, true);
     // Silly brits
     $greyscale = $this->fetchParam('greyscale', $grayscale, false, true);
     /*
     |--------------------------------------------------------------------------
     | Assemble filename and check for duplicate
     |--------------------------------------------------------------------------
     |
     | We need to make sure we don't already have this image created, so we
     | defer any action until we've processed the parameters, which create
     | a unique filename.
     |
     */
     // Find .jpg, .png, etc
     $extension = File::getExtension($image_path);
     // Filename with the extension removed so we can append our unique filename flags
     $stripped_image_path = str_replace('.' . $extension, '', $image_path);
     // The possible filename flags
     $parameter_flags = array('width' => $width, 'height' => $height, 'quality' => $quality, 'rotate' => $angle, 'flip' => $flip_side, 'pos_x' => $pos_x, 'pos_y' => $pos_y, 'blur' => $blur, 'pixelate' => $pixelate, 'greyscale' => $greyscale);
     // Start with a 1 character action flag
     $file_breadcrumbs = '-' . $action[0];
     foreach ($parameter_flags as $param => $value) {
         if ($value) {
             $flag = is_bool($value) ? '' : $value;
             // don't show boolean flags
             $file_breadcrumbs .= '-' . $param[0] . $flag;
         }
     }
     // Allow converting filetypes (jpg, png, gif)
     $extension = $this->fetchParam('type', $extension);
     // Allow saving in a different directory
     $destination = $this->fetchParam('destination', Config::get('transform_destination', false), false, false, false);
     if ($destination) {
         $destination = Path::tidy(BASE_PATH . '/' . $destination);
         // Method checks to see if folder exists before creating it
         Folder::make($destination);
         $stripped_image_path = Path::tidy($destination . '/' . basename($stripped_image_path));
     }
     // Reassembled filename with all flags filtered and delimited
     $new_image_path = $stripped_image_path . $file_breadcrumbs . '.' . $extension;
     // Check if we've already built this image before
     if (File::exists($new_image_path)) {
         return File::cleanURL($new_image_path);
     }
     /*
     |--------------------------------------------------------------------------
     | Create Image
     |--------------------------------------------------------------------------
     |
     | Transform just needs the path to an image to get started. The image is
     | created in memory so we can start manipulating it.
     |
     */
     $image = Image::make($image_path);
     /*
     |--------------------------------------------------------------------------
     | Perform Actions
     |--------------------------------------------------------------------------
     |
     | This is fresh transformation. Time to work the magic!
     |
     */
     if ($action === 'resize' && ($width || $height)) {
         $image->resize($width, $height, $ratio, $upsize);
     }
     if ($action === 'crop' && $width && $height) {
         $image->crop($width, $height, $pos_x, $pos_y);
     }
     if ($action === 'smart') {
         $image->grab($width, $height);
     }
     if ($angle) {
         $image->rotate($angle);
     }
     if ($flip_side === 'h' || $flip_side === 'v') {
         $image->flip($flip_side);
     }
     if ($greyscale) {
         $image->greyscale();
     }
     if ($blur) {
         $image->blur($blur);
     }
     if ($pixelate) {
         $image->pixelate($pixelate);
     }
     /*
     |--------------------------------------------------------------------------
     | Save
     |--------------------------------------------------------------------------
     |
     | Get out of dodge!
     |
     */
     $image->save($new_image_path, $quality);
     return File::cleanURL($new_image_path);
 }
Example #30
0
 /**
  * Finds test for $file by looping through all supported test directories.
  *
  * @param File $File File to get test for.
  * @return string Test file.
  */
 public function findTestFor($File)
 {
     $ds = DIRECTORY_SEPARATOR;
     $test = null;
     $path = explode($ds, $File->getPathname());
     $filename = array_pop($path);
     $extension = '.' . $File->getExtension();
     $checked = array();
     foreach ($this->testSuffixes as $suffix) {
         $test = implode($ds, $path) . $ds;
         $test .= substr($filename, 0, -strlen($extension)) . $suffix;
         if (!in_array($test, $checked) && file_exists($test)) {
             array_push($checked, $test);
             return $test;
         }
         array_push($checked, $test);
     }
     foreach ($this->testPaths($path) as $testPath) {
         foreach ($this->testSuffixes as $suffix) {
             $test = $testPath . substr($filename, 0, -strlen($extension)) . $suffix;
             if (!in_array($test, $checked) && file_exists($test)) {
                 array_push($checked, $test);
                 return $test;
             }
             array_push($checked, $test);
         }
     }
     if (!$test || !file_exists($test)) {
         return false;
     }
     return $test;
 }