Example #1
0
 function __construct($title, $from = '', $until = '')
 {
     global $wgCategoryPagingLimit;
     $this->title = $title;
     $this->from = $from;
     $this->until = $until;
     $this->limit = $wgCategoryPagingLimit;
     $this->cat = Category::newFromName($title->getDBKey());
 }
Example #2
0
 private function doPopulateCategory($begin, $maxlag, $throttle, $force)
 {
     $dbw = wfGetDB(DB_MASTER);
     if (!$force) {
         $row = $dbw->selectRow('updatelog', '1', array('ul_key' => 'populate category'), __FUNCTION__);
         if ($row) {
             $this->output("Category table already populated.  Use php " . "maintenance/populateCategory.php\n--force from the command line " . "to override.\n");
             return true;
         }
     }
     $maxlag = intval($maxlag);
     $throttle = intval($throttle);
     $force = (bool) $force;
     if ($begin !== '') {
         $where = 'cl_to > ' . $dbw->addQuotes($begin);
     } else {
         $where = null;
     }
     $i = 0;
     while (true) {
         # Find which category to update
         $row = $dbw->selectRow('categorylinks', 'cl_to', $where, __FUNCTION__, array('ORDER BY' => 'cl_to'));
         if (!$row) {
             # Done, hopefully.
             break;
         }
         $name = $row->cl_to;
         $where = 'cl_to > ' . $dbw->addQuotes($name);
         # Use the row to update the category count
         $cat = Category::newFromName($name);
         if (!is_object($cat)) {
             $this->output("The category named {$name} is not valid?!\n");
         } else {
             $cat->refreshCounts();
         }
         ++$i;
         if (!($i % self::REPORTING_INTERVAL)) {
             $this->output("{$name}\n");
             wfWaitForSlaves($maxlag);
         }
         usleep($throttle * 1000);
     }
     if ($dbw->insert('updatelog', array('ul_key' => 'populate category'), __FUNCTION__, 'IGNORE')) {
         wfOut("Category population complete.\n");
         return true;
     } else {
         wfOut("Could not insert category population row.\n");
         return false;
     }
 }
/**
 * Hook point to SkinBuildSidebar
 * 
 * Finds all top-level entries in the sidebar that have the format category:$1|$2.
 * Replaces the entry with a list of pages in Category:$1 and changes the label
 * to $2, or $1 if $2 not available.
 * 
 * @param $skin Skin
 * @param $bar array
 * @return bool True
 */
