public function getListForVisualization($langCode)
 {
     return WikiaDataAccess::cache($this->getCollectionsListVisualizationCacheKey($langCode), 6 * 60 * 60, function () use($langCode) {
         $list = $this->getList($langCode);
         foreach ($list as &$collection) {
             if (!empty($collection['sponsor_hero_image'])) {
                 $collection['sponsor_hero_image'] = ImagesService::getLocalFileThumbUrlAndSizes($collection['sponsor_hero_image'], 0, ImagesService::EXT_JPG);
             }
             if (!empty($collection['sponsor_image'])) {
                 $collection['sponsor_image'] = ImagesService::getLocalFileThumbUrlAndSizes($collection['sponsor_image'], 0, ImagesService::EXT_JPG);
             }
             $collection['wikis'] = $this->getWikisFromCollection($collection['id']);
         }
         return $list;
     });
 }
Exemplo n.º 2
0
 public static function uploadFile(PromoImage $promoImage, GlobalTitle $sourceTitle, $sourceWikiId)
 {
     $sourceFile = \GlobalFile::newFromText($sourceTitle->getText(), $sourceWikiId);
     if (!$sourceFile->exists()) {
         echo "sourceFile doesn't exist" . PHP_EOL;
         return false;
     }
     $sourceImageUrl = $sourceFile->getUrl();
     $user = User::newFromName('WikiaBot');
     $imageData = new stdClass();
     $imageData->name = $promoImage->getPathname();
     $imageData->description = $imageData->comment = wfMessage('wikiahome-image-auto-uploaded-comment')->plain();
     $result = ImagesService::uploadImageFromUrl($sourceImageUrl, $imageData, $user);
     if (!$result['status']) {
         var_dump($result['errors'], $sourceImageUrl);
     }
     return $result['status'];
 }
 /**
  * Get image list
  *
  * @param  integer $userId ID of the user to get the list for
  * @param  string  $from   Timestamp to get images before
  * @return array           List of images
  */
 public function getImageList($userId, $from = null)
 {
     wfProfileIn(__METHOD__);
     $imageList = [];
     $db = $this->getDatawareDB(DB_MASTER);
     $where = ['user_id' => $userId, 'state != ' . ImageReviewStatuses::STATE_DELETED . ' AND state != ' . ImageReviewStatuses::STATE_WIKI_DISABLED];
     $from = wfTimestampOrNull(TS_DB, $from);
     if (!empty($from)) {
         $where[] = 'last_edited < ' . $db->addQuotes($from);
     }
     $result = $db->select(['image_review'], ['wiki_id, page_id, state, flags, priority, last_edited'], $where, __METHOD__, ['ORDER BY' => 'last_edited desc', 'LIMIT' => self::LIMIT_IMAGES]);
     foreach ($result as $row) {
         $img = ImagesService::getImageSrc($row->wiki_id, $row->page_id);
         $wikiRow = WikiFactory::getWikiByID($row->wiki_id);
         $extension = pathinfo(strtolower($img['page']), PATHINFO_EXTENSION);
         $isThumb = true;
         if (empty($img['src'])) {
             // If we don't have a thumb by this point, we still need to display something, fall back to placeholder
             $globalTitle = GlobalTitle::newFromId($row->page_id, $row->wiki_id);
             if (is_object($globalTitle)) {
                 $img['page'] = $globalTitle->getFullUrl();
                 // @TODO this should be taken from the code instead of being hardcoded
                 $img['src'] = '//images.wikia.com/central/images/8/8c/Wikia_image_placeholder.png';
             } else {
                 // This should never happen
                 continue;
             }
         }
         if (in_array($extension, ['gif', 'svg'])) {
             $img = ImagesService::getImageOriginalUrl($row->wiki_id, $row->page_id);
             $isThumb = false;
         }
         $imageList[] = ['wikiId' => $row->wiki_id, 'pageId' => $row->page_id, 'state' => $row->state, 'src' => $img['src'], 'priority' => $row->priority, 'url' => $img['page'], 'isthumb' => $isThumb, 'flags' => $row->flags, 'wiki_url' => isset($wikiRow->city_url) ? $wikiRow->city_url : '', 'user_page' => '', 'last_edited' => $row->last_edited];
     }
     $db->freeResult($result);
     wfProfileOut(__METHOD__);
     return $imageList;
 }
Exemplo n.º 4
0
 protected function getImageSrcByTitle($wikiId, $imageTitle, $imgWidth, $imgHeight)
 {
     return ImagesService::getImageSrcByTitle($wikiId, $imageTitle, $imgWidth, $imgHeight);
 }
Exemplo n.º 5
0
<?php

