/**
  * Retrieve recently uploaded images from this wiki.  This will filter out video files
  * and images uploaded by bots if necessary.  Additionally, arbitrary constraints can
  * be passed in to filter out additional images.  These constraints can be either of:
  *
  *   $constrain[] = "img_name = 'bar'"
  *   $constrain['img_minor_mime'] = 'youtube'
  *
  * @param int $limit Limit the number of images to return
  * @param int $offset Grab images after an offset.  Used with $limit to page the results
  * @param array $constrain An array of constraint/value that will be used in the query
  * @return array An array of images
  */
 function getImages($limit, $offset = 0, $constrain = array())
 {
     // Load the next set of images, eliminating images uploaded by bots as
     // well as eliminating any video files
     $dbr = wfGetDB(DB_SLAVE);
     $image = $dbr->tableName('image');
     $sql = 'SELECT img_size, img_name, img_user, img_user_text, img_description, img_timestamp ' . "FROM {$image}";
     $botconds = array();
     foreach (User::getGroupsWithPermission('bot') as $groupname) {
         $botconds[] = 'ug_group = ' . $dbr->addQuotes($groupname);
     }
     $where = array();
     if (count($botconds)) {
         $isbotmember = $dbr->makeList($botconds, LIST_OR);
         // LEFT join to the user_groups table on being a bot and then make sure
         // we get null rows back (i.e. we're not a bot)
         $ug = $dbr->tableName('user_groups');
         $sql .= " LEFT JOIN {$ug} ON img_user=ug_user AND ({$isbotmember})";
         $where[] = 'ug_group IS NULL';
     }
     // Eliminate videos from this listing
     $where[] = 'img_media_type != \'VIDEO\'';
     $where[] = 'img_major_mime != \'video\'';
     $where[] = 'img_media_type != \'swf\'';
     // Add any additional constraints
     if ($constrain) {
         foreach ($constrain as $cond) {
             $where[] = $cond;
         }
     }
     $sql .= ' WHERE ' . $dbr->makeList($where, LIST_AND);
     $sql .= ' ORDER BY img_timestamp DESC ';
     $sql .= ' LIMIT ' . ($limit + 1);
     if ($offset) {
         $sql .= " OFFSET {$offset}";
     }
     $res = $dbr->query($sql, __FUNCTION__);
     $images = array();
     while ($s = $dbr->fetchObject($res)) {
         $images[] = $s;
     }
     $dbr->freeResult($res);
     // Load the images into a new gallery
     $gallery = new WikiaPhotoGallery();
     $gallery->parseParams(array("rowdivider" => true, "hideoverflow" => true));
     $gallery->setWidths(212);
     $foundImages = 0;
     foreach ($images as $s) {
         $foundImages++;
         if ($foundImages > $limit) {
             // One extra just to test for whether to show a page link;
             // don't actually show it.
             break;
         }
         $nt = Title::newFromText($s->img_name, NS_FILE);
         $gallery->add($nt);
     }
     $info = array("gallery" => $gallery);
     // Set pagination information
     if ($offset > 0) {
         $info['prev'] = $offset - $limit;
     }
     if ($foundImages > $limit) {
         $info['next'] = $offset + $limit;
     }
     return $info;
 }
