/**
  * Indexes document that was set in __construct.
  */
 public function indexCrawledDocuments()
 {
     $sFileName = $this->oFile->getName();
     $oFileMinorDocType = $this->oDbr->selectRow('image', 'img_minor_mime', array('img_name' => $sFileName, 'img_major_mime' => 'application'));
     if ($oFileMinorDocType === false) {
         return;
     }
     $sFileDocType = $this->mimeDecoding($oFileMinorDocType->img_minor_mime, $sFileName);
     if (!$this->checkDocType($sFileDocType, $sFileName)) {
         return;
     }
     $sFileTimestamp = $this->oFile->getTimestamp();
     $sVirtualFilePath = $this->oFile->getPath();
     $oFileRepoLocalRef = $this->oFile->getRepo()->getLocalReference($sVirtualFilePath);
     if (!is_null($oFileRepoLocalRef)) {
         $sFilePath = $oFileRepoLocalRef->getPath();
     }
     if ($this->checkExistence($sVirtualFilePath, 'repo', $sFileTimestamp, $sFileName)) {
         return;
     }
     $sFileText = $this->getFileText($sFilePath, $sFileName);
     $doc = $this->makeRepoDocument($sFileDocType, $sFileName, $sFileText, $sFilePath, $sFileTimestamp, $sVirtualFilePath);
     if ($doc) {
         // mode and ERROR_MSG_KEY are only passed for the case when addDocument fails
         $this->oMainControl->addDocument($doc, $this->mode, self::S_ERROR_MSG_KEY);
     }
 }
Example #2
0
	/**
	 * @return bool
	 */
	protected function loadFile() {
		if ( $this->mFileLoaded ) {
			return true;
		}
		$this->mFileLoaded = true;

		$this->mFile = wfFindFile( $this->mTitle );
		if ( !$this->mFile ) {
			$this->mFile = wfLocalFile( $this->mTitle ); // always a File
		}
		$this->mRepo = $this->mFile->getRepo();
		return true;
	}
Example #3
0
 protected function updateFileHeaders(File $file, array $headers)
 {
     $status = $file->getRepo()->getBackend()->describe(['src' => $file->getPath(), 'headers' => $headers]);
     if (!$status->isGood()) {
         $this->error("Encountered error: " . print_r($status, true));
     }
 }
	/**
	 * Stream the file if there were no errors
	 *
	 * @param array $headers Additional HTTP headers to send on success
	 * @return Bool success
	 */
	public function streamFile( $headers = array() ) {
		if ( !$this->path ) {
			return false;
		} elseif ( FileBackend::isStoragePath( $this->path ) ) {
			$be = $this->file->getRepo()->getBackend();
			return $be->streamFile( array( 'src' => $this->path, 'headers' => $headers ) )->isOK();
		} else { // FS-file
			return StreamFile::stream( $this->getLocalCopyPath(), $headers );
		}
	}
Example #5
0
 /**
  * @return bool
  */
 protected function loadFile()
 {
     if ($this->mFileLoaded) {
         return true;
     }
     $this->mFileLoaded = true;
     $this->mFile = false;
     if (!$this->mFile) {
         $this->mFile = wfFindFile($this->mTitle);
         /** Wikia change start (@author Garth Webb) */
         wfRunHooks('WikiFilePageCheckFile', [&$this->mFile]);
         /** Wikia change end */
         if (!$this->mFile) {
             $this->mFile = wfLocalFile($this->mTitle);
             // always a File
         }
     }
     $this->mRepo = $this->mFile->getRepo();
     return true;
 }
 /**
  * Stream the file if there were no errors
  *
  * @param array $headers Additional HTTP headers to send on success
  * @return Status
  * @since 1.27
  */
 public function streamFileWithStatus($headers = [])
 {
     if (!$this->path) {
         return Status::newFatal('backend-fail-stream', '<no path>');
     } elseif (FileBackend::isStoragePath($this->path)) {
         $be = $this->file->getRepo()->getBackend();
         return $be->streamFile(['src' => $this->path, 'headers' => $headers]);
     } else {
         // FS-file
         $success = StreamFile::stream($this->getLocalCopyPath(), $headers);
         return $success ? Status::newGood() : Status::newFatal('backend-fail-stream', $this->path);
     }
 }
 /**
  * Get alternative thumbnail sizes.
  *
  * @note This will only list several alternatives if thumbnails are rendered on 404
  * @param int $origWidth Actual width of image
  * @param int $origHeight Actual height of image
  * @return array An array of [width, height] pairs.
  */
 protected function getThumbSizes($origWidth, $origHeight)
 {
     global $wgImageLimits;
     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($origWidth, $origHeight);
     } else {
         # Creating thumb links triggers thumbnail generation.
         # Just generate the thumb for the current users prefs.
         $thumbSizes = array($this->getImageLimitsFromOption($this->getContext()->getUser(), 'thumbsize'));
         if (!$this->displayImg->mustRender()) {
             // We can safely include a link to the "full-size" preview,
             // without actually rendering.
             $thumbSizes[] = array($origWidth, $origHeight);
         }
     }
     return $thumbSizes;
 }