// get wiki thumbnail and thumbnail tracking
$image = (new PromoImage(PromoImage::MAIN))->setCityId($result['id'])->getPathname();
$isOnWikiMatch = isset($result['onWikiMatch']) && $result['onWikiMatch'];
$thumbTracking = 'class="wiki-thumb-tracking" data-pos="' . $pos . '" data-event="search_click_wiki-thumb"';
$imageURL = ImagesService::getImageSrcByTitle((new CityVisualization())->getTargetWikiId($result['lang_s']), $image, WikiaSearchController::CROSS_WIKI_PROMO_THUMBNAIL_WIDTH, WikiaSearchController::CROSS_WIKI_PROMO_THUMBNAIL_HEIGHT);
if (empty($imageURL)) {
    // display placeholder image if no thumbnail
    $imageURL = $wg->ExtensionsPath . '/wikia/Search/images/wiki_image_placeholder.png';
    $thumbTracking = 'class="wiki-thumb-tracking" data-pos="' . $pos . '" data-event="search_click_wiki-no-thumb"';
}
$service = new Wikia\Search\MediaWikiService();
$pagesMsg = $service->shortnumForMsg($result['articles_i'] ?: 0, 'wikiasearch2-pages');
$imgMsg = $service->shortnumForMsg($result['images_i'] ?: 0, 'wikiasearch2-images');
$videoMsg = $service->shortnumForMsg($result['videos_i'] ?: 0, 'wikiasearch2-videos');
$title = ($sn = $result->getText('sitename_txt')) ? $sn : $result->getText('headline_txt');
$url = $result->getText('url');
?>

<div class="Results exact">
	<p class="result-count subtle">
		<?php 
echo wfMsg('wikiasearch2-exact-result', '<strong>' . $title . '</strong>');
?>
	</p>

	<div class="result">

		<?php 
$trackingData = 'class="result-link" data-pos="' . $pos . '"';
 /**
  * Get first image from slider from selected hub v3
  *
  * @param $cityId hub wiki id
  * @return null|string
  */
 public function getHubV3Images($cityId)
 {
     $imageUrl = null;
     $destSize = $this->getHubsImgWidth() . 'x' . $this->getHubsImgHeight();
     $sliderData = $this->getHubSliderData(['city' => $cityId]);
     if (isset($sliderData['data']['slides'][0]['photoName'])) {
         $imgName = $sliderData['data']['slides'][0]['photoName'];
         $title = GlobalTitle::newFromText($imgName, NS_FILE, $cityId);
         if ($title !== null) {
             $file = new GlobalFile($title);
             if ($file !== null) {
                 $imageUrl = ImagesService::getThumbUrlFromFileUrl($file->getUrl(), $destSize);
             }
         }
     }
     return $imageUrl;
 }
Exemplo n.º 7
0
	protected function uploadImage($imageUrl, $imageName, $wikiId, $isSliderImage = false) {
		wfProfileIn(__METHOD__);

		$success = false;

		//fb#45624
		$user = F::build('User', array('WikiaBot'), 'newFromName');
		$user = ($user instanceof User) ? $user : null;
		$imageData = new stdClass();
		$imageData->name = $imageName;
		$imageData->description = $imageData->comment = wfMsg('wikiahome-image-auto-uploaded-comment');

		$result = ImagesService::uploadImageFromUrl($imageUrl, $imageData, $user);

		if( $isSliderImage ) {
			$statusArrayKey = 'slider-images';
		} else {
			$statusArrayKey = 'main-images';
		}

		if( $result['status'] === true ) {
			$this->okuploads[$statusArrayKey][] = array('city_id' => $wikiId, 'id' => $result['page_id'], 'name' => $imageName);
			echo '.';
			$success = true;
		} else {
			if (!empty($result['errors'][0]['message']) && $result['errors'][0]['message'] === 'filerenameerror') {
				$this->fileexists[$statusArrayKey][] = $imageName;
				echo '!';
			} else {
				$this->faileduploads[$statusArrayKey][] = $imageName;
				echo '.';
			}
		}

		wfProfileOut(__METHOD__);
		return $success;
	}
<?php