function wfSpecialWikiaNewFiles($par, $specialPage)
{
    global $wgOut, $wgLang, $wgRequest, $wgMiserMode;
    global $wmu, $wgOasisHD;
    $wpIlMatch = $wgRequest->getText('wpIlMatch');
    $dbr = wfGetDB(DB_SLAVE);
    $sk = RequestContext::getMain()->getSkin();
    $shownav = !$specialPage->including();
    $hidebots = $wgRequest->getBool('hidebots', 1);
    $hidebotsql = '';
    if ($hidebots) {
        # Make a list of group names which have the 'bot' flag set.
        $botconds = array();
        foreach (User::getGroupsWithPermission('bot') as $groupname) {
            $botconds[] = 'ug_group = ' . $dbr->addQuotes($groupname);
        }
        # If not bot groups, do not set $hidebotsql
        if ($botconds) {
            $isbotmember = $dbr->makeList($botconds, LIST_OR);
            # This join, in conjunction with WHERE ug_group IS NULL, returns
            # only those rows from IMAGE where the uploading user is not a mem-
            # ber of a group which has the 'bot' permission set.
            $ug = $dbr->tableName('user_groups');
            $hidebotsql = " LEFT JOIN {$ug} ON img_user=ug_user AND ({$isbotmember})";
        }
    }
    $image = $dbr->tableName('image');
    $sql = "SELECT img_timestamp from {$image}";
    if ($hidebotsql) {
        $sql .= "{$hidebotsql} WHERE ug_group IS NULL";
    }
    $sql .= ' ORDER BY img_timestamp DESC LIMIT 1';
    $res = $dbr->query($sql, __FUNCTION__);
    $row = $dbr->fetchRow($res);
    if ($row !== false) {
        $ts = $row[0];
    } else {
        $ts = false;
    }
    $dbr->freeResult($res);
    $sql = '';
    # If we were clever, we'd use this to cache.
    $latestTimestamp = wfTimestamp(TS_MW, $ts);
    # Hardcode this for now.
    $limit = 48;
    if ($parval = intval($par)) {
        if ($parval <= $limit && $parval > 0) {
            $limit = $parval;
        }
    }
    $where = array();
    $searchpar = '';
    if ($wpIlMatch != '' && !$wgMiserMode) {
        $nt = Title::newFromUrl($wpIlMatch);
        if ($nt) {
            $m = $dbr->buildLike($dbr->anyString(), strtolower($nt->getDBkey()), $dbr->anyString());
            $where[] = 'LOWER(img_name)' . $m;
            $searchpar = '&wpIlMatch=' . urlencode($wpIlMatch);
        }
    }
    $invertSort = false;
    if ($until = $wgRequest->getVal('until')) {
        $where[] = "img_timestamp < '" . $dbr->timestamp($until) . "'";
    }
    if ($from = $wgRequest->getVal('from')) {
        $where[] = "img_timestamp >= '" . $dbr->timestamp($from) . "'";
        $invertSort = true;
    }
    $sql = 'SELECT img_size, img_name, img_user, img_user_text,' . "img_description,img_timestamp FROM {$image}";
    if ($hidebotsql) {
        $sql .= $hidebotsql;
        $where[] = 'ug_group IS NULL';
    }
    // hook by Wikia, Bartek Lapinski 26.03.2009, for videos and stuff
    wfRunHooks('SpecialNewImages::beforeQuery', array(&$where));
    if (count($where)) {
        $sql .= ' WHERE ' . $dbr->makeList($where, LIST_AND);
    }
    $sql .= ' ORDER BY img_timestamp ' . ($invertSort ? '' : ' DESC');
    $sql .= ' LIMIT ' . ($limit + 1);
    $res = $dbr->query($sql, __FUNCTION__);
    /**
     * We have to flip things around to get the last N after a certain date
     */
    $images = array();
    while ($s = $dbr->fetchObject($res)) {
        if ($invertSort) {
            array_unshift($images, $s);
        } else {
            array_push($images, $s);
        }
    }
    $dbr->freeResult($res);
    $gallery = new WikiaPhotoGallery();
    $gallery->parseParams(array("rowdivider" => true, "hideoverflow" => true));
    //FB#1150 - make the images fit the whole horizontal space in Oasis and Oasis HD
    if (get_class($sk) == 'SkinOasis') {
        if ($wgOasisHD) {
            $gallery->setWidths(202);
        } else {
            $gallery->setWidths(212);
        }
    }
    $firstTimestamp = null;
    $lastTimestamp = null;
    $shownImages = 0;
    foreach ($images as $s) {
        $shownImages++;
        if ($shownImages > $limit) {
            # One extra just to test for whether to show a page link;
            # don't actually show it.
            break;
        }
        $name = $s->img_name;
        $ut = $s->img_user_text;
        $nt = Title::newFromText($name, NS_FILE);
        $ul = $sk->link(Title::makeTitle(NS_USER, $ut), $ut, array('class' => 'wikia-gallery-item-user'));
        $timeago = wfTimeFormatAgo($s->img_timestamp);
        $links = getLinkedFiles($s);
        // If there are more than two files, remove the 2nd and link to the
        // image page
        if (count($links) == 2) {
            array_splice($links, 1);
            $moreFiles = true;
        } else {
            $moreFiles = false;
        }
        $caption = wfMsgHtml('wikianewfiles-uploadby', $ul) . "<br />\n" . "<i>{$timeago}</i><br />\n";
        if (count($links)) {
            $caption .= wfMsg('wikianewfiles-postedin') . "&nbsp;" . $links[0];
        }
        if ($moreFiles) {
            $caption .= ", " . '<a href="' . $nt->getLocalUrl() . '#filelinks" class="wikia-gallery-item-more">' . wfMsgHtml('wikianewfiles-more') . '</a>';
        }
        $gallery->add($nt, $caption);
        $timestamp = wfTimestamp(TS_MW, $s->img_timestamp);
        if (empty($firstTimestamp)) {
            $firstTimestamp = $timestamp;
        }
        $lastTimestamp = $timestamp;
    }
    wfRunHooks('SpecialNewImages::beforeDisplay', array(&$images, &$gallery, &$limit));
    $titleObj = SpecialPage::getTitleFor('Newimages');
    $action = $titleObj->getLocalURL($hidebots ? '' : 'hidebots=0');
    if ($shownav && !$wgMiserMode) {
        $wgOut->addHTML(Xml::openElement('form', array('action' => $action, 'method' => 'post', 'id' => 'imagesearch')) . Xml::fieldset(wfMsg('newimages-legend')) . Xml::inputLabel(wfMsg('newimages-label'), 'wpIlMatch', 'wpIlMatch', 20, $wpIlMatch) . ' ' . Xml::submitButton(wfMsg('ilsubmit'), array('name' => 'wpIlSubmit')) . Xml::closeElement('fieldset') . Xml::closeElement('form'));
    }
    /**
     * Paging controls...
     */
    # If we change bot visibility, this needs to be carried along.
    if (!$hidebots) {
        $botpar = '&hidebots=0';
    } else {
        $botpar = '';
    }
    $now = wfTimestampNow();
    $d = $wgLang->date($now, true);
    $t = $wgLang->time($now, true);
    $dateLink = $sk->link($titleObj, wfMsgHtml('sp-newimages-showfrom', $d, $t), array('class' => 'navigation-filesfrom'), 'from=' . $now . $botpar . $searchpar);
    $botLink = $sk->link($titleObj, wfMsgHtml('showhidebots', $hidebots ? wfMsgHtml('show') : wfMsgHtml('hide')), array('class' => 'navigation-' . ($hidebots ? 'showbots' : 'hidebots')), 'hidebots=' . ($hidebots ? '0' : '1') . $searchpar);
    $opts = array('parsemag', 'escapenoentities');
    $prevLink = wfMsgExt('pager-newer-n', $opts, $wgLang->formatNum($limit));
    if ($firstTimestamp && $firstTimestamp != $latestTimestamp) {
        $wmu['prev'] = $firstTimestamp;
        $prevLink = $sk->link($titleObj, $prevLink, array('class' => 'navigation-newer'), 'from=' . $firstTimestamp . $botpar . $searchpar);
    }
    $nextLink = wfMsgExt('pager-older-n', $opts, $wgLang->formatNum($limit));
    if ($shownImages > $limit && $lastTimestamp) {
        $wmu['next'] = $lastTimestamp;
        $nextLink = $sk->link($titleObj, $nextLink, array('class' => 'navigation-older'), 'until=' . $lastTimestamp . $botpar . $searchpar);
    }
    $prevnext = '<p id="newfiles-nav">' . $botLink . ' ' . wfMsgHtml('viewprevnext', $prevLink, $nextLink, $dateLink) . '</p>';
    if (count($images)) {
        $wmu['gallery'] = $gallery;
        $wgOut->addHTML($gallery->toHTML());
        if ($shownav) {
            $wgOut->addHTML($prevnext);
        }
    } else {
        $wgOut->addWikiMsg('noimages');
    }
}