コード例 #1
0
 public static function onRegistration()
 {
     global $wgEmailPageGroup, $wgGroupPermissions, $wgEmailPageAllowRemoteAddr, $wgEmailPageToolboxLink, $wgEmailPageActionLink;
     if ($wgEmailPageGroup) {
         $wgGroupPermissions['sysop'][$wgEmailPageGroup] = true;
     }
     if (isset($_SERVER['SERVER_ADDR'])) {
         $wgEmailPageAllowRemoteAddr[] = $_SERVER['SERVER_ADDR'];
     }
     // If form has been posted, include the phpmailer class
     if (isset($_REQUEST['ea-send'])) {
         if ($files = glob("{$dir}/*/class.phpmailer.php")) {
             require_once $files[0];
         } else {
             die("PHPMailer class not found!");
         }
     }
     // Add toolbox and action links
     if ($wgEmailPageToolboxLink) {
         Hooks::register('SkinTemplateToolboxEnd', __CLASS__ . '::onSkinTemplateToolboxEnd');
     }
     if ($wgEmailPageActionLink) {
         Hooks::register('SkinTemplateTabs', __CLASS__ . '::onSkinTemplateTabs');
         Hooks::register('SkinTemplateNavigation', __CLASS__ . '::onSkinTemplateNavigation');
     }
 }
コード例 #2
0
 public static function setupHooks()
 {
     $rsObj = new self();
     \Hooks::register('UserSetCookies', $rsObj);
     \Hooks::register('UserLoadFromSession', $rsObj);
     \Hooks::register('UserLogout', $rsObj);
 }
コード例 #3
0
ファイル: phpunit.php プロジェクト: MediaWiki-stable/1.26.1
 public function finalSetup()
 {
     parent::finalSetup();
     global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgMainWANCache;
     global $wgLanguageConverterCacheType, $wgUseDatabaseMessages;
     global $wgLocaltimezone, $wgLocalisationCacheConf;
     global $wgDevelopmentWarnings;
     // Inject test autoloader
     require_once __DIR__ . '/../TestsAutoLoader.php';
     // wfWarn should cause tests to fail
     $wgDevelopmentWarnings = true;
     $wgMainCacheType = CACHE_NONE;
     $wgMainWANCache = CACHE_NONE;
     $wgMessageCacheType = CACHE_NONE;
     $wgParserCacheType = CACHE_NONE;
     $wgLanguageConverterCacheType = CACHE_NONE;
     $wgUseDatabaseMessages = false;
     # Set for future resets
     // Assume UTC for testing purposes
     $wgLocaltimezone = 'UTC';
     $wgLocalisationCacheConf['storeClass'] = 'LCStoreNull';
     // Bug 44192 Do not attempt to send a real e-mail
     Hooks::clear('AlternateUserMailer');
     Hooks::register('AlternateUserMailer', function () {
         return false;
     });
     // xdebug's default of 100 is too low for MediaWiki
     ini_set('xdebug.max_nesting_level', 1000);
 }
コード例 #4
0
ファイル: phpunit.php プロジェクト: ngertrudiz/mediawiki
 public function finalSetup()
 {
     parent::finalSetup();
     global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgMainWANCache;
     global $wgLanguageConverterCacheType, $wgUseDatabaseMessages;
     global $wgLocaltimezone, $wgLocalisationCacheConf;
     global $wgDevelopmentWarnings;
     // Inject test autoloader
     require_once __DIR__ . '/../TestsAutoLoader.php';
     // wfWarn should cause tests to fail
     $wgDevelopmentWarnings = true;
     // Make sure all caches and stashes are either disabled or use
     // in-process cache only to prevent tests from using any preconfigured
     // cache meant for the local wiki from outside the test run.
     // See also MediaWikiTestCase::run() which mocks CACHE_DB and APC.
     // Disabled in DefaultSettings, override local settings
     $wgMainWANCache = $wgMainCacheType = CACHE_NONE;
     // Uses CACHE_ANYTHING in DefaultSettings, use hash instead of db
     $wgMessageCacheType = $wgParserCacheType = $wgSessionCacheType = $wgLanguageConverterCacheType = 'hash';
     // Uses db-replicated in DefaultSettings
     $wgMainStash = 'hash';
     $wgUseDatabaseMessages = false;
     # Set for future resets
     // Assume UTC for testing purposes
     $wgLocaltimezone = 'UTC';
     $wgLocalisationCacheConf['storeClass'] = 'LCStoreNull';
     // Bug 44192 Do not attempt to send a real e-mail
     Hooks::clear('AlternateUserMailer');
     Hooks::register('AlternateUserMailer', function () {
         return false;
     });
     // xdebug's default of 100 is too low for MediaWiki
     ini_set('xdebug.max_nesting_level', 1000);
 }
コード例 #5
0
ファイル: MathJax.php プロジェクト: muwiki/mediawiki-mathjax
 public static function parserInit(Parser $parser)
 {
     Hooks::register('ParserBeforeStrip', self::class . '::markBlockMathTags');
     $parser->setHook('math', self::class . '::mathTag');
     $parser->setHook('nomathjax', self::class . '::noMathJaxTag');
     Hooks::register('ParserAfterTidy', self::class . '::afterTidy');
     Hooks::register('BeforePageDisplay', self::class . '::Inject_JS');
     return true;
 }