// get wiki thumbnail and thumbnail tracking
$isOnWikiMatch = isset($result['onWikiMatch']) && $result['onWikiMatch'];
$imageFileName = PromoImage::fromPathname($result['image_s'])->ensureCityIdIsSet($result['id'])->getPathname();
$imageOriginalURL = ImagesService::getImageSrcByTitle($corporateWikiId, $imageFileName, WikiaSearchController::CROSS_WIKI_PROMO_THUMBNAIL_WIDTH, WikiaSearchController::CROSS_WIKI_PROMO_THUMBNAIL_HEIGHT);
if (!empty($imageOriginalURL)) {
    $imageURL = ImagesService::overrideThumbnailFormat($imageOriginalURL, ImagesService::EXT_JPG);
    $thumbTracking = 'class="wiki-thumb-tracking" data-pos="' . $pos . '" data-event="search_click_wiki-thumb"';
}
if (empty($imageURL)) {
    // display placeholder image if no thumbnail
    $imageURL = $wg->ExtensionsPath . '/wikia/Search/images/wiki_image_placeholder.png';
    $thumbTracking = 'class="wiki-thumb-tracking" data-pos="' . $pos . '" data-event="search_click_wiki-no-thumb"';
}
$service = new Wikia\Search\MediaWikiService();
$pagesMsg = $service->shortnumForMsg($result['articles_i'] ?: 0, 'wikiasearch2-pages');
$imgMsg = $service->shortnumForMsg($result['images_i'] ?: 0, 'wikiasearch2-images');
$videoMsg = $service->shortnumForMsg($result['videos_i'] ?: 0, 'wikiasearch2-videos');
$title = ($sn = $result->getText('sitename_txt')) ? $sn : $result->getText('headline_txt');
$url = $result->getText('url');
?>

<li class="result">
	<?php 
$suffix = $result['exactWikiMatch'] ? "match" : "wiki";
$trackingData = 'class="result-link" data-pos="' . $pos . '" data-event="search_click_' . $suffix . '"';
?>
	<a href="<?php 
echo $url;
?>
 /**
  * @desc Uses ImagesService to create an image URL
  *
  * @param String $imageTitle
  * @param int $width optional
  * @param int $height optional
  *
  * @return bool|null|Object|string
  */
 private function getImage($imageTitle, $width = self::IMG_WIDTH_SMALL, $height = self::IMG_HEIGHT_SMALL)
 {
     return ImagesService::getImageSrcByTitle($this->cityId, $imageTitle, $width, $height);
 }
Exemplo n.º 10
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' => ''];
 }
Exemplo n.º 11
0
if( empty($imageUrl) ) {
	echo 'ERROR: Invalid original image url'."\n";
	exit(3);
}

if( empty($destImageName) ) {
	echo 'ERROR: Invalid destination name'."\n";
	exit(4);
}

if( $sourceWikiId <= 0 ) {
	echo 'ERROR: Invalid source wiki id'."\n";
	exit(5);
}

$imageData = new stdClass();
$imageData->name = $destImageName;
$imageData->description = $imageData->comment = wfMsg('wikiahome-image-auto-uploaded-comment');

$result = ImagesService::uploadImageFromUrl($imageUrl, $imageData, $user);

if( $result['status'] === true ) {
	echo json_encode(array('id' => $result['page_id'], 'name' => $destImageName));
	exit(0);
} else {
	echo 'ERROR: Something went wrong with uploading the image.'."\n";
	print_r($result['errors']);
	exit(7);
}
Exemplo n.º 12
0
 /**
  * method for taking scaled avatars
  * - avatar will be scaled by external image thumbnailer
  * - external image thumbnailer use only width and scale it with the same
  *   proportion as original
  * - currently there's no thumbnail file, it's only cached on varnish and
  *   generated on fly as needed
  *
  * @access public
  * @author Krzysztof Krzyżaniak (eloy)
  *
  * @param width - the width of the thumbnail (height will be same propotion to width as in unscaled image)
  * @param inPurgeFormat - boolean - if true, then the returned URL will be in the format used for purging
  *                                  which means it will use images.wikia.com instead of a CDN hostname.
  *
  *
  * @return string -- url to Avatar
  */
 public function getThumbnail($width, $inPurgeFormat = false)
 {
     if ($inPurgeFormat) {
         $url = $this->getPurgeUrl('/thumb/');
     } else {
         $url = $this->getUrl('/thumb/');
     }
     return ImagesService::getThumbUrlFromFileUrl($url, $width);
 }
Exemplo n.º 13
0
 private function prepareWikisForVisualization($batch)
 {
     foreach ($batch as $slotName => &$wikis) {
         $size = $this->getProcessedWikisImgSizes($slotName);
         foreach ($wikis as &$wiki) {
             if (!empty($wiki['image'])) {
                 $wiki['main_image'] = $wiki['image'];
             }
             $wiki['image'] = ImagesService::overrideThumbnailFormat($this->getImageUrl($wiki['main_image'], $size->width, $size->height), ImagesService::EXT_JPG);
             unset($wiki['main_image']);
         }
     }
     return $batch;
 }