Example #8
0
 /**
  * @param File $file
  * @param Title $target
  */
 function __construct(File $file, Title $target)
 {
     $this->file = $file;
     $this->target = $target;
     $this->oldHash = $this->file->repo->getHashPath($this->file->getName());
     $this->newHash = $this->file->repo->getHashPath($this->target->getDBkey());
     $this->oldName = $this->file->getName();
     $this->newName = $this->file->repo->getNameFromTitle($this->target);
     $this->oldRel = $this->oldHash . $this->oldName;
     $this->newRel = $this->newHash . $this->newName;
     $this->db = $file->getRepo()->getMasterDb();
 }
Example #9
0
 /**
  * Conversion to PNG for inline display can be disabled here...
  * Note scaling should work with ImageMagick, but may not with GD scaling.
  *
  * Files pulled from an another MediaWiki instance via ForeignAPIRepo /
  * InstantCommons will have thumbnails managed from the remote instance,
  * so we can skip this check.
  *
  * @param File $file
  * @return bool
  */
 public function canRender($file)
 {
     global $wgTiffThumbnailType;
     return (bool) $wgTiffThumbnailType || $file->getRepo() instanceof ForeignAPIRepo;
 }
Example #10
0
 /**
  * Output HTTP response for file
  * Side effect: writes HTTP response to STDOUT.
  *
  * @param File $file File object with a local path (e.g. UnregisteredLocalFile,
  *   LocalFile. Oddly these don't share an ancestor!)
  * @throws SpecialUploadStashTooLargeException
  * @return bool
  */
 private function outputLocalFile(File $file)
 {
     if ($file->getSize() > self::MAX_SERVE_BYTES) {
         throw new SpecialUploadStashTooLargeException();
     }
     return $file->getRepo()->streamFile($file->getPath(), array('Content-Transfer-Encoding: binary', 'Expires: Sun, 17-Jan-2038 19:14:07 GMT'));
 }