function efCategoryMembersOnSidebar($skin, &$bar)
{
    $newbar = array();
    $i = 0;
    foreach ($bar as $key => $data) {
        # Check if this entry needs to be handled by this extension
        $matches = array();
        preg_match('/category\\:([^|]*)\\|?([^|]*)/i', $key, $matches);
        if ($matches) {
            # Extract the new message key
            $newkey = trim($matches[2]) ? trim($matches[2]) : $matches[1];
            # Extract category members
            $cat = Category::newFromName($matches[1]);
            if (!$cat) {
                # Invalid title
                continue;
            }
            $members = $cat->getMembers();
            if ($members->count()) {
                # Create the subbar
                $subbar = array();
                foreach ($members as $title) {
                    $subbar[] = array('text' => $title->getText(), 'href' => $title->getLocalURL(), 'id' => 'catsb-' . Sanitizer::escapeId($title->getText()), 'active' => false);
                }
                $bar[$key] = $subbar;
                # Store the index of this top-level entry, because we need to
                # replace the key later with our new key
                $newbar[$i] = $newkey;
            }
        }
        $i++;
    }
    if ($newbar) {
        # Replace the keys without changing the order
        $keys = array_keys($bar);
        foreach ($newbar as $i => $newkey) {
            array_splice($keys, $i, 1, $newkey);
        }
        $bar = array_combine($keys, array_values($bar));
    }
    return true;
}
 public function save()
 {
     if (!$this->wg->User->isAllowed('gameguidescontent')) {
         $this->displayRestrictionError();
         return false;
         // skip rendering
     }
     $this->response->setFormat('json');
     $categories = $this->getVal('categories');
     $err = array();
     $tags = array();
     if (!empty($categories)) {
         //check if categories exists
         foreach ($categories as $categoryName => $values) {
             $category = Category::newFromName($categoryName);
             if (!$category instanceof Category || $category->getPageCount() === 0) {
                 $err[] = $categoryName;
             } else {
                 if (empty($err)) {
                     if (array_key_exists($values['tag'], $tags)) {
                         $tags[$values['tag']]['categories'][] = array('category' => $categoryName, 'name' => $values['name']);
                     } else {
                         $tags[$values['tag']] = array('name' => $values['tag'], 'categories' => array(array('category' => $categoryName, 'name' => $values['name'])));
                     }
                 }
             }
         }
         if (!empty($err)) {
             $this->response->setVal('error', $err);
             return true;
         }
     }
     $status = WikiFactory::setVarByName('wgWikiaGameGuidesContent', $this->wg->CityId, array_values($tags));
     $this->response->setVal('status', $status);
     if ($status) {
         $this->wf->RunHooks('GameGuidesContentSave');
     }
     return true;
 }
    public static function SkinBuildSidebar($skin, &$sidebar)
    {
        global $wgOut, $wgTitle, $wgAdManagerService, $wgAdManagerCode;
        $fullTableName = AD_TABLE;
        $dbr = wfGetDB(DB_SLAVE);
        if (!$dbr->tableExists($fullTableName)) {
            return $sidebar;
        }
        // check if an ad zone was set for this page.
        $thisPageID = $wgTitle->getArticleID();
        if ($thisPageID <= 0) {
            return $sidebar;
        }
        $thisPageAdZonesDB = $dbr->select($fullTableName, array('ad_zone'), "ad_page_id = {$thisPageID} AND ad_page_is_category IS NOT TRUE", __METHOD__);
        $thisPageAdZones = array();
        if ($thisPageAdZonesDB->numRows() !== 0) {
            // If there's a page zone set, it gets precedence.
            while ($row = $thisPageAdZonesDB->fetchObject()) {
                $thisPageAdZones[] = $row->ad_zone;
            }
        } else {
            // check if an ad zone was set for any of this page's categories
            $allCategories = $dbr->select($fullTableName, array('ad_page_id', 'ad_zone'), 'ad_page_is_category IS TRUE', __METHOD__);
            $thisCategoryIDS = $wgTitle->getParentCategoryTree();
            array_walk($thisCategoryIDS, 'self::assignLevel');
            asort(self::$catList);
            // give precedence to the closest ancestors
            if (!empty(self::$catList)) {
                // find first match in this page's catlist that exists in the database
                foreach (self::$catList as $catName => $level) {
                    // @todo FIXME: this is awfully hacky and specfic to
                    // English; the correct way of doing this would be
                    // constructing a Title object and calling getText() on it
                    // or something like that to get the name of the category
                    // without the namespace
                    $catName = substr($catName, 9);
                    // strips Category: prefix
                    $catID = Category::newFromName($catName)->getID();
                    $firstMatch = $dbr->select($fullTableName, array('ad_zone'), "ad_page_id = {$catID} AND ad_page_is_category IS TRUE", __METHOD__);
                    if ($firstMatch->numRows() !== 0) {
                        break;
                    }
                }
                while ($row = $firstMatch->fetchObject()) {
                    $thisPageAdZones[] = $row->ad_zone;
                }
            }
        }
        // And finally, pop those ads in
        if (empty($thisPageAdZones)) {
            // No zone set for this page or its categories
            return true;
        }
        if (in_array(null, $thisPageAdZones)) {
            // An entry in this array was set to "None" so show no ads
            return true;
        }
        if ($wgAdManagerService == 'openx') {
            $wgAdManagerCode = "<a href='http://d1.openx.org/ck.php?cb=91238047' target='_blank'><img src='http://d1.openx.org/avw.php?zoneid=\$1&amp;cb=1378957897235' border='0' alt='' /></a>";
        }
        if ($wgAdManagerService == 'banman') {
            $wgAdManagerCode = <<<END
\t<!-- Begin -  Site: AAO Zone: /eyewiki -->
\t<script language="javascript"  type="text/javascript">
\t<!--
\tvar browName = navigator.appName;
\tvar SiteID = 1;
\tvar ZoneID = \$1;
\tvar browDateTime = (new Date()).getTime();
\tif ( browName=='Netscape' ) {
\t\tdocument.write('<s'+'cript lang' + 'uage="jav' + 'ascript" src="http://aaoads.enforme.com/a.aspx?ZoneID=' + ZoneID + '&amp;Task=Get&amp;IFR=False&amp;Browser=NETSCAPE4&amp;SiteID=' + SiteID + '&amp;Random=' + browDateTime  + '">'); document.write('</'+'scr'+'ipt>');
\t}
\tif ( browName != 'Netscape' ) {
\t\tdocument.write('<s'+'cript lang' + 'uage="jav' + 'ascript" src="http://aaoads.enforme.com/a.aspx?ZoneID=' + ZoneID + '&amp;Task=Get&amp;IFR=False&amp;SiteID=' + SiteID + '&amp;Random=' + browDateTime  + '">'); document.write('</'+'scr'+'ipt>');
\t}
\t// -->
\t</script>
\t<noscript>
\t\t<a href="http://aaoads.enforme.com/a.aspx?ZoneID=\$1&amp;Task=Click&amp;Mode=HTML&amp;SiteID=1" target="_blank">
\t\t<img src="http://aaoads.enforme.com/a.aspx?ZoneID=\$1&amp;Task=Get&amp;Mode=HTML&amp;SiteID=1" border="0"  alt=""></a>
\t</noscript>
\t<!-- End -  Site: AAO Zone: /eyewiki_0 -->
END;
        }
        // Other ad services can be added here, with the same format as above
        if (!isset($wgAdManagerCode)) {
            return true;
            // TODO: show error
        }
        // Adds some CSS, but puts it in <body>
        $wgOut->addHTML(<<<EOT
<style type="text/css">
div[id*='AdManager'] h5 {
\tdisplay: none;
}
div[id*='AdManager'] .pBody {
\tborder: none;
\tpadding-left: 0;
}
</style>
EOT
);
        $adNumber = 0;
        foreach ($thisPageAdZones as $thisPageAdZone) {
            $adNumber++;
            // Allows admins to use any ad service or inclusion code they
            // desire by inserting in LocalSettings.php
            $out = str_replace('$1', $thisPageAdZone, $wgAdManagerCode);
            $sidebar["AdManager{$adNumber}"] = $out;
        }
        return true;
    }
 /**
  * Return the number of pages in the given category, or 0 if it's nonexis-
  * tent.  This is an expensive parser function and can't be called too many
  * times per page.
  */
 static function pagesincategory($parser, $name = '', $raw = null)
 {
     static $cache = array();
     $category = Category::newFromName($name);
     if (!is_object($category)) {
         $cache[$name] = 0;
         return self::formatRaw(0, $raw);
     }
     # Normalize name for cache
     $name = $category->getName();
     $count = 0;
     if (isset($cache[$name])) {
         $count = $cache[$name];
     } elseif ($parser->incrementExpensiveFunctionCount()) {
         $count = $cache[$name] = (int) $category->getPageCount();
     }
     return self::formatRaw($count, $raw);
 }
 /**
  * Prepare wiki categories string (eg [[Category:MyCategory]] )
  * @return string
  */
 public function prepareCategoriesString()
 {
     $this->pageCategories[] = wfMessage('videohandler-category')->inContentLanguage()->text();
     $this->pageCategories = array_unique($this->pageCategories);
     $categoryStr = '';
     foreach ($this->pageCategories as $categoryName) {
         $category = Category::newFromName($categoryName);
         if ($category instanceof Category) {
             $categoryStr .= '[[' . $category->getTitle()->getFullText() . ']]';
         }
     }
     return $categoryStr . "\n";
 }
 function deletePermanently($title)
 {
     global $wgOut;
     $ns = $title->getNamespace();
     $t = $title->getDBkey();
     $id = $title->getArticleID();
     $cats = $title->getParentCategories();
     $dbw = wfGetDB(DB_MASTER);
     $dbw->begin();
     ####
     ## First delete entries, which are in direct relation with the page:
     ####
     # delete redirect...
     $dbw->delete('redirect', array('rd_from' => $id), __METHOD__);
     # delete external link...
     $dbw->delete('externallinks', array('el_from' => $id), __METHOD__);
     # delete language link...
     $dbw->delete('langlinks', array('ll_from' => $id), __METHOD__);
     # delete search index...
     $dbw->delete('searchindex', array('si_page' => $id), __METHOD__);
     # Delete restrictions for the page
     $dbw->delete('page_restrictions', array('pr_page' => $id), __METHOD__);
     # Delete page Links
     $dbw->delete('pagelinks', array('pl_from' => $id), __METHOD__);
     # delete category links
     $dbw->delete('categorylinks', array('cl_from' => $id), __METHOD__);
     # delete template links
     $dbw->delete('templatelinks', array('tl_from' => $id), __METHOD__);
     # read text entries for all revisions and delete them.
     $res = $dbw->select('revision', 'rev_text_id', "rev_page={$id}");
     while ($row = $dbw->fetchObject($res)) {
         $value = $row->rev_text_id;
         $dbw->delete('text', array('old_id' => $value), __METHOD__);
     }
     # In the table 'revision' : Delete all the revision of the page where 'rev_page' = $id
     $dbw->delete('revision', array('rev_page' => $id), __METHOD__);
     # delete image links
     $dbw->delete('imagelinks', array('il_from' => $id), __METHOD__);
     ####
     ## then delete entries which are not in direct relation with the page:
     ####
     # Clean up recentchanges entries...
     $dbw->delete('recentchanges', array('rc_namespace' => $ns, 'rc_title' => $t), __METHOD__);
     # read text entries for all archived pages and delete them.
     $res = $dbw->select('archive', 'ar_text_id', array('ar_namespace' => $ns, 'ar_title' => $t));
     while ($row = $dbw->fetchObject($res)) {
         $value = $row->ar_text_id;
         $dbw->delete('text', array('old_id' => $value), __METHOD__);
     }
     # Clean archive entries...
     $dbw->delete('archive', array('ar_namespace' => $ns, 'ar_title' => $t), __METHOD__);
     # Clean up log entries...
     $dbw->delete('logging', array('log_namespace' => $ns, 'log_title' => $t), __METHOD__);
     # Clean up watchlist...
     $dbw->delete('watchlist', array('wl_namespace' => $ns, 'wl_title' => $t), __METHOD__);
     # In the table 'page' : Delete the page entry
     $dbw->delete('page', array('page_id' => $id), __METHOD__);
     ####
     ## If the article belongs to a category, update category counts
     ####
     if (!empty($cats)) {
         foreach ($cats as $parentcat => $currentarticle) {
             $catname = split(':', $parentcat, 2);
             $cat = Category::newFromName($catname[1]);
             $cat->refreshCounts();
         }
     }
     ####
     ## If an image is beeing deleted, some extra work needs to be done
     ####
     if ($ns == NS_IMAGE) {
         $file = wfFindFile($t);
         if ($file) {
             # Get all filenames of old versions:
             $fields = OldLocalFile::selectFields();
             $res = $dbw->select('oldimage', $fields, array('oi_name' => $t));
             while ($row = $dbw->fetchObject($res)) {
                 $oldLocalFile = OldLocalFile::newFromRow($row, $file->repo);
                 $path = $oldLocalFile->getArchivePath() . '/' . $oldLocalFile->getArchiveName();
                 try {
                     # Using the FileStore to delete the file
                     $transaction = FileStore::deleteFile($path);
                     $transaction->commit();
                 } catch (Exception $e) {
                     $wgOut->addHTML($e->getMessage());
                 }
             }
             $path = $file->getPath();
             try {
                 # Using the FileStore to delete the file itself
                 $transaction = FileStore::deleteFile($path);
                 $transaction->commit();
             } catch (Exception $e) {
                 $wgOut->addHTML($e->getMessage());
             }
         }
         # clean the filearchive for the given filename:
         $fa_archive_name = array();
         $res = $dbw->select('filearchive', 'fa_storage_key', array('fa_name' => $t));
         while ($row = $dbw->fetchObject($res)) {
             $key = $row->fa_storage_key;
             # Using the FileStore to delete the file
             $store = FileStore::get('deleted');
             $transaction = $store->delete($key);
             $transaction->commit();
         }
         # Delete old db entries of the image:
         $dbw->delete('oldimage', array('oi_name' => $t), __METHOD__);
         # Delete archive entries of the image:
         $dbw->delete('filearchive', array('fa_name' => $t), __METHOD__);
         # Delete image entry:
         $dbw->delete('image', array('img_name' => $t), __METHOD__);
         $dbw->commit();
         $linkCache = LinkCache::singleton();
         $linkCache->clear();
     }
 }
 public static function getApprovabilityStringsForDB()
 {
     $perms = self::getPermissions();
     $approvableNamespaceIdString = implode(',', array_keys($perms['Namespace Permissions']));
     $dbSafeCategoryNames = array();
     foreach (array_keys($perms['Category Permissions']) as $category) {
         $mwCategoryObject = Category::newFromName($category);
         // cannot use category IDs like with pages and namespaces. Instead
         // need to create database-safe SQL column names. Columns in same
         // form as categorylinks.cl_to
         $dbSafeCategoryNames[] = "'" . mysql_real_escape_string($mwCategoryObject->getName()) . "'";
     }
     $dbSafeCategoryNamesString = implode(',', $dbSafeCategoryNames);
     $approvablePageIds = array();
     foreach (array_keys($perms['Page Permissions']) as $page) {
         $title = Title::newFromText($page);
         $approvablePageIds[] = $title->getArticleID();
     }
     $approvablePageIdString = implode(',', $approvablePageIds);
     return array($approvableNamespaceIdString, $dbSafeCategoryNamesString, $approvablePageIdString);
 }
 protected function doDBUpdates()
 {
     $mode = $this->getOption('mode', 'both');
     $begin = $this->getOption('begin', '');
     $throttle = $this->getOption('throttle', 0);
     if (!in_array($mode, ['add', 'remove', 'both'])) {
         $this->output("--mode must be 'add', 'remove', or 'both'.\n");
         return false;
     }
     $dbw = $this->getDB(DB_MASTER);
     $throttle = intval($throttle);
     if ($mode === 'add' || $mode === 'both') {
         if ($begin !== '') {
             $where = ['page_title > ' . $dbw->addQuotes($begin)];
         } else {
             $where = [];
         }
         $this->output("Adding empty categories with description pages...\n");
         while (true) {
             # Find which category to update
             $rows = $dbw->select(['page', 'category'], 'page_title', array_merge($where, ['page_namespace' => NS_CATEGORY, 'cat_title' => null]), __METHOD__, ['ORDER BY' => 'page_title', 'LIMIT' => $this->mBatchSize], ['category' => ['LEFT JOIN', 'page_title = cat_title']]);
             if (!$rows || $rows->numRows() <= 0) {
                 # Done, hopefully.
                 break;
             }
             foreach ($rows as $row) {
                 $name = $row->page_title;
                 $where = ['page_title > ' . $dbw->addQuotes($name)];
                 # Use the row to update the category count
                 $cat = Category::newFromName($name);
                 if (!is_object($cat)) {
                     $this->output("The category named {$name} is not valid?!\n");
                 } else {
                     $cat->refreshCounts();
                 }
             }
             $this->output("--mode={$mode} --begin={$name}\n");
             wfWaitForSlaves();
             usleep($throttle * 1000);
         }
         $begin = '';
     }
     if ($mode === 'remove' || $mode === 'both') {
         if ($begin !== '') {
             $where = ['cat_title > ' . $dbw->addQuotes($begin)];
         } else {
             $where = [];
         }
         $this->output("Removing empty categories without description pages...\n");
         while (true) {
             # Find which category to update
             $rows = $dbw->select(['category', 'page'], 'cat_title', array_merge($where, ['page_title' => null, 'cat_pages' => 0]), __METHOD__, ['ORDER BY' => 'cat_title', 'LIMIT' => $this->mBatchSize], ['page' => ['LEFT JOIN', ['page_namespace' => NS_CATEGORY, 'page_title = cat_title']]]);
             if (!$rows || $rows->numRows() <= 0) {
                 # Done, hopefully.
                 break;
             }
             foreach ($rows as $row) {
                 $name = $row->cat_title;
                 $where = ['cat_title > ' . $dbw->addQuotes($name)];
                 # Use the row to update the category count
                 $cat = Category::newFromName($name);
                 if (!is_object($cat)) {
                     $this->output("The category named {$name} is not valid?!\n");
                 } else {
                     $cat->refreshCounts();
                 }
             }
             $this->output("--mode=remove --begin={$name}\n");
             wfWaitForSlaves();
             usleep($throttle * 1000);
         }
     }
     $this->output("Category cleanup complete.\n");
     return true;
 }
 public function getCategoryContents($categoryName, $limit = null, $batch = 1, $totalLimit = self::CATEGORY_RESULTS_LIMIT)
 {
     wfProfileIn(__METHOD__);
     $categoryName = trim($categoryName);
     $category = Category::newFromName($categoryName);
     if ($category) {
         $cacheKey = $this->generateCacheKey(__METHOD__ . ":{$category->getID()}" . ":{$totalLimit}");
         //$contents = $this->loadFromCache( $cacheKey );
         if (empty($contents)) {
             $contents = array();
             $titles = $category->getMembers($totalLimit);
             foreach ($titles as $title) {
                 $contents[] = array('title' => $title->getText(), 'url' => $title->getLocalUrl(array('useskin' => GameGuidesController::SKIN_NAME)));
             }
             $this->storeInCache($cacheKey, $contents);
         }
     } else {
         wfProfileOut(__METHOD__);
         throw new WikiaException("No data for '{$categoryName}'");
     }
     $ret = wfpaginateArray($contents, $limit, $batch);
     wfProfileOut(__METHOD__);
     return $ret;
 }
 public function makeCategoriesFilterCondition(&$aConditions, $aArgs, $sPageIdFileName)
 {
     if ($aArgs['categories'] != '-' && $aArgs['categories'] != '') {
         $aCategories = explode(',', $aArgs['categories']);
         $iCnt = count($aCategories);
         for ($i = 0; $i < $iCnt; $i++) {
             $oCategory = Category::newFromName(trim($aCategories[$i]));
             if ($oCategory === false) {
                 unset($aCategories[$i]);
                 continue;
             }
             $aCategories[$i] = "'" . $oCategory->getName() . "'";
         }
         $aArgs['categories'] = implode(',', $aCategories);
         $dbr = wfGetDB(DB_SLAVE);
         if ($aArgs['categoryMode'] == 'OR') {
             $aConditions[] = $sPageIdFileName . ' IN ( SELECT cl_from FROM ' . $dbr->tableName('categorylinks') . ' WHERE cl_to IN (' . $aArgs['categories'] . ') )';
         } else {
             foreach ($aCategories as $sCategory) {
                 $aConditions[] = $sPageIdFileName . ' IN ( SELECT cl_from FROM ' . $dbr->tableName('categorylinks') . ' WHERE cl_to = ' . $sCategory . ' )';
             }
         }
     }
 }