コード例 #6
0
 /**
  * Register all hooks that are necessary to update wiki data in ExactTarget
  */
 public function registerWikiHooks()
 {
     $oWikiHooks = $this->getWikiHooks();
     \Hooks::register('CreateWikiLocalJob-complete', [$oWikiHooks, 'onCreateWikiLocalJobComplete']);
     \Hooks::register('WikiFactoryChangeCommitted', [$oWikiHooks, 'onWikiFactoryChangeCommitted']);
     \Hooks::register('WikiFactoryVerticalSet', [$oWikiHooks, 'onWikiFactoryVerticalSet']);
     \Hooks::register('CityCatMappingUpdated', [$oWikiHooks, 'onCityCatMappingUpdated']);
     \Hooks::register('WikiFactoryPublicStatusChanged', [$oWikiHooks, 'onWikiFactoryPublicStatusChanged']);
 }
コード例 #7
0
ファイル: phpunit.php プロジェクト: claudinec/galan-wiki
 public function finalSetup()
 {
     parent::finalSetup();
     global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgMainWANCache;
     global $wgMainStash;
     global $wgLanguageConverterCacheType, $wgUseDatabaseMessages;
     global $wgLocaltimezone, $wgLocalisationCacheConf;
     global $wgDevelopmentWarnings;
     global $wgSessionProviders;
     global $wgJobTypeConf;
     global $wgAuthManagerConfig, $wgAuth, $wgDisableAuthManager;
     // Inject test autoloader
     require_once __DIR__ . '/../TestsAutoLoader.php';
     // wfWarn should cause tests to fail
     $wgDevelopmentWarnings = true;
     // Make sure all caches and stashes are either disabled or use
     // in-process cache only to prevent tests from using any preconfigured
     // cache meant for the local wiki from outside the test run.
     // See also MediaWikiTestCase::run() which mocks CACHE_DB and APC.
     // Disabled in DefaultSettings, override local settings
     $wgMainWANCache = $wgMainCacheType = CACHE_NONE;
     // Uses CACHE_ANYTHING in DefaultSettings, use hash instead of db
     $wgMessageCacheType = $wgParserCacheType = $wgSessionCacheType = $wgLanguageConverterCacheType = 'hash';
     // Uses db-replicated in DefaultSettings
     $wgMainStash = 'hash';
     // Use memory job queue
     $wgJobTypeConf = ['default' => ['class' => 'JobQueueMemory', 'order' => 'fifo']];
     $wgUseDatabaseMessages = false;
     # Set for future resets
     // Assume UTC for testing purposes
     $wgLocaltimezone = 'UTC';
     $wgLocalisationCacheConf['storeClass'] = 'LCStoreNull';
     // Generic MediaWiki\Session\SessionManager configuration for tests
     // We use CookieSessionProvider because things might be expecting
     // cookies to show up in a FauxRequest somewhere.
     $wgSessionProviders = [['class' => MediaWiki\Session\CookieSessionProvider::class, 'args' => [['priority' => 30, 'callUserSetCookiesHook' => true]]]];
     // Generic AuthManager configuration for testing
     $wgAuthManagerConfig = ['preauth' => [], 'primaryauth' => [['class' => MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider::class, 'args' => [['authoritative' => false]]], ['class' => MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider::class, 'args' => [['authoritative' => true]]]], 'secondaryauth' => []];
     $wgAuth = $wgDisableAuthManager ? new AuthPlugin() : new MediaWiki\Auth\AuthManagerAuthPlugin();
     // Bug 44192 Do not attempt to send a real e-mail
     Hooks::clear('AlternateUserMailer');
     Hooks::register('AlternateUserMailer', function () {
         return false;
     });
     // xdebug's default of 100 is too low for MediaWiki
     ini_set('xdebug.max_nesting_level', 1000);
     // Bug T116683 serialize_precision of 100
     // may break testing against floating point values
     // treated with PHP's serialize()
     ini_set('serialize_precision', 17);
     // TODO: we should call MediaWikiTestCase::prepareServices( new GlobalVarConfig() ) here.
     // But PHPUnit may not be loaded yet, so we have to wait until just
     // before PHPUnit_TextUI_Command::main() is executed at the end of this file.
 }