Example #11
0
    protected function openShowImage()
    {
        global $wgOut, $wgUser, $wgImageLimits, $wgRequest, $wgLang, $wgEnableUploads, $wgSend404Code;
        $this->loadFile();
        $sizeSel = intval($wgUser->getOption('imagesize'));
        if (!isset($wgImageLimits[$sizeSel])) {
            $sizeSel = User::getDefaultOption('imagesize');
            // The user offset might still be incorrect, specially if
            // $wgImageLimits got changed (see bug #8858).
            if (!isset($wgImageLimits[$sizeSel])) {
                // Default to the first offset in $wgImageLimits
                $sizeSel = 0;
            }
        }
        $max = $wgImageLimits[$sizeSel];
        $maxWidth = $max[0];
        $maxHeight = $max[1];
        $dirmark = $wgLang->getDirMark();
        if ($this->displayImg->exists()) {
            # image
            $page = $wgRequest->getIntOrNull('page');
            if (is_null($page)) {
                $params = array();
                $page = 1;
            } else {
                $params = array('page' => $page);
            }
            $width_orig = $this->displayImg->getWidth($page);
            $width = $width_orig;
            $height_orig = $this->displayImg->getHeight($page);
            $height = $height_orig;
            $longDesc = wfMsg('parentheses', $this->displayImg->getLongDesc());
            wfRunHooks('ImageOpenShowImageInlineBefore', array(&$this, &$wgOut));
            if ($this->displayImg->allowInlineDisplay()) {
                # image
                # "Download high res version" link below the image
                # $msgsize = wfMsgHtml( 'file-info-size', $width_orig, $height_orig, Linker::formatSize( $this->displayImg->getSize() ), $mime );
                # 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) {
                        $height = round($height * $maxWidth / $width);
                        $width = $maxWidth;
                        # Note that $height <= $maxHeight now.
                    } else {
                        $newwidth = floor($width * $maxHeight / $height);
                        $height = round($height * $newwidth / $width);
                        $width = $newwidth;
                        # Note that $height <= $maxHeight now, but might not be identical
                        # because of rounding.
                    }
                    $msgbig = wfMsgHtml('show-big-image');
                    $otherSizes = array();
                    foreach ($wgImageLimits as $size) {
                        if ($size[0] < $width_orig && $size[1] < $height_orig && $size[0] != $width && $size[1] != $height) {
                            $otherSizes[] = $this->makeSizeLink($params, $size[0], $size[1]);
                        }
                    }
                    $msgsmall = wfMessage('show-big-image-preview')->rawParams($this->makeSizeLink($params, $width, $height))->parse();
                    if (count($otherSizes) && $this->displayImg->getRepo()->canTransformVia404()) {
                        $msgsmall .= ' ' . Html::rawElement('span', array('class' => 'mw-filepage-other-resolutions'), wfMessage('show-big-image-other')->rawParams($wgLang->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 = '';
                } 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);
                $showLink = true;
                $anchorclose = Html::rawElement('div', array('class' => 'mw-filepage-resolutioninfo'), $msgsmall);
                $isMulti = $this->displayImg->isMultipage() && $this->displayImg->pageCount() > 1;
                if ($isMulti) {
                    $wgOut->addHTML('<table class="multipageimage"><tr><td>');
                }
                if ($thumbnail) {
                    $options = array('alt' => $this->displayImg->getTitle()->getPrefixedText(), 'file-link' => true);
                    $wgOut->addHTML('<div class="fullImageLink" id="file">' . $thumbnail->toHtml($options) . $anchorclose . "</div>\n");
                }
                if ($isMulti) {
                    $count = $this->displayImg->pageCount();
                    if ($page > 1) {
                        $label = $wgOut->parse(wfMsg('imgmultipageprev'), false);
                        $link = Linker::link($this->getTitle(), $label, array(), array('page' => $page - 1), array('known', 'noclasses'));
                        $thumb1 = Linker::makeThumbLinkObj($this->getTitle(), $this->displayImg, $link, $label, 'none', array('page' => $page - 1));
                    } else {
                        $thumb1 = '';
                    }
                    if ($page < $count) {
                        $label = wfMsg('imgmultipagenext');
                        $link = Linker::link($this->getTitle(), $label, array(), array('page' => $page + 1), array('known', 'noclasses'));
                        $thumb2 = Linker::makeThumbLinkObj($this->getTitle(), $this->displayImg, $link, $label, 'none', array('page' => $page + 1));
                    } else {
                        $thumb2 = '';
                    }
                    global $wgScript;
                    $formParams = array('name' => 'pageselector', 'action' => $wgScript, 'onchange' => 'document.pageselector.submit();');
                    $options = array();
                    for ($i = 1; $i <= $count; $i++) {
                        $options[] = Xml::option($wgLang->formatNum($i), $i, $i == $page);
                    }
                    $select = Xml::tags('select', array('id' => 'pageselector', 'name' => 'page'), implode("\n", $options));
                    $wgOut->addHTML('</td><td><div class="multipageimagenavbox">' . Xml::openElement('form', $formParams) . Html::hidden('title', $this->getTitle()->getPrefixedDBkey()) . wfMsgExt('imgmultigoto', array('parseinline', 'replaceafter'), $select) . Xml::submitButton(wfMsg('imgmultigo')) . Xml::closeElement('form') . "<hr />{$thumb1}\n{$thumb2}<br style=\"clear: both\" /></div></td></tr></table>");
                }
            } else {
                # if direct link is allowed but it's not a renderable image, show an icon.
                if ($this->displayImg->isSafeFile()) {
                    $icon = $this->displayImg->iconThumb();
                    $wgOut->addHTML('<div class="fullImageLink" id="file">' . $icon->toHtml(array('file-link' => true)) . "</div>\n");
                }
                $showLink = true;
            }
            if ($showLink) {
                $filename = wfEscapeWikiText($this->displayImg->getName());
                $linktext = $filename;
                if (isset($msgbig)) {
                    $linktext = wfEscapeWikiText($msgbig);
                }
                $medialink = "[[Media:{$filename}|{$linktext}]]";
                if (!$this->displayImg->isSafeFile()) {
                    $warning = wfMsgNoTrans('mediawarning');
                    $wgOut->addWikiText(<<<EOT
<div class="fullMedia"><span class="dangerousLink">{$medialink}</span>{$dirmark} <span class="fileInfo">{$longDesc}</span></div>
<div class="mediaWarning">{$warning}</div>
EOT
);
                } else {
                    $wgOut->addWikiText(<<<EOT
<div class="fullMedia">{$medialink}{$dirmark} <span class="fileInfo">{$longDesc}</span>
</div>
EOT
);
                }
            }
            if (!$this->displayImg->isLocal()) {
                $this->printSharedImageText();
            }
        } else {
            # Image does not exist
            if ($wgEnableUploads && $wgUser->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 overriden
            // by Article::View().
            $wgOut->setRobotPolicy('noindex,nofollow');
            $wgOut->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.
                $wgRequest->response()->header('HTTP/1.1 404 Not Found');
            }
        }
        $wgOut->setFileVersion($this->displayImg);
    }