Exemplo n.º 14
0
 /**
  * Get URL for avatar
  *
  * @param string|User $user user name
  * @param int $avatarSize
  * @return String avatar's URL
  */
 static function getAvatarUrl($user, $avatarSize = 20)
 {
     global $wgEnableVignette;
     wfProfileIn(__METHOD__);
     static $avatarsCache;
     if ($user instanceof User) {
         $key = "{$user->getName()}::{$avatarSize}";
     } else {
         // assumes $user is a string with user name
         $key = "{$user}::{$avatarSize}";
     }
     if (isset($avatarsCache[$key])) {
         $avatarUrl = $avatarsCache[$key];
     } else {
         if (!$user instanceof User) {
             $user = self::getUser($user);
         }
         // handle anon users - return default avatar
         if (empty($user) || !class_exists('Masthead')) {
             $avatarUrl = self::getDefaultAvatar($avatarSize);
             wfProfileOut(__METHOD__);
             return $avatarUrl;
         }
         $masthead = Masthead::newFromUser($user);
         // use per-user cachebuster when custom avatar is used
         $cb = !$masthead->isDefault() ? intval($user->getGlobalAttribute('avatar_rev')) : 0;
         if ($wgEnableVignette) {
             $avatarUrl = self::getVignetteUrl($masthead, $avatarSize, $cb);
         } else {
             $avatarUrl = $masthead->getThumbnailPurgeUrl($avatarSize);
             // Make URLs consistent and using no-cookie domain.  We need to pass a
             // stringified zero rather than an actual zero because this function
             // treats them differently o_O  Setting this to string zero matches
             // the anonymous user behavior (BugId:22190)
             $avatarUrl = wfReplaceImageServer($avatarUrl, $cb > 0 ? $cb : "0");
             // make avatars as JPG intead of PNGs / GIF but only when it will be a gain (most likely)
             if (intval($avatarSize) > self::PERFORMANCE_JPEG_THRESHOLD) {
                 $avatarUrl = ImagesService::overrideThumbnailFormat($avatarUrl, ImagesService::EXT_JPG);
             }
         }
         $avatarsCache[$key] = $avatarUrl;
     }
     wfProfileOut(__METHOD__);
     return $avatarUrl;
 }
Exemplo n.º 15
0
 protected function getArticleDetail($wikiId, $articleId)
 {
     $res = ApiService::foreignCall(WikiFactory::IDtoDB($wikiId), ['ids' => $articleId], self::ENDPOINT_DETAILS);
     if (!$res) {
         return [];
     }
     $article = $res['items'][$articleId];
     if (!$article['thumbnail']) {
         $wikiService = $this->getWikiService();
         $article['thumbnail'] = $wikiService->getWikiWordmark($wikiId);
     } else {
         $article['thumbnail'] = ImagesService::getFileUrlFromThumbUrl($article['thumbnail']);
     }
     return ['img' => ['url' => $article['thumbnail'], 'width' => $article['original_dimensions']['width'] < self::MIN_IMAGE_SIZE ? self::MIN_IMAGE_SIZE : $article['original_dimensions']['width'], 'height' => $article['original_dimensions']['height'] < self::MIN_IMAGE_SIZE ? self::MIN_IMAGE_SIZE : $article['original_dimensions']['height']], 'title' => $article['title']];
 }
Exemplo n.º 16
0
 /**
  * @desc returns URL to the cropped thumb of an image
  *
  * @param String $url - image url
  * @param Integer $width desired width of a thumbnail
  * @param Integer $height desired height of a thumbnail
  * @param String $align - crop align (origin || center)
  *
  * @return String - thumbnail URL
  */
 public function createCroppedThumb($url, $width, $height, $align = self::THUMB_ALIGNMENT_CENTER)
 {
     $breakPoint = strrpos($url, '/');
     $baseURL = substr($url, 0, $breakPoint);
     $fileName = substr($url, $breakPoint + 1);
     $deltaY = $align === self::THUMB_ALIGNMENT_CENTER ? self::DELTA_Y_CENTERED : self::DELTA_Y_DEFAULT;
     return ImagesService::getThumbUrlFromFileUrl($baseURL . self::MAP_THUMB_PREFIX . $fileName, $width . 'x' . $height . 'x' . $deltaY);
 }
Exemplo n.º 17
0
 /**
  * @dataProvider getThumbUrlFromFileUrlDataProvider
  */
 public function testGetThumbUrlFromFileUrl($imageUrl, $destSize, $newExtension, $expected)
 {
     $this->assertEquals($expected, ImagesService::getThumbUrlFromFileUrl($imageUrl, $destSize, $newExtension));
 }