コード例 #8
0
ファイル: Hookbase.php プロジェクト: jinshana/tangocms
 /**
  * Construtor
  *
  * Gets all of the methods for child (passed in) and register
  * all of the ones that are prefixed with 'hook_'
  *
  * @param object $child
  * @return object
  */
 public function __construct(Zula_HookBase $child)
 {
     $this->_log->message('hooks: attempting to register hooks for "' . get_class($child) . '"', Log::L_DEBUG);
     $this->module = strtolower(substr(get_class($child), 0, -6));
     foreach (get_class_methods($child) as $method) {
         if (substr($method, 0, 4) == 'hook') {
             $hookName = preg_split('#([A-Z][^A-Z]*)#', $method, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
             array_shift($hookName);
             Hooks::register(strtolower(implode('_', $hookName)), array($child, $method));
         }
     }
 }
コード例 #9
0
 public function setup()
 {
     global $wgOut, $wgResourceModules, $wgAutoloadClasses, $wgExtensionAssetsPath, $IP, $wgUser, $wgAjaxCommentsPollServer, $wgAjaxCommentsLikeDislike, $wgAjaxCommentsCopyTalkpages, $wgAjaxCommentsAdmins;
     // Determine if the current user is an admin for comments
     self::$admin = count(array_intersect($wgAjaxCommentsAdmins, $wgUser->getEffectiveGroups())) > 0;
     // If options set, hook into the new revisions to change talk page additions to ajaxcomments
     if ($wgAjaxCommentsCopyTalkpages) {
         Hooks::register('PageContentSave', $this);
     }
     // Create a hook to allow external condition for whether there should be comments shown
     $title = array_key_exists('title', $_GET) ? Title::newFromText($_GET['title']) : false;
     if (!array_key_exists('action', $_REQUEST) && self::checkTitle($title)) {
         Hooks::register('BeforePageDisplay', $this);
     } else {
         $wgAjaxCommentsPollServer = -1;
     }
     // Create a hook to allow external condition for whether comments can be added or replied to (default is just user logged in)
     $this->canComment = $wgUser->isLoggedIn();
     Hooks::run('AjaxCommentsCheckWritable', array($title, &$this->canComment));
     // Redirect talk pages with AjaxComments to the comments
     if (is_object($title) && $title->getNamespace() > 0 && $title->getNamespace() & 1) {
         $ret = true;
         Hooks::run('AjaxCommentsCheckTitle', array($userpage, &$ret));
         if ($ret) {
             $userpage = Title::newFromText($title->getText(), $title->getNamespace() - 1);
             global $mediaWiki;
             if (is_object($mediaWiki)) {
                 $mediaWiki->restInPeace();
             }
             $wgOut->disable();
             wfResetOutputBuffers();
             $url = $userpage->getLocalUrl();
             header("Location: {$url}#ajaxcomments");
             wfDebugLog(__CLASS__, "Redirecting to {$url}");
             exit;
         }
     }
     // This gets the remote path even if it's a symlink (MW1.25+)
     $path = $wgExtensionAssetsPath . str_replace("{$IP}/extensions", '', dirname($wgAutoloadClasses[__CLASS__]));
     $wgResourceModules['ext.ajaxcomments']['remoteExtPath'] = $path;
     $wgOut->addModules('ext.ajaxcomments');
     $wgOut->addStyle("{$path}/styles/ajaxcomments.css");
     // Add config vars to client side
     $wgOut->addJsConfigVars('ajaxCommentsPollServer', $wgAjaxCommentsPollServer);
     $wgOut->addJsConfigVars('ajaxCommentsCanComment', $this->canComment);
     $wgOut->addJsConfigVars('ajaxCommentsLikeDislike', $wgAjaxCommentsLikeDislike);
     $wgOut->addJsConfigVars('ajaxCommentsAdmin', self::$admin);
 }
コード例 #10
0
ファイル: phpunit.php プロジェクト: paladox/2
 public function finalSetup()
 {
     parent::finalSetup();
     global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgMainWANCache;
     global $wgMainStash;
     global $wgLanguageConverterCacheType, $wgUseDatabaseMessages;
     global $wgLocaltimezone, $wgLocalisationCacheConf;
     global $wgDevelopmentWarnings;
     global $wgSessionProviders;
     global $wgJobTypeConf;
     // Inject test autoloader
     require_once __DIR__ . '/../TestsAutoLoader.php';
     // wfWarn should cause tests to fail
     $wgDevelopmentWarnings = true;
     // Make sure all caches and stashes are either disabled or use
     // in-process cache only to prevent tests from using any preconfigured
     // cache meant for the local wiki from outside the test run.
     // See also MediaWikiTestCase::run() which mocks CACHE_DB and APC.
     // Disabled in DefaultSettings, override local settings
     $wgMainWANCache = $wgMainCacheType = CACHE_NONE;
     // Uses CACHE_ANYTHING in DefaultSettings, use hash instead of db
     $wgMessageCacheType = $wgParserCacheType = $wgSessionCacheType = $wgLanguageConverterCacheType = 'hash';
     // Uses db-replicated in DefaultSettings
     $wgMainStash = 'hash';
     // Use memory job queue
     $wgJobTypeConf = array('default' => array('class' => 'JobQueueMemory', 'order' => 'fifo'));
     $wgUseDatabaseMessages = false;
     # Set for future resets
     // Assume UTC for testing purposes
     $wgLocaltimezone = 'UTC';
     $wgLocalisationCacheConf['storeClass'] = 'LCStoreNull';
     // Generic MediaWiki\Session\SessionManager configuration for tests
     // We use CookieSessionProvider because things might be expecting
     // cookies to show up in a FauxRequest somewhere.
     $wgSessionProviders = array(array('class' => 'MediaWiki\\Session\\CookieSessionProvider', 'args' => array(array('priority' => 30, 'callUserSetCookiesHook' => true))));
     // Bug 44192 Do not attempt to send a real e-mail
     Hooks::clear('AlternateUserMailer');
     Hooks::register('AlternateUserMailer', function () {
         return false;
     });
     // xdebug's default of 100 is too low for MediaWiki
     ini_set('xdebug.max_nesting_level', 1000);
     // Bug T116683 serialize_precision of 100
     // may break testing against floating point values
     // treated with PHP's serialize()
     ini_set('serialize_precision', 17);
 }
コード例 #11
0
ファイル: benchmarkParse.php プロジェクト: paladox/mediawiki
 function execute()
 {
     if ($this->hasOption('tpl-time')) {
         $this->templateTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('tpl-time')));
         Hooks::register('BeforeParserFetchTemplateAndtitle', [$this, 'onFetchTemplate']);
     }
     $this->clearLinkCache = $this->hasOption('reset-linkcache');
     // Set as a member variable to avoid function calls when we're timing the parse
     $this->linkCache = MediaWikiServices::getInstance()->getLinkCache();
     $title = Title::newFromText($this->getArg());
     if (!$title) {
         $this->error("Invalid title");
         exit(1);
     }
     if ($this->hasOption('page-time')) {
         $pageTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('page-time')));
         $id = $this->getRevIdForTime($title, $pageTimestamp);
         if (!$id) {
             $this->error("The page did not exist at that time");
             exit(1);
         }
         $revision = Revision::newFromId($id);
     } else {
         $revision = Revision::newFromTitle($title);
     }
     if (!$revision) {
         $this->error("Unable to load revision, incorrect title?");
         exit(1);
     }
     $warmup = $this->getOption('warmup', 1);
     for ($i = 0; $i < $warmup; $i++) {
         $this->runParser($revision);
     }
     $loops = $this->getOption('loops', 1);
     if ($loops < 1) {
         $this->error('Invalid number of loops specified', true);
     }
     $startUsage = getrusage();
     $startTime = microtime(true);
     for ($i = 0; $i < $loops; $i++) {
         $this->runParser($revision);
     }
     $endUsage = getrusage();
     $endTime = microtime(true);
     printf("CPU time = %.3f s, wall clock time = %.3f s\n", ($endUsage['ru_utime.tv_sec'] + $endUsage['ru_utime.tv_usec'] * 1.0E-6 - $startUsage['ru_utime.tv_sec'] - $startUsage['ru_utime.tv_usec'] * 1.0E-6) / $loops, ($endTime - $startTime) / $loops);
 }
