function WidgetBookmark($id)
{
    global $wgRequest, $wgCityId;
    wfProfileIn(__METHOD__);
    $pages = false;
    $id = intval(substr($id, 7));
    // handle AJAX request
    if ($wgRequest->getVal('rs') == 'WidgetFrameworkAjax') {
        $pageId = $wgRequest->getVal('pid');
        $cmd = $wgRequest->getVal('cmd');
        if (!empty($pageId)) {
            switch ($cmd) {
                case 'add':
                    $pages = WidgetBookmarkAddPage($pageId);
                    break;
                case 'remove':
                    $pages = WidgetBookmarkRemovePage($pageId);
                    break;
            }
        }
    }
    if ($pages == false) {
        $pages = WidgetBookmarkGetPages();
    }
    // count pages from current wiki
    $count = 0;
    if (!empty($pages)) {
        // the newest bookmarks on top
        $pages = array_reverse($pages);
        $list = '<ul><!-- ' . count($pages) . ' bookmarks -->';
        foreach ($pages as $page_id => $page) {
            // filter the list by cityId
            if (isset($page['city']) && $page['city'] == $wgCityId) {
                $list .= '<li><a href="' . $page['href'] . '" title="' . htmlspecialchars($page['title']) . '">' . htmlspecialchars(wfShortenText($page['title'], 25)) . '</a>' . '<a class="WidgetBookmarkRemove" onclick="WidgetBookmarkDo(' . $id . ', \'remove\', \'' . $page_id . '\')">x</a></li>';
                $count++;
            }
        }
        $list .= '</ul>';
    }
    if ($count == 0) {
        $list = wfMsg('widget-bookmark-empty');
    }
    // "add bookmark" icon
    $menu = '<div class="WidgetBookmarkMenu">' . '<a class="addBookmark" onclick="WidgetBookmarkDo(' . $id . ', \'add\', wgArticleId ? wgArticleId : wgPageName)" ' . 'title="' . wfMsg('export-addcat') . '">&nbsp;</a></div>';
    wfProfileOut(__METHOD__);
    return $menu . $list;
}
function WidgetProblemReports($id, $params)
{
    // check whether ProblemReports extension is enabled on this wiki
    global $wgProblemReportsEnable;
    if (!isset($wgProblemReportsEnable) || !$wgProblemReportsEnable) {
        return '<em>Extension ProblemReports not enabled on this wiki</em>';
        // fallback message
    }
    $params['limit'] = intval($params['limit']);
    $apiParams = array('wkshowall' => $params['pr_raports_from_this_wikia'] == 0 && WikiaApiQueryProblemReports::userCanDoActions() ? 1 : NULL, 'wktype' => intval($params['pr_table_problem_type']) >= 0 ? intval($params['pr_table_problem_type']) : NULL, 'wkstaff' => $params['show'] == 2 ? 1 : NULL, 'wkarchived' => $params['show'] == 1 ? 1 : NULL, 'wklimit' => $params['limit'] <= 0 || $params['limit'] > 50 ? 25 : $params['limit']);
    $apiParams['action'] = 'query';
    $apiParams['list'] = 'problemreports';
    //print_pre($apiParams);
    $data = WidgetFramework::callAPI($apiParams);
    $count = intval($data['query']['reports']);
    if ($count == 0) {
        return array('title' => wfMsg('problemreports'), 'body' => wfMsg('pr_no_reports'));
    }
    $reports = $data['query']['problemreports'];
    $problemTypes = array(wfMsg('pr_what_problem_spam_short'), wfMsg('pr_what_problem_vandalised_short'), wfMsg('pr_what_problem_incorrect_content_short'), wfMsg('pr_what_problem_software_bug_short'), wfMsg('pr_what_problem_other_short'));
    // list reports
    $items = array();
    //url used for linking to PR ids
    $baseUrl = Title::newFromText('ProblemReports', NS_SPECIAL)->getLocalURL();
    // build params for 'more' link based on this widget's settings
    $urlParams = array();
    if ($params['show'] == 2) {
        $urlParams[] = 'staff=1';
    } elseif ($params['show'] == 1) {
        $urlParams[] = 'archived=1';
    }
    if ($apiParams['wkshowall'] == 1) {
        $urlParams[] = 'showall=1';
    }
    if ($apiParams['wktype'] != NULL) {
        $urlParams[] = 'problem=' . $apiParams['wktype'];
    }
    // smush
    $urlParams = implode('&', $urlParams);
    // apply and build
    $moreUrl = Title::newFromText('ProblemReports', NS_SPECIAL)->getLocalURL($urlParams);
    foreach ($reports as $problem) {
        $date = date('d m Y', strtotime($problem['date']));
        $items[] = array('href' => $baseUrl . '/' . $problem['id'], 'title' => '#' . $problem['id'] . ' - ' . wfMsg('pr_table_date_submitted') . ': ' . $date, 'name' => wfShortenText($problem['title'], 25) . ' [' . $problemTypes[$problem['type']] . ($apiParams['wkshowall'] == 1 ? ' | ' . str_replace(array('http://', '.wikia.com', '.wikia-inc.com'), '', $problem['server']) : '') . ']');
    }
    return array('title' => wfMsg('problemreports') . ' (' . $count . ')', 'body' => WidgetFramework::wrapLinks($items) . WidgetFramework::moreLink($moreUrl));
}
 /**
  * Gets a plain text snippet from an article.  An optional second argument allows a break limit.
  * When given, if the text is greater than $breakLimit, truncate it to $length, if its less than
  * $breakLimit, return the whole snippet.  This allows better snippets for text that is very close
  * in character count to $length.
  *
  * For example if $length=100 and $breakLimit=200 and the source text is 205 characters, the content
  * will be truncated at the word closest to 100 characters.  If the source text is 150 characters,
  * then this method will return all 150 characters.
  *
  * If however we only give one parameter, $length=200 and the source text is 205 characters, we
  * will return text truncated at the word nearest 200 characters, likely only leaving out a single
  * word from the snippet.  This can lead to a strange user experience in some cases (e.g. a user
  * clicks a link in a notification email to see the full edit and finds that there's only one word
  * they weren't able to read from the email)
  *
  * @param integer $length [OPTIONAL] The maximum snippet length, defaults to 100
  * @param integer $breakLimit A breakpoint for showing the full snippet.
  *
  * @return string The plain text snippet, it includes SUFFIX at the end of the string
  * if the length of the article's content is longer than $length, the text will be cut
  * respecting the integrity of the words
  *
  * @throws WikiaException If $length is bigger than MAX_LENGTH
  *
  * @example
  * $service = new ArticleService( $article );
  * $snippet = $service->getTextSnippet( 250, 400 );
  *
  * $service->setArticleById( $title->getArticleID() );
  * $snippet = $service->getTextSnippet( 50 );
  *
  * $service->setArticle( $anotherArticle );
  * $snippet = $service->getTextSnippet();
  */
 public function getTextSnippet($length = 100, $breakLimit = null)
 {
     // don't allow more than the maximum to avoid flooding Memcached
     if ($length > self::MAX_LENGTH) {
         throw new WikiaException('Maximum allowed length is ' . self::MAX_LENGTH);
     }
     // It may be that the article is just not there
     if (!$this->article instanceof Article) {
         return '';
     }
     $id = $this->article->getID();
     if ($id <= 0) {
         return '';
     }
     $text = $this->getTextSnippetSource($id);
     $length = $this->adjustTextSnippetLength($text, $length, $breakLimit);
     $snippet = wfShortenText($text, $length, $useContentLanguage = true);
     return $snippet;
 }
 public function getNew()
 {
     wfProfileIn(__METHOD__);
     $ns = $this->request->getArray(self::PARAMETER_NAMESPACES);
     $limit = $this->request->getInt(self::PARAMETER_LIMIT, self::DEFAULT_NEW_ARTICLES_LIMIT);
     $minArticleQuality = $this->request->getInt(self::PARAM_ARTICLE_QUALITY);
     if ($limit < 1) {
         throw new InvalidParameterApiException(self::PARAMETER_LIMIT);
     }
     if ($limit > self::MAX_NEW_ARTICLES_LIMIT) {
         $limit = self::MAX_NEW_ARTICLES_LIMIT;
     }
     if (empty($ns)) {
         $ns = [self::DEFAULT_SEARCH_NAMESPACE];
     } else {
         $ns = self::processNamespaces($ns, __METHOD__);
         sort($ns);
         $ns = array_unique($ns);
     }
     $key = self::getCacheKey(self::NEW_ARTICLES_CACHE_ID, '', [implode('-', $ns), $minArticleQuality, $limit]);
     $results = $this->wg->Memc->get($key);
     if ($results === false) {
         $solrResults = $this->getNewArticlesFromSolr($ns, $limit, $minArticleQuality);
         if (empty($solrResults)) {
             $results = [];
         } else {
             $articles = array_keys($solrResults);
             $articles = array_slice($articles, 0, $limit);
             $rev = new RevisionService();
             $revisions = $rev->getFirstRevisionByArticleId($articles);
             $creators = $this->getUserDataForArticles($articles, $revisions);
             $thumbs = $this->getArticlesThumbnails($articles);
             $results = [];
             foreach ($solrResults as $id => $item) {
                 $title = Title::newFromText($item['title']);
                 $item['title'] = $title->getText();
                 $item['url'] = $title->getLocalURL();
                 $item['creator'] = $creators[$id];
                 $item['creation_date'] = isset($revisions[$id]) ? $revisions[$id]['rev_timestamp'] : null;
                 $item['abstract'] = wfShortenText($item['abstract'], self::DEFAULT_ABSTRACT_LENGTH, true);
                 $item = array_merge($item, $thumbs[$id]);
                 $results[] = $item;
             }
             $this->wg->Memc->set($key, $results, self::CLIENT_CACHE_VALIDITY);
         }
     }
     if (empty($results)) {
         throw new NotFoundApiException('No members');
     }
     $this->setResponseData(['items' => $results, 'basepath' => $this->wg->Server], ['imgFields' => 'thumbnail', 'urlFields' => ['thumbnail', 'url', 'avatar']], self::NEW_ARTICLES_VARNISH_CACHE_EXPIRATION);
     wfProfileOut(__METHOD__);
 }
 /**
  * Normalize video details to a set of keys understood by this module
  *
  * @param array $video Details for a single video
  * @return array
  */
 protected function normalizeVideoDetail(array $video)
 {
     return ['title' => $video['fileTitle'], 'url' => $video['fileUrl'], 'thumbnail' => $video['thumbnail'], 'thumbUrl' => $video['thumbUrl'], 'description' => wfShortenText($video['description'], 50), 'videoKey' => $video['title'], 'duration' => $video['duration'], 'source' => $this->source];
 }
 private function processArticle($articleInfo)
 {
     $outputModel = [];
     $outputModel['wikiId'] = $articleInfo['wid'];
     $outputModel['articleId'] = $articleInfo['pageid'];
     $outputModel['title'] = $articleInfo['title'];
     $outputModel['url'] = $articleInfo['url'];
     $outputModel['lang'] = $articleInfo['lang'];
     $outputModel['quality'] = isset($articleInfo['article_quality_i']) ? $articleInfo['article_quality_i'] : null;
     if (isset($articleInfo['article_type_s'])) {
         $type = $articleInfo['article_type_s'];
         $outputModel['type'] = array_key_exists($type, $this->article_types_passed_on) ? $type : static::ARTICLE_TYPE_OTHER;
     } else {
         $outputModel['type'] = null;
     }
     if (isset($articleInfo[Utilities::field('html', $articleInfo['lang'])])) {
         $fullText = $articleInfo[Utilities::field('html', $articleInfo['lang'])];
         $outputModel['snippet'] = trim(wfShortenText($fullText, self::SNIPPET_LENGTH, true));
     }
     $image = $this->getImage($outputModel["wikiId"], $outputModel["articleId"]);
     if (!empty($image)) {
         $outputModel['image'] = $image;
     }
     return $outputModel;
 }
 /**
  * Searching for field with prefix 'html_' (e.g. 'html_en' or 'html_fr')
  * After finding corresponding field - shortening its value.
  * If there are few fields with such prefix - working with first one value.
  * If there are no fields with such prefix - returns empty string.
  */
 protected function getAbstract($item)
 {
     $html = $this->findFirstValueByKeyPrefix($item, 'html_', '');
     return wfShortenText($html, $this->abstractLength, true);
 }
 /**
  * Controller Helper Methods
  *----------------------------------------------------------------------------------*/
 protected function processArticleItem($item, $maxlen = 150)
 {
     if (empty($item['thumbnail'])) {
         //add placeholder
         $item['thumbnail'] = '';
     }
     //sanitize strings first
     $trimTitle = trim(strtolower($item['title']));
     $bracketPos = strpos($trimTitle, '(');
     if ($bracketPos !== false) {
         $trimTitleWObrackets = substr($trimTitle, 0, $bracketPos - 1);
     }
     $normSpacesAbs = preg_replace('|\\s+|', ' ', $item['abstract']);
     $lowerAbstract = strtolower($normSpacesAbs);
     if (!empty($trimTitle)) {
         $pos = strpos($lowerAbstract, $trimTitle);
         if ($pos !== false) {
             if ($pos <= static::SNIPPET_SUBSTR) {
                 $cutIn = $pos + strlen($trimTitle);
             }
         } elseif (isset($trimTitleWObrackets)) {
             $pos = strpos($lowerAbstract, $trimTitleWObrackets);
             if ($pos !== false && $pos <= static::SNIPPET_SUBSTR) {
                 $cutIn = $pos + strlen($trimTitleWObrackets);
             }
         }
     }
     //dont substr if next char is alphanumeric
     $splitted = str_split($lowerAbstract);
     if (isset($cutIn) && (ctype_punct($splitted[$cutIn]) || ctype_space($splitted[$cutIn]))) {
         $item['abstract'] = substr($normSpacesAbs, $cutIn);
     } elseif (!empty($item['abstract'])) {
         $item['abstract'] = ' - ' . preg_replace('|^[^\\pL\\pN\\p{Pi}"]+|', '', $normSpacesAbs);
     }
     if (!empty($item['abstract'])) {
         $maxlen -= strlen($trimTitle);
         if ($maxlen > 0) {
             $item['abstract'] = wfShortenText($item['abstract'], $maxlen, true);
         } else {
             $item['abstract'] = '';
         }
         return $item;
     }
     return null;
 }