Example #13
0
 function buildArticlesForDay($month, $day, $year)
 {
     //$date = "$month-$day-$year";
     $date = $this->userDateFormat($month, $day, $year);
     $search = "{$this->calendarPageName}/{$date}";
     $pages = PrefixSearch::titleSearch($search, '100');
     $category = Category::newFromName("Event");
     foreach ($category->getMembers() as $eventTitle) {
         if ($eventTitle->getNamespace() == NS_CATEGORY) {
             // TODO
             // This is a sub-category. We should recusre into it.
         } else {
             if ($eventTitle->isContentPage()) {
                 $event = Event::newFromTitle($eventTitle);
             }
         }
     }
     foreach ($pages as $page) {
         $this->addArticle($month, $day, $year, $page);
     }
     unset($pages);
     // subscribed events
     foreach ($this->subscribedPages as $subscribedPage) {
         $search = "{$subscribedPage}/{$date}";
         $pages = PrefixSearch::titleSearch($search, '100');
         foreach ($pages as $page) {
             $this->addArticle($month, $day, $year, $page);
         }
     }
 }
Example #14
0
 /**
  * Update all the appropriate counts in the category table, given that
  * we've added the categories $added and deleted the categories $deleted.
  *
  * @param array $added   The names of categories that were added
  * @param array $deleted The names of categories that were deleted
  */
 public function updateCategoryCounts(array $added, array $deleted)
 {
     $that = $this;
     $method = __METHOD__;
     $dbw = wfGetDB(DB_MASTER);
     // Do this at the end of the commit to reduce lock wait timeouts
     $dbw->onTransactionPreCommitOrIdle(function () use($dbw, $that, $method, $added, $deleted) {
         $ns = $that->getTitle()->getNamespace();
         // First make sure the rows exist.  If one of the "deleted" ones didn't
         // exist, we might legitimately not create it, but it's simpler to just
         // create it and then give it a negative value, since the value is bogus
         // anyway.
         //
         // Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
         $insertCats = array_merge($added, $deleted);
         if (!$insertCats) {
             // Okay, nothing to do
             return;
         }
         $insertRows = array();
         foreach ($insertCats as $cat) {
             $insertRows[] = array('cat_id' => $dbw->nextSequenceValue('category_cat_id_seq'), 'cat_title' => $cat);
         }
         $dbw->insert('category', $insertRows, $method, 'IGNORE');
         $addFields = array('cat_pages = cat_pages + 1');
         $removeFields = array('cat_pages = cat_pages - 1');
         if ($ns == NS_CATEGORY) {
             $addFields[] = 'cat_subcats = cat_subcats + 1';
             $removeFields[] = 'cat_subcats = cat_subcats - 1';
         } elseif ($ns == NS_FILE) {
             $addFields[] = 'cat_files = cat_files + 1';
             $removeFields[] = 'cat_files = cat_files - 1';
         }
         if ($added) {
             $dbw->update('category', $addFields, array('cat_title' => $added), $method);
         }
         if ($deleted) {
             $dbw->update('category', $removeFields, array('cat_title' => $deleted), $method);
         }
         foreach ($added as $catName) {
             $cat = Category::newFromName($catName);
             wfRunHooks('CategoryAfterPageAdded', array($cat, $that));
         }
         foreach ($deleted as $catName) {
             $cat = Category::newFromName($catName);
             wfRunHooks('CategoryAfterPageRemoved', array($cat, $that));
         }
     });
 }
 function addZoneToTitle()
 {
     global $wgOut;
     $dbw = wfGetDB(DB_MASTER);
     $fullTableName = AD_TABLE;
     $dbw->delete($fullTableName, '*', __METHOD__);
     $tableTypes = array('Page', 'Category');
     foreach ($tableTypes as $tableType) {
         foreach ($this->target[$tableType] as $targetZoneID => $titlesArray) {
             if ($targetZoneID == wfMsg('admanager_noads')) {
                 $targetZoneID = 'NULL';
             }
             foreach ($titlesArray as $title) {
                 // Depending on fields being processed, lookup either the
                 // text's Page ID or Category ID
                 if ($tableType == 'Page') {
                     $targetPageID = Title::newFromText($title)->getArticleID();
                 } else {
                     $targetPageID = Category::newFromName($title)->getID();
                 }
                 $dbw->insert($fullTableName, array('ad_page_id' => $targetPageID, 'ad_zone' => $targetZoneID, 'ad_page_is_category' => $tableType == 'Category' ? true : false), __METHOD__);
             }
         }
     }
     $wgOut->wrapWikiMsg("<div class=\"successbox\" style=\"margin-right:3em;\">\$1</div>", 'admanager_added');
     $wgOut->addWikiText('<br clear="both" />' . wfMsg('admanager_return'));
 }