コード例 #12
0
 /**
  * @since 1.9.1
  *
  * @return PageCreator
  */
 public function createPage(Title $title, $editContent = '', $pageContentLanguage = '')
 {
     if ($pageContentLanguage !== '') {
         \Hooks::register('PageContentLanguage', function ($titleByHook, &$pageLang) use($title, $pageContentLanguage) {
             // Only change the pageContentLanguage for the selected page
             if ($title->getPrefixedDBKey() === $titleByHook->getPrefixedDBKey()) {
                 $pageLang = $pageContentLanguage;
             }
             // MW 1.19
             return true;
         });
     }
     $this->page = new \WikiPage($title);
     if ($editContent === '') {
         $editContent = 'Content of ' . $title->getFullText();
     }
     $editMessage = 'SMW system test: create page';
     return $this->doEdit($editContent, $editMessage);
 }
コード例 #13
0
 public function testNewStyleHookInteraction()
 {
     global $wgHooks;
     $a = new NothingClass();
     $b = new NothingClass();
     // make sure to start with a clean slate
     Hooks::clear('MediaWikiHooksTest001');
     unset($wgHooks['MediaWikiHooksTest001']);
     $wgHooks['MediaWikiHooksTest001'][] = $a;
     $this->assertTrue(Hooks::isRegistered('MediaWikiHooksTest001'), 'Hook registered via $wgHooks should be noticed by Hooks::isRegistered');
     Hooks::register('MediaWikiHooksTest001', $b);
     $this->assertEquals(2, count(Hooks::getHandlers('MediaWikiHooksTest001')), 'Hooks::getHandlers() should return hooks registered via wgHooks as well as Hooks::register');
     $foo = 'quux';
     $bar = 'qaax';
     Hooks::run('MediaWikiHooksTest001', array(&$foo, &$bar));
     $this->assertEquals(1, $a->calls, 'Hooks::run() should run hooks registered via wgHooks as well as Hooks::register');
     $this->assertEquals(1, $b->calls, 'Hooks::run() should run hooks registered via wgHooks as well as Hooks::register');
     // clean up
     Hooks::clear('MediaWikiHooksTest001');
     unset($wgHooks['MediaWikiHooksTest001']);
 }
 protected function hookMailer($func = null)
 {
     \Hooks::clear('AlternateUserMailer');
     if ($func) {
         \Hooks::register('AlternateUserMailer', $func);
         // Safety
         \Hooks::register('AlternateUserMailer', function () {
             return false;
         });
     } else {
         \Hooks::register('AlternateUserMailer', function () {
             $this->fail('AlternateUserMailer hook called unexpectedly');
             return false;
         });
     }
     return new \ScopedCallback(function () {
         \Hooks::clear('AlternateUserMailer');
         \Hooks::register('AlternateUserMailer', function () {
             return false;
         });
     });
 }
コード例 #15
0
ファイル: HooksTest.php プロジェクト: yusufchang/app
 public function testNewStyleHooks()
 {
     $foo = 'Foo';
     $bar = 'Bar';
     $i = new NothingClass();
     Hooks::register('MediaWikiHooksTest001', array($i, 'someNonStatic'));
     Hooks::run('MediaWikiHooksTest001', array(&$foo, &$bar));
     $this->assertEquals('fOO', $foo, 'Standard method');
     $foo = 'Foo';
     Hooks::register('MediaWikiHooksTest001', $i);
     Hooks::run('MediaWikiHooksTest001', array(&$foo, &$bar));
     $this->assertEquals('foo', $foo, 'onEventName style');
     $foo = 'Foo';
     Hooks::register('MediaWikiHooksTest001', array($i, 'someNonStaticWithData', 'baz'));
     Hooks::run('MediaWikiHooksTest001', array(&$foo, &$bar));
     $this->assertEquals('baz', $foo, 'Data included');
     $foo = 'Foo';
     Hooks::register('MediaWikiHooksTest001', array($i, 'someStatic'));
     Hooks::run('MediaWikiHooksTest001', array(&$foo, &$bar));
     $this->assertEquals('bah', $foo, 'Standard static method');
     $foo = 'Foo';
 }
コード例 #16
0
 /**
  * @param AuthPlugin $auth AuthPlugin to wrap
  * @param string|null $requestType Class name of the
  *  PasswordAuthenticationRequest to use. If $auth->domainList() returns
  *  more than one domain, this must be a PasswordDomainAuthenticationRequest.
  */
 public function __construct(AuthPlugin $auth, $requestType = null)
 {
     parent::__construct();
     if ($auth instanceof AuthManagerAuthPlugin) {
         throw new \InvalidArgumentException('Trying to wrap AuthManagerAuthPlugin in AuthPluginPrimaryAuthenticationProvider ' . 'makes no sense.');
     }
     $need = count($auth->domainList()) > 1 ? PasswordDomainAuthenticationRequest::class : PasswordAuthenticationRequest::class;
     if ($requestType === null) {
         $requestType = $need;
     } elseif ($requestType !== $need && !is_subclass_of($requestType, $need)) {
         throw new \InvalidArgumentException("{$requestType} is not a {$need}");
     }
     $this->auth = $auth;
     $this->requestType = $requestType;
     $this->hasDomain = $requestType === PasswordDomainAuthenticationRequest::class || is_subclass_of($requestType, PasswordDomainAuthenticationRequest::class);
     $this->authoritative = $auth->strict();
     // Registering hooks from core is unusual, but is needed here to be
     // able to call the AuthPlugin methods those hooks replace.
     \Hooks::register('UserSaveSettings', [$this, 'onUserSaveSettings']);
     \Hooks::register('UserGroupsChanged', [$this, 'onUserGroupsChanged']);
     \Hooks::register('UserLoggedIn', [$this, 'onUserLoggedIn']);
     \Hooks::register('LocalUserCreated', [$this, 'onLocalUserCreated']);
 }