Example #12
0
 /**
  * @desc Return city_id for a given file
  * This is needed as File here is returned from wfFindFile
  * that can fallback to some other wikis
  *
  * @param File $file
  * @return int|null|string
  */
 private function getFileCityId(File $file)
 {
     global $wgCityId;
     $repo = $file->getRepo();
     /**
      * Only fetch city_id if the file is coming from
      * WikiaForeignDBViaLBRepo
      */
     if ($repo instanceof WikiaForeignDBViaLBRepo) {
         $dbName = $repo->getDBName();
         $wiki = WikiFactory::getWikiByDB($dbName);
         if (!empty($wiki)) {
             return $wiki->city_id;
         }
     }
     return $wgCityId;
 }
 /**
  * Check if the premium video is added to the wiki
  * @param File $file
  * @return boolean $isAdded
  */
 public static function isAdded($file)
 {
     $isAdded = true;
     if ($file instanceof File && !$file->isLocal() && F::app()->wg->WikiaVideoRepoDBName == $file->getRepo()->getWiki()) {
         $info = VideoInfo::newFromTitle($file->getTitle()->getDBkey());
         if (empty($info)) {
             $isAdded = false;
         }
     }
     return $isAdded;
 }
Example #14
0
/**
 * @param File $img
 * @param string $thumbName
 * @return string
 */