Example #16
0
 /**
  * Update all the appropriate counts in the category table, given that
  * we've added the categories $added and deleted the categories $deleted.
  *
  * @param array $added The names of categories that were added
  * @param array $deleted The names of categories that were deleted
  */
 public function updateCategoryCounts(array $added, array $deleted)
 {
     $that = $this;
     $method = __METHOD__;
     $dbw = wfGetDB(DB_MASTER);
     // Do this at the end of the commit to reduce lock wait timeouts
     $dbw->onTransactionPreCommitOrIdle(function () use($dbw, $that, $method, $added, $deleted) {
         $ns = $that->getTitle()->getNamespace();
         $addFields = array('cat_pages = cat_pages + 1');
         $removeFields = array('cat_pages = cat_pages - 1');
         if ($ns == NS_CATEGORY) {
             $addFields[] = 'cat_subcats = cat_subcats + 1';
             $removeFields[] = 'cat_subcats = cat_subcats - 1';
         } elseif ($ns == NS_FILE) {
             $addFields[] = 'cat_files = cat_files + 1';
             $removeFields[] = 'cat_files = cat_files - 1';
         }
         if (count($added)) {
             $existingAdded = $dbw->selectFieldValues('category', 'cat_title', array('cat_title' => $added), __METHOD__);
             // For category rows that already exist, do a plain
             // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
             // to avoid creating gaps in the cat_id sequence.
             if (count($existingAdded)) {
                 $dbw->update('category', $addFields, array('cat_title' => $existingAdded), __METHOD__);
             }
             $missingAdded = array_diff($added, $existingAdded);
             if (count($missingAdded)) {
                 $insertRows = array();
                 foreach ($missingAdded as $cat) {
                     $insertRows[] = array('cat_title' => $cat, 'cat_pages' => 1, 'cat_subcats' => $ns == NS_CATEGORY ? 1 : 0, 'cat_files' => $ns == NS_FILE ? 1 : 0);
                 }
                 $dbw->upsert('category', $insertRows, array('cat_title'), $addFields, $method);
             }
         }
         if (count($deleted)) {
             $dbw->update('category', $removeFields, array('cat_title' => $deleted), $method);
         }
         foreach ($added as $catName) {
             $cat = Category::newFromName($catName);
             Hooks::run('CategoryAfterPageAdded', array($cat, $that));
         }
         foreach ($deleted as $catName) {
             $cat = Category::newFromName($catName);
             Hooks::run('CategoryAfterPageRemoved', array($cat, $that));
         }
     });
 }