コード例 #17
0
ファイル: phpunit.php プロジェクト: mangowi/mediawiki
 public function finalSetup()
 {
     parent::finalSetup();
     global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
     global $wgLanguageConverterCacheType, $wgUseDatabaseMessages;
     global $wgLocaltimezone, $wgLocalisationCacheConf;
     global $wgDevelopmentWarnings;
     // wfWarn should cause tests to fail
     $wgDevelopmentWarnings = true;
     $wgMainCacheType = CACHE_NONE;
     $wgMessageCacheType = CACHE_NONE;
     $wgParserCacheType = CACHE_NONE;
     $wgLanguageConverterCacheType = CACHE_NONE;
     $wgUseDatabaseMessages = false;
     # Set for future resets
     // Assume UTC for testing purposes
     $wgLocaltimezone = 'UTC';
     $wgLocalisationCacheConf['storeClass'] = 'LCStore_Null';
     // Bug 44192 Do not attempt to send a real e-mail
     Hooks::clear('AlternateUserMailer');
     Hooks::register('AlternateUserMailer', function () {
         return false;
     });
 }
コード例 #18
0
 function execute()
 {
     if ($this->hasOption('tpl-time')) {
         $this->templateTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('tpl-time')));
         Hooks::register('BeforeParserFetchTemplateAndtitle', array($this, 'onFetchTemplate'));
     }
     $title = Title::newFromText($this->getArg());
     if (!$title) {
         $this->error("Invalid title");
         exit(1);
     }
     if ($this->hasOption('page-time')) {
         $pageTimestamp = wfTimestamp(TS_MW, strtotime($this->getOption('page-time')));
         $id = $this->getRevIdForTime($title, $pageTimestamp);
         if (!$id) {
             $this->error("The page did not exist at that time");
             exit(1);
         }
         $revision = Revision::newFromId($id);
     } else {
         $revision = Revision::newFromTitle($title);
     }
     if (!$revision) {
         $this->error("Unable to load revision, incorrect title?");
         exit(1);
     }
     if (!$this->hasOption('cold')) {
         $this->runParser($revision);
     }
     $startUsage = getrusage();
     $startTime = microtime(true);
     $this->runParser($revision);
     $endUsage = getrusage();
     $endTime = microtime(true);
     printf("CPU time = %.3f s, wall clock time = %.3f s\n", $endUsage['ru_utime.tv_sec'] + $endUsage['ru_utime.tv_usec'] * 1.0E-6 - $startUsage['ru_utime.tv_sec'] - $startUsage['ru_utime.tv_usec'] * 1.0E-6, $endTime - $startTime);
 }
コード例 #19
0
ファイル: LigminchaSettings.php プロジェクト: uinerd/Code
    $wgCookieDomain = '';
    foreach (array('UserID', 'UserName', 'Token', 'LoggedOut', '_session') as $k) {
        $wgUser->clearCookie($k);
    }
    $wgCookieDomain = $domain;
}
// Set up a private sysop-only Admin namespace
define('NS_ADMIN', 1020);
$wgExtraNamespaces[NS_ADMIN] = 'Admin';
$wgExtraNamespaces[NS_ADMIN + 1] = 'Admin_talk';
Hooks::register('ParserFirstCallInit', 'wfProtectAdminNamespace');
function wfProtectAdminNamespace(Parser $parser)
{
    global $wgTitle, $wgUser, $wgOut, $mediaWiki;
    if (is_object($wgTitle) && $wgTitle->getNamespace() == NS_ADMIN && !in_array('bureaucrat', $wgUser->getEffectiveGroups())) {
        if (is_object($mediaWiki)) {
            $mediaWiki->restInPeace();
        }
        $wgOut->disable();
        wfResetOutputBuffers();
        header("Location: https://wiki.ligmincha.com.br/Página_principal");
    }
    return true;
}
// Set "remember me" on by default
Hooks::register('UserLoginForm', 'wfRememberMe');
function wfRememberMe(&$template)
{
    $template->data['remember'] = true;
    return true;
}
コード例 #20
0
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgContributionTrackingFundraiserMaintenance, $wgContributionTrackingFundraiserMaintenanceUnsched;
     // FIXME: Deprecate "language" param.
     $language = $this->getRequest()->getVal('language');
     if ($language) {
         $this->getContext()->setLanguage($language);
         global $wgLang;
         $wgLang = $this->getContext()->getLanguage();
         // BackCompat
     }
     $gatewayName = $this->getGatewayIdentifier();
     $className = DonationInterface::getAdapterClassForGateway($gatewayName);
     try {
         $this->adapter = new $className();
         $this->logger = DonationLoggerFactory::getLogger($this->adapter);
         $this->getOutput()->addModuleStyles('donationInterface.styles');
         $this->getOutput()->addModules('donationInterface.skinOverride');
     } catch (Exception $ex) {
         if (!$this->logger) {
             $this->logger = DonationLoggerFactory::getLoggerForType($className, $this->getLogPrefix());
         }
         $this->logger->error("Exception setting up GatewayPage with adapter class {$className}: " . "{$ex->getMessage()}\n{$ex->getTraceAsString()}");
         // Setup scrambled, no point in continuing
         $this->displayFailPage();
         return;
     }
     if ($this->adapter->getGlobal('Enabled') !== true) {
         $this->logger->info('Displaying fail page for disabled gateway');
         $this->displayFailPage();
         return;
     }
     if ($wgContributionTrackingFundraiserMaintenance || $wgContributionTrackingFundraiserMaintenanceUnsched) {
         $this->getOutput()->redirect(Title::newFromText('Special:FundraiserMaintenance')->getFullURL(), '302');
         return;
     }
     if ($this->adapter->getFinalStatus() === FinalStatus::FAILED) {
         $this->logger->info('Displaying fail page for failed GatewayReady checks');
         $this->displayFailPage();
         return;
     }
     Hooks::register('MakeGlobalVariablesScript', array($this->adapter, 'setClientVariables'));
     try {
         $this->handleRequest();
     } catch (Exception $ex) {
         $this->logger->error("Displaying fail page for exception: " . $ex->getMessage());
         $this->displayFailPage();
         return;
     }
 }
