/** * @since 0.3 * * @param Page $page * @param string[] $protections where the 'key' is the action and the 'value' is the group * @param ProtectOptions $options * * @return bool * @throws InvalidArgumentException */ public function protect(Page $page, $protections, ProtectOptions $options = null) { if (!is_array($protections) || empty($protections)) { throw new InvalidArgumentException('$protections must be an array with keys and values'); } $params = array('pageid' => $page->getId(), 'token' => $this->api->getToken('protect')); $protectionsString = ''; foreach ($protections as $action => $value) { if (!is_string($action) || !is_string($value)) { throw new InvalidArgumentException('All keys and elements of $protections must be strings'); } $protectionsString = $action . '=' . $value . '|'; } $params['protections'] = rtrim($protectionsString, '|'); if ($options->getExpiry() !== 'infinite') { $params['expiry'] = $options->getExpiry(); } if ($options->getReason() !== '') { $params['reason'] = $options->getReason(); } if ($options->getCascade()) { $params['cascade'] = ''; } if ($options->getWatchlist() !== 'preferences') { $params['watchlist'] = $options->getWatchlist(); } $this->api->postRequest(new SimpleRequest('protect', $params)); return true; }
/** * @param ListLogEventsOptions $options * * @return LogList */ public function getLogList(ListLogEventsOptions $options = null) { if ($options == null) { $options = new ListLogEventsOptions(); } $logList = new LogList(); $continue = ''; $limit = $options->getLimit(); while (true) { $params = $this->getParamsFromOptions($options); if (!empty($continue)) { $params['lecontinue'] = $continue; } if ($limit === null) { $params['lelimit'] = 5000; } else { $params['lelimit'] = $limit; } $result = $this->api->getRequest(new SimpleRequest('query', $params)); $limit = $limit - count($result['query']['logevents']); foreach ($result['query']['logevents'] as $logevent) { $logList->addLog(new Log($logevent['logid'], $logevent['type'], $logevent['action'], $logevent['timestamp'], $logevent['user'], new Page(new PageIdentifier(new Title($logevent['title'], $logevent['ns']), $logevent['pageid']), new Revisions()), $logevent['comment'], $this->getLogDetailsFromEvent($logevent))); } if ($limit !== null && $limit <= 0) { return $logList; } if (empty($result['query-continue']['logevents']['lecontinue'])) { return $logList; } else { $continue = $result['query-continue']['logevents']['lecontinue']; } } }
/** * @param string $guid * * @return Statement */ public function getFromGuid($guid) { $params = array('claim' => $guid); $result = $this->api->getRequest(new SimpleRequest('wbgetclaims', $params)); $statementSerialization = array_shift(array_shift($result['claims'])); return $this->statementDeserializer->deserialize($statementSerialization); }
protected function execute(InputInterface $input, OutputInterface $output) { $wiki = $input->getOption('wiki'); $user = $input->getOption('user'); $userDetails = $this->appConfig->offsetGet('users.' . $user); $wikiDetails = $this->appConfig->offsetGet('wikis.' . $wiki); if ($userDetails === null) { throw new RuntimeException('User not found in config'); } if ($wikiDetails === null) { throw new RuntimeException('Wiki not found in config'); } $pageIdentifier = null; if ($input->getOption('pageid') != null) { $pageIdentifier = new PageIdentifier(null, (int) $input->getOption('pageid')); } elseif ($input->getOption('title') != null) { $pageIdentifier = new PageIdentifier(new Title($input->getOption('title'))); } else { throw new \RuntimeException('No titles or pageids were set!'); } $wiki = $input->getOption('wiki'); $wikiDetails = $this->appConfig->offsetGet('wikis.' . $wiki); $api = new MediawikiApi($wikiDetails['url']); $loggedIn = $api->login(new ApiUser($userDetails['username'], $userDetails['password'])); if (!$loggedIn) { $output->writeln('Failed to log in'); return -1; } $mwFactory = new MediawikiFactory($api); $saver = $mwFactory->newRevisionSaver(); $saver->save(new Revision(new Content($input->getArgument('text')), $pageIdentifier)); $output->writeln('Done'); return 0; }
/** * @param Revision $revision * @param EditInfo $editInfo * * @throws RuntimeException * @returns array */ private function getEditParams(Revision $revision, EditInfo $editInfo = null) { if (!$revision->getPageIdentifier()->identifiesPage()) { throw new RuntimeException('$revision PageIdentifier does not identify a page'); } $params = []; $content = $revision->getContent(); $data = $content->getData(); if (!is_string($data)) { throw new RuntimeException('Dont know how to save content of this model.'); } $params['text'] = $content->getData(); $params['md5'] = md5($content->getData()); $timestamp = $revision->getTimestamp(); if (!is_null($timestamp)) { $params['basetimestamp'] = $timestamp; } if (!is_null($revision->getPageIdentifier()->getId())) { $params['pageid'] = $revision->getPageIdentifier()->getId(); } else { $params['title'] = $revision->getPageIdentifier()->getTitle()->getTitle(); } $params['token'] = $this->api->getToken(); if ($this->api->isLoggedin()) { $params['assert'] = 'user'; } $this->addEditInfoParams($editInfo, $params); return $params; }
/** * @see EntityDocumentLookup::getEntityDocumentsForIds */ public function getEntityDocumentsForIds(array $entityIds) { if (empty($entityIds)) { return array(); } return $this->parseResponse($this->api->getRequest($this->buildRequest($entityIds))); }
/** * @param int $pageid * @param Title $target * @param array $extraParams * * @return array */ private function getMoveParams($pageid, $target, $extraParams) { $params = []; $params['fromid'] = $pageid; $params['to'] = $target->getTitle(); $params['token'] = $this->api->getToken('move'); return array_merge($extraParams, $params); }
/** * @param string $action * @param array $params * @param EditInfo|null $editInfo * * @return mixed */ public function postRequest($action, array $params, EditInfo $editInfo = null) { if ($editInfo !== null) { $params = array_merge($this->getEditInfoParams($editInfo), $params); } $params['token'] = $this->api->getToken(); return $this->api->postRequest(new SimpleRequest($action, $params)); }
/** * @param Title $title * * @throws OutOfBoundsException * @returns string */ private function getUndeleteToken(Title $title) { $response = $this->api->postRequest(new SimpleRequest('query', ['list' => 'deletedrevs', 'titles' => $title->getTitle(), 'drprop' => 'token'])); if (array_key_exists('token', $response['query']['deletedrevs'][0])) { return $response['query']['deletedrevs'][0]['token']; } else { throw new OutOfBoundsException('Could not get page undelete token from list=deletedrevs query'); } }
/** * @since 0.5 * @return ItemId[] */ public function get() { $result = $this->api->getRequest(new SimpleRequest('wbavailablebadges')); $ids = array(); foreach ($result['badges'] as $badgeIdString) { $ids[] = new ItemId($badgeIdString); } return $ids; }
/** * @since 0.2 * * @param DataValue $value * @param string $dataTypeId * @param GenericOptions $options * * @returns string */ public function format(DataValue $value, $dataTypeId, GenericOptions $options = null) { if ($options === null) { $options = new GenericOptions(); } $params = array('datavalue' => json_encode($this->dataValueSerializer->serialize($value)), 'datatype' => $dataTypeId, 'options' => json_encode($options->getOptions())); $result = $this->api->getRequest(new SimpleRequest('wbformatvalue', $params)); return $result['result']; }
/** * @param Revision $revision * * @return array */ private function getParamsFromRevision(Revision $revision) { $params = array('undo' => $revision->getId(), 'token' => $this->api->getToken()); if (!is_null($revision->getPageIdentifier()->getId())) { $params['pageid'] = $revision->getPageIdentifier()->getId(); } else { $params['title'] = $revision->getPageIdentifier()->getTitle()->getTitle(); } return $params; }
/** * Query the remote site for the list of namespaces in use, so that later we can tell what's a * category and what's not. This populates $this->namespaces, and will not re-request on * repeated invocations. * @return void */ protected function retrieveNamespaces() { if (is_array($this->namespaces)) { return; } $params = ['meta' => 'siteinfo', 'siprop' => 'namespaces']; $namespaces = $this->api->getRequest(new SimpleRequest('query', $params)); if (isset($namespaces['query']['namespaces'])) { $this->namespaces = $namespaces['query']['namespaces']; } }
/** * @param int $pageid * @param Title $target * @param MoveOptions|null $options * * @return array */ private function getMoveParams($pageid, $target, $options) { $params = array(); $params['fromid'] = $pageid; $params['to'] = $target->getTitle(); $reason = $options->getReason(); if (!empty($reason)) { $params['reason'] = $reason; } $params['token'] = $this->api->getToken('move'); return $params; }
/** * @since 0.3 * * @param User|string $user * @param array $extraParams * * @throws InvalidArgumentException * @return bool */ public function block($user, array $extraParams = []) { if (!$user instanceof User && !is_string($user)) { throw new InvalidArgumentException('$user must be either a string or User object'); } if ($user instanceof User) { $user = $user->getName(); } $params = ['user' => $user, 'token' => $this->api->getToken('block')]; $params = array_merge($extraParams, $params); $this->api->postRequest(new SimpleRequest('block', $params)); return true; }
/** * @since 0.1 * * @return SiteList */ public function getSiteList() { $sitematrixResult = $this->api->getRequest(new SimpleRequest('sitematrix')); unset($sitematrixResult['sitematrix']['count']); $siteListArray = array(); foreach ($sitematrixResult['sitematrix'] as $key => $siteGroup) { foreach ($siteGroup['site'] as $details) { $siteListArray[] = new Site($details['url'], $details['dbname'], $details['code'], $details['sitename']); } } $siteList = new SiteList($siteListArray); return $siteList; }
/** * @param array $extraParams * * @return LogList */ public function getLogList(array $extraParams = []) { $logList = new LogList(); while (true) { $params = ['list' => 'logevents', 'leprop' => 'title|ids|type|user|timestamp|comment|details']; $newParams = array_merge($extraParams, $params); $result = $this->api->getRequest(new SimpleRequest('query', $newParams)); foreach ($result['query']['logevents'] as $logevent) { $logList->addLog(new Log($logevent['logid'], $logevent['type'], $logevent['action'], $logevent['timestamp'], $logevent['user'], new Page(new PageIdentifier(new Title($logevent['title'], $logevent['ns']), $logevent['pageid']), new Revisions()), $logevent['comment'], $this->getLogDetailsFromEvent($logevent))); } return $logList; } }
/** * @param Page $page * * @returns bool */ public function watch(Page $page) { $params = ['token' => $this->api->getToken('watch')]; if (!is_null($page->getPageIdentifier()->getId())) { $params['pageids'] = $page->getPageIdentifier()->getId(); } elseif (!is_null($page->getPageIdentifier()->getTitle())) { $params['titles'] = $page->getPageIdentifier()->getTitle()->getTitle(); } elseif (!is_null($page->getRevisions()->getLatest())) { $params['revids'] = $page->getRevisions()->getLatest()->getId(); } $this->api->postRequest(new SimpleRequest('watch', $params)); return true; }
/** * @since 0.3 * * @param User $user * @param string[] $add * @param string[] $remove * @param array $extraParams * * @return bool */ public function change(User $user, $add = [], $remove = [], array $extraParams = []) { $result = $this->api->postRequest(new SimpleRequest('query', ['list' => 'users', 'ustoken' => 'userrights', 'ususers' => $user->getName()])); $params = ['user' => $user->getName(), 'token' => $result['query']['users'][0]['userrightstoken']]; if (!empty($add)) { $params['add'] = implode('|', $add); } if (!empty($remove)) { $params['remove'] = implode('|', $remove); } $this->api->postRequest(new SimpleRequest('userrights', array_merge($extraParams, $params))); return true; }
/** * @param string $targetName * @param string $location Can be local path or remote url * * @return bool */ public function upload($targetName, $location) { $params = array('filename' => $targetName, 'token' => $this->api->getToken('edit')); $headers = array(); if (is_file($location)) { $params['file'] = fopen($location, 'r'); $headers['Content-Type'] = 'multipart/form-data'; } else { $params['url'] = $location; } $this->api->postRequest(new SimpleRequest('upload', $params, $headers)); return true; }
protected function execute(InputInterface $input, OutputInterface $output) { $wiki = $input->getOption('wiki'); $user = $input->getOption('user'); $revids = $input->getArgument('revid'); $userDetails = $this->appConfig->offsetGet('users.' . $user); $wikiDetails = $this->appConfig->offsetGet('wikis.' . $wiki); if ($userDetails === null) { throw new RuntimeException('User not found in config'); } if ($wikiDetails === null) { throw new RuntimeException('Wiki not found in config'); } $api = new MediawikiApi($wikiDetails['url']); $loggedIn = $api->login(new ApiUser($userDetails['username'], $userDetails['password'])); if (!$loggedIn) { $output->writeln('Failed to log in'); return -1; } $mwFactory = new MediawikiFactory($api); $getter = $mwFactory->newPageGetter(); $saver = $mwFactory->newRevisionSaver(); foreach ($revids as $revid) { $revid = intval($revid); $page = $getter->getFromRevisionId($revid); $page = $getter->getFromPage($page); $goodText = $page->getRevisions()->get($revid)->getContent()->getData(); $currentRevision = $page->getRevisions()->getLatest(); $currentText = $currentRevision->getContent()->getData(); if ($goodText === $currentText) { $output->writeln('Page already has same content as revision: ' . $revid); return null; } if ($input->getOption('asheader')) { if (strstr($currentText, $goodText)) { $goodText = $goodText . "\n\n" . trim(str_replace($goodText, '', $currentText)); } else { $goodText = $goodText . "\n\n" . $currentText; } } $newRevision = new Revision(new Content($goodText), $page->getPageIdentifier()); $success = $saver->save($newRevision, new EditInfo($this->getEditSummary($input->getOption('summary'), $revid), boolval($input->getOption('minor')), boolval($input->getOption('bot')))); if ($success) { $output->writeln('Restored revision: ' . $revid); } else { $output->writeln('Failed to restore revision: ' . $revid); } } return null; }
private function reallyGetToken($type) { // We suppress errors on this call so the user doesn't get get a warning that isn't their fault. $result = @$this->api->postRequest(new SimpleRequest('query', array('meta' => 'tokens', 'type' => $this->getNewTokenType($type), 'continue' => ''))); // If mw<1.25 (no new module) if (array_key_exists('warnings', $result) && array_key_exists('query', $result['warnings']) && strstr($result['warnings']['query']['*'], "Unrecognized value for parameter 'meta': tokens")) { $this->usePre125TokensModule = true; $this->logger->log(LogLevel::DEBUG, 'Falling back to pre 1.25 token system'); $this->tokens[$type] = $this->reallyGetPre125Token($type); } else { $this->tokens[$type] = array_pop($result['query']['tokens']); } return $this->tokens[$type]; }
/** * @param PageIdentifier $pageIdentifier * * @return PromiseInterface of array the parse result (raw from the api) */ public function parsePageAsync(PageIdentifier $pageIdentifier) { $params = []; if ($pageIdentifier->getId() !== null) { $params['pageid'] = $pageIdentifier->getId(); } elseif ($pageIdentifier->getTitle() !== null) { $params['page'] = $pageIdentifier->getTitle()->getText(); } else { throw new \RuntimeException('No way to identify page'); } $promise = $this->api->getRequestAsync(new SimpleRequest('parse', $params)); return $promise->then(function ($result) { return $result['parse']; }); }
/** * @since 0.2 * * @param Revision $revision * @param array $extraParams * * @return Page */ public function getFromRevision(Revision $revision, array $extraParams = []) { $result = $this->api->getRequest(new SimpleRequest('query', $this->getQuery(['revids' => $revision->getId()], $extraParams))); $revisions = $this->getRevisionsFromResult(array_shift($result['query']['pages'])); $revisions->addRevision($revision); return new Page(new PageIdentifier(new Title($result['title'], $result['ns']), $result['pageid']), $revisions); }
/** * @see EntityRedirectLookup::getRedirectForEntityId */ public function getRedirectForEntityId(EntityId $entityId, $forUpdate = '') { $entityIdSerialization = $entityId->getSerialization(); $params = array('ids' => $entityIdSerialization); $result = $this->api->getRequest(new SimpleRequest('wbgetentities', $params)); $entitiesData = $result['entities']; if (!array_key_exists($entityIdSerialization, $entitiesData)) { throw new EntityRedirectLookupException($entityId, "Failed to get {$entityIdSerialization}"); } $entityData = $entitiesData[$entityIdSerialization]; if (!array_key_exists('redirects', $entityData)) { throw new EntityRedirectLookupException($entityId, "{$entityIdSerialization} is not a redirect"); } $entityIdParser = new BasicEntityIdParser(); return $entityIdParser->parse($entityData['redirects']['to']); }
/** * @since 0.3 * * @param User $user * @param string[] $add * @param string[] $remove * @param UserRightsOptions|null $options * * @return bool */ public function change(User $user, $add = array(), $remove = array(), UserRightsOptions $options = null) { $result = $this->api->postRequest(new SimpleRequest('query', array('list' => 'users', 'ustoken' => 'userrights', 'ususers' => $user->getName()))); $params = array('user' => $user->getName(), 'token' => $result['query']['users'][0]['userrightstoken']); $reason = $options->getReason(); if (!empty($reason)) { $params['reason'] = $reason; } if (!empty($add)) { $params['add'] = implode('|', $add); } if (!empty($remove)) { $params['remove'] = implode('|', $remove); } $this->api->postRequest(new SimpleRequest('userrights', $params)); return true; }
/** * @since 0.3 * * @param Page $page * @param string[] $protections where the 'key' is the action and the 'value' is the group * @param array $extraParams * * @return bool * @throws InvalidArgumentException */ public function protect(Page $page, $protections, array $extraParams = []) { if (!is_array($protections) || empty($protections)) { throw new InvalidArgumentException('$protections must be an array with keys and values'); } $params = ['pageid' => $page->getId(), 'token' => $this->api->getToken('protect')]; $protectionsString = ''; foreach ($protections as $action => $value) { if (!is_string($action) || !is_string($value)) { throw new InvalidArgumentException('All keys and elements of $protections must be strings'); } $protectionsString = $action . '=' . $value . '|'; } $params['protections'] = rtrim($protectionsString, '|'); $this->api->postRequest(new SimpleRequest('protect', array_merge($extraParams, $params))); return true; }
/** * NOTE: This service has not been fully tested * * @param File $file * @param int $rotation Degrees to rotate image clockwise, One value: 90, 180, 270 * * @throws UsageException * @return bool */ public function rotate(File $file, $rotation) { $params = array('rotation' => $rotation, 'token' => $this->api->getToken()); if (!is_null($file->getPageIdentifier()->getTitle())) { $params['titles'] = $file->getPageIdentifier()->getTitle()->getText(); } else { $params['pageids'] = $file->getPageIdentifier()->getId(); } $result = $this->api->postRequest(new SimpleRequest('imagerotate', $params)); // This module sometimes gives odd errors so deal with them.. if (array_key_exists('imagerotate', $result)) { $imageRotate = array_pop($result['imagerotate']); if (array_key_exists('result', $imageRotate) && $imageRotate['result'] == 'Failure') { throw new UsageException('imagerotate-Failure', $imageRotate['errormessage'], $result); } } return true; }
/** * @since 0.7 * * @param string|string[] $inputValues one or more * @param string $parser Id of the ValueParser to use * * @returns Promise of a DataValue object or array of DataValue objects with same keys as values */ public function parseAsync($inputValues, $parser) { $promise = $this->api->getRequestAsync(new SimpleRequest('wbparsevalue', array('parser' => $parser, 'values' => implode('|', $inputValues)))); return $promise->then(function ($result) use($inputValues) { if (is_array($inputValues)) { $indexedResults = array(); foreach ($result['results'] as $resultElement) { if (in_array($resultElement['raw'], $inputValues)) { $indexedResults[array_search($resultElement['raw'], $inputValues)] = $this->dataValueDeserializer->deserialize($resultElement); } else { throw new RuntimeException("Failed to match parse results with input data"); } } return $indexedResults; } else { return $this->dataValueDeserializer->deserialize($result['results'][0]); } }); }
/** * @since 0.2 * * @param Revision $revision * @param QueryOptions|null $options * * @return Page */ public function getFromRevision(Revision $revision, QueryOptions $options = null) { if (is_null($options)) { $options = new QueryOptions(); } $result = $this->api->getRequest(new SimpleRequest('query', $this->getQuery(array('revids' => $revision->getId()), $options))); $revisions = $this->getRevisionsFromResult(array_shift($result['query']['pages'])); $revisions->addRevision($revision); return new Page(new PageIdentifier(new Title($result['title'], $result['ns']), $result['pageid']), $revisions); }