本文整理汇总了PHP中MWExceptionHandler类的典型用法代码示例。如果您正苦于以下问题:PHP MWExceptionHandler类的具体用法?PHP MWExceptionHandler怎么用?PHP MWExceptionHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MWExceptionHandler类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: doUpdate
/**
* Run the update
*/
public function doUpdate()
{
global $wgHitcounterUpdateFreq;
$dbw = wfGetDB(DB_MASTER);
if ($wgHitcounterUpdateFreq <= 1 || $dbw->getType() == 'sqlite') {
$id = $this->id;
$method = __METHOD__;
$dbw->onTransactionIdle(function () use($dbw, $id, $method) {
try {
$dbw->update('page', array('page_counter = page_counter + 1'), array('page_id' => $id), $method);
} catch (DBError $e) {
MWExceptionHandler::logException($e);
}
});
return;
}
# Not important enough to warrant an error page in case of failure
try {
// Since `hitcounter` is non-transactional, the contention is minimal
$dbw->insert('hitcounter', array('hc_id' => $this->id), __METHOD__);
$checkfreq = intval($wgHitcounterUpdateFreq / 25 + 1);
if (rand() % $checkfreq == 0 && $dbw->lastErrno() == 0) {
$this->collect();
}
} catch (DBError $e) {
MWExceptionHandler::logException($e);
}
}
开发者ID:whysasse,项目名称:kmwiki,代码行数:31,代码来源:ViewCountUpdate.php
示例2: getResults
/**
* @param UUID $postId
* @param int $limit
* @param UUID|null $offset
* @param string $direction 'rev' or 'fwd'
* @return FormatterRow[]
*/
public function getResults(UUID $postId, $limit = 50, UUID $offset = null, $direction = 'fwd')
{
$history = $this->storage->find('TopicHistoryEntry', array('topic_root_id' => $postId), array('sort' => 'rev_id', 'order' => 'DESC', 'limit' => $limit, 'offset-id' => $offset, 'offset-dir' => $direction, 'offset-include' => false, 'offset-elastic' => false));
if (!$history) {
return array();
}
$this->loadMetadataBatch($history);
$results = $replies = array();
foreach ($history as $revision) {
try {
if ($this->excludeFromHistory($revision)) {
continue;
}
$results[] = $row = new TopicRow();
$this->buildResult($revision, null, $row);
if ($revision instanceof PostRevision) {
$replyToId = $revision->getReplyToId();
if ($replyToId) {
// $revisionId into the key rather than value prevents
// duplicate insertion
$replies[$replyToId->getAlphadecimal()][$revision->getPostId()->getAlphadecimal()] = true;
}
}
} catch (FlowException $e) {
\MWExceptionHandler::logException($e);
}
}
foreach ($results as $result) {
if ($result->revision instanceof PostRevision) {
$alpha = $result->revision->getPostId()->getAlphadecimal();
$result->replies = isset($replies[$alpha]) ? array_keys($replies[$alpha]) : array();
}
}
return $results;
}
开发者ID:TarLocesilion,项目名称:mediawiki-extensions-Flow,代码行数:42,代码来源:TopicHistoryQuery.php
示例3: getInlineScript
/**
* Get contents of a javascript file for inline use.
*
* Roughly based MediaWiki core methods:
* - ResourceLoader::filter()
* - ResourceLoaderFileModule::readScriptFiles()
*
* @param string $name Path to file relative to /modules/inline/
* @return string Minified script
* @throws Exception If file doesn't exist
*/
protected static function getInlineScript($name)
{
// Get file
$filePath = __DIR__ . '/../../modules/inline/' . $name;
if (!file_exists($filePath)) {
throw new Exception(__METHOD__ . ": file not found: \"{$filePath}\"");
}
$contents = file_get_contents($filePath);
// Try minified from cache
$key = wfMemcKey('centralauth', 'minify-js', md5($contents));
$cache = wfGetCache(CACHE_ANYTHING);
$cacheEntry = $cache->get($key);
if (is_string($cacheEntry)) {
return $cacheEntry;
}
// Compute new value
$result = '';
try {
$result = JavaScriptMinifier::minify($contents) . "\n/* cache key: {$key} */";
$cache->set($key, $result);
} catch (Exception $e) {
MWExceptionHandler::logException($e);
wfDebugLog('CentralAuth', __METHOD__ . ": minification failed for {$name}: {$e}");
$result = ResourceLoader::formatException($e) . "\n" . $contents;
}
return $result;
}
开发者ID:NDKilla,项目名称:mediawiki-extensions-CentralAuth,代码行数:38,代码来源:SpecialCentralAutoLogin.php
示例4: findMulti
/**
* All queries must be against the same index. Results are equivalent to
* array_map, maintaining order and key relationship between input $queries
* and $result.
*
* @param array $queries
* @param array $options
* @return array|null null is query failure. empty array is no result. array is success
*/
public function findMulti(array $queries, array $options = array())
{
if (!$queries) {
return array();
}
$keys = array_keys(reset($queries));
if (isset($options['sort']) && !is_array($options['sort'])) {
$options['sort'] = ObjectManager::makeArray($options['sort']);
}
try {
$index = $this->getIndexFor($keys, $options);
$res = $index->findMulti($queries, $options);
} catch (NoIndexException $e) {
if (array_search('topic_root_id', $keys)) {
wfDebugLog('Flow', __METHOD__ . ': ' . json_encode($keys) . ' : ' . json_encode($options) . ' : ' . json_encode(array_map('get_class', $this->indexes)));
\MWExceptionHandler::logException($e);
} else {
wfDebugLog('FlowDebug', __METHOD__ . ': ' . $e->getMessage());
}
$res = $this->storage->findMulti($queries, $this->convertToDbOptions($options));
}
if ($res === null) {
return null;
}
$output = array();
foreach ($res as $index => $queryOutput) {
foreach ($queryOutput as $k => $v) {
if ($v) {
$output[$index][$k] = $this->load($v);
}
}
}
return $output;
}
开发者ID:TarLocesilion,项目名称:mediawiki-extensions-Flow,代码行数:43,代码来源:ObjectLocator.php
示例5: getResults
/**
* @param UUID[]|TopicListEntry[] $topicIdsOrEntries
* @return FormatterRow[]
*/
public function getResults(array $topicIdsOrEntries)
{
$topicIds = $this->getTopicIds($topicIdsOrEntries);
$allPostIds = $this->collectPostIds($topicIds);
$topicSummary = $this->collectSummary($topicIds);
$posts = $this->collectRevisions($allPostIds);
$watchStatus = $this->collectWatchStatus($topicIds);
$missing = array_diff(array_keys($allPostIds), array_keys($posts));
if ($missing) {
$needed = array();
foreach ($missing as $alpha) {
// convert alpha back into UUID object
$needed[] = $allPostIds[$alpha];
}
$posts += $this->createFakePosts($needed);
}
$this->loadMetadataBatch($posts);
$results = array();
$replies = array();
foreach ($posts as $post) {
try {
if (!$this->permissions->isAllowed($post, 'view')) {
continue;
}
$row = new TopicRow();
$this->buildResult($post, null, $row);
/** @var PostRevision $revision */
$revision = $row->revision;
$replyToId = $revision->getReplyToId();
$replyToId = $replyToId ? $replyToId->getAlphadecimal() : null;
$postId = $revision->getPostId()->getAlphadecimal();
$replies[$replyToId] = $postId;
if ($post->isTopicTitle()) {
// Attach the summary
if (isset($topicSummary[$postId])) {
$row->summary = $this->buildResult($topicSummary[$postId], 'rev_id');
}
// Attach the watch status
if (isset($watchStatus[$postId]) && $watchStatus[$postId]) {
$row->isWatched = true;
}
}
$results[] = $row;
} catch (FlowException $e) {
\MWExceptionHandler::logException($e);
}
}
foreach ($results as $result) {
$alpha = $result->revision->getPostId()->getAlphadecimal();
$result->replies = isset($replies[$alpha]) ? $replies[$alpha] : array();
}
return $results;
}
开发者ID:TarLocesilion,项目名称:mediawiki-extensions-Flow,代码行数:57,代码来源:TopicListQuery.php
示例6: run
public function run()
{
/** @noinspection PhpUnusedLocalVariableInspection */
$scope = RequestContext::importScopedSession($this->params['session']);
$context = RequestContext::getMain();
$user = $context->getUser();
try {
if (!$user->isLoggedIn()) {
$this->setLastError("Could not load the author user from session.");
return false;
}
UploadBase::setSessionStatus($user, $this->params['filekey'], array('result' => 'Poll', 'stage' => 'publish', 'status' => Status::newGood()));
$upload = new UploadFromStash($user);
// @todo initialize() causes a GET, ideally we could frontload the antivirus
// checks and anything else to the stash stage (which includes concatenation and
// the local file is thus already there). That way, instead of GET+PUT, there could
// just be a COPY operation from the stash to the public zone.
$upload->initialize($this->params['filekey'], $this->params['filename']);
// Check if the local file checks out (this is generally a no-op)
$verification = $upload->verifyUpload();
if ($verification['status'] !== UploadBase::OK) {
$status = Status::newFatal('verification-error');
$status->value = array('verification' => $verification);
UploadBase::setSessionStatus($user, $this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => $status));
$this->setLastError("Could not verify upload.");
return false;
}
// Upload the stashed file to a permanent location
$status = $upload->performUpload($this->params['comment'], $this->params['text'], $this->params['watch'], $user);
if (!$status->isGood()) {
UploadBase::setSessionStatus($user, $this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => $status));
$this->setLastError($status->getWikiText());
return false;
}
// Build the image info array while we have the local reference handy
$apiMain = new ApiMain();
// dummy object (XXX)
$imageInfo = $upload->getImageInfo($apiMain->getResult());
// Cleanup any temporary local file
$upload->cleanupTempFile();
// Cache the info so the user doesn't have to wait forever to get the final info
UploadBase::setSessionStatus($user, $this->params['filekey'], array('result' => 'Success', 'stage' => 'publish', 'filename' => $upload->getLocalFile()->getName(), 'imageinfo' => $imageInfo, 'status' => Status::newGood()));
} catch (Exception $e) {
UploadBase::setSessionStatus($user, $this->params['filekey'], array('result' => 'Failure', 'stage' => 'publish', 'status' => Status::newFatal('api-error-publishfailed')));
$this->setLastError(get_class($e) . ": " . $e->getMessage());
// To prevent potential database referential integrity issues.
// See bug 32551.
MWExceptionHandler::rollbackMasterChangesAndLog($e);
return false;
}
return true;
}
开发者ID:mb720,项目名称:mediawiki,代码行数:52,代码来源:PublishStashedFileJob.php
示例7: run
public function run()
{
$scope = RequestContext::importScopedSession($this->params['session']);
$context = RequestContext::getMain();
try {
$user = $context->getUser();
if (!$user->isLoggedIn()) {
$this->setLastError("Could not load the author user from session.");
return false;
}
if (count($_SESSION) === 0) {
// Empty session probably indicates that we didn't associate
// with the session correctly. Note that being able to load
// the user does not necessarily mean the session was loaded.
// Most likely cause by suhosin.session.encrypt = On.
$this->setLastError("Error associating with user session. " . "Try setting suhosin.session.encrypt = Off");
return false;
}
UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Poll', 'stage' => 'assembling', 'status' => Status::newGood()));
$upload = new UploadFromChunks($user);
$upload->continueChunks($this->params['filename'], $this->params['filekey'], $context->getRequest());
// Combine all of the chunks into a local file and upload that to a new stash file
$status = $upload->concatenateChunks();
if (!$status->isGood()) {
UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'assembling', 'status' => $status));
$this->setLastError($status->getWikiText());
return false;
}
// We have a new filekey for the fully concatenated file
$newFileKey = $upload->getLocalFile()->getFileKey();
// Remove the old stash file row and first chunk file
$upload->stash->removeFileNoAuth($this->params['filekey']);
// Build the image info array while we have the local reference handy
$apiMain = new ApiMain();
// dummy object (XXX)
$imageInfo = $upload->getImageInfo($apiMain->getResult());
// Cleanup any temporary local file
$upload->cleanupTempFile();
// Cache the info so the user doesn't have to wait forever to get the final info
UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Success', 'stage' => 'assembling', 'filekey' => $newFileKey, 'imageinfo' => $imageInfo, 'status' => Status::newGood()));
} catch (MWException $e) {
UploadBase::setSessionStatus($this->params['filekey'], array('result' => 'Failure', 'stage' => 'assembling', 'status' => Status::newFatal('api-error-stashfailed')));
$this->setLastError(get_class($e) . ": " . $e->getText());
// To be extra robust.
MWExceptionHandler::rollbackMasterChangesAndLog($e);
return false;
}
return true;
}
开发者ID:Tarendai,项目名称:spring-website,代码行数:49,代码来源:AssembleUploadChunksJob.php
示例8: onSubmit
/**
* Creates a flow board.
* Archives any pre-existing wikitext talk page.
*
* @param array $data Form data
* @return Status Status indicating result
*/
public function onSubmit(array $data)
{
$page = $data['page'];
$title = Title::newFromText($page);
if (!$title) {
return Status::newFatal('flow-special-enableflow-invalid-title', $page);
}
// Canonicalize so the error or confirmation message looks nicer (no underscores).
$page = $title->getPrefixedText();
if ($this->occupationController->isTalkpageOccupied($title, true)) {
return Status::newFatal('flow-special-enableflow-board-already-exists', $page);
}
$status = Status::newGood();
if ($title->exists(Title::GAID_FOR_UPDATE)) {
if (class_exists('LqtDispatch') && \LqtDispatch::isLqtPage($title)) {
return Status::newFatal('flow-special-enableflow-page-is-liquidthreads', $page);
}
$logger = Container::get('default_logger');
$converter = new Converter(wfGetDB(DB_MASTER), Container::get('importer'), $logger, $this->occupationController->getTalkpageManager(), new EnableFlowWikitextConversionStrategy(Container::get('parser'), new NullImportSourceStore(), $logger, array(), $data['header']));
try {
$converter->convert($title);
} catch (\Exception $e) {
\MWExceptionHandler::logException($e);
$status->fatal('flow-error-external', $e->getMessage());
}
} else {
$allowCreationStatus = $this->occupationController->allowCreation($title, $this->getUser(), false);
if (!$allowCreationStatus->isGood()) {
return Status::newFatal('flow-special-enableflow-board-creation-not-allowed', $page);
}
$loader = $this->loaderFactory->createWorkflowLoader($title);
$blocks = $loader->getBlocks();
$action = 'edit-header';
$params = array('header' => array('content' => $data['header'], 'format' => 'wikitext'));
$blocksToCommit = $loader->handleSubmit($this->getContext(), $action, $params);
foreach ($blocks as $block) {
if ($block->hasErrors()) {
$errors = $block->getErrors();
foreach ($errors as $errorKey) {
$status->fatal($block->getErrorMessage($errorKey));
}
}
}
$loader->commit($blocksToCommit);
}
$this->page = $data['page'];
return $status;
}
开发者ID:TarLocesilion,项目名称:mediawiki-extensions-Flow,代码行数:55,代码来源:SpecialEnableFlow.php
示例9: run
public function run()
{
$scope = RequestContext::importScopedSession($this->params['session']);
$this->addTeardownCallback(function () use(&$scope) {
ScopedCallback::consume($scope);
// T126450
});
$context = RequestContext::getMain();
$user = $context->getUser();
try {
if (!$user->isLoggedIn()) {
$this->setLastError("Could not load the author user from session.");
return false;
}
UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Poll', 'stage' => 'assembling', 'status' => Status::newGood()]);
$upload = new UploadFromChunks($user);
$upload->continueChunks($this->params['filename'], $this->params['filekey'], new WebRequestUpload($context->getRequest(), 'null'));
// Combine all of the chunks into a local file and upload that to a new stash file
$status = $upload->concatenateChunks();
if (!$status->isGood()) {
UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'assembling', 'status' => $status]);
$this->setLastError($status->getWikiText(false, false, 'en'));
return false;
}
// We can only get warnings like 'duplicate' after concatenating the chunks
$status = Status::newGood();
$status->value = ['warnings' => $upload->checkWarnings()];
// We have a new filekey for the fully concatenated file
$newFileKey = $upload->getStashFile()->getFileKey();
// Remove the old stash file row and first chunk file
$upload->stash->removeFileNoAuth($this->params['filekey']);
// Build the image info array while we have the local reference handy
$apiMain = new ApiMain();
// dummy object (XXX)
$imageInfo = $upload->getImageInfo($apiMain->getResult());
// Cleanup any temporary local file
$upload->cleanupTempFile();
// Cache the info so the user doesn't have to wait forever to get the final info
UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Success', 'stage' => 'assembling', 'filekey' => $newFileKey, 'imageinfo' => $imageInfo, 'status' => $status]);
} catch (Exception $e) {
UploadBase::setSessionStatus($user, $this->params['filekey'], ['result' => 'Failure', 'stage' => 'assembling', 'status' => Status::newFatal('api-error-stashfailed')]);
$this->setLastError(get_class($e) . ": " . $e->getMessage());
// To be extra robust.
MWExceptionHandler::rollbackMasterChangesAndLog($e);
return false;
}
return true;
}
开发者ID:paladox,项目名称:mediawiki,代码行数:48,代码来源:AssembleUploadChunksJob.php
示例10: getResults
/**
* @param UUID $postId
* @param int $limit
* @param UUID|null $offset
* @param string $direction 'rev' or 'fwd'
* @return FormatterRow[]
*/
public function getResults(UUID $postId, $limit = 50, UUID $offset = null, $direction = 'fwd')
{
$history = $this->storage->find('PostRevision', array('rev_type_id' => $postId), array('sort' => 'rev_id', 'order' => 'DESC', 'limit' => $limit, 'offset-id' => $offset, 'offset-dir' => $direction, 'offset-include' => false, 'offset-elastic' => false));
if (!$history) {
return array();
}
$this->loadMetadataBatch($history);
$results = array();
foreach ($history as $revision) {
try {
$results[] = $row = new FormatterRow();
$this->buildResult($revision, null, $row);
} catch (FlowException $e) {
\MWExceptionHandler::logException($e);
}
}
return $results;
}
开发者ID:TarLocesilion,项目名称:mediawiki-extensions-Flow,代码行数:25,代码来源:PostHistoryQuery.php
示例11: testGetRedactedTrace
/**
* @covers MWExceptionHandler::getRedactedTrace
*/
public function testGetRedactedTrace()
{
$refvar = 'value';
try {
$array = array('a', 'b');
$object = new stdClass();
self::helperThrowAnException($array, $object, $refvar);
} catch (Exception $e) {
}
# Make sure our stack trace contains an array and an object passed to
# some function in the stacktrace. Else, we can not assert the trace
# redaction achieved its job.
$trace = $e->getTrace();
$hasObject = false;
$hasArray = false;
foreach ($trace as $frame) {
if (!isset($frame['args'])) {
continue;
}
foreach ($frame['args'] as $arg) {
$hasObject = $hasObject || is_object($arg);
$hasArray = $hasArray || is_array($arg);
}
if ($hasObject && $hasArray) {
break;
}
}
$this->assertTrue($hasObject, "The stacktrace must have a function having an object has parameter");
$this->assertTrue($hasArray, "The stacktrace must have a function having an array has parameter");
# Now we redact the trace.. and make sure no function arguments are
# arrays or objects.
$redacted = MWExceptionHandler::getRedactedTrace($e);
foreach ($redacted as $frame) {
if (!isset($frame['args'])) {
continue;
}
foreach ($frame['args'] as $arg) {
$this->assertNotInternalType('array', $arg);
$this->assertNotInternalType('object', $arg);
}
}
$this->assertEquals('value', $refvar, 'Ensuring reference variable wasn\'t changed');
}
开发者ID:jpena88,项目名称:mediawiki-dokku-deploy,代码行数:46,代码来源:MWExceptionHandlerTest.php
示例12: makeModuleResponse
/**
* Generate code for a response.
*
* @param ResourceLoaderContext $context Context in which to generate a response
* @param array $modules List of module objects keyed by module name
* @param array $missing List of requested module names that are unregistered (optional)
* @return string Response data
*/
public function makeModuleResponse(ResourceLoaderContext $context, array $modules, array $missing = array())
{
$out = '';
$states = array();
if (!count($modules) && !count($missing)) {
return <<<MESSAGE
/* This file is the Web entry point for MediaWiki's ResourceLoader:
<https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
no modules were requested. Max made me put this here. */
MESSAGE;
}
$image = $context->getImageObj();
if ($image) {
$data = $image->getImageData($context);
if ($data === false) {
$data = '';
$this->errors[] = 'Image generation failed';
}
return $data;
}
// Pre-fetch blobs
if ($context->shouldIncludeMessages()) {
try {
$this->blobStore->get($this, $modules, $context->getLanguage());
} catch (Exception $e) {
MWExceptionHandler::logException($e);
$this->logger->warning('Prefetching MessageBlobStore failed: {exception}', array('exception' => $e));
$this->errors[] = self::formatExceptionNoComment($e);
}
}
foreach ($missing as $name) {
$states[$name] = 'missing';
}
// Generate output
$isRaw = false;
foreach ($modules as $name => $module) {
try {
$content = $module->getModuleContent($context);
// Append output
switch ($context->getOnly()) {
case 'scripts':
$scripts = $content['scripts'];
if (is_string($scripts)) {
// Load scripts raw...
$out .= $scripts;
} elseif (is_array($scripts)) {
// ...except when $scripts is an array of URLs
$out .= self::makeLoaderImplementScript($name, $scripts, array(), array());
}
break;
case 'styles':
$styles = $content['styles'];
// We no longer seperate into media, they are all combined now with
// custom media type groups into @media .. {} sections as part of the css string.
// Module returns either an empty array or a numerical array with css strings.
$out .= isset($styles['css']) ? implode('', $styles['css']) : '';
break;
default:
$out .= self::makeLoaderImplementScript($name, isset($content['scripts']) ? $content['scripts'] : '', isset($content['styles']) ? $content['styles'] : array(), isset($content['messagesBlob']) ? new XmlJsCode($content['messagesBlob']) : array(), isset($content['templates']) ? $content['templates'] : array());
break;
}
} catch (Exception $e) {
MWExceptionHandler::logException($e);
$this->logger->warning('Generating module package failed: {exception}', array('exception' => $e));
$this->errors[] = self::formatExceptionNoComment($e);
// Respond to client with error-state instead of module implementation
$states[$name] = 'error';
unset($modules[$name]);
}
$isRaw |= $module->isRaw();
}
// Update module states
if ($context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw) {
if (count($modules) && $context->getOnly() === 'scripts') {
// Set the state of modules loaded as only scripts to ready as
// they don't have an mw.loader.implement wrapper that sets the state
foreach ($modules as $name => $module) {
$states[$name] = 'ready';
}
}
// Set the state of modules we didn't respond to with mw.loader.implement
if (count($states)) {
$out .= self::makeLoaderStateScript($states);
}
} else {
if (count($states)) {
$this->errors[] = 'Problematic modules: ' . FormatJson::encode($states, ResourceLoader::inDebugMode());
}
}
$enableFilterCache = true;
if (count($modules) === 1 && reset($modules) instanceof ResourceLoaderUserTokensModule) {
// If we're building the embedded user.tokens, don't cache (T84960)
//.........这里部分代码省略.........
开发者ID:ErdemA,项目名称:mediawiki,代码行数:101,代码来源:ResourceLoader.php
示例13: doViewUpdates
/**
* Do standard deferred updates after page view (existing or missing page)
* @param User $user The relevant user
* @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
*/
public function doViewUpdates(User $user, $oldid = 0)
{
if (wfReadOnly()) {
return;
}
Hooks::run('PageViewUpdates', [$this, $user]);
// Update newtalk / watchlist notification status
try {
$user->clearNotification($this->mTitle, $oldid);
} catch (DBError $e) {
// Avoid outage if the master is not reachable
MWExceptionHandler::logException($e);
}
}
开发者ID:paladox,项目名称:mediawiki,代码行数:19,代码来源:WikiPage.php
示例14: handleFatalError
/**
* Dual purpose callback used as both a set_error_handler() callback and
* a registered shutdown function. Receive a callback from the interpreter
* for a raised error or system shutdown, check for a fatal error, and log
* to the 'fatal' logging channel.
*
* Special handling is included for missing class errors as they may
* indicate that the user needs to install 3rd-party libraries via
* Composer or other means.
*
* @since 1.25
*
* @param int $level Error level raised
* @param string $message Error message
* @param string $file File that error was raised in
* @param int $line Line number error was raised at
* @param array $context Active symbol table point of error
* @param array $trace Backtrace at point of error (undocumented HHVM
* feature)
* @return bool Always returns false
*/
public static function handleFatalError($level = null, $message = null, $file = null, $line = null, $context = null, $trace = null)
{
// Free reserved memory so that we have space to process OOM
// errors
self::$reservedMemory = null;
if ($level === null) {
// Called as a shutdown handler, get data from error_get_last()
if (static::$handledFatalCallback) {
// Already called once (probably as an error handler callback
// under HHVM) so don't log again.
return false;
}
$lastError = error_get_last();
if ($lastError !== null) {
$level = $lastError['type'];
$message = $lastError['message'];
$file = $lastError['file'];
$line = $lastError['line'];
} else {
$level = 0;
$message = '';
}
}
if (!in_array($level, self::$fatalErrorTypes)) {
// Only interested in fatal errors, others should have been
// handled by MWExceptionHandler::handleError
return false;
}
$msg = "[{exception_id}] PHP Fatal Error: {$message}";
// Look at message to see if this is a class not found failure
// HHVM: Class undefined: foo
// PHP5: Class 'foo' not found
if (preg_match("/Class (undefined: \\w+|'\\w+' not found)/", $msg)) {
// @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
$msg = <<<TXT
{$msg}
MediaWiki or an installed extension requires this class but it is not embedded directly in MediaWiki's git repository and must be installed separately by the end user.
Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
TXT;
// @codingStandardsIgnoreEnd
}
// We can't just create an exception and log it as it is likely that
// the interpreter has unwound the stack already. If that is true the
// stacktrace we would get would be functionally empty. If however we
// have been called as an error handler callback *and* HHVM is in use
// we will have been provided with a useful stacktrace that we can
// log.
$trace = $trace ?: debug_backtrace();
$logger = LoggerFactory::getInstance('fatal');
$logger->error($msg, ['exception' => ['class' => 'ErrorException', 'message' => "PHP Fatal Error: {$message}", 'code' => $level, 'file' => $file, 'line' => $line, 'trace' => static::redactTrace($trace)], 'exception_id' => wfRandomString(8)]);
// Remember call so we don't double process via HHVM's fatal
// notifications and the shutdown hook behavior
static::$handledFatalCallback = true;
return false;
}
开发者ID:claudinec,项目名称:galan-wiki,代码行数:78,代码来源:MWExceptionHandler.php
示例15: foreach
$headers = [];
foreach (headers_list() as $header) {
list($name, $value) = explode(':', $header, 2);
$headers[strtolower(trim($name))][] = trim($value);
}
if (isset($headers['set-cookie'])) {
$cacheControl = isset($headers['cache-control']) ? implode(', ', $headers['cache-control']) : '';
if (!preg_match('/(?:^|,)\\s*(?:private|no-cache|no-store)\\s*(?:$|,)/i', $cacheControl)) {
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
header('Cache-Control: private, max-age=0, s-maxage=0');
MediaWiki\Logger\LoggerFactory::getInstance('cache-cookies')->warning('Cookies set on {url} with Cache-Control "{cache-control}"', ['url' => WebRequest::getGlobalRequestURL(), 'cookies' => $headers['set-cookie'], 'cache-control' => $cacheControl ?: '<not set>']);
}
}
});
}
MWExceptionHandler::installHandler();
require_once "{$IP}/includes/compat/normal/UtfNormalUtil.php";
$ps_validation = Profiler::instance()->scopedProfileIn($fname . '-validation');
// T48998: Bail out early if $wgArticlePath is non-absolute
foreach (['wgArticlePath', 'wgVariantArticlePath'] as $varName) {
if (${$varName} && !preg_match('/^(https?:\\/\\/|\\/)/', ${$varName})) {
throw new FatalError("If you use a relative URL for \${$varName}, it must start " . 'with a slash (<code>/</code>).<br><br>See ' . "<a href=\"https://www.mediawiki.org/wiki/Manual:\${$varName}\">" . "https://www.mediawiki.org/wiki/Manual:\${$varName}</a>.");
}
}
Profiler::instance()->scopedProfileOut($ps_validation);
$ps_default2 = Profiler::instance()->scopedProfileIn($fname . '-defaults2');
if ($wgCanonicalServer === false) {
$wgCanonicalServer = wfExpandUrl($wgServer, PROTO_HTTP);
}
// Set server name
$serverParts = wfParseUrl($wgCanonicalServer);
开发者ID:paladox,项目名称:mediawiki,代码行数:31,代码来源:Setup.php
示例16: rollbackMasterChanges
/**
* Issue ROLLBACK only on master, only if queries were done on connection
* @since 1.23
*/
public function rollbackMasterChanges()
{
$failedServers = array();
$masterIndex = $this->getWriterIndex();
foreach ($this->mConns as $conns2) {
if (empty($conns2[$masterIndex])) {
continue;
}
/** @var DatabaseBase $conn */
foreach ($conns2[$masterIndex] as $conn) {
if ($conn->trxLevel() && $conn->writesOrCallbacksPending()) {
try {
$conn->rollback(__METHOD__, 'flush');
} catch (DBError $e) {
MWExceptionHandler::logException($e);
$failedServers[] = $conn->getServer();
}
}
}
}
if ($failedServers) {
throw new DBExpectedError(null, "Rollback failed on server(s) " . implode(', ', array_unique($failedServers)));
}
}
开发者ID:MediaWiki-stable,项目名称:1.26.1,代码行数:28,代码来源:LoadBalancer.php
示例17: executeReadyPeriodicTasks
/**
* Execute any due periodic queue maintenance tasks for all queues.
*
* A task is "due" if the time ellapsed since the last run is greater than
* the defined run period. Concurrent calls to this function will cause tasks
* to be attempted twice, so they may need their own methods of mutual exclusion.
*
* @return int Number of tasks run
*/
public function executeReadyPeriodicTasks()
{
global $wgMemc;
list($db, $prefix) = wfSplitWikiID($this->wiki);
$key = wfForeignMemcKey($db, $prefix, 'jobqueuegroup', 'taskruns', 'v1');
$lastRuns = $wgMemc->get($key);
// (queue => task => UNIX timestamp)
$count = 0;
$tasksRun = array();
// (queue => task => UNIX timestamp)
foreach ($this->getQueueTypes() as $type) {
$queue = $this->get($type);
foreach ($queue->getPeriodicTasks() as $task => $definition) {
if ($definition['period'] <= 0) {
continue;
// disabled
} elseif (!isset($lastRuns[$type][$task]) || $lastRuns[$type][$task] < time() - $definition['period']) {
try {
if (call_user_func($definition['callback']) !== null) {
$tasksRun[$type][$task] = time();
++$count;
}
} catch (JobQueueError $e) {
MWExceptionHandler::logException($e);
}
}
}
}
if ($count === 0) {
return $count;
// nothing to update
}
$wgMemc->merge($key, function ($cache, $key, $lastRuns) use($tasksRun) {
if (is_array($lastRuns)) {
foreach ($tasksRun as $type => $tasks) {
foreach ($tasks as $task => $timestamp) {
if (!isset($lastRuns[$type][$task]) || $timestamp > $lastRuns[$type][$task]) {
$lastRuns[$type][$task] = $timestamp;
}
}
}
} else {
$lastRuns = $tasksRun;
}
return $lastRuns;
});
return $count;
}
开发者ID:eliagbayani,项目名称:LiteratureEditor,代码行数:57,代码来源:JobQueueGroup.php
示例18: saveSettings
/**
* Save this user's settings into the database.
* @todo Only rarely do all these fields need to be set!
*/
public function saveSettings()
{
global $wgAuth;
if (wfReadOnly()) {
// @TODO: caller should deal with this instead!
// This should really just be an exception.
MWExceptionHandler::logException(new DBExpectedError(null, "Could not update user with ID '{$this->mId}'; DB is read-only."));
return;
}
$this->load();
$this->loadPasswords();
if (0 == $this->mId) {
return;
// anon
}
// Get a new user_touched that is higher than the old one.
// This will be used for a CAS check as a last-resort safety
// check against race conditions and slave lag.
$oldTouched = $this->mTouched;
$newTouched = $this->newTouchedTimestamp();
if (!$wgAuth->allowSetLocalPassword()) {
$this->mPassword = self::getPasswordFactory()->newFromCiphertext(null);
}
$dbw = wfGetDB(DB_MASTER);
$dbw->update('user', array('user_name' => $this->mName, 'user_password' => $this->mPassword->toString(), 'user_newpassword' => $this->mNewpassword->toString(), 'user_newpass_time' => $dbw->timestampOrNull($this->mNewpassTime), 'user_real_name' => $this->mRealName, 'user_email' => $this->mEmail, 'user_email_authenticated' => $dbw->timestampOrNull($this->mEmailAuthenticated), 'user_touched' => $dbw->timestamp($newTouched), 'user_token' => strval($this->mToken), 'user_email_token' => $
|
请发表评论