コード例 #21
0
 /**
  * Called when the extension is first loaded
  */
 public static function onRegistration()
 {
     global $wgExtensionFunctions;
     $wgExtensionFunctions[] = __CLASS__ . '::setup';
     Hooks::register('ParserFirstCallInit', __CLASS__ . '::onParserFirstCallInit');
 }
コード例 #22
0
 private function setupEnvironment()
 {
     global $gDatabase, $cDatabaseConnectionString, $cMyDotCnfFile, $cDatabaseModule, $cIncludePath, $cLoggerName, $gLogger;
     set_exception_handler(array("Hotel", "exceptionHandler"));
     // check all the required PHP extensions are enabled on this SAPI
     $this->checkPhpExtensions();
     // start output buffering before anything is sent to the browser.
     ob_start();
     // not caught by the autoloader :(
     require_once 'smarty/Smarty.class.php';
     // many exceptions defined in one file, let's not clutter stuff.
     // This ofc breaks the autoloading, so let's include them all now.
     // (Depends on some smarty stuff)
     require_once $cIncludePath . "/_Exceptions.php";
     spl_autoload_register("Hotel::autoLoader");
     Session::start();
     $gLogger = new $cLoggerName();
     $gLogger->log("Initialising logger!");
     if (!extension_loaded($cDatabaseModule)) {
         throw new ExtensionUnavailableException($cDatabaseModule);
     }
     $mycnf = parse_ini_file($cMyDotCnfFile);
     $gDatabase = new Database($cDatabaseConnectionString, $mycnf["user"], $mycnf["password"]);
     // tidy up sensitive data we don't want lying around.
     unset($mycnf);
     // use exceptions on failed database stuff
     $gDatabase->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     // can we tidy up the output with tidy before we send it?
     if (extension_loaded("tidy")) {
         // Yes!
         global $cUseTidy;
         if ($cUseTidy) {
             // register a new function to hook into the output bit
             Hooks::register("BeforeOutputSend", function ($params) {
                 $tidy = new Tidy();
                 global $cTidyOptions;
                 return $tidy->repairString($params[0], $cTidyOptions, "utf8");
             });
         }
     }
     global $gCookieJar;
     $gCookieJar = array();
 }