Example #17
0
 /**
  * Update all the appropriate counts in the category table, given that
  * we've added the categories $added and deleted the categories $deleted.
  *
  * This should only be called from deferred updates or jobs to avoid contention.
  *
  * @param array $added The names of categories that were added
  * @param array $deleted The names of categories that were deleted
  * @param integer $id Page ID (this should be the original deleted page ID)
  */
 public function updateCategoryCounts(array $added, array $deleted, $id = 0)
 {
     $id = $id ?: $this->getId();
     $ns = $this->getTitle()->getNamespace();
     $addFields = ['cat_pages = cat_pages + 1'];
     $removeFields = ['cat_pages = cat_pages - 1'];
     if ($ns == NS_CATEGORY) {
         $addFields[] = 'cat_subcats = cat_subcats + 1';
         $removeFields[] = 'cat_subcats = cat_subcats - 1';
     } elseif ($ns == NS_FILE) {
         $addFields[] = 'cat_files = cat_files + 1';
         $removeFields[] = 'cat_files = cat_files - 1';
     }
     $dbw = wfGetDB(DB_MASTER);
     if (count($added)) {
         $existingAdded = $dbw->selectFieldValues('category', 'cat_title', ['cat_title' => $added], __METHOD__);
         // For category rows that already exist, do a plain
         // UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
         // to avoid creating gaps in the cat_id sequence.
         if (count($existingAdded)) {
             $dbw->update('category', $addFields, ['cat_title' => $existingAdded], __METHOD__);
         }
         $missingAdded = array_diff($added, $existingAdded);
         if (count($missingAdded)) {
             $insertRows = [];
             foreach ($missingAdded as $cat) {
                 $insertRows[] = ['cat_title' => $cat, 'cat_pages' => 1, 'cat_subcats' => $ns == NS_CATEGORY ? 1 : 0, 'cat_files' => $ns == NS_FILE ? 1 : 0];
             }
             $dbw->upsert('category', $insertRows, ['cat_title'], $addFields, __METHOD__);
         }
     }
     if (count($deleted)) {
         $dbw->update('category', $removeFields, ['cat_title' => $deleted], __METHOD__);
     }
     foreach ($added as $catName) {
         $cat = Category::newFromName($catName);
         Hooks::run('CategoryAfterPageAdded', [$cat, $this]);
     }
     foreach ($deleted as $catName) {
         $cat = Category::newFromName($catName);
         Hooks::run('CategoryAfterPageRemoved', [$cat, $this, $id]);
     }
     // Refresh counts on categories that should be empty now, to
     // trigger possible deletion. Check master for the most
     // up-to-date cat_pages.
     if (count($deleted)) {
         $rows = $dbw->select('category', ['cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files'], ['cat_title' => $deleted, 'cat_pages <= 0'], __METHOD__);
         foreach ($rows as $row) {
             $cat = Category::newFromRow($row);
             $cat->refreshCounts();
         }
     }
 }
