/**
  * Returns information to summarize an article with a snippet of text and a picture if applicable.
  */
 public function blurb()
 {
     wfProfileIn(__METHOD__);
     $idStr = $this->request->getVal('ids');
     $ids = explode(',', $idStr);
     $summary = array();
     # Iterate through each title per wiki ID
     foreach ($ids as $id) {
         $title = Title::newFromID($id);
         if (empty($title)) {
             $summary[$this->wg->CityId]['error'][] = "Unable to find title for ID {$id}";
             break;
         }
         $service = new ArticleService($id);
         $snippet = $service->getTextSnippet();
         $imageServing = new ImageServing(array($id), 200, array('w' => 2, 'h' => 1));
         $images = $imageServing->getImages(1);
         // get just one image per article
         $imageURL = '';
         if (isset($images[$id])) {
             $imageURL = $images[$id][0]['url'];
         }
         $summary[$id] = array('wiki' => $this->wg->Sitename, 'wikiUrl' => $this->wg->Server, 'titleDBkey' => $title->getPrefixedDBkey(), 'titleText' => $title->getFullText(), 'articleId' => $title->getArticleID(), 'imageUrl' => $imageURL, 'url' => $title->getFullURL(), 'snippet' => $snippet);
     }
     wfProfileOut(__METHOD__);
     $this->summary = $summary;
 }
 public function getForMap()
 {
     $pageName = $this->request->getVal('title');
     $oTitle = Title::newFromText($pageName);
     if (empty($oTitle) || !$oTitle->exists()) {
         return array();
     }
     $pageId = $oTitle->getArticleId();
     // TODO: getImages() are not cached
     $imageServing = new ImageServing(array($pageId), 100, array('w' => 1, 'h' => 1));
     $images = $imageServing->getImages(1);
     if (!empty($images[$pageId][0]['url'])) {
         $imageUrl = $images[$pageId][0]['url'];
     } else {
         $imageUrl = '';
     }
     $oArticleService = F::Build('ArticleService');
     $oArticleService->setArticleById($pageId);
     $textSnippet = $oArticleService->getTextSnippet(120);
     $strPos = mb_strrpos($textSnippet, ' ');
     $textSnippet = mb_substr($textSnippet, 0, $strPos);
     $textSnippet .= ' ...';
     $this->setVal('title', $oTitle->getText());
     $this->setVal('imgUrl', $imageUrl);
     $this->setVal('articleUrl', $oTitle->getLocalUrl());
     $this->setVal('textSnippet', $textSnippet);
 }
Пример #3
0
 public function execute()
 {
     global $wgRequest;
     wfProfileIn(__METHOD__);
     extract($this->extractRequestParams());
     $imageServing = new ImageServing(array($Id), $Size, array("w" => $Size, "h" => $Height));
     foreach ($imageServing->getImages(1) as $key => $value) {
         $tmpTitle = Title::newFromText($value[0]['name'], NS_FILE);
         $image = wfFindFile($tmpTitle);
         // BugId:31460 ForeignAPIFile does not support loading metadata from the file itself.
         // Note, that ForeignAPIFile::getPath() is a dommy method and always returns false, so
         // the 'File not found' dieUsage() call in the next if block is inevitable for ForeignAPIFile objects.
         if ($FailOnFileNotFound && false == $image instanceof ForeignAPIFile) {
             $image->loadFromFile();
             // side effect forces isMissing() check to fail if file really does not exist
         }
         if (!($image instanceof File && $image->exists()) || $image->isMissing() || $image->mime == 'unknown/unknown') {
             $this->dieUsage('File not found', 'filenotfound');
         }
         $width = $image->getWidth();
         $height = $image->getHeight();
         $imageUrl = $imageServing->getUrl($image->getName(), $width, $height);
     }
     $result = $this->getResult();
     $result->addValue('image', $this->getModuleName(), $imageUrl);
     $result->addValue('imagepage', $this->getModuleName(), $tmpTitle->getFullUrl());
     wfProfileOut(__METHOD__);
 }
 /**
  * @brief Returns an array containing result from Image Serving
  *
  * @requestParam Array $ids an array of Article IDs from which to retrieve images
  * @requestParam int $width the desired thumbnail width in pixels
  * @requestParam mixed $height the desired thumbnail height in pixels or an array of proportions (@see ImageServing::getImages)
  * @requestParam int $count the maximum number of images to retrieve for each Article ID
  *
  * @responseParam Array $result a multi-dimensional array whith the Article ID as the key and an array of image URL's as the values
  */
 public function getImages()
 {
     $this->response->setFormat('json');
     if (!$this->wg->User->isAllowed('read')) {
         $this->setVal('status', 'error');
         $this->setVal('result', 'User is not allowed to read');
         return true;
     }
     $ids = $this->getVal('ids');
     if (!is_array($ids)) {
         $this->setVal('status', 'error');
         $this->setVal('result', 'ids list needs to be an array');
         return true;
     }
     foreach ($ids as $key => $val) {
         $ids[$key] = (int) $ids[$key];
     }
     $height = $this->getVal('height');
     if (!is_array($height)) {
         $height = (int) $height;
     }
     $width = (int) $this->getVal('width');
     $count = (int) $this->getVal('count');
     if (!is_array($height) && $height < 1 || $count < 1 || $width < 1 || count($ids) < 1) {
         $this->setVal('status', 'error');
         $this->setVal('result', 'height, width, count and the total of passed in ID\'s need to be bigger than 0');
         return true;
     }
     $is = new ImageServing($ids, $width, $height);
     $this->setVal('status', 'ok');
     $this->setVal('result', $is->getImages($count));
 }
Пример #5
0
 public function execute()
 {
     $title = $this->getOption('title');
     $dryRun = true;
     # don't store results in database
     $this->output("Parsing '" . $title . "'...");
     $time = microtime(true);
     $title = Title::newFromText($title);
     if (!$title->exists()) {
         $this->error('Given title does not exist', 1);
     }
     $article = new Article($title);
     $images = ImageServingHelper::buildAndGetIndex($article, false, $dryRun);
     $time = microtime(true) - $time;
     $this->output(" done in " . round($time, 4) . " sec\n");
     $this->output("\nImages found: " . count($images) . "\n\n");
     $this->output(implode("\n", $images) . "\n");
     // get filtered list of images
     global $wgAllowMemcacheReads;
     $wgAllowMemcacheReads = false;
     $im = new ImageServing(array($title->getArticleID()), 32, 32);
     $ret = $im->getImages(20);
     $images = reset($ret);
     $this->output("\nImages list as returned by ImageServing (min size: 32x32 px):\n");
     foreach ($images as $image) {
         $this->output("* {$image['name']}\n");
     }
 }
Пример #6
0
 private function checkCrop(LocalFile $image)
 {
     $im = new ImageServing(null, 150);
     $crop = $im->getUrl($image, 250, 250);
     // take 250x250 square from original image and scale it down to 150px (width)
     $this->assertContains('150px-0%2C251%2C0%2C250-', $crop, 'Cropped URL is correct');
     $this->assertTrue(Http::get($crop, 'default', ['noProxy' => true]) !== false, 'Crop should return HTTP 200 - ' . $crop);
 }