Exemplo n.º 18
0
 /**
  * get image list from reviewer id based on the timestamp
  * Note: NOT update image state
  * @param integer $timestamp review_end
  * @return array images
  */
 public function refetchImageListByTimestamp($timestamp)
 {
     wfProfileIn(__METHOD__);
     $db = $this->getDatawareDB(DB_SLAVE);
     // try to re-fetch the previuos set of images
     // TODO: optimize it, so we don't do it on every request
     $review_start = wfTimestamp(TS_DB, $timestamp);
     $result = $db->select(array('image_review'), array('wiki_id, page_id, state, flags, priority'), array('review_start' => $review_start, 'reviewer_id' => $this->user_id), __METHOD__, array('ORDER BY' => 'priority desc, last_edited desc', 'LIMIT' => self::LIMIT_IMAGES));
     $imageList = array();
     while ($row = $db->fetchObject($result)) {
         $img = ImagesService::getImageSrc($row->wiki_id, $row->page_id);
         $wikiRow = WikiFactory::getWikiByID($row->wiki_id);
         $tmp = array('wikiId' => $row->wiki_id, 'pageId' => $row->page_id, 'state' => $row->state, 'src' => $img['src'], 'priority' => $row->priority, 'url' => $img['page'], 'flags' => $row->flags, 'wiki_url' => isset($wikiRow->city_url) ? $wikiRow->city_url : '', 'user_page' => '');
         if (!empty($tmp['src']) && !empty($tmp['url'])) {
             $imageList[] = $tmp;
         }
     }
     $db->freeResult($result);
     WikiaLogger::instance()->info("ImageReviewLog", ['method' => __METHOD__, 'message' => "Refetched " . count($imageList) . " images based on timestamp"]);
     wfProfileOut(__METHOD__);
     return $imageList;
 }
 /**
  * Get saved images for marketing slots
  *
  * @param $marketingSlots
  * @return array
  */
 private function prepareMarketingSlotImages($marketingSlots)
 {
     $marketingImages = [];
     if (!empty($marketingSlots)) {
         foreach ($marketingSlots as $key => $slot) {
             if (!empty($slot['marketing_slot_image'])) {
                 $photo = ImagesService::getLocalFileThumbUrlAndSizes($slot['marketing_slot_image'], 149, ImagesService::EXT_JPG);
                 $marketingImages[$key] = $photo->url;
             }
         }
     }
     return $marketingImages;
 }