function wfThumbAttemptKey(File $img, $thumbName)
{
    global $wgAttemptFailureEpoch;
    return wfMemcKey('attempt-failures', $wgAttemptFailureEpoch, $img->getRepo()->getName(), md5($img->getName()), md5($thumbName));
}
Example #15
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);
    }
 /**
  * @param File $file
  * @param bool $dumpContents
  * @return string
  */
 function writeUpload($file, $dumpContents = false)
 {
     if ($file->isOld()) {
         $archiveName = "      " . Xml::element('archivename', null, $file->getArchiveName()) . "\n";
     } else {
         $archiveName = '';
     }
     if ($dumpContents) {
         $be = $file->getRepo()->getBackend();
         # Dump file as base64
         # Uses only XML-safe characters, so does not need escaping
         # @todo Too bad this loads the contents into memory (script might swap)
         $contents = '      <contents encoding="base64">' . chunk_split(base64_encode($be->getFileContents(array('src' => $file->getPath())))) . "      </contents>\n";
     } else {
         $contents = '';
     }
     if ($file->isDeleted(File::DELETED_COMMENT)) {
         $comment = Xml::element('comment', array('deleted' => 'deleted'));
     } else {
         $comment = Xml::elementClean('comment', null, $file->getDescription());
     }
     return "    <upload>\n" . $this->writeTimestamp($file->getTimestamp()) . $this->writeContributor($file->getUser('id'), $file->getUser('text')) . "      " . $comment . "\n" . "      " . Xml::element('filename', null, $file->getName()) . "\n" . $archiveName . "      " . Xml::element('src', null, $file->getCanonicalURL()) . "\n" . "      " . Xml::element('size', null, $file->getSize()) . "\n" . "      " . Xml::element('sha1base36', null, $file->getSha1()) . "\n" . "      " . Xml::element('rel', null, $file->getRel()) . "\n" . $contents . "    </upload>\n";
 }
Example #17
0
/**
 * Actually try to generate a new thumbnail
 *
 * @param File $file
 * @param array $params
 * @param string $thumbName
 * @param string $thumbPath
 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
 */
function wfGenerateThumbnail(File $file, array $params, $thumbName, $thumbPath)
{
    global $wgMemc, $wgAttemptFailureEpoch;
    $key = wfMemcKey('attempt-failures', $wgAttemptFailureEpoch, $file->getRepo()->getName(), $file->getSha1(), md5($thumbName));
    // Check if this file keeps failing to render
    if ($wgMemc->get($key) >= 4) {
        return array(false, wfMessage('thumbnail_image-failure-limit', 4));
    }
    $done = false;
    // Record failures on PHP fatals in addition to caching exceptions
    register_shutdown_function(function () use(&$done, $key) {
        if (!$done) {
            // transform() gave a fatal
            global $wgMemc;
            // Randomize TTL to reduce stampedes
            $wgMemc->incrWithInit($key, 3600 + mt_rand(0, 300));
        }
    });
    $thumb = false;
    $errorHtml = false;
    // guard thumbnail rendering with PoolCounter to avoid stampedes
    // expensive files use a separate PoolCounter config so it is possible
    // to set up a global limit on them
    if ($file->isExpensiveToThumbnail()) {
        $poolCounterType = 'FileRenderExpensive';
    } else {
        $poolCounterType = 'FileRender';
    }
    // Thumbnail isn't already there, so create the new thumbnail...
    try {
        $work = new PoolCounterWorkViaCallback($poolCounterType, sha1($file->getName()), array('doWork' => function () use($file, $params) {
            return $file->transform($params, File::RENDER_NOW);
        }, 'getCachedWork' => function () use($file, $params, $thumbPath) {
            // If the worker that finished made this thumbnail then use it.
            // Otherwise, it probably made a different thumbnail for this file.
            return $file->getRepo()->fileExists($thumbPath) ? $file->transform($params, File::RENDER_NOW) : false;
            // retry once more in exclusive mode
        }, 'fallback' => function () {
            return wfMessage('generic-pool-error')->parse();
        }, 'error' => function (Status $status) {
            return $status->getHTML();
        }));
        $result = $work->execute();
        if ($result instanceof MediaTransformOutput) {
            $thumb = $result;
        } elseif (is_string($result)) {
            // error
            $errorHtml = $result;
        }
    } catch (Exception $e) {
        // Tried to select a page on a non-paged file?
    }
    /** @noinspection PhpUnusedLocalVariableInspection */
    $done = true;
    // no PHP fatal occured
    if (!$thumb || $thumb->isError()) {
        // Randomize TTL to reduce stampedes
        $wgMemc->incrWithInit($key, 3600 + mt_rand(0, 300));
    }
    return array($thumb, $errorHtml);
}