Пример #7
0
 public static function uploadNews($image, $name, $url)
 {
     global $wgSitename;
     $is = new ImageServing(array(), 90);
     $thumb_url = $is->getThumbnails(array($image));
     $thumb_url = array_pop($thumb_url);
     $thumb_url = $thumb_url['url'];
     $params = array('$IMGNAME' => $name, '$ARTICLE_URL' => $url, '$WIKINAME' => $wgSitename, '$IMG_URL' => $url, '$EVENTIMG' => $thumb_url);
     self::pushEvent(self::$messageName, $params, __CLASS__);
 }
 /**
  * Return first image from an article, matched criteria
  * @param $title
  * @param $width
  * @return null|Title
  */
 protected static function getFirstArticleImageLargerThan($title, $width, $height)
 {
     $imageServing = new ImageServing([$title->getArticleID()], $width, $height);
     $out = $imageServing->getImages(1);
     if (!empty($out)) {
         ///used reset instead direct call because we can get hashmap from ImageServing driver.
         $first = reset($out);
         $name = $first[0]['name'];
         return Title::newFromText($name, NS_FILE);
     }
     return null;
 }
Пример #9
0
 /**
  * @author Federico "Lox" Lucignano <*****@*****.**>
  *
  * Implementation of a parser function
  */
 public static function parseTag($input, $args, $parser)
 {
     $relatedTitle = null;
     $relatedImage = null;
     $relatedUrl = null;
     if (!empty($args[TOPLIST_ATTRIBUTE_RELATED])) {
         self::$mAttributes[TOPLIST_ATTRIBUTE_RELATED] = $args[TOPLIST_ATTRIBUTE_RELATED];
         $relatedTitle = Title::newFromText($args[TOPLIST_ATTRIBUTE_RELATED]);
         $relatedUrl = $relatedTitle->getLocalUrl();
     }
     if (!empty($args[TOPLIST_ATTRIBUTE_PICTURE])) {
         self::$mAttributes[TOPLIST_ATTRIBUTE_PICTURE] = $args[TOPLIST_ATTRIBUTE_PICTURE];
         if (!empty(self::$mAttributes[TOPLIST_ATTRIBUTE_PICTURE])) {
             $source = new ImageServing(null, 200);
             $result = $source->getThumbnails(array(self::$mAttributes[TOPLIST_ATTRIBUTE_PICTURE]));
             if (!empty($result[self::$mAttributes[TOPLIST_ATTRIBUTE_PICTURE]])) {
                 $relatedImage = $result[self::$mAttributes[TOPLIST_ATTRIBUTE_PICTURE]];
                 if (empty($relatedUrl)) {
                     $title = Title::newFromText($relatedImage['name'], NS_FILE);
                     $relatedUrl = $title->getLocalURL();
                 }
             }
         }
     }
     self::$mAttributes[TOPLIST_ATTRIBUTE_DESCRIPTION] = '';
     if (!empty($args[TOPLIST_ATTRIBUTE_DESCRIPTION])) {
         self::$mAttributes[TOPLIST_ATTRIBUTE_DESCRIPTION] = $args[TOPLIST_ATTRIBUTE_DESCRIPTION];
     }
     if (!empty(self::$mList)) {
         $list = self::$mList;
         self::$mList = null;
     } else {
         $list = TopList::newFromTitle($parser->mTitle);
     }
     if (!empty($list)) {
         $template = new EasyTemplate(dirname(__FILE__) . "/templates/");
         if ($relatedTitle instanceof Title) {
             $relatedTitleData = array('localURL' => $relatedTitle->getLocalURL(), 'text' => $relatedTitle->getText());
         } else {
             $relatedTitleData = null;
         }
         $template->set_vars(array('list' => $list, 'listTitle' => $list->getTitle()->getText(), 'relatedTitleData' => $relatedTitleData, 'relatedImage' => $relatedImage, 'attribs' => self::$mAttributes, 'relatedUrl' => $relatedUrl, 'description' => self::$mAttributes[TOPLIST_ATTRIBUTE_DESCRIPTION]));
         self::$mOutput = $template->render('list');
         // remove whitespaces to avoid extra <p> tags
         self::$mOutput = preg_replace("#[\n\t]+#", '', self::$mOutput);
     } else {
         self::$mOutput = '';
     }
     return self::$mOutput;
 }
Пример #10
0
	function testSize() {
		global $IP;
		
		$is = new ImageServing(array(1), 100, array("w" => 1, "h" => 1));
		$this->assertEquals( '100px-56,237,0,180', $is->getCut( 290, 180 ) );
		$this->assertEquals( '100px-68,285,0,216', $is->getCut( 350, 216 ) );
		
		$is = new ImageServing(array(1), 270, array("w" => 3, "h" => 1));
		$this->assertEquals( '270px-0,428,57,200', $is->getCut( 428, 285 ) );
		$this->assertEquals( '270px-0,669,119,342', $is->getCut( 669, 593 ) );
		
		$is = new ImageServing(array(1), 200, array("w" => 2, "h" => 1));
		$this->assertEquals( '200px-0,314,65,222', $is->getCut( 314, 654 ) );
		$this->assertEquals( '200px-0,572,36,322', $is->getCut( 572, 355 ) );
	
	}
Пример #11
0
 public function testCropping()
 {
     // requested crop size is 50 x 50
     $im = new ImageServing(null, 50);
     $file = wfFindFile(self::FILE_NAME);
     // pass dimensions of full size image
     $cropUrl = $im->getUrl($file, $file->getWidth(), $file->getHeight());
     $this->assertContains('/firefly/images/8/89/Wiki-wordmark.png/revision/latest/', $cropUrl);
     $this->assertContains('/width/50/', $cropUrl);
     // verify crop response
     $res = Http::get($cropUrl, 'default', ['noProxy' => true]);
     $this->assertTrue($res !== false, "<{$cropUrl}> should return HTTP 200");
     // verify crop size
     $this->tmpFile = tempnam(wfTempDir(), 'img');
     file_put_contents($this->tmpFile, $res);
     list($tmpWidth, $tmpHeight) = getimagesize($this->tmpFile);
     $this->assertEquals(50, $tmpWidth, 'expected crop width not matched - ' . $cropUrl);
     $this->assertEquals(49, $tmpHeight, 'expected crop height not matched - ' . $cropUrl);
 }
Пример #12
0
 /**
  * See functions below for expected URL params
  */
 public function execute()
 {
     global $wgRequest, $wgCacheBuster;
     wfProfileIn(__METHOD__);
     extract($this->extractRequestParams());
     // Allow optionally using a prefixed-title instead of the page_id.
     if (empty($Id)) {
         $title = Title::newFromText($Title);
         if (is_object($title)) {
             $Id = $title->getArticleID();
         }
     }
     $article = Article::newFromID($Id);
     if (is_object($article)) {
         // Automatically follow redirects.
         if ($article->isRedirect()) {
             $title = $article->followRedirect();
             if (is_object($title)) {
                 // if this is not an object, then we're pretty unlikely to get any good image matches, but more likely to get them for the original ID.
                 $Id = $title->getArticleID();
             }
         }
         $imageUrl = null;
         $imageServing = new ImageServing(array($Id));
         foreach ($imageServing->getImages(1) as $key => $value) {
             $imgTitle = Title::newFromText($value[0]['name'], NS_FILE);
             $imgFile = wfFindFile($imgTitle);
             if (!empty($imgFile)) {
                 $imageUrl = wfReplaceImageServer($imgFile->getFullUrl(), $wgCacheBuster);
             }
         }
         $result = $this->getResult();
         if (empty($imageUrl)) {
             $result->addValue('image', "error", "No good, representiative image was found for this page.");
             // TODO: i18n
         } else {
             $result->addValue('image', $this->getModuleName(), $imageUrl);
         }
     }
     wfProfileOut(__METHOD__);
 }