Example #18
0
 /**
  * Load quiz data (try to use cache layer)
  */
 private function load($master = false)
 {
     global $wgMemc;
     wfProfileIn(__METHOD__);
     if (!$master) {
         $this->mData = $wgMemc->get($this->mMemcacheKey);
     }
     if (empty($this->mData)) {
         $article = Article::newFromID($this->mQuizId);
         // check quiz existence
         if (empty($article)) {
             wfDebug(__METHOD__ . ": quiz doesn't exist\n");
             wfProfileOut(__METHOD__);
             return;
         }
         // get quiz's author and creation timestamp
         $title = $article->getTitle();
         $firstRev = $title->getFirstRevision();
         $titleText = $title->getText();
         $titleScreenText = '';
         $fbRecommendationText = '';
         $images = array();
         $imageShorts = array();
         $moreInfoHeading = '';
         $moreInfoLinks = array();
         // parse wikitext containing quiz data
         $content = $article->getContent();
         $lines = explode("\n", $content);
         foreach ($lines as $line) {
             if (startsWith($line, self::TITLESCREENTEXT_MARKER)) {
                 $titleScreenText = trim(substr($line, strlen(self::TITLESCREENTEXT_MARKER)));
             } elseif (startsWith($line, self::FBRECOMMENDATIONTEXT_MARKER)) {
                 $fbRecommendationText = trim(substr($line, strlen(self::FBRECOMMENDATIONTEXT_MARKER)));
             } elseif (startsWith($line, self::IMAGE_MARKER)) {
                 $imageShort = trim(substr($line, strlen(self::IMAGE_MARKER)));
                 $images[] = $this->getImageSrc($imageShort);
                 $imageShorts[] = $imageShort;
             } elseif (startsWith($line, self::MOREINFOHEADING_MARKER)) {
                 $moreInfoHeading = trim(substr($line, strlen(self::MOREINFOHEADING_MARKER)));
             } elseif (startsWith($line, self::MOREINFOLINK_MARKER)) {
                 $moreInfo = substr($line, strlen(self::MOREINFOLINK_MARKER));
                 $moreInfoChunks = explode(self::MOREINFOLINK_TEXT_MARKER, $moreInfo);
                 if (Http::isValidURI($moreInfoChunks[0])) {
                     $moreInfoUrl = $moreInfoChunks[0];
                 } else {
                     $title = Title::newFromText($moreInfoChunks[0]);
                     $moreInfoUrl = $title->getFullUrl();
                 }
                 $moreInfoLinks[] = array('article' => $moreInfoChunks[0], 'url' => $moreInfoUrl, 'text' => isset($moreInfoChunks[1]) ? $moreInfoChunks[1] : '');
             } elseif (startsWith($line, self::REQUIRE_EMAIL_MARKER)) {
                 $line = substr($line, strlen(self::REQUIRE_EMAIL_MARKER));
                 $requireEmail = $line == 'true';
             }
         }
         // load quiz's elements
         if (empty($this->mCategory)) {
             $catName = self::QUIZ_CATEGORY_PREFIX . $titleText;
             $cat = Category::newFromName($catName);
             $this->mCategory = $cat;
         }
         $quizElements = array();
         if (empty($this->mCategory) || !$this->mCategory->getID()) {
             wfDebug(__METHOD__ . ": quiz's category doesn't exist\n");
         } else {
             // get quiz elements
             $quizIterator = $this->mCategory->getMembers();
             while ($quizElementTitle = $quizIterator->current()) {
                 $quizElement = WikiaQuizElement::newFromId($quizElementTitle->getArticleId());
                 $quizElements[] = $quizElement->getData();
                 $quizIterator->next();
             }
         }
         $this->mData = array('id' => $this->mQuizId, 'name' => $titleText, 'requireEmail' => !empty($requireEmail), 'elements' => $quizElements, 'titlescreentext' => $titleScreenText, 'fbrecommendationtext' => $fbRecommendationText, 'images' => $images, 'imageShorts' => $imageShorts, 'moreinfoheading' => $moreInfoHeading, 'moreinfo' => $moreInfoLinks);
         wfDebug(__METHOD__ . ": loaded from scratch\n");
         // store it in memcache
         $wgMemc->set($this->mMemcacheKey, $this->mData, self::CACHE_TTL);
     } else {
         wfDebug(__METHOD__ . ": loaded from memcache\n");
     }
     $this->mExists = true;
     wfProfileOut(__METHOD__);
     return;
 }
 function execute($user_id)
 {
     wfProfileIn(__METHOD__);
     global $wgUser, $wgOut, $wgExtensionsPath, $wgResourceBasePath, $wgSupressPageTitle, $wgRequest, $wgJsMimeType, $wgCityId, $wgExternalSharedDB;
     global $wgEnableAchievementsStoreLocalData;
     // set basic headers
     $this->setHeaders();
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         wfProfileOut(__METHOD__);
         return;
     }
     if (!$this->userCanExecute($wgUser)) {
         $this->displayRestrictionError();
         return;
     }
     $wgSupressPageTitle = true;
     $errorMsg = null;
     $successMsg = null;
     if ($wgRequest->wasPosted()) {
         $jsonObj = json_decode($wgRequest->getVal('json-data'));
         $dbw = null;
         foreach ($jsonObj->messages as $mKey => $mVal) {
             $tokens = explode('_', $mKey);
             if (!isset($tokens[2])) {
                 $tokens[2] = null;
             }
             list(, $badgeTypeId, $lap) = $tokens;
             $badge = new AchBadge($badgeTypeId, $lap);
             if ($badge->getName() != $mVal) {
                 $article = new Article(Title::newFromText(AchConfig::getInstance()->getBadgeNameKey($badgeTypeId, $lap), NS_MEDIAWIKI));
                 $article->doEdit($mVal, '');
             }
         }
         $cond = array();
         if (empty($wgEnableAchievementsStoreLocalData)) {
             $dbw = wfGetDB(DB_MASTER, array(), $wgExternalSharedDB);
             $cond['wiki_id'] = $wgCityId;
         } else {
             $dbw = wfGetDB(DB_MASTER);
         }
         if (count($jsonObj->statusFlags)) {
             foreach ($jsonObj->statusFlags as $mKey => $mVal) {
                 $tokens = explode('_', $mKey);
                 $where = array_merge(array('id' => $tokens[1]), $cond);
                 $dbw->update('ach_custom_badges', array('enabled' => (int) $mVal), $where);
             }
         }
         $successMsg = wfMsg('achievements-special-saved');
         if ($wgRequest->getVal('add_edit_plus_category_track') == '1') {
             $catName = $wgRequest->getVal('edit_plus_category_name');
             $category = Category::newFromName($catName);
             if (!$category || !$category->getID()) {
                 $errorMsg = wfMsg('achievements-non-existing-category');
             } else {
                 $safeCatName = $category->getTitle()->getText();
                 if (strtolower($safeCatName) == 'stub' || stripos($safeCatName, 'stub ') === 0 || stripos($safeCatName, ' stub ') !== false || strripos($safeCatName, ' stub') === strlen($safeCatName) - 5) {
                     $errorMsg = wfMsg('achievements-no-stub-category');
                 } else {
                     $existingTrack = AchConfig::getInstance()->trackForCategoryExists($safeCatName);
                     if ($existingTrack !== false) {
                         $errorMsg = wfMsg('achievements-edit-plus-category-track-exists', $existingTrack);
                     } else {
                         $dbw->insert('ach_custom_badges', array('wiki_id' => $wgCityId, 'type' => BADGE_TYPE_INTRACKEDITPLUSCATEGORY, 'cat' => $safeCatName));
                         $jsonObj->sectionId = $badge_type_id = $dbw->insertId();
                     }
                 }
             }
         }
     }
     AchConfig::getInstance()->refreshData(true);
     $template = new EasyTemplate(dirname(__FILE__) . '/templates');
     $template->set_vars(array('config' => AchConfig::getInstance(), 'scrollTo' => isset($jsonObj->sectionId) ? $jsonObj->sectionId : null, 'successMsg' => $successMsg, 'errorMsg' => $errorMsg));
     $wgOut->addHTML($template->render('SpecialCustomize'));
     $wgOut->addStyle("common/article_sidebar.css");
     $wgOut->addExtensionStyle("{$wgExtensionsPath}/wikia/AchievementsII/css/customize.css");
     // FIXME: create a module with all these JS files
     $wgOut->addScript("<script type=\"{$wgJsMimeType}\" src=\"{$wgResourceBasePath}/resources/wikia/libraries/jquery/scrollto/jquery.scrollTo-1.4.2.js\"></script>\n");
     $wgOut->addScript("<script type=\"{$wgJsMimeType}\" src=\"{$wgExtensionsPath}/wikia/AchievementsII/js/achievements.js\"></script>\n");
     $wgOut->addScript("<script type=\"{$wgJsMimeType}\" src=\"{$wgResourceBasePath}/resources/wikia/libraries/aim/jquery.aim.js\"></script>\n");
     wfProfileOut(__METHOD__);
 }
 public function createVideo(array $data, &$msg, $params = array())
 {
     wfProfileIn(__METHOD__);
     $debug = !empty($params['debug']);
     $ignoreRecent = !empty($params['ignorerecent']) ? $params['ignorerecent'] : 0;
     if ($debug) {
         print "data after initial processing: \n";
         foreach (explode("\n", var_export($data, 1)) as $line) {
             print ":: {$line}\n";
         }
     }
     $addlCategories = !empty($params['addlCategories']) ? $params['addlCategories'] : array();
     $id = $data['videoId'];
     $name = $this->generateName($data);
     $metadata = $this->generateMetadata($data, $msg);
     if (!empty($msg)) {
         print "Error when generating metadata\n";
         var_dump($msg);
         wfProfileOut(__METHOD__);
         return 0;
     }
     $duplicates = WikiaFileHelper::findVideoDuplicates(static::$PROVIDER, $id);
     $dup_count = count($duplicates);
     $previousFile = null;
     if ($dup_count > 0) {
         if ($this->reupload === false) {
             // if reupload is disabled finish now
             if ($debug) {
                 print "Not uploading - video already exists and reupload is disabled\n";
             }
             return 0;
         }
         // if there are duplicates use name of one of them as reference
         // instead of generating new one
         $name = $duplicates[0]['img_name'];
         echo "Video already exists, using it's old name: {$name}\n";
         $previousFile = Title::newFromText($name, NS_FILE);
     } else {
         // sanitize name
         $name = VideoFileUploader::sanitizeTitle($name);
         // make sure the name is unique
         $name = $this->getUniqueName($name);
     }
     $metadata['destinationTitle'] = $name;
     if (!$this->validateTitle($id, $name, $msg, $debug)) {
         wfProfileOut(__METHOD__);
         return 0;
     }
     // prepare wiki categories string (eg [[Category:MyCategory]] )
     $categories = $this->generateCategories($data, $addlCategories);
     $categories[] = wfMsgForContent('videohandler-category');
     $categories = array_unique($categories);
     $categoryStr = '';
     foreach ($categories as $categoryName) {
         $category = Category::newFromName($categoryName);
         if ($category instanceof Category) {
             $categoryStr .= '[[' . $category->getTitle()->getFullText() . ']]';
         }
     }
     // parepare article body
     $apiWrapper = new static::$API_WRAPPER($id, $metadata);
     $descriptionHeader = '==' . F::app()->wf->Msg('videohandler-description') . '==';
     $body = $categoryStr . "\n" . $descriptionHeader . "\n" . $apiWrapper->getDescription();
     if ($debug) {
         print "Ready to create video\n";
         print "id:          {$id}\n";
         print "name:        {$name}\n";
         print "categories:  " . implode(',', $categories) . "\n";
         print "metadata:\n";
         foreach (explode("\n", var_export($metadata, 1)) as $line) {
             print ":: {$line}\n";
         }
         print "body:\n";
         foreach (explode("\n", $body) as $line) {
             print ":: {$line}\n";
         }
         wfProfileOut(__METHOD__);
         return 1;
     } else {
         if (!empty($ignoreRecent) && !is_null($previousFile)) {
             $revId = $previousFile->getLatestRevID();
             $revision = Revision::newFromId($revId);
             $time = $revision->getTimestamp();
             $timeUnix = intval(wfTimestamp(TS_UNIX, $time));
             $timeNow = intval(wfTimestamp(TS_UNIX, time()));
             if ($timeUnix + $ignoreRecent >= $timeNow) {
                 print "Recently uploaded, ignoring\n";
                 return 0;
             }
         }
         $uploadedTitle = null;
         $result = VideoFileUploader::uploadVideo(static::$PROVIDER, $id, $uploadedTitle, $body, false, $metadata);
         if ($result->ok) {
             $fullUrl = WikiFactory::getLocalEnvURL($uploadedTitle->getFullURL());
             print "Ingested {$uploadedTitle->getText()} from partner clip id {$id}. {$fullUrl}\n\n";
             wfWaitForSlaves(self::THROTTLE_INTERVAL);
             wfProfileOut(__METHOD__);
             return 1;
         }
     }
     wfProfileOut(__METHOD__);
     return 0;
 }