function getLinkedFiles($image)
{
    global $wgMemc;
    $anchorLength = 60;
    wfProfileIn(__METHOD__);
    $cacheKey = wfMemcKey(__METHOD__, md5($image->img_name));
    $data = $wgMemc->get($cacheKey);
    if (!is_array($data)) {
        // The ORDER BY ensures we get NS_MAIN pages first
        $dbr = wfGetDB(DB_SLAVE);
        $res = $dbr->select(array('imagelinks', 'page'), array('page_namespace', 'page_title'), array('il_to' => $image->img_name, 'il_from = page_id'), __METHOD__, array('LIMIT' => 2, 'ORDER BY' => 'page_namespace ASC'));
        while ($s = $res->fetchObject()) {
            $data[] = array('ns' => $s->page_namespace, 'title' => $s->page_title);
        }
        $dbr->freeResult($res);
        $wgMemc->set($cacheKey, $data, 60 * 15);
    }
    $links = array();
    if (!empty($data)) {
        foreach ($data as $row) {
            $name = Title::makeTitle($row['ns'], $row['title']);
            $links[] = Linker::link($name, wfShortenText($name, $anchorLength), array('class' => 'wikia-gallery-item-posted'));
        }
    }
    wfProfileOut(__METHOD__);
    return $links;
}