Пример #13
0
 function execute($article_id = null, $limit = "", $offset = "", $show = true)
 {
     global $wgRequest, $wgOut, $wgTitle, $wgUser;
     if (!$wgUser->isAllowed('imageservingtest')) {
         throw new PermissionsError('imageservingtest');
     }
     $this->size = 200;
     $this->prop = array("w" => 2, "h" => 1);
     switch ($wgRequest->getVal("option", 1)) {
         case "2":
             $this->size = 270;
             $this->prop = array("w" => 3, "h" => 1);
             break;
         case "3":
             $this->size = 100;
             $this->prop = array("w" => 1, "h" => 1);
             break;
     }
     if ($wgRequest->getVal("article", "") != "") {
         $title = Title::newFromText($wgRequest->getVal("article"), NS_MAIN);
         $test = new ImageServing(array($title->getArticleId()), $this->size, $this->prop);
         foreach ($test->getImages(20) as $value) {
             $wgOut->addHTML("<b>" . $title->getText() . "</b><br><br>");
             foreach ($value as $value2) {
                 $wgOut->addHTML("<img src='{$value2['url']}' /> <br>");
                 $wgOut->addHTML($value2['name'] . "<br>");
             }
         }
         return;
     }
     $wgOut->addHTML(Xml::element("a", array("href" => $wgTitle->getLocalURL("option=1")), wfMsg('imageserving-option1')) . "<br>");
     $wgOut->addHTML(Xml::element("a", array("href" => $wgTitle->getLocalURL("option=2")), wfMsg('imageserving-option2')) . "<br>");
     $wgOut->addHTML(Xml::element("a", array("href" => $wgTitle->getLocalURL("option=3")), wfMsg('imageserving-option3')) . "<br>");
     if (empty($limit) && empty($offset)) {
         list($limit, $offset) = wfCheckLimits();
     }
     /** removed reference to deprecated mechanism of Mostvisitedpages
      *  right now operation of ImageServing Test is not very clear
      *  TODO: provide clearer way of using ImageServingTest (BugId:97236)
      */
 }
Пример #14
0
 /**
  * @param array $wikiInfo
  * @param int $width Image width
  * @param int $height Image height
  * @return array
  */
 protected function getImageData($wikiInfo, $width = null, $height = null)
 {
     $imageName = $wikiInfo['image'];
     $crop = $width != null || $height != null;
     $width = $width !== null ? $width : static::DEFAULT_WIDTH;
     $height = $height !== null ? $height : static::DEFAULT_HEIGHT;
     $imgWidth = null;
     $imgHeight = null;
     $img = wfFindFile($imageName);
     if ($img instanceof WikiaLocalFile) {
         //found on en-corporate wiki
         $imgWidth = $img->getWidth();
         $imgHeight = $img->getHeight();
         if ($crop) {
             //get original image if no cropping
             $imageServing = new ImageServing(null, $width, $height);
             $imgUrl = $imageServing->getUrl($img, $width, $height);
         } else {
             $imgUrl = $img->getFullUrl();
         }
     } else {
         $f = $this->findGlobalFileImage($imageName, $wikiInfo['lang'], $wikiInfo['id']);
         if ($f && $f->exists()) {
             $imgWidth = $f->getWidth();
             $imgHeight = $f->getHeight();
             if ($crop) {
                 $globalTitle = $f->getTitle();
                 $imageService = new ImagesService();
                 $response = $imageService->getImageSrc($globalTitle->getCityId(), $globalTitle->getArticleID(), $width, $height);
                 $imgUrl = $response['src'];
             } else {
                 $imgUrl = $f->getUrl();
             }
         }
     }
     if (isset($imgUrl)) {
         return ['image' => $imgUrl, 'original_dimensions' => ['width' => $imgWidth, 'height' => $imgHeight]];
     }
     return ['image' => ''];
 }
 /**
  * Returns image or snippet for the category on id basis.
  * Uses in modified getArticle
  *
  * @param $iCategoryId int category pageId
  * @return array
  */
 protected function getCategoryImageOrSnippet($iCategoryId)
 {
     $title = Title::newFromID($iCategoryId);
     $sCategoryDBKey = $title->getDBKey();
     // tries to get image from images in category
     $result = CategoryDataService::getAlphabetical($sCategoryDBKey, NS_FILE, 1);
     if (!empty($result)) {
         $counter = 0;
         foreach ($result as $item) {
             if ($counter > F::App()->wg->maxCategoryExhibitionSubcatChecks) {
                 break;
             }
             $imageServing = new ImageServing(array($item['page_id']), $this->thumbWidth, array("w" => $this->thumbWidth, "h" => $this->thumbHeight));
             $itemTitle = Title::newFromID($item['page_id']);
             $image = wfFindFile($itemTitle);
             if (!empty($image)) {
                 $imageSrc = wfReplaceImageServer($image->getThumbUrl($imageServing->getCut($image->width, $image->height) . "-" . $image->getName()));
                 return array('imageUrl' => (string) $imageSrc, 'snippetText' => '');
             }
             $counter++;
         }
     }
     // if no images found, tries to get image or snippet from artice
     unset($result);
     $result = CategoryDataService::getAlphabetical($sCategoryDBKey, NS_MAIN, 10);
     if (!empty($result)) {
         $counter = 0;
         $snippetText = '';
         $imageUrl = '';
         foreach ($result as $item) {
             if ($counter > F::App()->wg->maxCategoryExhibitionSubcatChecks) {
                 break;
             }
             $imageUrl = $this->getImageFromPageId($item['page_id']);
             if (!empty($imageUrl)) {
                 break;
             }
             if (empty($snippetText)) {
                 $snippetService = new ArticleService($item['page_id']);
                 $snippetText = $snippetService->getTextSnippet();
             }
             $counter++;
         }
         return array('imageUrl' => $imageUrl, 'snippetText' => $snippetText);
     } else {
         return array('imageUrl' => '', 'snippetText' => '');
     }
 }