Example #21
0
	/**
	 * Update all the appropriate counts in the category table, given that
	 * we've added the categories $added and deleted the categories $deleted.
	 *
	 * @param array $added   The names of categories that were added
	 * @param array $deleted The names of categories that were deleted
	 */
	public function updateCategoryCounts( array $added, array $deleted ) {
		$that = $this;
		$method = __METHOD__;
		$dbw = wfGetDB( DB_MASTER );

		// Do this at the end of the commit to reduce lock wait timeouts
		$dbw->onTransactionPreCommitOrIdle(
			function() use ( $dbw, $that, $method, $added, $deleted ) {
				$ns = $that->getTitle()->getNamespace();

				$addFields = array( 'cat_pages = cat_pages + 1' );
				$removeFields = array( 'cat_pages = cat_pages - 1' );
				if ( $ns == NS_CATEGORY ) {
					$addFields[] = 'cat_subcats = cat_subcats + 1';
					$removeFields[] = 'cat_subcats = cat_subcats - 1';
				} elseif ( $ns == NS_FILE ) {
					$addFields[] = 'cat_files = cat_files + 1';
					$removeFields[] = 'cat_files = cat_files - 1';
				}

				if ( count( $added ) ) {
					$insertRows = array();
					foreach ( $added as $cat ) {
						$insertRows[] = array(
							'cat_title'   => $cat,
							'cat_pages'   => 1,
							'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
							'cat_files'   => ( $ns == NS_FILE ) ? 1 : 0,
						);
					}
					$dbw->upsert(
						'category',
						$insertRows,
						array( 'cat_title' ),
						$addFields,
						$method
					);
				}

				if ( count( $deleted ) ) {
					$dbw->update(
						'category',
						$removeFields,
						array( 'cat_title' => $deleted ),
						$method
					);
				}

				foreach ( $added as $catName ) {
					$cat = Category::newFromName( $catName );
					wfRunHooks( 'CategoryAfterPageAdded', array( $cat, $that ) );
				}

				foreach ( $deleted as $catName ) {
					$cat = Category::newFromName( $catName );
					wfRunHooks( 'CategoryAfterPageRemoved', array( $cat, $that ) );
				}
			}
		);
	}
 public static function getPermissionsStringsForDB()
 {
     $perms = self::getPermissions();
     $nsIDs = array();
     foreach ($perms['Namespaces'] as $ns) {
         if (strtolower($ns) == 'main') {
             $ns = '';
         }
         $nsIDs[] = MWNamespace::getCanonicalIndex(strtolower($ns));
     }
     // using array of categories from $perms, create array of category
     // names in the same form as categorylinks.cl_to
     // FIXME: is mysql_real_escape_string the way to go? of does MW have something built in?
     $catCols = array();
     foreach ($perms['Categories'] as $cat) {
         $catObj = Category::newFromName($cat);
         $catCols[] = "'" . mysql_real_escape_string($catObj->getName()) . "'";
     }
     $pgIDs = array();
     foreach ($perms['Pages'] as $pg) {
         $title = Title::newFromText($pg);
         $pgIDs[] = $title->getArticleID();
     }
     return array(count($nsIDs) > 0 ? implode(',', $nsIDs) : false, count($catCols) > 0 ? implode(',', $catCols) : false, count($pgIDs) > 0 ? implode(',', $pgIDs) : false);
 }