本文整理汇总了PHP中Hooks类的典型用法代码示例。如果您正苦于以下问题:PHP Hooks类的具体用法?PHP Hooks怎么用?PHP Hooks使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Hooks类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: event
/**
* 运行事件
* @param string $which 事件名称
* @param string $type 事件类型 '':pc站 m:手机站
* @return Hooks
*/
public static function event($which, $assets = '', $type = '')
{
if (empty(self::$instance)) {
self::$instance = new static();
}
self::$instance->type = $type;
self::$instance->assets = $assets;
self::$instance->position($which);
self::$instance->type = '';
self::$instance->assets = '';
return self::$instance;
}
示例2: __construct
public function __construct()
{
parent::__construct();
$paths = [];
// Autodiscover extension unit tests
$registry = ExtensionRegistry::getInstance();
foreach ($registry->getAllThings() as $info) {
$paths[] = dirname($info['path']) . '/tests/phpunit';
}
// Extensions can return a list of files or directories
Hooks::run('UnitTestsList', [&$paths]);
foreach (array_unique($paths) as $path) {
if (is_dir($path)) {
// If the path is a directory, search for test cases.
// @since 1.24
$suffixes = ['Test.php'];
$fileIterator = new File_Iterator_Facade();
$matchingFiles = $fileIterator->getFilesAsArray($path, $suffixes);
$this->addTestFiles($matchingFiles);
} elseif (file_exists($path)) {
// Add a single test case or suite class
$this->addTestFile($path);
}
}
if (!$paths) {
$this->addTest(new DummyExtensionsTest('testNothing'));
}
}
示例3: getTokenTypes
private function getTokenTypes()
{
// If we're in a mode that breaks the same-origin policy, no tokens can
// be obtained
if ($this->lacksSameOriginSecurity()) {
return [];
}
static $types = null;
if ($types) {
return $types;
}
$types = ['patrol' => ['ApiQueryRecentChanges', 'getPatrolToken']];
$names = ['edit', 'delete', 'protect', 'move', 'block', 'unblock', 'email', 'import', 'watch', 'options'];
foreach ($names as $name) {
$types[$name] = ['ApiQueryInfo', 'get' . ucfirst($name) . 'Token'];
}
Hooks::run('ApiTokensGetTokenTypes', [&$types]);
// For forwards-compat, copy any token types from ApiQueryTokens that
// we don't already have something for.
$user = $this->getUser();
$request = $this->getRequest();
foreach (ApiQueryTokens::getTokenTypeSalts() as $name => $salt) {
if (!isset($types[$name])) {
$types[$name] = function () use($salt, $user, $request) {
return ApiQueryTokens::getToken($user, $request->getSession(), $salt)->toString();
};
}
}
ksort($types);
return $types;
}
示例4: check_user_identity
function check_user_identity($required = true)
{
$realm = 'OpenMediakit Transcoder';
if ($required && !isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="' . $realm . '"');
header('HTTP/1.0 401 Unauthorized');
echo 'Please authenticate';
exit;
}
/*
* Autre exemple de hook possible:
* Hooks::call('pre_check_user_identity', array($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']));
*/
require_once __DIR__ . '/../modules/users/libs/users.php';
if ($required && isset($_SERVER['PHP_AUTH_USER'])) {
$GLOBALS["me"] = Users::auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
} else {
$GLOBALS["me"] = array();
}
if ($required && !$GLOBALS["me"]) {
header('WWW-Authenticate: Basic realm="' . $realm . '"');
header('HTTP/1.0 401 Unauthorized');
echo 'Login or password incorrect, or account disabled';
exit;
}
Hooks::call('post_check_user_identity', $GLOBALS["me"]);
// mq("UPDATE user SET lastlogin=NOW() WHERE id='".$GLOBALS["me"]["id"]."';");
}
示例5: setup
protected function setup($par)
{
// Options
$opts = new FormOptions();
$this->opts = $opts;
// bind
$opts->add('hideliu', false);
$opts->add('hidepatrolled', $this->getUser()->getBoolOption('newpageshidepatrolled'));
$opts->add('hidebots', false);
$opts->add('hideredirs', true);
$opts->add('limit', $this->getUser()->getIntOption('rclimit'));
$opts->add('offset', '');
$opts->add('namespace', '0');
$opts->add('username', '');
$opts->add('feed', '');
$opts->add('tagfilter', '');
$opts->add('invert', false);
$this->customFilters = [];
Hooks::run('SpecialNewPagesFilters', [$this, &$this->customFilters]);
foreach ($this->customFilters as $key => $params) {
$opts->add($key, $params['default']);
}
// Set values
$opts->fetchValuesFromRequest($this->getRequest());
if ($par) {
$this->parseParams($par);
}
// Validate
$opts->validateIntBounds('limit', 0, 5000);
}
示例6: setup
public function setup()
{
global $wgOut, $wgExtensionAssetsPath, $IP, $wgResourceModules, $wgAutoloadClasses, $wgHooks, $wgParser, $wgJQUploadFileMagic;
// If attachments allowed in this page, add the module into the page
if ($title = array_key_exists('title', $_GET) ? Title::newFromText($_GET['title']) : false) {
$this->id = $title->getArticleID();
}
// Set up the #file parser-function
$wgParser->setFunctionHook($wgJQUploadFileMagic, array($this, 'expandFile'), SFH_NO_HASH);
// Allow overriding of the file ID
Hooks::run('jQueryUploadSetId', array($title, &$this->id));
// If attachments allowed in this page, add the module into the page
$attach = is_object($title) && $this->id && !$title->isRedirect() && !array_key_exists('action', $_REQUEST) && $title->getNamespace() != 6;
if ($attach) {
Hooks::run('jQueryUploadAddAttachLink', array($title, &$attach));
}
if ($attach) {
$this->head();
$wgHooks['BeforePageDisplay'][] = $this;
}
// Add the extensions own js
$path = $wgExtensionAssetsPath . str_replace("{$IP}/extensions", '', dirname($wgAutoloadClasses[__CLASS__]));
$wgResourceModules['ext.jqueryupload']['remoteExtPath'] = $path;
$wgOut->addModules('ext.jqueryupload');
$wgOut->addStyle("{$path}/styles/jqueryupload.css");
}
示例7: instance
/**
* Returns the globally available instance of a Hooks
* @return object The Hooks object.
*/
public static function instance()
{
if (!isset(self::$instance) && !self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
示例8: setupHooks
public static function setupHooks()
{
$rsObj = new self();
\Hooks::register('UserSetCookies', $rsObj);
\Hooks::register('UserLoadFromSession', $rsObj);
\Hooks::register('UserLogout', $rsObj);
}
示例9: onRegistration
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');
}
}
示例10: replaceSection
/**
* @param string|number|null|bool $sectionId
* @param Content $with
* @param string $sectionTitle
*
* @throws MWException
* @return Content
*
* @see Content::replaceSection()
*/
public function replaceSection($sectionId, Content $with, $sectionTitle = '')
{
$myModelId = $this->getModel();
$sectionModelId = $with->getModel();
if ($sectionModelId != $myModelId) {
throw new MWException("Incompatible content model for section: " . "document uses {$myModelId} but " . "section uses {$sectionModelId}.");
}
$oldtext = $this->getNativeData();
$text = $with->getNativeData();
if (strval($sectionId) === '') {
return $with;
# XXX: copy first?
}
if ($sectionId === 'new') {
# Inserting a new section
$subject = $sectionTitle ? wfMessage('newsectionheaderdefaultlevel')->rawParams($sectionTitle)->inContentLanguage()->text() . "\n\n" : '';
if (Hooks::run('PlaceNewSection', array($this, $oldtext, $subject, &$text))) {
$text = strlen(trim($oldtext)) > 0 ? "{$oldtext}\n\n{$subject}{$text}" : "{$subject}{$text}";
}
} else {
# Replacing an existing section; roll out the big guns
global $wgParser;
$text = $wgParser->replaceSection($oldtext, $sectionId, $text);
}
$newContent = new static($text);
return $newContent;
}
示例11: execute
public function execute($par)
{
$this->setHeaders();
$this->getOutput()->addModuleStyles('mediawiki.special');
$this->edits = SiteStats::edits();
$this->good = SiteStats::articles();
$this->images = SiteStats::images();
$this->total = SiteStats::pages();
$this->users = SiteStats::users();
$this->activeUsers = SiteStats::activeUsers();
$this->hook = '';
$text = Xml::openElement('table', ['class' => 'wikitable mw-statistics-table']);
# Statistic - pages
$text .= $this->getPageStats();
# Statistic - edits
$text .= $this->getEditStats();
# Statistic - users
$text .= $this->getUserStats();
# Statistic - usergroups
$text .= $this->getGroupStats();
# Statistic - other
$extraStats = [];
if (Hooks::run('SpecialStatsAddExtra', [&$extraStats, $this->getContext()])) {
$text .= $this->getOtherStats($extraStats);
}
$text .= Xml::closeElement('table');
# Customizable footer
$footer = $this->msg('statistics-footer');
if (!$footer->isBlank()) {
$text .= "\n" . $footer->parse();
}
$this->getOutput()->addHTML($text);
}
示例12: execute
function execute($par)
{
/**
* Some satellite ISPs use broken precaching schemes that log people out straight after
* they're logged in (bug 17790). Luckily, there's a way to detect such requests.
*/
if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '&') !== false) {
wfDebug("Special:Userlogout request {$_SERVER['REQUEST_URI']} looks suspicious, denying.\n");
throw new HttpError(400, $this->msg('suspicious-userlogout'), $this->msg('loginerror'));
}
$this->setHeaders();
$this->outputHeader();
// Make sure it's possible to log out
$session = MediaWiki\Session\SessionManager::getGlobalSession();
if (!$session->canSetUser()) {
throw new ErrorPageError('cannotlogoutnow-title', 'cannotlogoutnow-text', [$session->getProvider()->describe(RequestContext::getMain()->getLanguage())]);
}
$user = $this->getUser();
$oldName = $user->getName();
$user->logout();
$loginURL = SpecialPage::getTitleFor('Userlogin')->getFullURL($this->getRequest()->getValues('returnto', 'returntoquery'));
$out = $this->getOutput();
$out->addWikiMsg('logouttext', $loginURL);
// Hook.
$injected_html = '';
Hooks::run('UserLogoutComplete', [&$user, &$injected_html, $oldName]);
$out->addHTML($injected_html);
$out->returnToMain();
}
示例13: getConfigSettings
/**
* @param ResourceLoaderContext $context
* @return array
*/
protected function getConfigSettings($context)
{
$hash = $context->getHash();
if (isset($this->configVars[$hash])) {
return $this->configVars[$hash];
}
global $wgContLang;
$mainPage = Title::newMainPage();
/**
* Namespace related preparation
* - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
* - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
*/
$namespaceIds = $wgContLang->getNamespaceIds();
$caseSensitiveNamespaces = array();
foreach (MWNamespace::getCanonicalNamespaces() as $index => $name) {
$namespaceIds[$wgContLang->lc($name)] = $index;
if (!MWNamespace::isCapitalized($index)) {
$caseSensitiveNamespaces[] = $index;
}
}
$conf = $this->getConfig();
// Build list of variables
$vars = array('wgLoadScript' => wfScript('load'), 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $conf->get('StylePath'), 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $conf->get('ArticlePath'), 'wgScriptPath' => $conf->get('ScriptPath'), 'wgScriptExtension' => '.php', 'wgScript' => wfScript(), 'wgSearchType' => $conf->get('SearchType'), 'wgVariantArticlePath' => $conf->get('VariantArticlePath'), 'wgActionPaths' => (object) $conf->get('ActionPaths'), 'wgServer' => $conf->get('Server'), 'wgServerName' => $conf->get('ServerName'), 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgTranslateNumerals' => $conf->get('TranslateNumerals'), 'wgVersion' => $conf->get('Version'), 'wgEnableAPI' => $conf->get('EnableAPI'), 'wgEnableWriteAPI' => $conf->get('EnableWriteAPI'), 'wgMainPageTitle' => $mainPage->getPrefixedText(), 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgContentNamespaces' => MWNamespace::getContentNamespaces(), 'wgSiteName' => $conf->get('Sitename'), 'wgDBname' => $conf->get('DBname'), 'wgExtraSignatureNamespaces' => $conf->get('ExtraSignatureNamespaces'), 'wgAvailableSkins' => Skin::getSkinNames(), 'wgExtensionAssetsPath' => $conf->get('ExtensionAssetsPath'), 'wgCookiePrefix' => $conf->get('CookiePrefix'), 'wgCookieDomain' => $conf->get('CookieDomain'), 'wgCookiePath' => $conf->get('CookiePath'), 'wgCookieExpiration' => $conf->get('CookieExpiration'), 'wgResourceLoaderMaxQueryLength' => $conf->get('ResourceLoaderMaxQueryLength'), 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass(Title::legalChars()), 'wgResourceLoaderStorageVersion' => $conf->get('ResourceLoaderStorageVersion'), 'wgResourceLoaderStorageEnabled' => $conf->get('ResourceLoaderStorageEnabled'), 'wgResourceLoaderLegacyModules' => self::getLegacyModules(), 'wgForeignUploadTargets' => $conf->get('ForeignUploadTargets'), 'wgEnableUploads' => $conf->get('EnableUploads'));
Hooks::run('ResourceLoaderGetConfigVars', array(&$vars));
$this->configVars[$hash] = $vars;
return $this->configVars[$hash];
}
示例14: showReturnToPage
/**
* Show a return link or redirect to it.
* Extensions can change where the link should point or inject content into the page
* (which will change it from redirect to link mode).
*
* @param string $type One of the following:
* - error: display a return to link ignoring $wgRedirectOnLogin
* - success: display a return to link using $wgRedirectOnLogin if needed
* - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
* @param string $returnTo
* @param array|string $returnToQuery
* @param bool $stickHTTPS Keep redirect link on HTTPS
*/
public function showReturnToPage($type, $returnTo = '', $returnToQuery = '', $stickHTTPS = false)
{
global $wgRedirectOnLogin, $wgSecureLogin;
if ($type !== 'error' && $wgRedirectOnLogin !== null) {
$returnTo = $wgRedirectOnLogin;
$returnToQuery = [];
} elseif (is_string($returnToQuery)) {
$returnToQuery = wfCgiToArray($returnToQuery);
}
// Allow modification of redirect behavior
Hooks::run('PostLoginRedirect', [&$returnTo, &$returnToQuery, &$type]);
$returnToTitle = Title::newFromText($returnTo) ?: Title::newMainPage();
if ($wgSecureLogin && !$stickHTTPS) {
$options = ['http'];
$proto = PROTO_HTTP;
} elseif ($wgSecureLogin) {
$options = ['https'];
$proto = PROTO_HTTPS;
} else {
$options = [];
$proto = PROTO_RELATIVE;
}
if ($type === 'successredirect') {
$redirectUrl = $returnToTitle->getFullURL($returnToQuery, false, $proto);
$this->getOutput()->redirect($redirectUrl);
} else {
$this->getOutput()->addReturnTo($returnToTitle, $returnToQuery, null, $options);
}
}
示例15: applyDefaultParameters
/**
* @param array $params
* @param Config $mainConfig
* @return array
*/
public static function applyDefaultParameters(array $params, Config $mainConfig)
{
$logger = LoggerFactory::getInstance('Mime');
$params += ['typeFile' => $mainConfig->get('MimeTypeFile'), 'infoFile' => $mainConfig->get('MimeInfoFile'), 'xmlTypes' => $mainConfig->get('XMLMimeTypes'), 'guessCallback' => function ($mimeAnalyzer, &$head, &$tail, $file, &$mime) use($logger) {
// Also test DjVu
$deja = new DjVuImage($file);
if ($deja->isValid()) {
$logger->info(__METHOD__ . ": detected {$file} as image/vnd.djvu\n");
$mime = 'image/vnd.djvu';
return;
}
// Some strings by reference for performance - assuming well-behaved hooks
Hooks::run('MimeMagicGuessFromContent', [$mimeAnalyzer, &$head, &$tail, $file, &$mime]);
}, 'extCallback' => function ($mimeAnalyzer, $ext, &$mime) {
// Media handling extensions can improve the MIME detected
Hooks::run('MimeMagicImproveFromExtension', [$mimeAnalyzer, $ext, &$mime]);
}, 'initCallback' => function ($mimeAnalyzer) {
// Allow media handling extensions adding MIME-types and MIME-info
Hooks::run('MimeMagicInit', [$mimeAnalyzer]);
}, 'logger' => $logger];
if ($params['infoFile'] === 'includes/mime.info') {
$params['infoFile'] = __DIR__ . "/libs/mime/mime.info";
}
if ($params['typeFile'] === 'includes/mime.types') {
$params['typeFile'] = __DIR__ . "/libs/mime/mime.types";
}
$detectorCmd = $mainConfig->get('MimeDetectorCommand');
if ($detectorCmd) {
$params['detectCallback'] = function ($file) use($detectorCmd) {
return wfShellExec("{$detectorCmd} " . wfEscapeShellArg($file));
};
}
return $params;
}