Пример #16
0
 public function saveSettings($settings, $cityId = null)
 {
     global $wgCityId, $wgUser;
     $cityId = empty($cityId) ? $wgCityId : $cityId;
     // Verify wordmark length ( CONN-116 )
     if (!empty($settings['wordmark-text'])) {
         $settings['wordmark-text'] = trim($settings['wordmark-text']);
     }
     if (empty($settings['wordmark-text'])) {
         // Do not save wordmark if its empty.
         unset($settings['wordmark-text']);
     } else {
         if (mb_strlen($settings['wordmark-text']) > 50) {
             $settings['wordmark-text'] = mb_substr($settings['wordmark-text'], 0, 50);
         }
     }
     if (isset($settings['favicon-image-name']) && strpos($settings['favicon-image-name'], 'Temp_file_') === 0) {
         $temp_file = new LocalFile(Title::newFromText($settings['favicon-image-name'], 6), RepoGroup::singleton()->getLocalRepo());
         $file = new LocalFile(Title::newFromText(self::FaviconImageName, 6), RepoGroup::singleton()->getLocalRepo());
         $file->upload($temp_file->getPath(), '', '');
         $temp_file->delete('');
         Wikia::invalidateFavicon();
         $settings['favicon-image-url'] = $file->getURL();
         $settings['favicon-image-name'] = $file->getName();
         $file->repo->forceMaster();
         $history = $file->getHistory(1);
         if (count($history) == 1) {
             $oldFaviconFile = array('url' => $history[0]->getURL(), 'name' => $history[0]->getArchiveName());
         }
     }
     if (isset($settings['wordmark-image-name']) && strpos($settings['wordmark-image-name'], 'Temp_file_') === 0) {
         $temp_file = new LocalFile(Title::newFromText($settings['wordmark-image-name'], 6), RepoGroup::singleton()->getLocalRepo());
         $file = new LocalFile(Title::newFromText(self::WordmarkImageName, 6), RepoGroup::singleton()->getLocalRepo());
         $file->upload($temp_file->getPath(), '', '');
         $temp_file->delete('');
         $settings['wordmark-image-url'] = $file->getURL();
         $settings['wordmark-image-name'] = $file->getName();
         $file->repo->forceMaster();
         $history = $file->getHistory(1);
         if (count($history) == 1) {
             $oldFile = array('url' => $history[0]->getURL(), 'name' => $history[0]->getArchiveName());
         }
     }
     if (isset($settings['background-image-name']) && strpos($settings['background-image-name'], 'Temp_file_') === 0) {
         $temp_file = new LocalFile(Title::newFromText($settings['background-image-name'], 6), RepoGroup::singleton()->getLocalRepo());
         $file = new LocalFile(Title::newFromText(self::BackgroundImageName, 6), RepoGroup::singleton()->getLocalRepo());
         $file->upload($temp_file->getPath(), '', '');
         $temp_file->delete('');
         $settings['background-image'] = $file->getURL();
         $settings['background-image-name'] = $file->getName();
         $settings['background-image-width'] = $file->getWidth();
         $settings['background-image-height'] = $file->getHeight();
         $imageServing = new ImageServing(null, 120, array("w" => "120", "h" => "65"));
         $settings['user-background-image'] = $file->getURL();
         $settings['user-background-image-thumb'] = wfReplaceImageServer($file->getThumbUrl($imageServing->getCut($file->getWidth(), $file->getHeight(), "origin") . "-" . $file->getName()));
         $file->repo->forceMaster();
         $history = $file->getHistory(1);
         if (count($history) == 1) {
             $oldBackgroundFile = array('url' => $history[0]->getURL(), 'name' => $history[0]->getArchiveName());
         }
     }
     $reason = wfMsg('themedesigner-reason', $wgUser->getName());
     // update history
     if (!empty($GLOBALS[self::WikiFactoryHistory])) {
         $history = $GLOBALS[self::WikiFactoryHistory];
         $lastItem = end($history);
         $revisionId = intval($lastItem['revision']) + 1;
     } else {
         $history = array();
         $revisionId = 1;
     }
     // #140758 - Jakub
     // validation
     // default color values
     foreach (ThemeDesignerHelper::getColorVars() as $sColorVar => $sDefaultValue) {
         if (!isset($settings[$sColorVar]) || !ThemeDesignerHelper::isValidColor($settings[$sColorVar])) {
             $settings[$sColorVar] = $sDefaultValue;
         }
     }
     // update WF variable with current theme settings
     WikiFactory::setVarByName(self::WikiFactorySettings, $cityId, $settings, $reason);
     // add entry
     $history[] = array('settings' => $settings, 'author' => $wgUser->getName(), 'timestamp' => wfTimestampNow(), 'revision' => $revisionId);
     // limit history size to last 10 changes
     $history = array_slice($history, -self::HistoryItemsLimit);
     if (count($history) > 1) {
         for ($i = 0; $i < count($history) - 1; $i++) {
             if (isset($oldFaviconFile) && isset($history[$i]['settings']['favicon-image-name'])) {
                 if ($history[$i]['settings']['favicon-image-name'] == self::FaviconImageName) {
                     $history[$i]['settings']['favicon-image-name'] = $oldFaviconFile['name'];
                     $history[$i]['settings']['favicon-image-url'] = $oldFaviconFile['url'];
                 }
             }
             if (isset($oldFile) && isset($history[$i]['settings']['wordmark-image-name'])) {
                 if ($history[$i]['settings']['wordmark-image-name'] == self::WordmarkImageName) {
                     $history[$i]['settings']['wordmark-image-name'] = $oldFile['name'];
                     $history[$i]['settings']['wordmark-image-url'] = $oldFile['url'];
                 }
             }
             if (isset($oldBackgroundFile) && isset($history[$i]['settings']['background-image-name'])) {
                 if ($history[$i]['settings']['background-image-name'] == self::BackgroundImageName) {
                     $history[$i]['settings']['background-image-name'] = $oldBackgroundFile['name'];
                 }
             }
         }
     }
     WikiFactory::setVarByName(self::WikiFactoryHistory, $cityId, $history, $reason);
 }
 public function getThumbnails($articleIds = null, $width = null)
 {
     wfProfileIn(__METHOD__);
     $articleIds = !empty($articleIds) ? $articleIds : $this->getVal('articleIds');
     $width = !empty($width) ? $width : $this->getVal('width');
     $source = new ImageServing($articleIds, $width, array("w" => 3, "h" => 2));
     $result = $source->getImages(1);
     $this->setVal('thumbnails', $result);
     wfProfileOut(__METHOD__);
     return $result;
 }
 /**
  * Returns image from page.
  * @param $mPageId int page id
  * @return string - image url
  */
 protected function getImageFromPageId($mPageId)
 {
     if (!is_array($mPageId)) {
         $mPageId = array($mPageId);
     }
     $imageServing = new ImageServing($mPageId, $this->thumbWidth, array("w" => $this->thumbWidth, "h" => $this->thumbHeight));
     $imageUrl = '';
     foreach ($imageServing->getImages(1) as $value) {
         if (!empty($value[0]['name'])) {
             $tmpTitle = Title::newFromText($value[0]['name'], NS_FILE);
             $image = wfFindFile($tmpTitle);
             if (empty($image)) {
                 return '';
             }
             $imageUrl = wfReplaceImageServer($image->getThumbUrl($imageServing->getCut($image->getWidth(), $image->getHeight()) . "-" . $image->getName()));
         }
     }
     return $imageUrl;
 }
 function execute($par)
 {
     function purgeInput($elem)
     {
         $val = trim($elem);
         return !empty($val);
     }
     wfProfileIn(__METHOD__);
     global $wgExtensionsPath, $wgJsMimeType, $wgSupressPageSubtitle, $wgRequest, $wgOut, $wgUser;
     // set basic headers
     $this->setHeaders();
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         wfProfileOut(__METHOD__);
         return;
     }
     //Check blocks
     if ($wgUser->isBlocked()) {
         wfProfileOut(__METHOD__);
         throw new UserBlockedError($wgUser->getBlock());
     }
     if (!F::app()->checkSkin('oasis')) {
         $this->getOutput()->showErrorPage('error', 'toplists-oasis-only');
         wfProfileOut(__METHOD__);
         return;
     }
     if (!$this->userCanExecute($wgUser)) {
         $this->displayRestrictionError();
         wfProfileOut(__METHOD__);
         return;
     }
     // include resources (css and js)
     $wgOut->addStyle(AssetsManager::getInstance()->getSassCommonURL('/extensions/wikia/TopLists/css/editor.scss'));
     $wgOut->addScript("<script type=\"{$wgJsMimeType}\" src=\"{$wgExtensionsPath}/wikia/TopLists/js/editor.js\"></script>\n");
     //hide specialpage subtitle in Oasis
     $wgSupressPageSubtitle = true;
     TopListHelper::clearSessionItemsErrors();
     $errors = array();
     $listName = null;
     $relatedArticleName = null;
     $description = null;
     $selectedPictureName = null;
     $selectedImage = null;
     $imageTitle = null;
     $items = null;
     $userCanEditItems = $userCanDeleteItems = true;
     if ($wgRequest->wasPosted()) {
         $listName = $wgRequest->getText('list_name');
         $relatedArticleName = $wgRequest->getText('related_article_name');
         $selectedPictureName = $wgRequest->getText('selected_picture_name');
         $description = $wgRequest->getText('description');
         $itemsNames = array_filter($wgRequest->getArray('items_names', array()), 'purgeInput');
         $listItems = array();
         $list = TopList::newFromText($listName);
         $listUrl = null;
         if (!empty($selectedPictureName)) {
             //check image
             $imageTitle = Title::newFromText($selectedPictureName, NS_FILE);
             if (empty($imageTitle)) {
                 $errors['selected_picture_name'] = array(wfMsg('toplists-error-invalid-picture'));
             } else {
                 $text = $imageTitle->getText();
                 $source = new ImageServing(null, 120, array("w" => 3, "h" => 2));
                 $result = $source->getThumbnails(array($imageTitle->getText()));
                 if (!empty($result[$text])) {
                     $selectedImage = $result[$text];
                 }
             }
         }
         if (!$list) {
             $errors['list_name'] = array(wfMsg('toplists-error-invalid-title'));
         } else {
             $title = $list->getTitle();
             $listName = $title->getText();
             $listUrl = $title->getFullUrl();
             if (!empty($relatedArticleName)) {
                 $title = Title::newFromText($relatedArticleName);
                 if (empty($title)) {
                     $errors['related_article_name'] = array(wfMsg('toplists-error-invalid-title'));
                 } else {
                     $setResult = $list->setRelatedArticle($title);
                     if ($setResult !== true) {
                         foreach ($setResult as $errorTuple) {
                             $errors['related_article_name'][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                         }
                     }
                 }
             }
             if (!empty($selectedImage)) {
                 $setResult = $list->setPicture($imageTitle);
                 if ($setResult !== true) {
                     foreach ($setResult as $errorTuple) {
                         $errors['selected_picture_name'][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                     }
                 }
             }
             if (!empty($description)) {
                 $list->setDescription($description);
             }
             $checkResult = $list->checkForProcessing(TOPLISTS_SAVE_CREATE);
             if ($checkResult !== true) {
                 foreach ($checkResult as $errorTuple) {
                     $errors['list_name'][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                 }
             } else {
                 //first check all the items and then save the list, saving items happens only after this
                 $alreadyProcessed = array();
                 foreach ($itemsNames as $index => $itemName) {
                     $lcName = strtolower($itemName);
                     $index++;
                     //index 0 refers to the empty template item in the form
                     if (in_array($lcName, $alreadyProcessed)) {
                         $errors["item_{$index}"] = array(wfMsg('toplists-error-duplicated-entry'));
                     } else {
                         $alreadyProcessed[] = $lcName;
                         $listItem = $list->createItem();
                         if (empty($listItem)) {
                             $errors["item_{$index}"] = array(wfMsg('toplists-error-invalid-title'));
                         } else {
                             $listItem->setNewContent($itemName);
                             $checkResult = $listItem->checkForProcessing(TOPLISTS_SAVE_CREATE, null, TOPLISTS_SAVE_CREATE);
                             if ($checkResult !== true) {
                                 foreach ($checkResult as $errorTuple) {
                                     $errors["item_{$index}"][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                                 }
                             } else {
                                 $listItems[] = $listItem;
                             }
                         }
                     }
                 }
                 if (empty($errors)) {
                     $saveResult = $list->save();
                     if ($saveResult !== true) {
                         foreach ($saveResult as $errorTuple) {
                             $errors['list_name'] = array(wfMsg($errorTuple['msg'], $errorTuple['params']));
                         }
                     } else {
                         //save items, in this case errors go in session and are displayed in the redirected edit specialpage
                         $unsavedItemNames = array();
                         $itemsErrors = array();
                         foreach ($listItems as $item) {
                             $saveResult = $item->save();
                             if ($saveResult !== true) {
                                 $unsavedItemNames[] = $item->getNewContent();
                                 $counter = 0;
                                 foreach ($saveResult as $errorTuple) {
                                     $itemsErrors[] = array(wfMsg($errorTuple['msg'], $errorTuple['params']));
                                     $counter++;
                                 }
                             } else {
                                 $item->getTitle()->invalidateCache();
                             }
                         }
                         //update page's cache, items where added
                         $list->invalidateCache();
                         if (empty($itemsErrors)) {
                             $wgOut->redirect($listUrl);
                         } else {
                             TopListHelper::setSessionItemsErrors($listName, $unsavedItemNames, $itemsErrors);
                             $specialPageTitle = Title::newFromText('EditTopList', NS_SPECIAL);
                             $wgOut->redirect($specialPageTitle->getFullUrl() . '/' . $list->getTitle()->getPrefixedURL());
                         }
                     }
                 }
             }
         }
         foreach ($itemsNames as $item) {
             $items[] = array('type' => 'new', 'value' => $item);
         }
     } elseif (!empty($par)) {
         $title = Title::newFromText($par);
         if (!empty($title)) {
             $listName = $title->getText();
         }
     }
     //show at least 3 items by default, if not enough fill in with empty ones
     for ($x = !empty($items) ? count($items) : 0; $x < 3; $x++) {
         $items[] = array('type' => 'new', 'value' => null);
     }
     // pass data to template
     $template = new EasyTemplate(dirname(__FILE__) . '/../templates');
     $template->set_vars(array('mode' => 'create', 'listName' => $listName, 'relatedArticleName' => $relatedArticleName, 'description' => $description, 'selectedImage' => $selectedImage, 'errors' => $errors, 'items' => array_merge(array(array('type' => 'template', 'value' => null)), $items), 'userCanEditItems' => $userCanEditItems, 'userCanDeleteItems' => $userCanDeleteItems));
     // render template
     $wgOut->addHTML($template->render('editor'));
     wfProfileOut(__METHOD__);
 }
Пример #20
0
 /**
  * @static
  * @return AjaxResponse
  */
 public static function getImageData()
 {
     global $wgRequest;
     $ret = array('result' => false);
     $titleText = $wgRequest->getText('title');
     if (!empty($titleText)) {
         $title = Title::newFromText($titleText);
         if (!empty($title) && $title->exists()) {
             $articleId = $title->getArticleId();
             $source = new ImageServing(array($articleId), 120, array("w" => 3, "h" => 2));
             $result = $source->getImages(1);
             if (!empty($result[$articleId][0])) {
                 $ret = array_merge(array('result' => true), $result[$articleId][0]);
             }
         }
     }
     $json = json_encode($ret);
     $response = new AjaxResponse($json);
     $response->setContentType('application/json; charset=utf-8');
     return $response;
 }
 function execute($editListName)
 {
     global $wgExtensionsPath, $wgJsMimeType, $wgSupressPageSubtitle, $wgRequest, $wgOut, $wgUser;
     wfProfileIn(__METHOD__);
     // set basic headers
     $this->setHeaders();
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         wfProfileOut(__METHOD__);
         return;
     }
     //Check blocks
     if ($wgUser->isBlocked()) {
         wfProfileOut(__METHOD__);
         throw new UserBlockedError($wgUser->getBlock());
     }
     if (!F::app()->checkSkin('oasis')) {
         $this->getOutput()->showErrorPage('error', 'toplists-oasis-only');
         wfProfileOut(__METHOD__);
         return;
     }
     if (!$this->userCanExecute($wgUser)) {
         $this->displayRestrictionError();
         wfProfileOut(__METHOD__);
         return;
     }
     if (empty($editListName)) {
         $this->_redirectToCreateSP();
     }
     // include resources (css and js)
     $wgOut->addStyle(AssetsManager::getInstance()->getSassCommonURL('/extensions/wikia/TopLists/css/editor.scss'));
     $wgOut->addScript("<script type=\"{$wgJsMimeType}\" src=\"{$wgExtensionsPath}/wikia/TopLists/js/editor.js\"></script>\n");
     //hide specialpage subtitle in Oasis
     $wgSupressPageSubtitle = true;
     $errors = array();
     $listName = null;
     $listUrl = null;
     $relatedArticleName = null;
     $description = null;
     $selectedPictureName = null;
     $items = array();
     $removedItems = array();
     $list = TopList::newFromText($editListName);
     /** @var $list TopList */
     if (empty($list) || !$list->exists()) {
         $this->_redirectToCreateSP($editListName);
     } else {
         $title = $list->getTitle();
         $listName = $title->getText();
         $description = $list->getDescription();
         $listUrl = $title->getFullURL();
         $listItems = $list->getItems();
         $userCanEditItems = $list->checkUserItemsRight('edit');
         $userCanDeleteItems = $list->checkUserItemsRight('delete');
         if ($wgRequest->wasPosted()) {
             TopListHelper::clearSessionItemsErrors();
             $relatedArticleName = $wgRequest->getText('related_article_name');
             $selectedDescription = $wgRequest->getText('description');
             $selectedPictureName = $wgRequest->getText('selected_picture_name');
             $itemsNames = $wgRequest->getArray('items_names', array());
             $removedItems = $userCanDeleteItems ? $wgRequest->getArray('removed_items', array()) : array();
             //handle related article
             $title = $list->getRelatedArticle();
             $curValue = null;
             if (!empty($title)) {
                 $curValue = $title->getText();
             }
             $relatedArticleChanged = $curValue != $relatedArticleName;
             if ($relatedArticleChanged) {
                 if (!empty($relatedArticleName)) {
                     $title = Title::newFromText($relatedArticleName);
                     if (empty($title)) {
                         $errors['related_article_name'] = array(wfMsg('toplists-error-invalid-title'));
                     } else {
                         $setResult = $list->setRelatedArticle($title);
                         if ($setResult !== true) {
                             foreach ($setResult as $errorTuple) {
                                 $errors['related_article_name'][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                             }
                         }
                     }
                 } else {
                     $list->setRelatedArticle(null);
                 }
             }
             //handle picture
             $title = $list->getPicture();
             $curValue = null;
             if (!empty($title)) {
                 $curValue = $title->getText();
             }
             $selectedPictureChanged = $curValue != $selectedPictureName;
             if ($selectedPictureChanged) {
                 if (!empty($selectedPictureName)) {
                     $title = Title::newFromText($selectedPictureName, NS_FILE);
                     if (empty($title)) {
                         $errors['selected_picture_name'][] = wfMsg('toplists-error-invalid-picture');
                     } else {
                         $setResult = $list->setPicture($title);
                         if ($setResult !== true) {
                             foreach ($setResult as $errorTuple) {
                                 $errors['selected_picture_name'][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                             }
                         }
                     }
                 } else {
                     $list->setPicture(null);
                 }
             }
             //handle description
             $curValue = null;
             if (!empty($description)) {
                 $curValue = $description;
             }
             $selectedDescriptionChanged = $curValue != $selectedDescription;
             if ($selectedDescriptionChanged) {
                 $list->setDescription($selectedDescription);
             }
             //check the list for processability
             $checkResult = $list->checkForProcessing(TOPLISTS_SAVE_UPDATE);
             if ($checkResult !== true) {
                 foreach ($checkResult as $errorTuple) {
                     $errors['list_name'][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                 }
             }
             //filter input
             foreach ($itemsNames as $index => $item) {
                 $itemsNames[$index] = trim($item);
             }
             //collect existing items and related updates, filter out the removed ones (processed separately)
             $counter = 0;
             foreach ($listItems as $index => $item) {
                 if (!in_array($index, $removedItems)) {
                     $items[] = array('type' => 'existing', 'value' => $itemsNames[$counter], 'index' => $index, 'changed' => false, 'object' => null);
                     if (empty($itemsNames[$counter])) {
                         $errors['item_' . ($counter + 1)][] = wfMsg('toplists-error-empty-item-name');
                     } elseif ($userCanEditItems && $listItems[$index]->getArticle()->getContent() != $itemsNames[$counter]) {
                         $listItems[$index]->setNewContent($itemsNames[$counter]);
                         $items[$counter]['object'] = $listItems[$index];
                         $items[$counter]['changed'] = true;
                     }
                     $counter++;
                 }
             }
             //collect new items, filter out the empty ones
             $splitAt = count($listItems) - count($removedItems);
             $newItemsNames = array_filter(array_slice($itemsNames, $splitAt));
             foreach ($newItemsNames as $index => $item) {
                 $items[] = array('type' => 'new', 'value' => $item, 'changed' => true);
                 $newItem = $list->createItem();
                 $newItem->setNewContent($newItemsNames[$index]);
                 $items[$counter]['object'] = $newItem;
                 $counter++;
             }
             //check items for processing
             $usedNames = array();
             foreach ($items as $index => $item) {
                 $lcName = strtolower($item['value']);
                 if (in_array($lcName, $usedNames)) {
                     $errors['item_' . ++$index][] = wfMsg('toplists-error-duplicated-entry');
                 } else {
                     $usedNames[] = $lcName;
                 }
                 if ($item['changed'] && !empty($item['object'])) {
                     if ($item['type'] == 'new') {
                         $checkResult = $item['object']->checkForProcessing(TOPLISTS_SAVE_AUTODETECT, null, TOPLISTS_SAVE_CREATE);
                     } else {
                         $checkResult = $item['object']->checkForProcessing();
                     }
                     if ($checkResult !== true) {
                         foreach ($checkResult as $errorTuple) {
                             $errors['item_' . ++$index][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                         }
                     }
                 }
             }
             //with no errors or no save required, proceed with items
             $itemTouched = 0;
             if (empty($errors)) {
                 foreach ($items as $index => $item) {
                     if ($item['changed'] && !empty($item['object'])) {
                         $saveResult = $item['object']->save();
                         if ($saveResult !== true) {
                             foreach ($saveResult as $errorTuple) {
                                 $errors['item_' . ++$index][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                             }
                         } else {
                             $item['object']->getTitle()->invalidateCache();
                             $itemTouched++;
                         }
                     }
                 }
                 //purge items removed from the list
                 foreach ($removedItems as $index) {
                     $item = $listItems[$index];
                     if (is_object($item) && $item instanceof TopListItem) {
                         $removeResult = $item->remove();
                     } else {
                         // if item does not exist it means that it's deleted anyway
                         $removeResult = true;
                     }
                     if ($removeResult !== true) {
                         $items[] = array('type' => 'existing', 'value' => $item->getArticle()->getContent(), 'index' => $counter, 'changed' => false, 'object' => $item);
                         $counter++;
                         foreach ($removeResult as $errorTuple) {
                             $errors['item_' . $counter][] = wfMsg($errorTuple['msg'], $errorTuple['params']);
                         }
                     } else {
                         $itemTouched++;
                     }
                 }
             }
             //if no errors proceed with saving, list comes first
             if (empty($errors) || $itemTouched) {
                 if ($relatedArticleChanged || $selectedPictureChanged || $selectedDescriptionChanged || $itemTouched) {
                     $saveResult = $list->save();
                     if ($saveResult !== true) {
                         foreach ($saveResult as $errorTuple) {
                             $errors['list_name'] = array(wfMsg($errorTuple['msg'], $errorTuple['params']));
                         }
                     }
                 }
                 //invalidate caches
                 $list->invalidateCache();
                 if (empty($errors)) {
                     $wgOut->redirect($listUrl);
                 }
             }
         } else {
             $title = $list->getRelatedArticle();
             if (!empty($title)) {
                 $relatedArticleName = $title->getText();
             }
             $title = $list->getPicture();
             if (!empty($title)) {
                 $selectedPictureName = $title->getText();
             }
             foreach ($listItems as $index => $item) {
                 $items[] = array('type' => 'existing', 'value' => $item->getArticle()->getContent(), 'index' => $index);
             }
             list($sessionListName, $failedItemsNames, $sessionErrors) = TopListHelper::getSessionItemsErrors();
             if ($listName == $sessionListName && !empty($failedItemsNames)) {
                 $counter = count($items);
                 foreach ($failedItemsNames as $index => $itemName) {
                     $items[] = array('type' => 'new', 'value' => $itemName);
                     $errors['item_' . $counter++] = $sessionErrors[$index];
                 }
             }
             TopListHelper::clearSessionItemsErrors();
         }
         $selectedImage = null;
         if (!empty($selectedPictureName)) {
             $source = new ImageServing(null, 120, array("w" => 3, "h" => 2));
             $result = $source->getThumbnails(array($selectedPictureName));
             if (!empty($result[$selectedPictureName])) {
                 $selectedImage = $result[$selectedPictureName];
             }
         }
         //show at least 3 items by default, if not enough fill in with empty ones
         for ($x = !empty($items) ? count($items) : 0; $x < 3; $x++) {
             $items[] = array('type' => 'new', 'value' => null);
         }
         // pass data to template
         $template = new EasyTemplate(dirname(__FILE__) . '/../templates');
         $template->set_vars(array('mode' => 'update', 'listName' => $listName, 'listUrl' => $listUrl, 'relatedArticleName' => $relatedArticleName, 'description' => $description, 'selectedImage' => $selectedImage, 'errors' => $errors, 'items' => array_merge(array(array('type' => 'template', 'value' => null)), $items), 'removedItems' => $removedItems, 'userCanEditItems' => $userCanEditItems, 'userCanDeleteItems' => $userCanDeleteItems));
         // render template
         $wgOut->addHTML($template->render('editor'));
     }
     wfProfileOut(__METHOD__);
 }
 /**
  * Render slider preview
  *
  * @author Jakub Kurcek
  */
 public static function renderSliderPreview($slider)
 {
     global $wgTitle, $wgParser;
     wfProfileIn(__METHOD__);
     // use global instance of parser (RT #44689 / RT #44712)
     $parserOptions = new ParserOptions();
     wfDebug(__METHOD__ . "\n" . print_r($slider, true));
     // render slider images
     foreach ($slider['images'] as &$image) {
         $imageTitle = Title::newFromText($image['name'], NS_FILE);
         $image['pageTitle'] = '';
         $img = wfFindFile($imageTitle);
         if (is_object($img) && $imageTitle->getNamespace() == NS_FILE) {
             // render thumbnail
             $is = new ImageServing(null, self::STRICT_IMG_WIDTH_PREV, array('w' => self::STRICT_IMG_WIDTH_PREV, 'h' => self::STRICT_IMG_HEIGHT_PREV));
             $image['thumbnailBg'] = $is->getUrl($image['name'], $img->getWidth(), $img->getHeight());
         } elseif (is_object($imageTitle)) {
             $image['pageTitle'] = $imageTitle->getText();
         }
         $image['isFileTypeVideo'] = WikiaFileHelper::isFileTypeVideo($img);
         //need to use parse() - see RT#44270
         $image['caption'] = $wgParser->parse($image['caption'], $wgTitle, $parserOptions)->getText();
         // remove <p> tags from parser caption
         if (preg_match('/^<p>(.*)\\n?<\\/p>\\n?$/sU', $image['caption'], $m)) {
             $image['caption'] = $m[1];
         }
     }
     wfDebug(__METHOD__ . '::after' . "\n" . print_r($slider, true));
     // render gallery HTML preview
     $template = new EasyTemplate(dirname(__FILE__) . '/templates');
     $template->set_vars(array('height' => self::STRICT_IMG_HEIGHT_PREV, 'slider' => $slider, 'width' => self::STRICT_IMG_WIDTH_PREV));
     $html = $template->render('sliderPreview');
     wfProfileOut(__METHOD__);
     return $html;
 }
Пример #23
0
 /**
  * Returns data needed to render marker for a given place on a map with multiple places
  *
  * This method returns article's URL, text snippet and an image for current place
  *
  * TODO: add caching
  */
 public function getForMap()
 {
     if ($this->isEmpty()) {
         return false;
     }
     wfProfileIn(__METHOD__);
     $pageId = $this->getPageId();
     $oTitle = F::build('Title', array($pageId), 'newFromID');
     if (empty($oTitle) || !$oTitle->exists()) {
         wfProfileOut(__METHOD__);
         return array();
     }
     // TODO: getImages() are not cached
     $imageServing = new ImageServing(array($pageId), 100, array('w' => 1, 'h' => 1));
     $images = $imageServing->getImages(1);
     if (!empty($images[$pageId][0]['url'])) {
         $imageUrl = $images[$pageId][0]['url'];
     } else {
         $imageUrl = '';
     }
     $oArticleService = F::Build('ArticleService');
     $oArticleService->setArticleById($pageId);
     $textSnippet = $oArticleService->getTextSnippet(120);
     $strPos = mb_strrpos($textSnippet, ' ');
     $textSnippet = mb_substr($textSnippet, 0, $strPos);
     $textSnippet .= ' ...';
     $ret = array('lat' => $this->getLat(), 'lan' => $this->getLon(), 'label' => $oTitle->getText(), 'imageUrl' => $imageUrl, 'articleUrl' => $oTitle->getLocalUrl(), 'textSnippet' => $textSnippet);
     wfProfileOut(__METHOD__);
     return $ret;
 }
Пример #24
0
 /**
  * Proxy function for fetching thumbnails from ImageServing.
  *
  * @param $articles array List of article ids
  * @return array
  */
 protected function findImages($articles)
 {
     wfProfileIn(__METHOD__);
     $articleIds = array_keys($articles);
     $result = array();
     foreach ($articleIds as $articleId) {
         $imageServing = new ImageServing(array($articleId), $this->confThumbWidth, $this->confThumbProportion);
         $images = $imageServing->getImages(1);
         if (!empty($images) && !empty($images[$articleId]) && is_array($images[$articleId])) {
             $result[$articleId] = array_shift($images);
         }
     }
     wfProfileOut(__METHOD__);
     return $result;
 }
Пример #25
0
 /**
  * @param array $wikiIds
  * @param int $imageWidth
  * @param int $imageHeight
  *
  * @return mixed|null|string
  */
 public function getWikiImages($wikiIds, $imageWidth, $imageHeight = self::IMAGE_HEIGHT_KEEP_ASPECT_RATIO)
 {
     $images = array();
     try {
         $db = wfGetDB(DB_SLAVE, array(), $this->wg->ExternalSharedDB);
         $tables = array('city_visualization');
         $fields = array('city_id', 'city_lang_code', 'city_main_image');
         $conds = array('city_id' => $wikiIds);
         $results = $db->select($tables, $fields, $conds, __METHOD__, array(), array());
         while ($row = $results->fetchObject()) {
             $promoImage = PromoImage::fromPathname($row->city_main_image);
             $promoImage->ensureCityIdIsSet($row->city_id);
             $file = $promoImage->corporateFileByLang($row->city_lang_code);
             if ($file->exists()) {
                 $imageServing = new ImageServing(null, $imageWidth, $imageHeight);
                 $images[$row->city_id] = ImagesService::overrideThumbnailFormat($imageServing->getUrl($file, $file->getWidth(), $file->getHeight()), ImagesService::EXT_JPG);
             }
         }
     } catch (Exception $e) {
         Wikia::log(__METHOD__, false, $e->getMessage());
     }
     return $images;
 }
Пример #26
0
 function formatResult($skin, $result)
 {
     global $wgRequest, $wgTitle;
     $res = false;
     if (empty($this->show)) {
         $this->data[$result->title] = array('value' => $result->value, 'namespace' => $result->namespace);
     } else {
         $title = Title::newFromText($result->title, $result->namespace);
         $article_name = $title->getText();
         if ($title) {
             $result->title = Xml::element("a", array("href" => $title->getLocalURL()), $title->getFullText() . "(" . $title->getArticleId() . ")");
             $is = new ImageServing(array($title->getArticleId()), $this->size, $this->prop);
             $result->title .= "<div>";
             foreach ($is->getImages(1) as $key => $value) {
                 foreach ($value as $value2) {
                     $result->title .= "<img src='{$value2['url']}' /> <br>";
                     $result->title .= $value2['name'] . "<br>";
                 }
             }
             $result->title .= Xml::element("a", array("href" => $wgTitle->getLocalURL("option=" . $wgRequest->getVal("option", 1) . "&article=" . $article_name)), wfMsg("imageserving-showall")) . "<br>";
             $result->title .= "</div>";
         }
         $res = wfSpecialList($result->title, $result->value);
     }
     return $res;
 }
Пример #27
0
 protected function afterGet($pages, $limit)
 {
     global $wgContentNamespaces, $wgEnableRelatedPagesUnionSelectQueries, $wgUser;
     wfProfileIn(__METHOD__);
     // ImageServing extension enabled, get images
     $imageServing = new ImageServing(array_keys($pages), 200, array('w' => 2, 'h' => 1));
     $images = $imageServing->getImages(1);
     // get just one image per article
     // TMP: always remove last article to get a text snippeting working example
     // macbre: removed as requested by Angie
     //$images = array_slice($images, 0, $limit-1, true);
     foreach ($pages as $pageId => $data) {
         if (isset($images[$pageId])) {
             $image = $images[$pageId][0];
             $data['imgUrl'] = $image['url'];
             $this->pushData($data);
         } else {
             // no images, get a text snippet
             $data['text'] = $this->getArticleSnippet($pageId);
             if ($data['text'] != '') {
                 $this->pushData($data);
             }
         }
         if (count($this->getData()) >= $limit) {
             break;
         }
     }
     wfProfileOut(__METHOD__);
 }
	private function getTemplateData($element) {

		if (! isset($element['file'])) return array();

		$file = $element['file'];
		// crop the images correctly using extension:imageservice
		$is = new ImageServing(array(), self::THUMB_SIZE);
		$thumb_url = $is->getThumbnails(array($file));
		$thumb_url = array_pop($thumb_url);
		$thumb_url = $thumb_url['url'];
		$userName = $file->user_text;

		$retval = array (
			"file_url" => $element['url'],
			"image_url" => $file->getUrl(),
			"thumb_url" => $thumb_url,
			"image_filename" => $file->getTitle()->getFullText(),
			"user_href" => Wikia::link(Title::newFromText($userName, NS_USER), $userName),
			"links" => $this->getLinkedFiles($file->name),
			"isVideoThumb"  => WikiaFileHelper::isFileTypeVideo( $file ),
			"date" => wfTimestamp(TS_ISO_8601, $file->timestamp));
		return $retval;
	}
Пример #29
0
 function testHasArticleIdsEmpty()
 {
     $is = new ImageServing(null, 200, 100);
     $articles = array(1234);
     $this->assertFalse($is->hasArticleIds($articles));
 }
Пример #30
0
 /**
  * @param $outputModel
  * @return mixed
  */
 protected function getImage($wikiId, $articleId)
 {
     $dbName = '';
     try {
         $row = \WikiFactory::getWikiByID($wikiId);
         if ($row) {
             $dbName = $row->city_dbname;
             if (!empty($dbName)) {
                 $db = wfGetDB(DB_SLAVE, [], $dbName);
                 // throws if database does not exits.
                 $imageServing = new \ImageServing([$articleId], self::IMAGE_SIZE, self::IMAGE_SIZE, $db);
                 $isResult = $imageServing->getImages(1);
                 $images = isset($isResult[$articleId]) ? $isResult[$articleId] : false;
                 if ($images && sizeof($images) > 0) {
                     $imageName = $images[0]['name'];
                     $file = \GlobalFile::newFromText($imageName, $wikiId);
                     if ($file->exists()) {
                         return $imageServing->getUrl($file, $file->getWidth(), $file->getHeight());
                     }
                 }
             }
         }
     } catch (\DBConnectionError $ex) {
         // Swallow this exception. there is no simple way of telling if database does not exist other than catching exception.
         // Or am I wrong ?
         \Wikia::log(__METHOD__, false, "Cannot get database connection to " . $dbName);
     }
     return null;
 }