Exemplo n.º 20
0
    /**
     * get image list
     * @return array imageList
     */
    public function getImageList($timestamp, $state = ImageReviewStatuses::STATE_UNREVIEWED, $order = self::ORDER_LATEST)
    {
        $this->wf->ProfileIn(__METHOD__);
        // get images
        $db = $this->getDatawareDB(DB_MASTER);
        $result = $db->query('
			SELECT pages.page_title_lower, image_review.wiki_id, image_review.page_id, image_review.state, image_review.flags, image_review.priority
			FROM (
				SELECT image_review.wiki_id, image_review.page_id, image_review.state, image_review.flags, image_review.priority
				FROM `image_review`
				WHERE state = ' . $state . ' AND top_200 = false
				ORDER BY ' . $this->getOrder($order) . '
				LIMIT ' . self::LIMIT_IMAGES_FROM_DB . '
			) as image_review
			LEFT JOIN pages ON (image_review.wiki_id=pages.page_wikia_id) AND (image_review.page_id=pages.page_id)');
        $rows = array();
        $updateWhere = array();
        $iconsWhere = array();
        while ($row = $db->fetchObject($result)) {
            $rows[] = $row;
            $updateWhere[] = "(wiki_id = {$row->wiki_id} and page_id = {$row->page_id})";
        }
        $db->freeResult($result);
        # update records
        if (count($updateWhere) > 0) {
            $review_start = wfTimestamp(TS_DB, $timestamp);
            switch ($state) {
                case ImageReviewStatuses::STATE_QUESTIONABLE:
                    $target_state = ImageReviewStatuses::STATE_QUESTIONABLE_IN_REVIEW;
                    break;
                case ImageReviewStatuses::STATE_REJECTED:
                    $target_state = ImageReviewStatuses::STATE_REJECTED_IN_REVIEW;
                    break;
                default:
                    $target_state = ImageReviewStatuses::STATE_IN_REVIEW;
            }
            $values = array('reviewer_id' => $this->user_id, 'review_start' => $review_start, 'state' => $target_state);
            if ($state == ImageReviewStatuses::STATE_QUESTIONABLE || $state == ImageReviewStatuses::STATE_REJECTED) {
                $values[] = "review_end = '0000-00-00 00:00:00'";
            }
            $db->update('image_review', $values, array(implode(' OR ', $updateWhere)), __METHOD__);
        }
        $db->commit();
        $imageList = $invalidImages = $unusedImages = array();
        foreach ($rows as $row) {
            $record = "(wiki_id = {$row->wiki_id} and page_id = {$row->page_id})";
            if (count($imageList) < self::LIMIT_IMAGES) {
                $img = ImagesService::getImageSrc($row->wiki_id, $row->page_id);
                if (empty($img['src'])) {
                    $invalidImages[] = $record;
                } elseif ('ico' == pathinfo(strtolower($img['src']), PATHINFO_EXTENSION)) {
                    $iconsWhere[] = $record;
                } else {
                    $imageList[] = array('wikiId' => $row->wiki_id, 'pageId' => $row->page_id, 'state' => $row->state, 'src' => $img['src'], 'url' => $img['page'], 'priority' => $row->priority, 'flags' => $row->flags);
                }
            } else {
                $unusedImages[] = $record;
            }
        }
        $commit = false;
        if (count($invalidImages) > 0) {
            $db->update('image_review', array('state' => ImageReviewStatuses::STATE_INVALID_IMAGE), array(implode(' OR ', $invalidImages)), __METHOD__);
            $commit = true;
        }
        if (count($iconsWhere) > 0) {
            $db->update('image_review', array('state' => ImageReviewStatuses::STATE_ICO_IMAGE), array(implode(' OR ', $iconsWhere)), __METHOD__);
            $commit = true;
        }
        if (count($unusedImages) > 0) {
            $db->update('image_review', array('reviewer_id = null', 'state' => $state), array(implode(' OR ', $unusedImages)), __METHOD__);
            $commit = true;
            error_log("ImageReview : returning " . count($unusedImages) . " back to the queue");
        }
        if ($commit) {
            $db->commit();
        }
        error_log("ImageReview : fetched new " . count($imageList) . " images");
        $this->wf->ProfileOut(__METHOD__);
        return $imageList;
    }
 protected function getImageInfo($fileName, $destSize = 0)
 {
     return ImagesService::getLocalFileThumbUrlAndSizes($fileName, $destSize, ImagesService::EXT_JPG);
 }
Exemplo n.º 22
0
 /**
  * @desc Used by WMU to get the image url
  */
 public function getImageDetails()
 {
     if (!$this->checkAccess()) {
         return false;
     }
     wfProfileIn(__METHOD__);
     $fileName = $this->getVal('fileHandler', false);
     if ($fileName) {
         $imageData = ImagesService::getLocalFileThumbUrlAndSizes($fileName, $this->editHubModel->getThumbnailSize(), ImagesService::EXT_JPG);
         $this->fileUrl = $imageData->url;
         $this->imageWidth = $imageData->width;
         $this->imageHeight = $imageData->height;
         $this->fileTitle = $imageData->title;
     }
     wfProfileOut(__METHOD__);
 }
 public function getImageUrl($wikiId, $pageId, $imgSize)
 {
     $data = ImagesService::getImageSrc($wikiId, $pageId, $imgSize);
     $url = !empty($data['src']) ? $data['src'] : null;
     return $url;
 }
Exemplo n.º 24
0
 /**
  * @param integer $destImageWidth
  * @return stdClass (simple stdObject with fields: title, url, width and height)
  */
 public function getImageThumbData($destImageWidth = 0)
 {
     return ImagesService::getLocalFileThumbUrlAndSizes($this->getFileName(), $destImageWidth, ImagesService::EXT_JPG);
 }
Exemplo n.º 25
0
 /**
  * main entry point, create wiki with given parameters
  *
  * @throw CreateWikiException an exception with status of operation set
  */
 public function create()
 {
     global $wgExternalSharedDB, $wgSharedDB, $wgUser;
     $then = microtime(true);
     // Set this flag to ensure that all select operations go against master
     // Slave lag can cause random errors during wiki creation process
     global $wgForceMasterDatabase;
     $wgForceMasterDatabase = true;
     wfProfileIn(__METHOD__);
     if (wfReadOnly()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('DB is read only', self::ERROR_READONLY);
     }
     // check founder
     if ($this->mFounder->isAnon()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Founder is anon', self::ERROR_USER_IN_ANON);
     }
     // check executables
     $status = $this->checkExecutables();
     if ($status != 0) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('checkExecutables() failed', $status);
     }
     // check domains
     $status = $this->checkDomain();
     if ($status != 0) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Check domain failed', $status);
     }
     // prepare all values needed for creating wiki
     $this->prepareValues();
     // prevent domain to be registered more than once
     if (!AutoCreateWiki::lockDomain($this->mDomain)) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Domain name taken', self::ERROR_DOMAIN_NAME_TAKEN);
     }
     // start counting time
     $this->mCurrTime = wfTime();
     // check and create database
     $this->mDBw = wfGetDB(DB_MASTER, array(), $wgExternalSharedDB);
     # central
     ///
     // local database handled is handler to cluster we create new wiki.
     // It doesn't have to be the same like wikifactory cluster or db cluster
     // where Special:CreateWiki exists.
     //
     // @todo do not use hardcoded name, code below is only for test
     //
     // set $activeCluster to false if you want to create wikis on first
     // cluster
     //
     $this->mClusterDB = self::ACTIVE_CLUSTER ? "wikicities_" . self::ACTIVE_CLUSTER : "wikicities";
     $this->mNewWiki->dbw = wfGetDB(DB_MASTER, array(), $this->mClusterDB);
     // database handler, old $dbwTarget
     // check if database is creatable
     // @todo move all database creation checkers to canCreateDatabase
     if (!$this->canCreateDatabase()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('DB exists - ' . $this->mNewWiki->dbname, self::ERROR_DATABASE_ALREADY_EXISTS);
     } else {
         $this->mNewWiki->dbw->query(sprintf("CREATE DATABASE `%s`", $this->mNewWiki->dbname));
         wfDebugLog("createwiki", "Database {$this->mNewWiki->dbname} created\n", true);
     }
     /**
      * create position in wiki.factory
      * (I like sprintf construction, so sue me)
      */
     if (!$this->addToCityList()) {
         wfDebugLog("createwiki", __METHOD__ . ": Cannot set data in city_list table\n", true);
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot add wiki to city_list', self::ERROR_DATABASE_WRITE_TO_CITY_LIST_BROKEN);
     }
     // set new city_id
     $this->mNewWiki->city_id = $this->mDBw->insertId();
     if (empty($this->mNewWiki->city_id)) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot set data in city_list table. city_id is empty after insert', self::ERROR_DATABASE_WIKI_FACTORY_TABLES_BROKEN);
     }
     wfDebugLog("createwiki", __METHOD__ . ": Row added added into city_list table, city_id = {$this->mNewWiki->city_id}\n", true);
     /**
      * add domain and www.domain to the city_domains table
      */
     if (!$this->addToCityDomains()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Cannot set data in city_domains table', self::ERROR_DATABASE_WRITE_TO_CITY_DOMAINS_BROKEN);
     }
     wfDebugLog("createwiki", __METHOD__ . ": Row added into city_domains table, city_id = {$this->mNewWiki->city_id}\n", true);
     /**
      * create image folder
      */
     global $wgEnableSwiftFileBackend;
     if (empty($wgEnableSwiftFileBackend)) {
         wfMkdirParents("{$this->mNewWiki->images_dir}");
         wfDebugLog("createwiki", __METHOD__ . ": Folder {$this->mNewWiki->images_dir} created\n", true);
     }
     // Force initialize uploader user from correct shared db
     $uploader = User::newFromName('CreateWiki script');
     $uploader->getId();
     $oldUser = $wgUser;
     $wgUser = $uploader;
     /**
      * wikifactory variables
      */
     wfDebugLog("createwiki", __METHOD__ . ": Populating city_variables\n", true);
     $this->setWFVariables();
     $tmpSharedDB = $wgSharedDB;
     $wgSharedDB = $this->mNewWiki->dbname;
     $this->mDBw->commit(__METHOD__);
     // commit shared DB changes
     /**
      * we got empty database created, now we have to create tables and
      * populate it with some default values
      */
     wfDebugLog("createwiki", __METHOD__ . ": Creating tables in database\n", true);
     $this->mNewWiki->dbw = wfGetDB(DB_MASTER, array(), $this->mNewWiki->dbname);
     if (!$this->createTables()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Creating tables not finished', self::ERROR_SQL_FILE_BROKEN);
     }
     /**
      * import language starter
      */
     if (!$this->importStarter()) {
         wfProfileOut(__METHOD__);
         throw new CreateWikiException('Starter import failed', self::ERROR_SQL_FILE_BROKEN);
     }
     /**
      * making the wiki founder a sysop/bureaucrat
      */
     wfDebugLog("createwiki", __METHOD__ . ": Create user sysop/bureaucrat for user: {$this->mNewWiki->founderId} \n", true);
     if (!$this->addUserToGroups()) {
         wfDebugLog("createwiki", __METHOD__ . ": Create user sysop/bureaucrat for user: {$this->mNewWiki->founderId} failed \n", true);
     }
     /**
      * init site_stats table (add empty row)
      */
     $this->mNewWiki->dbw->insert("site_stats", array("ss_row_id" => "1"), __METHOD__);
     /**
      * copy default logo
      */
     $res = ImagesService::uploadImageFromUrl(self::CREATEWIKI_LOGO, (object) ['name' => 'Wiki.png'], $uploader);
     if ($res['status'] === true) {
         wfDebugLog("createwiki", __METHOD__ . ": Default logo has been uploaded\n", true);
     } else {
         wfDebugLog("createwiki", __METHOD__ . ": Default logo has not been uploaded - " . print_r($res['errors'], true) . "\n", true);
     }
     /**
      * destroy connection to newly created database
      */
     $this->waitForSlaves(__METHOD__);
     $wgSharedDB = $tmpSharedDB;
     $oHub = WikiFactoryHub::getInstance();
     $oHub->setVertical($this->mNewWiki->city_id, $this->mNewWiki->vertical, "CW Setup");
     wfDebugLog("createwiki", __METHOD__ . ": Wiki added to the vertical: {$this->mNewWiki->vertical} \n", true);
     for ($i = 0; $i < count($this->mNewWiki->categories); $i++) {
         $oHub->addCategory($this->mNewWiki->city_id, $this->mNewWiki->categories[$i]);
         wfDebugLog("createwiki", __METHOD__ . ": Wiki added to the category: {$this->mNewWiki->categories[$i]} \n", true);
     }
     /**
      * define wiki type
      */
     $wiki_type = 'default';
     /**
      * modify variables
      */
     global $wgUniversalCreationVariables;
     if (!empty($wgUniversalCreationVariables) && !empty($wiki_type) && isset($wgUniversalCreationVariables[$wiki_type])) {
         $this->addCustomSettings(0, $wgUniversalCreationVariables[$wiki_type], "universal");
         wfDebugLog("createwiki", __METHOD__ . ": Custom settings added for wiki_type: {$wiki_type} \n", true);
     }
     /**
      * set variables per language
      */
     global $wgLangCreationVariables;
     $langCreationVar = isset($wgLangCreationVariables[$wiki_type]) ? $wgLangCreationVariables[$wiki_type] : $wgLangCreationVariables;
     $this->addCustomSettings($this->mNewWiki->language, $langCreationVar, "language");
     wfDebugLog("createwiki", __METHOD__ . ": Custom settings added for wiki_type: {$wiki_type} and language: {$this->mNewWiki->language} \n", true);
     /**
      * set tags per language and per hub
      * @FIXME the switch is !@#$ creazy, but I didn't find a core function
      */
     $tags = new WikiFactoryTags($this->mNewWiki->city_id);
     $langTag = $this->mNewWiki->language;
     if ($langTag !== 'en') {
         switch ($langTag) {
             case 'pt-br':
                 $langTag = 'pt';
                 break;
             case 'zh-tw':
             case 'zh-hk':
             case 'zh-clas':
             case 'zh-class':
             case 'zh-classical':
             case 'zh-cn':
             case 'zh-hans':
             case 'zh-hant':
             case 'zh-min-':
             case 'zh-min-n':
             case 'zh-mo':
             case 'zh-sg':
             case 'zh-yue':
                 $langTag = 'zh';
                 break;
         }
         $tags->addTagsByName($langTag);
     }
     /**
      * move main page -> this code exists in CreateWikiLocalJob - so it is not needed anymore
      */
     /**
      * Unset database from mNewWiki, because database objects cannot be serialized from MW1.19
      */
     unset($this->mNewWiki->dbw);
     // Restore wgUser
     $wgUser = $oldUser;
     unset($oldUser);
     /**
      * Schedule an async task
      */
     $creationTask = new \Wikia\Tasks\Tasks\CreateNewWikiTask();
     $job_params = new stdClass();
     foreach ($this->mNewWiki as $id => $value) {
         if (!is_object($value)) {
             $job_params->{$id} = $value;
         }
     }
     // BugId:15644 - I need to pass this to CreateWikiLocalJob::changeStarterContributions
     $job_params->sDbStarter = $this->sDbStarter;
     $task_id = (new \Wikia\Tasks\AsyncTaskList())->wikiId($this->mNewWiki->city_id)->prioritize()->add($creationTask->call('postCreationSetup', $job_params))->add($creationTask->call('maintenance', rtrim($this->mNewWiki->url, "/")))->queue();
     wfDebugLog("createwiki", __METHOD__ . ": Local maintenance task added as {$task_id}\n", true);
     $this->info(__METHOD__ . ': done', ['task_id' => $task_id, 'took' => microtime(true) - $then]);
     wfProfileOut(__METHOD__);
 }
 /**
  * @desc This is exactly the same as in WikiaHubsModuleService class
  * and is here only for testing purposes
  *
  * @param $image
  * @param int $destSize
  * @return stdClass
  */
 public function getImageInfo($image, $destSize = 0)
 {
     return ImagesService::getLocalFileThumbUrlAndSizes($image, $destSize, ImagesService::EXT_JPG);
 }