MediaWiki  1.28.0
Pingback.php
Go to the documentation of this file.
1 <?php
25 
31 class Pingback {
32 
38  const SCHEMA_REV = 15781718;
39 
41  protected $logger;
42 
44  protected $config;
45 
47  protected $key;
48 
50  protected $id;
51 
56  public function __construct( Config $config = null, LoggerInterface $logger = null ) {
57  $this->config = $config ?: RequestContext::getMain()->getConfig();
58  $this->logger = $logger ?: LoggerFactory::getInstance( __CLASS__ );
59  $this->key = 'Pingback-' . $this->config->get( 'Version' );
60  }
61 
66  private function shouldSend() {
67  return $this->config->get( 'Pingback' ) && !$this->checkIfSent();
68  }
69 
74  private function checkIfSent() {
75  $dbr = wfGetDB( DB_REPLICA );
76  $sent = $dbr->selectField(
77  'updatelog', '1', [ 'ul_key' => $this->key ], __METHOD__ );
78  return $sent !== false;
79  }
80 
85  private function markSent() {
86  $dbw = wfGetDB( DB_MASTER );
87  return $dbw->insert(
88  'updatelog', [ 'ul_key' => $this->key ], __METHOD__, 'IGNORE' );
89  }
90 
99  private function acquireLock() {
101  if ( !$cache->add( $this->key, 1, 60 * 60 ) ) {
102  return false; // throttled
103  }
104 
105  $dbw = wfGetDB( DB_MASTER );
106  if ( !$dbw->lock( $this->key, __METHOD__, 0 ) ) {
107  return false; // already in progress
108  }
109 
110  return true;
111  }
112 
125  public function getSystemInfo() {
126  $event = [
127  'database' => $this->config->get( 'DBtype' ),
128  'MediaWiki' => $this->config->get( 'Version' ),
129  'PHP' => PHP_VERSION,
130  'OS' => PHP_OS . ' ' . php_uname( 'r' ),
131  'arch' => PHP_INT_SIZE === 8 ? 64 : 32,
132  'machine' => php_uname( 'm' ),
133  ];
134 
135  if ( isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
136  $event['serverSoftware'] = $_SERVER['SERVER_SOFTWARE'];
137  }
138 
139  $limit = ini_get( 'memory_limit' );
140  if ( $limit && $limit != -1 ) {
141  $event['memoryLimit'] = $limit;
142  }
143 
144  return $event;
145  }
146 
152  private function getData() {
153  return [
154  'schema' => 'MediaWikiPingback',
155  'revision' => self::SCHEMA_REV,
156  'wiki' => $this->getOrCreatePingbackId(),
157  'event' => $this->getSystemInfo(),
158  ];
159  }
160 
169  private function getOrCreatePingbackId() {
170  if ( !$this->id ) {
171  $id = wfGetDB( DB_REPLICA )->selectField(
172  'updatelog', 'ul_value', [ 'ul_key' => 'PingBack' ] );
173 
174  if ( $id == false ) {
176  $dbw = wfGetDB( DB_MASTER );
177  $dbw->insert(
178  'updatelog',
179  [ 'ul_key' => 'PingBack', 'ul_value' => $id ],
180  __METHOD__,
181  'IGNORE'
182  );
183 
184  if ( !$dbw->affectedRows() ) {
185  $id = $dbw->selectField(
186  'updatelog', 'ul_value', [ 'ul_key' => 'PingBack' ] );
187  }
188  }
189 
190  $this->id = $id;
191  }
192 
193  return $this->id;
194  }
195 
211  private function postPingback( array $data ) {
212  $json = FormatJson::encode( $data );
213  $queryString = rawurlencode( str_replace( ' ', '\u0020', $json ) ) . ';';
214  $url = 'https://www.mediawiki.org/beacon/event?' . $queryString;
215  return Http::post( $url ) !== false;
216  }
217 
232  public function sendPingback() {
233  if ( !$this->acquireLock() ) {
234  $this->logger->debug( __METHOD__ . ": couldn't acquire lock" );
235  return false;
236  }
237 
238  $data = $this->getData();
239  if ( !$this->postPingback( $data ) ) {
240  $this->logger->warning( __METHOD__ . ": failed to send pingback; check 'http' log" );
241  return false;
242  }
243 
244  $this->markSent();
245  $this->logger->debug( __METHOD__ . ": pingback sent OK ({$this->key})" );
246  return true;
247  }
248 
253  public static function schedulePingback() {
255  $instance = new Pingback;
256  if ( $instance->shouldSend() ) {
257  $instance->sendPingback();
258  }
259  } );
260  }
261 }
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
getSystemInfo()
Collect basic data about this MediaWiki installation and return it as an associative array conforming...
Definition: Pingback.php:125
the array() calling protocol came about after MediaWiki 1.4rc1.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
acquireLock()
Acquire lock for sending a pingback.
Definition: Pingback.php:99
static getLocalClusterInstance()
Get the main cluster-local cache object.
checkIfSent()
Has a pingback already been sent for this MediaWiki version?
Definition: Pingback.php:74
const DB_MASTER
Definition: defines.php:23
string $id
Randomly-generated identifier for this wiki.
Definition: Pingback.php:50
static getMain()
Static methods.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition: design.txt:25
sendPingback()
Send information about this MediaWiki instance to MediaWiki.org.
Definition: Pingback.php:232
Config $config
Definition: Pingback.php:44
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
$cache
Definition: mcc.php:33
string $key
updatelog key (also used as cache/db lock key)
Definition: Pingback.php:47
static schedulePingback()
Schedule a deferred callable that will check if a pingback should be sent and (if so) proceed to send...
Definition: Pingback.php:253
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
__construct(Config $config=null, LoggerInterface $logger=null)
Definition: Pingback.php:56
getData()
Get the EventLogging packet to be sent to the server.
Definition: Pingback.php:152
static generateHex($chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format...
Definition: MWCryptRand.php:76
postPingback(array $data)
Serialize pingback data and send it to MediaWiki.org via a POST to its event beacon endpoint...
Definition: Pingback.php:211
static post($url, $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'POST' )
Definition: Http.php:117
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1046
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
getOrCreatePingbackId()
Get a unique, stable identifier for this wiki.
Definition: Pingback.php:169
shouldSend()
Should a pingback be sent?
Definition: Pingback.php:66
static addCallableUpdate($callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
const DB_REPLICA
Definition: defines.php:22
markSent()
Record the fact that we have sent a pingback for this MediaWiki version, to ensure we don't submit da...
Definition: Pingback.php:85
LoggerInterface $logger
Definition: Pingback.php:33
Send information about this MediaWiki instance to MediaWiki.org.
Definition: Pingback.php:31