/** * @todo Add unit tests * * @param File $image * @return bool */ function getImageArea($image) { $ser = $image->getMetadata(); if ($ser) { $metadata = unserialize($ser); return $image->getWidth() * $image->getHeight() * $metadata['frameCount']; } else { return $image->getWidth() * $image->getHeight(); } }
/** * @param File $file * @return string */ function getDimensionsString($file) { $pages = $file->pageCount(); if ($pages > 1) { return wfMessage('widthheightpage')->numParams($file->getWidth(), $file->getHeight(), $pages)->text(); } else { return wfMessage('widthheight')->numParams($file->getWidth(), $file->getHeight())->text(); } }
/** * @param File $img */ private static function imgIsVertical($img) { $height = $img->getHeight(); $width = $img->getWidth(); if (!$height || !$width) { return false; } return $height > $width; }
/** * Adds some metadata to a {@link File} object that is used by the view. This function * allows us to avoid having to use a decorator on the {@link File} class. * * @param File * @return array */ protected function getFields(File $f) { if ($f instanceof Folder) { return array('Link' => $this->Link($this->getBrowseAction() . '/' . $f->ID), 'Item' => $f); } $image = $f instanceof Image; $tooltipurl = ""; if ($image) { if ($f->getHeight() > 64 || $f->getWidth() > 64) { if ($f->getOrientation() == Image::ORIENTATION_SQUARE || $f->getOrientation() == Image::ORIENTATION_LANDSCAPE) { $tooltipurl = $f->getWidth() > self::$tooltip_size ? $f->SetWidth(self::$tooltip_size)->getURL() : $f->getURL(); } else { $tooltipurl = $f->getHeight() > self::$tooltip_size ? $f->setHeight(self::$tooltip_size)->getURL() : $f->getURL(); } } } return array('Link' => '', 'Item' => $f, 'IconURL' => $image ? ($i = $f->SetHeight(64)) ? $i->getURL() : KickAssetUtil::get_icon($f) : KickAssetUtil::get_icon($f), 'Image' => $image, 'TooltipURL' => $tooltipurl); }
public function onThumbnailVideoHTML($options, $linkAttribs, $imageAttribs, File $file, &$html) { $this->wf->profileIn(__METHOD__); if (self::$isWikiaMobile) { /** * WikiaMobile: lazy loading images in a SEO-friendly manner * @author Federico "Lox" Lucignano <federico@wikia-inc.com * @author Artur Klajnerok <*****@*****.**> */ $origImg = Xml::element('img', $imageAttribs, '', true); if (empty($imageAttribs['alt'])) { unset($imageAttribs['alt']); } $imageParams = array('type' => 'video', 'full' => $imageAttribs['src']); if (!empty($linkAttribs['data-video-name'])) { $imageParams['name'] = $linkAttribs['data-video-name']; } if (!empty($options['caption'])) { $imageParams['capt'] = true; } if ($file instanceof File) { $size = WikiaMobileMediaService::calculateMediaSize($file->getWidth(), $file->getHeight()); $thumb = $file->transform($size); $imageAttribs['src'] = wfReplaceImageServer($thumb->getUrl(), $file->getTimestamp()); $imageAttribs['width'] = $size['width']; $imageAttribs['height'] = $size['height']; } $data = array('attributes' => $imageAttribs, 'parameters' => array($imageParams), 'anchorAttributes' => $linkAttribs, 'noscript' => $origImg); if ($file instanceof File) { $title = $file->getTitle()->getDBKey(); $titleText = $file->getTitle()->getText(); $data['content'] = Xml::element('span', array('class' => 'videoInfo'), "{$titleText} (" . $file->getHandler()->getFormattedDuration() . ", " . $this->wf->MsgForContent('wikiamobile-video-views-counter', MediaQueryService::getTotalVideoViewsByTitle($title)) . ')'); } $html = $this->app->sendRequest('WikiaMobileMediaService', 'renderImageTag', $data, true)->toString(); } $this->wf->profileOut(__METHOD__); return true; }
public function getHTML() { $data = $this->list->msg('widthheight')->numParams($this->file->getWidth(), $this->file->getHeight())->text() . ' (' . $this->list->msg('nbytes')->numParams($this->file->getSize())->text() . ')'; return '<li>' . $this->getLink() . ' ' . $this->getUserTools() . ' ' . $data . ' ' . $this->getComment() . '</li>'; }
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 * @returns string */ private function fileLine($file) { global $wgLang, $wgTitle; $target = $this->page->getPrefixedText(); $date = $wgLang->timeanddate($file->getTimestamp(), true); $del = ''; # Hidden files... if ($file->isDeleted(File::DELETED_FILE)) { $del = ' <tt>' . wfMsgHtml('deletedrev') . '</tt>'; if (!$file->userCan(File::DELETED_FILE)) { $pageLink = $date; } else { $pageLink = $this->skin->makeKnownLinkObj($wgTitle, $date, "target={$target}&file={$file->sha1}." . $file->getExtension()); } $pageLink = '<span class="history-deleted">' . $pageLink . '</span>'; # Regular files... } else { $url = $file->getUrlRel(); $pageLink = "<a href=\"{$url}\">{$date}</a>"; } $data = wfMsg('widthheight', $wgLang->formatNum($file->getWidth()), $wgLang->formatNum($file->getHeight())) . ' (' . wfMsgExt('nbytes', 'parsemag', $wgLang->formatNum($file->getSize())) . ')'; $data = htmlspecialchars($data); return "<li>{$pageLink} " . $this->fileUserTools($file) . " {$data} " . $this->fileComment($file) . "{$del}</li>"; }
/** * Return height and width for image $file such that the image is shrunk (keeping aspect ratio) to just the * height or width of $dim, whichever is closest. Typically the image will then be cropped to the $dim bounds. * The original file height and width will be returned for images both shorter and narrower than $dim. * * @param File $file * @param array $dim * @return array */ public function fitClosest(File $file, array $dim) { $aspect = $file->getWidth() / $file->getHeight(); $adjWidth = $file->getWidth(); $adjHeight = $file->getHeight(); // Adjust the image to the closest dimension. if ($file->getWidth() > $dim['w'] || $file->getHeight() > $dim['h']) { $widthDelta = $file->getWidth() - $dim['w']; $heightDelta = $file->getHeight() - $dim['h']; if ($widthDelta > 0 && $widthDelta < $heightDelta) { // Oversized image, constrain on width $adjWidth = $dim['w']; $adjHeight = intval($adjWidth / $aspect); } else { // Oversized image, constrain on height $adjHeight = $dim['h']; $adjWidth = intval($adjHeight * $aspect); } } return [$adjWidth, $adjHeight]; }
/** * Function that returns the number of pixels to be thumbnailed. * Intended for animated GIFs to multiply by the number of frames. * * @param File $image * @return int */ function getImageArea($image) { return $image->getWidth() * $image->getHeight(); }
/** * Make an image link * @param Title $title Title object * @param File $file File object, or false if it doesn't exist * * @param array $frameParams Associative array of parameters external to the media handler. * Boolean parameters are indicated by presence or absence, the value is arbitrary and * will often be false. * thumbnail If present, downscale and frame * manualthumb Image name to use as a thumbnail, instead of automatic scaling * framed Shows image in original size in a frame * frameless Downscale but don't frame * upright If present, tweak default sizes for portrait orientation * upright_factor Fudge factor for "upright" tweak (default 0.75) * border If present, show a border around the image * align Horizontal alignment (left, right, center, none) * valign Vertical alignment (baseline, sub, super, top, text-top, middle, * bottom, text-bottom) * alt Alternate text for image (i.e. alt attribute). Plain text. * caption HTML for image caption. * * @param array $handlerParams Associative array of media handler parameters, to be passed * to transform(). Typical keys are "width" and "page". * @param string $time, timestamp of the file, set as false for current */ function makeImageLink2(Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false) { global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright; if ($file && !$file->allowInlineDisplay()) { wfDebug(__METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n"); return $this->makeKnownLinkObj($title); } if (!$file) { return; } // Shortcuts $fp =& $frameParams; $hp =& $handlerParams; $section = WikihowArticleEditor::getImageSection($file->getName()); // Clean up parameters $page = isset($hp['page']) ? $hp['page'] : false; if (!isset($fp['align'])) { $fp['align'] = ''; } if (!isset($fp['alt'])) { $fp['alt'] = ''; } $imageClass = ""; $prefix = $postfix = ''; $isPortrait = false; $isLarge = false; $sourceWidth = $file->getWidth(); $sourceHeight = $file->getHeight(); if ($sourceHeight > $sourceWidth) { if ($sourceWidth > 200) { $isPortrait = true; $isLarge = true; } } else { //landscape if ($sourceWidth > 400) { $isLarge = true; } } if ($section != "summary" && $section != "steps") { $isLarge = false; } if ($section == "summary") { //for intro they must specify 625 and center to have it shown if ($hp['width'] >= 625) { $imageClass .= " introimage "; } } if ($file && !isset($hp['width'])) { $hp['width'] = $file->getWidth($page); if (isset($fp['thumbnail']) || isset($fp['framed']) || isset($fp['frameless']) || !$hp['width']) { $wopt = $wgUser->getOption('thumbsize'); if (!isset($wgThumbLimits[$wopt])) { $wopt = User::getDefaultOption('thumbsize'); } // Reduce width for upright images when parameter 'upright' is used if (isset($fp['upright']) && $fp['upright'] == 0) { $fp['upright'] = $wgThumbUpright; } // Use width which is smaller: real image width or user preference width // For caching health: If width scaled down due to upright parameter, round to full __0 pixel to avoid the creation of a lot of odd thumbs $prefWidth = isset($fp['upright']) ? round($wgThumbLimits[$wopt] * $fp['upright'], -1) : $wgThumbLimits[$wopt]; if ($hp['width'] <= 0 || $prefWidth < $hp['width']) { $hp['width'] = $prefWidth; } } } //not using thumbs on large images anymore if (!$isLarge && isset($fp['thumbnail']) || isset($fp['manualthumb']) || isset($fp['framed'])) { # Create a thumbnail. Alignment depends on language # writing direction, # right aligned for left-to-right- # languages ("Western languages"), left-aligned # for right-to-left-languages ("Semitic languages") # # If thumbnail width has not been provided, it is set # to the default user option as specified in Language*.php if ($fp['align'] == '') { $fp['align'] = $wgContLang->isRTL() ? 'left' : 'right'; } return $prefix . $this->makeThumbLink2($title, $file, $fp, $hp, $time) . $postfix; } if ($file && isset($fp['frameless'])) { # For "frameless" option: do not present an image bigger than the source (for bitmap-style images) # This is the same behaviour as the "thumb" option does it already. if ($sourceWidth && !$file->mustRender() && $hp['width'] > $sourceWidth) { $hp['width'] = $sourceWidth; } } if ($file && $hp['width']) { # Create a resized image, without the additional thumbnail features if ($isLarge) { if ($isPortrait) { //it's a portrait image $height = min(550, $sourceHeight); $hp['width'] = $sourceWidth * $height / $sourceHeight; $imageClass .= " largeimage portrait"; } else { if ($isLarge) { //this is our low threshold, so show it as big as possible $hp['width'] = min(670, $sourceWidth); //now make sure it's not too tall. $newHeight = $sourceHeight * $hp['width'] / $sourceWidth; if ($newHeight > 550) { //limit all images to 550 $hp['width'] = $sourceWidth * 525 / $sourceHeight; } $imageClass .= " largeimage "; } } if ($hp['width'] < 670) { $imageClass .= " underwidth "; } } $thumb = $file->transform($hp); } else { $thumb = false; } if (!$isLarge) { $imageClass .= " t{$fp['align']}"; } if (!$thumb) { $s = $this->makeBrokenImageLinkObj($title, '', '', '', '', $time == true); } else { $s = $thumb->toHtml(array('desc-link' => true, 'href' => '', 'onclick' => 'return loadimg("' . $thumb->path . '", "' . $thumb->url . '" );', 'alt' => $fp['alt'], 'valign' => isset($fp['valign']) ? $fp['valign'] : false, 'img-class' => isset($fp['border']) ? 'thumbborder' : false)); $h = $thumb->getHeight(); $w = $thumb->getWidth(); /*$s = "<div class='rounders' style='width:{$w}px;height:{$h}px;'>$s <div class='corner top_left'></div><div class='corner top_right'></div><div class='corner bottom_left'></div><div class='corner bottom_right'></div> </div>";*/ } if ('' == $fp['align']) { $fp['align'] = 'right'; } $imageClass .= " float{$fp['align']} "; if (isset($fp['thumbnail'])) { $imageClass .= " mthumb "; } //for mobile thumb $rptLink = class_exists('InaccurateImages') ? InaccurateImages::getReportImageLink() : ""; $s = "<div class='mwimg {$imageClass}' style='max-width:{$hp['width']}px'>{$rptLink}{$s}</div>"; return str_replace("\n", ' ', $prefix . $s . $postfix); }
/** * Given parameters derived from [[Image:Foo|options...]], generate the * HTML that that syntax inserts in the page. * * @param Title $title Title object * @param File $file File object, or false if it doesn't exist * * @param array $frameParams Associative array of parameters external to the media handler. * Boolean parameters are indicated by presence or absence, the value is arbitrary and * will often be false. * thumbnail If present, downscale and frame * manualthumb Image name to use as a thumbnail, instead of automatic scaling * framed Shows image in original size in a frame * frameless Downscale but don't frame * upright If present, tweak default sizes for portrait orientation * upright_factor Fudge factor for "upright" tweak (default 0.75) * border If present, show a border around the image * align Horizontal alignment (left, right, center, none) * valign Vertical alignment (baseline, sub, super, top, text-top, middle, * bottom, text-bottom) * alt Alternate text for image (i.e. alt attribute). Plain text. * caption HTML for image caption. * link-url URL to link to * link-title Title object to link to * no-link Boolean, suppress description link * * @param array $handlerParams Associative array of media handler parameters, to be passed * to transform(). Typical keys are "width" and "page". * @param string $time, timestamp of the file, set as false for current * @param string $query, query params for desc url * @return string HTML for an image, with links, wrappers, etc. */ function makeImageLink2(Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "") { $res = null; if (!wfRunHooks('ImageBeforeProduceHTML', array(&$this, &$title, &$file, &$frameParams, &$handlerParams, &$time, &$res))) { return $res; } global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright; if ($file && !$file->allowInlineDisplay()) { wfDebug(__METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n"); return $this->link($title); } // Shortcuts $fp =& $frameParams; $hp =& $handlerParams; // Clean up parameters $page = isset($hp['page']) ? $hp['page'] : false; if (!isset($fp['align'])) { $fp['align'] = ''; } if (!isset($fp['alt'])) { $fp['alt'] = ''; } # Backward compatibility, title used to always be equal to alt text if (!isset($fp['title'])) { $fp['title'] = $fp['alt']; } $prefix = $postfix = ''; if ('center' == $fp['align']) { $prefix = '<div class="center">'; $postfix = '</div>'; $fp['align'] = 'none'; } if ($file && !isset($hp['width'])) { $hp['width'] = $file->getWidth($page); if (isset($fp['thumbnail']) || isset($fp['framed']) || isset($fp['frameless']) || !$hp['width']) { $wopt = $wgUser->getOption('thumbsize'); if (!isset($wgThumbLimits[$wopt])) { $wopt = User::getDefaultOption('thumbsize'); } // Reduce width for upright images when parameter 'upright' is used if (isset($fp['upright']) && $fp['upright'] == 0) { $fp['upright'] = $wgThumbUpright; } // Use width which is smaller: real image width or user preference width // For caching health: If width scaled down due to upright parameter, round to full __0 pixel to avoid the creation of a lot of odd thumbs $prefWidth = isset($fp['upright']) ? round($wgThumbLimits[$wopt] * $fp['upright'], -1) : $wgThumbLimits[$wopt]; if ($hp['width'] <= 0 || $prefWidth < $hp['width']) { $hp['width'] = $prefWidth; } } } if (isset($fp['thumbnail']) || isset($fp['manualthumb']) || isset($fp['framed'])) { # Create a thumbnail. Alignment depends on language # writing direction, # right aligned for left-to-right- # languages ("Western languages"), left-aligned # for right-to-left-languages ("Semitic languages") # # If thumbnail width has not been provided, it is set # to the default user option as specified in Language*.php if ($fp['align'] == '') { $fp['align'] = $wgContLang->isRTL() ? 'left' : 'right'; } return $prefix . $this->makeThumbLink2($title, $file, $fp, $hp, $time, $query) . $postfix; } if ($file && isset($fp['frameless'])) { $srcWidth = $file->getWidth($page); # For "frameless" option: do not present an image bigger than the source (for bitmap-style images) # This is the same behaviour as the "thumb" option does it already. if ($srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth) { $hp['width'] = $srcWidth; } } if ($file && $hp['width']) { # Create a resized image, without the additional thumbnail features $thumb = $file->transform($hp); } else { $thumb = false; } if (!$thumb) { $s = $this->makeBrokenImageLinkObj($title, '', '', '', '', $time == true); } else { $params = array('alt' => $fp['alt'], 'title' => $fp['title'], 'valign' => isset($fp['valign']) ? $fp['valign'] : false, 'img-class' => isset($fp['border']) ? 'thumbborder' : false); if (!empty($fp['link-url'])) { $params['custom-url-link'] = $fp['link-url']; } elseif (!empty($fp['link-title'])) { $params['custom-title-link'] = $fp['link-title']; } elseif (!empty($fp['no-link'])) { // No link } else { $params['desc-link'] = true; $params['desc-query'] = $query; } $s = $thumb->toHtml($params); } if ('' != $fp['align']) { $s = "<div class=\"float{$fp['align']}\">{$s}</div>"; } return str_replace("\n", ' ', $prefix . $s . $postfix); }
public static function onThumbnailVideoHTML($options, $linkAttribs, $imageAttribs, File $file, &$html) { global $wgRTEParserEnabled; if (!empty($wgRTEParserEnabled)) { return true; } if (is_null(self::$isWikiaMobile)) { self::init(); } if (self::$isWikiaMobile) { wfProfileIn(__METHOD__); /** * WikiaMobile: lazy loading images in a SEO-friendly manner * @author Federico "Lox" Lucignano <federico@wikia-inc.com * @author Artur Klajnerok <*****@*****.**> */ $origImg = Xml::element('img', $imageAttribs, '', true); if (empty($imageAttribs['alt'])) { unset($imageAttribs['alt']); } //Not all 'files' have getProviderName defined if (is_callable([$file, 'getProviderName'])) { $provider = $file->getProviderName(); } else { $provider = ''; } $imageParams = array('type' => 'video', 'provider' => $provider, 'full' => $imageAttribs['src']); if (!empty($imageAttribs['data-video-key'])) { $imageParams['name'] = htmlspecialchars($imageAttribs['data-video-key']); } if (!empty($options['caption'])) { $imageParams['capt'] = 1; } // TODO: this resizes every video thumbnail with a width over 64px regardless of where it appears. // We may want to add the ability to allow custom image widths (like on the file page history table for example) $size = WikiaMobileMediaService::calculateMediaSize($file->getWidth(), $file->getHeight()); $thumb = $file->transform($size); $imageAttribs['src'] = wfReplaceImageServer($thumb->getUrl(), $file->getTimestamp()); $imageAttribs['width'] = $size['width']; $imageAttribs['height'] = $size['height']; $data = ['attributes' => $imageAttribs, 'parameters' => [$imageParams], 'anchorAttributes' => $linkAttribs, 'noscript' => $origImg, 'isSmall' => WikiaMobileMediaService::isSmallImage($imageAttribs['width'], $imageAttribs['height'])]; $title = $file->getTitle()->getDBKey(); $titleText = $file->getTitle()->getText(); $views = MediaQueryService::getTotalVideoViewsByTitle($title); $data['content'] = Xml::element('span', ['class' => 'videoInfo'], "{$titleText} (" . $file->getHandler()->getFormattedDuration() . ", " . wfMessage('wikiamobile-video-views-counter', $views)->inContentLanguage()->text() . ')'); $html = F::app()->sendRequest('WikiaMobileMediaService', 'renderImageTag', $data, true)->toString(); wfProfileOut(__METHOD__); } return true; }
/** * Return a URL that displays $file scaled and/or cropped to fill the entire square thumbnail dimensions with * no whitespace if possible. Images smaller than the thumbnail size will be enlarged if their image area (L x W) * is above a certain threshold. This threshold is expressed as a percentage of the requested thumb area and * given by: * * self::thumbEnlargeThreshold * * Small images that do not meet this threshold will be centered within the thumb container and padded with a * transparent background. * * @param File $file * @param int $dimension * @param bool $useWebP * @return string The URL of the image */ public static function getSquaredThumbnailUrl(File $file, $dimension, $useWebP = false) { // Create a new url generator $gen = $file->getUrlGenerator(); // Determine if this image falls into a small image category. We compare the area of the image with the // area of the requested thumb and use self::thumbEnlargeThreshold as the threshold for enlarging $height = $file->getHeight(); $width = $file->getWidth(); $isSmallImage = $height < $dimension || $width < $dimension; $imageBelowThreshold = $height * $width <= self::thumbEnlargeThreshold * $dimension * $dimension; // If height or width is less than a side of our square target thumbnail, we need to decide whether we're // going to enlarge it or not if ($isSmallImage && $imageBelowThreshold) { // Leave the (small) full sized image as is, but put within the requested container with transparent fill $gen->fixedAspectRatioDown()->backgroundFill('transparent'); } else { if ($height > $width) { // Portrait mode, crop at the top $gen->topCrop(); } else { // Landscape mode, crop in the middle $gen->zoomCrop(); } } if ($useWebP) { $gen->webp(); } $url = $gen->width($dimension)->height($dimension)->url(); return $url; }
/** * Check if the file is smaller than the maximum image area for thumbnailing. * * Runs the 'BitmapHandlerCheckImageArea' hook. * * @param File $file * @param array $params * @return bool * @since 1.25 */ public function isImageAreaOkForThumbnaling($file, &$params) { global $wgMaxImageArea; # For historical reasons, hook starts with BitmapHandler $checkImageAreaHookResult = null; Hooks::run('BitmapHandlerCheckImageArea', array($file, &$params, &$checkImageAreaHookResult)); if (!is_null($checkImageAreaHookResult)) { // was set by hook, so return that value return (bool) $checkImageAreaHookResult; } $srcWidth = $file->getWidth($params['page']); $srcHeight = $file->getHeight($params['page']); if ($srcWidth * $srcHeight > $wgMaxImageArea && !($file->getMimeType() == 'image/jpeg' && $this->getScalerType(false, false) == 'im')) { # Only ImageMagick can efficiently downsize jpg images without loading # the entire file in memory return false; } return true; }
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); }
public function getHTML() { $data = wfMsg('widthheight', $this->list->getLang()->formatNum($this->file->getWidth()), $this->list->getLang()->formatNum($this->file->getHeight())) . ' (' . wfMsgExt('nbytes', 'parsemag', $this->list->getLang()->formatNum($this->file->getSize())) . ')'; return '<li>' . $this->getLink() . ' ' . $this->getUserTools() . ' ' . $data . ' ' . $this->getComment() . '</li>'; }
/** * @param Title $title * @param File $file * @param array $frameParams * @param array $handlerParams * @param bool $time * @param string $query * @return string */ public static function makeThumbLink2(Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "") { $exists = $file && $file->exists(); # Shortcuts $fp =& $frameParams; $hp =& $handlerParams; $page = isset($hp['page']) ? $hp['page'] : false; if (!isset($fp['align'])) { $fp['align'] = 'right'; } if (!isset($fp['alt'])) { $fp['alt'] = ''; } if (!isset($fp['title'])) { $fp['title'] = ''; } if (!isset($fp['caption'])) { $fp['caption'] = ''; } if (empty($hp['width'])) { // Reduce width for upright images when parameter 'upright' is used $hp['width'] = isset($fp['upright']) ? 130 : 180; } $thumb = false; $noscale = false; $manualthumb = false; if (!$exists) { $outerWidth = $hp['width'] + 2; } else { if (isset($fp['manualthumb'])) { # Use manually specified thumbnail $manual_title = Title::makeTitleSafe(NS_FILE, $fp['manualthumb']); if ($manual_title) { $manual_img = wfFindFile($manual_title); if ($manual_img) { $thumb = $manual_img->getUnscaledThumb($hp); $manualthumb = true; } else { $exists = false; } } } elseif (isset($fp['framed'])) { // Use image dimensions, don't scale $thumb = $file->getUnscaledThumb($hp); $noscale = true; } else { # Do not present an image bigger than the source, for bitmap-style images # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior $srcWidth = $file->getWidth($page); if ($srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth) { $hp['width'] = $srcWidth; } $thumb = $file->transform($hp); } if ($thumb) { $outerWidth = $thumb->getWidth() + 2; } else { $outerWidth = $hp['width'] + 2; } } # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs # So we don't need to pass it here in $query. However, the URL for the # zoom icon still needs it, so we make a unique query for it. See bug 14771 $url = $title->getLocalURL($query); if ($page) { $url = wfAppendQuery($url, array('page' => $page)); } if ($manualthumb && !isset($fp['link-title']) && !isset($fp['link-url']) && !isset($fp['no-link'])) { $fp['link-url'] = $url; } $s = "<div class=\"thumb t{$fp['align']}\">" . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">"; if (!$exists) { $s .= self::makeBrokenImageLinkObj($title, $fp['title'], '', '', '', $time == true); $zoomIcon = ''; } elseif (!$thumb) { $s .= wfMessage('thumbnail_error', '')->escaped(); $zoomIcon = ''; } else { if (!$noscale && !$manualthumb) { self::processResponsiveImages($file, $thumb, $hp); } $params = array('alt' => $fp['alt'], 'title' => $fp['title'], 'img-class' => (isset($fp['class']) && $fp['class'] !== '' ? $fp['class'] . ' ' : '') . 'thumbimage'); $params = self::getImageLinkMTOParams($fp, $query) + $params; $s .= $thumb->toHtml($params); if (isset($fp['framed'])) { $zoomIcon = ""; } else { $zoomIcon = Html::rawElement('div', array('class' => 'magnify'), Html::rawElement('a', array('href' => $url, 'class' => 'internal', 'title' => wfMessage('thumbnail-more')->text()), "")); } } $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>"; return str_replace("\n", ' ', $s); }
/** Validate and merge scale parameters with handler thumb parameters, give error if invalid. * * We do this later than getScale, since we need the image * to know which handler, since handlers can make their own parameters. * @param File $image Image that params are for. * @param array $thumbParams thumbnail parameters from getScale * @param string $otherParams of otherParams (iiurlparam). * @return Array of parameters for transform. */ protected function mergeThumbParams( $image, $thumbParams, $otherParams ) { global $wgThumbLimits; if ( !isset( $thumbParams['width'] ) && isset( $thumbParams['height'] ) ) { // We want to limit only by height in this situation, so pass the // image's full width as the limiting width. But some file types // don't have a width of their own, so pick something arbitrary so // thumbnailing the default icon works. if ( $image->getWidth() <= 0 ) { $thumbParams['width'] = max( $wgThumbLimits ); } else { $thumbParams['width'] = $image->getWidth(); } } if ( !$otherParams ) { return $thumbParams; } $p = $this->getModulePrefix(); $h = $image->getHandler(); if ( !$h ) { $this->setWarning( 'Could not create thumbnail because ' . $image->getName() . ' does not have an associated image handler' ); return $thumbParams; } $paramList = $h->parseParamString( $otherParams ); if ( !$paramList ) { // Just set a warning (instead of dieUsage), as in many cases // we could still render the image using width and height parameters, // and this type of thing could happen between different versions of // handlers. $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName() . '. Using only width and height' ); return $thumbParams; } if ( isset( $paramList['width'] ) ) { if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) { $this->setWarning( "Ignoring width value set in {$p}urlparam ({$paramList['width']}) " . "in favor of width value derived from {$p}urlwidth/{$p}urlheight ({$thumbParams['width']})" ); } } foreach ( $paramList as $name => $value ) { if ( !$h->validateParam( $name, $value ) ) { $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" ); } } return $thumbParams + $paramList; }
/** * Get result information for an image revision * * @param File $file * @param array $prop Array of properties to get (in the keys) * @param ApiResult $result * @param array $thumbParams Containing 'width' and 'height' items, or null * @param array|bool|string $opts Options for data fetching. * This is an array consisting of the keys: * 'version': The metadata version for the metadata option * 'language': The language for extmetadata property * 'multilang': Return all translations in extmetadata property * 'revdelUser': User to use when checking whether to show revision-deleted fields. * @return array Result array */ static function getInfo($file, $prop, $result, $thumbParams = null, $opts = false) { global $wgContLang; $anyHidden = false; if (!$opts || is_string($opts)) { $opts = array('version' => $opts ?: 'latest', 'language' => $wgContLang, 'multilang' => false, 'extmetadatafilter' => array(), 'revdelUser' => null); } $version = $opts['version']; $vals = array(ApiResult::META_TYPE => 'assoc'); // Timestamp is shown even if the file is revdelete'd in interface // so do same here. if (isset($prop['timestamp'])) { $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $file->getTimestamp()); } // Handle external callers who don't pass revdelUser if (isset($opts['revdelUser']) && $opts['revdelUser']) { $revdelUser = $opts['revdelUser']; $canShowField = function ($field) use($file, $revdelUser) { return $file->userCan($field, $revdelUser); }; } else { $canShowField = function ($field) use($file) { return !$file->isDeleted($field); }; } $user = isset($prop['user']); $userid = isset($prop['userid']); if ($user || $userid) { if ($file->isDeleted(File::DELETED_USER)) { $vals['userhidden'] = true; $anyHidden = true; } if ($canShowField(File::DELETED_USER)) { if ($user) { $vals['user'] = $file->getUser(); } if ($userid) { $vals['userid'] = $file->getUser('id'); } if (!$file->getUser('id')) { $vals['anon'] = true; } } } // This is shown even if the file is revdelete'd in interface // so do same here. if (isset($prop['size']) || isset($prop['dimensions'])) { $vals['size'] = intval($file->getSize()); $vals['width'] = intval($file->getWidth()); $vals['height'] = intval($file->getHeight()); $pageCount = $file->pageCount(); if ($pageCount !== false) { $vals['pagecount'] = $pageCount; } // length as in how many seconds long a video is. $length = $file->getLength(); if ($length) { // Call it duration, because "length" can be ambiguous. $vals['duration'] = (double) $length; } } $pcomment = isset($prop['parsedcomment']); $comment = isset($prop['comment']); if ($pcomment || $comment) { if ($file->isDeleted(File::DELETED_COMMENT)) { $vals['commenthidden'] = true; $anyHidden = true; } if ($canShowField(File::DELETED_COMMENT)) { if ($pcomment) { $vals['parsedcomment'] = Linker::formatComment($file->getDescription(File::RAW), $file->getTitle()); } if ($comment) { $vals['comment'] = $file->getDescription(File::RAW); } } } $canonicaltitle = isset($prop['canonicaltitle']); $url = isset($prop['url']); $sha1 = isset($prop['sha1']); $meta = isset($prop['metadata']); $extmetadata = isset($prop['extmetadata']); $commonmeta = isset($prop['commonmetadata']); $mime = isset($prop['mime']); $mediatype = isset($prop['mediatype']); $archive = isset($prop['archivename']); $bitdepth = isset($prop['bitdepth']); $uploadwarning = isset($prop['uploadwarning']); if ($uploadwarning) { $vals['html'] = SpecialUpload::getExistsWarning(UploadBase::getExistsWarning($file)); } if ($file->isDeleted(File::DELETED_FILE)) { $vals['filehidden'] = true; $anyHidden = true; } if ($anyHidden && $file->isDeleted(File::DELETED_RESTRICTED)) { $vals['suppressed'] = true; } if (!$canShowField(File::DELETED_FILE)) { //Early return, tidier than indenting all following things one level return $vals; } if ($canonicaltitle) { $vals['canonicaltitle'] = $file->getTitle()->getPrefixedText(); } if ($url) { if (!is_null($thumbParams)) { $mto = $file->transform($thumbParams); self::$transformCount++; if ($mto && !$mto->isError()) { $vals['thumburl'] = wfExpandUrl($mto->getUrl(), PROTO_CURRENT); // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted // thumbnail sizes for the thumbnail actual size if ($mto->getUrl() !== $file->getUrl()) { $vals['thumbwidth'] = intval($mto->getWidth()); $vals['thumbheight'] = intval($mto->getHeight()); } else { $vals['thumbwidth'] = intval($file->getWidth()); $vals['thumbheight'] = intval($file->getHeight()); } if (isset($prop['thumbmime']) && $file->getHandler()) { list(, $mime) = $file->getHandler()->getThumbType($mto->getExtension(), $file->getMimeType(), $thumbParams); $vals['thumbmime'] = $mime; } } elseif ($mto && $mto->isError()) { $vals['thumberror'] = $mto->toText(); } } $vals['url'] = wfExpandUrl($file->getFullURL(), PROTO_CURRENT); $vals['descriptionurl'] = wfExpandUrl($file->getDescriptionUrl(), PROTO_CURRENT); } if ($sha1) { $vals['sha1'] = wfBaseConvert($file->getSha1(), 36, 16, 40); } if ($meta) { wfSuppressWarnings(); $metadata = unserialize($file->getMetadata()); wfRestoreWarnings(); if ($metadata && $version !== 'latest') { $metadata = $file->convertMetadataVersion($metadata, $version); } $vals['metadata'] = $metadata ? self::processMetaData($metadata, $result) : null; } if ($commonmeta) { $metaArray = $file->getCommonMetaArray(); $vals['commonmetadata'] = $metaArray ? self::processMetaData($metaArray, $result) : array(); } if ($extmetadata) { // Note, this should return an array where all the keys // start with a letter, and all the values are strings. // Thus there should be no issue with format=xml. $format = new FormatMetadata(); $format->setSingleLanguage(!$opts['multilang']); $format->getContext()->setLanguage($opts['language']); $extmetaArray = $format->fetchExtendedMetadata($file); if ($opts['extmetadatafilter']) { $extmetaArray = array_intersect_key($extmetaArray, array_flip($opts['extmetadatafilter'])); } $vals['extmetadata'] = $extmetaArray; } if ($mime) { $vals['mime'] = $file->getMimeType(); } if ($mediatype) { $vals['mediatype'] = $file->getMediaType(); } if ($archive && $file->isOld()) { $vals['archivename'] = $file->getArchiveName(); } if ($bitdepth) { $vals['bitdepth'] = $file->getBitDepth(); } return $vals; }
private function getThumbSuffix(File $file, $expectedWidth, $expectedHeight, $crop) { $originalHeight = $file->getHeight(); $originalWidth = $file->getWidth(); $originalRatio = $originalWidth / $originalHeight; $ratio = $expectedWidth / $expectedHeight; if ($originalRatio > $ratio) { $width = round($originalHeight * $ratio); $height = $originalHeight; } else { $width = $originalWidth; $height = round($originalWidth / $ratio); } $width = $width > $expectedWidth ? $expectedWidth : $width; $left = 0; $right = $originalWidth; $top = round($originalHeight * $crop); $bottom = $top + $height; return "{$width}px-{$left},{$right},{$top},{$bottom}"; }
/** * Get width of this item * * @return type */ public function getWidth() { if ($this->file) { $width = $this->file->getWidth(); if ($width) { return $width; } } return $this->config()->insert_width; }
/** Validate and merge scale parameters with handler thumb parameters, give error if invalid. * * We do this later than getScale, since we need the image * to know which handler, since handlers can make their own parameters. * @param File $image Image that params are for. * @param array $thumbParams thumbnail parameters from getScale * @param string $otherParams of otherParams (iiurlparam). * @return Array of parameters for transform. */ protected function mergeThumbParams($image, $thumbParams, $otherParams) { if (!isset($thumbParams['width']) && isset($thumbParams['height'])) { // Populate the width with the image's width, so only the height restriction applies $thumbParams['width'] = $image->getWidth(); } if (!$otherParams) { return $thumbParams; } $p = $this->getModulePrefix(); $h = $image->getHandler(); if (!$h) { $this->setWarning('Could not create thumbnail because ' . $image->getName() . ' does not have an associated image handler'); return $thumbParams; } $paramList = $h->parseParamString($otherParams); if (!$paramList) { // Just set a warning (instead of dieUsage), as in many cases // we could still render the image using width and height parameters, // and this type of thing could happen between different versions of // handlers. $this->setWarning("Could not parse {$p}urlparam for " . $image->getName() . '. Using only width and height'); return $thumbParams; } if (isset($paramList['width'])) { if (intval($paramList['width']) != intval($thumbParams['width'])) { $this->setWarning("Ignoring width value set in {$p}urlparam ({$paramList['width']}) " . "in favor of width value derived from {$p}urlwidth/{$p}urlheight ({$thumbParams['width']})"); } } foreach ($paramList as $name => $value) { if (!$h->validateParam($name, $value)) { $this->dieUsage("Invalid value for {$p}urlparam ({$name}={$value})", "urlparam"); } } return $thumbParams + $paramList; }