コード例 #23
0
 /**
  * Insert hardcoded interwiki in the lookup table.
  *
  * This function insert a set of well known interwikis that are used in
  * the parser tests. They can be considered has fixtures are injected in
  * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
  * Since we are not interested in looking up interwikis in the database,
  * the hook completely replace the existing mechanism (hook returns false).
  *
  * @return closure for teardown
  */
 private function setupInterwikis()
 {
     # Hack: insert a few Wikipedia in-project interwiki prefixes,
     # for testing inter-language links
     Hooks::register('InterwikiLoadPrefix', function ($prefix, &$iwData) {
         static $testInterwikis = ['local' => ['iw_url' => 'http://doesnt.matter.org/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 0], 'wikipedia' => ['iw_url' => 'http://en.wikipedia.org/wiki/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 0], 'meatball' => ['iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 0], 'memoryalpha' => ['iw_url' => 'http://www.memory-alpha.org/en/index.php/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 0], 'zh' => ['iw_url' => 'http://zh.wikipedia.org/wiki/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 1], 'es' => ['iw_url' => 'http://es.wikipedia.org/wiki/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 1], 'fr' => ['iw_url' => 'http://fr.wikipedia.org/wiki/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 1], 'ru' => ['iw_url' => 'http://ru.wikipedia.org/wiki/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 1], 'mi' => ['iw_url' => 'http://mi.wikipedia.org/wiki/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 1], 'mul' => ['iw_url' => 'http://wikisource.org/wiki/$1', 'iw_api' => '', 'iw_wikiid' => '', 'iw_local' => 1]];
         if (array_key_exists($prefix, $testInterwikis)) {
             $iwData = $testInterwikis[$prefix];
         }
         // We only want to rely on the above fixtures
         return false;
     });
     // hooks::register
     return function () {
         // Tear down
         Hooks::clear('InterwikiLoadPrefix');
     };
 }
コード例 #24
0
 public static function setupHooks()
 {
     $oImageReviewHooks = new self();
     \Hooks::register('WikiFactoryPublicStatusChange', [$oImageReviewHooks, 'onWikiFactoryPublicStatusChange']);
 }
コード例 #25
0
ファイル: Theme.php プロジェクト: jinshana/tangocms
 /**
  * Constructs the main theme object. If the provided name contains a
  * forward slash, the left side will be used as the 'name', and
  * the right side will be used as the 'style'.
  *
  * @param string $name
  * @param string $style
  * @return object
  */
 public function __construct($name, $style = null)
 {
     if ($style) {
         list($name) = explode('/', $name);
     } else {
         list($name, $style) = explode('/', $name . '/');
     }
     if (!self::exists($name, $style)) {
         throw new Theme_NoExist("unable to construct theme '{$name}/{$style}' as it does not exist");
     }
     $this->details = array('path' => $this->_zula->getDir('themes') . '/' . $name, 'style' => $style);
     // Load all details for the theme
     $dom = new DomDocument();
     $dom->load($this->details['path'] . '/details.xml');
     foreach ($dom->getElementsByTagName('theme')->item(0)->getElementsByTagName('*') as $item) {
         $this->details[$item->nodeName] = $item->nodeValue;
     }
     // Construct parent view and register cache_purge hook
     if ($style) {
         try {
             parent::__construct($this->details['path'] . '/styles/' . $style . '/main_template.html');
         } catch (View_FileNoExist $e) {
             parent::__construct($this->details['path'] . '/main_template.html');
         }
     } else {
         parent::__construct($this->details['path'] . '/main_template.html');
     }
     Hooks::register('cache_purge', array('Theme', 'clearJsTmp'));
 }
コード例 #26
0
ファイル: PowerUser.hooks.php プロジェクト: Tjorriemorrie/app
 public static function setupHooks()
 {
     $oPowerUserHooks = new self();
     \Hooks::register('NewRevisionFromEditComplete', [$oPowerUserHooks, 'onNewRevisionFromEditComplete']);
     \Hooks::register('WikiaSkinTopScripts', [$oPowerUserHooks, 'onWikiaSkinTopScripts']);
 }
コード例 #27
0
 public function testRunLegacyHooks()
 {
     Hooks::register('testRunLegacyHooks', __CLASS__ . '::dummyHookHandler');
     $content = new WikitextContent('test text');
     $ok = ContentHandler::runLegacyHooks('testRunLegacyHooks', array('foo', &$content, 'bar'), false);
     $this->assertTrue($ok, "runLegacyHooks should have returned true");
     $this->assertEquals("TEST TEXT", $content->getNativeData());
 }
コード例 #28
0
ファイル: HooksTest.php プロジェクト: sttt/kohana-hooks
 /**
  * Tests Hooks::fire().
  * 
  * @test
  * @dataProvider provider_fire
  * @param   array   functions
  * @param   string  expected
  */
 public function test_fire($parameters, $expected)
 {
     foreach ($parameters as $parameter) {
         Hooks::register('event', function ($k, &$array) {
             for ($i = $k; $i < $k + 10; $i++) {
                 $array[] = $i;
             }
         }, array($parameter));
     }
     $array = array();
     Hooks::fire('event', array(&$array));
     $count = 0;
     foreach ($parameters as $parameter) {
         for ($i = $parameter; $i < $parameter + 10; $i++) {
             $count++;
             $this->assertContains($i, $array);
         }
     }
     $this->assertSame($count, sizeof($array));
 }
コード例 #29
0
ファイル: HooksTest.php プロジェクト: MediaWiki-stable/1.26.1
 /**
  * @expectedException FatalError
  * @covers Hooks::run
  */
 public function testFatalError()
 {
     Hooks::register('MediaWikiHooksTest001', function () {
         return 'test';
     });
     Hooks::run('MediaWikiHooksTest001', array());
 }
コード例 #30
0
 protected function doStore(EditPage $editor)
 {
     $title = $editor->getTitle();
     // If they used redlink=1 and the page exists, redirect to the main article and send notice
     if ($this->getRequest()->getBool('redlink') && $title->exists()) {
         $this->logMessage(wfMessage('sf_autoedit_redlinkexists')->parse(), self::WARNING);
     }
     $permErrors = $title->getUserPermissionsErrors('edit', $this->getUser());
     // if this title needs to be created, user needs create rights
     if (!$title->exists()) {
         $permErrors = array_merge($permErrors, wfArrayDiff2($title->getUserPermissionsErrors('create', $this->getUser()), $permErrors));
     }
     if ($permErrors) {
         // Auto-block user's IP if the account was "hard" blocked
         $this->getUser()->spreadAnyEditBlock();
         foreach ($permErrors as $error) {
             $this->logMessage(call_user_func_array('wfMessage', $error)->parse());
         }
         return;
     }
     $resultDetails = false;
     # Allow bots to exempt some edits from bot flagging
     $bot = $this->getUser()->isAllowed('bot') && $editor->bot;
     $request = $editor->sfFauxRequest;
     if ($editor->tokenOk($request)) {
         $ctx = RequestContext::getMain();
         $tempTitle = $ctx->getTitle();
         $ctx->setTitle($title);
         $status = $editor->internalAttemptSave($resultDetails, $bot);
         $ctx->setTitle($tempTitle);
     } else {
         throw new MWException(wfMessage('session_fail_preview')->parse());
     }
     switch ($status->value) {
         case EditPage::AS_HOOK_ERROR_EXPECTED:
             // A hook function returned an error
             // show normal Edit page
             // remove Preview and Diff standard buttons from editor page
             Hooks::register('EditPageBeforeEditButtons', function (&$editor, &$buttons, &$tabindex) {
                 foreach (array_keys($buttons) as $key) {
                     if ($key !== 'save') {
                         unset($buttons[$key]);
                     }
                 }
             });
             // Context title needed for correct Cancel link
             $editor->setContextTitle($title);
             $editor->showEditForm();
             return false;
             // success
         // success
         case EditPage::AS_CONTENT_TOO_BIG:
             // Content too big (> $wgMaxArticleSize)
         // Content too big (> $wgMaxArticleSize)
         case EditPage::AS_ARTICLE_WAS_DELETED:
             // article was deleted while editting and param wpRecreate == false or form was not posted
         // article was deleted while editting and param wpRecreate == false or form was not posted
         case EditPage::AS_CONFLICT_DETECTED:
             // (non-resolvable) edit conflict
         // (non-resolvable) edit conflict
         case EditPage::AS_SUMMARY_NEEDED:
             // no edit summary given and the user has forceeditsummary set and the user is not editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
         // no edit summary given and the user has forceeditsummary set and the user is not editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
         case EditPage::AS_TEXTBOX_EMPTY:
             // user tried to create a new section without content
         // user tried to create a new section without content
         case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
             // article is too big (> $wgMaxArticleSize), after merging in the new section
         // article is too big (> $wgMaxArticleSize), after merging in the new section
         case EditPage::AS_END:
             // WikiPage::doEdit() was unsuccessfull
             throw new MWException(wfMessage('sf_autoedit_fail', $this->mOptions['target'])->parse());
         case EditPage::AS_HOOK_ERROR:
             // Article update aborted by a hook function
             $this->logMessage('Article update aborted by a hook function', self::DEBUG);
             return false;
             // success
             // TODO: This error code only exists from 1.21 onwards. It is
             // suitably handled by the default branch, but really should get its
             // own branch. Uncomment once compatibility to pre1.21 is dropped.
             //			case EditPage::AS_PARSE_ERROR: // can't parse content
             //
             //				throw new MWException( $status->getHTML() );
             //				return true; // fail
         // success
         // TODO: This error code only exists from 1.21 onwards. It is
         // suitably handled by the default branch, but really should get its
         // own branch. Uncomment once compatibility to pre1.21 is dropped.
         //			case EditPage::AS_PARSE_ERROR: // can't parse content
         //
         //				throw new MWException( $status->getHTML() );
         //				return true; // fail
         case EditPage::AS_SUCCESS_NEW_ARTICLE:
             // Article successfully created
             $query = $resultDetails['redirect'] ? 'redirect=no' : '';
             $anchor = isset($resultDetails['sectionanchor']) ? $resultDetails['sectionanchor'] : '';
             $this->getOutput()->redirect($title->getFullURL($query) . $anchor);
             $this->getResult()->addValue(NULL, 'redirect', $title->getFullURL($query) . $anchor);
             return false;
             // success
         // success
         case EditPage::AS_SUCCESS_UPDATE:
             // Article successfully updated
             $extraQuery = '';
             $sectionanchor = $resultDetails['sectionanchor'];
             // Give extensions a chance to modify URL query on update
             Hooks::run('ArticleUpdateBeforeRedirect', array($editor->getArticle(), &$sectionanchor, &$extraQuery));
             if ($resultDetails['redirect']) {
                 if ($extraQuery == '') {
                     $extraQuery = 'redirect=no';
                 } else {
                     $extraQuery = 'redirect=no&' . $extraQuery;
                 }
             }
             $this->getOutput()->redirect($title->getFullURL($extraQuery) . $sectionanchor);
             $this->getResult()->addValue(NULL, 'redirect', $title->getFullURL($extraQuery) . $sectionanchor);
             return false;
             // success
         // success
         case EditPage::AS_BLANK_ARTICLE:
             // user tried to create a blank page
             $this->logMessage('User tried to create a blank page', self::DEBUG);
             $this->getOutput()->redirect($editor->getContextTitle()->getFullURL());
             $this->getResult()->addValue(NULL, 'redirect', $editor->getContextTitle()->getFullURL());
             return false;
             // success
         // success
         case EditPage::AS_SPAM_ERROR:
             // summary contained spam according to one of the regexes in $wgSummarySpamRegex
             $match = $resultDetails['spam'];
             if (is_array($match)) {
                 $match = $this->getLanguage()->listToText($match);
             }
             throw new MWException(wfMessage('spamprotectionmatch', wfEscapeWikiText($match))->parse());
             // FIXME: Include better error message
         // FIXME: Include better error message
         case EditPage::AS_BLOCKED_PAGE_FOR_USER:
             // User is blocked from editting editor page
             throw new UserBlockedError($this->getUser()->getBlock());
         case EditPage::AS_IMAGE_REDIRECT_ANON:
             // anonymous user is not allowed to upload (User::isAllowed('upload') == false)
         // anonymous user is not allowed to upload (User::isAllowed('upload') == false)
         case EditPage::AS_IMAGE_REDIRECT_LOGGED:
             // logged in user is not allowed to upload (User::isAllowed('upload') == false)
             throw new PermissionsError('upload');
         case EditPage::AS_READ_ONLY_PAGE_ANON:
             // editor anonymous user is not allowed to edit editor page
         // editor anonymous user is not allowed to edit editor page
         case EditPage::AS_READ_ONLY_PAGE_LOGGED:
             // editor logged in user is not allowed to edit editor page
             throw new PermissionsError('edit');
         case EditPage::AS_READ_ONLY_PAGE:
             // wiki is in readonly mode (wfReadOnly() == true)
             throw new ReadOnlyError();
         case EditPage::AS_RATE_LIMITED:
             // rate limiter for action 'edit' was tripped
             throw new ThrottledError();
         case EditPage::AS_NO_CREATE_PERMISSION:
             // user tried to create editor page, but is not allowed to do that ( Title->usercan('create') == false )
             $permission = $title->isTalkPage() ? 'createtalk' : 'createpage';
             throw new PermissionsError($permission);
         default:
             // We don't recognize $status->value. The only way that can happen
             // is if an extension hook aborted from inside ArticleSave.
             // Render the status object into $editor->hookError
             $editor->hookError = '<div class="error">' . $status->getWikitext() . '</div>';
             throw new MWException($status->getHTML());
     }
 }